Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8034: chore: clean historical comments across the codebase (#9274)

Jiayuan Zhang231dedb55287
diff --git a/AGENTS.md b/AGENTS.md
index c87d399ee1..09feabb01d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -122,6 +122,7 @@ Workspace-scoped queries filter by `workspace_id`; membership gates access and `
## Change and Delivery Rules
- Keep changes scoped; reuse existing patterns. Code comments are English.
+- Use names, types, and tests to express behavior. Keep comments for non-obvious rationale and constraints; remove superseded plans and incident narratives when updating code. Preserve tool directives and mixed-version contracts.
- Do not add internal compatibility shims, dual writes, fallback paths, or legacy adapters unless requested. This does not relax API response compatibility above.
- New global pre-workspace routes use a single word or `/{noun}/{verb}`, not hyphenated root names. Update `server/internal/handler/reserved_slugs.json`, run `pnpm generate:reserved-slugs`, and commit `packages/core/paths/reserved-slugs.ts` when changing reserved slugs.
- Use atomic conventional commits and the repository PR template. For releases, follow [.github/RELEASING.md](.github/RELEASING.md); default to a patch bump unless specified otherwise.
diff --git a/apps/desktop/src/main/keyboard-shortcuts.ts b/apps/desktop/src/main/keyboard-shortcuts.ts
index 3145b3bf76..26b525805c 100644
--- a/apps/desktop/src/main/keyboard-shortcuts.ts
+++ b/apps/desktop/src/main/keyboard-shortcuts.ts
@@ -26,28 +26,10 @@ const ZOOM_MIN = -3;
const ZOOM_MAX = 4.5;
/**
- * Inspect a `before-input-event` key and apply (or block) the matching
- * window-level shortcut. Returns `true` when the caller should call
- * `event.preventDefault()` — that both swallows the renderer keydown and
- * prevents the application menu accelerator from firing, so we don't
- * double-trigger zoom on macOS where the default menu also binds these
- * keys.
- *
- * Why we don't rely on the menu's `zoomIn` / `zoomOut` roles: on macOS the
- * default `Cmd+-` accelerator does not fire reliably across keyboard
- * layouts (issue MUL-2354 — Cmd+= zooms in but Cmd+- doesn't undo it).
- * Handling the shortcuts here gives identical behavior on every platform
- * and every layout.
- */
-/**
- * Result of handleAppShortcut:
- * - `false`: not handled, let Electron continue
- * - `true`: handled (preventDefault), no further action
- * - `"close-tab"`: Cmd/Ctrl+W intercepted — caller should send IPC to renderer
- * - `"open-settings"`: Cmd/Ctrl+, intercepted — caller should route the
- * request to the tabbed main window
- * - `{ action: "select-tab", key }`: Cmd/Ctrl+1..9 intercepted — caller
- * should route the requested browser-style tab position to the main window
+ * Window shortcut outcomes tell the caller whether to continue, preventDefault,
+ * or dispatch a renderer action. Prevent handled input from also firing the menu
+ * accelerator. Handle zoom here for consistent keyboard-layout behavior.
+ * close-tab, open-settings, and select-tab actions route to the main window.
*/
export type ShortcutResult =
| boolean
diff --git a/apps/desktop/src/main/navigation-guard.ts b/apps/desktop/src/main/navigation-guard.ts
index 59651b2fdb..498ba050aa 100644
--- a/apps/desktop/src/main/navigation-guard.ts
+++ b/apps/desktop/src/main/navigation-guard.ts
@@ -1,24 +1,8 @@
/**
- * Top-level navigation hardening for renderer windows.
- *
- * Scope note (MUL-4899) — this is origin hardening ONLY, and deliberately NOT
- * the mechanism that handles in-app links.
- *
- * Client-side routing never fires `will-navigate`: React Router pushes history
- * entries without a document load. So an in-app path — a good one like
- * `/acme/issues/1` or a bad one like `/Users/me/shot.png` pasted by an agent —
- * never reaches this guard at all. Bad in-app paths are a routing concern,
- * answered by the renderer's 404 page. Trying to police application paths here
- * would be both ineffective (the hook does not see them) and wrong (it would
- * break legitimate reloads).
- *
- * What it does catch is a real document-level navigation away from the trusted
- * renderer: `window.location = 'https://evil.example'`, an anchor Chromium
- * resolves to a remote URL in the same window, a dropped file URL. These windows
- * run with `webSecurity: false` (the process sandbox is enabled), so a
- * foreign document landing in one would inherit privileged context. New
- * windows and external links already route through `setWindowOpenHandler` →
- * `openExternalSafely`; this closes the same-window path.
+ * Guard document-level renderer navigation to trusted origins or the packaged
+ * entry file. Same-window foreign documents must not inherit renderer privileges.
+ * Client-side route changes do not fire will-navigate and remain the router's
+ * responsibility. New windows and external links use openExternalSafely.
*/
/** The subset of BrowserWindow this module needs — keeps it unit-testable. */
diff --git a/apps/desktop/src/renderer/src/components/tab-bar.tsx b/apps/desktop/src/renderer/src/components/tab-bar.tsx
index 8cd04478d2..7ab3964cab 100644
--- a/apps/desktop/src/renderer/src/components/tab-bar.tsx
+++ b/apps/desktop/src/renderer/src/components/tab-bar.tsx
@@ -47,33 +47,11 @@ import { parseIssueWindowPath } from "../../../shared/issue-window";
const TAB_SCROLL_FADE_SIZE = 24;
const TAB_ENTRY_EASE = [0.22, 1, 0.36, 1] as const;
-// Chrome-style merged tab: the active tab shares the content surface's fill and
-// flares into it through concave bottom corners. Each flare is a small square
-// whose radial gradient carves a quarter-circle notch (transparent, so the
-// strip behind the flare shows through), strokes a 1px arc that continues the
-// tab's side border into the content card's top ring, and fills the rest with
-// the surface colour. The 0.4px spread on either side of the --surface-border
-// pair anti-aliases that arc.
-//
-// That background-color is load-bearing, not decoration: the flare's bottom row
-// overlaps the content card's top ring, and in dark mode --surface-border is
-// translucent (oklch(1 0 0 / 10%)), so without an opaque layer beneath it the
-// arc would composite over the ring instead of replacing it and the two keylines
-// would stack into a markedly lighter line right where the straight ring meets
-// the curve. It therefore has to be the strip's real backdrop — the sidebar
-// wrapper's fill, which is conditional and not this file's to re-derive.
-// SIDEBAR_WRAPPER_FILL_CLASS reads it off the wrapper itself.
-//
-// The backing may only reach as far as it is needed, though. A flare hangs 9px
-// past the tab's edge, over the neighbouring tab, so an opaque square there
-// prints over whatever that neighbour draws: its hover pill lost the whole
-// corner it shares with the flare and read as a dark bite (MUL-6160). Masking
-// the notch away removes the backing exactly where the gradient is transparent
-// anyway, so the notch is a hole rather than a painted-on copy of the strip and
-// shows whatever is actually behind it — bare strip usually, the neighbour's
-// pill where it reaches in. The mask is opaque again by the radius where the
-// arc's anti-aliasing starts, so every pixel the arc and the canvas fill cover
-// keeps its backing.
+// Concave tab flares need an opaque backing beneath translucent border arcs
+// to avoid compositing a second keyline over the content ring. Read that backdrop
+// from SIDEBAR_WRAPPER_FILL_CLASS rather than duplicating the wrapper's fill rule.
+// Mask the transparent notch so the backing cannot paint over a neighboring hover
+// pill, while retaining backing beneath the arc's antialiasing.
const TAB_FLARE_RADIUS = 10;
const tabFlareGradient = (side: "left" | "right") => {
const r = TAB_FLARE_RADIUS;
diff --git a/apps/desktop/src/renderer/src/platform/tab-coordinator.ts b/apps/desktop/src/renderer/src/platform/tab-coordinator.ts
index 7df5b666f9..afe07e16b8 100644
--- a/apps/desktop/src/renderer/src/platform/tab-coordinator.ts
+++ b/apps/desktop/src/renderer/src/platform/tab-coordinator.ts
@@ -14,24 +14,10 @@ import {
} from "@/stores/tab-store";
/**
- * Tab Coordinator (MUL-4741 Phase 2) — the ONLY writer of the single app
- * router.
- *
- * Architecture: the tab store is the source of truth; the router is a
- * projection of the active session's URL. The Coordinator subscribes to the
- * store and *reconciles* the router to `activeSession.url`, stamping every
- * navigation with a token. All entry points (tab bar clicks, adapter
- * push/replace, shell back/forward, error recovery) mutate the store — none
- * of them touch the router. This makes invariant 1 hold by construction:
- *
- * - Router location change WITH a pending token → expected, consume it.
- * - Router location change WITHOUT a pending token → protocol error →
- * bounded recovery (re-reconcile toward the session URL, capped).
- *
- * The router's own history is never used: the Coordinator always navigates
- * with `replace`, and per-tab back/forward is a session operation over the
- * session's virtual history stack. A POP therefore can only come from
- * unforeseen code and is handled by the same protocol-error path.
+ * Project the active tab session onto the single app router. Navigation entry
+ * points mutate the store; only this coordinator writes the router, using replace
+ * and a pending token. Untokened location changes trigger bounded reconciliation.
+ * Per-tab virtual history owns back/forward; router POP is a protocol error.
*/
let router: DataRouter | null = null;
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.ts
index 0df8289f52..f8c8be09b3 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts
@@ -5,17 +5,9 @@ import { createPersistStorage, defaultStorage } from "@multica/core/platform";
import { createSafeId } from "@multica/core/utils";
import { isReservedSlug } from "@multica/core/paths";
-// ---------------------------------------------------------------------------
-// Types
-// ---------------------------------------------------------------------------
-//
-// MUL-4741 Phase 2: tabs are *sessions*, not routers. A TabSession is pure
-// serializable state — URL, identity, virtual history, and a memento of
-// restorable view state. The single app router is a projection of the active
-// session, driven exclusively by the tab Coordinator (src/platform/
-// tab-coordinator.ts) which subscribes to this store and reconciles the
-// router to `activeSession.url` with a navigation token. Nothing in this
-// file touches react-router.
+// Tab sessions hold serializable URLs, identity, virtual history, and view
+// mementos. The coordinator projects the active session onto the single router;
+// this store does not operate the router.
/**
* One captured scroll position.
@@ -293,9 +285,7 @@ interface TabStore {
reset: () => void;
}
-// ---------------------------------------------------------------------------
// Session identity helpers
-// ---------------------------------------------------------------------------
//
// A tab's icon is NOT part of this model. It is derived from `tab.url` at
// render time via `routeIconForPath` (@multica/views/layout), which shares the
@@ -312,9 +302,7 @@ function extractWorkspaceSlug(path: string): string | null {
return first;
}
-// ---------------------------------------------------------------------------
// URL helpers
-// ---------------------------------------------------------------------------
/** Split a tab URL into pathname and the search+hash suffix. */
export function splitTabUrl(url: string): { pathname: string; suffix: string } {
@@ -405,9 +393,7 @@ export function sanitizeTabPath(path: string): string | null {
return path;
}
-// ---------------------------------------------------------------------------
// Session factory
-// ---------------------------------------------------------------------------
function createId(): string {
return createSafeId();
@@ -618,9 +604,7 @@ function normalizeBrowsingHistoryTitles(
return result;
}
-// ---------------------------------------------------------------------------
// Group helpers
-// ---------------------------------------------------------------------------
/**
* Build a group with its MRU order reconciled against the new (tabs,
@@ -711,9 +695,7 @@ function buildCloseOtherTabsResult(
};
}
-// ---------------------------------------------------------------------------
// Store
-// ---------------------------------------------------------------------------
export const useTabStore = create<TabStore>()(
persist(
@@ -1497,9 +1479,7 @@ function setHistoryIndex(
});
}
-// ---------------------------------------------------------------------------
// Persisted shapes (for migration)
-// ---------------------------------------------------------------------------
interface V1Tab {
id: string;
@@ -1711,9 +1691,7 @@ export function migrateV1ToV2(v1: Partial<V1Persisted>): V2Persisted {
return { activeWorkspaceSlug, byWorkspace };
}
-// ---------------------------------------------------------------------------
// Selectors (convenience hooks)
-// ---------------------------------------------------------------------------
/**
* Pure non-hook helper — useful from event handlers / effects that already
diff --git a/apps/mobile/app/(app)/[workspace]/search.tsx b/apps/mobile/app/(app)/[workspace]/search.tsx
index 4b976102dc..d276372550 100644
--- a/apps/mobile/app/(app)/[workspace]/search.tsx
+++ b/apps/mobile/app/(app)/[workspace]/search.tsx
@@ -65,9 +65,7 @@ const SEARCH_HEADER_LABELS: Record<string, string> = {
"h-cancelled": "issues:status.cancelled",
};
-// =====================================================
// HighlightText — mobile port of web's HighlightText
-// =====================================================
// Web uses an HTML <mark> which doesn't exist in RN, so we segment the
// string ourselves and wrap matched parts in a styled <Text>. Same regex
// escape + case-insensitive substring match as
@@ -125,9 +123,7 @@ function HighlightText({
);
}
-// =====================================================
// Row item types — drives the single FlatList render
-// =====================================================
// RowItem + buildSearchRows live in lib/search-rows.ts so the ordering rules
// (including the cancelled partition) are testable without mounting the screen.
@@ -304,9 +300,7 @@ function RecentRow({ item, slug }: RecentRowProps) {
);
}
-// =====================================================
// Screen
-// =====================================================
interface SearchResultsState {
issues: SearchIssueResult[];
diff --git a/apps/mobile/components/chat/chat-message-list.tsx b/apps/mobile/components/chat/chat-message-list.tsx
index b78f459a96..05cbd457f1 100644
--- a/apps/mobile/components/chat/chat-message-list.tsx
+++ b/apps/mobile/components/chat/chat-message-list.tsx
@@ -1,44 +1,11 @@
/**
- * Chat message list — user / assistant bubbles, oldest at top, newest at
- * bottom. Initial render lands at the bottom; new arrivals auto-scroll
- * when the user is anchored near the bottom; reading history is never
- * yanked down.
+ * Chronological FlashList chat with initial bottom positioning and MVCP.
+ * Follow new messages only while the user is near the bottom; preserve reading
+ * position through asynchronous Markdown and image resizing.
*
- * Behavioral parity (apps/mobile/CLAUDE.md):
- * - Render ALL message roles. Unknown role values are downgraded to
- * "assistant" by ChatMessageSchema's `.catch()`, so this list never
- * needs to silently drop a row.
- * - Render `failure_reason` messages with destructive styling — same
- * boolean as web's destructive bubble + failureReasonLabel().
- *
- * v1 simplifications:
- * - No "Replied in Ns" badge under assistant bubbles (elapsed_ms is
- * parsed but not displayed). Easy v2 add — show below the bubble.
- * - Attachments bound to a message but NOT referenced inline in `content`
- * render as standalone cards below the bubble via `CommentAttachmentList`
- * (same component the comment thread uses; mirrors web reusing
- * `AttachmentList` in chat). Inline `![](url)` / `[name](url)` still flow
- * through the markdown renderer and are de-duped out of the card list.
- *
- * Interaction: long-press inside a bubble fires a native iOS
- * `ActionSheetIOS` (Copy / Select Text / Cancel). While the sheet is on
- * screen the targeted bubble's border highlights. The assistant branch
- * has no border baseline because its bubble has no shell — adding a 2px
- * baseline would shift layout per message. See `useChatMessageLongPress`
- * in `./message-long-press.tsx`.
- *
- * List engine: FlashList v2 (Shopify). FlatList was the original choice
- * (per the now-outdated "no FlashList" baseline in apps/mobile/CLAUDE.md
- * — written before FlashList v2 stabilised). FlatList's `scrollToEnd` is
- * janky on variable-height lists by RN's own docs admission, and our
- * markdown bubbles render in multiple async passes (Shiki highlight,
- * image natural-size, lightbox provider injection) — each pass used to
- * fire onContentSizeChange and trigger another forced scroll, causing
- * the "open chat → feels stuck" jank. FlashList v2 replaces the manual
- * scroll dance with `maintainVisibleContentPosition`
- * (default-on; locks visible item across content changes) +
- * `startRenderingFromBottom` (initial paint at bottom, no setTimeout
- * hacks). Cell recycling also keeps scroll-up smooth.
+ * Render all normalized message roles and failure styling. Attachments not used
+ * inline appear as standalone cards. Long-press actions highlight the target
+ * without adding a border that would shift the layout.
*/
import { useMemo, useState } from "react";
import { ActivityIndicator, Pressable, View } from "react-native";
diff --git a/apps/mobile/components/issue/comment-context-menu.tsx b/apps/mobile/components/issue/comment-context-menu.tsx
index 8b5caf57a5..50a6675279 100644
--- a/apps/mobile/components/issue/comment-context-menu.tsx
+++ b/apps/mobile/components/issue/comment-context-menu.tsx
@@ -1,21 +1,9 @@
/**
- * Long-press handler for a comment bubble. Exposes `onLongPress` (drives a
- * native iOS ActionSheetIOS) and `isPressed` (drives the caller's highlight
- * ring while the sheet is on screen).
+ * Native long-press actions for a comment bubble, with a pressed highlight
+ * while the sheet is visible. Reply targets the inline composer.
*
- * iOS-native first per apps/mobile/CLAUDE.md §UI components → waterfall step
- * 1: `ActionSheetIOS.showActionSheetWithOptions`. Zero custom layout, zero
- * animation, zero overflow math, zero new deps.
- *
- * Item set (conditional, mirrors web's comment context menu):
- * Reply (stub) · React… (opens nested sheet) · Copy · Select Text ·
- * Copy Link · Resolve/Unresolve Thread (root only) · Delete (own only) ·
- * Cancel
- *
- * The nested React… sheet (5 quick emojis + More reactions… + Cancel) is
- * fired from INSIDE the outer sheet's completion callback rather than
- * inline, because iOS will refuse to present a second ActionSheet while the
- * first is still dismissing — the callback runs after dismissal completes.
+ * Present nested reaction sheets from the outer sheet's completion callback;
+ * iOS cannot present the next ActionSheet while the first is dismissing.
*/
import { useCallback, useState } from "react";
import { ActionSheetIOS, Alert } from "react-native";
diff --git a/apps/mobile/components/issue/composer-attachment-row.tsx b/apps/mobile/components/issue/composer-attachment-row.tsx
index 00f588a8bc..4308572c31 100644
--- a/apps/mobile/components/issue/composer-attachment-row.tsx
+++ b/apps/mobile/components/issue/composer-attachment-row.tsx
@@ -121,9 +121,7 @@ export function ComposerAttachmentRow({
);
}
-// ---------------------------------------------------------------------------
// Mention chip — small capsule, no tap (only × removes).
-// ---------------------------------------------------------------------------
function MentionChipView({
mention,
@@ -166,9 +164,7 @@ function MentionChipView({
);
}
-// ---------------------------------------------------------------------------
// Attachment chip — image / file capsule with status overlay.
-// ---------------------------------------------------------------------------
interface AttachmentChipProps {
item: ComposerAttachmentItem;
diff --git a/apps/mobile/components/issue/timeline-list.tsx b/apps/mobile/components/issue/timeline-list.tsx
index 20b2e513f9..a9dd10cf3f 100644
--- a/apps/mobile/components/issue/timeline-list.tsx
+++ b/apps/mobile/components/issue/timeline-list.tsx
@@ -1,79 +1,12 @@
/**
- * The scrolling timeline. ASC chronological — oldest at top, newest near the
- * bottom (above the composer). Pull-to-refresh refetches issue + timeline.
+ * Chronological issue timeline backed by FlashList.
+ * Normal opens show the header; deep links start at the bottom and highlight a
+ * target when its row is rendered. MVCP keeps the viewport stable as asynchronous
+ * Markdown, images, and WebSocket patches change row heights.
*
- * Backend returns the full timeline in one shot (server-side pagination
- * was dropped in #2322 — p99 ~30 entries per issue, cursor walking only
- * created bugs at reply-thread boundaries). The previous "Pull to load
- * older" UX and top-edge `fetchOlder` trigger are gone.
- *
- * Inbox deep-link — FlashList v2 `startRenderingFromBottom` (mirrors
- * chat-message-list.tsx):
- * When `highlightCommentId` is set, we pass
- * `maintainVisibleContentPosition.startRenderingFromBottom: true` to
- * FlashList and remount the list via `key={`hl-${highlightNonce}`}` once
- * timeline data has arrived. FlashList's `getInitialScrollIndex()` then
- * lands on the last data item; after the initial paint MVCP keeps the
- * visible content stable across async resizes (Shiki highlight, image
- * natural-size, WS `comment:updated`). No JS-side scroll dance.
- *
- * The previous implementation hand-rolled a `landed` state gate that
- * re-fired `scrollToEnd` on every `onContentSizeChange`. That deadlocked
- * the user at the bottom: `onScrollBeginDrag` queued `setLanded(true)`
- * but a concurrent `onContentSizeChange` (from MVCP's own ScrollAnchor
- * reposition, or from a markdown pass finishing) read the stale React
- * closure, saw `landed === false`, and slammed the user back to bottom
- * before the commit landed. State-vs-event races don't survive iOS
- * markdown rendering hogging the JS thread.
- *
- * The matching <CommentCard>'s `RootHighlightOverlay` fires when the
- * target row enters the render window — so for a deep-link pointing
- * at an old comment, the user scrolls up and the flash plays as the
- * row mounts. `HIGHLIGHT_HOLD_MS` (5s) is the window for that.
- *
- * Why not `scrollToIndex`: it requires accurate height estimates that
- * variable-height markdown bubbles can't provide, even with
- * `onScrollToIndexFailed` retry. Same lesson web learned (see
- * `packages/views/issues/components/issue-detail.tsx:1822-1850` — they
- * split the path into virtualized-for-browse / flat-for-deep-link
- * precisely because "virtualization and 'land precisely on a target'
- * have fundamentally opposed contracts"). Mobile sidesteps the split
- * by not pretending to land precisely.
- *
- * `maintainVisibleContentPosition` is enabled by default on FlashList v2
- * and is implemented inside the C++ shadow tree — it compensates the
- * scroll offset both when a row is INSERTED above the viewport AND when
- * an upper row RESIZES (a WS `comment:updated` / `reaction:added` /
- * `resolved` event on an older comment used to push the user's read
- * position down by the delta). On FlatList the same prop was iOS-only
- * + JS-side; the FlashList path is steadier and animates the offset
- * compensation rather than snapping it.
- *
- * List engine: FlashList v2 (Shopify). Migrated from FlatList because:
- * 1. Cell recycling — markdown bubbles (Shiki highlight, image natural-
- * size, lightbox provider injection) are expensive to mount; FlashList
- * keeps them in recycled cells when scrolling through history rather
- * than re-running the multi-pass render each time a row re-enters the
- * window.
- * 2. Native MVCP — see paragraph above. Smoother behavior than FlatList's
- * JS-side implementation when WS events resize an upper row.
- * 3. Async-render stability — async markdown size changes inside the
- * viewport no longer cause the visual "twitch" we saw with FlatList,
- * because FlashList re-layouts inside the shadow tree without
- * surfacing a JS-side onContentSizeChange storm.
- *
- * What FlashList v2 does NOT change about this file:
- * - The deep-link "land at bottom + flash on row mount" pattern (Linear
- * iOS). FlashList's `scrollToIndex` is still estimate-based, so we
- * intentionally don't try to land precisely on a specific comment —
- * we land at the bottom and let `RootHighlightOverlay` claim the
- * target when the user scrolls past it. `startRenderingFromBottom`
- * is NOT enabled: a normal issue-open should show the header (title,
- * description, status) first, not jump straight to the latest reply.
- * - Spacing between rows. FlashList ignores `gap-*` on
- * `contentContainer` the same way it does in chat-message-list.tsx —
- * we use `ItemSeparatorComponent` for the 12 px breathing room and
- * `ListHeaderComponentStyle` to add the same gap below the header.
+ * Avoid repeated scrollToEnd calls during content resizing: they can override
+ * user scrolling. New replies use the explicit jump-to-new chip instead of
+ * automatically following appends. Item separators provide spacing between rows.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
diff --git a/apps/mobile/data/queries/my-issues.ts b/apps/mobile/data/queries/my-issues.ts
index f7f1571f88..f765c6a893 100644
--- a/apps/mobile/data/queries/my-issues.ts
+++ b/apps/mobile/data/queries/my-issues.ts
@@ -1,18 +1,10 @@
/**
- * "My Issues" list, server-filtered by scope. Mirrors the three scopes web
- * exposes in `packages/views/my-issues/components/my-issues-page.tsx:48-65`:
- * - assigned: issues where assignee_id = me
- * - created: issues where creator_id = me
- * - agents: issues where the assignee is an *indirect* extension of me —
- * an owned agent, OR a squad I'm a human member of, lead, or
- * have an owned agent inside. Driven server-side by the
- * `involves_user_id` predicate (see MUL-2397, 2026-05-19).
- * Direct member assignment is intentionally EXCLUDED — that's
- * the `assigned` scope's meaning.
+ * Server-filtered My Issues scopes: direct assignments, creations, or involvement
+ * through owned agents and squad membership. The agents scope excludes direct
+ * member assignment, which belongs to assigned.
*
- * Cache key shape is `issueKeys.myList(wsId, scope, filter)` — same prefix
- * as web's `packages/core/issues/queries.ts` so a future WS handler can
- * invalidate `issueKeys.myAll(wsId)` and reach both clients.
+ * Mobile owns these query keys and its QueryClient. useMyIssuesRealtime patches
+ * or invalidates local lists; each client receives its own server events.
*/
import { queryOptions } from "@tanstack/react-query";
import { api } from "@/data/api";
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.ts b/apps/mobile/data/realtime/chat-ws-updaters.ts
index 4986501766..4038cffe83 100644
--- a/apps/mobile/data/realtime/chat-ws-updaters.ts
+++ b/apps/mobile/data/realtime/chat-ws-updaters.ts
@@ -37,9 +37,7 @@ import type {
} from "@multica/core/types";
import { chatKeys } from "@/data/queries/chat";
-// =====================================================
// Sessions list (ChatSession[] keyed by wsId)
-// =====================================================
export function patchSessionListAfterRename(
qc: QueryClient,
@@ -90,9 +88,7 @@ export function flipSessionUnread(
);
}
-// =====================================================
// Messages cache (ChatMessage[] keyed by sessionId)
-// =====================================================
/**
* Apply `chat:done` to the messages cache.
@@ -205,9 +201,7 @@ export async function applyChatQuickActionsToCache(
);
}
-// =====================================================
// Pending task (ChatPendingTask keyed by sessionId)
-// =====================================================
export function seedPendingTaskFromQueued(
qc: QueryClient,
@@ -296,9 +290,7 @@ export function seedAcceptedPendingTask(
invalidatePendingTask(qc, payload.chat_session_id);
}
-// =====================================================
// Task messages (live timeline, keyed by taskId)
-// =====================================================
/**
* Append a `task:message` payload into the per-task timeline cache.
diff --git a/apps/mobile/data/realtime/issue-ws-updaters.ts b/apps/mobile/data/realtime/issue-ws-updaters.ts
index 60ae28f4ef..984a5d9b27 100644
--- a/apps/mobile/data/realtime/issue-ws-updaters.ts
+++ b/apps/mobile/data/realtime/issue-ws-updaters.ts
@@ -1,29 +1,9 @@
/**
- * Mobile-owned WS cache patchers for the issue domain. These are pure
- * functions over `QueryClient` — no React, no WS plumbing. The hooks in
- * `use-issue-realtime.ts` and `use-my-issues-realtime.ts` translate WS
- * events into calls into this module.
- *
- * Why mobile-owned (and not importing from packages/core/issues/ws-updaters):
- * - Web's updaters reference `issueKeys` from `packages/core/issues/queries`,
- * a different runtime instance than mobile's `data/queries/issue-keys.ts`.
- * TanStack Query keys are compared structurally so this would *appear*
- * to work, but binding cache mutation to a foreign key factory invites
- * drift the moment either side adjusts its key shape.
- * - Mobile cache shapes are simpler: no status-bucketed list, no children
- * subtree, no childProgress, no label-byIssue cache. A direct mirror
- * would be ~120 lines of conditional dead-code paths.
- *
- * Cache shapes (the design contract here):
- * - Issue detail: Issue (keyed by detail(wsId, id))
- * - Issue timeline: TimelineEntry[] (keyed by timeline(wsId, id))
- * ASC oldest-first; new entries inserted at sorted position.
- * - My Issues list: Issue[] (keyed by myList(wsId, scope, filter))
- * Multiple list caches per wsId (one per scope/filter combo).
- * Patch ALL of them via setQueriesData on myAll(wsId).
- * - Workspace list: Issue[] (keyed by list(wsId))
- * Single cache per wsId (no scope/filter in the key —
- * filtering happens client-side off the same list).
+ * Mobile-owned issue cache patchers, called by record and listing subscriptions.
+ * Use mobile's key factories and cache shapes rather than web's bucketed caches.
+ * Detail stores an Issue; timelines store chronological TimelineEntry arrays;
+ * My Issues stores one Issue array per scope/filter and patches all matching keys;
+ * the workspace list stores a single client-filtered Issue array.
*/
import type { QueryClient } from "@tanstack/react-query";
import type {
@@ -122,9 +102,7 @@ function acceptsRevision(current: number | undefined, incoming: number | undefin
return incoming !== undefined && incoming >= current;
}
-// =====================================================
// Issue detail cache (single Issue per id)
-// =====================================================
export function patchIssueDetail(
qc: QueryClient,
@@ -233,9 +211,7 @@ export function invalidateIssueAfterReconnect(
qc.invalidateQueries({ queryKey: issueKeys.tasks(wsId, issueId) });
}
-// =====================================================
// Issue timeline (flat TimelineEntry[], ASC oldest-first)
-// =====================================================
export function appendTimelineEntry(
qc: QueryClient,
@@ -385,9 +361,7 @@ export function removeCommentCascade(
);
}
-// =====================================================
// My Issues list (flat Issue[] across many keys)
-// =====================================================
export function patchMyIssuesList(
qc: QueryClient,
@@ -420,9 +394,7 @@ export function removeFromMyIssuesList(
);
}
-// =====================================================
// Workspace Issues list (flat Issue[] under list(wsId))
-// =====================================================
export function patchIssuesList(
qc: QueryClient,
@@ -464,9 +436,7 @@ export function removeFromIssuesList(
);
}
-// =====================================================
// Reactions
-// =====================================================
export function addCommentReaction(
qc: QueryClient,
@@ -599,9 +569,7 @@ export function removeIssueReaction(
);
}
-// =====================================================
// Labels
-// =====================================================
export function patchIssueLabels(
qc: QueryClient,
@@ -637,9 +605,7 @@ export function patchIssueLabels(
onIssueAuxiliaryRevision(qc, wsId, issueId, issueRevision, "labels");
}
-// =====================================================
// Helpers — payload normalization
-// =====================================================
/**
* Convert a Comment WS payload into a TimelineEntry. The two types share
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index 18aaddb1f9..436155225d 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -238,9 +238,7 @@ export const EMPTY_LIST_PROJECT_RESOURCES_RESPONSE: ListProjectResourcesResponse
total: 0,
};
-// =====================================================
// Chat (sessions / messages / pending task)
-// =====================================================
// Lenient on every field that's purely informational (status enum, timestamps,
// agent/creator ids). `.loose()` so server-added fields pass through. The two
// fields mobile keys behaviour on — `id` and `chat_session_id` — are required.
@@ -363,9 +361,7 @@ export const TaskMessageListSchema = z.array(TaskMessagePayloadSchema).default([
export const EMPTY_TASK_MESSAGE_LIST: TaskMessagePayload[] = [];
-// =====================================================
// Search (issues + projects)
-// =====================================================
// Mirrors SearchIssueResult / SearchProjectResult in packages/core/types/api.ts.
// Web does not currently route search responses through parseWithFallback, so
// the schemas live mobile-side. Promote to core when web adopts the same
@@ -401,9 +397,7 @@ export const EMPTY_SEARCH_PROJECTS_RESPONSE: SearchProjectsResponse = {
projects: [],
};
-// =====================================================
// Agent tasks (per-issue runs, active + history)
-// =====================================================
// Mirrors AgentTask in packages/core/types/agent.ts. Backend handlers:
// GET /api/issues/{id}/active-task → { tasks: AgentTask[] } (may be empty)
// GET /api/issues/{id}/task-runs → AgentTask[]
@@ -473,9 +467,7 @@ export interface ActiveTasksResponse {
export const EMPTY_AGENT_TASK_LIST: AgentTask[] = [];
export const EMPTY_ACTIVE_TASKS_RESPONSE: ActiveTasksResponse = { tasks: [] };
-// =====================================================
// User / Workspace / Inbox / Member / Agent
-// =====================================================
// Mobile reads these on every cold start (auth → workspaces → inbox → members
// → agents form the boot sequence). A schema drift in any of them used to
// cascade — getMe failure flushed the user, listWorkspaces failure landed the
diff --git a/apps/mobile/lib/markdown/markdown-style.ts b/apps/mobile/lib/markdown/markdown-style.ts
index 2f3342e506..7f2a84a7b0 100644
--- a/apps/mobile/lib/markdown/markdown-style.ts
+++ b/apps/mobile/lib/markdown/markdown-style.ts
@@ -179,46 +179,10 @@ export function useMarkdownStyle() {
color: t.brand,
underline: true,
},
- // Inline code — monospace + muted-foreground tint, NO background chip.
- //
- // Why no background: on iOS, NSAttributedString draws
- // NSBackgroundColorAttributeName as a rectangle spanning the full
- // line-box height (24pt for our CJK-tuned body leading). PingFang
- // SC places the baseline at ~75-80% of the line-box, so monospaced
- // glyphs sit low inside that rectangle, leaving ~11pt empty at the
- // top vs ~6pt at the bottom — a visible 2:1 asymmetry in CJK
- // paragraphs. This is a platform-level constraint, not a library
- // bug: the library's STYLES.md exposes only fontFamily / fontSize /
- // color / backgroundColor / borderColor for inline code — no
- // padding, lineHeight, or baselineOffset knob. Confirmed 2026-05-21
- // (researcher brief): zero open PRs / forks / prereleases touching
- // inline-code vertical geometry; upstream issue #255 has no
- // maintainer response since 2026-04-20. The only real fixes are at
- // the native layer (custom NSLayoutManager.drawBackground override
- // or TextKit 2 NSTextLayoutManager.enumerateTextSegments(.highlight))
- // which would require forking the library — not worth the perpetual
- // patch-rebase cost for a polish issue.
- //
- // Visual identification stays strong without the chip: monospace
- // font + muted-foreground tint matches Apple Notes / iA Writer.
- //
- // Color choice — mutedForeground (NOT brand):
- // - mutedForeground is a neutral gray, reads as "subdued prose".
- // - brand is reserved for links; tinting code blue confused users
- // into tapping it as if it were a link (tried 2026-05-19, then
- // reverted same day for this reason).
- //
- // fontFamily intentionally NOT set: enriched-markdown's default is
- // the platform system monospace (SF Mono on iOS, monospace on
- // Android), which has a larger visual x-height than the previously-
- // explicit "Menlo" override.
- //
- // Revisit when:
- // - upstream #255 ships a paddingVertical / lineHeight knob, OR
- // - we contribute the TextKit 2 fix upstream (the right hook is
- // NSTextLayoutManager.enumerateTextSegments(in:type:.highlight:))
- // Either way, switch back to a tinted-chip style for cross-platform
- // visual parity with web/desktop.
+ // Keep inline code backgrounds transparent: native attributed-string chips
+ // span the line box and cannot be vertically padded by this renderer. Monospace
+ // and a neutral tint identify code without making it look like a link.
+ // Leave fontFamily unset to use the platform's system monospace.
code: {
color: t.mutedForeground,
backgroundColor: "transparent",
diff --git a/apps/mobile/lib/markdown/split-markdown.ts b/apps/mobile/lib/markdown/split-markdown.ts
index 307ea994b0..b723be8115 100644
--- a/apps/mobile/lib/markdown/split-markdown.ts
+++ b/apps/mobile/lib/markdown/split-markdown.ts
@@ -1,47 +1,10 @@
/**
- * Hybrid-render segment splitter.
+ * Split Markdown into native prose, React code blocks, and interactive images.
+ * Use lexer token boundaries so fenced/indented code and paragraph images are
+ * handled without fragile regex reconstruction. Preserve prose through token.raw.
*
- * react-native-enriched-markdown gives us native-quality rendering of
- * prose (paragraphs / headings / lists / quotes / tables / inline code /
- * links / mentions) but does NOT let us inject React for any leaf node
- * (see issues #54, #232, #246 — maintainer's stance is "no custom
- * renderers, ever, by design"). That blocks three product needs:
- *
- * 1. Shiki syntax-highlighted code blocks (web parity).
- * 2. Tap-to-lightbox on images.
- * 3. Horizontal scroll + copy button on code.
- *
- * Maintainer-endorsed workaround (issue #246): split the markdown at
- * those boundaries, render each fragment as its own enriched instance
- * for prose and as React for the rest. This file is that splitter.
- *
- * Strategy:
- *
- * - Run `marked.lexer` (we already depend on it for preprocess).
- * - Walk the top-level token list.
- * - `code` token → emit a `code` segment.
- * - `paragraph` token containing image tokens → split the paragraph
- * at each image boundary. Each image becomes its own `image`
- * segment; the surrounding text rejoins the prose stream. (RN's
- * <Image> can't be inline in a <Text>, and tap-to-lightbox needs a
- * Pressable wrapper that's not viable inside an attributed string
- * anyway. GitHub mobile and Linear iOS both promote inline images
- * to block-level — we follow.)
- * - Every other block stays in the prose buffer and is handed to
- * enriched verbatim via `token.raw`.
- *
- * Why not regex: code inside lists, indented code, paragraph-embedded
- * images, and consecutive code blocks without a blank line all have
- * boundaries regex can't reliably detect. marked.lexer already knows;
- * reuse it.
- *
- * Known trade-off: code blocks nested inside a list item stay with the
- * list and render via enriched (no Shiki). That's because the splitter
- * only inspects top-level tokens — descending into list/quote children
- * would force us to also re-serialise their surrounding markdown,
- * complicating prose reconstruction. Top-level code is the >95% case
- * for issue descriptions / comments; revisit if real content shows
- * otherwise.
+ * Only top-level code is extracted. Nested list/quote code stays in the native
+ * renderer to preserve its surrounding Markdown structure.
*/
import { marked, type Tokens } from "marked";
diff --git a/apps/web/app/[workspaceSlug]/layout.tsx b/apps/web/app/[workspaceSlug]/layout.tsx
index f150e61d5f..ce2744e2ea 100644
--- a/apps/web/app/[workspaceSlug]/layout.tsx
+++ b/apps/web/app/[workspaceSlug]/layout.tsx
@@ -54,28 +54,10 @@ export default function WorkspaceLayout({
enabled: !!user,
});
- // Render-phase sync: feed the URL slug into the platform singleton so
- // the first child query's X-Workspace-Slug header is already correct.
- // setCurrentWorkspace self-dedupes + runs rehydrate as a side effect;
- // safe to call on every render.
- //
- // Gated on the live pathname because this is a module-global write from
- // render, and the App Router can keep a previous workspace's layout mounted
- // beside the incoming one. Both instances re-render on their own query
- // activity, so an unguarded write let them alternate — every render flipping
- // the singleton back to its own slug, indefinitely. Each flip tore down and
- // rebuilt the realtime socket (packages/core/realtime/provider.tsx binds it
- // to this slug) and re-pointed the @mention lookup, which reads the same
- // singleton synchronously and falls back to an empty list when the workspace
- // it names has no warm cache (packages/views/editor/extensions/
- // mention-suggestion.tsx). Realtime went dead and the mention list came back
- // empty for whichever workspace the user was actually looking at.
- //
- // Comparing against the pathname resolves it without an ownership handshake:
- // the URL is the source of truth for workspace identity, and usePathname()
- // is one value shared by every mounted instance, so exactly one layout — the
- // routed one — can define it. Desktop needs its own protocol instead
- // (workspace-route-layout.tsx) because it has no URL bar to appeal to.
+ // Sync routed workspace identity during render so the first child request has
+ // the correct workspace header. Gate this global write on the live pathname:
+ // App Router can retain old layouts whose rerenders would otherwise switch the
+ // singleton and realtime connection back to a stale workspace.
if (workspace && workspaceSlug === workspaceSlugFromPathname(pathname)) {
setCurrentWorkspace(workspaceSlug, workspace.id);
}
diff --git a/apps/web/app/manifest.ts b/apps/web/app/manifest.ts
index 873108e06b..a4c2fb49bd 100644
--- a/apps/web/app/manifest.ts
+++ b/apps/web/app/manifest.ts
@@ -1,30 +1,12 @@
import type { MetadataRoute } from "next";
/**
- * Web app manifest — what makes the mobile web app installable and lets it run
- * in its own window instead of a browser tab.
+ * Installable web manifest. Start at /inbox so session-aware proxy routing
+ * opens the workspace or login; the marketing host's root would open the landing
+ * page even for a signed-in user.
*
- * `start_url` is deliberately NOT "/". The official marketing hosts keep the
- * root path on the public site even for a signed-in session (see
- * `isOfficialMarketingHost` in proxy.ts), so an installed app pointed at "/"
- * would open the landing page. "/inbox" is one of `LEGACY_ROUTE_SEGMENTS`,
- * which proxy.ts resolves per session: signed in with a known workspace it
- * lands on that workspace's inbox, signed in without one it lands on /login
- * (which resolves against the workspace list), and signed out it lands on
- * /login too. All three are pinned in manifest.test.ts, because a launcher
- * icon has no URL bar to recover from a wrong destination.
- *
- * The icons under /icons are generated, not hand-drawn. To regenerate after a
- * brand change, edit public/icons/icon.svg and run from public/icons:
- *
- * sips -s format png --resampleHeightWidth 512 512 icon.svg --out icon-maskable-512.png
- * sips -s format png --resampleHeightWidth 180 180 icon.svg --out apple-touch-icon.png
- * sips -s format png --resampleHeightWidth 512 512 ../../../desktop/build/icon.png --out icon-512.png
- * sips -s format png --resampleHeightWidth 192 192 ../../../desktop/build/icon.png --out icon-192.png
- *
- * The two `any` icons come from the desktop app icon so an installed web app
- * and an installed desktop app show the same artwork; the maskable one is
- * full-bleed because Android crops it to the launcher's shape.
+ * Standard icons share desktop artwork. The maskable SVG supplies full-bleed
+ * artwork for launcher cropping; regenerate raster sizes from those source assets.
*/
/** Launch path. Exported so manifest.test.ts can run it through the proxy. */
diff --git a/apps/web/features/landing/components/download/all-platforms.tsx b/apps/web/features/landing/components/download/all-platforms.tsx
index 1c3cd0680e..8c8f7f6ca2 100644
--- a/apps/web/features/landing/components/download/all-platforms.tsx
+++ b/apps/web/features/landing/components/download/all-platforms.tsx
@@ -148,9 +148,7 @@ export function AllPlatforms({
);
}
-// ------------------------------------------------------------
// Row
-// ------------------------------------------------------------
interface RowProps {
icon: React.ReactNode;
diff --git a/apps/web/features/landing/components/download/hero.tsx b/apps/web/features/landing/components/download/hero.tsx
index 0f35eb6966..13028684b4 100644
--- a/apps/web/features/landing/components/download/hero.tsx
+++ b/apps/web/features/landing/components/download/hero.tsx
@@ -78,9 +78,7 @@ export function DownloadHero({
);
}
-// ------------------------------------------------------------
// Content resolver — maps (detect, assets) → CTA props
-// ------------------------------------------------------------
interface HeroContent {
title: string;
@@ -207,9 +205,7 @@ export function resolveContent(
};
}
-// ------------------------------------------------------------
// Pieces
-// ------------------------------------------------------------
function PrimaryCta({
href,
diff --git a/apps/web/platform/in-app-history.ts b/apps/web/platform/in-app-history.ts
index 57fbf17886..a796c04eb8 100644
--- a/apps/web/platform/in-app-history.ts
+++ b/apps/web/platform/in-app-history.ts
@@ -1,25 +1,9 @@
/**
- * "Is there a Multica page behind this one?" for the web navigation adapter.
- *
- * Callers that want to step back (deleting an issue returns the user to the
- * list they opened it from) must not step back off the app when the current
- * page was opened cold — a shared link, a pasted URL, a new tab.
- *
- * Only the browser can answer this, and exactly one API does: the Navigation
- * API's `entries()` spans just the contiguous same-origin run around the
- * current entry, so arriving from an external site reports `canGoBack` false
- * even though the browser technically has somewhere to go. `history.length`
- * is no substitute — it counts other origins' entries too.
- *
- * Nothing else here is a guess. Counting the adapter's own `router.push`
- * calls looks like a workable fallback and is not: a push is a request, not a
- * committed history entry. Next drops it to `replaceState` when the canonical
- * URL is unchanged (`app-router.js`, the `pendingPush && href !== canonicalUrl`
- * branch), and pushes can also be superseded or abandoned mid-transition. Any
- * count derived from calls can therefore claim history that does not exist,
- * and a wrong `true` walks the user out of Multica — the precise failure this
- * exists to prevent. So where the browser cannot answer we report `false`,
- * and callers take their fallback path.
+ * Determine whether web navigation has a safe in-app back destination.
+ * Use Navigation API entries for committed same-origin history. history.length
+ * includes external entries, and counting router.push requests includes navigations
+ * that may be replaced or abandoned. Return false when the browser cannot prove
+ * a destination so callers use their fallback instead of leaving the app.
*/
/** Minimal shape of the Navigation API — not in TypeScript's DOM lib yet. */
diff --git a/packages/core/agents/failure-reason.ts b/packages/core/agents/failure-reason.ts
index 1f01cdecc6..0875dab9b7 100644
--- a/packages/core/agents/failure-reason.ts
+++ b/packages/core/agents/failure-reason.ts
@@ -1,25 +1,10 @@
import type { TaskFailureReason } from "../types";
/**
- * Picks the copy key a UI surface should render for a server-supplied
- * `failure_reason`, degrading instead of falling off a cliff.
- *
- * Resolution order:
- * 1. Exact match — the surface has copy for this precise reason.
- * 2. Coarse family — `agent_error.provider_network` degrades to
- * `agent_error` when the surface only has family-level copy.
- * 3. `undefined` — nothing usable; the caller renders its own fallback.
- *
- * Why this exists: the backend's taxonomy is refined (`agent_error.*`) and
- * grows independently of shipped clients. Before MUL-5370 the surfaces did an
- * exact `Record` lookup against the six-value coarse enum, so every refined
- * reason missed and rendered a generic "something went wrong" — the useful
- * classification the backend had already computed was thrown away at the last
- * step. Step 2 makes an unseen `agent_error.<new_thing>` land on the family
- * line rather than the fallback, which is the repo's "enum drift downgrades,
- * not crashes" rule applied to copy.
- *
- * Pure and dependency-free so mobile can import it directly.
+ * Resolve failure copy by exact reason, then coarse family, then caller fallback.
+ * The server taxonomy can grow independently of installed clients; unfamiliar
+ * agent_error subtypes should retain family-level guidance. Keep this helper pure
+ * so mobile can share it.
*/
export function resolveFailureReasonKey<K extends string>(
reason: TaskFailureReason | string | null | undefined,
diff --git a/packages/core/agents/types.ts b/packages/core/agents/types.ts
index 3bb23ef562..a306c928ee 100644
--- a/packages/core/agents/types.ts
+++ b/packages/core/agents/types.ts
@@ -1,27 +1,6 @@
-// Derived presence types for agents — the user-facing state we display
-// across the UI (list dots, hover cards, status lines). Computed in the
-// front-end from raw server data (agent + runtime + recent tasks); the
-// back-end never knows about these enums.
-//
-// Two orthogonal dimensions, derived independently and answering only
-// "what's true right now?" — historical / error context lives on the
-// agent detail page (Recent Work, failure_reason) and Inbox, not in the
-// list-level summary state:
-//
-// 1. AgentAvailability — "Can this agent take work right now?"
-// Depends only on runtime reachability. The dot colour everywhere in
-// the app reflects this single dimension; never sticky-red because of
-// a past task outcome.
-//
-// 2. Workload — "What is on this agent's plate right now?"
-// Depends only on the workspace task snapshot. Three states, each
-// pointing at a clear user action:
-// working → tasks running, normal
-// queued → tasks queued but nothing running (= stuck if availability
-// is offline/unstable; momentary if online)
-// idle → nothing to do
-// No `failed` / `completed` / `cancelled` states — those are historical,
-// surfaced via Recent Work + Inbox.
+// Agent presence has two independent current-state dimensions: runtime
+// availability and active task workload. Past failures and completed tasks belong
+// in Recent Work and Inbox rather than persisting as a list-level error state.
// Runtime-reachability dimension. `unstable` is the transient amber state
// during the runtime sweeper's grace window (offline < 5 min); it decays
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 265d284571..7719f247ad 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -2054,12 +2054,10 @@ export class ApiClient {
});
}
- // ---------------------------------------------------------------------
// Cloud Billing — proxies to multica-cloud /api/v1/billing/*. The
// multica-api server stamps X-User-ID and forwards bytes; everything
// here is upstream-shaped. See packages/core/types/billing.ts for the
// response field documentation.
- // ---------------------------------------------------------------------
async getCloudBillingBalance(): Promise<BillingBalance> {
const raw = await this.fetch<unknown>("/api/cloud-billing/balance");
@@ -2183,7 +2181,6 @@ export class ApiClient {
);
}
- // ---------------------------------------------------------------------
// Workspace subscriptions — the server resolves the workspace from the
// authenticated request context, so no caller names one.
//
@@ -2193,7 +2190,6 @@ export class ApiClient {
// - non-2xx (older cloud without the route, 403, 503) throws ApiError from
// `fetch`, so a React Query caller sees `isError`;
// - a 2xx body that does not match the contract returns null here.
- // ---------------------------------------------------------------------
async getWorkspaceSubscriptionSummary(): Promise<WorkspaceSubscriptionSummary | null> {
const raw = await this.fetch<unknown>("/api/cloud-subscriptions/summary");
@@ -2375,10 +2371,8 @@ export class ApiClient {
});
}
- // ---------------------------------------------------------------------
// Custom runtime profiles (MUL-3284). All workspace-scoped: the caller
// passes the workspace id the same way the runtimes list resolves it.
- // ---------------------------------------------------------------------
async listRuntimeProfiles(workspaceId: string): Promise<RuntimeProfile[]> {
const res = await this.fetch<{ runtime_profiles?: RuntimeProfile[] }>(
@@ -2520,12 +2514,10 @@ export class ApiClient {
);
}
- // ---------------------------------------------------------------------------
// Workspace dashboard — three independent rollups for `/{slug}/dashboard`.
// Each accepts an optional `project_id` to narrow the scope to one project.
// Cost is computed client-side from the model pricing table (same contract
// as the per-runtime endpoints above).
- // ---------------------------------------------------------------------------
async getDashboardUsageDaily(
params: { days?: number; project_id?: string | null; tz?: string },
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 70703c647f..a4999b3011 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -780,7 +780,6 @@ export interface AppConfigResponse {
server_version?: string;
}
-// ---------------------------------------------------------------------------
// Schemas for the highest-risk API endpoints — those whose responses drive
// the issue detail page (timeline, comments, subscribers) and the issues
// list. These are the surfaces that white-screened in #2143 / #2147 / #2192.
@@ -806,7 +805,6 @@ export interface AppConfigResponse {
// literal unions, which would defeat the leniency above. `parseWithFallback`
// returns the parsed value cast to the caller-supplied `T`, so the strict
// type still flows out at the call site; the schema only guards shape.
-// ---------------------------------------------------------------------------
const ReactionSchema = z.object({
id: z.string(),
@@ -1679,7 +1677,6 @@ export const EMPTY_CLOUD_RUNTIME_NODE: CloudRuntimeNode = {
updated_at: "",
};
-// ---------------------------------------------------------------------------
// Workspace dashboard schemas
//
// The dashboard hits three independent rollup endpoints. Each returns a flat
@@ -1688,7 +1685,6 @@ export const EMPTY_CLOUD_RUNTIME_NODE: CloudRuntimeNode = {
// String fields default to "" (no enum narrowing) to survive future model /
// agent ID drift, and so a single null from tz-aware SQL bucketing fails
// only that row instead of dropping the whole array to the `[]` fallback.
-// ---------------------------------------------------------------------------
// Cost split carried by every usage row. `cost_usd_ticks` is what the provider
// itself charged for the rows behind this aggregate (1e-10 USD); the
@@ -1788,12 +1784,10 @@ export const DashboardFailureByAgentListSchema = z.array(
DashboardFailureByAgentSchema,
);
-// ---------------------------------------------------------------------------
// Runtime usage schemas — the runtime-detail page's four usage endpoints
// (`/api/runtimes/:id/usage*`). Same leniency rules as the dashboard
// schemas above: numbers default to 0, strings to "", `.loose()` passes
// unknown fields.
-// ---------------------------------------------------------------------------
const RuntimeUsageSchema = z.object({
runtime_id: z.string().default(""),
@@ -1843,10 +1837,8 @@ const RuntimeUsageByHourSchema = z.object({
export const RuntimeUsageByHourListSchema = z.array(RuntimeUsageByHourSchema);
-// ---------------------------------------------------------------------------
// Agent task responses. The base object stays loose so daemon/runtime fields
// can drift while task-list consumers still validate the fields they render.
-// ---------------------------------------------------------------------------
// Human attribution (MUL-4302 §9): who an agent run is accountable to, and how
// that human was resolved. Every field is defensive so a departed member, an
@@ -2320,7 +2312,6 @@ export const SquadMemberStatusListResponseSchema = z.object({
export const EMPTY_SQUAD_MEMBER_STATUS_LIST = { members: [] };
-// ---------------------------------------------------------------------------
// Structured error body — POST /api/workspaces/:wsId/issues 409 conflict.
//
// When the server detects an active issue with the same title in the same
@@ -2340,7 +2331,6 @@ export const EMPTY_SQUAD_MEMBER_STATUS_LIST = { members: [] };
// so a future server-side rename of `status` must not knock this branch
// out. `.loose()` lets the field pass through unchanged for any other
// consumer.
-// ---------------------------------------------------------------------------
export const DuplicateIssueErrorBodySchema = z.object({
code: z.literal("active_duplicate_issue"),
@@ -2362,14 +2352,12 @@ export interface DuplicateIssueErrorBody {
};
}
-// ---------------------------------------------------------------------------
// Webhook delivery schemas — backing the Autopilot Deliveries section. Enums
// (`status`, `signature_status`, `provider`) are kept as `z.string()` so a
// future server-side value (e.g. a Stripe provider, a new dedupe state)
// degrades to a generic UI fallback rather than collapsing the list into
// the empty array. `.loose()` lets unknown fields pass through, matching
// the rule used by every other endpoint here.
-// ---------------------------------------------------------------------------
const WebhookDeliverySchema = z.object({
id: z.string(),
@@ -2416,13 +2404,11 @@ export const EMPTY_LIST_WEBHOOK_DELIVERIES_RESPONSE: ListWebhookDeliveriesRespon
total: 0,
};
-// ---------------------------------------------------------------------------
// Autopilot list schema. Enums (`status`, `execution_mode`, `trigger_kinds`,
// `last_run_status`) stay `z.string()` so future server-side values degrade
// to a generic UI fallback. The three derived fields (trigger_kinds /
// next_run_at / last_run_status) are list-endpoint-only and absent on older
// servers — optional by contract, the list renders "—" without them.
-// ---------------------------------------------------------------------------
const AutopilotListItemSchema = z.object({
id: z.string(),
@@ -2551,7 +2537,6 @@ export const EMPTY_WEBHOOK_DELIVERY: WebhookDelivery = {
created_at: "",
};
-// ---------------------------------------------------------------------------
// User (`/api/me` GET + PATCH). The auth store and Settings → Account both
// trust this shape — a drift here would knock both surfaces out. Kept
// lenient by the same rules as IssueSchema: enums stay `z.string()`,
@@ -2560,7 +2545,6 @@ export const EMPTY_WEBHOOK_DELIVERY: WebhookDelivery = {
// MUL-2406; the server emits `""` when unset (NOT NULL DEFAULT ''), so
// the schema defaults to `""` too — keeps the type tight without
// breaking older backends that don't return the column yet.
-// ---------------------------------------------------------------------------
export const UserSchema = z.object({
id: z.string(),
@@ -2592,13 +2576,11 @@ export const EMPTY_USER: User = {
updated_at: "",
};
-// ---------------------------------------------------------------------------
// Cross-workspace unread inbox summary (`/api/inbox/unread-summary` GET).
// One entry per workspace the user belongs to that has unread items; the
// sidebar derives the workspace-switcher dot from it. Lenient per the usual
// rules so a future field addition can't blank the dot — on malformed JSON
// parseWithFallback returns the empty list, which simply hides the dot.
-// ---------------------------------------------------------------------------
export const InboxUnreadSummarySchema = z.array(
z
@@ -2611,7 +2593,6 @@ export const InboxUnreadSummarySchema = z.array(
export const EMPTY_INBOX_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];
-// ---------------------------------------------------------------------------
// Inbox items (`/api/inbox` and `/api/inbox/archived` GET).
// Lenient per the usual rules: `severity` / `type` / `recipient_type` stay
// `z.string()` so a notification kind this client doesn't know yet still
@@ -2621,7 +2602,6 @@ export const EMPTY_INBOX_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];
// empty list — the affected view then reads as empty rather than white-
// screening the inbox. Both endpoints share this boundary because they return
// the same row shape and both feed the status/priority filter UI.
-// ---------------------------------------------------------------------------
export const InboxItemListSchema = z.array(
z
@@ -2664,7 +2644,6 @@ export const ArchivedInboxFacetsSchema = z.object({
export const EMPTY_INBOX_ITEMS: InboxItem[] = [];
-// ---------------------------------------------------------------------------
// Billing schemas (cloud-billing proxy surface)
//
// All billing JSON we receive comes from multica-cloud verbatim — we proxy
@@ -2834,7 +2813,6 @@ export const EMPTY_CREATE_BILLING_PORTAL_SESSION_RESPONSE: CreateBillingPortalSe
url: "",
};
-// ---------------------------------------------------------------------------
// Workspace subscriptions (`/api/cloud-subscriptions/*`)
//
// These schemas are the compatibility boundary with multica-cloud. Three rules
@@ -3130,7 +3108,6 @@ export const CreateWorkspaceSubscriptionPortalResponseSchema = z
}),
);
-// ---------------------------------------------------------------------------
// Runtime model discovery (`POST /api/runtimes/:id/models`,
// `GET /api/runtimes/:id/models/:requestId`). Both endpoints return the same
// request record, and the UI drives a state machine off `status`, so the two
@@ -3146,7 +3123,6 @@ export const CreateWorkspaceSubscriptionPortalResponseSchema = z
//
// `cached` / `cached_at` are additive markers for a snapshot served from the
// server-side catalog cache (MUL-5444); an older backend omits them.
-// ---------------------------------------------------------------------------
const RuntimeModelThinkingLevelSchema = z.object({
value: z.string(),
diff --git a/packages/core/attachments/image-sequence.ts b/packages/core/attachments/image-sequence.ts
index c6ccf620c7..c16c21f016 100644
--- a/packages/core/attachments/image-sequence.ts
+++ b/packages/core/attachments/image-sequence.ts
@@ -72,9 +72,7 @@ export function isImageAttachment(
return ext !== "" && IMAGE_EXTENSIONS.has(ext);
}
-// ---------------------------------------------------------------------------
// URL → attachment matching
-// ---------------------------------------------------------------------------
function stripQueryAndFragment(url: string): string {
return url.split(/[?#]/, 1)[0] ?? "";
@@ -177,9 +175,7 @@ export function orderStandaloneAttachments<T extends Pick<Attachment, "content_t
return [...groups.image, ...groups.file];
}
-// ---------------------------------------------------------------------------
// Inline image references
-// ---------------------------------------------------------------------------
function blankOut(text: string): string {
// Newlines survive so line-anchored patterns below keep their line numbers.
@@ -299,9 +295,7 @@ function extractInlineRefs(rawContent: string): InlineRef[] {
return refs.sort((a, b) => a.index - b.index);
}
-// ---------------------------------------------------------------------------
// Sequence
-// ---------------------------------------------------------------------------
/** One attachment the viewer can page to. */
export interface ImageSequenceItem {
diff --git a/packages/core/github/pull-request-status.ts b/packages/core/github/pull-request-status.ts
index 68cb208878..474bb8742f 100644
--- a/packages/core/github/pull-request-status.ts
+++ b/packages/core/github/pull-request-status.ts
@@ -21,9 +21,7 @@ import type {
// fields; each rule defaults defensively (`?? 0`, `?? []`, explicit `=== "..."`
// checks) so an absent field never fabricates a positive verdict.
-// ---------------------------------------------------------------------------
// CI status
-// ---------------------------------------------------------------------------
// Discriminated union for the CI element. `none` is a current snapshot with no
// checks; `unavailable` means there is no current snapshot region to render.
@@ -94,9 +92,7 @@ export function deriveChecksStatus(input: PullRequestChecksInput): PullRequestCh
return input.snapshot_available === true ? { kind: "none" } : { kind: "unavailable" };
}
-// ---------------------------------------------------------------------------
// Mergeability
-// ---------------------------------------------------------------------------
// Discriminated union for the mergeability element. `none` renders nothing:
// when GitHub has not decided (mergeable unknown/null and no decisive
@@ -141,9 +137,7 @@ export function deriveMergeStatus(input: PullRequestMergeInput): PullRequestMerg
return { kind: "none" };
}
-// ---------------------------------------------------------------------------
// Diff stats
-// ---------------------------------------------------------------------------
export interface PullRequestStatsInput {
additions?: number;
@@ -163,9 +157,7 @@ export function shouldShowPullRequestStats(input: PullRequestStatsInput): boolea
return a + d + f > 0;
}
-// ---------------------------------------------------------------------------
// Row verdict
-// ---------------------------------------------------------------------------
// The one thing the sidebar row says about a PR: what stands between it and a
// merge, or how it ended. `failed` carries the failing check names and whether
@@ -224,9 +216,7 @@ export function derivePullRequestVerdict(input: PullRequestVerdictInput): PullRe
return { kind: "unknown" };
}
-// ---------------------------------------------------------------------------
// Row copy
-// ---------------------------------------------------------------------------
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
diff --git a/packages/core/hooks/use-file-upload.ts b/packages/core/hooks/use-file-upload.ts
index 68e92916df..603503056a 100644
--- a/packages/core/hooks/use-file-upload.ts
+++ b/packages/core/hooks/use-file-upload.ts
@@ -6,49 +6,12 @@ import type { Attachment } from "../types";
import { attachmentDownloadPath } from "../types/attachment-url";
import { MAX_FILE_SIZE } from "../constants/upload";
-// Carries the full Attachment so editors that need preview metadata
-// (`content_type`, `download_url`) get it directly. Two URL fields are
-// surfaced because they have different lifetimes:
-//
-// `link` — the same value as `att.url`. Short-lived for the
-// LocalStorage backend (HMAC-signed `/uploads/<key>`)
-// and a long-lived CDN URL on S3 / CloudFront. This
-// is what avatar / logo callers persist into
-// `avatar_url` style fields, and what URL-only
-// consumers (Markdown renderers without a record
-// in hand) get to load directly. Keeping it
-// semantically equal to `att.url` preserves the
-// pre-MUL-3130 contract for non-markdown callers
-// so avatar uploads do not get rerouted through
-// the workspace-membership-gated download endpoint.
-//
-// `markdownLink` — the URL the editor writes into markdown bodies.
-// Source: `att.markdown_url` from the server, which
-// `buildMarkdownURL` picks per deployment policy
-// (public CDN durable URL, or
-// `<MULTICA_PUBLIC_URL>/api/attachments/<id>/download`).
-// The contract is "absolute, no TTL, loads natively
-// on every client" — that's what fixes the Desktop /
-// mobile-webview regression where a site-relative
-// `/api/attachments/<id>/download` couldn't resolve
-// against `file://` (MUL-3192).
-//
-// Falls back through two layers when the server
-// didn't populate `markdown_url`:
-// 1. `attachmentDownloadPath(att.id)` — the legacy
-// site-relative shape. Works on web (Next
-// rewrite proxies /api/* to the API host) and
-// is what older comments persist; render
-// surfaces handle the absolutize for non-web
-// clients via attachment.tsx's legacy compat.
-// 2. `att.url` — the no-workspace avatar branch
-// where there's no attachment-row id at all.
-//
-// MUL-3130 introduced the persisted-image regression by collapsing
-// these two semantics into a single `link` field; MUL-3192 followed up
-// by moving the durable-URL choice from the client to the server so
-// the persisted shape is correct for the deployment without the client
-// having to know whether it's running on web / desktop / mobile.
+// UploadResult keeps raw storage and durable Markdown URLs separate.
+// link preserves att.url for avatars and other storage-reference consumers.
+// markdownLink uses the server's absolute, non-expiring markdown_url so native
+// clients can load persisted media across origins. Older responses fall back to
+// an attachment-ID path, then the raw URL when no attachment row exists.
+// The full Attachment carries preview metadata alongside these conveniences.
export type UploadResult = Attachment & {
link: string;
markdownLink: string;
@@ -60,20 +23,8 @@ export interface UploadContext {
chatSessionId?: string;
}
-// pickMarkdownLink chooses the URL the editor will write into markdown.
-//
-// Order:
-// 1. `att.markdown_url` — server-provided durable URL. This is the
-// modern contract introduced in MUL-3192; the server (`buildMarkdownURL`)
-// decides whether to emit a public CDN URL or an absolute API
-// endpoint pinned to `MULTICA_PUBLIC_URL` based on the deployment.
-// 2. `attachmentDownloadPath(att.id)` — site-relative legacy shape,
-// retained for compatibility with backends old enough to predate
-// MUL-3192. Web's Next rewrite makes this load; desktop / mobile
-// surfaces hit the attachment.tsx legacy-absolutize fallback.
-// 3. `att.url` — no attachment-row id (the no-workspace avatar branch
-// of UploadFile). Markdown callers fall back to whatever storage
-// backend produced for the upload; persistence is on the caller.
+// pickMarkdownLink prefers the server's durable URL. Older responses fall back
+// to an attachment-ID path, then raw storage for uploads without a row ID.
function pickMarkdownLink(att: Attachment): string {
if (att.markdown_url) return att.markdown_url;
if (att.id) return attachmentDownloadPath(att.id);
diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.ts
index 0c6b2880e4..b4becc22f7 100644
--- a/packages/core/inbox/mutations.ts
+++ b/packages/core/inbox/mutations.ts
@@ -7,35 +7,13 @@ import { useWorkspaceId } from "../hooks";
import type { InboxItem } from "../types";
/**
- * Re-read every inbox cache a write can change: both workspace lists and the
- * cross-workspace unread summary.
+ * Refresh workspace inbox lists and the account-level unread summary after a
+ * confirmed write. Use realtime's refresh helpers so in-flight reads are cancelled
+ * before refetching; a workspace query prefix does not reach the summary.
*
- * The unread badge reads that summary (`useInboxUnreadCount`), and it lives
- * under its own account-level key which `inboxKeys.all(wsId)` does not reach.
- * Every mutation here can change the number it holds, so each one refreshes it
- * once the server has confirmed, rather than waiting for the WebSocket echo of
- * its own action.
- *
- * Deliberately the same entry points realtime uses, not local copies: both
- * refreshes have to cancel any in-flight request first, and a mutation racing
- * a first load hits exactly the same hole a WS event does. A plain
- * `invalidateQueries` on the list here would let the list fall behind the
- * badge — the two are rendered side by side (see `refreshInboxQuery`).
- *
- * Not awaited by `onSettled`: the mutation is finished once the server has
- * answered, and a background refresh should not hold its lifecycle open.
- *
- * The rows are patched optimistically but the badge is NOT: it follows the
- * server's confirmation, which buys a single writer at the cost of the badge
- * trailing the row. Deriving it locally instead — recomputing the count from
- * the list cache and writing that back — reads as instant but is unsound: a
- * list cache proves only that the list was loaded ONCE, never that it is
- * complete or concurrent with the summary, and the account-level summary
- * request is not cancelled by the workspace-scoped `cancelQueries` below, so a
- * response already in flight lands on top of the local value anyway. Under
- * pagination it would be wrong by construction — one loaded page cannot
- * produce a global count. If instant feedback is wanted later, it has to be a
- * per-group delta that handles the race, not a recomputed total.
+ * Rows may patch optimistically, but the unread badge follows server confirmation.
+ * A partial or independently fetched list cannot produce a reliable global total.
+ * Do not hold the completed mutation open while the refresh runs.
*/
function refreshInboxAfterWrite(qc: QueryClient, wsId: string) {
void onInboxInvalidate(qc, wsId);
diff --git a/packages/core/issue-statuses/mutations.ts b/packages/core/issue-statuses/mutations.ts
index 55ebdcd3cc..9905806d85 100644
--- a/packages/core/issue-statuses/mutations.ts
+++ b/packages/core/issue-statuses/mutations.ts
@@ -11,33 +11,11 @@ import type {
} from "../types";
/**
- * Catalog mutations (MUL-6243).
- *
- * No mutation invalidates the catalog on success. The refresh is the
- * `issue_status:changed` realtime event, which reaches the writing tab as well
- * as every other one, so a catalog edit costs each client exactly ONE catalog
- * read. Invalidating here too would make the admin who did the writing the
- * only client that reads it twice. (MUL-6458)
- *
- * That refetch is what CONVERGES the cache, and it is ordered correctly by
- * construction: the event is published after the write commits, so the refetch
- * it triggers can only read post-commit state.
- *
- * Which is why no mutation writes its RESPONSE BODY into the cache. A response
- * is authoritative for the row as of that write, not as of now — and the two
- * channels are independent, so a slow response can land after a refetch that
- * already picked up someone else's later write and quietly roll the catalog
- * back to a state nothing will correct. Every local write below is instead
- * something that stays true no matter what else has landed in between:
- *
- * - an optimistic field patch (rename, recolor, reorder),
- * - an insert of a row nobody else can have seen yet (create),
- * - a monotonic flag (archive — there is no unarchive endpoint, and the server
- * refuses to edit an archived row, so setting it can never be stale).
- *
- * On FAILURE the invalidate stays, and it is not symmetry for its own sake: a
- * 409 usually means this client's catalog is the stale thing — someone else
- * took the name, or archived the row that was being dragged.
+ * Catalog edits converge through the post-commit issue_status:changed event.
+ * Avoid a duplicate success invalidation or writing a response snapshot that can
+ * arrive after a newer refetch. Local patches must remain valid across that race:
+ * optimistic fields, newly created rows, or monotonic archive flags.
+ * Invalidate failures because a conflict may reveal stale local catalog state.
*/
function useCatalogCache() {
diff --git a/packages/core/issues/cache-coordinator.ts b/packages/core/issues/cache-coordinator.ts
index 439fae5866..a4d6d44ccf 100644
--- a/packages/core/issues/cache-coordinator.ts
+++ b/packages/core/issues/cache-coordinator.ts
@@ -39,46 +39,15 @@ export type IssueFlatCache = InfiniteData<ListIssuesResponse, number>;
export type IssueTableRowCache = IssueTableRowsResponse;
/**
- * IssueCacheCoordinator — the one rules table for how a single issue change
- * propagates through the query cache.
+ * IssueCacheCoordinator applies shared mutation and WebSocket cache rules.
+ * Patch determinate loaded rows, remove rows that leave a filter, and mark keys
+ * stale when membership or an unloaded row's server-sorted position is uncertain.
+ * Update bucket totals for known transitions without inserting speculative rows.
*
- * Every write path converges here: `useUpdateIssue` (onMutate optimistic +
- * onSuccess server reconcile), `useBatchUpdateIssues`, and the WS
- * `issue:updated` handler all call {@link applyIssueChange}, so "I changed
- * it" and "someone else changed it" follow the same rules by construction.
- *
- * The rules, per loaded bucketed list (workspace board + every myList
- * scope — My Issues, Project, actor panels, workspace members/agents tabs):
- *
- * card present, filter untouched by the change → surgical patch (rebucket
- * on status, position-slot insert; never a refetch — refetching the
- * visible list is what made drags flicker)
- * card present, no longer matches the list's filter → surgical REMOVE
- * (bucket total decremented) — the "issue left this surface" case that a
- * filter-blind patch used to leave behind (MUL-3669)
- * card present, membership undecidable client-side (involves / my:all) →
- * patch + mark the key stale
- * card absent, change can't affect this list → skip
- * card absent, stayed a member + status changed → move one unit of the
- * server total between the two buckets immediately, then mark the key
- * stale: the row's slot in the destination bucket's loaded window is
- * server knowledge, and under staleTime: Infinity an explicit
- * invalidation is the only channel that ever fills it in
- * card absent, left the list (reassigned / re-projected) → old status
- * bucket total -1
- * card absent, may have ENTERED, or anything undecidable (no base entity,
- * unknown membership) → mark the key stale (never hard-insert: the
- * right page/slot under the list's sort+filter is server knowledge)
- *
- * Stale keys are NOT invalidated here — timing is the caller's contract:
- * mutations defer them to onSettled (invalidating mid-flight would refetch
- * uncommitted state and stomp the optimistic patch), the WS path invalidates
- * immediately (the server already committed).
- *
- * The detail cache and the Inbox issue projections are patched in the
- * same pass. Aggregate projections that cannot be recomputed from one entity
- * (assignee-grouped boards, Gantt, project metrics) go through
- * {@link invalidateIssueDerivatives}.
+ * This helper returns stale keys without invalidating them: mutations wait until
+ * onSettled so refetches cannot overwrite optimistic work, while committed WS
+ * changes invalidate immediately. Detail and inbox projections are patched here;
+ * aggregate projections use invalidateIssueDerivatives.
*/
export interface IssueCacheChangeResult {
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 5dfc3cc81d..8f28beb073 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -56,10 +56,8 @@ import {
reconcileIssueFullSnapshotRevision,
} from "./ws-updaters";
-// ---------------------------------------------------------------------------
// Shared mutation variable types — used by both mutation hooks and
// useMutationState consumers to keep the type assertion in sync.
-// ---------------------------------------------------------------------------
export type ToggleCommentReactionVars = {
commentId: string;
@@ -81,13 +79,9 @@ export type UpdateIssueMutationInput = {
move_intent?: Pick<MoveIssueRequest, "before_id" | "after_id">;
} & UpdateIssueRequest;
-// ---------------------------------------------------------------------------
// Per-status pagination
-// ---------------------------------------------------------------------------
-// ---------------------------------------------------------------------------
// Issue CRUD
-// ---------------------------------------------------------------------------
// Shared by the single and batch update hooks, so the inbox re-read can wait
// for the last of them (see `owedInboxRereads`).
@@ -816,9 +810,7 @@ export function useBatchDeleteIssues() {
});
}
-// ---------------------------------------------------------------------------
// Comments / Timeline
-// ---------------------------------------------------------------------------
type TimelineCache = TimelineEntry[];
@@ -1091,9 +1083,7 @@ export function useToggleCommentReaction(issueId: string) {
});
}
-// ---------------------------------------------------------------------------
// Issue-level Reactions
-// ---------------------------------------------------------------------------
export function useToggleIssueReaction(issueId: string) {
const qc = useQueryClient();
@@ -1119,9 +1109,7 @@ export function useToggleIssueReaction(issueId: string) {
});
}
-// ---------------------------------------------------------------------------
// Issue Subscribers
-// ---------------------------------------------------------------------------
export function useToggleIssueSubscriber(issueId: string) {
const qc = useQueryClient();
diff --git a/packages/core/onboarding/step-order.ts b/packages/core/onboarding/step-order.ts
index ad4423d5d7..ece7828d9c 100644
--- a/packages/core/onboarding/step-order.ts
+++ b/packages/core/onboarding/step-order.ts
@@ -1,32 +1,10 @@
import type { OnboardingStep } from "./types";
/**
- * Canonical order of the persisted onboarding steps.
- *
- * Single source of truth for "what step comes after what" — consumed
- * by the UI progress indicator to compute `index of current_step` and
- * `total step count`. Inserting, reordering, or removing a step only
- * requires changing this array; every call site that reads it updates
- * automatically.
- *
- * Intentionally excludes "welcome": welcome is a first-entry product
- * intro, not a persisted step. It doesn't show a progress indicator
- * for the same reason — users shouldn't think of reading the intro
- * as progress toward completing setup.
- *
- * Two questions are intentionally NOT steps anymore:
- *
- * - "source" (How did you hear about Multica?) is pure attribution
- * data with zero user-facing payoff, so it no longer taxes the
- * critical path. It is collected post-onboarding by the workspace
- * source-backfill prompt, and only after agents have completed
- * work for the user — see `needs-backfill.ts`.
- * - "role" / "use_case" merged into the single "about_you" step so
- * related personalization inputs stay together.
- *
- * Runtime is the final form step. A connected path provisions Mika and opens
- * the interactive onboarding chat as part of the runtime step's submit action;
- * that chat is the product experience itself, not another progress-screen step.
+ * Canonical persisted onboarding order for progress and navigation.
+ * Welcome is an unpersisted introduction; source attribution is collected later.
+ * About-you combines personalization questions. Runtime is the final form step;
+ * its connected path provisions Mika and enters chat without another progress step.
*/
export const ONBOARDING_STEP_ORDER: readonly OnboardingStep[] = [
"about_you",
diff --git a/packages/core/onboarding/types.ts b/packages/core/onboarding/types.ts
index 46b66b7d91..91b70604a7 100644
--- a/packages/core/onboarding/types.ts
+++ b/packages/core/onboarding/types.ts
@@ -55,33 +55,13 @@ export type UseCase =
| "other";
/**
- * Questionnaire shape. `use_case` allows multiple values (users hire
- * Multica for several jobs at once); `source` and `role` are single-
- * select — for `source` we capture the primary acquisition channel
- * for clean self-reported-attribution math (the array shape is
- * preserved for back-compat with v2 multi-select rows; the client
- * now always commits a one-element array), and `role` stays single
- * because downstream personalization wants a primary identity.
+ * Questionnaire persistence shared by onboarding and source backfill.
+ * use_case is multi-select; source and role are single-select. Source retains an
+ * array shape for stored compatibility and is collected after agent work completes.
+ * Explicit *_skipped flags distinguish declines from unanswered fields.
*
- * `role` / `use_case` are collected in-flow on the About-you step;
- * `source` is no longer asked during onboarding — it is collected
- * after the user has seen agents complete work, via the workspace
- * source-backfill prompt (see `needs-backfill.ts`). The slots stay in
- * this one shape because they share the same JSONB column and PATCH
- * endpoint.
- *
- * `*_skipped: true` distinguishes an explicit Skip / decline from a
- * slot the user never reached. Both states are "unknown" for
- * personalization purposes; the skip marker exists for analytics and
- * so future re-prompts can avoid nagging users who already declined.
- *
- * Backward compat: prior versions of this app wrote `source` and
- * `use_case` as a single string. `mergeQuestionnaire` in
- * `onboarding-flow.tsx` upgrades those rows to single-element arrays
- * on read; the server's `questionnaireAnswers.UnmarshalJSON` does the
- * same. `version` stays at 2 — the JSONB column is schema-less so a
- * mechanical bump would only show up in analytics, not in storage,
- * and we keep one funnel cohort.
+ * Readers normalize older single-string source/use_case values to arrays.
+ * Version 2 remains the shared analytics cohort; the JSONB storage is schema-less.
*/
export interface QuestionnaireAnswers {
source: Source[];
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 1653cdf74c..8d1759d801 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -7,7 +7,6 @@ export type AgentRuntimeMode = "local" | "cloud";
export type AgentVisibility = "workspace" | "private";
-// ---------------------------------------------------------------------------
// Agent invocation permissions (MUL-3963)
//
// `permission_mode` + `invocation_targets` are the AUTHORITATIVE gate for who
@@ -24,7 +23,6 @@ export type AgentVisibility = "workspace" | "private";
// - permission_mode "public_to" + workspace target: any workspace member
// - permission_mode "public_to" + member target: only the matching user
// - team target: reserved, INERT in v1 (never grants)
-// ---------------------------------------------------------------------------
export type AgentPermissionMode = "private" | "public_to";
@@ -93,7 +91,6 @@ export interface RuntimeDevice {
export type AgentRuntime = RuntimeDevice;
-// ---------------------------------------------------------------------------
// Custom runtime profiles (MUL-3284)
//
// A RuntimeProfile is a workspace-level *definition* of a custom runtime
@@ -101,7 +98,6 @@ export type AgentRuntime = RuntimeDevice;
// *instance*. An admin authors a profile (display name + base protocol
// family + the CLI command to launch), and daemons can then register
// runtimes against it; those instances carry `profile_id` pointing back here.
-// ---------------------------------------------------------------------------
// The fixed allow-list of base protocol families a custom runtime can wrap.
// These are the only backends the create flow may select; the server rejects
diff --git a/packages/core/types/attachment-url.ts b/packages/core/types/attachment-url.ts
index 9f73af8854..9b9a980594 100644
--- a/packages/core/types/attachment-url.ts
+++ b/packages/core/types/attachment-url.ts
@@ -1,24 +1,7 @@
/**
- * Stable URL helpers for attachment references that get persisted into
- * markdown bodies (issue descriptions, comment bodies, chat messages).
- *
- * Background — MUL-3130:
- *
- * The original upload flow returned `att.url` as the link to embed in
- * markdown. After PR #3903 (MUL-3132), `att.url` for the LocalStorage
- * backend became a 30-minute HMAC-signed `/uploads/<key>?exp&sig` URL.
- * That URL is short-lived by design — it's the in-memory token that
- * keeps native browser <img>/<video> resource loads working without an
- * Authorization header. Persisting it into a comment body means the
- * comment's images break the moment the signature expires (default
- * 30 min). The same problem applies to CloudFront-mode `download_url`
- * values, which are also signed redirects.
- *
- * The fix is to persist a STABLE path that contains only the
- * attachment id. The server's /api/attachments/{id}/download endpoint
- * self-resolves the workspace from the attachment row and re-signs (or
- * proxies) on every request, so the URL is correct forever — until
- * the attachment row itself is deleted.
+ * Stable attachment URLs for persisted Markdown. Signed storage/download URLs
+ * expire; persist attachment-ID paths so the server can authorize and resolve a
+ * fresh download on each request.
*/
const DOWNLOAD_PREFIX = "/api/attachments/";
diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.ts
index 7415d462e4..a32c58ee81 100644
--- a/packages/core/types/billing.ts
+++ b/packages/core/types/billing.ts
@@ -181,7 +181,6 @@ export interface CreateBillingPortalSessionResponse {
url: string;
}
-// ---------------------------------------------------------------------------
// Workspace subscriptions (`/api/cloud-subscriptions/*`)
//
// Workspace-scoped, unlike the account-level wallet types above. The server
diff --git a/packages/core/types/composio.ts b/packages/core/types/composio.ts
index ceb5feb6f4..a1348082f0 100644
--- a/packages/core/types/composio.ts
+++ b/packages/core/types/composio.ts
@@ -23,9 +23,7 @@ export interface ComposioToolkit {
export interface ComposioConnection {
id: string;
toolkit_slug: string;
- /** Connection lifecycle state. `expired` surfaces a Reconnect affordance in
- * the UI; the backend only starts emitting it once Stage 4 webhook handling
- * lands (MUL-3719), but the client renders the branch ahead of that. */
+ /** The backend does not yet emit "expired"; the reconnect UI is prepared for it. */
status: "active" | "expired" | "revoked" | string;
connected_at: string;
last_used_at?: string | null;
diff --git a/packages/views/agents/components/agents-page.tsx b/packages/views/agents/components/agents-page.tsx
index 476546a6bf..8de28298c4 100644
--- a/packages/views/agents/components/agents-page.tsx
+++ b/packages/views/agents/components/agents-page.tsx
@@ -245,9 +245,7 @@ export interface AgentsPageProps {
hasLocalMachine?: boolean;
}
-// ---------------------------------------------------------------------------
// Page header
-// ---------------------------------------------------------------------------
function PageHeaderBar({
totalCount,
@@ -328,9 +326,7 @@ function EmptyState({ onCreate }: { onCreate: () => void }) {
);
}
-// ---------------------------------------------------------------------------
// Cells
-// ---------------------------------------------------------------------------
function CheckboxCell({
checked,
@@ -568,9 +564,7 @@ function LastActiveCell({ row }: { row: AgentListRow }) {
);
}
-// ---------------------------------------------------------------------------
// Header row + skeleton
-// ---------------------------------------------------------------------------
function AgentListHeader({
sortField,
@@ -762,10 +756,8 @@ function LoadingSkeleton() {
);
}
-// ---------------------------------------------------------------------------
// Batch toolbar — archive (with confirm; archiving cancels active tasks) and
// Page
-// ---------------------------------------------------------------------------
export function AgentsPage(_props: AgentsPageProps = {}) {
const { t } = useT("agents");
diff --git a/packages/views/agents/components/runtime-machine-filter-dropdown.tsx b/packages/views/agents/components/runtime-machine-filter-dropdown.tsx
index 597fbd0dea..ddfd0ced2c 100644
--- a/packages/views/agents/components/runtime-machine-filter-dropdown.tsx
+++ b/packages/views/agents/components/runtime-machine-filter-dropdown.tsx
@@ -10,13 +10,11 @@ import {
import type { RuntimeMachine, RuntimeMachineSection } from "../../runtimes/components/runtime-machines";
import { useT } from "../../i18n";
-// ---------------------------------------------------------------------------
// Runtime machine filter — dropdown next to the search input. The trigger
// shows the active machine's title (or "All runtimes"); the menu groups
// machines by section (Local / Remote / Cloud) the same way the
// Runtimes page sidebar does, so a user moving between the two pages
// sees consistent labels and counts.
-// ---------------------------------------------------------------------------
const RUNTIME_MACHINE_SECTIONS: RuntimeMachineSection[] = [
"local",
diff --git a/packages/views/attachments/use-html-preview-scroll-restore.ts b/packages/views/attachments/use-html-preview-scroll-restore.ts
index a3aeb25650..f0c452280a 100644
--- a/packages/views/attachments/use-html-preview-scroll-restore.ts
+++ b/packages/views/attachments/use-html-preview-scroll-restore.ts
@@ -1,38 +1,14 @@
"use client";
/**
- * useHtmlPreviewScrollRestore — wires the full-page HTML attachment iframe
- * into the desktop tab Coordinator's scroll-capture/restore channel
- * (multica-ai#6405).
+ * Bridge a full-page opaque-origin HTML iframe into desktop scroll restoration.
+ * The coordinator cannot read scrollY directly, so the iframe reports positions
+ * through postMessage and this hook registers an ExternalScrollSource.
*
- * Why this exists: the full-page preview renders user HTML inside
- * `<iframe sandbox="allow-scripts" srcDoc>` with no `allow-same-origin`, so
- * the outer document cannot read `iframe.contentWindow.scrollY` (opaque
- * origin → SecurityError) and the Coordinator's `[data-tab-scroll-root]`
- * scan can't see it. The in-iframe bridge (see `iframe-scroll-bridge.ts`)
- * reports `scroll`/`ready` via postMessage; this hook holds the latest value
- * in a ref, registers it as an `ExternalScrollSource` so the Coordinator
- * captures it synchronously at tab-switch, and sends `restore` back when the
- * iframe remounts for the same content.
- *
- * Content-change isolation:
- * - `contentKey` = DJB2 hash of the rendered text.
- * - The iframe is keyed on it, so new content structurally remounts a
- * fresh iframe element + srcdoc document — the old document's bridge,
- * listeners, and `event.source` are gone with the element.
- * - Every bridge message carries the token; late messages from a previous
- * document are dropped.
- * - `capture()` returns top 0 with the NEW token until the new document
- * reports, so a content change followed by an immediate tab switch can
- * never resurrect the old position.
- *
- * Scope: only the full-page `AttachmentPreviewPage` calls this. The viewer
- * modal renders via a separate component
- * (`HtmlPreviewBody` → `CodeBlockIframe`) and never touches this hook, so it
- * cannot register an external source against the current tab. On web
- * (no provider / adapter without `registerExternalSource`) `restoreActive`
- * is false: no bridge is injected, no source is registered, behavior is
- * byte-identical to before.
+ * Content keys remount changed documents and reject late messages. Until the new
+ * document reports, capture zero with the new key to avoid restoring old content's
+ * position. Modal previews and web adapters without external-source support do
+ * not participate.
*/
import { useCallback, useLayoutEffect, useRef } from "react";
diff --git a/packages/views/auth/login-page.tsx b/packages/views/auth/login-page.tsx
index ed1f578b5d..7233cb42c3 100644
--- a/packages/views/auth/login-page.tsx
+++ b/packages/views/auth/login-page.tsx
@@ -25,9 +25,7 @@ import { api } from "@multica/core/api";
import type { User } from "@multica/core/types";
import { useT } from "../i18n";
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
interface GoogleAuthConfig {
clientId: string;
@@ -64,9 +62,7 @@ interface LoginPageProps {
extra?: ReactNode;
}
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
export function redirectToCliCallback(url: string, token: string, state: string) {
const separator = url.includes("?") ? "&" : "?";
@@ -94,9 +90,7 @@ export function validateCliCallback(cliCallback: string): boolean {
}
}
-// ---------------------------------------------------------------------------
// Component
-// ---------------------------------------------------------------------------
export function LoginPage({
logo,
@@ -297,9 +291,7 @@ export function LoginPage({
window.location.href = `https://accounts.google.com/o/oauth2/v2/auth?${params}`;
};
- // -------------------------------------------------------------------------
// CLI confirm step
- // -------------------------------------------------------------------------
if (step === "cli_confirm" && existingUser) {
return (
@@ -341,9 +333,7 @@ export function LoginPage({
);
}
- // -------------------------------------------------------------------------
// Code verification step
- // -------------------------------------------------------------------------
if (step === "code") {
return (
@@ -413,9 +403,7 @@ export function LoginPage({
);
}
- // -------------------------------------------------------------------------
// Email step
- // -------------------------------------------------------------------------
return (
<div className="flex min-h-svh items-center justify-center">
diff --git a/packages/views/autopilots/components/autopilot-dialog.tsx b/packages/views/autopilots/components/autopilot-dialog.tsx
index 1c761da6a4..fb50366599 100644
--- a/packages/views/autopilots/components/autopilot-dialog.tsx
+++ b/packages/views/autopilots/components/autopilot-dialog.tsx
@@ -73,9 +73,7 @@ import { useT } from "../../i18n";
import { formatSchedulePartialFailureToast } from "./autopilot-dialog-toast";
import type { WebhookEventFilter } from "@multica/core/types";
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
export interface AutopilotInitial {
title: string;
@@ -106,9 +104,7 @@ export type AutopilotDialogProps =
canManageAccess: boolean;
};
-// ---------------------------------------------------------------------------
// Static schema-level data (not user-visible)
-// ---------------------------------------------------------------------------
const OUTPUT_MODE_KEYS: AutopilotExecutionMode[] = ["create_issue", "run_only"];
@@ -117,9 +113,7 @@ const OUTPUT_MODE_ICONS: Record<AutopilotExecutionMode, typeof FilePlus2> = {
run_only: Play,
};
-// ---------------------------------------------------------------------------
// Webhook event-filter dirty detection
-// ---------------------------------------------------------------------------
// serializeEventFilters returns a stable JSON string so the edit-mode dirty
// check can compare the current filters against the snapshot taken on open
@@ -131,9 +125,7 @@ function serializeEventFilters(filters: WebhookEventFilter[]): string {
);
}
-// ---------------------------------------------------------------------------
// AutopilotDialog
-// ---------------------------------------------------------------------------
export function AutopilotDialog(props: AutopilotDialogProps) {
const { t } = useT("autopilots");
@@ -737,9 +729,7 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
);
}
-// ---------------------------------------------------------------------------
// Right column sections
-// ---------------------------------------------------------------------------
function SectionLabel({
children,
@@ -1005,9 +995,7 @@ function ScheduleEmptyState({ onAdd }: { onAdd: () => void }) {
);
}
-// ---------------------------------------------------------------------------
// Trigger kind segmented control + webhook help section
-// ---------------------------------------------------------------------------
function TriggerKindSection({
kind,
@@ -1073,10 +1061,8 @@ function WebhookSection({
);
}
-// ---------------------------------------------------------------------------
// Post-create state for webhook autopilots: shows the freshly minted URL
// inline so the user can copy it without leaving the dialog.
-// ---------------------------------------------------------------------------
function WebhookCreatedPanel({
trigger,
diff --git a/packages/views/autopilots/components/autopilot-list-actions.tsx b/packages/views/autopilots/components/autopilot-list-actions.tsx
index 8de93be201..4823d134e2 100644
--- a/packages/views/autopilots/components/autopilot-list-actions.tsx
+++ b/packages/views/autopilots/components/autopilot-list-actions.tsx
@@ -36,9 +36,7 @@ import {
import { useT } from "../../i18n";
import { useIntentNavigate } from "../../navigation";
-// ---------------------------------------------------------------------------
// Delete dialog — single row (kebab) and batch share one implementation.
-// ---------------------------------------------------------------------------
export function DeleteAutopilotsDialog({
rows,
@@ -119,9 +117,7 @@ export function DeleteAutopilotsDialog({
);
}
-// ---------------------------------------------------------------------------
// Status helpers shared by kebab and batch toolbar.
-// ---------------------------------------------------------------------------
function useSetStatus() {
const updateAutopilot = useUpdateAutopilot();
@@ -137,12 +133,10 @@ function useSetStatus() {
};
}
-// ---------------------------------------------------------------------------
// Row kebab — the row is a plain `<div>` whose whole-row navigation is a mouse
// `onClick` (see `useRowLink`), not an ancestor `<a>`. The wrapper span stops
// click propagation so opening this menu never navigates the row — just
// stopPropagation, no preventDefault (same pattern as the skills list).
-// ---------------------------------------------------------------------------
export function AutopilotRowActions({ row }: { row: Autopilot }) {
const { t } = useT("autopilots");
@@ -221,9 +215,7 @@ export function AutopilotRowActions({ row }: { row: Autopilot }) {
);
}
-// ---------------------------------------------------------------------------
// Batch toolbar
-// ---------------------------------------------------------------------------
export function AutopilotBatchToolbar({
rows,
diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsx
index b4535b4b0a..bd173ef849 100644
--- a/packages/views/autopilots/components/autopilots-page.tsx
+++ b/packages/views/autopilots/components/autopilots-page.tsx
@@ -128,11 +128,9 @@ function columnTrackVars(
} as React.CSSProperties;
}
-// ---------------------------------------------------------------------------
// Templates for the empty state (unchanged from the previous page version).
// Prompts stay raw English because they're injected directly into the
// agent's task input.
-// ---------------------------------------------------------------------------
type TemplateId =
| "daily_news"
@@ -219,9 +217,7 @@ const TEMPLATES: AutopilotTemplate[] = [
},
];
-// ---------------------------------------------------------------------------
// Cells
-// ---------------------------------------------------------------------------
function CheckboxCell({
checked,
@@ -439,9 +435,7 @@ function CreatorCell({ autopilot }: { autopilot: Autopilot }) {
);
}
-// ---------------------------------------------------------------------------
// Header row
-// ---------------------------------------------------------------------------
function AutopilotListHeader({
sortField,
@@ -615,9 +609,7 @@ function LoadingSkeleton() {
);
}
-// ---------------------------------------------------------------------------
// Page
-// ---------------------------------------------------------------------------
export function AutopilotsPage() {
const navigation = useNavigation();
diff --git a/packages/views/chat/components/use-chat-draft-restore.ts b/packages/views/chat/components/use-chat-draft-restore.ts
index 2dec44362b..1e67de7578 100644
--- a/packages/views/chat/components/use-chat-draft-restore.ts
+++ b/packages/views/chat/components/use-chat-draft-restore.ts
@@ -25,71 +25,20 @@ export interface RestoreDraftRequest {
}
/**
- * Owns the durable draft-restore lifecycle for one composer (#5219). Shared by
- * the chat page controller and the floating chat window — the two entry points
- * must not drift, because the state machine below is the only thing standing
- * between a cancelled prompt and losing it.
+ * Owns draft restoration for the chat page and floating composer.
+ * Durable cancellation restores remain on the server until applied. Failed-send
+ * and synchronous-cancel restores have no server copy, so persist them per session
+ * until the composer confirms application. The shared request slot exposes only
+ * the visible session's next offer.
*
- * Two kinds of restore feed one composer, and they have different failure modes:
+ * Only visible composers participate. A nonempty draft defers the offer without
+ * consuming it. Record application in a persisted ledger before sending consume;
+ * retry consumption on later fetches and clear the ledger on server confirmation.
+ * This ordering prevents a lost response from offering an already-applied prompt.
*
- * - Durable (a deferred-cancellation row, #5219): the server holds the text, so
- * an offer that is never taken can simply be dropped and refetched.
- * - Server-less (a failed send, or a cancel that answered synchronously): the
- * send already cleared the persisted draft, so this hook's queue is the ONLY
- * copy of the user's text. It is therefore persisted per session
- * (pendingSendRestores) from the moment it is created until the composer
- * reports it applied — never parked in the shared slot, which is component
- * state and dies with an unmount.
- *
- * The single `restoreDraftRequest` slot is only a view onto whichever of those
- * the composer can act on RIGHT NOW: it never holds a request for a session
- * other than the one on screen, so a restore for a session the user may never
- * return to cannot starve the one they are looking at.
- *
- * The hand-off is at-most-once and lossless:
- *
- * - A restore is offered to the composer, which either applies it (empty draft)
- * or leaves it alone (the user has work in progress). A skipped restore stays
- * pending — ChatInput re-evaluates as the draft changes and applies it the
- * moment the draft is clear. It is never marked done, never consumed, and the
- * server row (or queue entry) survives.
- * - Only an applied restore is recorded — in a *persisted* ledger, before the
- * consume request goes out. A consume that is lost (offline, app closed, retries
- * exhausted) therefore cannot cause the prompt to be restored a second time
- * after the user has sent it; the ledger, not the server row, is what makes the
- * offer at-most-once.
- * - Any row that outlives its ledger entry is reconciled: the consume is fired
- * again on every fetch until the row is gone, and the ledger entry is dropped
- * only when the server confirms it.
- *
- * Ownership. The restore belongs to the *user*, not to a device: the endpoints
- * are creator-authorized, so every client of theirs sees the row until one
- * consumes it. `enabled` is what decides which composers may take it: a client
- * only claims a restore into a composer the user can actually see. The cost of
- * getting this wrong is not a duplicate draft — it is a silent theft, where a
- * background composer applies (and consumes) the prompt the user is waiting for
- * on the device in front of them, and the row is gone before they ever see it.
- * A hidden composer must therefore never take part.
- *
- * Two *visible* composers on the same session, however, may both adopt it. That
- * is a deliberate product decision, not an accident of the implementation:
- *
- * - What happens: both write the prompt into their own device-local draft. The
- * consume DELETE is idempotent, so the first one to reach the server takes the
- * row and the other's call is a no-op. Nothing is lost; the user sees the
- * restored prompt on both screens and could send it twice.
- * - Why we accept it: both composers being visible means the user is looking at
- * one of them. A restored draft is not a sent message — it sits in the input
- * until the user presses send — so the worst case is that they see their own
- * prompt on their other open device and dismiss it there.
- * - Why not fix it: eliminating it needs a server-side claim/lease keyed on
- * client identity, taken *before* the local draft is written. That inverts the
- * ordering this whole state machine is built on (apply first, then consume) and
- * reopens the hole it exists to close: a client that wins the claim and then
- * dies — offline, closed, crashed — has taken the row without ever putting the
- * prompt anywhere, and the text is gone for good. Trading a recoverable
- * duplicate for an unrecoverable loss is the wrong side of that bet, and a
- * lease with an expiry to bound the loss buys the duplicate right back.
+ * Two visible clients may restore the same prompt locally; consumption is
+ * idempotent. Apply before consume: claiming first could lose the only copy if
+ * the winning client closes before writing its draft.
*/
export function useChatDraftRestore(activeSessionId: string | null, enabled = true) {
const qc = useQueryClient();
diff --git a/packages/views/common/picker-keys.ts b/packages/views/common/picker-keys.ts
index 73ffbcf150..995b8c3fae 100644
--- a/packages/views/common/picker-keys.ts
+++ b/packages/views/common/picker-keys.ts
@@ -1,7 +1,5 @@
-// ---------------------------------------------------------------------------
// Picker key policy — one answer to "what moves the highlight" and "what
// accepts", shared by every list-with-a-highlight in the product.
-// ---------------------------------------------------------------------------
//
// Lives here rather than next to the editor's suggestion popups because the
// consumers are no longer only editor pickers: the issue detail's thread
diff --git a/packages/views/dashboard/utils.ts b/packages/views/dashboard/utils.ts
index fd209593af..efcc1221e3 100644
--- a/packages/views/dashboard/utils.ts
+++ b/packages/views/dashboard/utils.ts
@@ -31,7 +31,6 @@ import type {
FailureClassCounts,
} from "../runtimes/components/charts";
-// ---------------------------------------------------------------------------
// Dashboard data aggregations
//
// The workspace dashboard returns the same per-(date, model) and
@@ -41,7 +40,6 @@ import type {
// which carries a `provider` field) we replicate here with a tighter
// type — fewer optional fields, less conditional logic on the consumer
// side.
-// ---------------------------------------------------------------------------
// Mirrors `DailyCostStackData` in the runtimes utils, including its cache-read
// segment — the dashboard feeds the very same DailyCostChart, so a category
@@ -359,14 +357,12 @@ export function isSyntheticAgentRow(agentId: string): boolean {
return agentId === DELETED_AGENTS_ROW_ID || agentId === RESTRICTED_AGENTS_ROW_ID;
}
-// ---------------------------------------------------------------------------
// Weekly fold for run-time + tasks. Mirrors `aggregateByWeek` in
// `runtimes/utils.ts` which already covers cost / tokens — same calendar
// week semantics (Mon–Sun anchored at today-in-tz), same pre-zeroed buckets,
// same partial-week metadata. Workspace dashboard uses the user-chosen
// timezone here; the runtime page uses the runtime's IANA tz. Behaviour is
// identical apart from where the tz comes from.
-// ---------------------------------------------------------------------------
interface WeekShell {
weekStart: string;
@@ -525,7 +521,6 @@ export function formatDuration(seconds: number, lessThanMinuteLabel: string): st
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
}
-// ---------------------------------------------------------------------------
// Failure aggregations
//
// The two failure rollups ship every terminal task, with `failure_reason: ""`
@@ -539,7 +534,6 @@ export function formatDuration(seconds: number, lessThanMinuteLabel: string): st
// `@multica/core/dashboard`; the raw reason survives only in
// `aggregateFailureReasons`, which powers the detail rows under the class
// summary.
-// ---------------------------------------------------------------------------
function emptyClassCounts(): FailureClassCounts {
return Object.fromEntries(
diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsx
index 1595816ec0..4578b6419f 100644
--- a/packages/views/editor/attachment-preview-modal.tsx
+++ b/packages/views/editor/attachment-preview-modal.tsx
@@ -1,50 +1,13 @@
"use client";
/**
- * AttachmentPreviewModal — full-window viewer for an attachment.
+ * Shared full-window attachment viewer and standalone preview page.
+ * Media uses signed download URLs; text uses the authenticated content endpoint
+ * to avoid storage CORS and attachment-disposition restrictions.
*
- * The file gets the whole window (MUL-7642): no card, no max width. A fixed
- * near-black stage sits behind the content whatever the theme — a photo, a
- * PDF page and a white HTML document all read against it — and the chrome
- * over it (top bar, prev / next, messages on the stage) wears the dark token
- * set via a `dark` class on each chrome element. Documents that are read
- * rather than looked at (Markdown, text) render on a centered sheet that
- * keeps the app's own theme.
- *
- * Single viewer for every previewable kind. Handles 9 PreviewKinds:
- *
- * - image : <img> on the shared ZoomCanvas — fit on open, then wheel /
- * drag / pinch / double-click / keyboard zoom, same controls as
- * the Mermaid viewer.
- * - pdf : <iframe src={download_url}> — relies on Chromium's PDFium
- * plugin. On desktop, requires webPreferences.plugins=true
- * (see apps/desktop/src/main/index.ts).
- * - video : <video controls src={download_url}>
- * - audio : <audio controls src={download_url}>
- *
- * - markdown : fetch text via api.getAttachmentTextContent, render via
- * the existing ReadonlyContent (full mention/mermaid/katex
- * pipeline included).
- * - html : fetch text, hand to <iframe srcdoc={text}
- * sandbox="allow-scripts">. The iframe runs in an opaque
- * origin: scripts execute (chart libraries / vanilla SVG
- * JS work), but cookie / localStorage / parent access /
- * top-navigation / popups / forms stay blocked because
- * `allow-same-origin` is intentionally NOT included.
- * Laid out at a device width on demand, or shown as source.
- * - table : fetch text, parse CSV / TSV, sortable virtualized table.
- * - structured : fetch text, parse JSON / JSON Lines / YAML into a
- * collapsible tree, with the source one toggle away.
- * - text : fetch text, highlight with lowlight if the extension
- * maps to a known hljs language, with numbered lines and a
- * wrap toggle.
- *
- * The same top bar and stage also stand alone as the "open in new tab" page
- * (`AttachmentPreviewStandalone`), so a file looks the same in both.
- *
- * Media types load directly from the CloudFront signed `download_url`.
- * Text types go through `/api/attachments/{id}/content` to sidestep
- * CloudFront CORS (not configured) + Content-Disposition: attachment.
+ * HTML runs in a sandboxed opaque-origin iframe: allow scripts for interactive
+ * artifacts, but do not add allow-same-origin, navigation, popup, or form privileges.
+ * Desktop PDF previews require the Chromium PDF plugin to be enabled.
*/
import {
@@ -139,9 +102,7 @@ import {
type HtmlViewport,
} from "./html-viewport-frame";
-// ---------------------------------------------------------------------------
// Preview source — full attachment, or URL-only (media types only)
-// ---------------------------------------------------------------------------
//
// `full` carries the resolved Attachment record and supports every PreviewKind
// (text types require the attachment id to call /api/attachments/{id}/content).
@@ -229,9 +190,7 @@ function normalize(source: PreviewSource): PreviewState {
};
}
-// ---------------------------------------------------------------------------
// Public props
-// ---------------------------------------------------------------------------
/**
* Position of this preview inside a surface's image sequence (MUL-5752).
@@ -279,9 +238,7 @@ interface AttachmentPreviewModalProps {
onOpenOverview?: () => void;
}
-// ---------------------------------------------------------------------------
// Hook — local state + ready-to-mount modal JSX
-// ---------------------------------------------------------------------------
//
// Why no React context / provider: packages/views/ cannot mount a Context.Provider
// inside CoreProvider (in packages/core/), and threading a new provider through
@@ -339,9 +296,7 @@ export function useAttachmentPreview(): AttachmentPreviewHandle {
return useMemo(() => ({ open, tryOpen, modal }), [open, tryOpen, modal]);
}
-// ---------------------------------------------------------------------------
// Image swap without a blank frame
-// ---------------------------------------------------------------------------
// Returns the last image URL that finished decoding, holding the previous one
// on screen while the next downloads. Swapping `<img src>` (or remounting the
@@ -420,9 +375,7 @@ export function PreviewImagePrefetch({ source }: { source: PreviewSource }) {
return null;
}
-// ---------------------------------------------------------------------------
// Viewer — frame + dispatch
-// ---------------------------------------------------------------------------
// Desktop window chrome. The viewer covers the whole window, including the
// top bar's drag region, so it declares its own: the viewer is `no-drag`
@@ -639,9 +592,7 @@ export function AttachmentPreviewModal({
);
}
-// ---------------------------------------------------------------------------
// Panel — top bar + stage
-// ---------------------------------------------------------------------------
const KIND_ICONS: Record<PreviewKind, LucideIcon> = {
image: ImageIcon,
@@ -1126,9 +1077,7 @@ function PreviewPanel({
);
}
-// ---------------------------------------------------------------------------
// Chrome controls
-// ---------------------------------------------------------------------------
// Top-bar icon button. Sits inside the `dark` header, so the semantic tokens
// resolve to the dark set whatever the app theme is.
@@ -1250,9 +1199,7 @@ function SequenceButton({
);
}
-// ---------------------------------------------------------------------------
// Image — zoom canvas
-// ---------------------------------------------------------------------------
function ImagePreview({
state,
@@ -1330,9 +1277,7 @@ function ImagePreview({
);
}
-// ---------------------------------------------------------------------------
// Dispatch
-// ---------------------------------------------------------------------------
// What the top bar decided about how the file shows — see PreviewPanel.
interface StageView {
@@ -1565,9 +1510,7 @@ function DocumentSheet({
);
}
-// ---------------------------------------------------------------------------
// Text-backed preview — fetches body once, then hands to the render prop
-// ---------------------------------------------------------------------------
// React Query owns server state per the project convention; re-opening the
// same attachment hits the cache instead of re-fetching. Query is keyed on
@@ -1621,9 +1564,7 @@ function TextBackedPreview({
return <>{render(query.data.text)}</>;
}
-// ---------------------------------------------------------------------------
// Fallback — used for 413 / 415 / unknown kinds. Sits on the stage, so dark.
-// ---------------------------------------------------------------------------
function UnsupportedFallback({
message,
@@ -1649,9 +1590,7 @@ function UnsupportedFallback({
);
}
-// ---------------------------------------------------------------------------
// Standalone — the viewer's top bar and stage as a page of their own
-// ---------------------------------------------------------------------------
/**
* The "Open in new tab" destination: the same bar and stage as the viewer,
diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsx
index 6c7b321027..d7dba81103 100644
--- a/packages/views/editor/attachment.tsx
+++ b/packages/views/editor/attachment.tsx
@@ -53,9 +53,7 @@ import { AttachmentCard, AttachmentFileCard } from "./attachment-card";
import { canOpenPreview, getPreviewKind, type PreviewKind } from "./utils/preview";
import "./styles/attachment.css";
-// ---------------------------------------------------------------------------
// Public API
-// ---------------------------------------------------------------------------
export type AttachmentInput =
// Server response in hand — full record. Used by AttachmentList and any
@@ -206,63 +204,14 @@ function absolutizeMediaURL(rawUrl: string): string {
return `${baseUrl}${rawUrl}`;
}
-// pickInlineMediaURL returns the URL most likely to load successfully
-// inside a native <img>/<video>/<iframe> resource fetch — i.e. without
-// the calling client attaching an Authorization header.
+// pickInlineMediaURL chooses a URL usable by native media loads, which cannot
+// attach the API client's Authorization header. Signed download URLs are suitable
+// for rendering but must not replace durable Markdown references.
//
-// The metadata response carries three URL fields per attachment row,
-// each with a different lifetime / accessibility:
-//
-// - `record.download_url` — this-response click-time URL. In
-// CloudFront-signed mode this is the
-// signed redirect (works as a native img
-// src for the duration of the TTL); in
-// other modes it's the bare API endpoint
-// (`/api/attachments/<id>/download`) which
-// requires per-request auth and does NOT
-// load as a native img on a non-same-site
-// origin like Desktop's file://.
-// - `record.markdown_url` — the durable URL the server picked for
-// persistence (MUL-3192 / `buildMarkdownURL`):
-// public CDN passthrough when the storage is
-// public-readable, or `MULTICA_PUBLIC_URL +
-// /api/attachments/<id>/download` for
-// private-bucket modes. Aligned with the
-// server-side policy by construction, so it
-// beats `record.url` whenever both exist.
-// - `record.url` — raw storage URL. May be private (S3 /
-// CloudFront-signed, R2, MinIO) and unable
-// to load directly. Last-resort fallback
-// for legacy responses that omit
-// `markdown_url`.
-//
-// Order:
-//
-// 1. Signed `download_url` — when CloudFront has minted a signed
-// redirect for THIS response, use it; the TTL means the signed URL
-// beats `markdown_url` on first paint (no extra hop through the
-// API endpoint), and the renderer doesn't persist it so the TTL is
-// not a problem.
-// 2. Known CDN `record.url` — when `/api/config` exposes the same CDN
-// host as the attachment record, the browser can load the object
-// directly (public CDN, or CloudFront cookie mode). Prefer it over
-// an API-shaped `markdown_url` so the rendered `<img src>` and Copy
-// Link affordance expose the CDN URL while the persisted markdown
-// can remain the stable attachment endpoint. Skipped when the server
-// reports `cdn_signed` — in CloudFront signed-URL mode the same
-// domain serves PRIVATE content and a raw (unsigned) storage URL is
-// a guaranteed 403 (MUL-3254).
-// 3. Local disk `record.url` — self-host LocalStorage without
-// LOCAL_UPLOAD_BASE_URL stores a site-relative `/uploads/...` path.
-// It is the direct static object URL and is loadable once
-// `absolutizeMediaURL` prefixes apiBaseUrl in split-origin clients.
-// 4. `record.markdown_url` — the durable, server-policy-aligned URL.
-// Beats raw `record.url` because it never points at a private
-// bucket (must-fix 2 from MUL-3192 review), except for the explicit
-// site-relative local upload path above.
-// 5. `record.url` — legacy fallback for responses that omit
-// `markdown_url` (a backend old enough to predate MUL-3192).
-// 6. The input URL — when there's no record at all.
+// Use known public/CDN URLs directly only when cdn_signed is false; unsigned URLs
+// on a private CDN fail even when the domain matches. Local /uploads paths remain
+// valid after origin normalization. Otherwise prefer the server's markdown_url,
+// then legacy storage URLs, then the original input.
function pickInlineMediaURL(
record: AttachmentRecord,
fallback: string,
@@ -319,9 +268,7 @@ function hasExpiringSignatureQuery(q: URLSearchParams): boolean {
return false;
}
-// ---------------------------------------------------------------------------
// Dispatcher
-// ---------------------------------------------------------------------------
export function Attachment({
attachment,
@@ -467,9 +414,7 @@ export function Attachment({
);
}
-// ---------------------------------------------------------------------------
// ImageAttachmentView — inline image with hover toolbar
-// ---------------------------------------------------------------------------
//
// DOM and styling are intentionally a direct port of the original
// extensions/image-view.tsx <figure> structure. Shared visual styles live in
diff --git a/packages/views/editor/bubble-menu.tsx b/packages/views/editor/bubble-menu.tsx
index 203058b9f4..8375a5ecab 100644
--- a/packages/views/editor/bubble-menu.tsx
+++ b/packages/views/editor/bubble-menu.tsx
@@ -76,9 +76,7 @@ import {
MessageSquarePlus,
} from "lucide-react";
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
function shouldShowBubbleMenu(editor: Editor, hasSelectionAction = false): boolean {
if (!editor.isEditable) return false;
@@ -92,9 +90,7 @@ function shouldShowBubbleMenu(editor: Editor, hasSelectionAction = false): boole
return true;
}
-// ---------------------------------------------------------------------------
// Mark Toggle Button
-// ---------------------------------------------------------------------------
type InlineMark = "bold" | "italic" | "strike" | "code" | "highlight";
@@ -144,9 +140,7 @@ function MarkButton({
);
}
-// ---------------------------------------------------------------------------
// URL normalisation
-// ---------------------------------------------------------------------------
/** Protocols that can execute code in the browser — the only ones we block. */
const DANGEROUS_PROTOCOL_RE = /^(javascript|data|vbscript):/i;
@@ -174,9 +168,7 @@ function normalizeUrl(input: string): string {
return `https://${trimmed}`;
}
-// ---------------------------------------------------------------------------
// Link Edit Bar
-// ---------------------------------------------------------------------------
function LinkEditBar({
editor,
@@ -257,9 +249,7 @@ function LinkEditBar({
);
}
-// ---------------------------------------------------------------------------
// Heading Dropdown
-// ---------------------------------------------------------------------------
function HeadingDropdown({ editor, onOpenChange, activeLevel }: { editor: Editor; onOpenChange: (open: boolean) => void; activeLevel: number | undefined }) {
const { t } = useT("editor");
@@ -315,9 +305,7 @@ function HeadingDropdown({ editor, onOpenChange, activeLevel }: { editor: Editor
);
}
-// ---------------------------------------------------------------------------
// List Dropdown
-// ---------------------------------------------------------------------------
function ListDropdown({ editor, onOpenChange, isBullet, isOrdered, isTask }: { editor: Editor; onOpenChange: (open: boolean) => void; isBullet: boolean; isOrdered: boolean; isTask: boolean }) {
const { t } = useT("editor");
@@ -393,9 +381,7 @@ function ListDropdown({ editor, onOpenChange, isBullet, isOrdered, isTask }: { e
);
}
-// ---------------------------------------------------------------------------
// Create Sub-Issue Button
-// ---------------------------------------------------------------------------
/**
* Turns the current selection into a sub-issue of `parentIssueId` and replaces
@@ -488,9 +474,7 @@ function CreateSubIssueButton({
);
}
-// ---------------------------------------------------------------------------
// Main Bubble Menu — @floating-ui/dom + portal to body
-// ---------------------------------------------------------------------------
function EditorBubbleMenu({
editor,
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index cba4dcab28..e321e742ac 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -75,9 +75,7 @@ import { AttachmentDownloadProvider } from "./attachment-download-context";
import "katex/dist/katex.min.css";
import "./styles/index.css";
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
/** Canonical comparison form for a markdown string: drop the blank lines a
* block leaves behind at either end, so both sides of a dirty check compare
@@ -115,9 +113,7 @@ function hasUploadingNode(editor: Editor): boolean {
return found;
}
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
interface ContentEditorBaseProps {
/**
@@ -352,9 +348,7 @@ interface ContentEditorRef {
adoptContent: (markdown: string) => void;
}
-// ---------------------------------------------------------------------------
// Component
-// ---------------------------------------------------------------------------
const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
function ContentEditor(
diff --git a/packages/views/editor/extensions/file-card.tsx b/packages/views/editor/extensions/file-card.tsx
index 292f2d11df..e0b28dec98 100644
--- a/packages/views/editor/extensions/file-card.tsx
+++ b/packages/views/editor/extensions/file-card.tsx
@@ -29,9 +29,7 @@ const FILE_CARD_MARKDOWN_RE = new RegExp(
);
-// ---------------------------------------------------------------------------
// React NodeView — thin wrapper, all rendering lives in <Attachment>
-// ---------------------------------------------------------------------------
export function FileCardView({ node, editor, deleteNode }: NodeViewProps) {
const href = (node.attrs.href as string) || "";
@@ -52,9 +50,7 @@ export function FileCardView({ node, editor, deleteNode }: NodeViewProps) {
);
}
-// ---------------------------------------------------------------------------
// Tiptap Node Extension
-// ---------------------------------------------------------------------------
export const FileCardExtension = Node.create({
name: "fileCard",
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index 95618b2125..d62f2da532 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -66,9 +66,7 @@ import {
import { isTriggerArmedAt } from "./suggestion-trigger-arming";
import { blockedReasonLabel } from "../../issues/blocked-trigger-copy";
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
export interface MentionItem {
id: string;
@@ -106,9 +104,7 @@ export interface MentionListRef {
onKeyDown: (props: { event: KeyboardEvent }) => boolean;
}
-// ---------------------------------------------------------------------------
// Group items by section
-// ---------------------------------------------------------------------------
interface MentionGroup {
label: string;
@@ -150,9 +146,7 @@ function groupItems(items: MentionItem[], query: string): MentionGroup[] {
return groups;
}
-// ---------------------------------------------------------------------------
// MentionList — the popup rendered inside the editor
-// ---------------------------------------------------------------------------
const MAX_ITEMS = 20;
const SERVER_ISSUE_SEARCH_LIMIT = 20;
@@ -531,9 +525,7 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(
},
);
-// ---------------------------------------------------------------------------
// MentionRow — single item in the list
-// ---------------------------------------------------------------------------
function MentionRow({
item,
@@ -674,9 +666,7 @@ function MentionRow({
);
}
-// ---------------------------------------------------------------------------
// Suggestion config factory
-// ---------------------------------------------------------------------------
function issueToMention(
i: Pick<Issue, "id" | "identifier" | "title" | "status"> & Partial<Pick<Issue, "status_category">>,
diff --git a/packages/views/editor/extensions/slash-command-suggestion.tsx b/packages/views/editor/extensions/slash-command-suggestion.tsx
index 8c41c4d523..02093458a5 100644
--- a/packages/views/editor/extensions/slash-command-suggestion.tsx
+++ b/packages/views/editor/extensions/slash-command-suggestion.tsx
@@ -272,9 +272,7 @@ export function createSlashCommandSuggestion(qc: QueryClient): Omit<
};
}
-// ---------------------------------------------------------------------------
// Built-in command menu (issue comments)
-// ---------------------------------------------------------------------------
/**
* Built-in slash commands offered in the issue comment composer. Unlike the
diff --git a/packages/views/editor/link-hover-card.tsx b/packages/views/editor/link-hover-card.tsx
index 2099729555..4a85f1cb2e 100644
--- a/packages/views/editor/link-hover-card.tsx
+++ b/packages/views/editor/link-hover-card.tsx
@@ -34,9 +34,7 @@ function truncateUrl(url: string, max = 48): string {
}
}
-// ---------------------------------------------------------------------------
// Hook — manages hover state with enter/leave delays
-// ---------------------------------------------------------------------------
const SHOW_DELAY = 300;
const HIDE_DELAY = 150;
@@ -123,9 +121,7 @@ function useLinkHover(containerRef: React.RefObject<HTMLElement | null>, disable
return { ...state, cardRef, onCardEnter, onCardLeave };
}
-// ---------------------------------------------------------------------------
// Component
-// ---------------------------------------------------------------------------
function LinkHoverCard({
visible,
diff --git a/packages/views/editor/title-editor.tsx b/packages/views/editor/title-editor.tsx
index bdb1fca31b..5b20b8a417 100644
--- a/packages/views/editor/title-editor.tsx
+++ b/packages/views/editor/title-editor.tsx
@@ -17,9 +17,7 @@ import { useT } from "../i18n";
import { createSubmitShortcutExtension } from "./extensions/submit-shortcut";
import "./title-editor.css";
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
interface TitleEditorProps {
defaultValue?: string;
@@ -61,17 +59,13 @@ interface TitleEditorRef {
focusAtCoords: (coords: { x: number; y: number }) => void;
}
-// ---------------------------------------------------------------------------
// Single-paragraph document — prevents Enter from creating new lines
-// ---------------------------------------------------------------------------
const SingleLineDocument = Document.extend({
content: "paragraph",
});
-// ---------------------------------------------------------------------------
// Keyboard shortcuts: Enter → submit, Escape → blur
-// ---------------------------------------------------------------------------
/**
* Whether `onSubmitShortcut` may fire for the configured `send` chord.
@@ -112,9 +106,7 @@ function createTitleKeymap(opts: {
});
}
-// ---------------------------------------------------------------------------
// Component
-// ---------------------------------------------------------------------------
const TitleEditor = forwardRef<TitleEditorRef, TitleEditorProps>(
function TitleEditor(
diff --git a/packages/views/issues/blocked-trigger-copy.ts b/packages/views/issues/blocked-trigger-copy.ts
index 88c6562b69..7ae3451f44 100644
--- a/packages/views/issues/blocked-trigger-copy.ts
+++ b/packages/views/issues/blocked-trigger-copy.ts
@@ -1,39 +1,12 @@
import type { useT } from "../i18n";
-// Localized copy for a blocked @agent / @squad trigger outcome (MUL-4525 §2),
-// shared by the composer preview chip and the post-send toast so both name the
-// same reason the same way. `reason_code` is the enumeration-safe wire code; the
-// label it maps to never reveals the target's identity — the caller supplies the
-// name it already has from the user's own mention markup.
+// Shared blocked-trigger labels for preview and post-send feedback.
+// Do not infer more than reason_code guarantees: invocation_not_allowed covers
+// both an inaccessible target and one that does not resolve. Labels disclose no
+// target identity beyond the caller's existing mention markup.
//
-// A label must not assert a cause the code does not carry. `invocation_not_allowed`
-// is deliberately ambiguous server-side (see dispatch/reason.go): it covers BOTH
-// "you may not invoke this target" and "this id resolved to nothing here". Copy
-// that blamed permission alone sent people to audit agent visibility settings over
-// what was really a mistyped mention uuid (MUL-5548), so both labels name the two
-// possibilities instead.
-//
-// `agent_runtime_required` and `runtime_offline` are kept apart for the same
-// reason (MUL-5559): an unbound agent has no machine to reconnect, so "runtime
-// offline" copy sends the user looking for a computer that does not exist. The
-// fix it needs is binding the agent to a runtime.
-//
-// `runtime_unusable` is the third member of that family (MUL-6164): the machine
-// IS reachable and its agent CLI cannot be executed there, so "offline" copy
-// sends the user to reconnect something that is already connected. The fix is a
-// reinstall on that machine, and the system comment the server leaves on the
-// issue carries the exact command.
-//
-// `runtime_access_denied` is another member of that family (PUCK-89): the
-// target is permitted but its agent owner cannot execute it on the selected
-// private runtime. No retry helps — the fix is making the runtime public or
-// rebinding/copying the agent to a runtime its owner can use.
-//
-// `runtime_profile_missing` is split from `runtime_unusable`
-// on the same rule: the CLI there runs perfectly and is missing a runtime
-// profile (DSH's `multica` profile, which supplies the protocol Multica
-// drives). "Reinstall the CLI" copy sends the user to re-run an install that
-// was never broken; the fix is installing the profile.
+// Keep remedies distinct for an unbound agent, an offline runtime, an unusable CLI,
+// denied runtime access, and a missing runtime profile.
type IssuesT = ReturnType<typeof useT<"issues">>["t"];
// Full sentence — for tooltips and other surfaces with room to explain.
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 88084f76f9..4ab97dea99 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -104,9 +104,7 @@ function StickyHeaderShell({
);
}
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
interface CommentCardProps {
issueId: string;
@@ -160,9 +158,7 @@ interface CommentCardProps {
highlightedCommentId?: string | null;
}
-// ---------------------------------------------------------------------------
// Shared delete confirmation dialog
-// ---------------------------------------------------------------------------
function DeleteCommentDialog({
open,
@@ -203,9 +199,7 @@ function DeleteCommentDialog({
);
}
-// ---------------------------------------------------------------------------
// Standalone attachment list — renders attachments not already in the markdown
-// ---------------------------------------------------------------------------
export function AttachmentList({
attachments,
@@ -356,9 +350,7 @@ function TaskCommentRetryButton({
);
}
-// ---------------------------------------------------------------------------
// Shared edit-attachment state hook
-// ---------------------------------------------------------------------------
const NEVER_STEER = () => false;
@@ -625,9 +617,7 @@ function CommentRevisionConflict({
);
}
-// ---------------------------------------------------------------------------
// Single comment row (used for both parent and replies within the same Card)
-// ---------------------------------------------------------------------------
function CommentRow({
runHeader,
@@ -999,9 +989,7 @@ export function AgentRunComment({ run, standalone = false, commentProps, enterin
);
}
-// ---------------------------------------------------------------------------
// CommentCard — One Card per thread (parent + all replies flat inside)
-// ---------------------------------------------------------------------------
// A quick action posts an ordinary comment and is rendered as one (MUL-5465).
// It briefly had a collapsed one-line header that expanded to reveal the
diff --git a/packages/views/issues/components/deliverables/deliverable-details.tsx b/packages/views/issues/components/deliverables/deliverable-details.tsx
index cf3f9c88f8..9b2e679b8e 100644
--- a/packages/views/issues/components/deliverables/deliverable-details.tsx
+++ b/packages/views/issues/components/deliverables/deliverable-details.tsx
@@ -100,9 +100,7 @@ export function useDeliverableDetails({
);
}
-// ---------------------------------------------------------------------------
// Version switcher
-// ---------------------------------------------------------------------------
function VersionSwitcher({
file,
@@ -161,9 +159,7 @@ function VersionSwitcher({
);
}
-// ---------------------------------------------------------------------------
// Info panel
-// ---------------------------------------------------------------------------
function DeliverableInfo({
item,
diff --git a/packages/views/issues/components/gantt-view.tsx b/packages/views/issues/components/gantt-view.tsx
index a0f74b86b7..d56620871e 100644
--- a/packages/views/issues/components/gantt-view.tsx
+++ b/packages/views/issues/components/gantt-view.tsx
@@ -33,10 +33,8 @@ import { IssueActionsContextMenu } from "../actions";
import { sortIssues } from "../utils/sort";
import { useLocale, useT } from "../../i18n";
-// ---------------------------------------------------------------------------
// Date utilities — everything is UTC-day-aligned so a `due_date` ISO string
// produced anywhere maps to exactly one column on the axis.
-// ---------------------------------------------------------------------------
const MS_PER_DAY = 24 * 60 * 60 * 1000;
@@ -72,9 +70,7 @@ function isWeekStartUTC(d: Date): boolean {
return d.getUTCDay() === 1; // Monday
}
-// ---------------------------------------------------------------------------
// Geometry
-// ---------------------------------------------------------------------------
const ROW_HEIGHT = 36;
const HEADER_HEIGHT = 56;
@@ -114,9 +110,7 @@ function computeRange(issues: Issue[], today: Date, zoom: GanttZoom): Range {
};
}
-// ---------------------------------------------------------------------------
// Top axis — sticky on vertical scroll. Renders month + day/week ticks.
-// ---------------------------------------------------------------------------
function GanttAxis({
range,
@@ -239,10 +233,8 @@ function GanttAxis({
);
}
-// ---------------------------------------------------------------------------
// Background layer — weekend shading, week/month gridlines, today line.
// Rendered once across the full timeline track height behind all bars.
-// ---------------------------------------------------------------------------
function BackgroundLayer({
range,
@@ -294,9 +286,7 @@ function BackgroundLayer({
);
}
-// ---------------------------------------------------------------------------
// Bar color by status (uses semantic Tailwind tokens, not hardcoded colors).
-// ---------------------------------------------------------------------------
// Keyed by CATEGORY, not by status key: an issue on a custom status draws in
// the color of the category it behaves as. Keying this by IssueStatus made the
@@ -309,9 +299,7 @@ const STATUS_BAR_BG: Record<IssueStatusCategory, string> = {
closed: "bg-muted-foreground/40",
};
-// ---------------------------------------------------------------------------
// One row — left label cell + right timeline track with absolute bar.
-// ---------------------------------------------------------------------------
function ScheduledRow({
issue,
@@ -464,9 +452,7 @@ function ScheduledRow({
);
}
-// ---------------------------------------------------------------------------
// GanttView — public component
-// ---------------------------------------------------------------------------
export function GanttView({ issues }: { issues: Issue[] }) {
const { t } = useT("issues");
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 0dd3b1caa5..6ebdb1dace 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -475,17 +475,13 @@ function ActivityText({ entry, text }: { entry: TimelineEntry; text: string }) {
);
}
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
// Stable reference for threads with no replies. Inline `[]` would create a
// new array on every render and bust React.memo on CommentCard / ResolvedThreadBar.
const EMPTY_REPLIES: TimelineEntry[] = [];
-// ---------------------------------------------------------------------------
// Sidebar progressive disclosure
-// ---------------------------------------------------------------------------
//
// Properties shown in the sidebar split into two groups:
// - core: always rendered (status / assignee / project)
@@ -821,9 +817,7 @@ function ActivityBlock({
);
}
-// ---------------------------------------------------------------------------
// SubIssueRow — sub-issue list item with inline status & assignee editing
-// ---------------------------------------------------------------------------
function SubIssueRow({
child,
@@ -1040,9 +1034,7 @@ function SubIssueRow({
);
}
-// ---------------------------------------------------------------------------
// SubIssueDisplayPopover — per-user "which properties do rows show" control
-// ---------------------------------------------------------------------------
// Reuses the main Display panel's `card_*` labels — the property names are
// identical, so the sub-issues control needs no locale keys of its own.
@@ -1129,9 +1121,7 @@ function SubIssueDisplayPopover({
);
}
-// ---------------------------------------------------------------------------
// Props
-// ---------------------------------------------------------------------------
interface IssueDetailProps {
issueId: string;
@@ -1169,9 +1159,7 @@ interface IssueDetailProps {
trailingActions?: ReactNode;
}
-// ---------------------------------------------------------------------------
// Not found
-// ---------------------------------------------------------------------------
/**
* Exported so `IssueDetailRoute` can render it for an identifier that names no
@@ -1220,9 +1208,7 @@ export function IssueNotFound({
);
}
-// ---------------------------------------------------------------------------
// Loading skeleton
-// ---------------------------------------------------------------------------
/**
* Exported so `IssueDetailRoute` can show the identical frame while it resolves
@@ -1297,9 +1283,7 @@ export function IssueDetailSkeleton({
);
}
-// ---------------------------------------------------------------------------
// IssueDetail
-// ---------------------------------------------------------------------------
export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, leadingAction, variant = "page", trailingActions }: IssueDetailProps) {
const isPeek = variant === "peek";
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index 3da45a9ebc..f7123e1f10 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -133,9 +133,7 @@ type LocalDateRange = {
to?: Date;
};
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
function getActiveFilterCount(
state: {
@@ -305,15 +303,11 @@ function useIssueCounts(
}, [allIssues, serverFacets]);
}
-// ---------------------------------------------------------------------------
// Scope config
-// ---------------------------------------------------------------------------
const SCOPE_VALUES: IssuesScope[] = ["all", "members", "agents"];
-// ---------------------------------------------------------------------------
// Actor sub-menu content (shared between Assignee and Creator)
-// ---------------------------------------------------------------------------
function ActorSubContent({
counts,
@@ -498,9 +492,7 @@ function ActorSubContent({
);
}
-// ---------------------------------------------------------------------------
// Project sub-menu content
-// ---------------------------------------------------------------------------
function ProjectSubContent({
counts,
@@ -599,9 +591,7 @@ function ProjectSubContent({
);
}
-// ---------------------------------------------------------------------------
// Project status sub-menu content
-// ---------------------------------------------------------------------------
function ProjectStatusSubContent({
selected,
@@ -641,9 +631,7 @@ function ProjectStatusSubContent({
);
}
-// ---------------------------------------------------------------------------
// Label sub-menu content
-// ---------------------------------------------------------------------------
function LabelSubContent({
counts,
@@ -1040,9 +1028,7 @@ function PropertyFilterOptions({
);
}
-// ---------------------------------------------------------------------------
// Date sub-menu content
-// ---------------------------------------------------------------------------
function DateSubContent({
value,
@@ -1164,9 +1150,7 @@ function DateSubContent({
);
}
-// ---------------------------------------------------------------------------
// ViewRefreshIndicator
-// ---------------------------------------------------------------------------
/**
* Neutral "view is revalidating" slot for the header controls cluster.
@@ -1191,9 +1175,7 @@ export function ViewRefreshIndicator({ active }: { active: boolean }) {
);
}
-// ---------------------------------------------------------------------------
// IssuesHeader
-// ---------------------------------------------------------------------------
export function IssuesHeader({
scopedIssues,
diff --git a/packages/views/issues/components/pickers/property-picker.tsx b/packages/views/issues/components/pickers/property-picker.tsx
index aa268c620e..fe4521c3ac 100644
--- a/packages/views/issues/components/pickers/property-picker.tsx
+++ b/packages/views/issues/components/pickers/property-picker.tsx
@@ -35,9 +35,7 @@ const isEmptyItem = (el: HTMLButtonElement | undefined) =>
export const PICKER_TRIGGER_CLASS =
"flex items-center gap-1.5 cursor-pointer rounded-xs px-1 -mx-1 hover:bg-accent/30 transition-colors overflow-hidden";
-// ---------------------------------------------------------------------------
// PropertyPicker — generic Popover shell with optional search
-// ---------------------------------------------------------------------------
export function PropertyPicker({
open,
@@ -225,9 +223,7 @@ export function PropertyPicker({
);
}
-// ---------------------------------------------------------------------------
// PickerItem — single selectable row
-// ---------------------------------------------------------------------------
export function PickerItem({
selected,
@@ -293,9 +289,7 @@ export function PickerItem({
);
}
-// ---------------------------------------------------------------------------
// PickerSection — group header
-// ---------------------------------------------------------------------------
export function PickerSection({
label,
@@ -314,9 +308,7 @@ export function PickerSection({
);
}
-// ---------------------------------------------------------------------------
// PickerEmpty — no results state
-// ---------------------------------------------------------------------------
export function PickerEmpty() {
const { t } = useT("issues");
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index ae07aed8f8..20292cf8e4 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -22,9 +22,7 @@ import { useStopRunsBeforeSend } from "./use-stop-runs-before-send";
import { useCommentUploads } from "./use-comment-uploads";
import { useQuickActionMenu } from "../hooks/use-quick-action-menu";
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
interface ReplyInputProps {
issueId: string;
@@ -51,9 +49,7 @@ interface ReplyInputProps {
const NEVER_STEER_BY_DEFAULT = () => false;
-// ---------------------------------------------------------------------------
// ReplyInput
-// ---------------------------------------------------------------------------
function ReplyInput({
issueId,
diff --git a/packages/views/issues/components/status-icon.tsx b/packages/views/issues/components/status-icon.tsx
index fb2e684f90..d27ab5b6b9 100644
--- a/packages/views/issues/components/status-icon.tsx
+++ b/packages/views/issues/components/status-icon.tsx
@@ -8,18 +8,14 @@ import type {
} from "@multica/core/types";
import { STATUS_CONFIG } from "@multica/core/issues/config";
-// ---------------------------------------------------------------------------
// Geometry constants (viewBox 0 0 14 14, center 7,7)
-// ---------------------------------------------------------------------------
const CX = 7;
const CY = 7;
const OUTER_R = 6;
const FILL_R = 3.5;
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
/** Build a pie-wedge SVG path from 12 o'clock, clockwise */
function piePath(cx: number, cy: number, r: number, progress: number): string {
@@ -30,9 +26,7 @@ function piePath(cx: number, cy: number, r: number, progress: number): string {
return `M${cx},${cy} L${cx},${cy - r} A${r},${r} 0 ${largeArc},1 ${endX},${endY} Z`;
}
-// ---------------------------------------------------------------------------
// Base component — dashed outer ring + pie fill + optional center icon
-// ---------------------------------------------------------------------------
function ProgressCircle({
progress,
@@ -65,9 +59,7 @@ function ProgressCircle({
);
}
-// ---------------------------------------------------------------------------
// Per-status renderers
-// ---------------------------------------------------------------------------
/** 16 small dots arranged in a ring */
function BacklogIcon() {
@@ -146,9 +138,7 @@ function CancelledIcon() {
);
}
-// ---------------------------------------------------------------------------
// Renderer map
-// ---------------------------------------------------------------------------
const STATUS_RENDERERS: Record<BuiltInIssueStatus, () => React.ReactNode> = {
backlog: BacklogIcon,
@@ -187,9 +177,7 @@ const BUILT_IN_ICON_COLOR: Record<BuiltInIssueStatus, string> = {
cancelled: "text-muted-foreground",
};
-// ---------------------------------------------------------------------------
// Public component
-// ---------------------------------------------------------------------------
export function StatusIcon({
status,
diff --git a/packages/views/issues/components/thread-minimap.tsx b/packages/views/issues/components/thread-minimap.tsx
index a41f4797db..1b52b7da0e 100644
--- a/packages/views/issues/components/thread-minimap.tsx
+++ b/packages/views/issues/components/thread-minimap.tsx
@@ -8,7 +8,6 @@ import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import { useT, useTimeAgo } from "../../i18n";
-// ---------------------------------------------------------------------------
// ThreadMinimap — quick-jump rail with a complete comment outline.
// Every thread is a long tick and every reply a short tick beneath it, so the
// rail doubles as a map of where the conversation runs long. Hovering or
@@ -31,9 +30,7 @@ const PREVIEW_OPEN_DELAY_MS = 150;
/** Grace period on leave — long enough to travel from rail onto the card. */
const PREVIEW_CLOSE_DELAY_MS = 150;
-// ---------------------------------------------------------------------------
// Hover wave — Dock-style proximity magnification
-// ---------------------------------------------------------------------------
//
// While the pointer travels along the rail, every tick scales with a cosine
// falloff of its distance to the cursor, so the hovered tick peaks and its
@@ -152,9 +149,7 @@ function flattenThreads(threads: readonly ThreadMinimapThread[]): MinimapItem[]
return items;
}
-// ---------------------------------------------------------------------------
// useVisibleCommentIds — "which rail comments are on screen right now"
-// ---------------------------------------------------------------------------
//
// Which ticked comments intersect the scroll viewport, so the rail can darken
// their ticks. A thread root's anchor wraps its whole card, so a thread tick
diff --git a/packages/views/issues/components/use-board-drag-pan.ts b/packages/views/issues/components/use-board-drag-pan.ts
index b817688b41..303380c869 100644
--- a/packages/views/issues/components/use-board-drag-pan.ts
+++ b/packages/views/issues/components/use-board-drag-pan.ts
@@ -34,51 +34,15 @@ const INTERACTIVE_SELECTOR = [
].join(", ");
/**
- * Blank-area left-drag panning for a horizontally scrollable board (#6700,
- * Trello/Linear pattern): pressing the LEFT mouse button on empty board
- * background and dragging pans the board horizontally — the page follows the
- * cursor. Dragging a card still moves the card (dnd-kit); this hook stays out
- * of the way because it never activates when the gesture starts on a card or
- * any interactive element. Touch and pen input are intentionally left to the
- * browser; this PR only owns the left-mouse-button gesture.
+ * Returns left-mouse drag handlers for horizontal panning of empty board space.
+ * Exclude interactive elements and data-board-card roots so panning cannot compete
+ * with dnd-kit card dragging. Keep that attribute on every draggable card root.
*
- * ### dnd-kit coexistence invariant (P2-5 — do not break)
- * These pointer handlers sit on the SAME scroll container that hosts the
- * `DndContext`. They are mutually exclusive with card dragging purely by
- * ORIGIN: `onPointerDown` bails whenever the press starts inside
- * `INTERACTIVE_SELECTOR`, and every draggable card root carries
- * `data-board-card` (see `DraggableBoardCard` in `board-card.tsx`). If a future
- * change removes that attribute from the card root, or nests the pan container
- * below the card listeners, card drags and board pans will start fighting.
- * Keep `data-board-card` on the card root and keep this exclusion in sync.
- *
- * ### Design notes
- * - Pointer Events + pointer capture claimed on `pointerdown` (not deferred
- * to first move), so every `pointermove` keeps dispatching to the container
- * even after the pointer leaves it or the window. Deferring capture was the
- * "scrolls back when the pointer exits the board" bug: without an early
- * capture the browser ran a native selection-drag whose auto-scroll fought
- * `scrollLeft`, and re-entering the container produced a jumped delta.
- * - Text selection is suppressed from `pointerdown` (P1-3): `user-select:
- * none` on the container plus `selectstart` / `dragstart` preventers, then
- * restored in `reset`. Doing it on down (not after the 5px threshold) closes
- * the window where Safari/Firefox would start a selection whose auto-scroll
- * yanks the board back. Because selection can no longer begin, `pointermove`
- * no longer needs a per-frame `removeAllRanges` (P3-7).
- * - Mouse left button only (`event.pointerType === "mouse"` and
- * `event.button === 0`). Touch/pen are untouched so native touch scrolling
- * and pinch zoom stay browser-owned.
- * - Activation is gated on a ~5px move so a plain click is not swallowed.
- * - Panning uses the captured pointer's `clientX` deltas — never a hover
- * target or `elementFromPoint` — so leaving the container can't lose track.
- * - Horizontal axis only: `deltaY` is never read, `scrollTop` never written.
- * `scrollLeft` is clamped to `[0, scrollWidth - clientWidth]` so reaching an
- * edge stops cleanly instead of bouncing back.
- * - Cleanup on `pointerup` / `pointercancel` / `lostpointercapture` and
- * window `blur`, plus a `buttons` check on move, so a lost release cannot
- * leave the board stuck in a panning state.
- *
- * Returns props to spread onto the scroll container.
+ * Capture the pointer and suppress native selection on pointerdown; waiting for
+ * the movement threshold lets native selection autoscroll fight scrollLeft.
+ * The threshold still distinguishes a click from a pan. Use captured clientX
+ * deltas and clamp horizontal bounds; leave touch and pen scrolling to the browser.
+ * Reset on release, cancellation, lost capture, blur, or a missing pressed button.
*/
export function useBoardDragPan<T extends HTMLElement>() {
const ref = useRef<T | null>(null);
diff --git a/packages/views/issues/hooks/use-in-page-find.ts b/packages/views/issues/hooks/use-in-page-find.ts
index 31d0f48727..429f858ec0 100644
--- a/packages/views/issues/hooks/use-in-page-find.ts
+++ b/packages/views/issues/hooks/use-in-page-find.ts
@@ -4,7 +4,6 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { getShortcut, shortcutMatchesEvent } from "@multica/core/shortcuts";
import { isImeComposing } from "@multica/core/utils";
-// ---------------------------------------------------------------------------
// In-page find (Cmd/Ctrl+F) for the issue detail page.
//
// The comment timeline is virtualized, so native browser find only sees the
@@ -14,7 +13,6 @@ import { isImeComposing } from "@multica/core/utils";
// CSS Custom Highlight API — ranges only, never DOM mutation, so it works
// over React-rendered markdown AND the contenteditable title/description
// editors without fighting ProseMirror.
-// ---------------------------------------------------------------------------
const HIGHLIGHT_NAME = "multica-find";
const ACTIVE_HIGHLIGHT_NAME = "multica-find-active";
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index 7260bd1628..663e609b95 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -98,13 +98,11 @@ import { useT } from "../i18n";
import { SourceContextPreviewCard, useSourceContextFailureMessage } from "./source-context-preview";
import { useIssueLimitUpgradePrompt } from "./use-issue-limit-upgrade-prompt";
-// ---------------------------------------------------------------------------
// ManualCreatePanel — manual-mode body of the create-issue dialog. Renders
// DialogContent + everything inside; the surrounding `<Dialog>` is owned by
// CreateIssueDialog so mode switching swaps only the inner panel without
// remounting the Dialog Root (no overlay flash). `onSwitchMode` flips the
// shell's local mode state.
-// ---------------------------------------------------------------------------
// CreateRunHint is the create modal's passive pre-trigger label (MUL-3375 §4):
// whether saving will start a run, driven by the unified backend predicate
diff --git a/packages/views/modals/create-squad.tsx b/packages/views/modals/create-squad.tsx
index 1cad0cf40d..1da53ef1de 100644
--- a/packages/views/modals/create-squad.tsx
+++ b/packages/views/modals/create-squad.tsx
@@ -238,11 +238,9 @@ export function CreateSquadModal({ onClose }: { onClose: () => void }) {
);
}
-// ---------------------------------------------------------------------------
// LeaderPicker — single-select agent picker, grouped "My Agents" first then
// "Workspace Agents". Empty workspaces render a disabled trigger that points
// the user at agent creation.
-// ---------------------------------------------------------------------------
function LeaderPicker({
agents,
currentUserId,
@@ -381,12 +379,10 @@ function LeaderPicker({
);
}
-// ---------------------------------------------------------------------------
// AdditionalMembersPicker — multi-select agents + workspace members. The
// trigger shows up to 3 chips inline; the rest collapse into "+N". The popup
// stays open while the user toggles selections so they can pick multiple
// without re-opening it.
-// ---------------------------------------------------------------------------
function AdditionalMembersPicker({
agents,
members,
diff --git a/packages/views/navigation/use-back-or-replace.ts b/packages/views/navigation/use-back-or-replace.ts
index 81ec056f55..da3533a013 100644
--- a/packages/views/navigation/use-back-or-replace.ts
+++ b/packages/views/navigation/use-back-or-replace.ts
@@ -4,30 +4,9 @@ import { useCallback } from "react";
import { useNavigation } from "./context";
/**
- * Leave a page whose subject no longer exists, returning the user to wherever
- * they came from.
- *
- * Deleting an issue from its detail page is the canonical case: the user may
- * have opened it from My Issues, a project's list, a search result or a pin,
- * and every one of those is a better destination than a hardcoded workspace
- * list. Going back is the only thing that knows which — no caller has to
- * thread a "source view" through the URL or a store.
- *
- * `fallback` covers the case where there is nothing to go back to: a shared
- * link opened cold, a new tab, a pasted URL. Stepping back from those would
- * leave Multica entirely, so we navigate to `fallback` instead.
- *
- * It also covers every platform that cannot answer the question — the desktop
- * issue window, test stubs, and browsers with no Navigation API. That branch
- * is the behaviour those surfaces had before this hook existed, so a platform
- * going quiet costs the user a better destination and nothing more. Only ever
- * answer `canGoBack` from something that knows; a hopeful guess here is what
- * puts a user outside the app.
- *
- * Never `push`: the page we are leaving is dead, so its URL must not be left
- * on the back stack for the back button to land on a 404. Stepping back still
- * leaves it ahead of us in forward history — that is the browser's own
- * contract, and reachable only by an explicit Forward.
+ * Leave a deleted subject through known in-app history, or replace with fallback
+ * when history is unavailable or cannot be proven safe. Never guess canGoBack or
+ * use push: the dead page must not remain as a new back-stack destination.
*/
export function useBackOrReplace(): (fallback: string) => void {
const { back, replace, canGoBack } = useNavigation();
diff --git a/packages/views/navigation/use-row-link.ts b/packages/views/navigation/use-row-link.ts
index e38f6a2745..75f2a57c3e 100644
--- a/packages/views/navigation/use-row-link.ts
+++ b/packages/views/navigation/use-row-link.ts
@@ -5,44 +5,13 @@ import { resolveClickIntent, type LinkClickIntent } from "./click-intent";
import { useNavigation } from "./context";
/**
- * Whole-row click navigation for list rows.
+ * Whole-row navigation uses a div, so useRowLink resolves modifier and middle
+ * clicks explicitly through the desktop adapter or a shareable browser URL.
+ * Call the hook once per list and use its returned row-props factory.
*
- * Call once at the top of a list component; it returns a factory that builds
- * the props to spread onto each `<ListGridRow>` (a plain `<div>`, never an
- * `<a>`) given that row's href. Calling it per row keeps it outside the
- * rules-of-hooks trap of invoking `useNavigation` inside a `.map()`.
- *
- * The whole row navigates on click — the row is the click target, so the
- * name cell stays plain text (no nested `<a>`, which would be a redundant
- * second entry point). Interactive cells (checkbox, kebab, inline editors)
- * must stop propagation so interacting with them never reaches these
- * handlers — spread `rowLinkInteractiveProps` on them rather than wiring
- * `onClick` alone, because the row handles `auxclick` too.
- *
- * Mirrors AppLink's modifier semantics via `resolveClickIntent`: a plain left
- * click pushes; cmd/ctrl (or a middle click) opens a background tab on
- * desktop; cmd/ctrl+shift opens a foreground tab. On web there is no adapter
- * and — because the row is a `<div>`, not an `<a>` — no native modifier-click
- * behaviour to inherit either, so the browser tab is opened here against the
- * shareable URL (always foreground: JS cannot open a background browser tab).
- * Without that fallback a modifier or middle click would silently navigate in
- * place.
- *
- * `newTabTitle` labels the desktop tab a modifier/middle click creates until
- * the tab bar resolves the real title from the URL.
- *
- * Callers add `cursor-pointer` to the row's own className (kept out of the
- * returned props so it can't clash with the row's existing className).
- */
-/**
- * Props for interactive elements nested inside a `useRowLink` row.
- *
- * Stops BOTH `click` and `auxclick` from bubbling to the row. Stopping only
- * `click` is a trap: a middle click bubbles as `auxclick`, the row handler
- * calls `preventDefault()`, and for a nested `<a>` that cancels the anchor's
- * native middle-click open — so the row opens in a background tab instead of
- * the link's own destination. Native behaviour on the element itself is
- * untouched (no `preventDefault` here), so anchors keep their default open.
+ * Nested interactive cells use rowLinkInteractiveProps to stop both click and
+ * auxclick propagation. Do not prevent their defaults: anchors must retain native
+ * middle-click behavior. Callers own cursor styling and temporary tab titles.
*/
export const rowLinkInteractiveProps = {
onClick: (e: React.MouseEvent) => e.stopPropagation(),
diff --git a/packages/views/onboarding/source-backfill-modal.tsx b/packages/views/onboarding/source-backfill-modal.tsx
index ccad9d9de0..e7dd0ccf2f 100644
--- a/packages/views/onboarding/source-backfill-modal.tsx
+++ b/packages/views/onboarding/source-backfill-modal.tsx
@@ -54,39 +54,13 @@ const EMPTY_BACKFILL: Pick<
};
/**
- * Source-attribution prompt for onboarded users whose questionnaire
- * never recorded a source. The question is not asked during
- * onboarding at all — this prompt is its only collection point.
- * Rendered as a Dialog overlay on top of the workspace shell — the
- * user keeps their workspace context visible behind a dimmed backdrop.
+ * Collect missing acquisition attribution after onboarding has delivered value.
+ * User eligibility and workspace completion thresholds gate opening; latch the
+ * open decision so a successful write cannot interrupt the closing animation.
*
- * Self-mounted: the caller drops `<SourceBackfillModal />` once inside
- * the dashboard layout. Two gates decide whether the dialog opens:
- *
- * 1. User-level: `needsSourceBackfill(user, dismissCount)` — no
- * source recorded, never declined, dismiss cap not reached.
- * 2. Workspace-level: agents (or squads) have completed at least
- * SOURCE_BACKFILL_MIN_AGENT_DONE_ISSUES issues here. Attribution
- * is a zero-payoff ask for the user, so it waits until Multica
- * has visibly delivered value. The count query only runs while
- * gate 1 passes, so settled users never pay for it.
- *
- * Once the dialog opens we capture the open decision in a ref so
- * subsequent re-renders that flip the predicate to false (e.g. after
- * submit, before refreshMe round-trips) don't tear the dialog away
- * mid-animation.
- *
- * Three exit shapes:
- * - Submit → PATCH merged questionnaire, terminal.
- * - Skip → PATCH `source_skipped=true`, terminal (never
- * ask again).
- * - Close X / ESC → bump per-user dismiss counter; predicate
- * returns false on next mount once the cap is
- * reached.
- *
- * State persistence is intentional:
- * - source / source_other: server (JSONB merged with prior answers).
- * - dismissCount: per-user localStorage, view-layer only.
+ * Submit and explicit Skip persist terminal server answers. Dismissal only raises
+ * a per-user local counter. Merge questionnaire fields rather than replacing prior
+ * answers, and skip the completion-count query once user eligibility is settled.
*/
export function SourceBackfillModal() {
const user = useAuthStore((s) => s.user);
diff --git a/packages/views/onboarding/steps/step-platform-fork.tsx b/packages/views/onboarding/steps/step-platform-fork.tsx
index 9d24e8ae99..666c969255 100644
--- a/packages/views/onboarding/steps/step-platform-fork.tsx
+++ b/packages/views/onboarding/steps/step-platform-fork.tsx
@@ -170,9 +170,7 @@ export function StepPlatformFork({
);
}
-// ------------------------------------------------------------
// Fork cards
-// ------------------------------------------------------------
function ForkPrimary({ onClick }: { onClick: () => void }) {
const { t } = useT("onboarding");
@@ -255,9 +253,7 @@ function ForkAlt({
);
}
-// ------------------------------------------------------------
// CLI install dialog
-// ------------------------------------------------------------
/**
* Modal dialog for the CLI install path. Contains the real install
diff --git a/packages/views/onboarding/steps/step-runtime-connect.tsx b/packages/views/onboarding/steps/step-runtime-connect.tsx
index 055bed8e45..97e25d630b 100644
--- a/packages/views/onboarding/steps/step-runtime-connect.tsx
+++ b/packages/views/onboarding/steps/step-runtime-connect.tsx
@@ -83,9 +83,7 @@ export function StepRuntimeConnect({
);
}
-// ============================================================
// Fancy desktop view
-// ============================================================
type Phase = "scanning" | "found" | "empty";
@@ -292,9 +290,7 @@ function FancyView({
);
}
-// ------------------------------------------------------------
// Phase views (inline — all three share the same 620px column)
-// ------------------------------------------------------------
function ScanningView() {
const { t } = useT("onboarding");
@@ -551,9 +547,7 @@ function EmptyCard({
);
}
-// ------------------------------------------------------------
// Card components
-// ------------------------------------------------------------
function SkeletonRuntimeCard() {
return (
diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsx
index cb0dff4ccf..bc3de74975 100644
--- a/packages/views/projects/components/project-detail.tsx
+++ b/packages/views/projects/components/project-detail.tsx
@@ -74,9 +74,7 @@ import { useT } from "../../i18n";
import { useProjectStatusLabels, useProjectPriorityLabels } from "./labels";
import { matchesPinyin } from "../../editor/extensions/pinyin-match";
-// ---------------------------------------------------------------------------
// Property row — sidebar property display
-// ---------------------------------------------------------------------------
function PropRow({
label,
@@ -95,9 +93,7 @@ function PropRow({
);
}
-// ---------------------------------------------------------------------------
// ProjectDetail
-// ---------------------------------------------------------------------------
export function ProjectDetail({ projectId }: { projectId: string }) {
const { t } = useT("projects");
diff --git a/packages/views/projects/components/projects-page.tsx b/packages/views/projects/components/projects-page.tsx
index cb4076b8b1..ae70bc48fe 100644
--- a/packages/views/projects/components/projects-page.tsx
+++ b/packages/views/projects/components/projects-page.tsx
@@ -137,12 +137,10 @@ function leadFilterValue(p: Project): string | null {
return p.lead_type && p.lead_id ? `${p.lead_type}:${p.lead_id}` : null;
}
-// ---------------------------------------------------------------------------
// Table (compact) view — ListGrid. Name + status are the core columns;
// priority/progress/lead/issues/created collapse below @2xl, with min-width
// + the wrapper's overflow as the escape valve. Rows use whole-row mouse
// navigation; inline controls stop propagation so edit/menu clicks stay local.
-// ---------------------------------------------------------------------------
const COLUMN_WIDTHS: Record<ProjectColumnKey, number> = {
priority: 116,
@@ -572,9 +570,7 @@ function ProjectTableHeader({
);
}
-// ---------------------------------------------------------------------------
// Card (comfortable) view — kept from the prior page.
-// ---------------------------------------------------------------------------
function ProjectCard({
project,
@@ -670,10 +666,8 @@ function ProjectCard({
);
}
-// ---------------------------------------------------------------------------
// Toolbar — search + result count + filter + display (compact only) + view
// toggle.
-// ---------------------------------------------------------------------------
const STATUS_VALUES: ProjectStatus[] = [
"planned",
@@ -790,9 +784,7 @@ function ProjectBatchToolbar({
);
}
-// ---------------------------------------------------------------------------
// Page
-// ---------------------------------------------------------------------------
export function ProjectsPage() {
const { t } = useT("projects");
diff --git a/packages/views/rich-content/rich-content.tsx b/packages/views/rich-content/rich-content.tsx
index 55e1d44745..5bcde7aa03 100644
--- a/packages/views/rich-content/rich-content.tsx
+++ b/packages/views/rich-content/rich-content.tsx
@@ -87,9 +87,7 @@ import "./rich-content.css";
export type RichContentDensity = "compact" | "document";
export type RichContentPhase = "streaming" | "settled";
-// ---------------------------------------------------------------------------
// Fence gate context
-// ---------------------------------------------------------------------------
//
// The closed-fence offsets travel by context rather than by rebuilding the
// components map. The map must stay referentially stable: react-markdown
@@ -109,9 +107,7 @@ function useClosedFence(offset: number | undefined): ClosedFence | undefined {
return offset == null ? undefined : closed.get(offset);
}
-// ---------------------------------------------------------------------------
// Mention / link renderers
-// ---------------------------------------------------------------------------
/**
* Issue mention chip. Navigation — plain click, modifier click, and the
@@ -356,9 +352,7 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
return plainLink;
}
-// ---------------------------------------------------------------------------
// Fenced code
-// ---------------------------------------------------------------------------
function getTextContent(node: ReactNode): string {
if (node == null || typeof node === "boolean") return "";
@@ -550,9 +544,7 @@ const REHYPE_PLUGINS = [
rehypeKatex,
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
-// ---------------------------------------------------------------------------
// Component
-// ---------------------------------------------------------------------------
export interface RichContentProps {
content: string;
diff --git a/packages/views/runtimes/components/connect-remote-dialog.tsx b/packages/views/runtimes/components/connect-remote-dialog.tsx
index 36dffd6447..29e0bfd065 100644
--- a/packages/views/runtimes/components/connect-remote-dialog.tsx
+++ b/packages/views/runtimes/components/connect-remote-dialog.tsx
@@ -161,9 +161,7 @@ export function ConnectRemoteDialog({ onClose }: { onClose: () => void }) {
);
}
-// ---------------------------------------------------------------------------
// Copy button + code row — mirrors onboarding/CliInstallInstructions
-// ---------------------------------------------------------------------------
function CopyButton({ text, ariaLabel }: { text: string; ariaLabel: string }) {
const [copied, setCopied] = useState(false);
@@ -235,9 +233,7 @@ function CommandStep({
);
}
-// ---------------------------------------------------------------------------
// Step 1: Instructions
-// ---------------------------------------------------------------------------
function InstructionsStep({ onClose }: { onClose: () => void }) {
const { t } = useT("runtimes");
@@ -361,9 +357,7 @@ function TroubleshootingDetails({ tokenCmd }: { tokenCmd: string }) {
);
}
-// ---------------------------------------------------------------------------
// Live-listening indicator
-// ---------------------------------------------------------------------------
function LiveListening() {
const { t } = useT("runtimes");
@@ -384,9 +378,7 @@ function LiveListening() {
);
}
-// ---------------------------------------------------------------------------
// Step 2: Success
-// ---------------------------------------------------------------------------
function SuccessStep({
onGoToAgents,
diff --git a/packages/views/runtimes/components/delete-runtime-dialog.tsx b/packages/views/runtimes/components/delete-runtime-dialog.tsx
index 3a1d94000b..065fb85ffb 100644
--- a/packages/views/runtimes/components/delete-runtime-dialog.tsx
+++ b/packages/views/runtimes/components/delete-runtime-dialog.tsx
@@ -232,12 +232,10 @@ export function DeleteRuntimeDialog({
);
}
-// ---------------------------------------------------------------------------
// Persistence notice — informational banner shown when deleting the runtime
// row may not permanently remove the runnable backend. Profile-backed custom
// runtimes win over the generic local-daemon warning: stopping the daemon is
// not sufficient when the workspace-level profile still exists.
-// ---------------------------------------------------------------------------
function DeletePersistenceNotice({ runtime }: { runtime: AgentRuntime }) {
const { t } = useT("runtimes");
@@ -264,11 +262,9 @@ function DeletePersistenceNotice({ runtime }: { runtime: AgentRuntime }) {
);
}
-// ---------------------------------------------------------------------------
// Light mode — no active agents, classic "are you sure" prompt. Title and
// description match the legacy AlertDialog so existing screenshots / muscle
// memory still apply.
-// ---------------------------------------------------------------------------
function LightBody({
runtime,
@@ -323,11 +319,9 @@ function LightBody({
);
}
-// ---------------------------------------------------------------------------
// Cascade mode — destructive warning, agent table, checkbox-confirmed
// destructive button. Copy follows 赵刚's English text verbatim per the
// squad lead's directive.
-// ---------------------------------------------------------------------------
function CascadeBody({
runtime,
@@ -591,9 +585,7 @@ function VisibilityCell({ visibility }: { visibility: string }) {
);
}
-// ---------------------------------------------------------------------------
// Server response parsing
-// ---------------------------------------------------------------------------
interface ActiveAgentsConflict {
code: "runtime_has_active_agents" | "runtime_delete_plan_changed";
diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsx
index 8b7b37e225..341df3f742 100644
--- a/packages/views/runtimes/components/runtime-list.tsx
+++ b/packages/views/runtimes/components/runtime-list.tsx
@@ -184,9 +184,7 @@ export function buildWorkloadIndex(
return result;
}
-// ---------------------------------------------------------------------------
// Cells
-// ---------------------------------------------------------------------------
function RuntimeNameCell({
runtime,
@@ -656,9 +654,7 @@ export function RuntimeRowMenu({
);
}
-// ---------------------------------------------------------------------------
// List
-// ---------------------------------------------------------------------------
export function RuntimeList({
runtimes,
diff --git a/packages/views/runtimes/components/runtime-profiles-dialog.tsx b/packages/views/runtimes/components/runtime-profiles-dialog.tsx
index 320696682d..4bc9c90594 100644
--- a/packages/views/runtimes/components/runtime-profiles-dialog.tsx
+++ b/packages/views/runtimes/components/runtime-profiles-dialog.tsx
@@ -248,9 +248,7 @@ export function RuntimeProfilesDialog({
);
}
-// ---------------------------------------------------------------------------
// Master list — custom profiles first, built-in families as collapsed reference.
-// ---------------------------------------------------------------------------
function CatalogList({
catalog,
@@ -472,10 +470,8 @@ function CatalogRow({
);
}
-// ---------------------------------------------------------------------------
// Detail panel — adaptive: built-in is read-only, custom shows fields +
// Edit / Delete.
-// ---------------------------------------------------------------------------
function DetailPanel({
entry,
@@ -636,9 +632,7 @@ function DetailRow({
);
}
-// ---------------------------------------------------------------------------
// Create / edit form.
-// ---------------------------------------------------------------------------
function ProfileFormView({
wsId,
diff --git a/packages/views/runtimes/components/usage-section.tsx b/packages/views/runtimes/components/usage-section.tsx
index 48dac7afc8..783b1c1294 100644
--- a/packages/views/runtimes/components/usage-section.tsx
+++ b/packages/views/runtimes/components/usage-section.tsx
@@ -76,11 +76,9 @@ function rangesForDim(dim: Exclude<WhenTab, "heatmap">) {
);
}
-// ---------------------------------------------------------------------------
// Local segmented control. shadcn's Tabs is wired for full tab pages with
// keyboard nav and ARIA semantics that a compact toolbar pill doesn't need.
// Visual: light-grey track + white "raised" active pill.
-// ---------------------------------------------------------------------------
function Segmented<T extends string | number>({
value,
@@ -118,7 +116,6 @@ function Segmented<T extends string | number>({
);
}
-// ---------------------------------------------------------------------------
// Top-level orchestrator. Owns the time window, fetches a 180-day usage
// cache once, slices it into "current" / "prior" windows for delta math,
// and threads everything into the four visual blocks below.
@@ -127,7 +124,6 @@ function Segmented<T extends string | number>({
// weeks (~6 months) so the long view actually looks long. The 7d/30d/90d
// period selector slices client-side; the prior-window delta on the Cost
// KPI also benefits from having extra history available.
-// ---------------------------------------------------------------------------
export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
const { t, i18n } = useT("runtimes");
@@ -327,13 +323,11 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
);
}
-// ---------------------------------------------------------------------------
// WhenChart — answers "WHEN was this runtime spending money?".
// Dimension (Daily / Weekly) is owned by the parent so the page-level
// period selector can react to it. Heatmap is an independent view toggled
// inside this card; it ignores both the dimension and the period selector,
// always showing the long 26-week view.
-// ---------------------------------------------------------------------------
type Dim = Exclude<WhenTab, "heatmap">;
type DailyMetric = "cost" | "tokens";
@@ -503,14 +497,12 @@ function WeeklyTab({
return <WeeklyCostChart data={costData} />;
}
-// ---------------------------------------------------------------------------
// EmptyChartState — drop-in replacement for "the chart would render empty".
// Two cases worth distinguishing:
// 1. No tokens at all → "no usage" (genuinely nothing happened).
// 2. Tokens present but cost is $0 → almost always means the model name
// reported by the daemon isn't in our pricing table. List the offenders
// so a developer can update MODEL_PRICING in one go.
-// ---------------------------------------------------------------------------
function EmptyChartState({ usage }: { usage: RuntimeUsage[] }) {
const { t } = useT("runtimes");
@@ -551,7 +543,6 @@ function EmptyChartState({ usage }: { usage: RuntimeUsage[] }) {
);
}
-// ---------------------------------------------------------------------------
// CustomPricingBar — the only entry point into the custom-pricing dialog,
// rendered above the KPI grid. Two states:
//
@@ -565,7 +556,6 @@ function EmptyChartState({ usage }: { usage: RuntimeUsage[] }) {
// saved rates could no longer be corrected or removed from the UI.
//
// Hidden entirely when nothing is unmapped and nothing is overridden.
-// ---------------------------------------------------------------------------
function CustomPricingBar({ usage }: { usage: RuntimeUsage[] }) {
const { t } = useT("runtimes");
@@ -622,10 +612,8 @@ function CustomPricingBar({ usage }: { usage: RuntimeUsage[] }) {
);
}
-// ---------------------------------------------------------------------------
// Chart legend — one coloured dot + label per stack segment, rendered in
// WhenChart's header so the chart body keeps its full vertical real estate.
-// ---------------------------------------------------------------------------
function ChartLegend({ includeCacheRead = false }: { includeCacheRead?: boolean }) {
const { t } = useT("runtimes");
@@ -655,9 +643,7 @@ function ChartLegend({ includeCacheRead = false }: { includeCacheRead?: boolean
);
}
-// ---------------------------------------------------------------------------
// Cost-by block: two-tab attribution view (by agent / by model).
-// ---------------------------------------------------------------------------
function CostByBlock({
runtimeId,
@@ -804,11 +790,9 @@ function CostByList({
);
}
-// ---------------------------------------------------------------------------
// Folded row — single chevron-toggle link revealing the raw breakdown
// table. The Activity heatmap used to live here too; it was promoted to a
// WhenChart toggle, leaving only the breakdown table behind.
-// ---------------------------------------------------------------------------
function FoldedRow({ usage }: { usage: RuntimeUsage[] }) {
const { t } = useT("runtimes");
@@ -881,9 +865,7 @@ function DailyBreakdownTable({ usage }: { usage: RuntimeUsage[] }) {
);
}
-// ---------------------------------------------------------------------------
// Loading + empty states
-// ---------------------------------------------------------------------------
function UsageSkeleton() {
return (
@@ -907,9 +889,7 @@ function UsageEmpty() {
);
}
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
interface UsageTotals {
input: number;
diff --git a/packages/views/runtimes/utils.ts b/packages/views/runtimes/utils.ts
index eb696bde5a..42f152278a 100644
--- a/packages/views/runtimes/utils.ts
+++ b/packages/views/runtimes/utils.ts
@@ -13,9 +13,7 @@ export function isSelfHealingRuntime(runtime: AgentRuntime): boolean {
return runtime.runtime_mode === "local" && runtime.status === "online";
}
-// ---------------------------------------------------------------------------
// Formatting helpers
-// ---------------------------------------------------------------------------
// Compound-unit relative timestamp ("2m 14s ago", "1d 4h ago", "6d 19h ago")
// — gives the user enough precision to tell "just lost" from "long lost"
@@ -168,9 +166,7 @@ export function formatUsd(n: number): string {
return `$${n.toFixed(2)}`;
}
-// ---------------------------------------------------------------------------
// Cost estimation
-// ---------------------------------------------------------------------------
// Pricing per million tokens (USD). Sources, each authoritative for the
// rows tagged under it — keep in sync when providers release new models
@@ -764,9 +760,7 @@ export function estimateCostBreakdown(usage: Priceable): CostBreakdown {
};
}
-// ---------------------------------------------------------------------------
// Per-run usage
-// ---------------------------------------------------------------------------
/** Collapsed usage for one agent run, or for a set of runs. */
export interface TaskUsageSummary {
@@ -844,9 +838,7 @@ export function estimateCacheSavings(usage: Priceable): number {
return wouldHaveCost - actualCost;
}
-// ---------------------------------------------------------------------------
// Data aggregation
-// ---------------------------------------------------------------------------
export interface DailyTokenData {
date: string;
@@ -1179,13 +1171,11 @@ function diffDaysIso(from: string, to: string): number {
return Math.round((b - a) / 86_400_000);
}
-// ---------------------------------------------------------------------------
// Calendar helpers — all date math runs on YYYY-MM-DD strings in the
// runtime's IANA timezone. The backend already groups daily usage by
// `start-of-day in runtime tz`, so we keep the entire frontend aggregation
// on the same axis (Daily / Weekly) to avoid one-day drift when the browser
// and runtime sit in different time zones.
-// ---------------------------------------------------------------------------
// Today's calendar date (YYYY-MM-DD) in the given IANA timezone. `en-CA`
// gives ISO-shaped output without us having to assemble Intl parts by hand.
@@ -1232,14 +1222,12 @@ export function formatShortDate(iso: string): string {
});
}
-// ---------------------------------------------------------------------------
// Cost-by-X aggregations
//
// All three "Cost by …" tabs share the same shape: a sorted list of rows
// where each row carries a key (agent name, model name, or hour-of-day),
// total tokens and total cost. The chart / list components are oblivious
// to which axis they're rendering — they just see {key, tokens, cost}.
-// ---------------------------------------------------------------------------
export interface CostByKey {
key: string;
diff --git a/packages/views/settings/components/composio-tab.tsx b/packages/views/settings/components/composio-tab.tsx
index 529567e1c1..871b111608 100644
--- a/packages/views/settings/components/composio-tab.tsx
+++ b/packages/views/settings/components/composio-tab.tsx
@@ -108,9 +108,7 @@ export function ComposioTab() {
return m;
}, [connectionsQuery.data]);
- // Toolkits whose latest connection is expired render a Reconnect affordance
- // instead of Connected/Connect. Backend only emits `expired` once Stage 4
- // (MUL-3719) lands, but the branch is wired up now so it lights up for free.
+ // The reconnect branch is prepared, but the backend does not yet emit "expired".
const expiredBySlug = useMemo(() => {
const m = new Set<string>();
for (const c of connectionsQuery.data ?? []) {
@@ -119,10 +117,6 @@ export function ComposioTab() {
return m;
}, [connectionsQuery.data]);
- // Last-used timestamp per active connection, for the "Last used …" line on a
- // connected card. Backend leaves this null until tool-call dispatch starts
- // stamping it (Stage 3, MUL-3721); the card shows a "never used" placeholder
- // until then.
const lastUsedBySlug = useMemo(() => {
const m = new Map<string, string | null>();
for (const c of connectionsQuery.data ?? []) {
@@ -329,8 +323,6 @@ function ToolkitCard({
</Button>
</div>
) : expired ? (
- // Token-expired connection: surface the failure and let the user
- // re-run the same connect flow in one click (no disconnect step).
<div className="flex items-center gap-2">
<span className="inline-flex items-center gap-1 text-caption text-amber-600">
<AlertTriangle className="h-3 w-3" />
diff --git a/packages/views/skills/components/create-skill-dialog.tsx b/packages/views/skills/components/create-skill-dialog.tsx
index 48f6a30389..b31195069b 100644
--- a/packages/views/skills/components/create-skill-dialog.tsx
+++ b/packages/views/skills/components/create-skill-dialog.tsx
@@ -62,9 +62,7 @@ function seedAfterCreate(
qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
}
-// ---------------------------------------------------------------------------
// Chooser — initial method picker (4 cards)
-// ---------------------------------------------------------------------------
function MethodChooser({ onChoose }: { onChoose: (m: Method) => void }) {
const { t } = useT("skills");
@@ -104,9 +102,7 @@ function MethodChooser({ onChoose }: { onChoose: (m: Method) => void }) {
);
}
-// ---------------------------------------------------------------------------
// Manual form
-// ---------------------------------------------------------------------------
function ManualForm({
onCreated,
@@ -241,9 +237,7 @@ function ManualForm({
);
}
-// ---------------------------------------------------------------------------
// URL import form
-// ---------------------------------------------------------------------------
type DetectedSource = "clawhub" | "skills.sh" | "github" | null;
@@ -427,9 +421,7 @@ function UrlForm({
);
}
-// ---------------------------------------------------------------------------
// Local folder / archive import
-// ---------------------------------------------------------------------------
function LocalForm({
prepared,
@@ -604,9 +596,7 @@ function LocalForm({
);
}
-// ---------------------------------------------------------------------------
// Root dialog
-// ---------------------------------------------------------------------------
export function CreateSkillDialog({
onClose,
diff --git a/packages/views/skills/components/file-tree.tsx b/packages/views/skills/components/file-tree.tsx
index c5bb01c214..c5fcdf61db 100644
--- a/packages/views/skills/components/file-tree.tsx
+++ b/packages/views/skills/components/file-tree.tsx
@@ -42,9 +42,7 @@ export interface FileTreeActions {
reservedPath: string;
}
-// ---------------------------------------------------------------------------
// Tree data structures
-// ---------------------------------------------------------------------------
interface FileTreeNode {
name: string;
@@ -104,9 +102,7 @@ function getFileIcon(name: string) {
return File;
}
-// ---------------------------------------------------------------------------
// Tree node renderer
-// ---------------------------------------------------------------------------
function TreeNodeItem({
node,
@@ -341,9 +337,7 @@ function RenameRow({
);
}
-// ---------------------------------------------------------------------------
// Public component
-// ---------------------------------------------------------------------------
export function FileTree({
filePaths,
diff --git a/packages/views/skills/components/runtime-local-skill-import-panel.tsx b/packages/views/skills/components/runtime-local-skill-import-panel.tsx
index 0dba45405f..00a492c767 100644
--- a/packages/views/skills/components/runtime-local-skill-import-panel.tsx
+++ b/packages/views/skills/components/runtime-local-skill-import-panel.tsx
@@ -65,9 +65,7 @@ import {
} from "../../runtimes/components/runtime-machines";
import { isNameConflictError } from "../lib/utils";
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
type BulkImportResult = {
key: string;
@@ -102,9 +100,7 @@ const INITIAL_BULK_STATE: BulkImportState = {
results: [],
};
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
/**
* Max concurrent imports. Higher = faster but more daemon/network pressure.
@@ -135,9 +131,7 @@ function ResultIcon({ status }: { status: BulkImportResult["status"] }) {
}
}
-// ---------------------------------------------------------------------------
// Skill row with checkbox
-// ---------------------------------------------------------------------------
function SkillItem({
skill,
@@ -248,9 +242,7 @@ function SkillItem({
);
}
-// ---------------------------------------------------------------------------
// Summary view (shown after bulk import completes)
-// ---------------------------------------------------------------------------
function BulkImportSummary({ results }: { results: BulkImportResult[] }) {
const { t } = useT("skills");
@@ -499,9 +491,7 @@ function ConflictResolutionPanel({
);
}
-// ---------------------------------------------------------------------------
// Panel
-// ---------------------------------------------------------------------------
export function RuntimeLocalSkillImportPanel({
onImported,
diff --git a/packages/views/skills/components/skill-detail-page.tsx b/packages/views/skills/components/skill-detail-page.tsx
index b2817dd8ad..635f6b581a 100644
--- a/packages/views/skills/components/skill-detail-page.tsx
+++ b/packages/views/skills/components/skill-detail-page.tsx
@@ -172,9 +172,7 @@ function isDetailView(value: string | null): value is DetailView {
return value === "overview" || value === "files";
}
-// ---------------------------------------------------------------------------
// File path validation + inline add
-// ---------------------------------------------------------------------------
export function useValidateNewFilePath() {
const { t } = useT("skills");
@@ -256,9 +254,7 @@ function AddFileInline({
);
}
-// ---------------------------------------------------------------------------
// Header
-// ---------------------------------------------------------------------------
function useOriginLabel(origin: OriginInfo | null, runtime: AgentRuntime | null) {
const { t } = useT("skills");
@@ -385,9 +381,7 @@ function SkillIdentity({
);
}
-// ---------------------------------------------------------------------------
// Overview tab
-// ---------------------------------------------------------------------------
function PropertyRow({
label,
@@ -557,9 +551,7 @@ function OverviewTab({
);
}
-// ---------------------------------------------------------------------------
// Files tab
-// ---------------------------------------------------------------------------
function FilesTab({
filePaths,
@@ -756,9 +748,7 @@ function FilesTab({
);
}
-// ---------------------------------------------------------------------------
// Main page
-// ---------------------------------------------------------------------------
export function SkillDetailPage({ skillId }: { skillId: string }) {
const { t } = useT("skills");
diff --git a/packages/views/skills/components/skill-list-actions.tsx b/packages/views/skills/components/skill-list-actions.tsx
index d33d55b3a4..736eb63811 100644
--- a/packages/views/skills/components/skill-list-actions.tsx
+++ b/packages/views/skills/components/skill-list-actions.tsx
@@ -66,9 +66,7 @@ export interface SkillActionsContext {
isAdmin: boolean;
}
-// ---------------------------------------------------------------------------
// Add-to-agent dialog (multi-select; shared by row kebab and batch toolbar)
-// ---------------------------------------------------------------------------
// Attaching is permission-gated by the TARGET agent (its owner, or a
// workspace owner/admin — server/internal/handler/agent.go canManageAgent).
@@ -399,9 +397,7 @@ export function AddToAgentDialog({
);
}
-// ---------------------------------------------------------------------------
// Delete confirmation (single row and batch share one dialog)
-// ---------------------------------------------------------------------------
export function DeleteSkillsDialog({
rows,
@@ -507,9 +503,7 @@ export function DeleteSkillsDialog({
);
}
-// ---------------------------------------------------------------------------
// Bulk update-from-source (batch toolbar)
-// ---------------------------------------------------------------------------
/**
* Confirm-and-run dialog for updating several imported skills from their
@@ -642,9 +636,7 @@ export function UpdateSkillsDialog({
);
}
-// ---------------------------------------------------------------------------
// Row kebab
-// ---------------------------------------------------------------------------
// The row is a plain `<div>` whose whole-row navigation is a mouse `onClick`
// (see `useRowLink`), not an ancestor `<a>`. The wrapper span stops click
@@ -748,9 +740,7 @@ export function SkillRowActions({
);
}
-// ---------------------------------------------------------------------------
// Batch toolbar (floating bottom bar, same shape as the issues batch bar)
-// ---------------------------------------------------------------------------
export function SkillBatchToolbar({
rows,
diff --git a/packages/views/skills/components/skills-page.tsx b/packages/views/skills/components/skills-page.tsx
index 8d9316fb37..0b943bb783 100644
--- a/packages/views/skills/components/skills-page.tsx
+++ b/packages/views/skills/components/skills-page.tsx
@@ -156,10 +156,8 @@ function columnTrackVars(
export type SortField = SkillSortField;
export { rowMatchesFilters, type SkillRow } from "./skill-list-filter";
-// ---------------------------------------------------------------------------
// Page header bar — uses shared PageHeader so the mobile sidebar trigger and
// h-12 chrome stay consistent with every other dashboard list page.
-// ---------------------------------------------------------------------------
function PageHeaderBar({
totalCount,
@@ -190,9 +188,7 @@ function PageHeaderBar({
);
}
-// ---------------------------------------------------------------------------
// Cells
-// ---------------------------------------------------------------------------
// Hover-revealed multi-select checkbox. Same pattern as SkillPickerList:
// the shadcn Checkbox is presentational only (`pointer-events-none`, so the
@@ -397,9 +393,7 @@ function CreatorCell({ creator }: { creator: MemberWithUser | null }) {
);
}
-// ---------------------------------------------------------------------------
// Empty state
-// ---------------------------------------------------------------------------
function EmptyState({ onCreate }: { onCreate: () => void }) {
const { t } = useT("skills");
@@ -418,9 +412,7 @@ function EmptyState({ onCreate }: { onCreate: () => void }) {
);
}
-// ---------------------------------------------------------------------------
// List
-// ---------------------------------------------------------------------------
function SkillListHeader({
sortField,
@@ -573,9 +565,7 @@ function LoadingSkeleton() {
);
}
-// ---------------------------------------------------------------------------
// Page
-// ---------------------------------------------------------------------------
export default function SkillsPage() {
const { t } = useT("skills");
diff --git a/packages/views/squads/components/squad-detail-page.tsx b/packages/views/squads/components/squad-detail-page.tsx
index cba6e9c492..ff35b4511e 100644
--- a/packages/views/squads/components/squad-detail-page.tsx
+++ b/packages/views/squads/components/squad-detail-page.tsx
@@ -708,11 +708,9 @@ function RoleEditor({ value, onSave }: { value: string; onSave: (next: string) =
);
}
-// ---------------------------------------------------------------------------
// SquadDetailInspector — left 320px column, mirrors AgentDetailInspector.
// Holds identity (avatar / name / description) + leader / member count /
// timestamps. All inline-editable.
-// ---------------------------------------------------------------------------
function SquadDetailInspector({
squad,
memberCount,
@@ -931,11 +929,9 @@ function SquadDescriptionEditorBody({
);
}
-// ---------------------------------------------------------------------------
// SquadOverviewPane — right column with two tabs (Members | Instructions).
// Mirrors AgentOverviewPane: dirty-guard via AlertDialog when switching tabs
// with unsaved Instructions.
-// ---------------------------------------------------------------------------
type SquadDetailTab = "members" | "instructions";
const squadDetailTabs: { id: SquadDetailTab; icon: typeof FileText }[] = [
diff --git a/packages/views/squads/components/squads-page.tsx b/packages/views/squads/components/squads-page.tsx
index 91b783d370..f65b28039a 100644
--- a/packages/views/squads/components/squads-page.tsx
+++ b/packages/views/squads/components/squads-page.tsx
@@ -138,9 +138,7 @@ function columnTrackVars(
} as React.CSSProperties;
}
-// ---------------------------------------------------------------------------
// Cells
-// ---------------------------------------------------------------------------
function SquadAvatar({ squad }: { squad: Squad }) {
const initials = squad.name
@@ -248,11 +246,9 @@ function MembersCell({ squad }: { squad: Squad }) {
);
}
-// ---------------------------------------------------------------------------
// Archive (= delete) dialog — reuses the existing archive_dialog copy.
// Workspace owner/admin only (backend gate). No restore endpoint exists, so
// once archived a squad is gone from the UI.
-// ---------------------------------------------------------------------------
function ArchiveSquadDialog({
squad,
@@ -372,9 +368,7 @@ function SquadRowActions({ squad }: { squad: Squad }) {
);
}
-// ---------------------------------------------------------------------------
// Header + toolbar
-// ---------------------------------------------------------------------------
function SquadListHeader({
sortField,
@@ -766,9 +760,7 @@ function SquadListToolbar({
);
}
-// ---------------------------------------------------------------------------
// Page
-// ---------------------------------------------------------------------------
export function SquadsPage() {
const { t } = useT("squads");
diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.go
index 99c6a51477..f067bf46b5 100644
--- a/server/cmd/multica/cmd_agent.go
+++ b/server/cmd/multica/cmd_agent.go
@@ -511,9 +511,7 @@ func requireWorkspaceID(cmd *cobra.Command) (string, error) {
return id, nil
}
-// ---------------------------------------------------------------------------
// Agent commands
-// ---------------------------------------------------------------------------
func runAgentList(cmd *cobra.Command, _ []string) error {
client, err := newAPIClient(cmd)
@@ -1010,9 +1008,7 @@ func runAgentAvatar(cmd *cobra.Command, args []string) error {
return nil
}
-// ---------------------------------------------------------------------------
// Agent skills subcommands
-// ---------------------------------------------------------------------------
func runAgentSkillsList(cmd *cobra.Command, args []string) error {
client, err := newAPIClient(cmd)
@@ -1140,9 +1136,7 @@ func printAgentSkillsMutationResult(cmd *cobra.Command, agentID string, result j
return nil
}
-// ---------------------------------------------------------------------------
// Agent env subcommands
-// ---------------------------------------------------------------------------
// runAgentEnvGet fetches the plaintext custom_env for a single agent
// via the audited `/env` endpoint. The CLI prints raw JSON in JSON
@@ -1217,9 +1211,7 @@ func runAgentEnvSet(cmd *cobra.Command, args []string) error {
return nil
}
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
// parseCustomEnv parses the --custom-env flag value (a JSON object literal)
// into a string map suitable for the request body. The clear-all signal is
diff --git a/server/cmd/multica/cmd_autopilot.go b/server/cmd/multica/cmd_autopilot.go
index 8fd953285f..aeab37911f 100644
--- a/server/cmd/multica/cmd_autopilot.go
+++ b/server/cmd/multica/cmd_autopilot.go
@@ -182,9 +182,7 @@ func init() {
autopilotTriggerUpdateCmd.Flags().String("output", "json", "Output format: table or json")
}
-// ---------------------------------------------------------------------------
// Autopilot commands
-// ---------------------------------------------------------------------------
func runAutopilotList(cmd *cobra.Command, _ []string) error {
client, err := newAPIClient(cmd)
@@ -1012,9 +1010,7 @@ func resolveAutopilotSubscriberInputs(ctx context.Context, client *cli.APIClient
return inputs, nil
}
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
// uuidRegexp matches a canonical UUID (8-4-4-4-12 hex).
var uuidRegexp = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
diff --git a/server/cmd/multica/cmd_daemon_autostart.go b/server/cmd/multica/cmd_daemon_autostart.go
index 9aba64a1d1..ae7dc1e66a 100644
--- a/server/cmd/multica/cmd_daemon_autostart.go
+++ b/server/cmd/multica/cmd_daemon_autostart.go
@@ -147,9 +147,7 @@ var (
// state on the machine running the tests.
var syncDaemonAutostart = syncDaemonAutostartDefault
-// ---------------------------------------------------------------------------
// command wiring
-// ---------------------------------------------------------------------------
var daemonAutostartCmd = &cobra.Command{
Use: "autostart",
@@ -394,9 +392,7 @@ func mechanismLabel(key string) string {
}
}
-// ---------------------------------------------------------------------------
// the `daemon start` hook
-// ---------------------------------------------------------------------------
// shouldManageAutostart decides whether the hint/refresh side of
// `daemon start` applies to this invocation:
@@ -523,9 +519,7 @@ func autostartProfileSlug(profile string) string {
return fmt.Sprintf("%s-%06x", slug, h.Sum32()&0xffffff)
}
-// ---------------------------------------------------------------------------
// platform-agnostic builders (pure; exercised by tests on every OS)
-// ---------------------------------------------------------------------------
// windowsQuoteArg quotes one argv element for a Windows command line using
// the CRT parsing rules (backslashes before quotes and at the end of a
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 5af1550d16..e25b52afd0 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -748,9 +748,7 @@ func init() {
issueSubscriberRemoveCmd.Flags().String("output", "json", "Output format: table or json")
}
-// ---------------------------------------------------------------------------
// Issue commands
-// ---------------------------------------------------------------------------
func runIssueList(cmd *cobra.Command, _ []string) error {
client, err := newAPIClient(cmd)
@@ -2018,9 +2016,7 @@ func recordedDuplicateOf(result map[string]any, ref string) (string, error) {
return ref, nil
}
-// ---------------------------------------------------------------------------
// Reorder command
-// ---------------------------------------------------------------------------
// registerIssueReorderFlags wires the reorder command's flags and declares its
// target selector as a cobra flag group: mutually exclusive so at most one of
@@ -2331,9 +2327,7 @@ func floatVal(m map[string]any, key string) float64 {
return 0
}
-// ---------------------------------------------------------------------------
// Comment commands
-// ---------------------------------------------------------------------------
func runIssueCommentList(cmd *cobra.Command, args []string) error {
client, err := newAPIClient(cmd)
@@ -2687,9 +2681,7 @@ func runIssueCommentResolution(cmd *cobra.Command, commentID string, resolve boo
return cli.PrintJSON(os.Stdout, result)
}
-// ---------------------------------------------------------------------------
// Execution history commands
-// ---------------------------------------------------------------------------
func runIssueRuns(cmd *cobra.Command, args []string) error {
client, err := newAPIClient(cmd)
@@ -2934,9 +2926,7 @@ func runIssueRunMessages(cmd *cobra.Command, args []string) error {
return nil
}
-// ---------------------------------------------------------------------------
// Search command
-// ---------------------------------------------------------------------------
func runIssueRerun(cmd *cobra.Command, args []string) error {
client, err := newAPIClient(cmd)
@@ -3069,9 +3059,7 @@ func runIssueSearch(cmd *cobra.Command, args []string) error {
return nil
}
-// ---------------------------------------------------------------------------
// Subscriber commands
-// ---------------------------------------------------------------------------
func runIssueSubscriberList(cmd *cobra.Command, args []string) error {
client, err := newAPIClient(cmd)
@@ -3175,9 +3163,7 @@ func runIssueSubscriberMutation(cmd *cobra.Command, issueID, action string) erro
return cli.PrintJSON(os.Stdout, result)
}
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
type assigneeMatch struct {
Type string // "member", "agent", or "squad"
diff --git a/server/cmd/multica/cmd_label.go b/server/cmd/multica/cmd_label.go
index 23f770107e..d1487b16af 100644
--- a/server/cmd/multica/cmd_label.go
+++ b/server/cmd/multica/cmd_label.go
@@ -11,9 +11,7 @@ import (
"github.com/multica-ai/multica/server/internal/cli"
)
-// ---------------------------------------------------------------------------
// Label commands — workspace-scoped CRUD for labels (issues and skills).
-// ---------------------------------------------------------------------------
var labelCmd = &cobra.Command{
Use: "label",
diff --git a/server/cmd/multica/cmd_project.go b/server/cmd/multica/cmd_project.go
index 73c8afb5d0..50036d1208 100644
--- a/server/cmd/multica/cmd_project.go
+++ b/server/cmd/multica/cmd_project.go
@@ -193,9 +193,7 @@ func init() {
projectStatusCmd.Flags().String("output", "table", "Output format: table or json")
}
-// ---------------------------------------------------------------------------
// Project commands
-// ---------------------------------------------------------------------------
func runProjectList(cmd *cobra.Command, _ []string) error {
client, err := newAPIClient(cmd)
@@ -522,9 +520,7 @@ func runProjectStatus(cmd *cobra.Command, args []string) error {
return nil
}
-// ---------------------------------------------------------------------------
// Project resource commands
-// ---------------------------------------------------------------------------
func runProjectResourceList(cmd *cobra.Command, args []string) error {
client, err := newAPIClient(cmd)
@@ -973,9 +969,7 @@ func summarizeResourceRef(raw any) string {
return ""
}
-// ---------------------------------------------------------------------------
// Helpers
-// ---------------------------------------------------------------------------
func formatLead(project map[string]any, actors actorDisplayLookup) string {
lType := strVal(project, "lead_type")
diff --git a/server/cmd/multica/cmd_property.go b/server/cmd/multica/cmd_property.go
index 5564507319..505a5a01af 100644
--- a/server/cmd/multica/cmd_property.go
+++ b/server/cmd/multica/cmd_property.go
@@ -459,9 +459,7 @@ func makePropertyArchiveRun(archive bool) func(*cobra.Command, []string) error {
}
}
-// ---------------------------------------------------------------------------
// issue property {list|set|unset}
-// ---------------------------------------------------------------------------
// memberDirectory serves every member lookup in one command from a single
// request. An actor --property filter, an actor --value and
@@ -1034,9 +1032,7 @@ func runIssuePropertyUnset(cmd *cobra.Command, args []string) error {
return nil
}
-// ---------------------------------------------------------------------------
// issue list --property / --sort property:<ref>
-// ---------------------------------------------------------------------------
// propertyNoValueSentinel is the server's reserved filter value meaning "the
// property is not set" (see parsePropertiesFilterParam in
diff --git a/server/cmd/multica/cmd_runtime.go b/server/cmd/multica/cmd_runtime.go
index dd197b550e..1d81fb814a 100644
--- a/server/cmd/multica/cmd_runtime.go
+++ b/server/cmd/multica/cmd_runtime.go
@@ -100,9 +100,7 @@ func init() {
runtimeDeleteCmd.Flags().String("output", "table", "Output format: table or json")
}
-// ---------------------------------------------------------------------------
// Runtime commands
-// ---------------------------------------------------------------------------
func runRuntimeList(cmd *cobra.Command, _ []string) error {
client, err := newAPIClient(cmd)
diff --git a/server/cmd/multica/cmd_runtime_profile.go b/server/cmd/multica/cmd_runtime_profile.go
index 3c268f3ce7..7d29f099ac 100644
--- a/server/cmd/multica/cmd_runtime_profile.go
+++ b/server/cmd/multica/cmd_runtime_profile.go
@@ -16,7 +16,6 @@ import (
"github.com/multica-ai/multica/server/pkg/agent"
)
-// ---------------------------------------------------------------------------
// `multica runtime profile ...` — custom runtime profiles (MUL-3284)
//
// A runtime profile lets a workspace declare a custom agent runtime built on
@@ -30,7 +29,6 @@ import (
// config so the daemon can launch a profile whose command isn't on PATH (or
// pick a specific install among several). That mapping never leaves the
// machine — it is not sent to the server.
-// ---------------------------------------------------------------------------
var runtimeProfileCmd = &cobra.Command{
Use: "profile",
diff --git a/server/cmd/multica/cmd_skill.go b/server/cmd/multica/cmd_skill.go
index dd4c134c1b..5073368114 100644
--- a/server/cmd/multica/cmd_skill.go
+++ b/server/cmd/multica/cmd_skill.go
@@ -172,9 +172,7 @@ func init() {
skillFilesUpsertCmd.Flags().String("output", "json", "Output format: table or json")
}
-// ---------------------------------------------------------------------------
// Skill commands
-// ---------------------------------------------------------------------------
// newSkillAPIClient is newAPIClient with the transport swapped for the
// stall-aware one (see internal/cli/stall.go). Skill payloads are the largest
@@ -679,9 +677,7 @@ func runSkillSearch(cmd *cobra.Command, args []string) error {
return nil
}
-// ---------------------------------------------------------------------------
// Skill file subcommands
-// ---------------------------------------------------------------------------
func runSkillFilesList(cmd *cobra.Command, args []string) error {
client, err := newSkillAPIClient(cmd)
diff --git a/server/internal/analytics/client.go b/server/internal/analytics/client.go
index 7e011c65d2..c044f04b2a 100644
--- a/server/internal/analytics/client.go
+++ b/server/internal/analytics/client.go
@@ -1,15 +1,9 @@
-// Package analytics ships product telemetry events to an external analytics
-// backend (PostHog). Events feed the acquisition → activation → expansion
-// funnel — see events.go for the event contract.
+// Package analytics provides a buffered PostHog client.
+// Product events go through metrics.RecordEvent; current server events are
+// metrics-only. The client remains available for non-metrics-only events.
//
-// Design:
-// - Capture is non-blocking. Request handlers must never wait on analytics
-// network I/O, so we enqueue into a bounded channel and a background
-// worker flushes to PostHog in batches.
-// - When the queue is full events are dropped (and counted). A broken
-// analytics backend must never degrade the product.
-// - When POSTHOG_API_KEY is empty the package runs a no-op client, which
-// keeps local dev and self-hosted instances friction-free.
+// Capture never blocks request handlers: a bounded queue drops excess events,
+// and a worker sends batches. Empty POSTHOG_API_KEY selects a no-op client.
package analytics
import (
diff --git a/server/internal/attribution/attribution.go b/server/internal/attribution/attribution.go
index 18c493891f..c1e834212a 100644
--- a/server/internal/attribution/attribution.go
+++ b/server/internal/attribution/attribution.go
@@ -471,58 +471,16 @@ type SubscriptionFacts struct {
OriginRootSource Source
}
-// DelegatedSubscriber resolves the human who should be auto-subscribed to an
-// agent-created issue, and the reason label to record.
+// DelegatedSubscriber resolves a directly requesting human for subscription.
+// Use the originator copied through delegation, but require proof that the chain
+// began with SourceDirectHuman. A schedule/webhook's authorization principal is
+// not a request to receive notifications. Unproven roots, degraded attribution,
+// and autopilot-origin issues receive no inferred subscription.
//
-// It deliberately mirrors ClassifyDirect's origin branch rather than inventing
-// a second notion of "whose behalf is this" — the whole defect this fixes was
-// attribution and notification disagreeing about that (MUL-5483). The waterfall
-// is narrower than ClassifyDirect's on purpose:
-//
-// - OriginOriginator valid AND the chain root is a DIRECT human act →
-// subscribe. Because attribution COPIES the accountable human across every
-// agent hop rather than chaining it (see SourceDelegation), the originator
-// resolves the ORIGINAL human at any depth, and the delivery tier — not a
-// depth cutoff — is what bounds the noise a deep chain makes. The root check
-// is what keeps "has a human" from being read as "a human asked", see below.
-//
-// WHO the human is therefore has no depth limit; proving the chain BEGAN
-// with them does: the caller reads the root by walking the lineage, and that
-// walk stops after 32 hops (GetDelegatedSubscriptionFacts). Past that the
-// root is reported as unproven and nobody is subscribed, which is a real
-// truncation and not a formality — accepted deliberately (MUL-7051, Bohan's
-// call) because no observed chain approaches it. Raising it is a one-number
-// change; moving the root onto the run at enqueue time would remove the
-// limit outright.
-//
-// - quick_create → reason 'creator', agent_create → reason 'delegated'. The
-// quick-create human asked for THAT issue by name, so it is direct intent and
-// keeps full notifications; an agent_create child is the agent's own decision
-// made under a broader mandate, so it takes the reduced delegated tier.
-//
-// - Anything else → no subscription. Notably origin_type='autopilot' is
-// excluded: an autopilot already has an explicitly configured
-// autopilot_subscriber template, and that list — not the member who happened
-// to arm the trigger — is the intended audience for its issues. Degraded
-// attribution (owner_fallback / unattributed) is excluded for the same
-// reason it is degraded: we do not fabricate a human to notify.
-//
-// WHY the root source is checked at all (MUL-7051). This rule was written when
-// SourceDirectHuman was the only root that left an originator behind, so "the
-// origin run carries a human" and "a human asked for this work" were the same
-// statement and only the first had to be tested. MUL-6951 separated them: an
-// armed schedule/webhook trigger now runs with its created_by principal's
-// authorization (SourceTriggerOwner), and that human is copied down the whole
-// chain exactly like a requester would be. The untested half of the old
-// equivalence is what broke — every issue an autopilot's agent filed started
-// subscribing whoever armed the trigger, which is the case the
-// origin_type='autopilot' exclusion above already says must not happen, arriving
-// one hop lower.
-//
-// So the condition is stated as what it means — the chain BEGAN with a member
-// acting — and it is a whitelist. A future root that resolves a human some other
-// way stays silent here until someone decides it should subscribe people, rather
-// than turning this rule on for a population nobody chose.
+// Quick-create keeps the creator tier; agent-created work uses the reduced
+// delegated tier. Lineage lookup is bounded to 32 hops; exceeding it leaves the
+// root unproven and subscribes nobody. New root-source kinds require an explicit
+// decision before they can opt people into notifications.
func DelegatedSubscriber(f SubscriptionFacts) (pgtype.UUID, string, bool) {
if f.CreatorType != "agent" || !f.OriginOriginator.Valid {
return pgtype.UUID{}, "", false
diff --git a/server/internal/daemon/agents_refresh.go b/server/internal/daemon/agents_refresh.go
index 0f709e2f0f..0b71a0f9c5 100644
--- a/server/internal/daemon/agents_refresh.go
+++ b/server/internal/daemon/agents_refresh.go
@@ -351,56 +351,18 @@ func (d *Daemon) refreshAgentAvailability() []string {
return gained
}
-// refreshAgentVersions re-probes every installed agent CLI and re-registers the
-// built-in runtimes whenever the server has not been told a version this daemon
-// has already detected, so what the server reports matches what is on disk.
-//
-// This is the agent-CLI counterpart to trySelfReload, and it deliberately does
-// NOT restart. What a user needs when codex or claude upgrades is that
-// subsequent tasks run the new CLI under the new version's rules — not that
-// Multica's availability tracks a third party's release cadence. An in-place
-// POSIX upgrade changes the binary behind the pinned path; a Windows installer
-// upgrade retargets the stable junction resolved by resolveAgentEntry. The two
-// things left stale are the cached version (which keys version-sensitive policy
-// such as the Codex sandbox) and the version the server displays. Both are
-// refreshed here with running tasks untouched.
-//
-// detectBuiltinRuntimes does the probing, which buys three properties for free:
-// probes fan out, a fast failure is retried (runtimeVersionProbeAttempts), and
-// the minimum-version gate still applies. A provider whose probe fails this
-// round keeps its previous version and is retried next round — a failed probe
-// never looks like a version change.
-//
-// What to send is decided per WORKSPACE, from workspaceState.builtinVersions —
-// the versions the last register call the server accepted for that workspace
-// actually carried — never from a before/after diff of the shared version
-// cache. The cache is written by every path that probes, so a diff only sees a
-// change when this round happens to be the first writer: a converge round, a
-// new workspace registering, or a self-heal at task launch will all move it
-// first and leave this round seeing nothing to do — while the workspaces those
-// paths did not touch keep the old version indefinitely.
-//
-// The acknowledgement is per-workspace rather than a global pending set for
-// the same reason in reverse: registration entry points are not serialized, so
-// a register that probed BEFORE an upgrade can land AFTER a refresh round has
-// updated every workspace it could see. A global "done" flag cleared at that
-// moment would strand the late workspace on the old version forever. Scoped to
-// the workspace, the late-landing call simply records what it sent, the record
-// disagrees with the next probe round, and that round re-registers exactly the
-// workspace that fell behind.
-//
-// Re-registration carries the whole built-in set because that is the shape the
-// register endpoint upserts, so one provider's upgrade re-sends its neighbours
-// too. That is safe rather than disruptive: the unchanged entries upsert
-// identically, and mergeBuiltinRegisterResponse swaps a server-side ID rotation
-// in place instead of accumulating a duplicate — the workspace still holds
-// exactly one runtime per provider, and no running task is touched.
-// This runs unconditionally rather than yielding when the converge half has
-// work to do, even though the two occasionally probe in the same window. A
-// provider that is permanently below the minimum supported version never leaves
-// providersMissingRuntimes — that is by design, so it recovers on its own after
-// an upgrade — so yielding to it would let one stuck CLI silently disable version
-// refresh for every healthy provider on the machine, forever.
+// refreshAgentVersions re-probes installed CLIs and re-registers workspaces
+// whose last acknowledged versions differ, without restarting running tasks.
+// Failed probes retain previous values and retry on a later round.
+//
+// Compare against each workspace's accepted registration, not the shared version
+// cache: another probe path may update that cache first, and an older registration
+// may arrive after a refresh. Per-workspace acknowledgements let the next round
+// repair either ordering.
+//
+// Send the full built-in set and reconcile IDs in place. Run even when runtime
+// convergence has pending providers so one below-minimum CLI cannot starve version
+// updates for healthy providers.
func (d *Daemon) refreshAgentVersions(ctx context.Context) {
// Nothing has ever been version-detected: the daemon is still starting up,
// and initial registration is the sync path's job.
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index afe090d253..39af184c71 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -977,47 +977,16 @@ type healedAgent struct {
version string
}
-// resolveAgentEntry returns entry with a usable executable path plus the CLI
-// version that corresponds to that path. It resolves retargetable Windows
-// installer junctions per launch and self-heals vanished pinned paths on other
-// platforms (MUL-4486).
-//
-// The daemon pins each agent's discovered entry point at startup so a later
-// PATH change cannot redirect a task launch. POSIX discovery also resolves
-// symlinks to a concrete path. But a version manager
-// (Homebrew Cask, nvm/fnm) upgrading in place deletes the old versioned
-// directory that pinned path points into and repoints the stable command name
-// at the new version — leaving the daemon holding a path that no longer exists
-// until it restarts. Every consumer of entry.Path (task launch, model listing,
-// version detection at registration) then hard-fails with "executable not
-// found".
-//
-// The returned version always matches the returned path, so callers key
-// version-sensitive policy (e.g. the Codex sandbox) off it directly rather than
-// re-reading the shared version cache, which a concurrent heal could still be
-// updating.
-//
-// Behaviour:
-// - A Windows stable entry point -> its final target is verified and returned
-// with the detected version; a retarget publishes the new pair atomically.
-// - A previous self-heal that is still live -> returned with its paired
-// version. This is checked first so that once we've re-resolved to a new
-// binary, a reappearing stale path (a downgrade / reinstall recreating the
-// old versioned directory) cannot re-pair that old binary with the healed
-// version — a mismatched {old path, new version} (MUL-4486 review).
-// - Otherwise, pinned Path still present -> returned unchanged, paired with
-// its registration-detected version. The anti-redirect guarantee holds for
-// the normal (never-healed) case: a live pinned binary is never
-// second-guessed even if PATH now points elsewhere.
-// - Pinned Path gone and no live heal -> re-resolve entry.Command once
-// (preserving the ~/.multica/hooks exclusion and the login-shell fallback).
-// Before adopting the re-resolved binary it is version-detected and run
-// through the same minimum-version gate registration applies. This
-// reproduces exactly what a daemon restart would resolve, so it is no less
-// safe than the documented restart workaround — only automatic.
-// - Re-resolution fails, the candidate can't be version-detected, or it is
-// below the minimum supported version -> entry is returned unchanged so the
-// candidate is never launched and the downstream error still surfaces.
+// resolveAgentEntry returns a usable executable and its matching version.
+// Resolve retargetable Windows junctions per launch. Prefer an existing healed
+// path over a reappearing old path; otherwise keep a live pinned path even when
+// PATH changes, so task launches cannot be redirected incidentally.
+//
+// If the pinned path vanished, rediscover the command with the normal hooks
+// exclusion and login-shell fallback. Adopt only a version-detectable candidate
+// meeting the registration minimum. Failed recovery returns the original entry
+// so the launch error remains visible. Callers use the paired version rather
+// than a shared cache another recovery may be updating.
func (d *Daemon) resolveAgentEntry(ctx context.Context, provider string, entry AgentEntry) (AgentEntry, string) {
resolved, version, _ := d.resolveAgentEntryWithHeal(ctx, provider, entry)
return resolved, version
@@ -1480,58 +1449,15 @@ func (d *Daemon) workspaceNeedsRuntimeRecovery(workspaceID string) bool {
return len(ws.runtimeIDs) == 0
}
-// reregisterWorkspaceAfterRuntimeGone calls registerRuntimesForWorkspace and
-// updates the existing workspaceState in place. The register response is
-// authoritative for this workspace's runtime set — every configured provider
-// is included, with UpsertAgentRuntime returning the same row ID for surviving
-// providers and a fresh ID for any that were deleted server-side. Replacing
-// (rather than appending) is required: a partial recovery, where only one
-// runtime in a multi-provider workspace was deleted, would otherwise produce
-// duplicates for every provider that wasn't deleted.
-//
-// The workspaceState pointer is NEVER replaced (see syncWorkspacesFromAPI's
-// invariant about repoRefreshMu). Only fields are mutated.
-// applyRegisterResponseInPlace folds a fresh /api/daemon/register response
-// back into the workspaceState and runtimeIndex without replacing the
-// workspaceState pointer (see syncWorkspacesFromAPI's invariant about
-// repoRefreshMu). It is the shared converger used by both the runtime_gone
-// recovery and the profile-drift refresh; the two callers differ only in
-// follow-up side effects (RecoverOrphans / Deregister), so those stay at the
-// call site.
-//
-// Returns:
-// - newIDs: the runtime IDs the server returned in this response, in
-// the order they were returned. These are the daemon's authoritative
-// current runtime set after the call.
-// - droppedIDs: runtime IDs that were tracked before this call but did
-// NOT survive the response. Callers Deregister these so the server marks
-// them offline immediately instead of waiting on the 150 s
-// stale-heartbeat sweep. On the runtime_gone path the triggering row was
-// already deleted server-side (and pruned locally before the register),
-// but a SIBLING dropped here — e.g. a provider removed from the daemon's
-// config, or a disabled profile — still has a live server row that must be
-// deregistered.
-// - ok: false when the workspace was forgotten between the
-// register call and this apply (e.g. the user left the workspace and
-// syncWorkspacesFromAPI removed it). The caller must abort silently in
-// that case — there is no state left to update.
-//
-// profileSig is the digest captured during the register; an empty value is
-// the explicit "fetch failed, keep the previous signature" sentinel from
-// appendProfileRuntimes.
-//
-// preserveProviders lists the built-in providers this response is not
-// authoritative about, keyed by provider — see preserveProvidersFromProbe. Their
-// entries are absent from the payload, and therefore from the response, either
-// because the probe failed (transient) or because they were confirmed
-// below-minimum by a path with no authority to demote. Either way, dropping
-// their rows here would take a runtime offline outside the one path that does it
-// safely, so their existing built-in runtime rows are kept instead.
-//
-// A provider already under a demotion hold is a different case and is still
-// rejected below: that verdict was reached by demoteBelowMinimumRuntimes, which
-// removed the rows under the claim barrier, and this response merely predates
-// it.
+// applyRegisterResponseInPlace reconciles the authoritative runtime response
+// without replacing workspaceState, whose mutexes are shared with other callers.
+// Return current IDs, dropped IDs to deregister, and false if the workspace has
+// been forgotten while registration was in flight.
+//
+// An empty profileSig keeps the previous signature. preserveProviders retains
+// built-in rows omitted by failed or non-authoritative probes; a confirmed demotion
+// still wins over a response sent before the demotion. Callers own recovery and
+// deregistration side effects.
func (d *Daemon) applyRegisterResponseInPlace(workspaceID string, resp *RegisterResponse, profileSig string, preserveProviders map[string]string) (newIDs, droppedIDs []string, ok bool) {
d.mu.Lock()
defer d.mu.Unlock()
@@ -2763,49 +2689,14 @@ probeLoop:
return "", reason, builtinProbeUnavailable
}
-// detectBuiltinRuntimes version-detects every configured built-in agent CLI and
-// returns a registration entry for each one that resolves and clears the
-// minimum-version gate. Probes run concurrently, bounded by
-// runtimeVersionProbeConcurrency.
-//
-// The previous implementation probed serially, so total latency was the SUM of
-// every CLI's `--version` call. On an onboarding host with several coding tools
-// installed that stacked into many seconds of dead time before the daemon could
-// register — long enough that the desktop runtime step timed out into its empty
-// "no runtime found" state while the probes were still running (MUL-5119).
-// Fanning the probes out makes total latency track the SLOWEST single probe
-// instead of their sum, so a freshly-created workspace lights up its runtimes
-// well inside the UI's scanning window.
-//
-// Each probe still self-heals a vanished pinned path (MUL-4486) and re-detects
-// the live version — nothing is cached on the Daemon, so an in-place CLI
-// upgrade is still reported with its current version. A provider whose version
-// stays undetectable across probeBuiltinRuntime's bounded attempts, or which is
-// below the minimum supported version, is logged and skipped, exactly as the
-// serial loop did.
-//
-// The result describes the machine, not a workspace, so a caller registering a
-// batch of workspaces at once calls this ONCE and passes the payload to
-// registerRuntimesForWorkspaceBatch for each workspace (MUL-5225).
-//
-// The second return value is THIS round's confirmed verdicts, provider to the
-// evidence against it. It is returned rather than read back
-// out of skippedAgents because that pair is a diagnostic snapshot of whichever
-// round published last: four different goroutines call this (the discovery
-// loop, the workspace sync, a runtime_gone re-register, a profile drift
-// refresh), so a caller acting on the shared copy can act on someone else's
-// probe — and demoting a runtime is not a decision to make on another round's
-// evidence.
-//
-// The third return value is THIS round's unavailable providers (version could
-// not be read), provider to reason. Callers that treat a register response as
-// AUTHORITATIVE for a workspace's whole runtime set (the runtime_gone recovery
-// and the profile drift refresh, via applyRegisterResponseInPlace) must
-// preserve these providers' existing runtimes: they are absent from the
-// payload because the probe failed, which is transient — tearing a working
-// runtime down over it is exactly what the unavailable/below-minimum verdict
-// split exists to prevent. demotableBuiltinProbeVerdict is the list of verdicts
-// that may demote.
+// detectBuiltinRuntimes probes configured CLIs with bounded concurrency and
+// returns registration entries that resolve and meet minimum versions. Reuse a
+// single probe result when registering several workspaces.
+//
+// Return this round's confirmed demotion evidence and unavailable-provider reasons
+// separately. Shared diagnostic snapshots may belong to another concurrent probe.
+// Authoritative reconciliation must preserve unavailable providers' existing rows;
+// a transient probe failure is not evidence that a runtime should be demoted.
func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) ([]map[string]string, map[string]runtimeVerdict, map[string]string) {
type detected struct {
name string
diff --git a/server/internal/daemon/execenv/codex_memory.go b/server/internal/daemon/execenv/codex_memory.go
index 494462cfb9..76375509bc 100644
--- a/server/internal/daemon/execenv/codex_memory.go
+++ b/server/internal/daemon/execenv/codex_memory.go
@@ -8,61 +8,13 @@ import (
"strings"
)
-// Background
+// Disable native Codex memory in task-local configuration by default to keep
+// host or previous-task memories from crossing workspace boundaries. The user's
+// global configuration is untouched; MULTICA_CODEX_MEMORY opts into native memory.
//
-// Codex CLI ships a native auto-memory subsystem: by default it writes
-// summaries of agent turns to `$CODEX_HOME/memories/raw_memories.md`
-// plus `state_*.sqlite`, and reads them back into the model context on
-// the next turn. The decision of what gets written is internal to Codex
-// — users cannot audit or edit the contents from any Multica UI.
-//
-// This conflicts with the Multica daemon's context model. Multica
-// already keeps per-(agent, issue) state via PriorSessionID, the issue
-// description / comments, issue metadata, and CLAUDE.md skill memory —
-// each channel is explicit, user-visible, and editable. Layering Codex
-// native memory on top introduces an opaque, daemon-uncontrolled second
-// store that can leak across tasks and (worse) across workspaces:
-//
-// - Per-task `codex-home/memories/` is preserved across `Reuse()` and
-// is never cleared by `prepareCodexHomeWithOpts`, so stale memories
-// from a prior turn on the same (agent, issue) feed into the next.
-// - Codex CLI may also read user-level state from `~/.codex/memories/`
-// entirely outside the daemon's per-task isolation, dragging
-// unrelated host-project context into Multica tasks. The reproduction
-// in github.com/multica-ai/multica#3130 saw Raw Memories from
-// `D:\Project\MoHaYu\WowChat` (a host-local project) injected into a
-// brand-new Multica issue's first Codex turn.
-//
-// Mitigation: write a managed block into the per-task `config.toml` that
-// disables both the `features.memories` flag and the `memories.*`
-// generation/consumption switches. Codex then neither writes nor reads
-// from its memory subsystem, eliminating both leak paths regardless of
-// where the residual files sit on disk. The user's global
-// `~/.codex/config.toml` is never modified.
-//
-// Users who explicitly want Codex native memory inside a Multica task
-// (and accept the leak risk) can keep the feature enabled by setting
-// `MULTICA_CODEX_MEMORY=1` in the daemon environment. The long-term
-// answer for durable agent context is a Multica-owned, user-visible,
-// project- or issue-scoped memory store — not re-enabling Codex's
-// hidden auto-memory.
-//
-// Layout note
-//
-// TOML rejects redefining a table that has already been created —
-// including implicitly via a dotted key — so the managed block must
-// adapt to the user's existing config. Two independent managed blocks
-// are written:
-//
-// 1. memory-feature: disables `features.memories`. If the user's
-// config contains a top-level `[features]` table, the override is
-// injected inside that table; otherwise it goes at the file root
-// in dotted-key form.
-// 2. memory-config: disables `memories.generate_memories` and
-// `memories.use_memories`. If the user's config contains a
-// top-level `[memories]` table, the overrides are injected inside
-// that table; otherwise they go at the file root in dotted-key
-// form.
+// Write separate feature and memory switches. Insert overrides inside existing
+// TOML tables when present; dotted keys at the root would otherwise redefine
+// tables, including tables created implicitly by earlier dotted keys.
// MulticaCodexMemoryEnv is the env var users can set to keep Codex
// native memory enabled inside daemon-managed tasks. Anything truthy
diff --git a/server/internal/daemon/execenv/hermes_home.go b/server/internal/daemon/execenv/hermes_home.go
index 3002a93a18..3a91da528e 100644
--- a/server/internal/daemon/execenv/hermes_home.go
+++ b/server/internal/daemon/execenv/hermes_home.go
@@ -14,55 +14,20 @@ import (
"github.com/multica-ai/multica/server/internal/util"
)
-// Hermes discovers skills from exactly two places (verified against the bundled
-// Hermes agent source, agent/skill_utils.py get_all_skills_dirs): its home
-// skills dir `<HERMES_HOME>/skills/` first, then the directories listed under
-// `skills.external_dirs` in `<HERMES_HOME>/config.yaml`, in config order. It has
-// NO workspace-relative discovery, so the generic `.agent_context/skills/`
-// fallback the daemon used before was never scanned and workspace-assigned
-// skills silently never took effect (issue #5242).
+// Hermes discovers skills in HERMES_HOME/skills before skills.external_dirs;
+// it does not scan the task workspace. Bound skills therefore use a task-local
+// home overlay, while skill-less tasks keep the original home.
//
-// Rather than replace HERMES_HOME with a home rebuilt from a fixed allowlist —
-// which would silently change behavior for tasks that don't even use skills and
-// would drop any home state not on the list (plugins, OAuth state, hooks, SOUL,
-// scripts, and whatever Hermes adds next) — this builds a minimal compatibility
-// overlay, and only when the agent actually has skills bound (gated at the call
-// site in Prepare/Reuse; a skill-less Hermes task keeps HERMES_HOME untouched).
+// Mirror host-home entries except task-owned overrides. The local skills directory
+// contains bound skills; external_dirs preserves shared skills and configured
+// directories normalized against the original home and effective environment.
//
-// The overlay:
-// - mirrors every top-level entry of the shared ~/.hermes/ into the per-task
-// home via symlink, EXCEPT the entries it overrides — so the denylist stays
-// tiny and future home state is inherited automatically instead of being
-// missed by an allowlist;
-// - derives a task-local config.yaml whose `skills.external_dirs` points at
-// the shared skills dir plus the user's existing external_dirs, expanded
-// against the agent's effective env and normalized to absolute paths (Hermes
-// resolves relative external_dirs against HERMES_HOME, so leaving them
-// relative after the redirect would silently repoint them) — this exposes
-// the user's global/builtin skills read-only without copying them;
-// - populates the task-local `skills/` dir with ONLY the Multica-bound skills,
-// which take precedence because Hermes lists the home skills dir first;
-// - keeps `memories/` overlay-owned, NOT symlinked to the shared home: Hermes
-// loads and writes back MEMORY.md/USER.md there, and per-agent memory is a
-// Multica product concern — the host's local Hermes memory must not bleed
-// into a task, nor task memory back out to the host. The overlay links it to
-// the agent's persistent store so it survives across tasks and issues
-// (hermes_memory.go); it is a fresh per-task dir only when no store applies;
-// - keeps the state.db SQLite session store and its journal sidecars
-// overlay-owned: the host's conversation history is never linked or copied.
-// state.db is then linked to the conversation's own persistent store
-// (hermes_sessions.go) so a multi-turn conversation survives the task; it
-// stays a task-local file only when there is no store to key on, or on a
-// host that cannot create the link;
-// - disables the external `memory.provider` in the derived config so a
-// host-configured Supermemory/Hindsight/etc. backend isn't shared across
-// tasks. This is the on-disk + external-backend memory isolation; a managed,
-// agent-scoped memory backend is a separate future product decision.
+// Keep memories, state.db and its journals overlay-owned, using agent-scoped
+// memory and conversation-scoped session stores when available. Disable external
+// memory providers to prevent cross-task sharing.
//
-// The shared ~/.hermes/ is never modified by this setup. Note however that
-// mirrored entries are writable symlinks, so if Hermes writes through one at
-// runtime (e.g. refreshing token state under a mirrored auth/OAuth path) that
-// write does reach the shared home — that propagation is intentional.
+// Setup does not modify the shared home. Mirrored auth and other entries remain
+// writable symlinks, so runtime updates through them intentionally reach the host.
// hermesOverriddenEntries are the fixed top-level entries of the shared
// ~/.hermes/ that the overlay supplies its own task-local version of, so they
diff --git a/server/internal/daemon/execenv/hermes_memory.go b/server/internal/daemon/execenv/hermes_memory.go
index b8a326670f..104df3af77 100644
--- a/server/internal/daemon/execenv/hermes_memory.go
+++ b/server/internal/daemon/execenv/hermes_memory.go
@@ -14,52 +14,13 @@ import (
"github.com/multica-ai/multica/server/internal/cli"
)
-// Background
+// Agent/profile-scoped Hermes memory lives under hermes-state and is linked
+// into the task home overlay. It survives tasks and issues without sharing the
+// host's memories or another agent's files. Different Hermes profiles use separate
+// stores. Session databases have their own conversation scope in hermes_sessions.go.
//
-// Hermes keeps its long-term memory (MEMORY.md / USER.md and whatever else the
-// agent writes back) in `<HERMES_HOME>/memories/`. Multica has to take over
-// HERMES_HOME to inject an agent's bound skills — Hermes discovers skills only
-// from its own home, never from the workspace (see hermes_home.go) — so the
-// overlay inherited the decision of where memory lives and made it task-local.
-//
-// Nobody designed the two behaviours that produced (issue #6638):
-//
-// - An agent WITH skills bound got a fresh memories/ per task, so it forgot
-// everything between tasks. Users read that as "Hermes 失忆", and it changed
-// the moment they bound an unrelated skill, with no UI signal.
-// - An agent with NO skills bound built no overlay at all, ran against the
-// user's real ~/.hermes, and therefore shared one memories/ with every
-// other skill-less agent, task, and issue on the runtime.
-//
-// This file makes memory an agent-scoped store Multica owns:
-//
-// <multica profile dir>/hermes-state/<agent>/<hermes profile>/memories
-//
-// linked into the per-task overlay. Memory then survives across tasks and issues
-// for the same agent, never touches the user's home, and is invisible to other
-// agents. The shape is deliberately identical to the per-issue Codex session
-// store (codex_home.go) and the per-agent Reasonix state home — same lifecycle,
-// same GC, same active-store guard.
-//
-// Scoping to (hermes profile, agent) rather than agent alone mirrors Hermes' own
-// model, where a profile is an isolated instance: pointing an agent at a
-// different profile gives it a different identity, so it gets a different memory
-// line. Same semantics as the Codex store keying on (profile, agent, issue).
-//
-// Deliberately NOT covered here:
-//
-// - The session database (state.db and its WAL sidecars) stays task-local.
-// Sharing a live SQLite database between one agent's concurrent tasks needs
-// lock and consistency work — plus Windows byte-range locks on -shm — that
-// plain memory files do not. Users get "remembers the agreements", not
-// "remembers the transcript".
-// - Skill-less Hermes agents still run against the host home unchanged.
-// Tightening that would break the only workaround #6638's reporter has, and
-// it belongs with the platform-wide memory_scope work (MUL-5969).
-//
-// Known trade-off, shared with the host-passthrough behaviour it replaces: one
-// agent's concurrent tasks write the same files and Hermes rewrites them whole,
-// so concurrent memory updates are last-writer-wins.
+// Skill-less agents still use the host home without this overlay. Concurrent tasks
+// of the same agent may overwrite memory files; updates remain last-writer-wins.
// hermesMemoryStoreRoot is the directory under the daemon's Multica profile dir
// that holds every agent's persistent Hermes state. `hermes-state` (not
diff --git a/server/internal/daemon/execenv/hermes_sessions.go b/server/internal/daemon/execenv/hermes_sessions.go
index 98f55be6bb..22e334fc8c 100644
--- a/server/internal/daemon/execenv/hermes_sessions.go
+++ b/server/internal/daemon/execenv/hermes_sessions.go
@@ -11,49 +11,15 @@ import (
"github.com/multica-ai/multica/server/internal/cli"
)
-// Background
+// Persist Hermes ACP session databases by agent, profile, and conversation under
+// hermes-sessions. Tasks for one conversation are serialized; separate conversations
+// get separate SQLite databases. This keeps resumable transcripts across task homes
+// without sharing a live database among an agent's concurrent issues.
//
-// Hermes persists every ACP session — the actual conversation transcript — in
-// the SQLite database at `<HERMES_HOME>/state.db` (acp_adapter/session.py).
-// Because Multica has to take over HERMES_HOME to inject bound skills, that
-// database landed inside the per-task overlay, which made a Hermes agent's
-// conversation last exactly one task.
-//
-// The failure was silent, which is what made it expensive. `session/resume`
-// against a database that does not hold the session does not fail: Hermes
-// creates a fresh session and answers with an ordinary success frame
-// (acp_adapter/server.py resume_session), so the daemon believed it had
-// resumed, re-sent the same dead id on every later turn, and the user saw a
-// conversation that restarted from zero with nothing in the logs (GH #6806).
-// The backend now detects that rebind (resolveHermesResumedSessionID), and
-// this file removes the cause.
-//
-// The store is keyed by (agent, hermes profile, conversation):
-//
-// <multica profile dir>/hermes-sessions/<agent>/<hermes profile>/<conversation>/state.db
-//
-// Keying to the conversation — the issue, or `chat_<id>` for a chat session —
-// is what makes this safe to share where #6693 could not. Its stated reason
-// for leaving state.db task-local was concurrency: one agent's parallel tasks
-// would write one live SQLite database, which needs lock and consistency work
-// (plus Windows byte-range locks on `-shm`) that plain memory files do not.
-// Tasks of the SAME conversation are serial by construction — a follow-up is
-// dispatched after its predecessor reports — so the shard has one writer at a
-// time, while two different issues get two different databases and never meet.
-//
-// The (agent, profile) prefix matches the memory store's scoping exactly, so
-// pointing an agent at another Hermes profile gives it a fresh conversation
-// line just as it gives it a fresh memory line. It is a sibling root rather
-// than a subdirectory of `hermes-state/<agent>/<profile>` because that
-// directory IS the agent's memories dir (the overlay links `memories/`
-// straight at it), so nesting sessions inside it would surface them to Hermes
-// as a memory entry.
-//
-// The overlay mounts the shard by symlinking `<overlay>/state.db` at
-// `<store>/state.db`. SQLite resolves the link when it derives the `-wal` and
-// `-shm` paths, so the journal sidecars are created in the store next to the
-// database rather than in the task directory, and a task teardown can never
-// take the write-ahead log with it.
+// Keep session storage outside the memories root. Link overlay/state.db to the
+// store so SQLite places WAL and SHM sidecars beside the persistent database and
+// task teardown cannot remove them. Detect provider session-ID rebinding when a
+// requested session is absent.
// hermesSessionStoreRoot is the directory under the daemon's Multica profile
// dir that holds every agent's persistent Hermes conversation shards.
diff --git a/server/internal/daemon/execenv/openclaw_config.go b/server/internal/daemon/execenv/openclaw_config.go
index 7b955c9754..58b2269982 100644
--- a/server/internal/daemon/execenv/openclaw_config.go
+++ b/server/internal/daemon/execenv/openclaw_config.go
@@ -47,57 +47,14 @@ const openclawMcpResetFile = "openclaw-mcp-reset.json"
// literal is the form a reader can check against the design in one glance.
const openclawMcpResetBody = "{\n \"mcp\": {\n \"servers\": null\n }\n}\n"
-// openclawCLITimeout is the default context deadline set on each
-// `openclaw config ...` invocation during task setup.
-//
-// It used to be 5s, on the assumption that the CLI answers in <200ms and 5s is
-// pure cold-start headroom. Field data (#7112) retired that assumption: on a
-// 2020 Intel MacBook Pro, `openclaw config file` takes 8.4–10.9s and
-// `config get agents.list --json` 4.3s, every time — so the runtime was
-// unusable on that host, with no user-side way to raise the limit. For scale,
-// the same commands take 0.7s / 0.3s on an M-series Mac, i.e. the real spread
-// across supported hardware is wider than the old margin.
-//
-// 30s is ~3x the slowest measured call, and even the worst case
-// (openclawMaxCLIDeadlinesPerPreparation serial steps at that budget) fits
-// inside the outer 5-minute task preparation deadline, so a genuinely hung CLI
-// fails with this specific, actionable reason instead of the generic prepare
-// timeout. Hosts outside that envelope can override with
-// MULTICA_OPENCLAW_CLI_TIMEOUT (or backends.openclaw.cli_timeout in the CLI
-// config, which the daemon translates into the same env var).
-//
-// The gap that used to be documented here — that this was a deadline and not a
-// cap — is closed as of MUL-5467. Keeping the measurements, because they are
-// what the fix has to hold against: CommandContext kills only the direct child,
-// and cmd.Output() blocks in Wait() until the stdout pipe closes, so a CLI that
-// leaves a descendant holding stdout ran for the descendant's lifetime.
-// Measured on linux/dash: a shim whose backgrounded child slept 6s took 6.01s
-// against a 150ms deadline. An npm shim is that shape on Windows (cmd.exe →
-// node). A cmd.WaitDelay backstop bounded the call but left the descendant
-// running (measured: returns in 2.17s with the grandchild still in state S),
-// trading a hang for a process leak, and on Unix nothing reaped it because
-// preparationProcessController.finish() is a no-op there.
-//
-// execOpenclawCLI goes through agent.RunCollectQuiet, which owns the pipes and
-// the process tree (Unix process group, Windows Job Object). Owning the pipes is
-// what makes the deadline enforceable: os/exec's own Wait cannot return while a
-// descendant holds an output pipe, so the bound has to come from somewhere else,
-// and a caller-side bound that reports failure would fail a call whose answer
-// arrived. Owning the tree is what stops the descendant becoming an orphan.
-//
-// Two limits on that claim, both deliberate:
-//
-// - "Enforceable", not "nothing survives": `openclaw-config` was measured with
-// its own PGID and SID, so on Unix no group signal reaches it. The deadline
-// holds anyway, because it is pipe ownership rather than the kill that makes
-// the call return.
-// - Returning before the CLI exits requires a completeness rule that the CLI's
-// pre-answer output cannot satisfy, which in practice means `--json` (see
-// openclawOutputComplete). Without one — `config file` as the fallback — this
-// deadline is what the call is bounded by, and reaching it is a failure. That
-// is a deliberate trade: an earlier revision judged `config file`'s stdout by
-// shape and review showed it returning a path-shaped *warning* line as the
-// answer.
+// openclawCLITimeout bounds each setup CLI call with headroom for slower hosts;
+// MULTICA_OPENCLAW_CLI_TIMEOUT overrides it. The serial call budget must fit the
+// outer preparation deadline.
+//
+// RunCollectQuiet owns pipes and process cleanup so descendants retaining stdout
+// cannot extend the call indefinitely. Unix descendants that leave the process
+// group may survive, but cannot extend the return bound. Early success requires
+// an unambiguous completeness rule; path-shaped warning output is insufficient.
const openclawCLITimeout = 30 * time.Second
// OpenclawCLITimeoutEnv overrides openclawCLITimeout. Accepts a Go duration
@@ -311,63 +268,18 @@ type OpenclawConfigResult struct {
IncludeRoot string
}
-// prepareOpenclawConfig writes a per-task OpenClaw config to envRoot and
-// returns its absolute path along with the include root the daemon must
-// grant. The daemon sets OPENCLAW_CONFIG_PATH to the path on the spawned
-// openclaw subprocess so the CLI resolves its `agents.defaults.workspace`
-// (and every `agents.list[].workspace`) to the task workdir — which is
-// what makes OpenClaw's native skill scanner pick up the per-task skills
-// we write under `<workDir>/skills/`.
+// prepareOpenclawConfig writes a per-task wrapper and returns its config path
+// and include root. OpenClaw's loader resolves JSON5, includes, and environment
+// substitution; the original config is not rewritten.
//
-// Strategy: delegate JSON5 / $include / env-substitution / state-dir
-// resolution to the openclaw CLI itself rather than re-implementing the
-// spec. We:
+// Override both the default and every agent-specific workspace so native skill
+// discovery stays in the task workdir. Host-workspace SOUL.md and MEMORY.md are
+// therefore excluded. Grant the active config's parent through OPENCLAW_INCLUDE_ROOTS
+// because OpenClaw confines cross-directory includes.
//
-// 1. Run `openclaw config file` to find the user's active config path.
-// For OpenClaw releases whose `config` command rejects the `file`
-// subcommand shape, fall back to resolving OpenClaw's active-config
-// candidates, including legacy Clawdbot/Moltbot/Moldbot locations.
-// 2. Run `openclaw config get agents.list --json` to enumerate every
-// registered agent ID with its resolved fields. The CLI parses JSON5,
-// follows $include, and substitutes ${VAR} for us.
-// 3. Write a wrapper config to envRoot/openclaw-config.json that
-// `$include`s the active path and overrides
-// `agents.defaults.workspace` plus every `agents.list[].workspace` to
-// workDir. The original config bytes are not mutated — they are loaded
-// by openclaw's own loader through the $include link, which preserves
-// comments, secrets, and nested $include chains verbatim.
-//
-// **Cross-directory $include confinement.** OpenClaw confines `$include`
-// resolution to the directory containing the wrapper file unless the
-// target's parent is listed in `OPENCLAW_INCLUDE_ROOTS`. Our wrapper lives
-// in envRoot but $includes the user's active config (typically
-// `~/.openclaw/openclaw.json`) — a cross-directory hop. We surface
-// `filepath.Dir(activePath)` as IncludeRoot so the daemon can prepend it
-// to whatever the user already has in OPENCLAW_INCLUDE_ROOTS; without
-// this, OpenClaw refuses to follow the link and the wrapper boots with no
-// user config. Fresh install emits no $include, so IncludeRoot is "".
-//
-// **Intentional task isolation.** The override of every per-agent workspace
-// is deliberate. OpenClaw's resolution order is
-// `agents.list[id].workspace → agents.defaults.workspace → ~/.openclaw/
-// workspace`. Pinning only the default would let a per-agent workspace the
-// user configured at host scope silently re-route the scanner back to the
-// shared workspace, defeating the per-task skill discovery this whole flow
-// exists for. The cost is that any per-agent SOUL.md / MEMORY.md / standing
-// orders the user laid in `<host-agent-workspace>/` are NOT visible to the
-// in-task openclaw run — task isolation wins over host carry-over. The
-// user's on-disk config is untouched; this only affects the wrapper used
-// for this single task.
-//
-// **Fail closed.** Missing openclaw binary, CLI errors, malformed CLI
-// output, or any IO error during write surfaces as an error to the caller
-// rather than degrading to a minimal config. An earlier version silently
-// synthesized a minimal config on parse failure; that masked broken user
-// configs by starting OpenClaw without the registered agents / model
-// providers / API keys it expects, which led to tasks routing to the wrong
-// agent or failing to authenticate. The only "synthesize minimal" case
-// kept is a fresh install where the CLI reports a path but no file exists
-// — there is no user data to lose in that case.
+// CLI, parse, and write failures abort preparation instead of silently losing user
+// configuration. Only a confirmed missing config permits a minimal fresh-install
+// wrapper.
func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (OpenclawConfigResult, error) {
bin := opts.OpenclawBin
if bin == "" {
@@ -400,50 +312,13 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op
return OpenclawConfigResult{}, fmt.Errorf("render openclaw mcp_config: %w", err)
}
- // **Strict replace for managed mcp_config.** When the agent has a managed
- // set, deep-merging the wrapper's `mcp.servers` against the user's active
- // config via `$include` would let user-only entries leak in (and an empty
- // managed set would not actually clear inherited servers).
- //
- // What this used to do instead was read the user's whole resolved config
- // through `config get --json` (no key path), strip `mcp.servers`, and write
- // the remainder into the task directory as a snapshot the wrapper included.
- // Two things were wrong with it, and only the first is why the task failed:
- //
- // - The read is not a valid invocation. `config get` requires a path, and
- // every channel measured on 2026-08-26 rejects the pathless form:
- // 2026.6.34 (extended-stable) exit 1 in 2.9s with
- // `Missing required argument "path".`, 2026.7.1-2 (latest) the same in
- // 3.0s, 2026.8.1-beta.3 (beta) the same as a JSON envelope in 4.4s. So
- // preparation failed for every managed-MCP task on every current channel.
- // (2026.5.27 instead wrote zero bytes and never exited within 60s;
- // #6275 made that shape fail predictably rather than hang, which is why
- // it is adjacent to this fix and not a substitute for it.)
- // - Even answered, the result is display data rather than a lossless
- // round-trip: `runConfigGet` applies `redactConfigObject`, so a sensitive
- // value comes back as the literal `__OPENCLAW_REDACTED__`. OpenClaw can
- // restore that sentinel from the original file when it writes; this daemon
- // cannot. Writing the remainder back would eventually overwrite a working
- // value with a placeholder.
- //
- // Both disappear by not reading the config at all. The wrapper includes the
- // user's live config and then a reset stage carrying exactly
- // `{"mcp":{"servers":null}}`, and its own `mcp.servers` merges over the
- // result:
+ // Replace managed MCP servers through ordered includes:
+ // live config -> mcp.servers: null -> managed servers.
//
- // live config -> mcp.servers: null -> managed servers
- //
- // The user's `mcp` siblings arrive from the live config and are never
- // observed by this process, so nothing can be lost in transit and no key this
- // daemon does not know about can be dropped or invented. OpenClaw's own
- // loader still resolves JSON5, nested includes and env substitution behind
- // the include, and no user config bytes, API keys or provider tokens are
- // written into the task directory.
- //
- // Verified against the real loader on 2026.6.34, 2026.7.1-2 and
- // 2026.8.1-beta.3: objects merge recursively, a null source replaces, and
- // sibling keys on the includer win over the include result. See
- // openclaw_mcp_real_integration_test.go.
+ // Deep merge alone would retain user-only servers, including for an empty managed
+ // set. Include the live config rather than snapshotting config-get output, which
+ // redacts secrets and cannot be round-tripped losslessly. OpenClaw's loader keeps
+ // MCP siblings, nested includes, environment substitution, and user config intact.
resetPath := ""
if hasManagedMcp && exists {
resetPath = filepath.Join(envRoot, openclawMcpResetFile)
@@ -558,48 +433,14 @@ const (
openclawAgentsSourceRegistry openclawAgentsSource = "registry"
)
-// buildPerTaskOpenclawConfig assembles the wrapper map that goes on disk.
-//
-// Exists=true: emit a $include link to the user's active config plus the
-// workspace overrides as siblings. OpenClaw deep-merges sibling object keys
-// after includes, so agents.defaults.workspace lands correctly. The
-// agents.list override is emitted as a full replacement carrying every
-// field of every resolved entry (id, model, prompts, tools, …) verbatim
-// with only `workspace` rewritten — this is robust regardless of whether
-// the runtime merges the sibling array or replaces it, because either way
-// the resulting list is shape-equivalent to the user's minus workspace. That
-// list is a lossless round-trip of the user's own file, so copying it changes
-// nothing but the one field we mean to change.
-//
-// The 2026.8+ `agents.entries.<id>` map is *not* a lossless round-trip and must
-// not be treated as one: `config get` redacts the config on its way out (a
-// sensitive value comes back as the literal `__OPENCLAW_REDACTED__`), and the
-// wrapper's sibling keys win the $include merge, so copying the resolved entry
-// would write that sentinel over the user's real secret for every task. The
-// write-back there is `workspace` alone — objects merge recursively under
-// $include, so one key per id is enough to pin the workspace and nothing else
-// is observed, copied, or dropped. See rewriteAgentsEntriesWorkspaces.
-//
-// Exists=false: a fresh install with no on-disk config. Emit a minimal
-// config containing only the workspace override. There is no user data to
-// $include here, so this is not the silent-fallback case the reviewer
-// flagged.
-//
-// resetPath, when non-empty, names the `{"mcp":{"servers":null}}` stage in
-// envRoot and is appended to the include list after the user's active config.
-// Include order is the mechanism: the user's servers are nulled after arriving
-// and before the wrapper's own `mcp.servers` merges over the result, so the
-// managed set is what resolves while every `mcp` sibling still comes straight
-// from the user's file. Empty means no managed set, in which case there is
-// nothing to enforce strictness against and the wrapper includes the active
-// path alone.
+// buildPerTaskOpenclawConfig includes the active config and pins task workspaces.
+// agents.list is replaced with resolved entries retaining every field except
+// workspace. agents.entries overrides only workspace: config-get redacts sensitive
+// fields, so copying whole entries would overwrite secrets with placeholders.
//
-// hasManagedMcp distinguishes "agent has a managed mcp_config (possibly an
-// empty set)" from "agent inherits the user's global mcp.servers". When
-// true we pin `mcp.servers` to managedMcp on the wrapper. Because the reset
-// stage has already nulled the user's server map, the resulting view of
-// `mcp.servers` is exactly the managed set — including `{}` for "admin saved
-// no servers" (mirrors `hasManagedCodexMcpConfig`).
+// For a confirmed missing config, emit only the task defaults. resetPath inserts
+// an MCP-null stage after the active config; managed servers then merge over it.
+// hasManagedMcp distinguishes an explicitly empty managed set from inheritance.
func buildPerTaskOpenclawConfig(activePath string, exists bool, resetPath string, resolvedList []any, agentsSource openclawAgentsSource, workDir string, managedMcp map[string]any, hasManagedMcp bool, gateway OpenclawGatewayPin) map[string]any {
agents := map[string]any{
"defaults": map[string]any{"workspace": workDir},
@@ -786,54 +627,14 @@ func rewriteAgentsEntriesWorkspaces(list []any, workDir string) map[string]any {
return entries
}
-// openclawActiveConfigPath discovers the path the openclaw CLI considers active.
-// Returns (absolutePath, exists, error).
-//
-// The CLI handles the full resolution chain — explicit config path, state
-// directory, OPENCLAW_HOME / default home, legacy locations, migration, and `~`
-// expansion — so we prefer it when the installed CLI supports the command.
-//
-// `config validate --json` is asked first, and `config file` is only the
-// fallback, because the two differ in whether the answer can be recognised:
-//
-// - `config validate --json` puts the path in a named `path` field of a JSON
-// document, and its stdout is that document and nothing else. Measured on
-// OpenClaw 2026.7.1-2 with a warning-producing config: 715 bytes, one line,
-// parseable whole. The Doctor and plugin warnings do not disappear — they
-// arrive as a `warnings` array *inside* the payload, which is what keeps the
-// stream parseable rather than merely quieter. (Upstream also has a
-// console-log reroute for `--json` argv, `withConsoleLogsRoutedToStderrForJson`,
-// but the structured payload is what was observed doing the work here.)
-// - `config file` prints the path as its *last line*, after any Doctor and
-// plugin warnings, on stdout. Deciding "is the answer in yet" then means
-// asking whether the last line looks like a path — and a warning line that
-// names one is indistinguishable. Review demonstrated it: a stub printing an
-// existing `plugin-cache.json` path, then pausing, then printing the real
-// path had the warning accepted as the answer.
-//
-// Both commands perform the same `readConfigFileSnapshot()` read upstream
-// (checked at `v2026.7.1`: `runConfigFile` prints `shortenHomePath(snapshot.path)`
-// and `runConfigValidate` reports `snapshot.path`, `snapshot.exists` and
-// `snapshot.valid` from that same snapshot), so validation is already part of the
-// read `config file` does. Measured, the JSON form is not merely no worse but
-// meaningfully cheaper: 1.65/1.66/1.65s against 6.36/4.16/4.06s for `config file`
-// over three runs each on the same host and config, which tracks the output it
-// does not have to render — 715 bytes of JSON against 2663 bytes and 28 lines of
-// warning UI.
-//
-// `config validate --json` has carried the `path` field on every branch since
-// `v2026.5.5`, which is minOpenclawVersion. Two of those branches exit non-zero —
-// a missing file and an invalid config, both with the path in the payload and
-// stderr empty — so the exit status must not be read as "no answer"; see
-// openclawValidatedConfigPath.
-//
-// OpenClaw 2026.2.x briefly rejected `openclaw config file` with the generic
-// "too many arguments for 'config'" error. For that command-shape failure only,
-// fall back to the same active-config candidate shape so task prep can still
-// continue without losing upgraded users' legacy config files.
+// openclawActiveConfigPath returns the active absolute path and its existence.
+// Prefer config validate --json: its named path field is distinguishable from
+// warnings, unlike the last-line output of config file. Missing or invalid configs
+// may still return a usable structured path with a nonzero exit status.
//
-// A reported path may use `~` or `$OPENCLAW_HOME` shorthand; we expand it so the
-// $include reference we write is unambiguously absolute.
+// Delegate config/state/home and legacy-location resolution to the CLI. Fall back
+// to active-config candidates only when the installed command shape is unsupported.
+// Expand reported home shorthand before writing an absolute include reference.
func openclawActiveConfigPath(bin string, timeout time.Duration) (string, bool, error) {
// One deadline for the question, not one per attempt. Both invocations answer
// "where is the active config", so they are a single step of preparation with
diff --git a/server/internal/daemon/execenv/reply_instructions.go b/server/internal/daemon/execenv/reply_instructions.go
index e1ae87c64e..b42251f7bc 100644
--- a/server/internal/daemon/execenv/reply_instructions.go
+++ b/server/internal/daemon/execenv/reply_instructions.go
@@ -2,58 +2,17 @@ package execenv
import "fmt"
-// BuildNewCommentsHint returns the comment-reading pointer for a run that
-// RESUMES its provider session and has new comments to catch up on. The server
-// count is ISSUE-WIDE (every thread, not just the triggering one) and excludes
-// the triggering comment itself because that body is already injected into the
-// prompt. It ships only the COUNT and the cursor — never the comment bodies —
-// so the server stays cheap and the agent pulls details on demand.
+// BuildNewCommentsHint supplies issue-wide catch-up facts and exact read commands
+// for a resumed provider session. The count excludes the injected trigger and
+// the agent's own comments; the unfiltered since read may return more rows.
//
-// The hint carries facts and this turn's exact commands: the issue-wide
-// volume and ONE read that returns exactly the comments behind it. It states
-// no modality: whether the scan runs is decided by step 2 alone, never here.
-// The earlier wording ("don't read them all blindly … only if you need context
-// from the other threads") made the same read optional that the brief calls
-// mandatory, and measured across 537 comment-triggered runs the "only if
-// needed" form meant "never": 0 of 36 non-scanning runs opened a thread the
-// prompt had not already named, against 1 in 10 of the scanning runs
-// (MUL-6984).
+// The issue-wide since read supplies the server-computed delta and satisfies the
+// workflow's scan. This hint does not make that scan optional. Keep per-run state
+// in the user message rather than the stable brief.
//
-// That wide read used to be the roots scan plus a per-thread expansion — two
-// or more calls to rediscover what the server already computed. A single
-// `--since <anchor>` with no `--thread` IS the delta: ListCommentsSinceForIssue
-// returns every comment on the issue created after the anchor, in every thread
-// and at every nesting level, with no folding, and its predicate is the same
-// `created_at > since` the server counted with (CountNewCommentsSince). It is
-// therefore a strict superset of what the scan could surface: roots-only
-// `last_activity_at` is MAX(created_at) over a thread, so any comment that
-// could move a thread's activity is already in the `--since` result. Reading
-// it satisfies step 2's scan, and the hint says so — the same rule as
-// BuildResumedCommentsHint, where a server-computed EMPTY delta answers the
-// scan (MUL-7344).
-//
-// The count and the read deliberately do not agree, and the text says so. The
-// COUNT is what the agent needs to size the catch-up, so it excludes the
-// injected trigger and the agent's own comments (CountNewCommentsSince). The
-// READ has no such filter — `--since` returns everything after the anchor —
-// and narrowing it to match would mean building a second, count-shaped query
-// for no gain. An agent that sees more rows than the number was told why.
-//
-// Known bounds of the `--since` read, unchanged by this hint: the handler caps
-// a page at 2000 comments and reports the cut in `X-Comments-Truncated`, which
-// the CLI does not surface; and `--thread` combined with `--since` drops the
-// thread root unless `--tail` is passed. The thread command below therefore
-// stays on `--tail 30`, never `--thread ... --since ...`.
-//
-// Since MUL-5377 the per-turn prompt (daemon.buildCommentPrompt) is the only
-// caller — the brief must not carry per-run routing state. The caller invokes
-// this only when the session actually resumes; a run whose resume was dropped
-// takes the cold path even though it carries a since-anchor.
-//
-// Renders nothing on cold start (no prior run → newCommentsSince empty) or when
-// there are no new comments (newCommentCount <= 0) or issueID is empty. In those
-// cases the caller falls back to BuildResumedCommentsHint (when a prior session
-// is active) or BuildColdCommentsHint.
+// The since read has a 2000-comment cap. Use tail for bounded thread reads because
+// thread+since alone may omit the root. Empty inputs render nothing, allowing
+// the caller to select resumed-empty or cold-start guidance instead.
func BuildNewCommentsHint(issueID, triggerCommentID, triggerThreadID, newCommentsSince string, newCommentCount int) string {
if newCommentCount <= 0 || newCommentsSince == "" || issueID == "" {
return ""
@@ -201,50 +160,12 @@ func activeThreadID(triggerThreadID, triggerCommentID string) string {
return triggerCommentID
}
-// BuildCommentReplyInstructions returns the canonical block telling an agent
-// how to post its reply for a comment-triggered task. Both the per-turn
-// prompt (daemon.buildCommentPrompt) and the CLAUDE.md workflow
-// (InjectRuntimeConfig) call this so the trigger comment ID and the
-// --parent value cannot drift between surfaces.
-//
-// The explicit "do not reuse --parent from previous turns" wording exists
-// because resumed Claude sessions keep prior turns' tool calls in context
-// and will otherwise copy the old --parent UUID forward.
-//
-// The template is platform-agnostic AND provider-agnostic — the failure it
-// guards against lives at the shell layer, so it cannot be scoped to one
-// provider or one OS:
-//
-// - Inline `--content "..."` lets the shell rewrite the body BEFORE the CLI
-// receives it: a backtick-wrapped token becomes a failed command
-// substitution that is silently deleted, the stored comment no longer
-// matches what the model intended, and a model that notices the mismatch
-// can retry forever (MUL-2904 / OKK-497). It also lets Codex emit literal
-// `\n` escapes inside `--content` (MUL-1467).
-// - `--content-stdin` with a HEREDOC has TWO failure modes the model cannot
-// see:
-// 1. On Windows, PowerShell 5.1's `$OutputEncoding` defaults to
-// ASCIIEncoding when piping to native commands and drops non-ASCII as
-// `?` before the bytes reach `multica.exe` (#2198 Chinese, #2236
-// Chinese, #2376 Cyrillic).
-// 2. On any host, when the model emits a multi-flag command (e.g.
-// `multica issue create --title ... --assignee-id ... --project ...`)
-// the bash heredoc/flag boundary is fragile: a `BODY \` "terminator
-// with trailing token" is not recognised as the heredoc end, so flag
-// lines after it are swallowed into the description; or a clean
-// terminator turns the trailing `--assignee ...` line into a separate
-// shell statement that fails while the create already succeeded with
-// no assignee. Both paths exit 0 with silently dropped flags. Github
-// issue #4182 documents two confirmed cases (OXY-78, OXY-76).
-//
-// The single safe path is therefore: write the body to a UTF-8 file with
-// the file-write tool, post with `--content-file`, then remove the file.
-// All flags live on one shell-token line; the body never touches the shell;
-// no heredoc boundary exists for flags to leak across. This converges with
-// the long-standing Windows path so the cross-platform template is one shape.
+// BuildCommentReplyInstructions formats this turn's reply target and file-based
+// posting command. Resumed sessions must not reuse a previous --parent value.
//
-// provider is retained for caller symmetry and future per-provider tweaks; the
-// guardrail itself is intentionally identical across providers and hosts.
+// Write UTF-8 with --content-file so shell substitution, pipeline encoding, and
+// heredoc boundaries cannot alter the body or swallow trailing flags. Cleanup
+// must depend on a successful post. The template is shared across providers.
func BuildCommentReplyInstructions(provider, issueID, triggerCommentID string, squadLeader bool) string {
if triggerCommentID == "" {
return ""
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 27fe2e4d1a..92ebda662a 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -45,58 +45,14 @@ func writeHeader(b *strings.Builder) {
b.WriteString("You are a coding agent in the Multica platform. Use the `multica` CLI to interact with the platform.\n\n")
}
-// writeBackgroundTaskSafetySlim emits the Background Task Safety section
-// in its judgment form (MUL-5442): four paragraphs — the platform fact
-// everything else derives from (turn exit is task-terminal, no wakeup
-// exists, never background-and-yield), the external-systems/CI boundary
-// with its single explicit-ask exception, and the persistent-service
-// handoff contract. The pinned anchors the tests assert are the fact,
-// each boundary, both exceptions, and the handoff triple.
-//
-// MUL-5223: the external-work boundary alone did not stop agents from
-// blocking on CI. Two holes are closed here. First, the boundary was
-// stated as a concept while the section's only concrete "how to wait"
-// example was a blocking foreground call — and `gh pr checks --watch` is
-// exactly that shape, so watching CI read as compliant. Named tool-shape
-// bans replace the inference. Second, the "unless acceptance criteria
-// require it" escape was being satisfied by the repo's own merge
-// requirements ("CI must pass before merge"), so the section now says
-// branch protection is not the agent's acceptance criterion, and gives
-// the replacement hand-off phrasing so the urge to prove quality lands
-// on local test output plus a PR link instead of on a wait.
-//
-// The ban is scoped, not absolute: an explicitly requested CI result is
-// still reachable, and it names the one executable way to collect it
-// (a single foreground blocking watch inside the same turn). Enabling
-// auto-merge is not a wait and stays allowed — only waiting for it to
-// land is banned.
-//
-// MUL-5274 adds one narrow lifetime exception: a user-requested local
-// development/test service may be handed off after its readiness and cleanup
-// contract are complete. It is not a future result or wakeup. The brief keeps
-// this separate from tests, builds, monitors, and CI polling, which remain
-// run-owned until their result is collected. The brief states only the
-// handoff contract (lifecycle independence, durable logs, cleanup handle);
-// how to detach is the Local Dev Environment skill's concern, not the brief's.
-//
-// Paragraph order: the CI exception lives INSIDE the boundary paragraph
-// (one "The one exception" occurrence, count-guarded in the tests), and the
-// persistent-service paragraph closes the section. A former scoping sentence
-// ("The rules above apply only to work owned by the current run") stays
-// dropped: the boundary paragraph carries its own scope ("are not
-// run-owned").
-//
-// MUL-5442 stage 2 (owner-authorized judgment rewrite): enforcement details
-// a frontier model derives from the platform fact were deliberately dropped
-// — the run-owned work enumeration, the tool-promise enumeration, the
-// wait/collect split rule, the persistent-service scope bullet, the
-// auto-merge and snapshot elaborations. Their pins were retired in the same
-// change. The incident history above (MUL-5223, MUL-5274, MUL-4091) remains
-// the WHY for what stays: the named --watch/watch/poll ban and merge-gate
-// denial survive because MUL-5223 proved the principle alone did not stop
-// CI-watching, and the handoff paragraph is review-locked verbatim
-// (URL/logs/stop triple, general cleanup handle) — do not reword it without
-// a fresh review decision.
+// writeBackgroundTaskSafetySlim states the task-lifetime and external-work
+// boundaries. Turn exit is terminal for run-owned work. External CI is handed off
+// unless this turn explicitly requires its result; a repository merge gate does
+// not supply that requirement.
+//
+// Keep the explicit watch/poll restriction and its foreground-watch exception
+// together. User-requested persistent services require a separate lifecycle,
+// readiness verification, durable logs, and a cleanup handle.
func writeBackgroundTaskSafetySlim(b *strings.Builder) {
b.WriteString("## Background Task Safety\n\n")
b.WriteString("Multica marks the task terminal the moment your top-level turn exits — any run-owned work still active is orphaned, its result lost, and the final comment you meant to post never sends. There is no background-completion wakeup, whatever a tool response promises; an issue wakeup (`multica issue wakeup create`) is different — the platform stores it and starts a new run later. Never background-and-yield: collect required results inside foreground tool calls that block to completion, run unobservable work synchronously, and never end a turn \"standing by\" for something to finish — that message becomes your final output.\n\n")
@@ -530,47 +486,14 @@ func writeInstructionPrecedence(b *strings.Builder) {
b.WriteString("Never treat this runtime workflow as permission to change issue status, investigate, implement, create issues, update issues, delegate, or otherwise act beyond your Agent Identity.\n\n")
}
-// The SessionContinuityNotice* family tells the agent a resume the task
-// expected could not be honored. The daemon has already cleared the resume
-// flags, so without this the run would silently reappear as a brand-new
-// conversation (MUL-4424).
+// SessionContinuityNotice variants describe missing provider working memory.
+// Issue discussion remains in issue comments; chat transcripts are recoverable
+// through history commands when SurfacePersistsTranscript says they are stored.
+// Only the unrecoverable variant requires telling the user discussion is lost.
//
-// There are three because the surfaces lose different things, and saying so
-// accurately matters more than saying it loudly. The question that separates
-// them is not "is this a chat?" but "can this conversation still be read?":
-//
-// - Issue: the conversation IS the issue body and its comments. Untouched,
-// and the workflow already makes the agent read them every turn.
-// - Slack: the conversation lives in the channel and `multica chat history` /
-// `multica chat thread` can fetch it — see buildChatPrompt, which hands the
-// agent exactly those commands. Recoverable, just from a different place.
-// - Web chat, Feishu, WeCom and DingTalk: the conversation is persisted in
-// Multica's chat_message table and `multica chat history` reads it back —
-// see handler/chat_history.go's chat_message fallback for non-Slack
-// sessions. Recoverable, just from a different place. The readable set is
-// decided in one place, SurfacePersistsTranscript.
-//
-// Only a surface whose conversation Multica never stored (so there is nothing
-// to read back) warrants telling the user; no current surface is in that
-// group, so SessionContinuityNoticeUnrecoverable is a defensive fallback. On
-// the readable ones the discussion survives, so announcing "the previous
-// context was lost" describes a loss that did not happen — the user reasonably
-// hears "the discussion is gone" when not a word of it is. There the notice
-// informs the agent and leaves mentioning it to the agent's judgement. What is
-// actually gone on every surface is the agent's own unrecorded working memory,
-// and each variant says so.
-//
-// Emitted into the per-turn user message rather than the runtime brief: it is
-// true of one run and false of the next on the same issue, so rendering it into
-// the brief broke prompt-cache prefix stability across resumes (MUL-5377).
-// The readable variants say the run "does not continue" the lost session, not
-// that the run is on a fresh one, and that the memory gone is "from the turns
-// that did not come back" rather than from every earlier turn. Under MUL-5305
-// the server may hand back an OLDER session with the gap flagged, and the
-// daemon resumes it (ResumeSessionID is not gated on the flag), so the agent
-// can hold earlier turns' memory while the latest turn's is gone. Both phrasings
-// are true in that case and in the plain fresh-session case; "you are on a fresh
-// one" was not (MUL-6984 review).
+// The server may resume an older session, so do not claim every earlier turn is
+// gone or that the run is necessarily fresh. Emit this run-specific notice in
+// the user message to preserve the stable brief's prompt-cache prefix.
const SessionContinuityNoticeIssue = "## Session Continuity Notice\n\n" +
"This run was meant to continue an earlier conversation, but that provider session could not be restored, and this run does not continue it. The issue and its full comment history are unaffected — that record is the authoritative version of this conversation, and reading it (which your workflow already requires) reconstructs it. What is gone is your own working memory from the turns that did not come back: what you already tried, what you ruled out, and how far you had got. Re-derive what you need instead of assuming it, and do not claim continuity the record cannot back up. Do not open your reply by announcing this — raise it only where it actually matters, such as when the user refers to reasoning you never wrote down.\n\n"
@@ -650,117 +573,18 @@ func writeWorkflowAutopilot(b *strings.Builder) {
b.WriteString("- " + AutopilotIssueCommandsGuard + "\n\n")
}
-// writeWorkflowIssue emits the single issue workflow used by every
-// issue-bound run, whatever triggered it.
-//
-// One section with no per-trigger branching, because this text lands in
-// messages[0] — ahead of the whole conversation — and any divergence between
-// the first run and later runs on the same resumed session throws away the
-// prompt cache for the entire history (MUL-5377). So nothing here may depend
-// on which trigger fired this turn, and no per-run identifier (trigger comment
-// id, thread id, new-comment delta, reply targets) may be interpolated. Those
-// travel in the per-turn user message instead; see daemon.buildCommentPrompt.
-//
-// There is deliberately no "turn mode" anymore (MUL-6417). The Reply/Ownership
-// split dated from PR #205 and was already merged in substance by MUL-5377
-// (one section, mode router) and MUL-6300 (reply turns own the same status
-// arc); what remained was a marker plus two small blocks restating information
-// the per-turn message already carries as data. The two rules that replace the
-// router:
-//
-// - Delivery routes on data: the per-turn message either carries a
-// triggering comment with this turn's --parent value (reply in that
-// thread) or it does not (post a new top-level comment).
-// - Status is written when the FACT changes, judged from what the work
-// changes about the issue — not from the trigger type, not from the run
-// lifecycle, and not gated on being the assignee. Lifecycle writes
-// oscillate under concurrent runs (every run flips its own open/close
-// pair — the churn MUL-6300's assignee gate existed to stop); fact
-// writes converge, because agents judging the same fact write the same
-// value or nothing. A todo issue the agent was only asked to research
-// correctly stays todo, which the old unconditional arc got wrong twice.
-//
-// The in_progress moment is the START of work, not the end of the turn: a
-// turn that advances the issue's own ask makes "being worked" true the moment
-// it begins, and the first work turn on a fresh assignment can run for half
-// an hour — judged only at turn end, the board showed todo the whole time
-// (Bohan's post-merge report on MUL-6417). This is the old rule's timing
-// with the fact anchor's conditionality: an ancillary turn still writes
-// nothing at either moment, so the concurrency convergence is unchanged.
-// The activity indicator still shows the run itself, but columns, filters,
-// and sorting read status — the indicator alone proved not to be the board
-// surface people actually watch.
-//
-// The start write lives INSIDE step 3, not in the status block below —
-// placement is load-bearing, not style. The first attempt stated it as a
-// bullet under the status heading, and a run on MUL-6460 that verifiably had
-// that brief walked steps 1→2→3 and never wrote a status: at the moment the
-// condition triggers the model is executing the numbered list, and a rule
-// outside the list does not fire (the pre-MUL-6417 opening write was
-// reliable precisely because it was an explicit step). Same incident killed
-// the "asked to research stays todo" example from the no-write bullet: that
-// run's work WAS research toward its own issue's ask, so the example
-// pattern-matched the exact case it was never meant to cover. Ancillary is
-// now defined by output alone — the turn produced none of the issue's own
-// deliverable. No activity-word list survives in EITHER direction: Elon's
-// review on #7295 caught "review" still sitting in a skip-list (the same
-// incident queued to replay on a review-the-PR issue), and J's review
-// caught the positive form-list that replaced it ("code, research, a
-// design, ...") — a whitelist reads as exhaustive, so a triage or
-// reproduce-the-bug turn would not find itself in it. What remains is the
-// criterion plus one never-decides sentence, placed inside step 3 because
-// that is the position that fires. The exit-side check is anchored inside
-// step 5 for the same reason, and the step-3 skip is scoped to the
-// in_progress CATEGORY so a custom status like Planning already counts as
-// recorded once MUL-6460 puts the catalog in front of agents.
-//
-// The invariants MUL-6300 pinned survive as consequences instead of gates: a
-// conversational turn changes nothing about the issue's state, so it writes
-// nothing; an @mention pull-in on someone else's (or an unassigned) issue
-// almost never changes its state, so it writes nothing — but a turn that
-// genuinely does move the work may now record it, whoever the assignee is.
-//
-// Step 2 is the ONLY place that decides WHETHER the scan runs (MUL-6984). The
-// per-turn hints (execenv.BuildColdCommentsHint / BuildNewCommentsHint /
-// BuildResumedCommentsHint) carry this turn's facts and exact commands and no
-// modality. Before this, the brief said "always run the scan, even when the
-// trigger looks self-contained" while the per-turn hints said "Need cross-thread
-// background?" / "Only if you need context from the other threads" — two
-// surfaces in one context, opposite modality, each written against a different
-// incident (#3494/#3535 against blind bulk reads, #6093 against missed
-// threads). The scan stays mandatory because the judgment "do other threads
-// matter?" needs exactly the data the scan produces: measured on 537
-// comment-triggered runs, 1 in 10 scans opened a thread the prompt had not
-// named, and 0 of 36 non-scanning runs did. The one data-driven exemption is
-// the server-computed empty delta on a resumed run, which the resumed hint
-// reports as the scan's answer.
-//
-// Step 2 asks for a roots scan first, not `--recent 10` (MUL-5372). `--recent N`
-// caps THREADS, not comments: each returned thread carries its root plus every
-// descendant with no depth cap, so on an issue with fewer than N root threads it
-// returns the entire comment history. Because this step is mandatory and fires on
-// every run, making it the bulk read meant every reply turn re-read the whole
-// issue — and, on comment-triggered turns, duplicated the bounded thread read the
-// per-turn message had already pointed at (see daemon.buildCommentPrompt and
-// BuildColdCommentsHint). `--roots-only --summary` keeps the anti-stale property
-// that step exists for — the agent still sees every thread that exists — at a
-// fraction of the payload, and the drill-down stays explicit.
-//
-// The step names ONLY the two reads it mandates. Flag semantics — including the
-// `--recent N` saturation trap above — belong to `## Available Commands`, which
-// is the single discovery point for the comment-read surface; repeating them per
-// step is what made this one bloat in the first place.
+// writeWorkflowIssue emits stable instructions for all issue-bound runs.
+// Keep trigger IDs and per-turn facts in the user message to preserve prompt caching.
+// Status writes depend on advancing the issue's deliverable and use exact built-in
+// keys. Keep the entry and exit checks inside steps 3 and 5 so they are encountered
+// at the relevant point in the workflow.
//
-// Squad leaders keep one status bullet: a dispatch turn leaves the parent
-// mid-flight, so its end-of-turn fact is in_progress, and in_review waits for
-// the re-trigger (member update / stage barrier) that confirms the overall
-// goal is met. Flipping the parent on the dispatch turn would mark unfinished
-// multi-stage work as ready for review; see the Squad Operating Protocol and
-// the sub-issue wakeup (service/issue_wakeup_system.go).
+// Step 2 owns the scan requirement; per-turn hints supply facts and commands.
+// Use roots-only summaries before bounded thread reads: recent limits threads,
+// not replies. A server-computed delta can satisfy the scan.
//
-// ctx.IsSquadLeader is a PER-TASK role, not agent configuration: branching on
-// it here does move brief bytes when the same agent runs leader one turn and
-// worker the next. Owner-accepted tradeoff; decision recorded in MUL-5811.
+// Squad dispatch leaves work in progress until a later turn confirms delivery.
+// The per-task leader role may change brief bytes across a resumed session.
func writeWorkflowIssue(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("**Every issue turn runs the same workflow.** The per-turn user message carries what triggered this run — an assignment handoff, or a triggering comment with its id and your `--parent` value — plus this issue's real id and ready-to-run context-read commands; assemble other calls from `## Available Commands`.\n\n")
diff --git a/server/internal/daemon/execenv/sidecar_manifest.go b/server/internal/daemon/execenv/sidecar_manifest.go
index 7733ae438f..23b229d135 100644
--- a/server/internal/daemon/execenv/sidecar_manifest.go
+++ b/server/internal/daemon/execenv/sidecar_manifest.go
@@ -230,47 +230,14 @@ func writeSidecarManifest(envRoot string, m *sidecarManifest) error {
return os.WriteFile(filepath.Join(envRoot, sidecarManifestFile), data, 0o644)
}
-// CleanupSidecars rolls the user's workdir back to its pre-Prepare
-// state by removing every file the manifest at envRoot records and
-// then rmdir-ing every directory it records, deepest first.
+// CleanupSidecars removes manifest-owned files, then directories deepest first.
+// Missing paths are already clean; nonempty directories belong to the user and
+// remain. Surface real I/O and parse errors while continuing other cleanup.
+// Determine nonempty directories by reading them after a failed rmdir rather
+// than treating every removal failure as nonempty.
//
-// Two failure modes the function deliberately swallows:
-//
-// - ENOENT on a recorded path. The file or directory was already
-// gone — either the user removed it during the task, or a prior
-// Cleanup run on the same envRoot already cleared it. Either
-// way there is nothing left for this call to do.
-// - Non-empty directory on rmdir. The user has populated a
-// directory we created (added a sibling file under .claude/
-// skills/, for example) and rmdir-ing would destroy that
-// content. We detect this by re-reading the directory after
-// rmdir fails: a non-empty listing means "user owns this — stop
-// here." This is the must-fix from PR #3444 review — the
-// previous version swallowed ANY non-ENOENT rmdir error as
-// "non-empty," which silently dropped real I/O failures
-// (EACCES, EPERM, EBUSY) and made cleanup look successful when
-// it wasn't.
-//
-// All other errors — ReadFile failure, JSON parse failure, real
-// EACCES/EPERM/EIO during file deletion, real EACCES/EPERM/EIO
-// during dir removal — are captured into firstErr and surfaced to
-// the caller. Cleanup still continues for the remaining manifest
-// entries so a single bad path does not strand the rest of the
-// rollback.
-//
-// The function is a no-op when:
-// - envRoot is empty (no daemon scratch for this task),
-// - the manifest file is missing (older build, or Prepare did not run).
-//
-// Pair this with CleanupRuntimeConfig on the local_directory cleanup
-// path: that function handles the runtime brief inside CLAUDE.md /
-// AGENTS.md, this one handles the sidecar tree
-// (.agent_context/, .multica/, .claude/skills/, .github/skills/,
-// .opencode/skills/, .codeartsdoer/skills/, skills/, .pi/skills/,
-// .omp/mcp.json, .omp/skills/, .cursor/skills/,
-// .kimi/skills/, .reasonix/skills/, .kiro/skills/, .agents/skills/, fallback
-// .agent_context/skills/). The two together restore the workdir to
-// byte-exact pre-task state.
+// An empty envRoot or missing manifest is a no-op. Pair with CleanupRuntimeConfig,
+// which restores the runtime brief; this function handles the sidecar tree.
func CleanupSidecars(envRoot string) error {
if envRoot == "" {
return nil
diff --git a/server/internal/handler/actor_guards.go b/server/internal/handler/actor_guards.go
index 764eab876c..931b9fb66e 100644
--- a/server/internal/handler/actor_guards.go
+++ b/server/internal/handler/actor_guards.go
@@ -4,95 +4,14 @@ import (
"net/http"
)
-// RequireHumanActor is a chi-style middleware that rejects requests
-// authenticated via a machine credential — currently mat_ task tokens
-// and mcn_ cloud-node PATs. It exists for endpoints whose
-// authorization model is "the human owner authorized this", not
-// "anyone holding the owner's credentials authorized this".
-//
-// Why this guard is needed (read carefully — auth here is subtle):
-//
-// The general Auth middleware (server/internal/middleware/auth.go)
-// turns four different bearer formats into the same shape — a stamped
-// `X-User-ID` header — so downstream handlers don't have to care which
-// token kind the caller used:
-//
-// - JWT cookie / mul_ PAT → X-User-ID = the human's user id.
-// X-Actor-Source is left empty.
-// - mat_ task token → X-User-ID = the OWNING human's user id,
-// plus X-Agent-ID, X-Task-ID, and the
-// authoritative server-set header
-// `X-Actor-Source: task_token`.
-// - mcn_ cloud-node PAT → X-User-ID = the OWNING human's user id,
-// plus `X-Actor-Source: cloud_pat`.
-// The token authenticates a cloud-runtime
-// EC2 node operating on the owner's
-// behalf — same conceptual category as
-// mat_ (machine running owner-scoped
-// code) for authorization purposes.
-//
-// The mat_ and mcn_ designs (MUL-2600 and the cloud-node PAT story
-// respectively) were both deliberately built this way: every request
-// the agent / node makes is treated as the owner's, so they can
-// post comments, claim issues, register runtimes, etc., as if the
-// owner had done it. That is correct for issue / comment / chat
-// scopes — those are bounded by workspace membership and by the
-// task or runtime binding.
-//
-// It is NOT correct for account-level scopes:
-//
-// - Billing balance / transactions / batches / topups list
-// are user-scoped. A running agent or a cloud node could read
-// its owner's wallet state without the owner ever having
-// approved a billing query.
-//
-// - Checkout / portal session creation can move money. A machine
-// credential that gets compromised — by a prompt injection, a
-// bad MCP tool, an escaped quote in scratch data, or a node
-// escape — could spin up a checkout for an attacker-controlled
-// email or open a Billing Portal session that leaks subscription
-// / payment-method state.
-//
-// `X-Actor-Source` is server-set only. The Auth middleware deletes any
-// client-supplied value first (see auth.go: `r.Header.Del("X-Actor-Source")`),
-// then re-sets it ONLY on the mat_ and mcn_ branches. So checking
-// this header is the safe, fast, single-source-of-truth way to know
-// "is the request from a machine credential?" — without re-querying
-// the token table.
-//
-// We deliberately do NOT use h.resolveActor() here:
-//
-// - resolveActor's primary job is "agent vs member" classification
-// for ownership / authorship attribution (issue creator, comment
-// author, etc.). It also has a fallback path that reads
-// X-Agent-ID + X-Task-ID directly; since MUL-3428 both middlewares
-// strip those headers, so that path is unreachable from the network
-// and irrelevant here either way. Billing authorization needs the
-// strict "machine credential → forbidden" gate, nothing else.
-// - resolveActor takes a workspaceID parameter; billing routes have
-// no workspace context, so threading one through just to call it
-// would be misleading.
-// - resolveActor doesn't currently classify mcn_ cloud-node PATs
-// because cloud nodes don't act on workspace-scoped resources
-// where author attribution matters. Bolting that classification
-// into resolveActor solely to reuse it here would be the wrong
-// coupling.
-//
-// Apply via `r.Use(handler.RequireHumanActor)` on a chi route group.
-// The middleware is intentionally NOT wired in via the router's main
-// Auth chain — the default contract elsewhere (issues, chat, etc.) is
-// "agent and human are interchangeable", and adding a global gate
-// would break legitimate agent traffic. Only attach it where the
-// scope is truly human-only.
-//
-// To extend: any new machine-credential auth branch added to
-// auth.go (e.g. a hypothetical service-account token) MUST stamp a
-// distinct X-Actor-Source value AND get reviewed against this gate
-// at the same time. The denylist below is intentionally explicit —
-// silently passing an unknown actor source is a feature, not a bug
-// (see TestRequireHumanActor_IgnoresUnknownActorSource), but the
-// addition of a new value is the moment to decide whether it's
-// human-equivalent or machine-equivalent.
+// RequireHumanActor rejects machine credentials on human-only route groups.
+// Auth strips client-supplied X-Actor-Source and stamps task_token or cloud_pat;
+// that authoritative header distinguishes a machine acting for its human owner.
+// resolveActor classifies workspace authorship and is not this authorization gate.
+//
+// Attach this middleware only to human-only scopes such as billing. Issue and
+// chat routes permit authorized agent traffic. Classify new auth sources here
+// when adding them; unknown values currently remain human-equivalent.
func RequireHumanActor(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if isMachineCredentialActor(r) {
diff --git a/server/internal/handler/attachment_capability.go b/server/internal/handler/attachment_capability.go
index 6ad7ba46b0..425a5730a1 100644
--- a/server/internal/handler/attachment_capability.go
+++ b/server/internal/handler/attachment_capability.go
@@ -180,9 +180,7 @@ func verifyAttachmentCapability(attachmentID, rawExp, rawSig, intent string, now
return hmac.Equal(got, want)
}
-// ---------------------------------------------------------------------------
// DownloadAttachmentWithCapability — GET /api/attachments/{id}/signed-download
-// ---------------------------------------------------------------------------
//
// Registered as a PUBLIC route. The capability in the query IS the credential,
// and a native download request has nothing for middleware.Auth to read, so
diff --git a/server/internal/handler/avatar.go b/server/internal/handler/avatar.go
index 5b9330cb75..817034bf73 100644
--- a/server/internal/handler/avatar.go
+++ b/server/internal/handler/avatar.go
@@ -23,66 +23,18 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-// ---------------------------------------------------------------------------
-// Avatar URLs (MUL-5393 / #6024)
-// ---------------------------------------------------------------------------
+// Persist raw storage URLs as durable avatar references. At read time, private
+// objects become stable /api/avatars/<sig>/<key> URLs that resolve through the
+// deployment's download policy. Never persist expiring signatures.
//
-// `avatar_url` columns (user / agent / squad / workspace) store the raw
-// storage object URL the upload returned. On a deployment whose bucket is
-// public — S3/R2 behind a public CDN domain, or the LocalStorage backend
-// whose /uploads/* route is served publicly — that URL loads fine in an
-// <img> and nothing here changes it.
+// The endpoint uses its HMAC as the credential so native image loads work across
+// origins without an Authorization header. Only image keys belonging to standalone,
+// unbound uploads are publishable; issue, comment, chat, and task attachments are
+// excluded. Enforce this at write time and on every read so old rows are covered
+// and later attachment binding revokes access.
//
-// On a PRIVATE bucket with no public CDN (S3 with Block Public Access, R2,
-// MinIO — the shape #6024 reports) that raw URL is a guaranteed 403 in the
-// browser: `ATTACHMENT_DOWNLOAD_MODE` only ever applied to the attachment
-// download endpoint, and avatars never went through it. Every avatar in the
-// deployment renders broken even though the upload itself succeeded.
-//
-// The fix resolves at READ time rather than at upload time:
-//
-// - What is PERSISTED stays the durable object reference (the raw storage
-// URL). Nothing with a TTL is ever written to the database — that is the
-// MUL-3130 regression this deliberately avoids — and avatars already
-// saved by an older build are fixed without a backfill.
-// - What is SERVED is `/api/avatars/<sig>/<key>`, a stable URL this server
-// resolves per request into a presigned redirect (or a proxied body)
-// using the deployment's existing storage download policy.
-//
-// The endpoint is unauthenticated on purpose, and the signature is the
-// credential. An auth-gated URL cannot be a native <img src>: the auth cookie
-// is SameSite=Strict, so a Desktop/mobile webview (token auth, non-API
-// document origin) and any split-origin self-hosted web app would fail the
-// resource load. This is the same reasoning behind CloudFront signed URLs,
-// and it is strictly tighter than the LocalStorage backend's existing
-// posture, where /uploads/* serves objects by key with no auth at all.
-//
-// Three things bound what a signed avatar URL can reach:
-//
-// - the HMAC covers the storage key, so a caller cannot mint one for a key
-// the server never published as an avatar;
-// - only image extensions resolve at all (see avatarContentType);
-// - and the object must be AVATAR-CLASS — a standalone image upload that is
-// not attached to an issue, comment, chat session, chat message, or task
-// (see avatarKeyIsPublishable).
-//
-// That last rule is the authorization boundary, and it is enforced on BOTH
-// sides. Being able to name a storage object is not permission to publish it:
-// without the check, any caller who had seen a private image attachment's raw
-// URL could submit it as their own avatar and the unauthenticated endpoint
-// would then keep re-signing it forever — and a user avatar propagates to
-// every workspace that user belongs to. The write side rejects such a value up
-// front; the read side re-checks per request, which is what makes the
-// guarantee hold for rows written before this check existed and revokes the
-// URL if an object is ever bound to a comment or chat afterwards.
-//
-// Uploader identity is deliberately NOT part of the rule. Duplicating an agent
-// legitimately reuses the source agent's avatar object, which a different
-// admin may have uploaded. The remaining theoretical case — publishing someone
-// else's *unbound* image — requires knowing that object's URL, and unbound
-// rows appear in no listing endpoint (ListAttachments is by issue,
-// groupAttachments by comment, chat attachments by message), so the only party
-// who ever sees one is its own uploader.
+// Uploader identity is not required because agent copies reuse existing avatars.
+// Unbound uploads are not exposed through attachment listing endpoints.
const avatarURLPathPrefix = "/api/avatars/"
@@ -375,9 +327,7 @@ func (h *Handler) absolutizeAvatarPath(relPath string) string {
return relPath
}
-// ---------------------------------------------------------------------------
// ServeAvatar — GET /api/avatars/{sig}/*
-// ---------------------------------------------------------------------------
//
// Unauthenticated by design (the signature is the credential) — see the file
// header. Resolution reuses resolveAttachmentDownloadMode so an avatar and an
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index 25cfb22169..e3e0eff1f5 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -29,9 +29,7 @@ import (
// meaningful summary, short enough to keep the dropdown row scannable.
const chatSessionTitleMaxLen = 200
-// ---------------------------------------------------------------------------
// Chat Sessions
-// ---------------------------------------------------------------------------
type CreateChatSessionRequest struct {
AgentID string `json:"agent_id"`
@@ -811,9 +809,7 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
-// ---------------------------------------------------------------------------
// Chat Messages
-// ---------------------------------------------------------------------------
type SendChatMessageRequest struct {
Content string `json:"content"`
@@ -1363,9 +1359,7 @@ func (h *Handler) MarkChatSessionRead(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
-// ---------------------------------------------------------------------------
// Deferred-cancellation draft restores (#5219)
-// ---------------------------------------------------------------------------
// ChatDraftRestoreResponse is one recoverable composer draft: a deferred
// cancellation settled as empty-transcript after the cancel HTTP response
@@ -1768,9 +1762,7 @@ func (h *Handler) ClearQueuedChatTasks(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
-// ---------------------------------------------------------------------------
// Task cancellation (user-facing, with ownership check)
-// ---------------------------------------------------------------------------
// CancelTaskByUser cancels a task the caller is allowed to act on within the
// current workspace.
@@ -1918,9 +1910,7 @@ func (h *Handler) CancelTaskByUser(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
-// ---------------------------------------------------------------------------
// Response types & helpers
-// ---------------------------------------------------------------------------
type ChatSessionResponse struct {
ID string `json:"id"`
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index f9bb026553..074af08990 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -330,88 +330,18 @@ var (
commentThreadMaxDepth = 64
)
-// ListComments returns comments for an issue. The default path returns the
-// newest commentHardCap comments in chronological order. If that defensive cap
-// fires, completeCommentThreads restores each affected thread within a bounded
-// context budget (or drops that thread as a unit), and the response sets
-// HeaderCommentsTruncated. Optional query params give agent-style readers
-// bounded views that scale to long issues without dragging every prior reply
-// into context:
+// ListComments returns chronological comments with bounded thread-aware reads.
+// The default newest-comment cap restores complete threads within a context budget
+// or drops each incomplete thread as a unit and sets HeaderCommentsTruncated.
//
-// - roots_only=true — return only top-level comments (parent_id IS NULL),
-// each annotated with reply_count + last_activity_at so the caller can
-// triage which thread to drill into. May combine with since for incremental
-// polling of newly created roots, but is exclusive with thread/recent/tail/
-// cursor modes because those have their own grouping or pagination semantics.
+// roots_only provides activity metadata; summary clips bodies. thread accepts a
+// root or descendant anchor; tail limits replies while retaining the root. recent
+// limits whole active threads, not individual comments. Resolved-thread folding
+// requires complete threads and cannot combine with partial-thread projections.
//
-// - summary=true — orthogonal content projection. Clips each returned
-// comment's content to a fixed budget and sets content_truncated, so an
-// agent can scan a list cheaply before pulling a full body. Composes with
-// every mode (default, since, thread, recent, roots_only).
-//
-// - fold=true — resolve-aware thread projection. Collapses each resolved
-// thread to root + conclusion (reply-resolved) or root only (root-resolved),
-// reusing the human timeline fold so an agent does not pay tokens for
-// settled discussion. The resolved thread's root carries thread_resolved +
-// folded_count; `--full` (no fold param) brings the dropped comments back.
-// Needs whole threads to compute a resolution, so it is rejected with since,
-// tail, and roots_only (partial-thread / reply-less reads) and composes with
-// the default list, recent, untailed thread, and summary.
-//
-// - thread=<comment-uuid> — return the root of the thread containing this
-// comment plus every descendant. The anchor may be a root or any reply;
-// the server walks up to the root via a recursive CTE, so callers do not
-// need to know whether the id they have is a root.
-//
-// - tail=<N> — only valid with thread. Cap the reply count at the N most
-// recent replies (per (created_at, id)). The thread root is always
-// returned, even when N=0, so the reader keeps the "what is this thread
-// about" context. Without tail, thread returns the entire thread (the
-// pre-MUL-2421 behavior).
-//
-// - recent=<N> — return the N most recently active threads (root + every
-// descendant per thread). A thread's recency is MAX(created_at) across
-// the whole subtree, so a stale-but-recently-replied thread ranks ahead
-// of an active-but-quiet one. Row-based "newest N comments" is
-// deliberately NOT exposed — it surfaces unrelated thread tails and
-// hides relevant history (#2340).
-//
-// - before=<RFC3339> + before-id=<uuid> — cursor. The pair's meaning is
-// context-dependent so the flag surface stays small:
-//
-// - with recent: a *thread* cursor — (last_activity_at, root_id) — and
-// the next page returns threads strictly less recent.
-//
-// - with thread + tail: a *reply* cursor — (created_at, id) — and the
-// next page returns replies in the same thread strictly older than
-// that reply.
-//
-// Both values must be set together so the cursor can tie-break entries
-// landing in the same microsecond. The cursor for the next page is
-// emitted via the X-Multica-Next-Before / X-Multica-Next-Before-Id
-// response headers.
-//
-// Combination rules (kept narrow on purpose — Elon flagged the matrix risk):
-//
-// - roots_only is exclusive with thread, recent, tail, and before/before-id.
-// It may combine with since. This keeps "list issue roots" separate from
-// "read a specific thread" and "read recently active threads".
-// - thread is exclusive with recent. Asking for "the most recent N within
-// thread X" mixes two different navigation models and is rejected.
-// - thread + before/before-id requires tail. Without tail, thread returns
-// the entire thread and a cursor would be ignored — reject loudly so
-// the documented "cursor scrolls within a tailed window" rule holds.
-// - tail requires thread (it is a thread-scoped limit; outside of thread
-// it has no defined behavior).
-// - thread may combine with since (incremental polling of one thread),
-// and the since filter is applied after the tail/cursor cut so the
-// thread root is still emitted but stale rows drop out.
-// - recent may combine with before/before-id (scroll older threads) and
-// with since (recent activity in a window).
-//
-// The response body is always chronological (oldest → newest); under recent
-// that means threads are listed oldest-active first and the freshest thread
-// sits at the tail, closest to "now" in an agent prompt.
+// Cursors pair a timestamp with an ID for tie-breaking: recent pages by thread
+// activity, while thread+tail pages by reply creation. Since filtering follows
+// the thread window. The validation below enforces supported combinations.
func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {
issueID := chi.URLParam(r, "id")
issue, ok := h.loadIssueForUser(w, r, issueID)
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 23dade0816..0d16221df6 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -47,9 +47,7 @@ import (
// state poll interval.
const claimPollHintMinDelay = time.Second
-// ---------------------------------------------------------------------------
// Daemon workspace ownership helpers
-// ---------------------------------------------------------------------------
// requireDaemonWorkspaceAccess verifies the caller has access to the given workspace.
// For daemon tokens (mdt_), compares the token's workspace ID directly.
@@ -190,9 +188,7 @@ func (h *Handler) verifyDaemonWorkspaceAccess(r *http.Request, workspaceID strin
return true
}
-// ---------------------------------------------------------------------------
// Daemon Registration & Heartbeat
-// ---------------------------------------------------------------------------
type DaemonRegisterRequest struct {
WorkspaceID string `json:"workspace_id"`
@@ -4113,9 +4109,7 @@ func (h *Handler) ListPendingTasksByRuntime(w http.ResponseWriter, r *http.Reque
writeJSON(w, http.StatusOK, resp)
}
-// ---------------------------------------------------------------------------
// Task Lifecycle (called by daemon)
-// ---------------------------------------------------------------------------
// ExtendTaskPrepareLease keeps a dispatched task protected while the daemon is
// resolving startup inputs and preparing the execution environment.
@@ -4490,46 +4484,18 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A
))
}
-// reconcileCommentsOnCompletion closes the at-least-once gap for member
-// comments a completing run did NOT deliver (MUL-4195).
+// reconcileCommentsOnCompletion replays qualifying comments absent from this
+// run's delivered_comment_ids receipt. Planned/coalesced IDs do not prove the
+// provider received them, particularly with older daemons or deleted comments.
//
-// The merge path (mergeCommentIntoPendingTask) folds a comment into a task only
-// while it is still PRE-CLAIM (queued/deferred). Those planned ids are not
-// proof of delivery: older daemons ignore structured coalesced fields, and a
-// referenced comment can be deleted before claim. Claim therefore records the
-// ids it actually embedded in delivered_comment_ids. Anything posted during
-// this run's lifetime that is NOT in that receipt must earn a follow-up.
+// Anchor at task creation and exclude the delivered set. A dispatch timestamp
+// would miss a comment whose pre-claim merge lost a race to claiming the task.
+// Replay chronologically through normal enqueue so comments coalesce into one
+// follow-up. That follow-up's later creation time and own receipt bound repetition.
//
-// Anchor = created_at + delivered-set exclusion, NOT a dispatch/start timestamp
-// (MUL-4195 review round-3 must-fix). A timestamp anchor cannot tell a
-// delivered comment from an undelivered one, and there is a race it structurally
-// misses: a comment created while the task was still queued, but whose merge
-// lost the race to the daemon claiming the task (queued→dispatched) — the merge
-// then finds no pre-claim row (ErrNoRows), the enqueue path defers to reconcile,
-// yet the comment's created_at is BEFORE dispatched_at, so a dispatched_at
-// anchor would skip it and it would vanish. Anchoring on the task's own
-// created_at reaches back over the whole run, and excluding the delivered set
-// is what prevents re-firing comments the run actually received. Together
-// they catch the pre-dispatch merge-race comment, the
-// dispatch→start comment, and the during-run comment, while never double-firing
-// a delivered one.
-//
-// Scope + loop safety:
-// - MEMBER comments keep their full routing. AGENT comments qualify through
-// explicit mentions, or a worker-to-leader route when the input was already
-// accepted and recorded in this run's plan. Timestamp-only
-// implicit agent replies are excluded: completion must not invent a new
-// conversation. Current invocation permissions and self-trigger guards
-// still apply to every replay.
-// - Only comments routing to THE AGENT THAT JUST RAN earn a follow-up here;
-// an `@other-agent` comment is left to that agent's own creation-time
-// trigger, so a completion never re-wakes an unrelated agent.
-// - Every undelivered qualifying comment is replayed through the normal
-// enqueue path in chronological order, so they coalesce into a SINGLE
-// follow-up task (the first enqueues it, the rest merge in). Bounded to one
-// run, and terminating: the follow-up's own created_at is later than all of
-// these comments and its delivered set will contain them, so its completion
-// finds nothing to re-schedule.
+// Preserve member routing and accepted explicit agent routes, current invocation
+// permissions, and self-trigger guards. Do not invent implicit agent conversation
+// routes or wake an unrelated agent from another agent's completion.
func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.AgentTaskQueue) {
if task == nil || !task.IssueID.Valid || !task.AgentID.Valid || !task.CreatedAt.Valid {
return
@@ -5139,9 +5105,7 @@ func (h *Handler) failTask(w http.ResponseWriter, r *http.Request, taskID, works
writeJSON(w, http.StatusOK, taskToResponse(*task, workspaceID))
}
-// ---------------------------------------------------------------------------
// Task Messages (live agent output)
-// ---------------------------------------------------------------------------
type TaskMessageRequest struct {
// CallID is an opaque tool-call identity scoped to one backend execution.
diff --git a/server/internal/handler/dashboard.go b/server/internal/handler/dashboard.go
index 1d6bffce3f..d75f106dff 100644
--- a/server/internal/handler/dashboard.go
+++ b/server/internal/handler/dashboard.go
@@ -9,7 +9,6 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-// ---------------------------------------------------------------------------
// Workspace / Project dashboard
//
// Six read endpoints power the workspace dashboard:
@@ -43,7 +42,6 @@ import (
// token spend / run time / failure volume are workspace-level operational
// metrics. The three per-AGENT rollups additionally apply per-agent visibility:
// see foldRestrictedAgents.
-// ---------------------------------------------------------------------------
// restrictedAgentsRowID is the synthetic agent_id that every row this response
// refuses to name is folded onto. Deliberately not a UUID, so it can never
@@ -509,7 +507,6 @@ func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.Reques
writeJSON(w, http.StatusOK, resp)
}
-// ---------------------------------------------------------------------------
// Failure rollups
//
// Both endpoints return EVERY terminal task, not just the failed ones: the
@@ -525,7 +522,6 @@ func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.Reques
// column. The client folds them into a handful of display classes; the raw
// reason stays on the wire so that mapping can change without a backend
// deploy.
-// ---------------------------------------------------------------------------
// DashboardFailureDailyResponse is one (date, failure_reason) bucket of
// terminal-task counts. FailureReason == "" is the succeeded bucket.
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index c1915c0904..5a8d26c597 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -54,9 +54,7 @@ const (
// 100 MB log dump can't blow up the renderer.
const maxPreviewTextSize = 2 << 20 // 2 MB
-// ---------------------------------------------------------------------------
// Response types
-// ---------------------------------------------------------------------------
type AttachmentResponse struct {
ID string `json:"id"`
@@ -372,9 +370,7 @@ func (h *Handler) groupChatMessageAttachments(ctx context.Context, workspaceID s
return grouped
}
-// ---------------------------------------------------------------------------
// UploadFile — POST /api/upload-file
-// ---------------------------------------------------------------------------
func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
r = h.withWakeupActor(r)
@@ -635,9 +631,7 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
})
}
-// ---------------------------------------------------------------------------
// ListAttachments — GET /api/issues/{id}/attachments
-// ---------------------------------------------------------------------------
func (h *Handler) ListAttachments(w http.ResponseWriter, r *http.Request) {
issueID := chi.URLParam(r, "id")
@@ -664,9 +658,7 @@ func (h *Handler) ListAttachments(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
-// ---------------------------------------------------------------------------
// GetAttachmentByID — GET /api/attachments/{id}
-// ---------------------------------------------------------------------------
func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {
att, ok := h.loadAttachmentForRequest(w, r)
@@ -846,9 +838,7 @@ func (h *Handler) loadAttachmentForDownload(w http.ResponseWriter, r *http.Reque
return att, true
}
-// ---------------------------------------------------------------------------
// DownloadAttachment — GET /api/attachments/{id}/download
-// ---------------------------------------------------------------------------
//
// Workspace context is derived from the attachment row itself, not from
// X-Workspace-Slug / X-Workspace-ID headers. This is what lets a markdown
@@ -1283,7 +1273,6 @@ func normalizeFrameAncestorSource(raw string) (string, bool) {
return scheme + "://" + strings.ToLower(u.Host), true
}
-// ---------------------------------------------------------------------------
// GetAttachmentContent — GET /api/attachments/{id}/content
//
// Streams the raw bytes of a text-previewable attachment back to the client.
@@ -1296,7 +1285,6 @@ func normalizeFrameAncestorSource(raw string) (string, bool) {
//
// Hard cap: 2 MB. Larger files return 413. Anything outside the text
// whitelist returns 415.
-// ---------------------------------------------------------------------------
func (h *Handler) GetAttachmentContent(w http.ResponseWriter, r *http.Request) {
att, ok := h.loadAttachmentForRequest(w, r)
@@ -1423,9 +1411,7 @@ func isTextPreviewable(contentType, filename string) bool {
return false
}
-// ---------------------------------------------------------------------------
// DeleteAttachment — DELETE /api/attachments/{id}
-// ---------------------------------------------------------------------------
func (h *Handler) DeleteAttachment(w http.ResponseWriter, r *http.Request) {
r = h.withWakeupActor(r)
@@ -1518,9 +1504,7 @@ func (h *Handler) DeleteAttachment(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
-// ---------------------------------------------------------------------------
// Attachment linking
-// ---------------------------------------------------------------------------
// linkAttachmentsByIssueIDs links unbound attachments to an issue. A caller
// that did not already advance the issue revision can ask this visible change
diff --git a/server/internal/handler/integrations_composio.go b/server/internal/handler/integrations_composio.go
index 174e78daf6..dea01501b5 100644
--- a/server/internal/handler/integrations_composio.go
+++ b/server/internal/handler/integrations_composio.go
@@ -61,9 +61,8 @@ func (h *Handler) composioMCPAppsEnabled(ctx context.Context) bool {
return featureflags.ComposioMCPAppsEnabled(ctx, h.FeatureFlags)
}
-// ComposioConnectInit (POST /api/integrations/composio/connect/init) starts a
-// hosted Composio auth flow for the requested toolkit and returns the redirect
-// URL. An unsupported toolkit slug is a 400 (the MVP only wires Notion).
+// ComposioConnectInit starts hosted auth for a toolkit with an enabled project
+// auth config. An unsupported toolkit slug returns 400.
func (h *Handler) ComposioConnectInit(w http.ResponseWriter, r *http.Request) {
if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {
writeFeatureDisabled(w, "composio_not_configured", "composio integration not configured")
diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.go
index 836c46dc6c..5738e020a8 100644
--- a/server/internal/handler/invitation.go
+++ b/server/internal/handler/invitation.go
@@ -53,10 +53,8 @@ func invitationToResponse(inv db.WorkspaceInvitation) InvitationResponse {
}
}
-// ---------------------------------------------------------------------------
// CreateInvitation replaces the old "instant-add" CreateMember flow.
// POST /api/workspaces/{id}/members (same endpoint, new behaviour)
-// ---------------------------------------------------------------------------
func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {
workspaceID := workspaceIDFromURL(r, "id")
@@ -248,10 +246,8 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, resp)
}
-// ---------------------------------------------------------------------------
// ListWorkspaceInvitations — pending invitations for a workspace (admin view).
// GET /api/workspaces/{id}/invitations
-// ---------------------------------------------------------------------------
func (h *Handler) ListWorkspaceInvitations(w http.ResponseWriter, r *http.Request) {
workspaceID := workspaceIDFromURL(r, "id")
@@ -287,10 +283,8 @@ func (h *Handler) ListWorkspaceInvitations(w http.ResponseWriter, r *http.Reques
writeJSON(w, http.StatusOK, resp)
}
-// ---------------------------------------------------------------------------
// RevokeInvitation — admin cancels a pending invitation.
// DELETE /api/workspaces/{id}/invitations/{invitationId}
-// ---------------------------------------------------------------------------
func (h *Handler) RevokeInvitation(w http.ResponseWriter, r *http.Request) {
workspaceID := workspaceIDFromURL(r, "id")
@@ -352,10 +346,8 @@ func (h *Handler) RevokeInvitation(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
-// ---------------------------------------------------------------------------
// GetMyInvitation — get a single invitation by ID (for the invite accept page).
// GET /api/invitations/{id}
-// ---------------------------------------------------------------------------
func (h *Handler) GetMyInvitation(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
@@ -399,10 +391,8 @@ func (h *Handler) GetMyInvitation(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
-// ---------------------------------------------------------------------------
// ListMyInvitations — current user's pending invitations across all workspaces.
// GET /api/invitations
-// ---------------------------------------------------------------------------
func (h *Handler) ListMyInvitations(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
@@ -447,10 +437,8 @@ func (h *Handler) ListMyInvitations(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
-// ---------------------------------------------------------------------------
// AcceptInvitation — user accepts a pending invitation.
// POST /api/invitations/{id}/accept
-// ---------------------------------------------------------------------------
func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
@@ -632,10 +620,8 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, memberResp)
}
-// ---------------------------------------------------------------------------
// DeclineInvitation — user declines a pending invitation.
// POST /api/invitations/{id}/decline
-// ---------------------------------------------------------------------------
func (h *Handler) DeclineInvitation(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 8f06cb8c3a..75fc2c676d 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -123,17 +123,8 @@ type IssueRefResponse struct {
// instead of a database CHECK violation bubbling up as a 500.
var validIssuePriorities = []string{"urgent", "high", "medium", "low", "none"}
-// validIssueStatuses is the 7 BUILT-IN status keys. Since MUL-6243 it is no
-// longer the set of writable statuses — write paths validate against the
-// workspace's catalog via validateIssueStatusKey — and it survives only for the
-// issue-table grouping/filtering paths, which key their group descriptors and
-// compound cells off a fixed status list.
-//
-// KNOWN LIMITATION: a custom status is therefore not yet selectable as an
-// issue-table group or filter value. That is a self-contained follow-up (the
-// table's group descriptors and compound cell keys need to become catalog
-// driven); it is scoped out here so this change cannot alter the table view for
-// workspaces that have no custom statuses.
+// validIssueStatuses contains the built-in status keys. Workspace writes,
+// grouping, and filters also support custom keys from the workspace catalog.
var validIssueStatuses = issuestatus.Canonical()
var validIssueStatusCategories = issuestatus.Categories()
@@ -4485,9 +4476,7 @@ func (h *Handler) publishClearedDuplicates(ctx context.Context, cleared []cleare
}
}
-// ---------------------------------------------------------------------------
// Batch operations
-// ---------------------------------------------------------------------------
type BatchUpdateIssuesRequest struct {
IssueIDs []string `json:"issue_ids"`
diff --git a/server/internal/handler/label.go b/server/internal/handler/label.go
index 73c6dc1b8c..e99bfad077 100644
--- a/server/internal/handler/label.go
+++ b/server/internal/handler/label.go
@@ -18,9 +18,7 @@ import (
"github.com/multica-ai/multica/server/pkg/protocol"
)
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
type LabelResponse struct {
ID string `json:"id"`
@@ -137,9 +135,7 @@ func validateLabelName(raw string) (string, error) {
return name, nil
}
-// ---------------------------------------------------------------------------
// Handlers — label CRUD
-// ---------------------------------------------------------------------------
func (h *Handler) ListLabels(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
@@ -365,9 +361,7 @@ func (h *Handler) DeleteLabel(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
-// ---------------------------------------------------------------------------
// Handlers — issue↔label attach/detach
-// ---------------------------------------------------------------------------
type AttachLabelRequest struct {
LabelID string `json:"label_id"`
@@ -569,9 +563,7 @@ func (h *Handler) DetachLabel(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, payload)
}
-// ---------------------------------------------------------------------------
// Handlers — agent/skill↔label attach/detach
-// ---------------------------------------------------------------------------
func (h *Handler) ListLabelsForAgent(w http.ResponseWriter, r *http.Request) {
agent, ok := h.loadAgentForUser(w, r, chi.URLParam(r, "id"))
diff --git a/server/internal/handler/property.go b/server/internal/handler/property.go
index d237899397..cfb29d2944 100644
--- a/server/internal/handler/property.go
+++ b/server/internal/handler/property.go
@@ -83,9 +83,7 @@ var reservedPropertyNames = map[string]struct{}{
"metadata": {}, "properties": {},
}
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
type PropertyOption struct {
ID string `json:"id"`
@@ -178,9 +176,7 @@ type UpdatePropertyRequest struct {
Archived *bool `json:"archived"`
}
-// ---------------------------------------------------------------------------
// Validation
-// ---------------------------------------------------------------------------
func normalizePropertyName(name string) string {
return strings.ReplaceAll(strings.ToLower(strings.TrimSpace(name)), " ", "_")
@@ -303,9 +299,7 @@ func selectOptionsHint(cfg PropertyConfig) string {
return strings.Join(parts, ", ")
}
-// ---------------------------------------------------------------------------
// Actor values (MUL-6286)
-// ---------------------------------------------------------------------------
// Compatibility aliases keep the focused handler tests on the same helper
// names while the implementation is shared with IssueService.Create.
@@ -393,9 +387,7 @@ func parseIssueProperties(raw []byte) map[string]any {
return util.JSONObjectOrEmpty(raw)
}
-// ---------------------------------------------------------------------------
// Definition handlers
-// ---------------------------------------------------------------------------
// requirePropertyAdmin gates definition writes: human owner/admin members
// only. Agent actors are rejected before the role check — an agent inherits
@@ -664,9 +656,7 @@ func (h *Handler) UpdateProperty(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
-// ---------------------------------------------------------------------------
// Issue value handlers
-// ---------------------------------------------------------------------------
type SetIssuePropertyRequest struct {
Value json.RawMessage `json:"value"`
@@ -846,9 +836,7 @@ func (h *Handler) withPropertyLock(r *http.Request, lockKeys []string, fn func(q
return tx.Commit(r.Context())
}
-// ---------------------------------------------------------------------------
// List-endpoint support: properties filter + property sort expressions
-// ---------------------------------------------------------------------------
const (
maxPropertiesFilterDefinitions = 20
diff --git a/server/internal/handler/quick_action.go b/server/internal/handler/quick_action.go
index 57655ec32e..18998e7409 100644
--- a/server/internal/handler/quick_action.go
+++ b/server/internal/handler/quick_action.go
@@ -82,9 +82,7 @@ var quickActionTemplateTokenRe = regexp.MustCompile(`\{\{[^}]*\}\}`)
// reaches nobody, so a prompt may legitimately point at related work.
var quickActionSideEffectMentionRe = regexp.MustCompile(`mention://(agent|squad|member|all)/`)
-// ---------------------------------------------------------------------------
// Types
-// ---------------------------------------------------------------------------
type QuickActionResponse struct {
ID string `json:"id"`
@@ -139,9 +137,7 @@ type ListQuickActionsResponse struct {
QuickActions []QuickActionResponse `json:"quick_actions"`
}
-// ---------------------------------------------------------------------------
// Validation
-// ---------------------------------------------------------------------------
func validateQuickActionName(raw string) (string, error) {
name := strings.TrimSpace(raw)
@@ -194,9 +190,7 @@ func normalizeQuickActionVisibility(raw string) (string, error) {
return v, nil
}
-// ---------------------------------------------------------------------------
// Target resolution
-// ---------------------------------------------------------------------------
// quickActionTarget is the resolved execution target of an action: the agent
// that will actually run, plus the display identity the client should show.
@@ -412,9 +406,7 @@ func (h *Handler) quickActionToResponse(ctx context.Context, qa db.QuickAction)
return resp
}
-// ---------------------------------------------------------------------------
// Management gate
-// ---------------------------------------------------------------------------
// requireQuickActionActor resolves the acting member. Agents are rejected: an
// agent inherits its runtime owner's credentials, and without this an admin's
@@ -476,9 +468,7 @@ func (h *Handler) requirePublicQuickActionRole(w http.ResponseWriter, r *http.Re
return ok
}
-// ---------------------------------------------------------------------------
// Handlers
-// ---------------------------------------------------------------------------
// ListQuickActions returns the workspace catalog. It performs NO permission
// work: `private` rows are scoped to their creator by the query (that is what
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index 3d0bb4f9dc..03c762e2a3 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -80,9 +80,7 @@ func runtimeToResponse(rt db.AgentRuntime) AgentRuntimeResponse {
}
}
-// ---------------------------------------------------------------------------
// Runtime Usage
-// ---------------------------------------------------------------------------
type RuntimeUsageResponse struct {
RuntimeID string `json:"runtime_id"`
diff --git a/server/internal/handler/runtime_model_catalog.go b/server/internal/handler/runtime_model_catalog.go
index 93354ea64c..4ed3182900 100644
--- a/server/internal/handler/runtime_model_catalog.go
+++ b/server/internal/handler/runtime_model_catalog.go
@@ -6,9 +6,7 @@ import (
"time"
)
-// ---------------------------------------------------------------------------
// Runtime model catalog cache (stale-while-revalidate)
-// ---------------------------------------------------------------------------
//
// Listing a runtime's models is a round trip to the user's machine: the request
// waits for the daemon's next heartbeat, the daemon shells out to the provider
diff --git a/server/internal/handler/runtime_models.go b/server/internal/handler/runtime_models.go
index ab57f6f7b1..d0edda49a4 100644
--- a/server/internal/handler/runtime_models.go
+++ b/server/internal/handler/runtime_models.go
@@ -14,9 +14,7 @@ import (
"github.com/multica-ai/multica/server/pkg/protocol"
)
-// ---------------------------------------------------------------------------
// Model list request store
-// ---------------------------------------------------------------------------
//
// The server cannot call the daemon directly (the daemon is behind the user's
// NAT and only polls the server). So "list models for this runtime" uses a
@@ -326,9 +324,7 @@ func modelListRequestTerminal(status ModelListStatus) bool {
return status == ModelListCompleted || status == ModelListFailed || status == ModelListTimeout
}
-// ---------------------------------------------------------------------------
// Handlers
-// ---------------------------------------------------------------------------
// InitiateListModels answers a "list this runtime's models" request.
//
diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.go
index b9a3d55c1a..c2c6600ef7 100644
--- a/server/internal/handler/runtime_profile.go
+++ b/server/internal/handler/runtime_profile.go
@@ -17,7 +17,6 @@ import (
"github.com/multica-ai/multica/server/pkg/protocol"
)
-// ---------------------------------------------------------------------------
// Custom Runtime Profiles (MUL-3284)
//
// A runtime_profile is a workspace-level, team-shared definition of a custom
@@ -30,7 +29,6 @@ import (
// Iron rule: a profile carries NO generic per-agent args. Per-agent launch args
// stay on agent.custom_args. The only args field is fixed_args — args every
// agent on this runtime must inherit to enter a compatible mode.
-// ---------------------------------------------------------------------------
type RuntimeProfileResponse struct {
ID string `json:"id"`
diff --git a/server/internal/handler/runtime_update.go b/server/internal/handler/runtime_update.go
index 07f94c6261..7f14376c5d 100644
--- a/server/internal/handler/runtime_update.go
+++ b/server/internal/handler/runtime_update.go
@@ -14,9 +14,7 @@ import (
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
)
-// ---------------------------------------------------------------------------
// CLI update request store
-// ---------------------------------------------------------------------------
type UpdateStatus string
@@ -206,9 +204,7 @@ func (s *InMemoryUpdateStore) Fail(_ context.Context, id string, errMsg string)
return nil
}
-// ---------------------------------------------------------------------------
// Handlers
-// ---------------------------------------------------------------------------
// InitiateUpdate creates a new CLI update request (protected route, called by frontend).
func (h *Handler) InitiateUpdate(w http.ResponseWriter, r *http.Request) {
diff --git a/server/internal/integrations/channel/doc.go b/server/internal/integrations/channel/doc.go
index b24612a727..cc8c17409d 100644
--- a/server/internal/integrations/channel/doc.go
+++ b/server/internal/integrations/channel/doc.go
@@ -1,45 +1,9 @@
-// Package channel is the platform-agnostic foundation for Multica's
-// inbound IM integrations (Feishu/Lark, Slack, WeCom, …). It owns the
-// contract every integration implements so the core never learns what a
-// given platform's event JSON looks like — design tracked in MUL-3506,
-// phase-1 foundation in MUL-3515.
-//
-// The contract has four pieces:
-//
-// 1. Channel — the per-integration interface
-// (Type / Connect / Disconnect / Send / Capabilities). An adapter
-// translates platform payloads in both directions and owns its own
-// connection mode (outbound WebSocket long-conn, inbound HTTP, …);
-// the core only calls these five methods.
-//
-// 2. InboundMessage / OutboundMessage — the normalized message
-// envelopes. Every platform's inbound payload is translated by its
-// adapter into one InboundMessage; the core routes, dedups, and
-// persists only this struct. Outbound is the minimal text reply
-// (ChatID + Text + optional thread / reply target) — rich cards,
-// media, and outbound webhooks are deliberately out of scope here
-// and stay inside the adapter that supports them.
-//
-// 3. Capability — a bitmask each Channel uses to DECLARE what it can
-// do (rich cards, threads, attachments, …). This package only
-// models the declaration; it intentionally contains no degrade
-// logic. Callers that want to degrade (rich card → plain text)
-// read the bitmask and decide for themselves, so adding a platform
-// never forces an if/else into the core.
-//
-// 4. Registry — a Type→Factory map with last-writer-wins semantics.
-// Adding a platform is "register a factory", not "edit the core".
-//
-// Boundary rule (MUL-3515 decision §2): the envelope holds ONLY fields
-// that are true across every platform — Text, a normalized message-type
-// enum, media references, the reply/thread anchors, the routing Source,
-// and the event/message ids used for dedup. Anything platform-specific
-// (a Lark raw msg_type, parent_id, root_id, …) lives in Raw and is read
-// ONLY by the adapter that produced it. The core never reads Raw.
-//
-// This package is pure: it has no database, network, or platform
-// dependencies, and nothing in it imports another integration package.
-// The concrete Feishu/Lark adapter, the DB-backed installation/identity/
-// session resolvers, and the supervisor that drives Connect/Disconnect
-// are wired in the follow-up cutover (see MUL-3515).
+// Package channel defines platform-independent IM interfaces and envelopes.
+// Adapters own transport and platform payloads; the engine consumes normalized
+// messages and capabilities. Rich cards and platform-specific delivery remain
+// inside their adapters. Callers choose capability degradation policies.
+//
+// Raw carries adapter-specific fields and must only be read by that adapter.
+// Registry maps channel types to factories with last-writer-wins semantics.
+// This foundation has no database, network, or integration dependencies.
package channel
diff --git a/server/internal/integrations/composio/dispatch.go b/server/internal/integrations/composio/dispatch.go
index f71707197c..a8e7bc1cb3 100644
--- a/server/internal/integrations/composio/dispatch.go
+++ b/server/internal/integrations/composio/dispatch.go
@@ -180,17 +180,8 @@ func normaliseAllowlistToSet(allow []string) map[string]struct{} {
return out
}
-// pinConnectedAccounts intersects the originator's active connection rows
-// with the allowlist set and returns the `connected_accounts` map shape the
-// Composio /tool_router/session endpoint expects: one entry per allowlisted
-// toolkit slug, value = array of the originator's connected account ids for
-// that toolkit. The product currently permits one active account per toolkit,
-// so each array has one element.
-//
-// Newest-wins on duplicates: rows arrive ordered by connected_at DESC
-// (see ListActiveUserComposioConnections), so the first row seen for a
-// given slug is the most recently connected account, matching the
-// single-account-per-toolkit invariant CreateMCPSession already documents.
+// pinConnectedAccounts intersects active connection rows with allowed toolkits.
+// Rows must be ordered newest first; the first account per toolkit wins.
func pinConnectedAccounts(rows []db.UserComposioConnection, allowSet map[string]struct{}) map[string]any {
pinned := make(map[string]any, len(rows))
for _, row := range rows {
diff --git a/server/internal/integrations/lark/doc.go b/server/internal/integrations/lark/doc.go
index b72b42298d..b471fbcbb4 100644
--- a/server/internal/integrations/lark/doc.go
+++ b/server/internal/integrations/lark/doc.go
@@ -1,62 +1,11 @@
-// Package lark contains the Multica ↔ 飞书 (Lark) Bot integration.
-//
-// MVP scope is tracked in MUL-2671. After the migration / service
-// boundary PRs landed, this package now covers:
-//
-// 1. DB schema + sqlc wrappers (migration 109_lark_integration.up.sql)
-// 2. InstallationService (encrypted app_secret, workspace-scoped lookups)
-// 3. BindingTokenService (15-minute single-use, transactional redeem
-// that rejects cross-user rebinds in-DB)
-// 4. Feishu ResolverSet (feishu_resolvers.go) feeding the shared,
-// channel-agnostic engine.ChatSession (chat_session ensure / append,
-// /issue parsing) — no Feishu-specific session service remains
-// 5. Dispatcher (inbound pipeline: installation route → top-level
-// message_id dedup → group filter → identity check → ensure
-// session → append → /issue → enqueue chat task; typed outcomes
-// for offline / archived / command guidance; emit returns
-// DispatchResult + error so the connector can post the matching
-// Lark-side reply card)
-// 6. AuditLogger (lark_inbound_audit; deliberately no body column)
-// 7. APIClient interface + http_client.go (real Lark Open Platform
-// transport for IM v1 send/patch + binding prompt + bot info;
-// stubAPIClient refuses calls when no production client is wired)
-// 8. Hub (WS lease + per-installation supervisor goroutines with
-// exponential backoff + jitter; renewer cancels the connector's
-// run ctx on lease loss to keep §4.4 ownership safe across
-// replicas; EventConnector interface is the seam for the real
-// wire protocol)
-// 9. WSLongConnConnector (real long-conn over gorilla/websocket; the
-// wire protocol is the binary Frame envelope from the official Go
-// SDK — bootstrap via POST /callback/ws/endpoint, app-layer
-// ping/pong, ACK responses on every data frame, ctx cancel breaks
-// blocking ReadMessage via a watchdog goroutine for §4.4)
-// 10. Patcher (subscribes to task / chat-done events; keeps the
-// per-task Lark interactive card in sync; throttled patches +
-// final/error bypass)
-// 11. OutcomeReplier (outbound side of the EventEmitter contract:
-// NeedsBinding mints a token + sends the binding prompt;
-// AgentOffline / AgentArchived push status notice cards into the
-// chat; FreshPending / IssueUsage push command guidance; Ingested
-// is owned by the Patcher; Dropped is silent)
-// 12. RegistrationService (RFC 8628 device-flow scan-to-install: opens
-// a session against accounts.feishu.cn, polls in the background,
-// and on success writes through InstallationService + auto-binds
-// the installer via InstallerBinder so §2.1 "scan to bind, you're
-// done" holds end-to-end)
-//
-// Architectural boundaries (frozen from Elon's 二审, MUL-2671 §4.8):
-//
-// 1. Issue creation goes through internal/service.IssueService.Create —
-// this package never calls qtx.CreateIssue directly.
-// 2. Inbound message ingestion uses the shared engine.ChatSession, NOT
-// the HTTP `SendChatMessage` handler. Group chat_sessions have multi-
-// member creator semantics that the HTTP handler's single-creator
-// guard rejects on purpose.
-// 3. Outbound card-message mapping lives in `lark_outbound_card_message`
-// (per task/message), never on `chat_session.metadata`.
-// 4. Unbound users and non-workspace members never reach
-// chat_session/chat_message. They land in `lark_inbound_audit` (no
-// body) with a drop_reason and nothing else.
-// 5. `app_secret` is encrypted at rest via internal/util/secretbox.
-// The DB never sees plaintext.
+// Package lark adapts Feishu bot traffic to the shared channel engine.
+// Installation and binding services handle encrypted credentials and user binding;
+// ResolverSet supplies platform-specific identity, dedup, session, and reply logic.
+// The hub owns leased WebSocket connections, and outbound patchers update cards.
+//
+// Issue creation uses service.IssueService.Create. Chat ingestion uses
+// engine.ChatSession rather than HTTP handlers, whose single-creator checks do
+// not represent group chats. Outbound card mappings live in their own table.
+// Unbound or non-member senders are audited without storing message bodies;
+// app_secret is encrypted before persistence.
package lark
diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.go
index ea42cc8aed..3cf15dfba1 100644
--- a/server/internal/integrations/lark/outbound.go
+++ b/server/internal/integrations/lark/outbound.go
@@ -236,47 +236,14 @@ func (p *Patcher) SetTypingIndicatorManager(m *TypingIndicatorManager) {
p.typingIndicator = m
}
-// Register subscribes the patcher to the task-lifecycle events it
-// cares about on the supplied bus. Idempotent only if you call it
-// against a fresh bus; call sites should invoke it exactly once
-// during server boot (after the bus + patcher are constructed and
-// before HTTP traffic starts).
+// Register attaches the patcher once during boot, before traffic starts.
+// ChatDone sends the reply, TaskFailed sends an error, and TaskCancelled clears
+// typing state without an answer. Every cancellation path must publish its event
+// after commit, including deletion paths whose workspace must come from the caller.
//
-// Subscriptions are deliberately minimal:
-//
-// - EventChatDone — the agent finished replying. The Patcher sends
-// the reply as a plain text IM message (Lark's `msg_type=text`),
-// not as an interactive card. The earlier card-based design (with
-// thinking → running → final patches) made every reply look like
-// a system notification nested in card chrome; flipping to plain
-// text makes free-form chat feel native.
-//
-// - EventTaskFailed — the run failed; surface a short error card
-// so the failure is visually distinct from a successful reply.
-//
-// - EventTaskCancelled — the run ended without an answer. Nothing is
-// sent for it; the subscription exists so the Typing reaction comes
-// off. A cancellation publishes no chat-done and no task-failed, so
-// without this the badge sits on the user's message for good.
-// task:cancelled is broadcast once per cancelled row by CancelTask,
-// the queued follow-up cancel behind it, the agent- and issue-level
-// bulk cancels, the runtime and member revocations, and deleting the
-// chat session. The delete is the one that used to publish nothing:
-// BroadcastCancelledTasks resolved each task's workspace through its
-// chat_session, the same row its transaction had just deleted, and an
-// event with no workspace is dropped before it reaches the bus. It now
-// takes the workspace from its caller. Archiving an agent also publishes
-// task:cancelled for chat tasks after commit, clearing their reactions
-// through this subscription. Clear marks in-flight adds as ended so a
-// late Add removes its own reaction when the HTTP call returns.
-//
-// We deliberately do NOT subscribe to EventTaskQueued / EventTaskRunning
-// (no thinking-card lifecycle anymore — adds noise without value) or to
-// EventTaskCompleted (chat tasks always emit EventChatDone first, which
-// is what we care about; non-chat tasks have no Lark binding anyway and
-// would early-return). Leaving EventTaskCompleted unsubscribed also
-// avoids the prior "Done." overwrite regression where the no-content
-// EventTaskCompleted payload would wipe the real reply.
+// Do not subscribe to TaskCompleted: chat tasks already emit ChatDone, and the
+// empty completion payload must not overwrite the reply. Queued/running events
+// do not drive a thinking-card lifecycle.
func (p *Patcher) Register(bus *events.Bus) {
bus.Subscribe(protocol.EventTaskFailed, p.handleEvent)
bus.Subscribe(protocol.EventChatDone, p.handleEvent)
diff --git a/server/internal/integrations/lark/ws_connector.go b/server/internal/integrations/lark/ws_connector.go
index c38e77a694..0eb8e6ba69 100644
--- a/server/internal/integrations/lark/ws_connector.go
+++ b/server/internal/integrations/lark/ws_connector.go
@@ -13,52 +13,15 @@ import (
"github.com/gorilla/websocket"
)
-// WSLongConnConnector is the production EventConnector that holds the
-// Lark long-conn WebSocket open, decodes the binary Frame envelope
-// the open-platform server pushes, and forwards normalized inbound
-// events to the Hub's Dispatcher.
+// WSLongConnConnector bootstraps and maintains the Lark WebSocket connection.
+// Use the returned service ID and application-level ping interval, not WebSocket
+// protocol PING frames. Data acknowledgements preserve inbound headers and report
+// dispatcher success or retryable failure.
//
-// Protocol layer (aligned with `larksuite/oapi-sdk-go/v3/ws`):
-//
-// 1. EndpointFetcher does the POST /callback/ws/endpoint bootstrap.
-// Lark returns a single-use wss URL with `device_id` + `service_id`
-// query parameters acting as the credential. The `service_id` is
-// extracted and used as Frame.Service on every outbound frame.
-// 2. Every WebSocket frame is a binary protobuf Frame. JSON envelopes
-// are wrapped inside Frame.Payload for data events; control,
-// ping, pong, ack frames are pure-binary.
-// 3. The client emits an app-layer ping frame (NewPingFrame) on the
-// PingInterval the server returned in the bootstrap ClientConfig.
-// WebSocket protocol-level PING is NOT used — Lark's server
-// ignores it. The server can also push pings at any time; we
-// reply with NewPongFrame.
-// 4. Every data frame requires an ACK back. The ACK reuses the
-// inbound frame's Headers verbatim (Lark correlates by
-// message_id) and writes a JSON Response{code:200, ...} as the
-// Payload. We send ACK 200 on successful Dispatcher emit, 500
-// when the Dispatcher reported an infra failure so Lark retries.
-//
-// Ownership of the §4.4 invariant (ctx cancel breaks blocking read):
-//
-// gorilla/websocket.ReadMessage blocks on the TCP socket and does NOT
-// observe a context. Cancelling our ctx flips ctx.Done but does not
-// touch the read syscall. We bridge ctx → read interrupt with a
-// watchdog goroutine that calls conn.Close once ctx fires;
-// gorilla.Close causes any in-flight Read to return immediately with
-// a "use of closed connection" error. The watchdog also runs on a
-// normal exit (so we never leak a goroutine) and is idempotent
-// because conn.Close is safe to call multiple times. This invariant
-// MUST be preserved by any future protocol change: without it,
-// renewLeaseUntil's cancelRun is meaningless and two replicas can
-// process the same installation during a healthy-but-silent socket.
-//
-// PersonalAgent compatibility risk: the official Feishu docs describe
-// long-conn as "supports 企业自建应用 only". PersonalAgent device-flow
-// apps are not listed as supported. If the bootstrap call returns a
-// structured error from Lark, this connector exits Run with the error
-// wrapped and the Hub's backoff loop logs it on every retry — making
-// the misconfiguration visible. See MUL-2671 review thread for the
-// smoke-test path.
+// ReadMessage does not observe context cancellation. A watchdog closes the socket
+// on cancellation so lease loss interrupts a silent connection before another
+// replica takes ownership. Stop that watchdog on normal exit as well.
+// Bootstrap failures return to the hub's backoff loop with their upstream error.
type WSLongConnConnector struct {
cfg WSConnectorConfig
}
diff --git a/server/internal/integrations/wecom/markdown.go b/server/internal/integrations/wecom/markdown.go
index e361c4f8d2..29f5524867 100644
--- a/server/internal/integrations/wecom/markdown.go
+++ b/server/internal/integrations/wecom/markdown.go
@@ -69,91 +69,19 @@ func breakLinkAdjacency(s string) string {
return channel.BreakMarkdownLinkAdjacency(s)
}
-// breakLinkReferenceDefinitions stops member-authored text from *defining* a
-// link the bot's card then resolves. Pushed through a live tenant, a comment
-// body containing
+// breakLinkReferenceDefinitions inserts a space between ] and : to stop
+// member-authored reference definitions from creating links under the bot's name.
+// Breaking inside the label would not work because label matching normalizes space.
//
-// [重置密码]: https://evil.example
-// [重置密码]
+// Only block scaffolding may precede a valid label, and the destination must be
+// capable of leaving the client's host. Relative destinations remain unchanged
+// to preserve forms such as "[Bug]: 登录失败". Labels may span lines; the same
+// container prefix must be used when locating a next-line destination.
//
-// came back with the first line gone — swallowed as a definition — and the
-// second rendered as a blue underlined link to evil.example. Nothing in it is
-// adjacent, so breakLinkAdjacency passes the whole attack through untouched.
-// Killing the definition kills the shortcut "[label]", the collapsed
-// "[label][]" and the full "[text][label]" alike: all three resolve through
-// the same map, and with no definition in the message none of them can.
-//
-// # The rule
-//
-// A "]" is separated from the ":" that follows it when all three hold:
-//
-// 1. Only block scaffolding precedes the opening "[" on its line —
-// indentation, ">" blockquote markers, list bullets. Necessary, not
-// decorative: a definition inside a blockquote or a list item still
-// populates the whole document's reference map and resolves outside it.
-// 2. The brackets form a CommonMark link label: closed by the first
-// unescaped "]", no unescaped "[" inside, at least one non-whitespace
-// character, at most 999. The label may span lines and still resolve, so
-// the scan does too.
-// 3. What follows the colon is plausibly a link *destination* — see
-// looksLikeLinkDestination.
-//
-// Conditions 1 and 3 are halves of one question and are kept honest by one
-// answer: containerPrefixBefore reports the block containers holding the
-// label, and looksLikeLinkDestination is handed that same containerPrefix so
-// it can step back into them when the destination sits on the next line.
-// Teaching one half about a container and not the other is what leaves a
-// definition intact — see the comment on containerPrefix.
-//
-// Condition 3 is the whole design. Breaking every "]:" would be simpler and is
-// the wrong trade: "[Bug]: 登录失败" is a form real people write, and it comes
-// back from here byte-identical because 登录失败 names no host — as a
-// destination it is relative, so it resolves against whatever base the client
-// itself is on and cannot aim the reader at someone else's server. That is the
-// line the rule draws: a destination that leaves for another host is broken, a
-// destination that cannot is left alone.
-//
-// # What it deliberately lets through
-//
-// - Relative destinations. "[文件]: report.pdf", "[页面]: /inbox",
-// "[Owner]: R&D", "[Regex]: \d+" and "[Bug]: 登录失败" all still define a
-// reference, and the label can still come out as a link — but pointing at
-// the client's own base, not at an attacker. Paid knowingly to keep the
-// human form intact.
-// - "[foo]:(https://evil.example)". CommonMark keeps the parens inside the
-// href, so it is not a URL anyone navigates to. A leading "(" is skipped
-// anyway before the destination is examined, in case this renderer is
-// looser, because skipping one costs nothing.
-//
-// # Where it over-fires, and why that is the safe side
-//
-// It models block containers only as a count of ">" markers, so it fires on a
-// "[x]: https://…" line that CommonMark would fold into the preceding
-// paragraph or read as indented code, and on a next-line destination whose
-// blockquote nesting is shallower than the definition's. It does not check the
-// spec's "nothing may follow the destination" rule either, so
-// "[x]: https://evil.example 请点击" is broken too though CommonMark would
-// leave it as prose. Every one of those costs a single space on a line that
-// already carries a URL. Under-firing costs a working link under the bot's
-// name, so the approximation runs this way round on purpose — the more so
-// because this renderer is demonstrably not CommonMark-exact (it reads
-// "\[ … \]" as a display-math delimiter).
-//
-// # Where the break goes
-//
-// Between the "]" and the ":". CommonMark requires the colon to follow the
-// label immediately, so one space ends the definition; verified against a
-// CommonMark parser in markdown_test.go, including inside a blockquote and
-// with the destination on the next line. It cannot go inside the label —
-// reference labels are matched on whitespace-collapsed, case-folded text, so
-// "[ 重置密码]" would still match "[重置密码]" and the definition would live.
-// It cannot be a backslash for the reason above. And it cannot go before the
-// "[": there is no character that pushes a line out of block position without
-// either showing up as content or, four spaces on, opening a code block.
-//
-// Like breakLinkAdjacency this adds one rune per occurrence, so callers that
-// budget a length cap must call it before measuring; and its output holds no
-// "]:" it would fire on again, so a second pass is a no-op.
+// Container detection intentionally over-approximates CommonMark: an extra space
+// is preferable to leaving an external reference active. See markdown_test.go for
+// inline, collapsed, shortcut, and nested-container cases. Apply before measuring
+// message length; the transformation adds a rune per match and is idempotent.
func breakLinkReferenceDefinitions(s string) string {
if !strings.Contains(s, "]:") {
return s
diff --git a/server/internal/integrations/wecom/media_download.go b/server/internal/integrations/wecom/media_download.go
index ed96c45dce..d97291d6bd 100644
--- a/server/internal/integrations/wecom/media_download.go
+++ b/server/internal/integrations/wecom/media_download.go
@@ -228,58 +228,13 @@ func hasExtendedFilename(raw string) bool {
return strings.Contains(strings.ToLower(raw), "filename*")
}
-// decodeFormEncodedFilename undoes application/x-www-form-urlencoding on a
-// filename that provably carries it, and leaves every other name byte for
-// byte.
+// decodeFormEncodedFilename decodes only names that round-trip through
+// url.QueryEscape. Unconditional QueryUnescape would corrupt literal pluses.
//
-// Why this is needed: a live tenant sent "PC D&T Strategy 2026.docx" and it
-// was stored as "PC+D%26T+Strategy+2026.docx" — space as '+', '&' as %26,
-// which is exactly url.QueryEscape of the original. COS form-encodes the
-// plain filename parameter because that parameter is ASCII-only by
-// specification, and Chinese names take the same route: a non-ASCII name
-// cannot legally sit there, so it arrives as a run of percent escapes, and
-// without this the user is shown the escapes.
-//
-// Why it is conditional: url.QueryUnescape on its own reads '+' as a space,
-// so it would rewrite "C++ notes.docx" to "C notes.docx". Both readings of
-// a bare '+' are legitimate and no header field distinguishes them. What does
-// distinguish them is self-consistency — a genuine form-encoding survives a
-// round trip through the encoder, and an accidental one usually does not:
-// "C++ notes.docx" re-encodes to "C+++notes.docx" (the literal space would
-// have been a '+' too) and is therefore left alone. So the rule is: decode
-// only when re-encoding the result reproduces the header value.
-//
-// What this does NOT handle, and why:
-//
-// - Any name whose only encoder-touched character is a '+' IS a canonical
-// encoding of the same name with spaces, so the round trip cannot rule it
-// out and this decodes it, losing the pluses. That is a wider class than
-// one odd example: "C++.docx" → "C .docx", and so do "React+Redux.md",
-// "Q1+Q2.xlsx", "C++11.pdf", "10+1.pdf". The ambiguity is irreducible from
-// the header alone, and this is the side chosen deliberately — a name with
-// a space is far more common than one with a '+' and no space, and a name
-// with both is already safe by the round trip above.
-// - A name percent-encoded in the RFC 3986 style, with %20 for space rather
-// than '+' ("PC%20D&T.docx"), re-encodes to "PC+D%26T.docx", fails the
-// check, and keeps its escapes.
-// - A name from a server whose unreserved set is not Go's. The round trip
-// re-encodes with url.QueryEscape, which leaves A-Za-z0-9-_.~ alone, so
-// the check silently assumes the sender agreed on that set. Java's
-// URLEncoder also passes '*', and PHP's urlencode escapes '~' as %7E, so
-// "backup~.docx" from either arrives as "backup%7E.docx", re-encodes to
-// "backup~.docx", and the lengths no longer match. The failure is
-// all-or-nothing rather than partial: ONE character outside Go's set and
-// the entire name keeps its escapes, so "Q1 report~.docx" is shown as
-// "Q1+report%7E.docx" — the unreadable state this decode exists to
-// remove, with the '+' still in it. Widening the comparison to tolerate
-// an escape on either side would mean deciding which of several encoders
-// wrote the header, and the evidence for that decision does not exist
-// yet.
-//
-// The gaps stay open because one stored filename is all the evidence there
-// is, and the URL that produced it is long expired. traceMediaHeaders records
-// the header as it arrives, so the next live run settles what COS really
-// sends with bytes rather than with another inference from one sample.
+// This cannot disambiguate plus-only names such as C++.docx from encoded spaces;
+// the chosen policy decodes them. RFC 3986 encodings using %20 and encoders with
+// a different unreserved set may fail the round trip and remain unchanged.
+// traceMediaHeaders provides evidence for changing that policy.
func decodeFormEncodedFilename(name string) string {
// Nothing an encoder produces looks like this, so there is nothing to
// undo and no round trip worth running.
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.go
index 624d39d391..db7486bf3e 100644
--- a/server/internal/integrations/wecom/outbound.go
+++ b/server/internal/integrations/wecom/outbound.go
@@ -1,49 +1,13 @@
package wecom
-// outbound.go — the WeCom EventChatDone / EventInboxNew subscriber. An agent's
-// answer leaves this process the way every other WeCom write does: over the
-// aibot WebSocket held in the sendersRegistry. aibot has no outbound REST path,
-// so there is nothing else to fall back on.
+// Send WeCom completions and inbox events through the lease-holding WebSocket.
+// Seal the task's existing stream bubble when available, including for empty
+// completions; otherwise send an addressed plain message from the delivery row.
//
-// Two shapes of write, tried in this order. A round that opened a bubble when
-// the question arrived has its answer written INTO that bubble and the bubble
-// sealed — that is the whole point of the streaming reply, and it is why an
-// empty completion still has to reach this far: a spinner nobody closes is
-// worse than a short answer (stream_store.go, typing_indicator.go). A round
-// with no bubble left — a restart mid-run, a stream past its window, a frame
-// the server refused — gets an ordinary message addressed by the task's own
-// delivery row.
-//
-// REPLICA TOPOLOGY: EventChatDone / EventInboxNew are dispatched on the
-// in-process events.Bus, so the replica that publishes an event is not
-// necessarily the one holding the bot's WS lease (Slack/Lark are immune —
-// their outbound is stateless HTTP any replica can perform).
-//
-// With a sharded/dual realtime relay running, a reply or inbox push produced
-// off-lease is forwarded to the lease holder over the relay
-// (relay_outbound.go) and the single-replica constraint no longer applies to
-// routing. Without a relay — legacy mode, or no REDIS_URL — the constraint
-// stands: run the WeCom-enabled backend as a single replica. In every mode, a
-// delivery produced while NO replica holds a live connection (all of them
-// mid-reconnect) is still lost; that residual window is a durability problem
-// the relay deliberately does not solve. Boot logs which of the two regimes is
-// in effect. See router.go.
-//
-// The bubble path and the relay never contend for the same turn. A bubble is
-// writable only on the replica that painted it, which is the replica holding
-// the socket; a round whose bubble lives elsewhere finds none here and takes
-// the addressed path, which is where the relay is.
-//
-// They MEET on the replica that takes a relayed reply. That replica is by
-// definition the one holding the socket, which is the one that painted the
-// bubble — a bubble is writable only where it was painted — so the frame
-// carries the task id and deliverRelayed seals the round with it instead of
-// pushing a second message underneath (relay_outbound.go). A relayed reply
-// whose round is gone, or whose seal is refused, takes the ordinary addressed
-// path, which is what a single-replica answer does too.
-//
-// Sessions with no wecom binding are ignored so this coexists with the Slack /
-// Lark subscribers on the shared bus.
+// Off-lease events require Redis relay. Without it, deployments need one backend
+// replica; no live connection can still lose a delivery. Relayed replies carry
+// task IDs so the receiver seals the original bubble instead of duplicating it.
+// Ignore sessions without a WeCom binding.
import (
"context"
diff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.go
index 8b03bee5c4..6e1fbcd776 100644
--- a/server/internal/integrations/wecom/relay_outbound.go
+++ b/server/internal/integrations/wecom/relay_outbound.go
@@ -1,56 +1,15 @@
package wecom
-// relay_outbound.go — how a reply reaches the replica that can send it.
+// Relay completions to the replica holding the bot's WebSocket lease.
+// Redis claims keyed by turn deduplicate replay across restarts and replicas.
//
-// WeCom is the one channel with no outbound REST path: every write goes over
-// the aibot WebSocket, and the WS lease means exactly one replica holds it.
-// chat:done, meanwhile, is published on the in-process events.Bus by whichever
-// replica served the daemon's POST /tasks/{id}/complete — a load-balancer
-// decision. Off-lease, outbound.go used to have nothing to do but drop the
-// reply (GH #7215, #6890; SELF_HOSTING.md states the resulting constraint).
+// Relay consumers run on the shard reader, so enqueue bounded work and return
+// without waiting for platform acknowledgements. Register before readers start;
+// Attach supplies the eventual handler while early frames wait in the queue.
//
-// This routes it over the Redis Stream relay the repository already runs for
-// exactly this shape of problem: daemonws.RelayNotifier wakes a daemon
-// connected to another replica by publishing under ScopeDaemonRuntime, and
-// every node's XREAD loop hands the frame to whoever holds that connection.
-//
-// THREE THINGS THAT MECHANISM REQUIRES OF ITS CONSUMERS, and that a naive copy
-// of the daemon-wakeup shape does not satisfy:
-//
-// 1. It replays. A shard reader starts from (now - ReplayGrace), not "$", so
-// events published while a pod was down are re-read — its own doc says
-// "downstream consumers must be idempotent". A per-process seen-set is not
-// idempotent across a restart, and does not span two replicas either. The
-// claim therefore lives in Redis, keyed on the turn, with a lifetime that
-// comfortably outlasts the replay window. Redis is not a new dependency
-// here: it IS the transport. No Redis means no relay, which means no
-// cross-replica delivery and nothing to deduplicate.
-//
-// 2. It calls the consumer SYNCHRONOUSLY on the shard read loop. The daemon
-// wakeup's work there is a map lookup and a buffered write; ours is a
-// network round trip that waits up to ackTimeout for the platform's
-// verdict. Doing that inline would let one unhealthy bot stall browser
-// realtime traffic, daemon wakeups, and every other bot on that shard. So
-// DeliverWecomOutbound only hands the frame to a bounded queue and
-// returns.
-//
-// 3. Its readers start early. Registration therefore has to be possible
-// before the senders registry and the subscriber exist: this object is
-// built and registered first, and Attach supplies the handler afterwards.
-// Frames that arrive in between wait in the queue rather than being
-// dropped against a nil field.
-//
-// ORDERING: every reply for one installation is carried by one queue and one
-// worker, in the order it arrived — INCLUDING across a re-offer. A frame that
-// has to be tried again does not go to the back of the queue; it parks at the
-// head of its own installation's line and everything behind it waits, because
-// two answers to the same person arriving in the wrong order is the defect
-// this ordering exists to prevent.
-//
-// Sharding is a CONCURRENCY bound, not an isolation guarantee: installations
-// are hashed onto RelayConfig.Shards queues, so two bots that collide on a
-// shard do wait behind each other. What the shard count buys is that one slow
-// bot cannot occupy every worker.
+// Preserve per-installation order across re-offers by retrying at the queue head.
+// Hashed shards bound concurrency, not isolation: colliding installations can
+// still wait behind each other.
import (
"context"
diff --git a/server/internal/integrations/wecom/stream_store.go b/server/internal/integrations/wecom/stream_store.go
index bec971b965..4da94764ac 100644
--- a/server/internal/integrations/wecom/stream_store.go
+++ b/server/internal/integrations/wecom/stream_store.go
@@ -1,100 +1,19 @@
package wecom
-// stream_store.go — the handles that let each answer land in the bubble its
-// question opened.
+// Stream handles map each chat session's pending answers to writable WeCom bubbles.
+// They are an in-memory cache: missing, expired, or rejected handles fall back to
+// plain messages addressed by the task's delivery row.
//
-// WeCom's aibot API has no typing indicator, no reaction, no read receipt, and
-// no way to edit a message after the fact. The one affordance it does have is
-// the streaming message: an aibot_respond_msg frame with finish=false paints a
-// bubble the client renders as "working", and a later frame carrying the SAME
-// stream.id replaces that bubble's body in place — finish=true seals it and
-// nothing can touch it again
-// (https://developer.work.weixin.qq.com/document/path/101463).
+// Messages join the collecting round; each queued run takes the oldest unbound
+// round. Sequence order, not arrival-time estimates, pairs the two. A task event
+// may precede its bubble, so unmatched runs wait in the session's pending queue.
+// After binding, lifecycle events match task IDs. Retries resolve the original
+// round through chat_input_task_id rather than taking another question's bubble.
//
-// THIS STORE IS A CACHE, NOTHING MORE. It maps a chat session to the bubbles
-// that can still be written to. An ending that finds a writable bubble writes
-// into it; one that does not goes out through the plain aibot_send_msg path
-// that outbound.go already has, addressed by the task's own delivery row. A
-// bubble that cannot be written to — never painted, past its window, lost to a
-// restart, or refused by the server when the closing frame goes out — is
-// simply not used. Nothing here records what was said, what is owed, or who
-// was told; nothing owes anyone anything once the bubble is gone.
-//
-// A session holds a LIST of open bubbles, not one. Messages the engine's
-// debouncer collects into one agent run share a bubble; a message it gives a
-// run of its own gets a bubble of its own, queued behind the run in flight —
-// immediately, because a message that produces nothing on screen reads as a
-// message that was lost.
-//
-// WHICH RUN A BUBBLE STANDS FOR IS DECIDED HERE, from two facts that arrive on
-// their own and in either order:
-//
-// - A message was ingested (open). That is a bubble, and nothing more — at
-// that moment nobody knows whether the debouncer will answer it with a run
-// of its own or fold it into the one already collecting.
-// - A chat run was queued for this session (bindNext, driven by the
-// task:queued subscription in typing_indicator.go). That is a run, and
-// nothing more — the event names a task and a chat session and says
-// nothing about which message produced it.
-//
-// The pairing rule is position, and position alone: a queued run takes the
-// OLDEST round that has no run yet, and a message joins the round that is
-// still collecting rather than opening a second one. That works because the
-// engine serializes a session's chat tasks (ClaimAgentTask) and its debouncer
-// produces at most one run per window, so per session the two sequences are in
-// step. Nothing here re-measures the debounce gap from arrival times: whether
-// a message opens a round or joins one is read off "is a round still waiting
-// for its run", not off a clock.
-//
-// The rounds are kept sorted by the store's own sequence number (insertLocked),
-// which for one session is the order its bubbles were painted in, and that
-// order IS consumed: bindNext and takeOldestUnbound both take the oldest
-// unbound round.
-//
-// The event can beat the bubble. The Router detaches the ingest goroutine, and
-// a session's first message enqueues its task inside dispatch (router.go's
-// startChat path) rather than on the debounced flush, so task:queued routinely
-// arrives before anything is painted. A run with no round to take waits in the
-// session's pending queue and is picked up by the next bubble.
-//
-// The task id, once bound, is what every later lifecycle event matches on —
-// never a position. An auto-retry clone carries a fresh id and inherits its
-// parent's chat_input_task_id, which is this round's own task id: see
-// roundTaker, which resolves the clone through it, and retryUnbind, which puts
-// the round back in line for the clone's own task:queued so the clone never
-// takes a bubble some other question opened.
-//
-// The catch is req_id. Every frame of one stream has to echo the req_id of the
-// aibot_msg_callback that started the turn, and that value is only ever seen
-// by the WebSocket read loop. The answer shows up minutes later on an event
-// bus subscriber holding nothing but a chat_session_id. This store is the seam
-// between the two: session in, {req_id, stream id, addressing} out.
-//
-// IN-MEMORY IS THE RIGHT STORAGE, and deliberately so. One bot is one long
-// connection, and the Supervisor's WS lease already guarantees at most one
-// replica holds it, so a handle is only ever useful in the process that
-// created it. A restart loses the handles and the answers fall back to plain
-// messages — degraded, not corrupted. Persisting them would be a trade rather
-// than a fix: a stored handle still inside the window would be writable from
-// the new process, at the cost of a row per bubble and a sweep to retire them,
-// to save a fallback message on the restart that lands mid-run.
-//
-// A RECONNECT IS NOT A RESTART, and the difference is why this store is built
-// once at boot, outside the connection loop (router.go). A handle outlives the
-// socket it was made on, and WeCom scopes a callback's req_id to the turn
-// rather than to that socket (measured 2026-08-09; sendersRegistry.stream
-// carries the detail), so the bubble a question opened before a drop is closed
-// by the answer over the next connection. A store rebuilt per connection, or
-// emptied when one ends, would leave every reconnect's bubbles spinning with
-// nothing left that could close them.
-//
-// Replay is not this file's problem. WeCom redelivers callbacks after a
-// reconnect, but a redelivered frame loses the dedup claim in
-// channel_inbound_message_dedup and never reaches OutcomeIngested, so it never
-// reaches the typing indicator either. What this file does bound is the
-// protocol's own window: a stream past streamMaxAge is refused by the server,
-// and a handle past that age is worse than no handle at all — it would swallow
-// the answer instead of delivering it.
+// Handles include the callback req_id needed by later stream frames. Keep this
+// store outside the connection loop: handles survive reconnects but are lost on
+// process restart. The bot lease limits writes to one replica, and streamMaxAge
+// bounds handle lifetime. Inbound dedup handles replay before it reaches this store.
import (
"context"
diff --git a/server/internal/integrations/wecom/types.go b/server/internal/integrations/wecom/types.go
index beff6f2688..050b2bb647 100644
--- a/server/internal/integrations/wecom/types.go
+++ b/server/internal/integrations/wecom/types.go
@@ -1,60 +1,15 @@
-// Package wecom is the WeCom (企业微信) smart-bot ("智能机器人" / aibot)
-// adapter for the channel-agnostic inbound engine (MUL-3620). It plugs into the
-// same engine.Router / ResolverSet as Feishu and Slack.
+// Package wecom adapts WeCom smart bots to the shared channel engine.
+// Each installation owns a leased WebSocket authenticated by bot_id and secret;
+// inbound callbacks, replies, and media uploads use that connection.
//
-// Unlike the internal customer-service ("内部客服号") flow which is HTTP-callback
-// based, the smart-bot flow is a client-initiated WebSocket long connection
-// against wss://openws.work.weixin.qq.com. Each installation carries a
-// (bot_id, secret) pair; after the WS handshake the client subscribes with
-// aibot_subscribe and thereafter receives aibot_msg_callback events and sends
-// aibot_send_msg / aibot_respond_msg / aibot_upload_media_* over the same
-// socket. No public callback URL is required.
+// Only the lease-holding replica can write. Redis Stream relay routes completions
+// from other replicas; without relay, a WeCom backend requires a single replica.
+// No live connection means delivery can still be lost. Per-chat quotas bound
+// outbound waits and retries. See SELF_HOSTING.md for deployment requirements.
//
-// One installation = one bot = one WebSocket. WeCom allows only one active
-// connection per bot; a second connection kicks the first with a
-// disconnected_event. That single-active-connection guarantee lines up with
-// engine.Supervisor's WS lease, so the multi-replica invariant (at most one
-// active connection per installation across processes) already holds without
-// wecom-specific code.
-//
-// Maintenance: this package is COMMUNITY-MAINTAINED. Its maintainers, the
-// support boundary and the retirement rule are published at
-// https://multica.ai/docs/community-maintained
-// (apps/docs/content/docs/community-maintained.mdx, four locales). That page
-// is the single source of truth — record ownership changes there, not here.
-// Changing the shared channel engine? Keep this adapter building, and loop in
-// its maintainers for anything that changes WeCom-visible behavior.
-//
-// Inbound handles text, the transcript WeCom returns for a voice note,
-// photos, files, videos and 图文混排 (media_ingest.go downloads and decrypts
-// what a callback points at); a kind it cannot read still gets a short
-// receipt.
-//
-// Outbound file delivery cannot report back to the agent that produced the
-// file. `multica attachment upload` returns once the object is in storage and
-// bound to the reply, while the send into the room runs on EventChatDone —
-// after the run has ended. A delivery that is shed, refused by WeCom, or lost
-// with the socket is therefore told to the person in the chat
-// (outbound_media.go) and never to the agent, which has already exited.
-// Routing that outcome back into a later turn is its own piece of work.
-//
-// Outbound no longer requires a single backend replica. The only send path is
-// still the in-process WebSocket in sendersRegistry, held by whichever replica
-// owns that bot's lease, so a reply produced on another replica is routed to
-// the lease holder over the Redis Stream relay (relay_outbound.go). Where
-// there is no relay to route it — legacy relay mode, or no Redis at all — the
-// reply is dropped, and a WeCom-enabled backend has to run as a single
-// replica. In every mode, a reply produced while NO replica holds a live
-// connection (all of them mid-reconnect) is still lost. See SELF_HOSTING.md.
-//
-// Every aibot_send_msg leaves under a per-chat quota gate (rate_limit.go).
-// A chat slightly over WeCom's quota has its push delayed into the next free
-// slot; one that bursts past what the caller's budget can wait for is refused
-// before the write, with nothing on the wire — best effort, not lossless. A
-// frame WeCom throttles anyway is retried once, when the caller can still
-// afford the wait. The gate holds no shared state: the same lease that makes
-// one replica the only sender makes that replica's own count the platform's
-// count.
+// Files are delivered after the agent exits, so failures are reported to the chat
+// rather than the producing run. Community ownership and support boundaries live
+// at https://multica.ai/docs/community-maintained.
package wecom
import (
diff --git a/server/internal/integrations/wecom/typing_indicator.go b/server/internal/integrations/wecom/typing_indicator.go
index d6d240c5a5..de8bbb90fd 100644
--- a/server/internal/integrations/wecom/typing_indicator.go
+++ b/server/internal/integrations/wecom/typing_indicator.go
@@ -1,46 +1,14 @@
package wecom
-// typing_indicator.go — WeCom's answer to "the bot heard you".
+// WeCom uses an open reply stream as its typing indicator. Every terminal path
+// must seal a live bubble with visible text, including failure, cancellation,
+// and a flush that produced no task. Normal answers close from outbound.go;
+// OnSettled handles the no-task case.
//
-// Slack stamps 👀 on the user's message, Feishu a typing badge. WeCom has
-// neither: the smart-bot protocol publishes no reaction, no read receipt and
-// no typing signal at all. What it does have is the streaming message, so the
-// same engine.TypingNotifier interface means something different here — the
-// indicator IS the reply, opened early and filled in later. Two consequences
-// follow from that, and both shape this file:
-//
-// - The bubble MUST be closed. A reaction that never clears is untidy; a
-// stream that never finishes is a spinner sitting in the user's chat for
-// good. So every way a turn can end — answered, failed, cancelled, never
-// started — writes a closing frame carrying visible text into the bubble
-// while there is one.
-// - OnSettled is not the normal ending. As on the other platforms the Router
-// only calls it when the flush produced no task run; the answer closes the
-// bubble from the chat-done subscriber in outbound.go, which is the only
-// place that has the answer to close it with.
-//
-// WHICH RUN A BUBBLE IS WAITING FOR COMES OFF THE BUS. The engine tells this
-// notifier that a message was ingested and nothing else — not which messages
-// the debouncer collected together, not the task the flush created — so the run
-// announces itself instead, on the task:queued every enqueue path already
-// publishes (Register, handleTaskQueued). A bubble pairs with the run queued
-// for its session while it was the one waiting, and from that binding every
-// later ending matches by task id. The alternative was for the engine to carry
-// two more facts through the Router for one platform's benefit.
-//
-// The bubble is a CACHE and nothing more (stream_store.go). A closer that
-// finds one writes into it; one that does not says its words as an ordinary
-// message where the words are worth saying — a failed run's notice — and stays
-// silent where they are not. Nothing is owed on the strength of a bubble that
-// is gone.
-//
-// TWO FRAMES PER ROUND, and no more: the opening one that paints the spinner,
-// and the closing one that replaces it with the answer. The stream's own
-// ten-minute window is counted from the opening frame and is not extended by
-// anything written in between (streamMaxAge), so a run that outlives it loses
-// its bubble and answers as an ordinary message — one message, whole. Filling
-// the bubble in while the run is going, and carrying a long run over onto a
-// fresh stream, are a separate layer on top of this one.
+// Pair pending bubbles with task:queued events, then match later events by task
+// ID. Missing or expired cache handles fall back to addressed messages where
+// needed. Each round sends opening and closing frames only; the stream lifetime
+// runs from opening and is not extended by intermediate writes.
import (
"context"
diff --git a/server/internal/metrics/wecom.go b/server/internal/metrics/wecom.go
index 5c3579b681..2ddb3f53f7 100644
--- a/server/internal/metrics/wecom.go
+++ b/server/internal/metrics/wecom.go
@@ -2,55 +2,15 @@ package metrics
import "github.com/prometheus/client_golang/prometheus"
-// WecomMetrics is the production sink behind the WeCom adapter's Metrics
-// interface (server/internal/integrations/wecom/metrics.go).
+// WecomMetrics implements the adapter's production metrics sink.
+// Separate infrastructure connection failures from credential rejections so
+// operators can distinguish retryable outages from installations needing repair.
+// The adapter classifies acknowledgements; this sink records its verdict.
//
-// The adapter is built to degrade quietly. A dial that fails and a handshake
-// the server refuses both yield the connection back to the Supervisor, which
-// backs off and tries again; an ingest queue the read loop has to wait on
-// yields nothing and simply stops draining the socket until the worker
-// catches up. None of the three changes anything an operator can see. A bot
-// that has been down since Tuesday and a bot nobody happened to message today
-// produce the same silence.
-//
-// The two connection counters are deliberately separate. A dial or a read that
-// fails is infrastructure and usually recovers on its own; a handshake the
-// server refuses on its merits is a wrong secret or a deleted bot, and it will
-// repeat identically on every backoff until a person fixes the installation.
-// Summed into one number the operator cannot tell "wait" from "rotate the
-// credential".
-//
-// Which side of that line an ack falls on is classifySubscribeAck's call, in
-// the adapter, and this package only counts the verdict. An ack it cannot
-// verify — a throttle, a platform-side failure — is a connect failure, on the
-// "wait" side, because rotating a credential that was fine costs a second
-// outage.
-//
-// No installation_id label anywhere. It is the same class of unbounded
-// identifier as workspace_id and session_id, which forbiddenMetricLabels
-// rejects outright. Attribution falls to the structured logs and is uneven
-// there: the two connection failures reach the Supervisor as a returned error
-// and are logged with installation_id, while a blocked ingest queue is
-// counted and nothing else — the counter says some bot is behind, not which.
-// The outbound counters answer a different question from the connection ones,
-// and it is the question GH #7215 and #6890 were filed as: a reply was
-// produced, the transcript has it, and the WeCom chat stayed quiet. Several
-// unrelated causes end that way and from the chat they are one symptom, so
-// each is counted where an operator can act on it: a frame the platform
-// refused, or no socket for this installation in this process, is a drop; a
-// turn that originated in the web UI, another platform's turn on the bus this
-// adapter shares, or an installation revoked between trigger and reply, was
-// never owed to WeCom and is a skip — as is a channel turn with no row saying
-// which chat, the one skip worth waking somebody for, because there a reply may
-// well be owed and nothing left can name the room; a frame whose verdict never
-// came back may already be on the user's screen and is unconfirmed, not a
-// drop. Delivered is the denominator: without it, a drop rate of zero and a bot
-// nobody messaged look identical, which is the same ambiguity the connection
-// counters exist to remove.
-//
-// reason is a closed set (wecom/outbound_outcome.go). It is the only label
-// here, and it stays bounded by construction — no installation, workspace or
-// session id, same rule as everywhere else in this package.
+// Outbound outcomes distinguish delivered, dropped, skipped, and unconfirmed
+// frames. A missing acknowledgement may already be visible to the user and is
+// not a confirmed drop. Reasons are bounded by wecom/outbound_outcome.go;
+// installation, workspace, and session IDs belong in logs, never metric labels.
type WecomMetrics struct {
ConnectFailures prometheus.Counter
AuthFailures prometheus.Counter
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index d6e015f639..c7a7085016 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -26,12 +26,10 @@ import (
"github.com/multica-ai/multica/server/pkg/protocol"
)
-// IssueService is the single service-layer entry point for creating issues.
-// Both the HTTP `POST /issues` handler and the future Lark `/issue` command
-// call into Create so that duplicate guard, issue numbering, attachment
-// linking, broadcast, analytics, and agent/squad enqueue stay aligned. The
-// service deliberately does NOT depend on http.Request — callers parse
-// their own transport and pass a fully-resolved IssueCreateParams.
+// IssueService is the shared issue-creation entry point for HTTP and channel
+// callers. It keeps numbering, duplicate guards, attachments, broadcasts,
+// analytics, and agent/squad enqueue aligned. Callers resolve transport inputs
+// into IssueCreateParams; the service does not depend on http.Request.
type IssueService struct {
Queries *db.Queries
TxStarter TxStarter
diff --git a/server/internal/util/path.go b/server/internal/util/path.go
index 0419b75c7e..324cf70b05 100644
--- a/server/internal/util/path.go
+++ b/server/internal/util/path.go
@@ -52,53 +52,17 @@ func ResolveSymlinks(p string) (string, error) {
return canonicalSpelling(resolved), nil
}
-// ResolveSymlinksBestEffort canonicalizes p the way the operating system would
-// open it, as far as the filesystem allows: it follows every symlink in the
-// existing prefix of p — on Windows directory junctions and other reparse
-// points too — applying ".." segments to the FOLLOWED path, not to the string,
-// and re-attaches the part that does not exist yet. The result is absolute,
-// and the error is ErrUnresolvablePath when even a fail-closed answer is
-// impossible to compute (see above).
+// ResolveSymlinksBestEffort returns an absolute path with existing symlinks
+// resolved and an unresolved tail reattached. Return ErrUnresolvablePath when
+// even a fail-closed result cannot be computed.
//
-// Windows path kinds are preserved rather than flattened onto the working
-// directory. A root-relative path (`\tmp\desc.md`) resolves against the root
-// of the working directory's volume, and a drive-relative path (`C:tmp\desc`)
-// against the working directory only when that drive IS the working
-// directory's drive, because those are the files os.ReadFile actually opens.
-// Prefixing either with the working directory instead would let a same-named
-// file inside the workdir shadow the outside file the kernel reads, and a
-// containment check would pass on the shadow. The same grammar applies to
-// link targets, which the kernel resolves by the same rules rather than
-// relative to the link.
+// Resolve .. against the followed path, never a lexically cleaned input: cleaning
+// first can hide a symlink escape. Resolve the longest existing prefix so missing
+// descendants remain in the same namespace as a containment root. Stop descent
+// on any resolution failure, including permission errors.
//
-// Two properties matter to callers that compare the result against a root.
-//
-// First, a path that does not fully exist still has to land in the same
-// namespace as the root. filepath.EvalSymlinks fails outright when any
-// component is missing, and falling back to filepath.Clean does not follow
-// symlinks at all, so the two sides of the comparison end up in different
-// namespaces (on macOS every /tmp and /var path is a symlink into /private) and
-// a path inside the root reads as outside it. Falling back one level via
-// filepath.Dir only narrows that to "the leaf is missing" — and inverts the
-// error for a deeper miss, since an unresolvable tail then reads as inside a
-// root it actually escapes. The walk below resolves the longest prefix the
-// filesystem can speak for and re-attaches the rest, so every component that
-// exists is still resolved and a symlink or junction planted inside the root
-// cannot smuggle a candidate past a containment check. Any resolution error
-// stops the descent, not just "not exists" — permission-denied on an ancestor
-// is equally a "cannot canonicalize here".
-//
-// Second, ".." is resolved physically wherever the filesystem can say so. The
-// path is never lexically cleaned before resolution, because filepath.Clean
-// (and filepath.Abs, and filepath.Join across the whole input) collapse
-// "escape/.." into nothing and thereby cross a symlink boundary invisibly: a
-// caller comparing the cleaned string sees a path inside its root while the
-// kernel would open one outside it. The walk applies each ".." to the resolved
-// prefix, which is the order the kernel uses. Only the tail after the first
-// unresolvable component is joined lexically, where a mismatch is inert — a
-// path with an unresolvable prefix cannot be opened at all.
-//
-// This mirrors Python's Path.resolve(strict=False).
+// Preserve Windows volume-rooted and drive-relative semantics for both input and
+// link targets so the result matches the path the kernel would open.
func ResolveSymlinksBestEffort(p string) (string, error) {
if p == "" {
return "", nil
diff --git a/server/pkg/agent/claude_models.go b/server/pkg/agent/claude_models.go
index d5562d64e7..66d1058df4 100644
--- a/server/pkg/agent/claude_models.go
+++ b/server/pkg/agent/claude_models.go
@@ -10,46 +10,13 @@ import (
"time"
)
-// ── Claude model discovery ───────────────────────────────────────────
+// Discover Claude models through the installed CLI's stream-json list_models
+// control request, including account-specific disabled entries. Cache unsupported
+// subtype responses so older CLIs fall back without repeating the round trip.
//
-// Claude Code has no `--list-models` flag and no models subcommand, which is
-// why this package carried a hand-maintained claudeStaticModels() for so long.
-// It does have a discovery hook, just not on the command line: the stream-json
-// control protocol answers a `list_models` control request with the same
-// ModelInfo rows the interactive /model picker renders.
-//
-// That distinction is the whole point of MUL-6961. A static catalog cannot know
-// what the CLI in front of it can actually run, so every new Anthropic model
-// opened a window where Multica offered a model that 400s ("Claude Code 2.1.246
-// does not support this model; version 2.1.251 or newer is required"). The
-// control protocol closes the window at the source: the answer is computed by
-// the installed binary, against the logged-in account, so a model the local CLI
-// cannot run is either absent or explicitly flagged disabled. Verified against
-// 2.1.223 / 2.1.228 / 2.1.246 / 2.1.258 — the three older builds return Fable
-// 5.1 as a disabled row carrying "Update to 2.1.255+ to use Fable 5.1", and
-// 2.1.258 returns it as a normal selectable entry.
-//
-// This governs SELECTION, and only selection. An agent already configured with
-// a model, whose CLI is downgraded afterwards, still starts and still gets the
-// upstream 400 — discovery cannot reach a value already persisted. That is the
-// accepted boundary, decided on MUL-6961 rather than assumed: the downgrade is
-// a rare case, the upstream error is accurate, and a run that fails loudly at
-// the moment it starts is a fine way to report it. Do not "improve" this by
-// clearing the configured model or substituting a runnable one when the catalog
-// no longer offers it. Clearing turns a legible error into a silent config
-// change the user did not make, and substituting is worse — it succeeds, using
-// a model nobody chose.
-//
-// No version gate guards the request, unlike codexSupportsDebugModels. It would
-// buy nothing: an unsupported subtype is answered, not ignored — every build
-// tested replies `Unsupported control request subtype: ...` in about two
-// seconds and exits 0 — so an old CLI costs one cheap round trip and falls back,
-// with no risk of hanging until the timeout. Gating instead on a version floor
-// would mean hand-maintaining exactly the kind of number this change exists to
-// stop hand-maintaining.
-//
-// "One round trip" is only true because that specific answer is remembered; see
-// claudeListModelsUnsupported below for why it has to be.
+// Discovery governs selection, not stored configuration: never clear or replace a
+// configured model just because the current catalog omits it. A downgraded CLI
+// may reject that model at launch; the error preserves the user's explicit choice.
// claudeListModelsArgs is the argv for a discovery-only Claude session.
//
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 6951b03503..377870f995 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -284,48 +284,13 @@ const codexRetiredCompactPath = "responses/compact"
// what failed, never which route ran.
const codexRemoteCompactMarker = "remote compact task"
-// CodexRetiredCompactionError reports whether an agent error is Codex failing
-// to compact a conversation over the route OpenAI has retired, e.g.
+// CodexRetiredCompactionError identifies failures on the retired
+// /responses/compact route so callers can suggest correcting remote_compaction_v2.
+// Require the path itself: the current route can emit the same compaction prefix
+// and HTTP status, so those alone would produce the opposite advice.
//
-// Error running remote compact task: unexpected status 404 Not Found: {"detail":"Not Found"},
-// url: https://chatgpt.com/backend-api/codex/responses/compact, cf-ray: ..., request id: ...
-//
-// The route is chosen by turning `remote_compaction_v2` off. Older Codex builds
-// ignored that setting, so a value added as a workaround for an unrelated,
-// since-fixed defect can start failing on upgrade without the user touching
-// anything (GH #8000, upstream openai/codex#42468). Nothing in the text names
-// the setting, so the failure is unreadable on its own — which is the whole
-// reason this predicate exists: callers use it to attach the remedy.
-//
-// The retired PATH is what has to be present. The compaction marker alone is
-// not evidence of anything: the v2 route wraps its own failures in the same
-// "Error running remote compact task" prefix, and a v2 stream can return 404
-// too — so keying on the marker plus a status code would tell a user whose
-// setting is already correct to go turn it off, the exact opposite of the fix.
-// The path cannot be produced that way; a compaction request reaching
-// /responses/compact at all means the legacy route was selected, whatever
-// status came back.
-//
-// That leaves a deliberate false negative: a Codex build that reports this
-// failure without the url tail gets no hint. There is no second signal in the
-// text that identifies the route, and the two errors are otherwise
-// indistinguishable, so the choice is between missing some cases and
-// misdirecting the users whose config was never the problem. A missed hint
-// costs what today already costs; a wrong hint spends someone's afternoon.
-//
-// Deliberately NOT a resume-safety predicate. The stuck thread is recoverable:
-// once the setting is right compaction succeeds and the same conversation
-// continues, so retiring the session here would throw away exactly the context
-// the fix restores. Text only.
-//
-// Delete once no Codex old enough to select the retired route is still in use.
-// Upstream intends to mark the flag Stage::Removed or fall back on the 404,
-// and under either fix this predicate simply stops matching: it overrides no
-// config and stands between nobody and a setting they may legitimately want
-// off, so it costs one substring check on an already-failing path until then
-// and comes out in a single commit. That is the difference from forcing
-// `--enable remote_compaction_v2`, which was declined for the opposite reason
-// (GH #8019) — an override outlives the defect and blocks the legitimate case.
+// This is diagnostic text, not a resume-safety verdict or a config override.
+// Correcting the setting can recover the existing conversation.
func CodexRetiredCompactionError(errText string) bool {
if errText == "" {
return false
@@ -1400,48 +1365,13 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
c.markProcessExited(errCodexProcessExited)
}()
- // drainAndWait closes stdin so codex shuts down, then joins cmd.Wait().
- // cmd.Wait() is the only Go-stdlib-documented synchronization point for
- // os/exec's internal stderr/stdout copy goroutines — until it returns,
- // stderrBuf may not have observed every byte codex wrote before it
- // exited, and stderrBuf.Tail() can come back empty or truncated. Any
- // code that reads stderrBuf.Tail() must call drainAndWait() first.
- // sync.Once makes it safe to call from both error paths and the deferred
- // cleanup.
- //
- // drainAndWait is also the cleanup safety net for the scanner-overflow
- // path (#4520). When codex emits a single stdout line larger than the
- // scanner's MaxScanTokenSize, the reader goroutine returns with
- // scanner.Err() set, fails all in-flight RPCs via markProcessExited, and
- // closes readerDone — but the codex child process is still alive and is
- // now blocked trying to write the rest of the oversized line into a
- // stdout pipe nobody is reading. A naive stdin.Close()+cmd.Wait() then
- // hangs forever: codex never reaches its stdin-read syscall, so it never
- // sees EOF, never exits, and cmd.Wait() never returns. The lifecycle
- // goroutine therefore never sends a failed Result, the outer daemon
- // blocks on its result channel, and the higher-level fresh-session
- // fallback never fires.
- //
- // To stay correct under both clean shutdown and the stuck-child case,
- // drainAndWait runs in two bounded phases:
- //
- // 1. Close stdin and wait for the reader goroutine to finish, capped by
- // codexGracefulShutdownTimeout. The reader exits when codex closes
- // stdout on its own (clean shutdown — gives OTEL batch exporters a
- // chance to flush) OR when the scanner errors out (overflow case —
- // readerDone is already closed and the select returns immediately).
- // Per os/exec docs, calling cmd.Wait() while reads are still
- // in-flight on a StdoutPipe-returned pipe is incorrect because Wait
- // closes the pipe and turns pending reads into spurious errors, so
- // we must wait for the reader first.
+ // drainAndWait closes stdin and joins the process exactly once. Read stderrBuf
+ // only after it returns, when os/exec's copy goroutines have finished.
//
- // 2. Wait for cmd.Wait() to return, capped by another
- // codexGracefulShutdownTimeout. Normally this returns immediately
- // because the process has already exited. In the stuck-child case
- // the process is still alive — we cancel the process context, which fires
- // cmd.Cancel (the group-SIGKILL helper installed above), and
- // cmd.WaitDelay then guarantees cmd.Wait() returns even if pipes
- // stay open.
+ // Wait for readerDone before cmd.Wait so Wait cannot close a pipe under an active
+ // read. Bound both reader shutdown and process reaping. Scanner overflow can leave
+ // the child blocked on unread stdout, so cancellation and WaitDelay must also
+ // cover that path instead of relying on stdin EOF to stop the child.
var waitOnce sync.Once
var cleanupConfirmed bool
var waitReturned bool
diff --git a/server/pkg/agent/run_collect_quiet.go b/server/pkg/agent/run_collect_quiet.go
index 7dd8243606..f400bc4bba 100644
--- a/server/pkg/agent/run_collect_quiet.go
+++ b/server/pkg/agent/run_collect_quiet.go
@@ -69,83 +69,23 @@ func JSONOutputComplete(stdout []byte) bool {
return len(trimmed) > 0 && json.Valid(trimmed)
}
-// RunCollectQuiet runs a one-shot CLI command and returns when the process
-// exits, or — for a CLI that will not exit — as soon as it has produced output
-// that `complete` accepts and that has then stayed idle for idleGrace.
-//
-// # Why "output is enough" beats "wait for exit"
-//
-// Measured on a host running openclaw 2026.5.27:
-//
-// openclaw --version 258ms exits cleanly
-// openclaw config file 60s correct path printed, then never exits
-// openclaw agents list 60s correct list printed, then never exits
-//
-// Waiting for exit turns two working commands into a task-fatal error, and they
-// sit on the task's critical path (Prepare -> prepareOpenclawConfig). The
-// contract of those commands is "print a value"; once the value has arrived,
-// whether the process tidies itself up is not the caller's business.
-//
-// Nor is that a quirk of the build those timings came from. Upstream has an
-// explicit opt-in for "print a one-shot answer and then exit" —
-// `requestExitAfterOneShotOutput`, flushed at the end of `runCli` after both
-// streams drain (`src/cli/one-shot-exit.ts`, checked at `v2026.7.1`). In the
-// shipped 2026.7.1 build only `models list`, `models status` and the hooks CLI
-// take it. `config file`, `config get` and `agents list` do not: their success
-// paths only print, so termination is whatever the Node event loop happens to
-// do, and `runtime.exit` appears on their failure paths alone. So a version
-// where they exit promptly is not making a promise a later one has to keep.
-//
-// # Why `complete` is required rather than "any output"
-//
-// An earlier revision returned success from the deadline branch whenever stdout
-// was non-empty. That salvaged partial answers: a CLI still streaming when the
-// deadline arrived had its truncated output reported as success (measured 9 runs
-// in 10 against a 250ms deadline). Two conditions now gate the early return, and
-// neither is sufficient alone:
-//
-// - `complete` accepts the buffer. Idle alone is not enough, because the CLI
-// may be pausing between a banner and the real answer — `openclaw config
-// file` prints Doctor warning UI first (see MUL-3136), and cutting off there
-// yields the banner instead of the path. The rule carries the whole weight of
-// that distinction: review broke a rule that judged the path by *shape* with a
-// warning line that was itself a path, so a rule has to be one the CLI's
-// pre-answer output cannot satisfy at all.
-// - The buffer has then been idle for idleGrace. Complete alone is not enough,
-// because more output may still follow and change the answer.
-//
-// Reaching the context deadline is never success. Whatever was captured is
-// returned alongside the error so a caller with a different rule can inspect it,
-// but this helper does not decide on the caller's behalf.
-//
-// A nil `complete` disables the early return entirely: the call then waits for
-// exit, bounded only by ctx. That is the right default for a command whose
-// output shape has no completeness rule.
-//
-// quiet reports that the return did not come from a clean exit, so callers can
-// log the CLI's misbehaviour without failing on it.
-//
-// Guarantees callers depend on:
-//
-// 1. Returns within roughly the caller's context deadline plus collectDrainGrace,
-// collectReapWindow and collectSettleGrace, whatever the CLI leaves behind.
-// 2. Descendants that are still in the leader's process group are signalled
-// before returning, and the signal is repeated across collectReapWindow so one
-// that was mid-fork does not escape. A descendant that left the group is out
-// of reach on Unix — OpenClaw's helper was measured with its own PGID and SID —
-// which is why guarantee 1 does not depend on the kill landing. Windows is
-// different: the Job Object owns the tree irrespective of groups.
-// 3. Output is not abandoned while something may still be writing it: after the
-// direct child exits, the call waits for pipe EOF unless `complete` says the
-// answer is in. Leader exit alone is not treated as completion.
-// 4. Retention is bounded — collectStdoutLimit for the answer (reported, not
-// silently truncated) and collectStderrTail for the diagnostic sample.
-// 5. The command's real exit status is reported, which openclawShimDiagnostic
-// depends on (it type-switches on *exec.ExitError).
-//
-// Use this only for commands whose entire output is a short one-shot response.
-// Anything that streams incrementally (agent execution) must keep its own
-// lifecycle handling, where a pause in output carries meaning.
+// RunCollectQuiet collects a short one-shot response until process exit, or
+// until complete accepts the buffer and no output arrives for idleGrace.
+// Both checks are required: banners can be idle, and a complete-looking answer
+// may still be followed by output. A nil complete disables early return.
+//
+// Context expiry is always an error, with captured output returned for inspection.
+// quiet distinguishes accepted output from a clean process exit.
+//
+// The collector owns pipes and process cleanup so descendants holding stdout do
+// not extend the deadline beyond the drain/reap/settle grace windows. Unix signals
+// reach the original process group; Windows uses a Job Object. The return bound
+// does not depend on every descendant being reachable.
+//
+// Leader exit alone is insufficient: wait for pipe EOF unless complete accepts
+// the answer. Retention is bounded and overflow is reported; preserve the real
+// exit status for callers inspecting exec.ExitError. Streaming agent execution
+// needs its own lifecycle handling and must not use this helper.
func RunCollectQuiet(ctx context.Context, env []string, idleGrace time.Duration, complete OutputComplete, execPath string, args ...string) (stdout []byte, stderr string, quiet bool, err error) {
// Command.exec, not exec.CommandContext: launch.go owns process construction so
// a custom runtime's fixed_args prefix cannot be dropped (GH #7046). A zero
diff --git a/server/pkg/composio/doc.go b/server/pkg/composio/doc.go
index 34cbaa4513..a81bdab4ab 100644
--- a/server/pkg/composio/doc.go
+++ b/server/pkg/composio/doc.go
@@ -1,56 +1,8 @@
-// Package composio is a small, standalone Go SDK for the Composio v3.1 REST API.
+// Package composio provides a standalone client for the Composio REST API.
+// It covers connection management, toolkit/auth-config discovery, MCP sessions,
+// tool execution, and webhook verification without Multica-specific dependencies.
//
-// It is intentionally self-contained: the only third-party dependency is
-// [github.com/go-resty/resty/v2]. It does not import any Multica-specific
-// package, so it can be reused by other Go services or extracted into its
-// own module unchanged.
-//
-// # MVP surface
-//
-// The SDK targets the surface required by the Composio integration MVP
-// (see MUL-3715 / MUL-3720). It is deliberately minimal — only the
-// endpoints actually used by the first-stage product are wired up:
-//
-// - Connect Link — POST /connected_accounts/link
-// - MCP Session — POST /tool_router/session
-// - Connected Accounts — GET /connected_accounts,
-// POST /connected_accounts/{id}/revoke,
-// DELETE /connected_accounts/{id}
-// - Toolkits — GET /toolkits, GET /toolkits/{slug}
-// - Tool Execute — POST /tools/execute/{tool_slug}
-// - Webhook — HMAC-SHA256 signature verification
-//
-// More surface (auth configs, triggers, proxy execute, etc.) can be
-// added later without changing the existing types.
-//
-// # Quick start
-//
-// client, err := composio.NewClient(composio.Options{
-// APIKey: os.Getenv("COMPOSIO_API_KEY"),
-// })
-// if err != nil { return err }
-//
-// link, err := client.CreateLink(ctx, composio.CreateLinkRequest{
-// AuthConfigID: "ac_abc",
-// UserID: "u_123",
-// CallbackURL: "https://app.example.com/composio/callback",
-// })
-// // redirect user to link.RedirectURL
-//
-// session, err := client.CreateSession(ctx, composio.CreateSessionRequest{
-// UserID: "u_123",
-// })
-// // agent runtime now consumes session.MCP.URL + composio.MCPAuthHeaders(...)
-//
-// # Errors
-//
-// All non-2xx responses come back as a *APIError carrying the upstream
-// status, slug, and message. Transport errors come back unwrapped from
-// resty so callers can errors.Is/As as usual.
-//
-// # Webhook verification
-//
-// [VerifyWebhook] verifies the HMAC-SHA256 signature Composio attaches
-// to every webhook delivery, with a configurable replay tolerance.
-// See https://docs.composio.dev/docs/setting-up-triggers/subscribing-to-events#verifying-signatures
+// Non-2xx responses return an APIError with upstream status, slug, and message;
+// transport errors remain inspectable with errors.Is/As. VerifyWebhook checks
+// HMAC-SHA256 signatures with a configurable replay tolerance.
package composio
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 56289d1ef7..b58582e0e9 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -2873,82 +2873,22 @@ type CreateRetryTaskParams struct {
NewTaskID pgtype.UUID `json:"new_task_id"`
}
-// Fenced against workspace teardown: lock_task_owner_rows (migration 284)
-// locks the owners' workspace rows in the writer's own transaction and returns
-// false once they are gone, so this statement writes no row instead of stranding
-// a task in a workspace that has just been deleted (MUL-5999).
-//
-// Fenced against slot contention too: ON CONFLICT DO NOTHING yields the single
-// queued/dispatched slot idx_one_pending_task_per_issue_agent_v2 allows per
-// (issue, agent) rather than raising 23505. A manual rerun may now be enqueued
-// behind a still-running task, and it can commit at any point — including
-// between a caller's "is a successor already pending?" check and this insert,
-// since that check takes no lock. Raising here would abort the caller's
-// transaction, and on the FailTask path that transaction also carries the
-// parent's failed status, so the failure would roll back and leave the task
-// stuck in 'running'. Yielding instead makes the policy explicit: whoever
-// already holds the slot keeps it, and a deliberate human rerun therefore wins
-// over an automatic retry.
-//
-// Both fences surface the same way — zero rows, i.e. pgx.ErrNoRows from this
-// :one query. Callers must treat that as "no retry was created" and still commit
-// their own work, NOT as a failure.
-// Clones a parent task into a fresh queued attempt. Carries forward the
-// agent's resume context (session_id/work_dir) so the child can continue
-// the conversation when the backend supports it. Resume-unsafe failures are
-// retried as fresh sessions so the child does not inherit a stuck agent
-// conversation, but work_dir is still carried forward: a poisoned
-// conversation says nothing about the files it left behind, and the claim
-// handler offers that workdir to the fresh session (MUL-7034). Keep the CASE
-// WHEN predicates in sync with resumeUnsafeFailureReason and the resume lookup
-// blacklists. attempt is
-// incremented; max_attempts, trigger_comment_id, coalesced_comment_ids,
-// is_leader_task, and squad_id are inherited so the retried task receives the
-// parent's complete planned comment batch and keeps the same squad-role
-// provenance. delivered_comment_ids intentionally stays at its '{}' default:
-// the child must earn its own delivery receipt at claim time.
+// Clone an attempt with inherited attribution, planned comments, and input-batch
+// identity. The child earns its own delivered-comment receipt at claim time.
+// Preserve a NULL chat_input_task_id for legacy/channel parents rather than
+// promoting untagged history to the task-owned input path.
//
-// originator_user_id is inherited so the Composio overlay decision sees the
-// same top-of-chain human across the retry: the user behind the original
-// run has not changed. The Composio overlay follows the agent's invocation
-// permission and uses the agent owner's connection (MUL-3963); originator is
-// carried for A2A/audit, not as an originator == agent.owner_id gate.
-// A system retry is NOT a new attribution event (MUL-4302 §5): it inherits the
-// parent's accountable human, source label, delegation lineage, rule version,
-// and trigger evidence UNCHANGED, and records retry_of_task_id = p.id so retry
-// and manual rerun stay separable in reporting. parent_task_id keeps its
-// existing meaning for the retry/resume machinery; retry_of_task_id is the
-// attribution-facing lineage column.
+// Keep work_dir for every retry, but clear resume context for unsafe sessions.
+// Keep failure predicates aligned with resumeUnsafeFailureReason and resume lookups.
+// Composio uses the agent owner's connection; originator remains audit provenance.
//
-// chat_input_task_id is inherited straight from the parent so the whole retry
-// chain keeps consuming the ORIGINAL root input batch (MUL-4351): the root
-// direct task set it to its own id, every descendant copies that value, and a
-// claim always reads the same user messages. A plain copy (not
-// COALESCE(parent.chat_input_task_id, parent.id)) is deliberate: legacy/channel
-// parents carry NULL and must stay NULL so their retries keep the trailing
-// selector — promoting a pre-migration NULL row to the task-owned path on retry
-// would risk replaying untagged history during a rolling deploy.
+// Owner-row locks fence workspace teardown. Slot conflicts yield no row instead
+// of aborting the caller's failure transaction; pgx.ErrNoRows means commit the
+// parent transition without a retry. Pending human reruns retain their slot.
//
-// Chat retries are queued at GREATEST(priority, 3) so a transiently-failed
-// earlier turn is re-claimed ahead of any fresh chat task (priority 2) the user
-// queued while the failing turn was still running — the retry continues the
-// older turn first. Combined with creating the retry inside FailTask's
-// transaction, this leaves no window for a newer input task to jump ahead.
-//
-// fire_at arms a backoff before the retry: when non-NULL the child is inserted
-// as 'deferred' with that fire_at and stays inert until the existing
-// PromoteDueDeferredTasksForRuntime sweeper (run promote-first on every claim
-// poll) flips it to 'queued'. Used for runtime_offline so the child waits for a
-// healthy runtime, and for provider_network's final attempt so it waits ~5s
-// instead of firing back-to-back with the immediate retry (MUL-4910). NULL
-// keeps the historical behaviour: an immediately-claimable 'queued' child.
-//
-// max_attempts overrides the inherited budget when non-NULL (NULL inherits
-// p.max_attempts unchanged). Callers persist the reason-aware effective ceiling
-// here so the row stays self-consistent — e.g. provider_network's chain records
-// attempt=3, max_attempts=3 rather than leaking attempt=3, max_attempts=2 to the
-// task API (MUL-4910). The Go retryAttemptCeiling already refuses to raise a
-// disabled (max_attempts<=1) task, so this only ever widens, never revives.
+// Chat retry priority keeps older input ahead of newer turns. A non-NULL fire_at
+// defers dispatch until promotion. max_attempts optionally persists the effective
+// ceiling; it does not re-enable tasks whose retry budget was disabled.
func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, createRetryTask,
arg.ID,
@@ -3207,68 +3147,14 @@ type ExpireStaleQueuedTasksParams struct {
MaxPerTick int32 `json:"max_per_tick"`
}
-// Fails queued tasks whose runtime can no longer prove it is alive.
-//
-// This used to be a pure wall clock: queued for longer than a TTL (default 2h)
-// meant failed. That conflated "nobody is coming for this task" with "the
-// queue ahead of it is long", and the second one is not a failure. MUL-6558
-// was exactly that — a self-hosted runtime with low task concurrency held its
-// own queue past 2h and healthy work died as queued_expired. The TTL knob
-// added then (MULTICA_TASK_QUEUED_TTL) only moved the cliff; it did not stop
-// a busy runtime from eventually crossing it.
-//
-// So the question is not "how long has this waited" but "is anything still
-// able to pick it up". A runtime that keeps heartbeating is busy, not dead,
-// and its backlog must be allowed to drain however long that takes. The
-// liveness signal is the same one FailTasksForOfflineRuntimes uses for
-// dispatched/running rows, so a daemon going down now retires its queued and
-// its in-flight work on one clock instead of two.
-//
-// The row must ALSO have been queued for a full grace of its own. Enqueue binds
-// a task to agent.runtime_id without checking that the runtime is up, so
-// runtime liveness alone would fail a task the instant it is assigned to a
-// runtime that has been offline a while — a laptop closed overnight would turn
-// "assign this issue" into a failure inside one 30s sweep tick instead of
-// waiting for the machine to come back. Requiring the task's own age keeps the
-// promise the name makes: a queued task gets one full reconnect grace before it
-// is given up on, counted from when it started waiting. It also bounds the
-// scan, which would otherwise re-evaluate the runtime subquery against every
-// queued row on every tick.
-//
-// Heartbeat age is read directly rather than gated on runtime.status='online',
-// so a row stuck at 'online' with a long-dead heartbeat still releases its
-// queue.
+// Expire queued work only when both the task's waiting age and the runtime's
+// heartbeat age exceed reconnect grace. Busy but heartbeating runtimes keep their
+// queues regardless of length. Read heartbeat age directly so a stale online
+// status cannot strand tasks. Missing runtime references are handled defensively.
//
-// The runtime_id IS NULL / missing-runtime arms are fail-closed defence, not
-// live paths: the schema already excludes both. runtime_id was NOT NULL from
-// migration 004 until 251 replaced it with CHECK (runtime_id IS NOT NULL OR
-// completed_at IS NOT NULL), which every insert and update is checked against
-// (NOT VALID only skips the backfill scan), so no queued row can be unbound.
-// A dangling reference is impossible because agent_task_queue_runtime_id_fkey
-// (migration 004) is ON DELETE CASCADE: deleting a runtime removes the rows
-// referencing it rather than orphaning them, and the normal delete path
-// (migration 251, MUL-5559) explicitly unbinds history tasks first in the same
-// transaction. They are kept so a future schema change cannot silently strand
-// rows that have no liveness signal at all.
-//
-// A retry created by runtime_offline is exempt: it deliberately waits for that
-// runtime to reconnect, and FailExpiredRuntimeReconnectRetries owns its exit.
-//
-// Concurrency safety: the daemon's claim path may race with this sweeper to
-// transition the same row out of 'queued'. We protect against that two
-// ways:
-// 1. The CTE selects victims with FOR UPDATE SKIP LOCKED so a row that is
-// currently being claimed (or otherwise locked) is skipped — no lock
-// contention with the dispatch path, and we won't queue up behind it.
-// 2. The outer UPDATE re-checks status='queued' AND the liveness predicate at
-// apply time. If a daemon claimed the row between selection and update
-// (e.g. lock released after the claim transaction commits), the row is
-// already 'dispatched'/'running' and the WHERE clause filters it out
-// so we cannot clobber an in-flight task.
-//
-// Capped via LIMIT inside the CTE so a single sweep tick cannot monopolise
-// the DB when the backlog is large — the sweeper drains the rest on
-// subsequent ticks.
+// runtime_offline retries have a separate reconnect expiry policy and are exempt.
+// Select bounded victims with SKIP LOCKED, then re-check status and liveness in
+// the update so concurrent claims cannot be overwritten.
func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQueuedTasksParams) ([]AgentTaskQueue, error) {
rows, err := q.db.Query(ctx, expireStaleQueuedTasks, arg.ReconnectGraceSecs, arg.MaxPerTick)
if err != nil {
@@ -4443,115 +4329,19 @@ type GetLastTaskSessionRow struct {
IssueSnapshot []byte `json:"issue_snapshot"`
}
-// Returns the session_id and work_dir from the most recent task for a given
-// (agent_id, issue_id) pair, used for session resumption on the auto-retry
-// path. We accept 'completed', 'failed' AND 'cancelled' tasks: a failed task
-// may have established a real agent session before crashing (orphaned by a
-// daemon restart, runtime offline, or sweeper timeout), and the daemon pins
-// the resume pointer mid-flight via UpdateAgentTaskSession. Without this,
-// an auto-retry of a mid-run failure would silently start a fresh
-// conversation and lose the in-flight context — exactly what MUL-1128's B
-// branch is meant to fix.
-//
-// A cancelled task is in exactly the same position, and excluding it was the
-// issue-side half of GH #6340: the pinned session is real (the provider emitted
-// it), the user stopped the run rather than the provider rejecting it, and
-// cancellation records no failure_reason/error for the poison filters below to
-// match on. So a stop-then-comment-again sequence keeps its context instead of
-// silently starting cold. A user who wants a clean slate has manual rerun,
-// which never takes this path (see below).
-//
-// Manual rerun (TaskService.RerunIssue) does NOT take this path. The claim
-// handler branches on rerun_of_task_id FIRST and resolves the session/workdir
-// from that exact source task (so a parallel task on the same issue can't be
-// resumed by mistake), reusing the source workdir and resuming its session only
-// when the source failure is resume-safe. The rerun row still carries
-// force_fresh_session=true purely as a rollback-safe signal: an OLD claim
-// handler that predates the rerun_of_task_id branch falls back to this query,
-// and force_fresh_session=true makes it start clean instead of resuming the
-// wrong execution (MUL-4869).
-//
-// Tasks that ended in a known "poisoned" terminal state are also excluded
-// here so even auto-retry does not inherit the bad session. The daemon
-// classifies these failures (iteration_limit, agent_fallback_message,
-// api_invalid_request, codex_semantic_inactivity, agent_error.context_overflow,
-// codex_resume_oversized)
-// when it detects either an agent fallback marker in the output, an upstream
-// API 400 that means the conversation history itself is unprocessable
-// (oversized image, malformed base64, etc.), a Codex semantic inactivity
-// timeout whose recorded session may replay the same stuck state, a context
-// window overflow that would immediately overflow again on resume, or a Codex
-// thread/resume response too large to read back (MUL-5722). Keep this
-// list in sync with resumeUnsafeFailureReason and GetLastChatTaskSession.
-//
-// The error-text ILIKE clause is defense-in-depth for the api_invalid_request
-// shape: a legacy row tagged 'agent_error' (pre-MUL-1921), a deploy-window
-// row that the old code wrote between migration and rollout, or a future
-// error format that escapes the daemon classifier all still get filtered
-// here as long as the canonical Anthropic 400 marker is present in the
-// error text. Migration 079 backfills the failure_reason column itself,
-// so observability stays accurate; this clause guarantees session resume
-// never picks up a bad session even when failure_reason hasn't caught up.
-//
-// Selection is per-session, not per-row: we first reduce to the single most
-// recent terminal row FOR EACH session_id (DISTINCT ON), then apply the
-// resume-unsafe filter. This closes a poisoning wormhole (GH #5975): when the
-// SAME session_id has both an older 'completed' row (the turn that first baked
-// in the bad history) and a newer poisoned 'failed' row, a plain row-level
-// filter would drop the poisoned row and happily fall back to the older
-// completed row — which points at the exact same dead session. Judging by each
-// session's LATEST terminal state instead means:
-// - a newer poisoned row invalidates the whole session, older completed rows
-// included;
-// - a different, healthy session (distinct id) is still eligible as a
-// fallback;
-// - if that same id later terminates cleanly again, the newer completed row
-// restores its resumability.
-//
-// The oversized-image ILIKE (dimension phrase AND image.source.base64.data) is
-// the GH #5975 analogue of the api_invalid_request defense-in-depth above: a
-// Kiro/ACP resume rejected for an oversized historical image is classified
-// 'api_invalid_request' at write time, but this text clause also blocks a
-// legacy/unclassified row (or a new-server + old-daemon deploy window) from
-// resuming the poisoned session. Both markers are required so the clause stays
-// exactly as narrow as classifyPoisonedError and the Kiro detector — an
-// unrelated error that only mentions image dimensions is NOT excluded.
-//
-// MUL-5722 needed a different shape, and the reason is worth stating because
-// the first attempt got it wrong: a row-level guard like the ones above CANNOT
-// work for an overflowed resume. That failure happens before the turn starts,
-// so the backend has no session id to report and the row lands with session_id
-// NULL — which the latest_per_session CTE drops before any filter runs. The
-// only row naming the oversized thread is the OLDER completed one, which looks
-// perfectly healthy. Hence resume_overflow_at below: block by TIME, which needs
-// nothing from the failed row but its existence. See the clause for details.
-//
-// The final pair of regexes is the provider-agnostic version of the same
-// guard, and it matters most for self-hosted installs: daemons upgrade on
-// their own cadence, so a host still running a daemon without
-// taskfailure.UnresumableHistory reports an empty-message rejection as
-// agent_error.unknown and would otherwise keep resuming the transcript the
-// provider just refused (GH #6066). Both regexes must match — an emptiness
-// complaint AND a locator pointing into the message history — mirroring
-// emptyContentRe and historyMessageLocatorRe in pkg/taskfailure/resume.go.
-// Keep the three in sync.
+// Find resume context for an agent/issue from completed, failed, or cancelled
+// execution tasks. Manual rerun uses its exact source task instead; its fresh
+// flag also protects older claim handlers during mixed-version deployment.
//
-// Triage runs are excluded from all three CTEs (MUL-7189 §5.6). A triage run
-// and the execution run that follows accept are the same (agent_id, issue_id)
-// pair, so without this the first execution run would resume the conversation
-// in which the agent was deciding whether the entry was worth keeping. From the
-// execution side an accepted issue is a new issue, and it starts cold. The
-// exclusion is symmetric: a triage run does not resume an execution session
-// either, which is what force_fresh_session on the triage task already ensures.
+// Reduce to the newest terminal row per session before applying safety filters;
+// otherwise an older healthy row could revive the same poisoned session.
+// Exclude explicitly retired sessions even when clean older rows still name them.
+// Triage sessions must never cross into execution or vice versa.
//
-// retired_sessions is the explicit half of the same rule (GH #6066). The
-// per-session latest state above can only judge sessions that some row still
-// POINTS at, so it cannot see a session a run deliberately abandoned: a fresh
-// retry that succeeded reports its own new id (or none), leaving the poisoned
-// id visible on nothing but an older completed row, which then looks perfectly
-// healthy. retired_session_id records the abandonment itself, so one row
-// retiring a session removes it from every later lookup no matter how many
-// clean rows still reference it.
+// Keep failure-reason and text guards aligned with GetLastChatTaskSession and
+// resumeUnsafeFailureReason. Text guards protect legacy or unclassified rows.
+// Resume overflow can leave no session ID, so its timestamp excludes earlier
+// sessions until a later healthy terminal row restores eligibility.
// status, started_at and issue_snapshot ride along because the row this query
// picks IS the run whose context the next turn continues, and both of a claim's
// deltas must be measured from THAT run rather than from whichever run started
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 0af074b364..79efac26af 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -459,82 +459,22 @@ WHERE id = $1 AND issue_id IS NULL
AND lock_task_owner_rows(NULL, $2, NULL);
-- name: CreateRetryTask :one
--- Fenced against workspace teardown: lock_task_owner_rows (migration 284)
--- locks the owners' workspace rows in the writer's own transaction and returns
--- false once they are gone, so this statement writes no row instead of stranding
--- a task in a workspace that has just been deleted (MUL-5999).
---
--- Fenced against slot contention too: ON CONFLICT DO NOTHING yields the single
--- queued/dispatched slot idx_one_pending_task_per_issue_agent_v2 allows per
--- (issue, agent) rather than raising 23505. A manual rerun may now be enqueued
--- behind a still-running task, and it can commit at any point — including
--- between a caller's "is a successor already pending?" check and this insert,
--- since that check takes no lock. Raising here would abort the caller's
--- transaction, and on the FailTask path that transaction also carries the
--- parent's failed status, so the failure would roll back and leave the task
--- stuck in 'running'. Yielding instead makes the policy explicit: whoever
--- already holds the slot keeps it, and a deliberate human rerun therefore wins
--- over an automatic retry.
---
--- Both fences surface the same way — zero rows, i.e. pgx.ErrNoRows from this
--- :one query. Callers must treat that as "no retry was created" and still commit
--- their own work, NOT as a failure.
--- Clones a parent task into a fresh queued attempt. Carries forward the
--- agent's resume context (session_id/work_dir) so the child can continue
--- the conversation when the backend supports it. Resume-unsafe failures are
--- retried as fresh sessions so the child does not inherit a stuck agent
--- conversation, but work_dir is still carried forward: a poisoned
--- conversation says nothing about the files it left behind, and the claim
--- handler offers that workdir to the fresh session (MUL-7034). Keep the CASE
--- WHEN predicates in sync with resumeUnsafeFailureReason and the resume lookup
--- blacklists. attempt is
--- incremented; max_attempts, trigger_comment_id, coalesced_comment_ids,
--- is_leader_task, and squad_id are inherited so the retried task receives the
--- parent's complete planned comment batch and keeps the same squad-role
--- provenance. delivered_comment_ids intentionally stays at its '{}' default:
--- the child must earn its own delivery receipt at claim time.
---
--- originator_user_id is inherited so the Composio overlay decision sees the
--- same top-of-chain human across the retry: the user behind the original
--- run has not changed. The Composio overlay follows the agent's invocation
--- permission and uses the agent owner's connection (MUL-3963); originator is
--- carried for A2A/audit, not as an originator == agent.owner_id gate.
--- A system retry is NOT a new attribution event (MUL-4302 §5): it inherits the
--- parent's accountable human, source label, delegation lineage, rule version,
--- and trigger evidence UNCHANGED, and records retry_of_task_id = p.id so retry
--- and manual rerun stay separable in reporting. parent_task_id keeps its
--- existing meaning for the retry/resume machinery; retry_of_task_id is the
--- attribution-facing lineage column.
---
--- chat_input_task_id is inherited straight from the parent so the whole retry
--- chain keeps consuming the ORIGINAL root input batch (MUL-4351): the root
--- direct task set it to its own id, every descendant copies that value, and a
--- claim always reads the same user messages. A plain copy (not
--- COALESCE(parent.chat_input_task_id, parent.id)) is deliberate: legacy/channel
--- parents carry NULL and must stay NULL so their retries keep the trailing
--- selector — promoting a pre-migration NULL row to the task-owned path on retry
--- would risk replaying untagged history during a rolling deploy.
---
--- Chat retries are queued at GREATEST(priority, 3) so a transiently-failed
--- earlier turn is re-claimed ahead of any fresh chat task (priority 2) the user
--- queued while the failing turn was still running — the retry continues the
--- older turn first. Combined with creating the retry inside FailTask's
--- transaction, this leaves no window for a newer input task to jump ahead.
---
--- fire_at arms a backoff before the retry: when non-NULL the child is inserted
--- as 'deferred' with that fire_at and stays inert until the existing
--- PromoteDueDeferredTasksForRuntime sweeper (run promote-first on every claim
--- poll) flips it to 'queued'. Used for runtime_offline so the child waits for a
--- healthy runtime, and for provider_network's final attempt so it waits ~5s
--- instead of firing back-to-back with the immediate retry (MUL-4910). NULL
--- keeps the historical behaviour: an immediately-claimable 'queued' child.
---
--- max_attempts overrides the inherited budget when non-NULL (NULL inherits
--- p.max_attempts unchanged). Callers persist the reason-aware effective ceiling
--- here so the row stays self-consistent — e.g. provider_network's chain records
--- attempt=3, max_attempts=3 rather than leaking attempt=3, max_attempts=2 to the
--- task API (MUL-4910). The Go retryAttemptCeiling already refuses to raise a
--- disabled (max_attempts<=1) task, so this only ever widens, never revives.
+-- Clone an attempt with inherited attribution, planned comments, and input-batch
+-- identity. The child earns its own delivered-comment receipt at claim time.
+-- Preserve a NULL chat_input_task_id for legacy/channel parents rather than
+-- promoting untagged history to the task-owned input path.
+--
+-- Keep work_dir for every retry, but clear resume context for unsafe sessions.
+-- Keep failure predicates aligned with resumeUnsafeFailureReason and resume lookups.
+-- Composio uses the agent owner's connection; originator remains audit provenance.
+--
+-- Owner-row locks fence workspace teardown. Slot conflicts yield no row instead
+-- of aborting the caller's failure transaction; pgx.ErrNoRows means commit the
+-- parent transition without a retry. Pending human reruns retain their slot.
+--
+-- Chat retry priority keeps older input ahead of newer turns. A non-NULL fire_at
+-- defers dispatch until promotion. max_attempts optionally persists the effective
+-- ceiling; it does not re-enable tasks whose retry budget was disabled.
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
status, priority, trigger_comment_id, coalesced_comment_ids, trigger_summary, context,
@@ -1039,115 +979,19 @@ WHERE id = $1 AND status = 'running'
RETURNING *;
-- name: GetLastTaskSession :one
--- Returns the session_id and work_dir from the most recent task for a given
--- (agent_id, issue_id) pair, used for session resumption on the auto-retry
--- path. We accept 'completed', 'failed' AND 'cancelled' tasks: a failed task
--- may have established a real agent session before crashing (orphaned by a
--- daemon restart, runtime offline, or sweeper timeout), and the daemon pins
--- the resume pointer mid-flight via UpdateAgentTaskSession. Without this,
--- an auto-retry of a mid-run failure would silently start a fresh
--- conversation and lose the in-flight context — exactly what MUL-1128's B
--- branch is meant to fix.
---
--- A cancelled task is in exactly the same position, and excluding it was the
--- issue-side half of GH #6340: the pinned session is real (the provider emitted
--- it), the user stopped the run rather than the provider rejecting it, and
--- cancellation records no failure_reason/error for the poison filters below to
--- match on. So a stop-then-comment-again sequence keeps its context instead of
--- silently starting cold. A user who wants a clean slate has manual rerun,
--- which never takes this path (see below).
---
--- Manual rerun (TaskService.RerunIssue) does NOT take this path. The claim
--- handler branches on rerun_of_task_id FIRST and resolves the session/workdir
--- from that exact source task (so a parallel task on the same issue can't be
--- resumed by mistake), reusing the source workdir and resuming its session only
--- when the source failure is resume-safe. The rerun row still carries
--- force_fresh_session=true purely as a rollback-safe signal: an OLD claim
--- handler that predates the rerun_of_task_id branch falls back to this query,
--- and force_fresh_session=true makes it start clean instead of resuming the
--- wrong execution (MUL-4869).
---
--- Tasks that ended in a known "poisoned" terminal state are also excluded
--- here so even auto-retry does not inherit the bad session. The daemon
--- classifies these failures (iteration_limit, agent_fallback_message,
--- api_invalid_request, codex_semantic_inactivity, agent_error.context_overflow,
--- codex_resume_oversized)
--- when it detects either an agent fallback marker in the output, an upstream
--- API 400 that means the conversation history itself is unprocessable
--- (oversized image, malformed base64, etc.), a Codex semantic inactivity
--- timeout whose recorded session may replay the same stuck state, a context
--- window overflow that would immediately overflow again on resume, or a Codex
--- thread/resume response too large to read back (MUL-5722). Keep this
--- list in sync with resumeUnsafeFailureReason and GetLastChatTaskSession.
---
--- The error-text ILIKE clause is defense-in-depth for the api_invalid_request
--- shape: a legacy row tagged 'agent_error' (pre-MUL-1921), a deploy-window
--- row that the old code wrote between migration and rollout, or a future
--- error format that escapes the daemon classifier all still get filtered
--- here as long as the canonical Anthropic 400 marker is present in the
--- error text. Migration 079 backfills the failure_reason column itself,
--- so observability stays accurate; this clause guarantees session resume
--- never picks up a bad session even when failure_reason hasn't caught up.
---
--- Selection is per-session, not per-row: we first reduce to the single most
--- recent terminal row FOR EACH session_id (DISTINCT ON), then apply the
--- resume-unsafe filter. This closes a poisoning wormhole (GH #5975): when the
--- SAME session_id has both an older 'completed' row (the turn that first baked
--- in the bad history) and a newer poisoned 'failed' row, a plain row-level
--- filter would drop the poisoned row and happily fall back to the older
--- completed row — which points at the exact same dead session. Judging by each
--- session's LATEST terminal state instead means:
--- - a newer poisoned row invalidates the whole session, older completed rows
--- included;
--- - a different, healthy session (distinct id) is still eligible as a
--- fallback;
--- - if that same id later terminates cleanly again, the newer completed row
--- restores its resumability.
---
--- The oversized-image ILIKE (dimension phrase AND image.source.base64.data) is
--- the GH #5975 analogue of the api_invalid_request defense-in-depth above: a
--- Kiro/ACP resume rejected for an oversized historical image is classified
--- 'api_invalid_request' at write time, but this text clause also blocks a
--- legacy/unclassified row (or a new-server + old-daemon deploy window) from
--- resuming the poisoned session. Both markers are required so the clause stays
--- exactly as narrow as classifyPoisonedError and the Kiro detector — an
--- unrelated error that only mentions image dimensions is NOT excluded.
---
--- MUL-5722 needed a different shape, and the reason is worth stating because
--- the first attempt got it wrong: a row-level guard like the ones above CANNOT
--- work for an overflowed resume. That failure happens before the turn starts,
--- so the backend has no session id to report and the row lands with session_id
--- NULL — which the latest_per_session CTE drops before any filter runs. The
--- only row naming the oversized thread is the OLDER completed one, which looks
--- perfectly healthy. Hence resume_overflow_at below: block by TIME, which needs
--- nothing from the failed row but its existence. See the clause for details.
---
--- The final pair of regexes is the provider-agnostic version of the same
--- guard, and it matters most for self-hosted installs: daemons upgrade on
--- their own cadence, so a host still running a daemon without
--- taskfailure.UnresumableHistory reports an empty-message rejection as
--- agent_error.unknown and would otherwise keep resuming the transcript the
--- provider just refused (GH #6066). Both regexes must match — an emptiness
--- complaint AND a locator pointing into the message history — mirroring
--- emptyContentRe and historyMessageLocatorRe in pkg/taskfailure/resume.go.
--- Keep the three in sync.
---
--- Triage runs are excluded from all three CTEs (MUL-7189 §5.6). A triage run
--- and the execution run that follows accept are the same (agent_id, issue_id)
--- pair, so without this the first execution run would resume the conversation
--- in which the agent was deciding whether the entry was worth keeping. From the
--- execution side an accepted issue is a new issue, and it starts cold. The
--- exclusion is symmetric: a triage run does not resume an execution session
--- either, which is what force_fresh_session on the triage task already ensures.
---
--- retired_sessions is the explicit half of the same rule (GH #6066). The
--- per-session latest state above can only judge sessions that some row still
--- POINTS at, so it cannot see a session a run deliberately abandoned: a fresh
--- retry that succeeded reports its own new id (or none), leaving the poisoned
--- id visible on nothing but an older completed row, which then looks perfectly
--- healthy. retired_session_id records the abandonment itself, so one row
--- retiring a session removes it from every later lookup no matter how many
--- clean rows still reference it.
+-- Find resume context for an agent/issue from completed, failed, or cancelled
+-- execution tasks. Manual rerun uses its exact source task instead; its fresh
+-- flag also protects older claim handlers during mixed-version deployment.
+--
+-- Reduce to the newest terminal row per session before applying safety filters;
+-- otherwise an older healthy row could revive the same poisoned session.
+-- Exclude explicitly retired sessions even when clean older rows still name them.
+-- Triage sessions must never cross into execution or vice versa.
+--
+-- Keep failure-reason and text guards aligned with GetLastChatTaskSession and
+-- resumeUnsafeFailureReason. Text guards protect legacy or unclassified rows.
+-- Resume overflow can leave no session ID, so its timestamp excludes earlier
+-- sessions until a later healthy terminal row restores eligibility.
WITH retired_sessions AS (
SELECT DISTINCT r.retired_session_id AS session_id
FROM agent_task_queue r
@@ -1412,67 +1256,14 @@ WHERE (
RETURNING *;
-- name: ExpireStaleQueuedTasks :many
--- Fails queued tasks whose runtime can no longer prove it is alive.
---
--- This used to be a pure wall clock: queued for longer than a TTL (default 2h)
--- meant failed. That conflated "nobody is coming for this task" with "the
--- queue ahead of it is long", and the second one is not a failure. MUL-6558
--- was exactly that — a self-hosted runtime with low task concurrency held its
--- own queue past 2h and healthy work died as queued_expired. The TTL knob
--- added then (MULTICA_TASK_QUEUED_TTL) only moved the cliff; it did not stop
--- a busy runtime from eventually crossing it.
---
--- So the question is not "how long has this waited" but "is anything still
--- able to pick it up". A runtime that keeps heartbeating is busy, not dead,
--- and its backlog must be allowed to drain however long that takes. The
--- liveness signal is the same one FailTasksForOfflineRuntimes uses for
--- dispatched/running rows, so a daemon going down now retires its queued and
--- its in-flight work on one clock instead of two.
---
--- The row must ALSO have been queued for a full grace of its own. Enqueue binds
--- a task to agent.runtime_id without checking that the runtime is up, so
--- runtime liveness alone would fail a task the instant it is assigned to a
--- runtime that has been offline a while — a laptop closed overnight would turn
--- "assign this issue" into a failure inside one 30s sweep tick instead of
--- waiting for the machine to come back. Requiring the task's own age keeps the
--- promise the name makes: a queued task gets one full reconnect grace before it
--- is given up on, counted from when it started waiting. It also bounds the
--- scan, which would otherwise re-evaluate the runtime subquery against every
--- queued row on every tick.
---
--- Heartbeat age is read directly rather than gated on runtime.status='online',
--- so a row stuck at 'online' with a long-dead heartbeat still releases its
--- queue.
---
--- The runtime_id IS NULL / missing-runtime arms are fail-closed defence, not
--- live paths: the schema already excludes both. runtime_id was NOT NULL from
--- migration 004 until 251 replaced it with CHECK (runtime_id IS NOT NULL OR
--- completed_at IS NOT NULL), which every insert and update is checked against
--- (NOT VALID only skips the backfill scan), so no queued row can be unbound.
--- A dangling reference is impossible because agent_task_queue_runtime_id_fkey
--- (migration 004) is ON DELETE CASCADE: deleting a runtime removes the rows
--- referencing it rather than orphaning them, and the normal delete path
--- (migration 251, MUL-5559) explicitly unbinds history tasks first in the same
--- transaction. They are kept so a future schema change cannot silently strand
--- rows that have no liveness signal at all.
---
--- A retry created by runtime_offline is exempt: it deliberately waits for that
--- runtime to reconnect, and FailExpiredRuntimeReconnectRetries owns its exit.
---
--- Concurrency safety: the daemon's claim path may race with this sweeper to
--- transition the same row out of 'queued'. We protect against that two
--- ways:
--- 1. The CTE selects victims with FOR UPDATE SKIP LOCKED so a row that is
--- currently being claimed (or otherwise locked) is skipped — no lock
--- contention with the dispatch path, and we won't queue up behind it.
--- 2. The outer UPDATE re-checks status='queued' AND the liveness predicate at
--- apply time. If a daemon claimed the row between selection and update
--- (e.g. lock released after the claim transaction commits), the row is
--- already 'dispatched'/'running' and the WHERE clause filters it out
--- so we cannot clobber an in-flight task.
--- Capped via LIMIT inside the CTE so a single sweep tick cannot monopolise
--- the DB when the backlog is large — the sweeper drains the rest on
--- subsequent ticks.
+-- Expire queued work only when both the task's waiting age and the runtime's
+-- heartbeat age exceed reconnect grace. Busy but heartbeating runtimes keep their
+-- queues regardless of length. Read heartbeat age directly so a stale online
+-- status cannot strand tasks. Missing runtime references are handled defensively.
+--
+-- runtime_offline retries have a separate reconnect expiry policy and are exempt.
+-- Select bounded victims with SKIP LOCKED, then re-check status and liveness in
+-- the update so concurrent claims cannot be overwritten.
WITH victims AS (
SELECT id FROM agent_task_queue
WHERE status = 'queued' AND context->>'wakeup_id' IS NULL