Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: add per-run context receipts (MUL-9013)
Bohan Jiange11ef1650a4c
diff --git a/packages/core/agents/queries.ts b/packages/core/agents/queries.tsindex dde47a015f..cd47a6fb91 100644--- a/packages/core/agents/queries.ts+++ b/packages/core/agents/queries.ts@@ -157,3 +157,23 @@ export function agentBuilderSessionListOptions(wsId: string) {staleTime: 0,});}++export const taskContextReceiptKeys = {+ all: (wsId: string) => ["workspaces", wsId, "task-context-receipt"] as const,+ detail: (wsId: string, taskId: string) =>+ [...taskContextReceiptKeys.all(wsId), taskId] as const,+};++/**+ * A run's context receipt (MUL-9013). The daemon writes it once before the+ * agent starts (and again for a fresh-session retry), so a finished run's+ * receipt never changes; a live run's is refetched whenever the dialog opens.+ */+export function taskContextReceiptOptions(wsId: string, taskId: string) {+ return queryOptions({+ queryKey: taskContextReceiptKeys.detail(wsId, taskId),+ queryFn: () => api.getTaskContextReceipt(taskId),+ enabled: !!wsId && !!taskId,+ staleTime: 60_000,+ });+}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 5820fbf1fb..7f22c2943e 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -97,6 +97,7 @@ import type {TimelineEntry,AssigneeFrequencyEntry,TaskMessagePayload,+ TaskContextReceiptResponse,Attachment,ChatSession,ChatPinnedAgent,@@ -389,6 +390,7 @@ import {SquadMemberStatusListResponseSchema,SubscribersListSchema,TaskMessageListSchema,+ TaskContextReceiptResponseSchema,TimelineEntriesSchema,UserSchema,WebhookDeliveryResponseSchema,@@ -2997,6 +2999,16 @@ export class ApiClient {});}+ async getTaskContextReceipt(taskId: string): Promise<TaskContextReceiptResponse> {+ const raw = await this.fetch<unknown>(`/api/tasks/${taskId}/context-receipt`);+ return parseWithFallback<TaskContextReceiptResponse>(+ raw,+ TaskContextReceiptResponseSchema,+ { receipt: null },+ { endpoint: "GET /api/tasks/:id/context-receipt" },+ );+ }+async listTasksByIssue(issueId: string, includeDescendants = false, options?: { view: "timeline" }): Promise<AgentTask[]> {const search = new URLSearchParams();if (includeDescendants) search.set("scope", "subtree");diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex a6dd0923b5..9f8969fd75 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2396,6 +2396,48 @@ export const TaskMessagePayloadSchema = z.object({export const TaskMessageListSchema = z.array(TaskMessagePayloadSchema).default([]);+// Context receipt (`GET /api/tasks/:id/context-receipt`, MUL-9013). Lenient:+// unknown enum values pass through as strings, and a malformed row is dropped+// rather than failing the whole receipt.+const ContextReceiptSourceSchema = z.object({+ kind: z.string(),+ name: z.string().optional(),+ bytes: z.number().catch(0),+ sha256: z.string().optional(),+ delivery: z.string().catch(""),+ path: z.string().optional(),+ load: z.string().catch("unverified"),+ verified_version: z.string().optional(),+ parent: z.string().optional(),+}).loose();++const ContextReceiptSchema = z.object({+ schema_version: z.number().catch(1),+ runtime: z.string().catch(""),+ runtime_version: z.string().optional(),+ model: z.string().optional(),+ prompt_bytes: z.number().catch(0),+ brief_bytes: z.number().catch(0),+ brief_delivery: z.string().catch(""),+ resumed_session: z.boolean().catch(false),+ fresh_retry: z.boolean().optional().catch(undefined),+ mcp_servers: z.array(z.string()).catch([]),+ sources: z+ .array(z.unknown())+ .catch([])+ .transform((rows) =>+ rows.flatMap((row) => {+ const parsed = ContextReceiptSourceSchema.safeParse(row);+ return parsed.success ? [parsed.data] : [];+ }),+ ),+}).loose();++export const TaskContextReceiptResponseSchema = z.object({+ receipt: ContextReceiptSchema.nullable().catch(null),+ recorded_at: z.string().optional(),+}).loose();+// Task cancellation (`POST /api/tasks/:id/cancel`) is consumed directly by// chat recovery. Its optional message payload must be well-formed before the// UI deletes a message from cache or restores text into the input.diff --git a/packages/core/api/task-context-receipt-schema.test.ts b/packages/core/api/task-context-receipt-schema.test.tsnew file mode 100644index 0000000000..7e6abee5c5--- /dev/null+++ b/packages/core/api/task-context-receipt-schema.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest";+import { TaskContextReceiptResponseSchema } from "./schemas";++describe("TaskContextReceiptResponseSchema", () => {+ it("passes a null receipt through", () => {+ expect(TaskContextReceiptResponseSchema.parse({ receipt: null })).toEqual({ receipt: null });+ });++ it("keeps unknown enum values and drops malformed source rows", () => {+ const parsed = TaskContextReceiptResponseSchema.parse({+ receipt: {+ schema_version: 1,+ runtime: "qwen",+ prompt_bytes: 10,+ brief_bytes: 20,+ brief_delivery: "file",+ resumed_session: false,+ mcp_servers: ["github"],+ sources: [+ { kind: "runtime_brief", bytes: 20, delivery: "file", path: "QWEN.md", load: "probed_by_future_daemon" },+ { bytes: 5 },+ "not an object",+ ],+ },+ recorded_at: "2026-11-11T11:29:00Z",+ });+ expect(parsed.receipt?.sources).toHaveLength(1);+ expect(parsed.receipt?.sources[0]?.load).toBe("probed_by_future_daemon");+ expect(parsed.recorded_at).toBe("2026-11-11T11:29:00Z");+ });++ it("defaults missing lists so the view can map them", () => {+ const parsed = TaskContextReceiptResponseSchema.parse({ receipt: { schema_version: 1, runtime: "claude" } });+ expect(parsed.receipt?.mcp_servers).toEqual([]);+ expect(parsed.receipt?.sources).toEqual([]);+ expect(parsed.receipt?.resumed_session).toBe(false);+ });+});diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 3eb8cd9828..d978435077 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -495,6 +495,52 @@ export interface TaskUsage {credits_micros?: number;}+/**+ * Per-run context receipt (MUL-9013): which context sources the daemon handed+ * a run, with sizes, short hashes, delivery and load evidence. Metadata only.+ * String enums stay open (`string`) so a newer daemon's value still renders.+ */+export type ContextReceiptLoad =+ | "delivered"+ | "verified"+ | "verified_other_version"+ | "unverified"+ | "not_delivered"+ | (string & {});++export interface ContextReceiptSource {+ kind: string;+ name?: string;+ bytes: number;+ sha256?: string;+ delivery: string;+ path?: string;+ load: ContextReceiptLoad;+ verified_version?: string;+ /** Set when this source is a section inside another (e.g. `runtime_brief`). */+ parent?: string;+}++export interface ContextReceipt {+ schema_version: number;+ runtime: string;+ runtime_version?: string;+ model?: string;+ prompt_bytes: number;+ brief_bytes: number;+ brief_delivery: string;+ resumed_session: boolean;+ fresh_retry?: boolean;+ mcp_servers: string[];+ sources: ContextReceiptSource[];+}++export interface TaskContextReceiptResponse {+ /** Null when the run has none: an older daemon, or a run that never launched. */+ receipt: ContextReceipt | null;+ recorded_at?: string;+}+/*** Response of the Mika bootstrap endpoint: the workspace's Mika plus the* caller's conversation with it, resolved together server-side so two clientsdiff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 28206b8043..4674d546ff 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -39,6 +39,10 @@ export type {AgentInvocationTargetInput,AgentTask,TaskUsage,+ ContextReceipt,+ ContextReceiptLoad,+ ContextReceiptSource,+ TaskContextReceiptResponse,TaskAttribution,AttributionUser,TaskCancellationActor,diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsxindex b6b87119e1..e8a3071ae0 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx@@ -50,6 +50,12 @@ vi.mock("react-virtuoso", () => ({),}));+// The receipt button fetches through React Query and has its own tests+// (context-receipt.test.tsx); this suite renders the dialog without a client.+vi.mock("./context-receipt", () => ({+ ContextReceiptButton: () => null,+}));+vi.mock("../actor-avatar", () => ({ActorAvatar: () => <span data-testid="actor-avatar" />,}));diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsxindex 870cc3843f..8ba2693bf4 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx@@ -80,6 +80,7 @@ import {} from "./build-steps";import { buildRunOutcome } from "./run-outcome";import { RunTimeline } from "./run-timeline";+import { ContextReceiptButton } from "./context-receipt";import {base64ByteLength,readImageResult,@@ -945,6 +946,9 @@ export function AgentTranscriptDialog({)}<div className="flex shrink-0 items-center gap-0.5">+ {/* What the agent was handed (MUL-9013). Renders nothing for+ runs whose daemon predates the receipt. */}+ <ContextReceiptButton taskId={task.id} open={open} />{hasRunDetails && (<Popover><PopoverTriggerdiff --git a/packages/views/common/task-transcript/context-receipt.test.tsx b/packages/views/common/task-transcript/context-receipt.test.tsxnew file mode 100644index 0000000000..7d3d6993dc--- /dev/null+++ b/packages/views/common/task-transcript/context-receipt.test.tsx@@ -0,0 +1,165 @@+// @vitest-environment jsdom++import { cleanup, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { ReactElement } from "react";+import { api } from "@multica/core/api";+import type { ContextReceipt } from "@multica/core/types/agent";+import { renderWithI18n } from "../../test/i18n";+import {+ ContextReceiptButton,+ ContextReceiptView,+ loadTone,+ receiptWarnings,+ topLevelSources,+} from "./context-receipt";++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace" }));+vi.mock("@multica/core/api", () => ({+ api: { getTaskContextReceipt: vi.fn() },+}));++afterEach(() => {+ cleanup();+ vi.mocked(api.getTaskContextReceipt).mockReset();+});++const receipt: ContextReceipt = {+ schema_version: 1,+ runtime: "kiro",+ runtime_version: "2.34.0",+ model: "claude-opus",+ prompt_bytes: 2640,+ brief_bytes: 19456,+ brief_delivery: "file",+ resumed_session: true,+ mcp_servers: [],+ sources: [+ {+ kind: "runtime_brief",+ bytes: 19456,+ sha256: "cdc096ed0000",+ delivery: "file",+ path: "AGENTS.md",+ load: "verified_other_version",+ verified_version: "2.13.0",+ },+ {+ kind: "agent_instructions",+ bytes: 810,+ sha256: "4b1e9c000000",+ delivery: "embedded",+ parent: "runtime_brief",+ load: "verified_other_version",+ },+ { kind: "task_prompt", bytes: 2640, delivery: "prompt", load: "delivered" },+ {+ kind: "skill",+ name: "pr-review",+ bytes: 19412,+ delivery: "file",+ path: ".kiro/skills/pr-review/SKILL.md",+ load: "unverified",+ },+ ],+};++function withClient(ui: ReactElement) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return renderWithI18n(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);+}++describe("receipt helpers", () => {+ it("grades load states", () => {+ expect(loadTone("delivered")).toBe("ok");+ expect(loadTone("verified")).toBe("ok");+ expect(loadTone("verified_other_version")).toBe("warn");+ expect(loadTone("unverified")).toBe("warn");+ expect(loadTone("not_delivered")).toBe("warn");+ expect(loadTone("something_new")).toBe("muted");+ });++ it("warns only on top-level sources", () => {+ expect(topLevelSources(receipt).map((s) => s.kind)).toEqual(["runtime_brief", "task_prompt", "skill"]);+ // The embedded instructions share the brief's state; warning on both+ // would say the same thing twice.+ expect(receiptWarnings(receipt).map((s) => s.kind)).toEqual(["runtime_brief", "skill"]);+ });+});++describe("ContextReceiptView", () => {+ it("lists every source with its size, delivery and load state", () => {+ renderWithI18n(<ContextReceiptView receipt={receipt} />);+ const view = screen.getByTestId("context-receipt");++ // Embedded rows are not counted again in the total.+ expect(within(view).getByText("3 sources · 41 KB")).toBeTruthy();+ expect(within(view).getByText("Kiro 2.34.0")).toBeTruthy();+ expect(within(view).getByText(/Resumed a prior session/)).toBeTruthy();+ expect(within(view).getByText("None")).toBeTruthy();++ const rows = within(view).getAllByRole("row").slice(1);+ expect(rows).toHaveLength(4);+ expect(within(rows[0]!).getByText("Runtime brief")).toBeTruthy();+ expect(within(rows[0]!).getByText("AGENTS.md")).toBeTruthy();+ expect(within(rows[0]!).getByText("Verified on 2.13.0 only")).toBeTruthy();+ expect(within(rows[1]!).getByText(/Agent instructions/)).toBeTruthy();+ expect(within(rows[1]!).getByText("Same as runtime brief")).toBeTruthy();+ expect(within(rows[2]!).getByText("Turn input")).toBeTruthy();+ expect(within(rows[2]!).getByText("Delivered")).toBeTruthy();+ expect(within(rows[3]!).getByText("Skill: pr-review")).toBeTruthy();+ expect(within(rows[3]!).getByText("Not verified")).toBeTruthy();++ // The warning box names exactly the sources we cannot vouch for.+ expect(within(view).getByText("Runtime brief: Verified on 2.13.0 only")).toBeTruthy();+ expect(within(view).getByText("Skill: pr-review: Not verified")).toBeTruthy();+ });++ it("shows no warning box when every source is confirmed", () => {+ const clean: ContextReceipt = {+ ...receipt,+ resumed_session: false,+ mcp_servers: ["github"],+ sources: [+ { kind: "runtime_brief", bytes: 100, delivery: "inline", load: "delivered" },+ { kind: "task_prompt", bytes: 10, delivery: "prompt", load: "delivered" },+ ],+ };+ renderWithI18n(<ContextReceiptView receipt={clean} />);+ expect(screen.getByText("System prompt")).toBeTruthy();+ expect(screen.getByText("New session")).toBeTruthy();+ expect(screen.getByText("github")).toBeTruthy();+ expect(screen.queryByText(/: Not verified/)).toBeNull();+ });++ it("renders in Chinese", () => {+ renderWithI18n(<ContextReceiptView receipt={receipt} />, { locale: "zh-Hans" });+ expect(screen.getByText("上下文回执")).toBeTruthy();+ expect(screen.getByText("技能:pr-review")).toBeTruthy();+ expect(screen.getAllByText("仅在 2.13.0 验证过").length).toBeGreaterThan(0);+ });+});++describe("ContextReceiptButton", () => {+ it("renders nothing for a run without a receipt", async () => {+ vi.mocked(api.getTaskContextReceipt).mockResolvedValue({ receipt: null });+ const { container } = withClient(<ContextReceiptButton taskId="task-1" open />);+ await waitFor(() => expect(api.getTaskContextReceipt).toHaveBeenCalledWith("task-1"));+ expect(container.querySelector("button")).toBeNull();+ });++ it("does not fetch while the dialog is closed", () => {+ withClient(<ContextReceiptButton taskId="task-1" open={false} />);+ expect(api.getTaskContextReceipt).not.toHaveBeenCalled();+ });++ it("opens the receipt from the header button", async () => {+ vi.mocked(api.getTaskContextReceipt).mockResolvedValue({ receipt, recorded_at: "2026-11-11T11:29:00Z" });+ withClient(<ContextReceiptButton taskId="task-1" open />);+ const button = await screen.findByRole("button", { name: "Context received" });+ await userEvent.click(button);+ expect(await screen.findByTestId("context-receipt")).toBeTruthy();+ });+});diff --git a/packages/views/common/task-transcript/context-receipt.tsx b/packages/views/common/task-transcript/context-receipt.tsxnew file mode 100644index 0000000000..b20cf7aee5--- /dev/null+++ b/packages/views/common/task-transcript/context-receipt.tsx@@ -0,0 +1,260 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { useWorkspaceId } from "@multica/core/hooks";+import { taskContextReceiptOptions } from "@multica/core/agents";+import type {+ ContextReceipt,+ ContextReceiptSource,+} from "@multica/core/types/agent";+import { Layers, TriangleAlert } from "@multica/ui/icons";+import { cn } from "@multica/ui/lib/utils";+import { IconButton } from "@multica/ui/components/common/icon-button";+import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";+import { providerDisplayName } from "@multica/core/runtimes";+import { useT } from "../../i18n";+import { formatBytes } from "../format-bytes";++// Per-run context receipt (MUL-9013): what the daemon handed this run, where+// each piece went and how sure we are the runtime loaded it. The daemon only+// reports metadata, so this view has sizes, short hashes and paths — never+// the content itself.++type LoadTone = "ok" | "warn" | "muted";++export function loadTone(load: string): LoadTone {+ switch (load) {+ case "delivered":+ case "verified":+ return "ok";+ case "verified_other_version":+ case "unverified":+ case "not_delivered":+ return "warn";+ default:+ return "muted";+ }+}++/** Top-level rows: sources that stand on their own, not sections of another. */+export function topLevelSources(receipt: ContextReceipt): ContextReceiptSource[] {+ return receipt.sources.filter((s) => !s.parent);+}++/** Rows the reader should look at first: delivery we cannot vouch for. */+export function receiptWarnings(receipt: ContextReceipt): ContextReceiptSource[] {+ return topLevelSources(receipt).filter((s) => loadTone(s.load) === "warn");+}++export function ContextReceiptButton({ taskId, open }: { taskId: string; open: boolean }) {+ const wsId = useWorkspaceId();+ const { t } = useT("agents");+ const { data } = useQuery({+ ...taskContextReceiptOptions(wsId, taskId),+ enabled: open && !!wsId && !!taskId,+ });+ const receipt = data?.receipt;+ // Runs from a daemon that predates receipts have none; no dead button.+ if (!receipt) return null;+ const warnings = receiptWarnings(receipt);++ return (+ <Popover>+ <PopoverTrigger+ render={+ <IconButton+ variant="ghost"+ size="icon-sm"+ label={t(($) => $.transcript.context_receipt_title)}+ tooltipSide="bottom"+ className={cn("text-muted-foreground", warnings.length > 0 && "text-warning")}+ />+ }+ >+ <Layers className="h-3.5 w-3.5" />+ </PopoverTrigger>+ <PopoverContent+ align="end"+ className="w-[36rem] max-w-[calc(100vw-2rem)] max-h-[min(36rem,calc(100vh-8rem))] overflow-y-auto p-3"+ >+ <ContextReceiptView receipt={receipt} />+ </PopoverContent>+ </Popover>+ );+}++export function ContextReceiptView({ receipt }: { receipt: ContextReceipt }) {+ const { t } = useT("agents");+ const topLevel = topLevelSources(receipt);+ const totalBytes = topLevel.reduce((sum, s) => sum + s.bytes, 0);+ const warnings = receiptWarnings(receipt);++ const runtimeLabel = [providerDisplayName(receipt.runtime), receipt.runtime_version]+ .filter(Boolean)+ .join(" ");++ return (+ <div className="space-y-3 text-caption" data-testid="context-receipt">+ <div>+ <div className="font-medium text-foreground">{t(($) => $.transcript.context_receipt_title)}</div>+ <div className="text-muted-foreground">+ {t(($) => $.transcript.context_receipt_summary, {+ count: topLevel.length,+ size: formatBytes(totalBytes),+ })}+ </div>+ </div>++ <div className="grid grid-cols-[6rem_minmax(0,1fr)] gap-x-3 gap-y-1">+ <span className="text-muted-foreground">{t(($) => $.transcript.details_runtime)}</span>+ <span className="text-foreground">{runtimeLabel || "—"}</span>+ {receipt.model && (+ <>+ <span className="text-muted-foreground">{t(($) => $.transcript.context_receipt_model)}</span>+ <span className="font-mono text-foreground">{receipt.model}</span>+ </>+ )}+ <span className="text-muted-foreground">{t(($) => $.transcript.context_receipt_session)}</span>+ <span className="text-foreground">+ {receipt.resumed_session+ ? t(($) => $.transcript.context_receipt_session_resumed)+ : receipt.fresh_retry+ ? t(($) => $.transcript.context_receipt_session_fresh_retry)+ : t(($) => $.transcript.context_receipt_session_new)}+ </span>+ <span className="text-muted-foreground">{t(($) => $.transcript.context_receipt_mcp)}</span>+ <span className="text-foreground">+ {receipt.mcp_servers.length > 0+ ? receipt.mcp_servers.join(", ")+ : t(($) => $.transcript.context_receipt_mcp_none)}+ </span>+ </div>++ {warnings.length > 0 && (+ <div className="space-y-1 rounded-md border border-warning/30 bg-warning/10 px-2.5 py-2">+ {warnings.map((s, i) => (+ <div key={`${s.kind}-${s.name ?? ""}-${i}`} className="flex items-start gap-1.5 text-foreground">+ <TriangleAlert className="mt-0.5 h-3 w-3 shrink-0 text-warning" />+ <span>+ {t(($) => $.transcript.context_receipt_warning, {+ source: sourceLabel(s, t),+ status: loadLabel(s, t),+ })}+ </span>+ </div>+ ))}+ </div>+ )}++ <table className="w-full table-fixed border-collapse">+ <thead>+ <tr className="border-b text-left text-muted-foreground">+ <th className="w-[34%] py-1 pr-2 font-normal">{t(($) => $.transcript.context_receipt_col_source)}</th>+ <th className="w-[12%] py-1 pr-2 text-right font-normal">{t(($) => $.transcript.context_receipt_col_size)}</th>+ <th className="w-[30%] py-1 pr-2 font-normal">{t(($) => $.transcript.context_receipt_col_delivery)}</th>+ <th className="py-1 font-normal">{t(($) => $.transcript.context_receipt_col_load)}</th>+ </tr>+ </thead>+ <tbody>+ {receipt.sources.map((s, i) => (+ <tr key={`${s.kind}-${s.name ?? ""}-${i}`} className="border-b align-top last:border-b-0">+ <td className={cn("py-1 pr-2 text-foreground", s.parent && "pl-3 text-muted-foreground")}>+ <div className="truncate" title={s.sha256 ? `sha256 ${s.sha256}` : undefined}>+ {s.parent ? "└ " : ""}+ {sourceLabel(s, t)}+ </div>+ {s.sha256 && <div className="font-mono text-micro text-faint-foreground">{s.sha256}</div>}+ </td>+ <td className="py-1 pr-2 text-right tabular-nums text-foreground">{formatBytes(s.bytes)}</td>+ <td className="py-1 pr-2">+ <div+ className={cn("truncate", s.delivery === "file" ? "font-mono text-foreground" : "text-muted-foreground")}+ title={s.path}+ >+ {deliveryLabel(s, t)}+ </div>+ </td>+ <td className="py-1">+ {s.parent ? (+ <span className="text-faint-foreground">{t(($) => $.transcript.context_receipt_same_as_brief)}</span>+ ) : (+ <span className="flex items-center gap-1.5">+ <span+ aria-hidden+ className={cn(+ "inline-block h-1.5 w-1.5 shrink-0 rounded-full",+ loadTone(s.load) === "ok" && "bg-success",+ loadTone(s.load) === "warn" && "bg-warning",+ loadTone(s.load) === "muted" && "bg-muted-foreground",+ )}+ />+ <span className="text-foreground">{loadLabel(s, t)}</span>+ </span>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>++ <p className="text-micro text-faint-foreground">{t(($) => $.transcript.context_receipt_footnote)}</p>+ </div>+ );+}++type T = ReturnType<typeof useT<"agents">>["t"];++function sourceLabel(source: ContextReceiptSource, t: T): string {+ switch (source.kind) {+ case "runtime_brief":+ return t(($) => $.transcript.context_source_runtime_brief);+ case "agent_instructions":+ return t(($) => $.transcript.context_source_agent_instructions);+ case "project_description":+ return t(($) => $.transcript.context_source_project_description);+ case "existing_instructions":+ return t(($) => $.transcript.context_source_existing_instructions);+ case "task_prompt":+ return t(($) => $.transcript.context_source_task_prompt);+ case "skill":+ return t(($) => $.transcript.context_source_skill, { name: source.name ?? "" });+ default:+ return source.name ? `${source.kind}: ${source.name}` : source.kind;+ }+}++function deliveryLabel(source: ContextReceiptSource, t: T): string {+ switch (source.delivery) {+ case "file":+ return source.path ?? t(($) => $.transcript.context_delivery_file);+ case "inline":+ return t(($) => $.transcript.context_delivery_inline);+ case "prompt":+ return t(($) => $.transcript.context_delivery_prompt);+ case "embedded":+ return t(($) => $.transcript.context_delivery_embedded);+ case "none":+ return t(($) => $.transcript.context_delivery_none);+ default:+ return source.delivery;+ }+}++function loadLabel(source: ContextReceiptSource, t: T): string {+ switch (source.load) {+ case "delivered":+ return t(($) => $.transcript.context_load_delivered);+ case "verified":+ return t(($) => $.transcript.context_load_verified);+ case "verified_other_version":+ return source.verified_version+ ? t(($) => $.transcript.context_load_verified_other_version, { version: source.verified_version })+ : t(($) => $.transcript.context_load_unverified);+ case "unverified":+ return t(($) => $.transcript.context_load_unverified);+ case "not_delivered":+ return t(($) => $.transcript.context_load_not_delivered);+ default:+ return source.load;+ }+}diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 8152bb7fee..08427a2bc8 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -976,7 +976,40 @@"tool_kind_write": "Edits","tool_kind_read": "Reads","tool_kind_misc": "Other",- "trigger_wakeup": "Wakeup"+ "trigger_wakeup": "Wakeup",+ "context_receipt_title": "Context received",+ "context_receipt_summary_one": "{{count}} source · {{size}}",+ "context_receipt_summary_other": "{{count}} sources · {{size}}",+ "context_receipt_model": "Model",+ "context_receipt_session": "Session",+ "context_receipt_session_resumed": "Resumed a prior session (its history is also in context)",+ "context_receipt_session_new": "New session",+ "context_receipt_session_fresh_retry": "New session after the resume was rejected",+ "context_receipt_mcp": "MCP servers",+ "context_receipt_mcp_none": "None",+ "context_receipt_warning": "{{source}}: {{status}}",+ "context_receipt_col_source": "Source",+ "context_receipt_col_size": "Size",+ "context_receipt_col_delivery": "Delivered via",+ "context_receipt_col_load": "Loaded",+ "context_receipt_same_as_brief": "Same as runtime brief",+ "context_receipt_footnote": "Recorded by the daemon before the agent started. Sizes and short hashes only; no content is stored. \"Verified\" means this runtime version was tested to load the file. Skill sizes and hashes cover the complete written package.",+ "context_source_runtime_brief": "Runtime brief",+ "context_source_agent_instructions": "Agent instructions",+ "context_source_project_description": "Project description",+ "context_source_existing_instructions": "Repository instructions",+ "context_source_task_prompt": "Turn prompt",+ "context_source_skill": "Skill: {{name}}",+ "context_delivery_file": "File",+ "context_delivery_inline": "System prompt",+ "context_delivery_prompt": "Turn input",+ "context_delivery_embedded": "Inside the runtime brief",+ "context_delivery_none": "No channel",+ "context_load_delivered": "Delivered",+ "context_load_verified": "Verified",+ "context_load_verified_other_version": "Verified on {{version}} only",+ "context_load_unverified": "Not verified",+ "context_load_not_delivered": "Not delivered"},"task_failure": {"cancelled_by_system": "Cancelled by the system",diff --git a/packages/views/locales/es/agents.json b/packages/views/locales/es/agents.jsonindex f5786ed312..c6925b29a0 100644--- a/packages/views/locales/es/agents.json+++ b/packages/views/locales/es/agents.json@@ -958,7 +958,40 @@"tool_kind_read": "Lecturas","tool_kind_misc": "Otros","trigger_wakeup": "Activación",- "kind_text": "Agente"+ "kind_text": "Agente",+ "context_receipt_title": "Contexto recibido",+ "context_receipt_summary_one": "{{count}} fuente · {{size}}",+ "context_receipt_summary_other": "{{count}} fuentes · {{size}}",+ "context_receipt_model": "Modelo",+ "context_receipt_session": "Sesión",+ "context_receipt_session_resumed": "Reanudó una sesión anterior (su historial también está en el contexto)",+ "context_receipt_session_new": "Sesión nueva",+ "context_receipt_session_fresh_retry": "Sesión nueva tras rechazarse la reanudación",+ "context_receipt_mcp": "Servidores MCP",+ "context_receipt_mcp_none": "Ninguno",+ "context_receipt_warning": "{{source}}: {{status}}",+ "context_receipt_col_source": "Fuente",+ "context_receipt_col_size": "Tamaño",+ "context_receipt_col_delivery": "Entregado vía",+ "context_receipt_col_load": "Cargado",+ "context_receipt_same_as_brief": "Igual que las instrucciones de ejecución",+ "context_receipt_footnote": "Registrado por el daemon antes de que arrancara el agente. Solo tamaños y hashes cortos; no se guarda contenido. \"Verificado\" significa que se comprobó que esta versión del runtime carga el archivo. Los tamaños y hashes de los skills abarcan todo el paquete escrito.",+ "context_source_runtime_brief": "Instrucciones de ejecución",+ "context_source_agent_instructions": "Instrucciones del agente",+ "context_source_project_description": "Descripción del proyecto",+ "context_source_existing_instructions": "Instrucciones del repositorio",+ "context_source_task_prompt": "Prompt del turno",+ "context_source_skill": "Skill: {{name}}",+ "context_delivery_file": "Archivo",+ "context_delivery_inline": "Prompt de sistema",+ "context_delivery_prompt": "Entrada del turno",+ "context_delivery_embedded": "Dentro de las instrucciones de ejecución",+ "context_delivery_none": "Sin canal",+ "context_load_delivered": "Entregado",+ "context_load_verified": "Verificado",+ "context_load_verified_other_version": "Verificado solo en {{version}}",+ "context_load_unverified": "Sin verificar",+ "context_load_not_delivered": "No entregado"},"task_failure": {"cancelled_by_system": "Cancelada por el sistema",diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.jsonindex 8d7512c789..7637392ee5 100644--- a/packages/views/locales/fr/agents.json+++ b/packages/views/locales/fr/agents.json@@ -976,7 +976,40 @@"tool_kind_write": "Modifications","tool_kind_read": "Lectures","tool_kind_misc": "Autres",- "trigger_wakeup": "Réveil"+ "trigger_wakeup": "Réveil",+ "context_receipt_title": "Contexte reçu",+ "context_receipt_summary_one": "{{count}} source · {{size}}",+ "context_receipt_summary_other": "{{count}} sources · {{size}}",+ "context_receipt_model": "Modèle",+ "context_receipt_session": "Session",+ "context_receipt_session_resumed": "Session précédente reprise (son historique est aussi dans le contexte)",+ "context_receipt_session_new": "Nouvelle session",+ "context_receipt_session_fresh_retry": "Nouvelle session après le refus de la reprise",+ "context_receipt_mcp": "Serveurs MCP",+ "context_receipt_mcp_none": "Aucun",+ "context_receipt_warning": "{{source}} : {{status}}",+ "context_receipt_col_source": "Source",+ "context_receipt_col_size": "Taille",+ "context_receipt_col_delivery": "Transmis via",+ "context_receipt_col_load": "Chargé",+ "context_receipt_same_as_brief": "Comme les instructions d'exécution",+ "context_receipt_footnote": "Enregistré par le daemon avant le démarrage de l'agent. Tailles et hachages courts uniquement ; aucun contenu n'est stocké. « Vérifié » signifie que cette version du runtime a été testée et charge le fichier. Les tailles et hachages des skills couvrent le paquet complet écrit sur disque.",+ "context_source_runtime_brief": "Instructions d'exécution",+ "context_source_agent_instructions": "Instructions de l'agent",+ "context_source_project_description": "Description du projet",+ "context_source_existing_instructions": "Instructions du dépôt",+ "context_source_task_prompt": "Prompt du tour",+ "context_source_skill": "Skill : {{name}}",+ "context_delivery_file": "Fichier",+ "context_delivery_inline": "Prompt système",+ "context_delivery_prompt": "Entrée du tour",+ "context_delivery_embedded": "Dans les instructions d'exécution",+ "context_delivery_none": "Aucun canal",+ "context_load_delivered": "Transmis",+ "context_load_verified": "Vérifié",+ "context_load_verified_other_version": "Vérifié en {{version}} seulement",+ "context_load_unverified": "Non vérifié",+ "context_load_not_delivered": "Non transmis"},"task_failure": {"cancelled_by_system": "Annulée par le système",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 400858bf88..245443b3ff 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -811,7 +811,39 @@"tool_kind_write": "編集","tool_kind_read": "読み取り","tool_kind_misc": "その他",- "trigger_wakeup": "起動"+ "trigger_wakeup": "起動",+ "context_receipt_title": "受け取ったコンテキスト",+ "context_receipt_summary_other": "{{count}} 件のソース · {{size}}",+ "context_receipt_model": "モデル",+ "context_receipt_session": "セッション",+ "context_receipt_session_resumed": "以前のセッションを再開(その履歴もコンテキストに含まれます)",+ "context_receipt_session_new": "新しいセッション",+ "context_receipt_session_fresh_retry": "再開が拒否されたため新しいセッション",+ "context_receipt_mcp": "MCP サーバー",+ "context_receipt_mcp_none": "なし",+ "context_receipt_warning": "{{source}}: {{status}}",+ "context_receipt_col_source": "ソース",+ "context_receipt_col_size": "サイズ",+ "context_receipt_col_delivery": "渡し方",+ "context_receipt_col_load": "読み込み",+ "context_receipt_same_as_brief": "ランタイム説明と同じ",+ "context_receipt_footnote": "エージェント開始前に daemon が記録。サイズと短いハッシュのみで、内容は保存されません。「検証済み」はこのランタイムのバージョンでファイルの読み込みを確認済みという意味です。 スキルのサイズとハッシュは、書き込まれたパッケージ全体を対象とします。",+ "context_source_runtime_brief": "ランタイム説明",+ "context_source_agent_instructions": "エージェントの指示",+ "context_source_project_description": "プロジェクトの説明",+ "context_source_existing_instructions": "リポジトリの指示",+ "context_source_task_prompt": "このターンのプロンプト",+ "context_source_skill": "スキル: {{name}}",+ "context_delivery_file": "ファイル",+ "context_delivery_inline": "システムプロンプト",+ "context_delivery_prompt": "ターン入力",+ "context_delivery_embedded": "ランタイム説明の中",+ "context_delivery_none": "経路なし",+ "context_load_delivered": "送信済み",+ "context_load_verified": "検証済み",+ "context_load_verified_other_version": "{{version}} でのみ検証済み",+ "context_load_unverified": "未検証",+ "context_load_not_delivered": "未送信"},"task_failure": {"cancelled_by_system": "システムによってキャンセルされました",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex 1562137dbb..2f84e89add 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -811,7 +811,39 @@"tool_kind_write": "편집","tool_kind_read": "읽기","tool_kind_misc": "기타",- "trigger_wakeup": "깨우기"+ "trigger_wakeup": "깨우기",+ "context_receipt_title": "받은 컨텍스트",+ "context_receipt_summary_other": "소스 {{count}}개 · {{size}}",+ "context_receipt_model": "모델",+ "context_receipt_session": "세션",+ "context_receipt_session_resumed": "이전 세션을 재개함 (그 기록도 컨텍스트에 포함)",+ "context_receipt_session_new": "새 세션",+ "context_receipt_session_fresh_retry": "재개가 거부되어 새 세션 사용",+ "context_receipt_mcp": "MCP 서버",+ "context_receipt_mcp_none": "없음",+ "context_receipt_warning": "{{source}}: {{status}}",+ "context_receipt_col_source": "소스",+ "context_receipt_col_size": "크기",+ "context_receipt_col_delivery": "전달 방식",+ "context_receipt_col_load": "로드",+ "context_receipt_same_as_brief": "런타임 안내와 동일",+ "context_receipt_footnote": "에이전트 시작 전에 daemon이 기록했습니다. 크기와 짧은 해시만 저장하며 내용은 저장하지 않습니다. \"검증됨\"은 이 런타임 버전에서 파일을 로드하는 것이 확인되었다는 뜻입니다. 스킬 크기와 해시는 실제로 기록된 전체 패키지를 기준으로 합니다.",+ "context_source_runtime_brief": "런타임 안내",+ "context_source_agent_instructions": "에이전트 지침",+ "context_source_project_description": "프로젝트 설명",+ "context_source_existing_instructions": "저장소 지침",+ "context_source_task_prompt": "이번 턴 프롬프트",+ "context_source_skill": "스킬: {{name}}",+ "context_delivery_file": "파일",+ "context_delivery_inline": "시스템 프롬프트",+ "context_delivery_prompt": "턴 입력",+ "context_delivery_embedded": "런타임 안내 안",+ "context_delivery_none": "전달 경로 없음",+ "context_load_delivered": "전달됨",+ "context_load_verified": "검증됨",+ "context_load_verified_other_version": "{{version}}에서만 검증됨",+ "context_load_unverified": "검증 안 됨",+ "context_load_not_delivered": "전달 안 됨"},"task_failure": {"cancelled_by_system": "시스템에서 취소함",diff --git a/packages/views/locales/ru/agents.json b/packages/views/locales/ru/agents.jsonindex 53fc144ff0..04d496f3a2 100644--- a/packages/views/locales/ru/agents.json+++ b/packages/views/locales/ru/agents.json@@ -1024,7 +1024,42 @@"group_calls_few": "Вызовов: {{count}}","group_calls_many": "Вызовов: {{count}}","steps_count_few": "Шагов: {{count}}",- "steps_count_many": "Шагов: {{count}}"+ "steps_count_many": "Шагов: {{count}}",+ "context_receipt_title": "Полученный контекст",+ "context_receipt_summary_one": "{{count}} источник · {{size}}",+ "context_receipt_summary_few": "{{count}} источника · {{size}}",+ "context_receipt_summary_many": "{{count}} источников · {{size}}",+ "context_receipt_summary_other": "{{count}} источника · {{size}}",+ "context_receipt_model": "Модель",+ "context_receipt_session": "Сессия",+ "context_receipt_session_resumed": "Продолжена прежняя сессия (её история тоже в контексте)",+ "context_receipt_session_new": "Новая сессия",+ "context_receipt_session_fresh_retry": "Новая сессия после отказа в продолжении",+ "context_receipt_mcp": "MCP-серверы",+ "context_receipt_mcp_none": "Нет",+ "context_receipt_warning": "{{source}}: {{status}}",+ "context_receipt_col_source": "Источник",+ "context_receipt_col_size": "Размер",+ "context_receipt_col_delivery": "Способ передачи",+ "context_receipt_col_load": "Загрузка",+ "context_receipt_same_as_brief": "Как у инструкций запуска",+ "context_receipt_footnote": "Записано daemon до запуска агента. Только размеры и короткие хеши, содержимое не сохраняется. «Проверено» значит, что эта версия среды выполнения проверена и загружает файл. Размеры и хеши навыков охватывают весь записанный пакет.",+ "context_source_runtime_brief": "Инструкции запуска",+ "context_source_agent_instructions": "Инструкции агента",+ "context_source_project_description": "Описание проекта",+ "context_source_existing_instructions": "Инструкции репозитория",+ "context_source_task_prompt": "Промпт хода",+ "context_source_skill": "Навык: {{name}}",+ "context_delivery_file": "Файл",+ "context_delivery_inline": "Системный промпт",+ "context_delivery_prompt": "Ввод хода",+ "context_delivery_embedded": "Внутри инструкций запуска",+ "context_delivery_none": "Нет канала",+ "context_load_delivered": "Передано",+ "context_load_verified": "Проверено",+ "context_load_verified_other_version": "Проверено только на {{version}}",+ "context_load_unverified": "Не проверено",+ "context_load_not_delivered": "Не передано"},"task_failure": {"cancelled_by_system": "Отменено системой",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex bee7a14668..3a45d5010b 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -952,7 +952,39 @@"tool_kind_write": "编辑","tool_kind_read": "读取","tool_kind_misc": "其他",- "trigger_wakeup": "唤醒触发"+ "trigger_wakeup": "唤醒触发",+ "context_receipt_title": "上下文回执",+ "context_receipt_summary_other": "{{count}} 个来源 · {{size}}",+ "context_receipt_model": "模型",+ "context_receipt_session": "会话",+ "context_receipt_session_resumed": "复用了之前的会话(其历史也在上下文中)",+ "context_receipt_session_new": "新会话",+ "context_receipt_session_fresh_retry": "恢复会话被拒后改用新会话",+ "context_receipt_mcp": "MCP 服务",+ "context_receipt_mcp_none": "无",+ "context_receipt_warning": "{{source}}:{{status}}",+ "context_receipt_col_source": "来源",+ "context_receipt_col_size": "大小",+ "context_receipt_col_delivery": "交付方式",+ "context_receipt_col_load": "加载状态",+ "context_receipt_same_as_brief": "同运行说明",+ "context_receipt_footnote": "由 daemon 在智能体启动前记录。只保存大小和短哈希,不保存内容。“已验证”表示该运行环境的这个版本经过测试,确认会加载该文件。 技能的大小和哈希覆盖实际写入的整个技能包。",+ "context_source_runtime_brief": "运行说明",+ "context_source_agent_instructions": "智能体指令",+ "context_source_project_description": "项目描述",+ "context_source_existing_instructions": "仓库自带指令",+ "context_source_task_prompt": "本轮 prompt",+ "context_source_skill": "技能:{{name}}",+ "context_delivery_file": "文件",+ "context_delivery_inline": "系统提示",+ "context_delivery_prompt": "本轮输入",+ "context_delivery_embedded": "在运行说明内",+ "context_delivery_none": "无交付渠道",+ "context_load_delivered": "已送达",+ "context_load_verified": "已验证",+ "context_load_verified_other_version": "仅在 {{version}} 验证过",+ "context_load_unverified": "未验证",+ "context_load_not_delivered": "未送达"},"task_failure": {"cancelled_by_system": "已由系统取消",diff --git a/packages/views/locales/zh-Hant/agents.json b/packages/views/locales/zh-Hant/agents.jsonindex 59a4a12d38..c89b5617f4 100644--- a/packages/views/locales/zh-Hant/agents.json+++ b/packages/views/locales/zh-Hant/agents.json@@ -952,7 +952,39 @@"tool_kind_write": "編輯","tool_kind_read": "讀取","tool_kind_misc": "其他",- "trigger_wakeup": "喚醒觸發"+ "trigger_wakeup": "喚醒觸發",+ "context_receipt_title": "上下文回執",+ "context_receipt_summary_other": "{{count}} 個來源 · {{size}}",+ "context_receipt_model": "模型",+ "context_receipt_session": "工作階段",+ "context_receipt_session_resumed": "沿用了先前的工作階段(其歷史也在上下文中)",+ "context_receipt_session_new": "新工作階段",+ "context_receipt_session_fresh_retry": "恢復工作階段被拒後改用新工作階段",+ "context_receipt_mcp": "MCP 服務",+ "context_receipt_mcp_none": "無",+ "context_receipt_warning": "{{source}}:{{status}}",+ "context_receipt_col_source": "來源",+ "context_receipt_col_size": "大小",+ "context_receipt_col_delivery": "交付方式",+ "context_receipt_col_load": "載入狀態",+ "context_receipt_same_as_brief": "同執行說明",+ "context_receipt_footnote": "由 daemon 在代理程式啟動前記錄。只保存大小和短雜湊,不保存內容。「已驗證」表示該執行環境的這個版本經過測試,確認會載入該檔案。 技能的大小和雜湊涵蓋實際寫入的整個技能包。",+ "context_source_runtime_brief": "執行說明",+ "context_source_agent_instructions": "代理程式指令",+ "context_source_project_description": "專案描述",+ "context_source_existing_instructions": "儲存庫自帶指令",+ "context_source_task_prompt": "本輪 prompt",+ "context_source_skill": "技能:{{name}}",+ "context_delivery_file": "檔案",+ "context_delivery_inline": "系統提示",+ "context_delivery_prompt": "本輪輸入",+ "context_delivery_embedded": "在執行說明內",+ "context_delivery_none": "無交付管道",+ "context_load_delivered": "已送達",+ "context_load_verified": "已驗證",+ "context_load_verified_other_version": "僅在 {{version}} 驗證過",+ "context_load_unverified": "未驗證",+ "context_load_not_delivered": "未送達"},"task_failure": {"cancelled_by_system": "已由系統取消",diff --git a/scripts/agent-environment.sh b/scripts/agent-environment.shindex 0703484ac6..ab0a6c0be0 100755--- a/scripts/agent-environment.sh+++ b/scripts/agent-environment.sh@@ -58,22 +58,32 @@ other_component() {# An atomic mkdir, as in dev-env.sh: flock is not on a stock macOS. A lock# whose holder is gone is taken over, so a killed stop cannot wedge the next.acquire_lock() {- local holder waited=0+ local holder marker waited=0mkdir -p "$STATE_DIR"while ! mkdir "$LOCK_DIR" 2>/dev/null; do- holder="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)"- if [ -n "$holder" ] && ! kill -0 "$holder" 2>/dev/null; then- rm -rf "$LOCK_DIR"- continue- fi+ # Removing a PID-specific marker is the reaper's atomic claim. Only+ # its winner may rmdir the old lock; another stale observer cannot+ # remove a new holder's marker (or its directory).+ for marker in "$LOCK_DIR"/owner-* "$LOCK_DIR/pid"; do+ [ -f "$marker" ] || continue+ case "$marker" in+ */pid) holder="$(cat "$marker" 2>/dev/null || true)" ;;+ *) holder="${marker##*/owner-}" ;;+ esac+ if [ -n "$holder" ] && ! kill -0 "$holder" 2>/dev/null && rm "$marker" 2>/dev/null; then+ rmdir "$LOCK_DIR" 2>/dev/null || true+ fi+ donewaited=$((waited + 1))[ "$waited" -lt 3000 ] || { echo "Timed out waiting for $LOCK_DIR." >&2; exit 1; }sleep 0.1done- printf '%s\n' "$$" > "$LOCK_DIR/pid"+ : > "$LOCK_DIR/owner-$$"}-release_lock() { rm -rf "$LOCK_DIR"; }+release_lock() {+ rm "$LOCK_DIR/owner-$$" && rmdir "$LOCK_DIR"+}claim_file() { printf '%s/%s.claim' "$STATE_DIR" "$1"; }diff --git a/scripts/agent-environment.test.sh b/scripts/agent-environment.test.shindex f5ed17360e..65edb8b670 100644--- a/scripts/agent-environment.test.sh+++ b/scripts/agent-environment.test.sh@@ -192,4 +192,85 @@ start_in_background webgrep -q -- "--ttl 25" "$repo/calls.log" || fail "start did not give a new environment its TTL"stop_job "$start_pid"+# 9. Both stops observed the same dead lock holder. Delay the second reaper+# until the first owns a new lock: stale observations must not remove that+# new lock and let both callers destroy the environment.+new_repo stale-lock+touch "$repo/registered"+live_claim web+live_claim desktop+mkdir -p "$repo/.multica/agent-environments/lock.d" "$repo/bin"+printf '%s\n' "$dead" > "$repo/.multica/agent-environments/lock.d/pid"+cp "$repo/.multica/agent-environments/lock.d/pid" "$repo/stale-pid"+real_cat="$(command -v cat)"+real_rm="$(command -v rm)"+cat > "$repo/bin/cat" <<'EOF'+#!/usr/bin/env bash+set -eu+if [ "$1" = "$RACE_REPO/.multica/agent-environments/lock.d/pid" ] && [ ! -f "$RACE_REPO/$RACE_COMPONENT.observed" ]; then+ touch "$RACE_REPO/$RACE_COMPONENT.observed"+ for i in $(seq 1 300); do+ [ ! -f "$RACE_REPO/web.observed" ] || [ ! -f "$RACE_REPO/desktop.observed" ] || break+ sleep 0.01+ done+ exec "$REAL_CAT" "$RACE_REPO/stale-pid"+fi+exec "$REAL_CAT" "$@"+EOF+cat > "$repo/bin/rm" <<'EOF'+#!/usr/bin/env bash+set -eu+if [ "$RACE_COMPONENT" = desktop ] && [ ! -f "$RACE_REPO/desktop.reaping" ]; then+ case "$*" in+ *agent-environments/lock.d*)+ touch "$RACE_REPO/desktop.reaping"+ for i in $(seq 1 300); do+ [ ! -f "$RACE_REPO/web.down" ] || break+ sleep 0.01+ done+ [ -f "$RACE_REPO/web.down" ] || { echo 'first stop never acquired its lock' >&2; exit 1; }+ result=0+ "$REAL_RM" "$@" || result=$?+ touch "$RACE_REPO/desktop.reaped"+ exit "$result" ;;+ esac+fi+exec "$REAL_RM" "$@"+EOF+chmod +x "$repo/bin/cat" "$repo/bin/rm"+# Keep the first lock holder in down until the stale reap actually finishes.+mv "$repo/scripts/dev-env.sh" "$repo/scripts/dev-env.original"+cat > "$repo/scripts/dev-env.sh" <<'EOF'+#!/usr/bin/env bash+set -eu+if [ "$1" = down ]; then+ touch "$RACE_REPO/$3.down"+ if [ "$3" = web ]; then+ for i in $(seq 1 300); do+ [ ! -f "$RACE_REPO/desktop.reaped" ] || break+ sleep 0.01+ done+ [ -f "$RACE_REPO/desktop.reaped" ] || { echo 'second stale reap never finished' >&2; exit 1; }+ fi+fi+exec bash "$(dirname "$0")/dev-env.original" "$@"+EOF+PATH="$repo/bin:$PATH" RACE_REPO="$repo" RACE_COMPONENT=web REAL_CAT="$real_cat" REAL_RM="$real_rm" \+ bash "$repo/scripts/agent-environment.sh" stop web > /dev/null &+first=$!+PATH="$repo/bin:$PATH" RACE_REPO="$repo" RACE_COMPONENT=desktop REAL_CAT="$real_cat" REAL_RM="$real_rm" \+ bash "$repo/scripts/agent-environment.sh" stop desktop > /dev/null &+second=$!+wait "$first" || fail "first stale-lock stop failed"+wait "$second" || fail "second stale-lock stop failed"+[ "$(count destroy)" = 1 ] || fail "stale lock observations destroyed $(count destroy) times, want once"++# The PID-specific format can also be reclaimed after a killed holder.+new_repo stale-owner+touch "$repo/registered"+mkdir -p "$repo/.multica/agent-environments/lock.d"+touch "$repo/.multica/agent-environments/lock.d/owner-$dead"+bash "$repo/scripts/agent-environment.sh" stop web > /dev/null+[ "$(count destroy)" = 1 ] || fail "a dead PID-specific lock prevented cleanup"+echo "✓ agent-environment.sh lifecycle verified"diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex e2ff196eb6..021d06f96b 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,8 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "651_task_context_receipt_issue_idx": "idx_task_context_receipt_issue",+ "650_task_context_receipt_workspace_idx": "idx_task_context_receipt_workspace","648_project_subscriber_user_idx": "idx_project_subscriber_workspace_user","645_issue_member_creator_index": "idx_issue_workspace_member_creator","644_issue_requester_index": "idx_issue_workspace_requester",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex b5f33c4753..2a2b4f508a 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1692,6 +1692,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/tasks/{taskId}/usage", h.ReportTaskUsage)r.Post("/tasks/{taskId}/environments", h.ReportTaskEnvironments)r.Post("/tasks/{taskId}/environment-configs", h.ReportTaskEnvironmentConfigs)+ r.Post("/tasks/{taskId}/context-receipt", h.ReportTaskContextReceipt)r.Post("/tasks/{taskId}/messages", h.ReportTaskMessages)r.Get("/tasks/{taskId}/messages", h.ListTaskMessages)r.Post("/tasks/{taskId}/cancel-ack", h.AckTaskCancelled)@@ -2211,6 +2212,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Task messages (user-facing, not daemon auth)r.Get("/api/tasks/{taskId}/messages", h.ListTaskMessagesByUser)+ r.Get("/api/tasks/{taskId}/context-receipt", h.GetTaskContextReceipt)r.With(handler.RequireHumanActor).Post("/api/tasks/{taskId}/retry-source-context", h.RetrySourceContextQuickCreate)// Issue quick actions (definitions; running one lives underdiff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 0664372fce..a88799979d 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -719,6 +719,15 @@ func (c *Client) ReportTaskEnvironmentConfigs(ctx context.Context, taskID string}, nil)}+// ReportTaskContextReceipt records which context sources this run was handed+// (MUL-9013). The server keeps one receipt per task; a second report for the+// same task (the fresh-session retry) replaces the first.+func (c *Client) ReportTaskContextReceipt(ctx context.Context, taskID string, receipt ContextReceipt) error {+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/context-receipt", taskID), map[string]any{+ "receipt": receipt,+ }, nil)+}+// EnvironmentCommand is a stop, restart, start or log read a member asked// for from the issue sidebar.type EnvironmentCommand struct {diff --git a/server/internal/daemon/context_receipt.go b/server/internal/daemon/context_receipt.gonew file mode 100644index 0000000000..0f8d3b0299--- /dev/null+++ b/server/internal/daemon/context_receipt.go@@ -0,0 +1,282 @@+package daemon++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "log/slog"+ "net/http"+ "regexp"+ "sort"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++// Context receipt (MUL-9013): a per-run record of which context sources this+// daemon handed the agent, how big each was, how it was delivered, and how+// sure we are the runtime actually loaded it. Metadata only — sizes, short+// hashes, workdir-relative paths and names. Content never leaves the machine.++// ContextReceiptSchemaVersion is bumped when the receipt's meaning changes in a+// way readers must branch on. Additive fields do not bump it.+const ContextReceiptSchemaVersion = 1++// Source kinds.+const (+ ReceiptKindRuntimeBrief = "runtime_brief"+ ReceiptKindAgentInstructions = "agent_instructions"+ ReceiptKindProjectDescription = "project_description"+ ReceiptKindExistingInstructions = "existing_instructions"+ ReceiptKindTaskPrompt = "task_prompt"+ ReceiptKindSkill = "skill"+)++// Delivery modes.+const (+ ReceiptDeliveryFile = "file" // written to a file the runtime is expected to discover+ ReceiptDeliveryInline = "inline" // passed as the turn's system prompt+ ReceiptDeliveryPrompt = "prompt" // the turn input itself+ ReceiptDeliveryEmbedded = "embedded" // a section inside another source (see Parent)+ ReceiptDeliveryNone = "none" // built but the runtime has no channel for it+)++// Load states, from strongest evidence to weakest.+const (+ // The daemon put it in the request the runtime received.+ ReceiptLoadDelivered = "delivered"+ // Written to a file this runtime, at this version, was probed to load.+ ReceiptLoadVerified = "verified"+ // Written to a file this runtime was probed to load, but at a different+ // (or unknown) version than the one that ran.+ ReceiptLoadVerifiedOtherVersion = "verified_other_version"+ // Written to disk; nothing confirms the runtime reads it.+ ReceiptLoadUnverified = "unverified"+ // Built but not delivered through any channel.+ ReceiptLoadNotDelivered = "not_delivered"+)++// ContextReceipt is the wire shape POSTed to the server.+type ContextReceipt struct {+ SchemaVersion int `json:"schema_version"`+ Runtime string `json:"runtime"`+ RuntimeVersion string `json:"runtime_version,omitempty"`+ Model string `json:"model,omitempty"`+ PromptBytes int `json:"prompt_bytes"`+ BriefBytes int `json:"brief_bytes"`+ BriefDelivery string `json:"brief_delivery"`+ // ResumedSession reports the turn continued a prior provider session, so+ // the model also carries that session's history beyond what is listed.+ ResumedSession bool `json:"resumed_session"`+ // FreshRetry marks the receipt rewritten for the cold retry after a+ // resume was rejected; it replaces the first attempt's receipt.+ FreshRetry bool `json:"fresh_retry,omitempty"`+ MCPServers []string `json:"mcp_servers"`+ Sources []ContextReceiptSource `json:"sources"`+}++// ContextReceiptSource is one row of the receipt.+type ContextReceiptSource struct {+ Kind string `json:"kind"`+ Name string `json:"name,omitempty"`+ Bytes int `json:"bytes"`+ SHA256 string `json:"sha256,omitempty"`+ Delivery string `json:"delivery"`+ Path string `json:"path,omitempty"`+ Load string `json:"load"`+ VerifiedVersion string `json:"verified_version,omitempty"`+ Parent string `json:"parent,omitempty"`+}++// contextFileLoadProbes records runtimes confirmed to load the context file+// the daemon writes, and the CLI version each probe ran against. Source: the+// MUL-5392 canary probes documented on providerNeedsInlineSystemPrompt, plus+// the kiro-cli ACP smoke. Add a row only with a probe behind it; an absent+// runtime reads "unverified" on the receipt, which is the honest answer.+var contextFileLoadProbes = map[string]string{+ "claude": "2.1.220",+ "codex": "0.144.6",+ "opencode": "1.17.7",+ "pi": "0.67.2",+ "hermes": "0.18.2",+ "kiro": "2.13.0",+ "mcode": "0.1.2",+}++var receiptVersionPattern = regexp.MustCompile(`\d+\.\d+\.\d+`)++// contextFileLoadState grades a file-delivered source for this runtime.+func contextFileLoadState(provider, runtimeVersion string) (state, verifiedVersion string) {+ probed, ok := contextFileLoadProbes[provider]+ if !ok {+ return ReceiptLoadUnverified, ""+ }+ if receiptVersionPattern.FindString(runtimeVersion) == probed {+ return ReceiptLoadVerified, probed+ }+ return ReceiptLoadVerifiedOtherVersion, probed+}++// receiptHash is a short content fingerprint: enough to tell two copies of a+// rule apart at a glance, too short to be useful for anything else.+func receiptHash(content string) string {+ sum := sha256.Sum256([]byte(content))+ return hex.EncodeToString(sum[:])[:12]+}++// contextReceiptInput is everything buildContextReceipt reads. Gathered at the+// launch site so the builder stays a pure function of its arguments.+type contextReceiptInput struct {+ Provider string+ RuntimeVersion string+ CustomRuntime bool+ Model string+ WorkDir string+ Prompt string+ RuntimeBrief string+ InlineBrief bool+ BriefWritten bool+ ResumedSession bool+ FreshRetry bool+ MCPConfig json.RawMessage+ TaskCtx execenv.TaskContextForEnv+ Skills []execenv.SkillReceipt+ // ExistingInstructions is the repository's own content in the runtime+ // config file, outside the managed block.+ ExistingInstructions string+}++func buildContextReceipt(in contextReceiptInput) ContextReceipt {+ r := ContextReceipt{+ SchemaVersion: ContextReceiptSchemaVersion,+ Runtime: in.Provider,+ RuntimeVersion: in.RuntimeVersion,+ Model: in.Model,+ PromptBytes: len(in.Prompt),+ BriefBytes: len(in.RuntimeBrief),+ ResumedSession: in.ResumedSession,+ FreshRetry: in.FreshRetry,+ MCPServers: receiptMCPServerNames(in.MCPConfig),+ }++ configPath := execenv.RuntimeConfigRelPath(in.WorkDir, in.Provider)+ fileLoad, fileVerifiedAt := contextFileLoadState(in.Provider, in.RuntimeVersion)+ if in.CustomRuntime {+ // A vendor CLI probe does not establish how an arbitrary command+ // speaking the same protocol discovers its instruction files.+ fileLoad, fileVerifiedAt = ReceiptLoadUnverified, ""+ }++ brief := ContextReceiptSource{+ Kind: ReceiptKindRuntimeBrief,+ Bytes: len(in.RuntimeBrief),+ SHA256: receiptHash(in.RuntimeBrief),+ }+ switch {+ case in.InlineBrief:+ // Inline wins over the file: providerNeedsInlineSystemPrompt exists+ // because these runtimes do not read the file the daemon also writes.+ brief.Delivery, brief.Load = ReceiptDeliveryInline, ReceiptLoadDelivered+ case configPath != "" && in.BriefWritten:+ brief.Delivery, brief.Path = ReceiptDeliveryFile, configPath+ brief.Load, brief.VerifiedVersion = fileLoad, fileVerifiedAt+ default:+ brief.Delivery, brief.Load = ReceiptDeliveryNone, ReceiptLoadNotDelivered+ }+ r.BriefDelivery = brief.Delivery+ r.Sources = append(r.Sources, brief)++ // Sections the owner configured that travel inside the brief. Listed on+ // their own so a reader can see their size and fingerprint without+ // diffing the brief; their load state is the brief's.+ embedded := func(kind, content string) {+ if content == "" {+ return+ }+ r.Sources = append(r.Sources, ContextReceiptSource{+ Kind: kind,+ Bytes: len(content),+ SHA256: receiptHash(content),+ Delivery: ReceiptDeliveryEmbedded,+ Parent: ReceiptKindRuntimeBrief,+ Load: brief.Load,+ VerifiedVersion: brief.VerifiedVersion,+ })+ }+ embedded(ReceiptKindAgentInstructions, in.TaskCtx.AgentInstructions)+ embedded(ReceiptKindProjectDescription, in.TaskCtx.ProjectDescription)++ if in.ExistingInstructions != "" && configPath != "" {+ r.Sources = append(r.Sources, ContextReceiptSource{+ Kind: ReceiptKindExistingInstructions,+ Bytes: len(in.ExistingInstructions),+ SHA256: receiptHash(in.ExistingInstructions),+ Delivery: ReceiptDeliveryFile,+ Path: configPath,+ Load: fileLoad,+ VerifiedVersion: fileVerifiedAt,+ })+ }++ r.Sources = append(r.Sources, ContextReceiptSource{+ Kind: ReceiptKindTaskPrompt,+ Bytes: len(in.Prompt),+ SHA256: receiptHash(in.Prompt),+ Delivery: ReceiptDeliveryPrompt,+ Load: ReceiptLoadDelivered,+ })++ for _, skill := range in.Skills {+ source := ContextReceiptSource{+ Kind: ReceiptKindSkill, Name: skill.Name, Bytes: skill.Bytes,+ SHA256: skill.SHA256, Path: skill.Path,+ Delivery: ReceiptDeliveryNone, Load: ReceiptLoadNotDelivered,+ }+ if skill.Available {+ // Materialization is confirmed, discovery has not been probed.+ source.Delivery, source.Load = ReceiptDeliveryFile, ReceiptLoadUnverified+ }+ r.Sources = append(r.Sources, source)+ }+ return r+}++// receiptMCPServerNames lists the server names in an mcpServers config. Names+// only: commands, URLs, args and env can carry credentials.+func receiptMCPServerNames(raw json.RawMessage) []string {+ names := []string{}+ if len(raw) == 0 {+ return names+ }+ var cfg struct {+ MCPServers map[string]json.RawMessage `json:"mcpServers"`+ }+ if err := json.Unmarshal(raw, &cfg); err != nil {+ return names+ }+ for name := range cfg.MCPServers {+ names = append(names, name)+ }+ sort.Strings(names)+ return names+}++// reportContextReceipt sends the receipt best-effort. The receipt is+// diagnostic: a failure — including a server that predates the endpoint —+// is logged and never affects the run.+func (d *Daemon) reportContextReceipt(ctx context.Context, taskID string, receipt ContextReceipt, taskLog *slog.Logger) {+ reportCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ err := d.client.ReportTaskContextReceipt(reportCtx, taskID, receipt)+ if err == nil {+ return+ }+ var reqErr *requestError+ if errors.As(err, &reqErr) && (reqErr.StatusCode == http.StatusNotFound || reqErr.StatusCode == http.StatusMethodNotAllowed) {+ taskLog.Debug("server does not accept context receipts; skipping", "error", err)+ return+ }+ taskLog.Warn("failed to report context receipt", "error", err)+}diff --git a/server/internal/daemon/context_receipt_test.go b/server/internal/daemon/context_receipt_test.gonew file mode 100644index 0000000000..522115ef9e--- /dev/null+++ b/server/internal/daemon/context_receipt_test.go@@ -0,0 +1,301 @@+package daemon++import (+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++func receiptSource(t *testing.T, r ContextReceipt, kind, name string) ContextReceiptSource {+ t.Helper()+ for _, s := range r.Sources {+ if s.Kind == kind && s.Name == name {+ return s+ }+ }+ t.Fatalf("receipt has no %s source named %q: %+v", kind, name, r.Sources)+ return ContextReceiptSource{}+}++func receiptHasKind(r ContextReceipt, kind string) bool {+ for _, s := range r.Sources {+ if s.Kind == kind {+ return true+ }+ }+ return false+}++func TestBuildContextReceiptFileDeliveredBrief(t *testing.T) {+ workDir := t.TempDir()+ r := buildContextReceipt(contextReceiptInput{+ Provider: "kiro",+ RuntimeVersion: "kiro-cli 2.34.0",+ Model: "claude-opus",+ WorkDir: workDir,+ Prompt: "do the task",+ RuntimeBrief: "# Multica Agent Runtime\nbrief",+ BriefWritten: true,+ ResumedSession: true,+ MCPConfig: json.RawMessage(`{"mcpServers":{"zeta":{"command":"z","env":{"TOKEN":"secret"}},"alpha":{"url":"https://x"}}}`),+ TaskCtx: execenv.TaskContextForEnv{+ AgentInstructions: "be precise",+ ProjectDescription: "project ctx",+ },+ Skills: []execenv.SkillReceipt{{+ Name: "pr-review", Path: ".kiro/skills/pr-review/SKILL.md",+ Bytes: 30, SHA256: "0123456789ab", Available: true,+ }},+ ExistingInstructions: "repo rules",+ })++ if r.SchemaVersion != ContextReceiptSchemaVersion || r.Runtime != "kiro" || !r.ResumedSession {+ t.Fatalf("unexpected header: %+v", r)+ }+ if r.PromptBytes != len("do the task") || r.BriefBytes != len("# Multica Agent Runtime\nbrief") {+ t.Fatalf("sizes: prompt=%d brief=%d", r.PromptBytes, r.BriefBytes)+ }+ if got := strings.Join(r.MCPServers, ","); got != "alpha,zeta" {+ t.Fatalf("mcp servers = %q, want sorted names only", got)+ }++ brief := receiptSource(t, r, ReceiptKindRuntimeBrief, "")+ if brief.Delivery != ReceiptDeliveryFile || brief.Path != "AGENTS.md" {+ t.Fatalf("brief delivery = %+v", brief)+ }+ // kiro was probed at 2.13.0; the run used 2.34.0, so the receipt must not+ // claim a full verification.+ if brief.Load != ReceiptLoadVerifiedOtherVersion || brief.VerifiedVersion != "2.13.0" {+ t.Fatalf("brief load = %q (verified at %q)", brief.Load, brief.VerifiedVersion)+ }+ if r.BriefDelivery != ReceiptDeliveryFile {+ t.Fatalf("brief_delivery = %q", r.BriefDelivery)+ }++ instr := receiptSource(t, r, ReceiptKindAgentInstructions, "")+ if instr.Parent != ReceiptKindRuntimeBrief || instr.Delivery != ReceiptDeliveryEmbedded || instr.Load != brief.Load {+ t.Fatalf("instructions row = %+v", instr)+ }+ if instr.SHA256 != receiptHash("be precise") || len(instr.SHA256) != 12 {+ t.Fatalf("instructions hash = %q", instr.SHA256)+ }+ receiptSource(t, r, ReceiptKindProjectDescription, "")++ existing := receiptSource(t, r, ReceiptKindExistingInstructions, "")+ if existing.Path != "AGENTS.md" || existing.Bytes != len("repo rules") {+ t.Fatalf("existing row = %+v", existing)+ }++ prompt := receiptSource(t, r, ReceiptKindTaskPrompt, "")+ if prompt.Load != ReceiptLoadDelivered || prompt.Delivery != ReceiptDeliveryPrompt {+ t.Fatalf("prompt row = %+v", prompt)+ }++ skill := receiptSource(t, r, ReceiptKindSkill, "pr-review")+ if skill.Path != ".kiro/skills/pr-review/SKILL.md" || skill.Load != ReceiptLoadUnverified {+ t.Fatalf("skill row = %+v", skill)+ }+ if skill.Bytes != 30 || skill.SHA256 != "0123456789ab" {+ t.Fatalf("skill metadata = %+v, want the prepared package's fingerprint", skill)+ }++ // Metadata only: no content or MCP secret may appear in the wire body.+ wire, err := json.Marshal(r)+ if err != nil {+ t.Fatal(err)+ }+ for _, leaked := range []string{"be precise", "project ctx", "repo rules", "do the task", "secret", "https://x", "body"} {+ if strings.Contains(string(wire), leaked) {+ t.Fatalf("receipt leaks content %q: %s", leaked, wire)+ }+ }+}++func TestBuildContextReceiptLoadStates(t *testing.T) {+ workDir := t.TempDir()+ cases := []struct {+ name string+ in contextReceiptInput+ delivery string+ load string+ path string+ }{+ {+ name: "probed runtime at its probed version",+ in: contextReceiptInput{Provider: "claude", RuntimeVersion: "2.1.220 (Claude Code)"},+ delivery: ReceiptDeliveryFile, load: ReceiptLoadVerified, path: "CLAUDE.md",+ },+ {+ name: "probed runtime with unknown version",+ in: contextReceiptInput{Provider: "codex"},+ delivery: ReceiptDeliveryFile, load: ReceiptLoadVerifiedOtherVersion, path: "AGENTS.md",+ },+ {+ name: "unprobed runtime",+ in: contextReceiptInput{Provider: "qwen", RuntimeVersion: "0.9.0"},+ delivery: ReceiptDeliveryFile, load: ReceiptLoadUnverified, path: "QWEN.md",+ },+ {+ name: "custom command at vendor probed version is not the probed runtime",+ in: contextReceiptInput{Provider: "claude", RuntimeVersion: "2.1.220", CustomRuntime: true},+ delivery: ReceiptDeliveryFile, load: ReceiptLoadUnverified, path: "CLAUDE.md",+ },+ {+ name: "inline system prompt wins over the file",+ in: contextReceiptInput{Provider: "traecli", InlineBrief: true},+ delivery: ReceiptDeliveryInline, load: ReceiptLoadDelivered,+ },+ {+ name: "no file target and not inline",+ in: contextReceiptInput{Provider: "no-such-runtime"},+ delivery: ReceiptDeliveryNone, load: ReceiptLoadNotDelivered,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ tc.in.WorkDir = workDir+ tc.in.RuntimeBrief = "brief"+ tc.in.BriefWritten = true+ r := buildContextReceipt(tc.in)+ brief := receiptSource(t, r, ReceiptKindRuntimeBrief, "")+ if brief.Delivery != tc.delivery || brief.Load != tc.load || brief.Path != tc.path {+ t.Fatalf("brief = %+v, want delivery=%s load=%s path=%q", brief, tc.delivery, tc.load, tc.path)+ }+ })+ }+}++func TestBuildContextReceiptOmitsEmptySections(t *testing.T) {+ r := buildContextReceipt(contextReceiptInput{Provider: "claude", WorkDir: t.TempDir(), ExistingInstructions: ""})+ for _, kind := range []string{ReceiptKindAgentInstructions, ReceiptKindProjectDescription, ReceiptKindExistingInstructions, ReceiptKindSkill} {+ if receiptHasKind(r, kind) {+ t.Fatalf("empty %s should not be listed: %+v", kind, r.Sources)+ }+ }+ if r.MCPServers == nil {+ t.Fatal("mcp_servers must encode as [] rather than null")+ }+}++func TestSkillDeliveryLocationForHomeBasedRuntimes(t *testing.T) {+ if got := execenv.SkillDeliveryLocation(t.TempDir(), "codex"); got != "$CODEX_HOME/skills" {+ t.Fatalf("codex skill path = %q", got)+ }+}++func TestExistingRuntimeConfigContentStripsManagedBlock(t *testing.T) {+ workDir := t.TempDir()+ path := filepath.Join(workDir, "AGENTS.md")+ if err := os.WriteFile(path, []byte("# Repo rules\nuse tabs\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ if _, err := execenv.InjectRuntimeConfig(workDir, "codex", execenv.TaskContextForEnv{IssueID: "i"}); err != nil {+ t.Fatal(err)+ }+ if got := execenv.ExistingRuntimeConfigContent(workDir, "codex"); got != "# Repo rules\nuse tabs\n" {+ t.Fatalf("existing content = %q", got)+ }++ // A file the daemon created from nothing has no pre-existing content.+ fresh := t.TempDir()+ if _, err := execenv.InjectRuntimeConfig(fresh, "claude", execenv.TaskContextForEnv{IssueID: "i"}); err != nil {+ t.Fatal(err)+ }+ if got := execenv.ExistingRuntimeConfigContent(fresh, "claude"); got != "" {+ t.Fatalf("daemon-created file reported existing content %q", got)+ }+}++func TestReportContextReceiptPostsAndToleratesOldServer(t *testing.T) {+ var gotPath string+ var gotBody map[string]json.RawMessage+ status := http.StatusOK+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotPath = r.URL.Path+ body, _ := io.ReadAll(r.Body)+ _ = json.Unmarshal(body, &gotBody)+ w.WriteHeader(status)+ }))+ defer srv.Close()++ d := &Daemon{client: NewClient(srv.URL)}+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ receipt := buildContextReceipt(contextReceiptInput{Provider: "claude", WorkDir: t.TempDir(), Prompt: "p"})++ d.reportContextReceipt(context.Background(), "task-1", receipt, logger)+ if gotPath != "/api/daemon/tasks/task-1/context-receipt" {+ t.Fatalf("posted to %q", gotPath)+ }+ var echoed ContextReceipt+ if err := json.Unmarshal(gotBody["receipt"], &echoed); err != nil || echoed.Runtime != "claude" {+ t.Fatalf("body receipt = %s (%v)", gotBody["receipt"], err)+ }++ // An older server without the route answers 404; the report must simply+ // return (the run is not affected).+ status = http.StatusNotFound+ d.reportContextReceipt(context.Background(), "task-1", receipt, logger)+}++func TestContextReceiptFailedBriefWrite(t *testing.T) {+ workDir := t.TempDir()+ // A directory at the instruction-file path rejects the write on every+ // platform, including test runners allowed to overwrite read-only files.+ if err := os.Mkdir(filepath.Join(workDir, "CLAUDE.md"), 0o755); err != nil {+ t.Fatal(err)+ }+ taskCtx := execenv.TaskContextForEnv{AgentInstructions: "required instruction"}+ brief, err := execenv.InjectRuntimeConfig(workDir, "claude", taskCtx)+ if err == nil {+ t.Fatal("expected injection to fail")+ }+ r := buildContextReceipt(contextReceiptInput{+ Provider: "claude", RuntimeVersion: "2.1.220", WorkDir: workDir,+ RuntimeBrief: brief, TaskCtx: taskCtx,+ })+ for _, kind := range []string{ReceiptKindRuntimeBrief, ReceiptKindAgentInstructions} {+ s := receiptSource(t, r, kind, "")+ if s.Load != ReceiptLoadNotDelivered {+ t.Errorf("%s after failed write: load = %s, want not_delivered", kind, s.Load)+ }+ }+}++func TestContextReceiptUsesMaterializedSkill(t *testing.T) {+ taskCtx := execenv.TaskContextForEnv{AgentSkills: []execenv.SkillContextForEnv{{+ Name: "Code Review", Content: "Be concise.",+ }}}+ env, err := execenv.Prepare(execenv.PrepareParams{+ WorkspacesRoot: t.TempDir(), WorkspaceID: "receipt-workspace",+ TaskID: "receipt-task", Provider: "kiro", Task: taskCtx,+ }, slog.New(slog.NewTextHandler(io.Discard, nil)))+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = env.Cleanup(true) })+ taskCtx = execenv.ApplyPreparedSkillNames(taskCtx, env.PreparedSkillNames)+ r := buildContextReceipt(contextReceiptInput{+ Provider: "kiro", WorkDir: env.WorkDir, TaskCtx: taskCtx,+ Skills: env.SkillReceipts("kiro", taskCtx.AgentSkills),+ })+ source := receiptSource(t, r, ReceiptKindSkill, taskCtx.AgentSkills[0].Name)+ actual, err := os.ReadFile(filepath.Join(env.WorkDir, filepath.FromSlash(source.Path)))+ if err != nil {+ t.Fatal(err)+ }+ if source.Bytes != len(actual) {+ t.Errorf("receipt bytes = %d, materialized file bytes = %d", source.Bytes, len(actual))+ }+ if source.SHA256 == receiptHash(taskCtx.AgentSkills[0].Content) || len(source.SHA256) != 12 {+ t.Errorf("skill fingerprint = %q, want the materialized package fingerprint", source.SHA256)+ }+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 7ec1102ced..d26a4abb78 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -8722,6 +8722,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// Build the runtime brief and inject it into the provider-specific// instruction file when supported.runtimeBrief, err := execenv.InjectRuntimeConfig(env.WorkDir, provider, taskCtx)+ runtimeBriefWritten := err == nilif err != nil {d.logger.Warn("execenv: inject runtime config failed (non-fatal)", "error", err)}@@ -8923,6 +8924,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ireturn TaskResult{}, fmt.Errorf("prepare fresh OpenCode session after clock check: %w", briefErr)} else {runtimeBrief = freshBrief+ runtimeBriefWritten = true}prompt = BuildPrompt(task, provider, promptOptions...)}@@ -9109,6 +9111,26 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i"idle_watchdog", execOpts.IdleWatchdogTimeout,)+ // MUL-9013: record what this run is being handed, before it starts, so a+ // run that dies early still has a receipt. Rebuilt for the cold retry.+ receiptInput := contextReceiptInput{+ Provider: provider,+ RuntimeVersion: resolvedVersion,+ CustomRuntime: usesCustomProfileCommand,+ Model: model,+ WorkDir: env.WorkDir,+ Prompt: prompt,+ RuntimeBrief: runtimeBrief,+ InlineBrief: execOpts.SystemPrompt != "",+ BriefWritten: runtimeBriefWritten,+ ResumedSession: execOpts.ResumeSessionID != "",+ MCPConfig: mcpConfig,+ TaskCtx: taskCtx,+ Skills: env.SkillReceipts(provider, taskCtx.AgentSkills),+ ExistingInstructions: execenv.ExistingRuntimeConfigContent(env.WorkDir, provider),+ }+ d.reportContextReceipt(ctx, task.ID, buildContextReceipt(receiptInput), taskLog)+// Shared across the resume-retry below so the retry's transcript rows// keep ascending seq values for the same task.var msgSeq atomic.Int32@@ -9170,16 +9192,34 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot itask.PriorSessionResumeUnavailable = trueexecOpts.ResumeContinuityNotice = ""taskCtx.PriorSessionResumed = false- if freshBrief, briefErr := execenv.InjectRuntimeConfig(env.WorkDir, provider, taskCtx); briefErr != nil {+ runtimeBriefWritten = false+ freshBrief, briefErr := execenv.InjectRuntimeConfig(env.WorkDir, provider, taskCtx)+ if briefErr != nil {taskLog.Warn("execenv: re-inject cold runtime config for fresh retry failed (non-fatal)", "error", briefErr)} else {runtimeBrief = freshBrief+ runtimeBriefWritten = trueif providerNeedsInlineSystemPrompt(provider) {execOpts.SystemPrompt = runtimeBrief}}freshPrompt := BuildPrompt(task, provider, promptOptions...)+ receiptInput.Prompt = freshPrompt+ receiptInput.RuntimeBrief = freshBrief+ receiptInput.InlineBrief = execOpts.SystemPrompt != ""+ if receiptInput.InlineBrief {+ // A failed file rewrite leaves the prior inline payload in use.+ receiptInput.RuntimeBrief = execOpts.SystemPrompt+ }+ receiptInput.BriefWritten = runtimeBriefWritten+ receiptInput.ResumedSession = false+ receiptInput.FreshRetry = true+ receiptInput.TaskCtx = taskCtx+ receiptInput.Skills = env.SkillReceipts(provider, taskCtx.AgentSkills)+ receiptInput.ExistingInstructions = execenv.ExistingRuntimeConfigContent(env.WorkDir, provider)+ d.reportContextReceipt(ctx, task.ID, buildContextReceipt(receiptInput), taskLog)+retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, freshPrompt, withPriorTaskUsage(execOpts, firstUsage), taskLog, task.ID, env.CodexHome, &msgSeq)if retryErr != nil {taskLog.Error("fresh session also failed to start; keeping the original poisoned result", "error", retryErr)diff --git a/server/internal/daemon/execenv/receipt.go b/server/internal/daemon/execenv/receipt.gonew file mode 100644index 0000000000..765ccb1516--- /dev/null+++ b/server/internal/daemon/execenv/receipt.go@@ -0,0 +1,146 @@+package execenv++import (+ "crypto/sha256"+ "encoding/binary"+ "encoding/hex"+ "io"+ "os"+ "path/filepath"+ "sort"+ "strings"++ skillpkg "github.com/multica-ai/multica/server/internal/skill"+)++// Read-only views over what Prepare / InjectRuntimeConfig put on disk, for the+// per-run context receipt (MUL-9013). None of these create, write or record+// anything: they only describe where a source went so the receipt can name it.++// RuntimeConfigRelPath returns the workdir-relative path of the provider's+// runtime config file (CLAUDE.md, AGENTS.md, QWEN.md, ...), or "" when the+// provider has no file target and the brief can only travel inline.+func RuntimeConfigRelPath(workDir, provider string) string {+ path := runtimeConfigPath(workDir, provider)+ if path == "" {+ return ""+ }+ if rel, err := filepath.Rel(workDir, path); err == nil {+ return filepath.ToSlash(rel)+ }+ return filepath.Base(path)+}++// ExistingRuntimeConfigContent returns the part of the provider's runtime+// config file that Multica does not manage: what the repository (or the user)+// already had in CLAUDE.md / AGENTS.md before the brief was appended. Empty+// when the file is missing, holds only the managed block, or cannot be read.+func ExistingRuntimeConfigContent(workDir, provider string) string {+ path := runtimeConfigPath(workDir, provider)+ if path == "" {+ return ""+ }+ // A missing or unreadable file both mean "nothing pre-existing we can+ // report"; the receipt is diagnostic and must not fail the run.+ data, err := os.ReadFile(path)+ if err != nil {+ return ""+ }+ content := string(data)+ start, end, ok := locateMarkerBlock(content)+ if !ok {+ return content+ }+ pre := strings.TrimSuffix(content[:start], runtimeManagedSeparator)+ return pre + content[end:]+}++// SkillDeliveryLocation names where this provider's skills are materialized,+// for display only. Workdir-relative for runtimes that discover skills from+// the project tree; a per-task home for the two that read them from there.+func SkillDeliveryLocation(workDir, provider string) string {+ switch provider {+ case "codex":+ return "$CODEX_HOME/skills"+ case "hermes":+ return "$HERMES_HOME/skills"+ case "qwenpaw":+ // QwenPaw receives this private directory through --workspace.+ return "<QwenPaw workspace>/skills"+ }+ dir := skillsDirPath(workDir, provider)+ if rel, err := filepath.Rel(workDir, dir); err == nil {+ return filepath.ToSlash(rel)+ }+ return dir+}++// SkillReceipt describes a complete materialized skill package. Available is+// false if any declared file could not be read; no partial fingerprint is used.+type SkillReceipt struct {+ Name string+ Path string+ Bytes int+ SHA256 string+ Available bool+}++// SkillReceipts snapshots the actual prepared files, including frontmatter+// rewriting and collision-free names. It reads only files declared by the+// skill, not neighboring user-installed skills or runtime-generated files.+func (e *Environment) SkillReceipts(provider string, skills []SkillContextForEnv) []SkillReceipt {+ dir := skillsDirPath(e.WorkDir, provider)+ switch provider {+ case "codex":+ dir = filepath.Join(e.CodexHome, "skills")+ case "hermes":+ dir = filepath.Join(e.HermesHome, "skills")+ case "qwenpaw":+ dir = filepath.Join(e.QwenpawWorkspace, "skills")+ }+ receipts := make([]SkillReceipt, 0, len(skills))+ for _, skill := range skills {+ r := SkillReceipt{+ Name: skill.Name,+ Path: SkillDeliveryLocation(e.WorkDir, provider) + "/" + skill.Name + "/SKILL.md",+ }+ paths := map[string]struct{}{"SKILL.md": {}}+ for _, f := range skill.Files {+ if skillpkg.IsReservedContentPath(f.Path) {+ continue+ }+ paths[filepath.ToSlash(filepath.Clean(f.Path))] = struct{}{}+ }+ ordered := make([]string, 0, len(paths))+ for path := range paths {+ ordered = append(ordered, path)+ }+ sort.Strings(ordered)+ hash := sha256.New()+ available := true+ for _, path := range ordered {+ data, err := os.ReadFile(filepath.Join(dir, skill.Name, filepath.FromSlash(path)))+ if err != nil {+ available = false+ break+ }+ // Frame sorted relative paths and file lengths so changes to any+ // file (or filename) affect the package hash unambiguously.+ _, _ = io.WriteString(hash, path)+ _, _ = hash.Write([]byte{0})+ var length [8]byte+ binary.BigEndian.PutUint64(length[:], uint64(len(data)))+ _, _ = hash.Write(length[:])+ _, _ = hash.Write(data)+ r.Bytes += len(data)+ }+ if available {+ r.Available = true+ r.SHA256 = hex.EncodeToString(hash.Sum(nil))[:12]+ } else {+ r.Bytes = 0+ }+ receipts = append(receipts, r)+ }+ return receipts+}diff --git a/server/internal/daemon/execenv/receipt_test.go b/server/internal/daemon/execenv/receipt_test.gonew file mode 100644index 0000000000..ed769973dc--- /dev/null+++ b/server/internal/daemon/execenv/receipt_test.go@@ -0,0 +1,70 @@+package execenv++import (+ "os"+ "path/filepath"+ "testing"+)++func TestSkillReceiptIncludesWrittenSupportingFiles(t *testing.T) {+ env := &Environment{WorkDir: t.TempDir()}+ skills := []SkillContextForEnv{{Name: "check", Content: "Check it.", Files: []SkillFileContextForEnv{+ {Path: "b.md", Content: "two"},+ {Path: "a.md", Content: "one"},+ {Path: "./SKILL.md", Content: "duplicate primary content is not written"},+ }}}+ dir := skillsDirPath(env.WorkDir, "kiro")+ if err := writeSkillFiles(dir, skills, nil); err != nil {+ t.Fatal(err)+ }+ before := env.SkillReceipts("kiro", skills)[0]+ primary, err := os.ReadFile(filepath.Join(dir, "check", "SKILL.md"))+ if err != nil {+ t.Fatal(err)+ }+ if !before.Available || before.Bytes != len(primary)+6 || len(before.SHA256) != 12 {+ t.Fatalf("receipt = %+v, primary bytes = %d", before, len(primary))+ }+ // Listing order does not change the package, and the duplicate SKILL.md+ // entry must not inflate the size or replace the prepared frontmatter.+ skills[0].Files[0], skills[0].Files[1] = skills[0].Files[1], skills[0].Files[0]+ if reordered := env.SkillReceipts("kiro", skills)[0]; reordered != before {+ t.Fatalf("reordering file declarations changed the receipt: %+v -> %+v", before, reordered)+ }+ // A same-size change on disk must change the fingerprint even though+ // the configured primary content and total bytes remain identical.+ if err := os.WriteFile(filepath.Join(dir, "check", "a.md"), []byte("new"), 0o644); err != nil {+ t.Fatal(err)+ }+ after := env.SkillReceipts("kiro", skills)[0]+ if after.SHA256 == before.SHA256 || after.Bytes != before.Bytes {+ t.Fatalf("supporting-file change: before=%+v after=%+v", before, after)+ }+ if err := os.Remove(filepath.Join(dir, "check", "a.md")); err != nil {+ t.Fatal(err)+ }+ if missing := env.SkillReceipts("kiro", skills)[0]; missing.Available || missing.SHA256 != "" || missing.Bytes != 0 {+ t.Fatalf("partial package got a fingerprint: %+v", missing)+ }+}++func TestSkillReceiptUsesRuntimeHome(t *testing.T) {+ for _, tc := range []struct{ provider, display string }{+ {"codex", "$CODEX_HOME/skills"},+ {"hermes", "$HERMES_HOME/skills"},+ {"qwenpaw", "<QwenPaw workspace>/skills"},+ } {+ t.Run(tc.provider, func(t *testing.T) {+ home := t.TempDir()+ env := &Environment{WorkDir: t.TempDir(), CodexHome: home, HermesHome: home, QwenpawWorkspace: home}+ skills := []SkillContextForEnv{{Name: "check", Content: "check"}}+ if err := writeSkillFiles(filepath.Join(home, "skills"), skills, nil); err != nil {+ t.Fatal(err)+ }+ got := env.SkillReceipts(tc.provider, skills)[0]+ if !got.Available || got.Path != tc.display+"/check/SKILL.md" {+ t.Fatalf("receipt = %+v", got)+ }+ })+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 6f31eb8115..0e7d94c3a1 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -6597,14 +6597,16 @@ func attachTaskUsage(resp []AgentTaskResponse, byTask map[string][]TaskUsageData}}-// ListTaskMessagesByUser returns task messages for a task.-// Used by the frontend under regular user auth (not daemon auth).-// Verifies the task belongs to the caller's workspace.-func (h *Handler) ListTaskMessagesByUser(w http.ResponseWriter, r *http.Request) {+// loadTaskForUser resolves {taskId} for a member request and enforces every+// read rule a run's details are under: same workspace, chat-session owner for+// chat tasks, and project visibility (MUL-8472). Any failure is written as the+// response — a task the caller may not see reads as not found — and false is+// returned.+func (h *Handler) loadTaskForUser(w http.ResponseWriter, r *http.Request) (db.AgentTaskQueue, bool) {taskID := chi.URLParam(r, "taskId")taskUUID, ok := parseUUIDOrBadRequest(w, taskID, "task_id")if !ok {- return+ return db.AgentTaskQueue{}, false}task, err := h.Queries.GetAgentTask(r.Context(), taskUUID)@@ -6612,10 +6614,10 @@ func (h *Handler) ListTaskMessagesByUser(w http.ResponseWriter, r *http.Request)if !isNotFound(err) {slog.Warn("get agent task failed", "task_id", taskID, "error", err)writeError(w, http.StatusInternalServerError, "failed to load task")- return+ return db.AgentTaskQueue{}, false}writeError(w, http.StatusNotFound, "task not found")- return+ return db.AgentTaskQueue{}, false}// Verify the task belongs to the caller's workspace. A failed lookup is a@@ -6626,28 +6628,41 @@ func (h *Handler) ListTaskMessagesByUser(w http.ResponseWriter, r *http.Request)if err != nil {slog.Warn("resolve task workspace failed", "task_id", taskID, "error", err)writeError(w, http.StatusInternalServerError, "failed to load task")- return+ return db.AgentTaskQueue{}, false}// Mismatch stays a 404 rather than a 403: a task in another workspace must// be indistinguishable from one that does not exist.wsID := scope.WorkspaceIDif wsID == "" || wsID != middleware.WorkspaceIDFromContext(r.Context()) {writeError(w, http.StatusNotFound, "task not found")- return+ return db.AgentTaskQueue{}, false}// A chat task's transcript belongs to the chat session's creator alone;// to anyone else it does not exist either.if task.ChatSessionID.Valid && (scope.ChatSessionOwnerID == "" || scope.ChatSessionOwnerID != requestUserID(r)) {writeError(w, http.StatusNotFound, "task not found")- return+ return db.AgentTaskQueue{}, false}// A run's transcript is visible exactly where the projects it reads are// (MUL-8472), including runs that have no issue. Task ids reach every// member through task lifecycle events, so this cannot rely on the issue// page being unreachable.if !h.requireTaskVisible(w, r, wsID, task, http.StatusNotFound, "task not found") {+ return db.AgentTaskQueue{}, false+ }+ return task, true+}++// ListTaskMessagesByUser returns task messages for a task.+// Used by the frontend under regular user auth (not daemon auth).+// Verifies the task belongs to the caller's workspace.+func (h *Handler) ListTaskMessagesByUser(w http.ResponseWriter, r *http.Request) {+ task, ok := h.loadTaskForUser(w, r)+ if !ok {return}+ taskID := chi.URLParam(r, "taskId")+ taskUUID := task.IDvar (messages []db.TaskMessagediff --git a/server/internal/handler/task_context_receipt.go b/server/internal/handler/task_context_receipt.gonew file mode 100644index 0000000000..d77a9a4c8d--- /dev/null+++ b/server/internal/handler/task_context_receipt.go@@ -0,0 +1,152 @@+package handler++import (+ "encoding/json"+ "log/slog"+ "net/http"+ "time"++ "github.com/go-chi/chi/v5"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Context receipt (MUL-9013). The daemon reports, once per run, which context+// sources it handed the agent — sizes, short hashes, delivery and load+// evidence, never content. Members read it from the run's transcript dialog.++const (+ maxContextReceiptBodyBytes = 256 << 10+ maxContextReceiptSources = 512+ maxContextReceiptMCP = 128+ maxContextReceiptString = 512+)++// contextReceipt is the stored shape. Decoding into it (rather than storing+// the raw body) drops any field this server does not know, so the column only+// ever holds metadata the reader is built for.+type contextReceipt struct {+ SchemaVersion int `json:"schema_version"`+ Runtime string `json:"runtime"`+ RuntimeVersion string `json:"runtime_version,omitempty"`+ Model string `json:"model,omitempty"`+ PromptBytes int `json:"prompt_bytes"`+ BriefBytes int `json:"brief_bytes"`+ BriefDelivery string `json:"brief_delivery"`+ ResumedSession bool `json:"resumed_session"`+ FreshRetry bool `json:"fresh_retry,omitempty"`+ MCPServers []string `json:"mcp_servers"`+ Sources []contextReceiptSource `json:"sources"`+}++type contextReceiptSource struct {+ Kind string `json:"kind"`+ Name string `json:"name,omitempty"`+ Bytes int `json:"bytes"`+ SHA256 string `json:"sha256,omitempty"`+ Delivery string `json:"delivery"`+ Path string `json:"path,omitempty"`+ Load string `json:"load"`+ VerifiedVersion string `json:"verified_version,omitempty"`+ Parent string `json:"parent,omitempty"`+}++func (c *contextReceipt) valid() bool {+ if c.SchemaVersion < 1 || c.Runtime == "" {+ return false+ }+ if len(c.Sources) > maxContextReceiptSources || len(c.MCPServers) > maxContextReceiptMCP {+ return false+ }+ if c.PromptBytes < 0 || c.BriefBytes < 0 {+ return false+ }+ for _, s := range []string{c.Runtime, c.RuntimeVersion, c.Model, c.BriefDelivery} {+ if len(s) > maxContextReceiptString {+ return false+ }+ }+ for _, name := range c.MCPServers {+ if len(name) > maxContextReceiptString {+ return false+ }+ }+ for _, src := range c.Sources {+ if src.Kind == "" || src.Bytes < 0 {+ return false+ }+ for _, s := range []string{src.Kind, src.Name, src.SHA256, src.Delivery, src.Path, src.Load, src.VerifiedVersion, src.Parent} {+ if len(s) > maxContextReceiptString {+ return false+ }+ }+ }+ return true+}++// ReportTaskContextReceipt stores the daemon's receipt for a task, replacing+// any earlier one (the fresh-session retry re-reports).+func (h *Handler) ReportTaskContextReceipt(w http.ResponseWriter, r *http.Request) {+ r.Body = http.MaxBytesReader(w, r.Body, maxContextReceiptBodyBytes)+ task, workspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, chi.URLParam(r, "taskId"))+ if !ok {+ return+ }++ var req struct {+ Receipt *contextReceipt `json:"receipt"`+ }+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Receipt == nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if !req.Receipt.valid() {+ writeError(w, http.StatusBadRequest, "invalid receipt")+ return+ }+ if req.Receipt.MCPServers == nil {+ req.Receipt.MCPServers = []string{}+ }+ if req.Receipt.Sources == nil {+ req.Receipt.Sources = []contextReceiptSource{}+ }+ stored, err := json.Marshal(req.Receipt)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to encode receipt")+ return+ }+ if err := h.Queries.UpsertTaskContextReceipt(r.Context(), db.UpsertTaskContextReceiptParams{+ TaskID: task.ID,+ WorkspaceID: parseUUID(workspaceID),+ IssueID: task.IssueID,+ Receipt: stored,+ }); err != nil {+ slog.Warn("store task context receipt failed", "task_id", uuidToString(task.ID), "error", err)+ writeError(w, http.StatusInternalServerError, "failed to store receipt")+ return+ }+ w.WriteHeader(http.StatusNoContent)+}++// GetTaskContextReceipt returns a run's receipt to a member who may read the+// run. A run without one (an older daemon, or a run that never launched)+// answers 200 with a null receipt so the reader can say so without an error.+func (h *Handler) GetTaskContextReceipt(w http.ResponseWriter, r *http.Request) {+ task, ok := h.loadTaskForUser(w, r)+ if !ok {+ return+ }+ row, err := h.Queries.GetTaskContextReceipt(r.Context(), task.ID)+ if err != nil {+ if isNotFound(err) {+ writeJSON(w, http.StatusOK, map[string]any{"receipt": nil})+ return+ }+ slog.Warn("load task context receipt failed", "task_id", uuidToString(task.ID), "error", err)+ writeError(w, http.StatusInternalServerError, "failed to load receipt")+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "receipt": json.RawMessage(row.Receipt),+ "recorded_at": row.UpdatedAt.Time.UTC().Format(time.RFC3339),+ })+}diff --git a/server/internal/handler/task_context_receipt_test.go b/server/internal/handler/task_context_receipt_test.gonew file mode 100644index 0000000000..8b9710c472--- /dev/null+++ b/server/internal/handler/task_context_receipt_test.go@@ -0,0 +1,196 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func contextReceiptFixture(t *testing.T, label ...string) (issueID, taskID string) {+ t.Helper()+ name := "context-receipt " + strings.Join(label, " ")+ runtimeID := dbfx.Runtime(t, name+" runtime")+ agentID := dbfx.Agent(t, name+" agent", runtimeID)+ issueID = dbfx.Issue(t, name+" issue")+ taskID = dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "runtime_id": runtimeID, "status": "running"})+ dbfx.Cleanup(t, `DELETE FROM task_context_receipt WHERE task_id = $1`, taskID)+ return issueID, taskID+}++func sampleContextReceipt() map[string]any {+ return map[string]any{+ "schema_version": 1,+ "runtime": "kiro",+ "runtime_version": "2.34.0",+ "model": "claude-opus",+ "prompt_bytes": 2640,+ "brief_bytes": 19022,+ "brief_delivery": "file",+ "resumed_session": true,+ "mcp_servers": []string{"github"},+ "sources": []map[string]any{+ {"kind": "runtime_brief", "bytes": 19022, "sha256": "cdc096ed0000", "delivery": "file", "path": "AGENTS.md", "load": "verified_other_version", "verified_version": "2.13.0"},+ {"kind": "skill", "name": "pr-review", "bytes": 19412, "sha256": "e07c21000000", "delivery": "file", "path": ".kiro/skills/pr-review/SKILL.md", "load": "unverified"},+ },+ // A field this server does not know must not reach the column.+ "content": "the full brief text",+ }+}++func reportContextReceipt(t *testing.T, taskID string, receipt any) *testutil.Response {+ t.Helper()+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/context-receipt",+ map[string]any{"receipt": receipt}), "taskId", taskID)+ return testutil.Call(t, testHandler.ReportTaskContextReceipt, req)+}++type contextReceiptResponse struct {+ Receipt *contextReceipt `json:"receipt"`+ RecordedAt string `json:"recorded_at"`+}++func getContextReceipt(t *testing.T, taskID, userID string) *testutil.Response {+ t.Helper()+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/tasks/"+taskID+"/context-receipt", nil), userID), "taskId", taskID)+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))+ return testutil.Call(t, testHandler.GetTaskContextReceipt, req)+}++func TestTaskContextReceipt_ReportThenRead(t *testing.T) {+ issueID, taskID := contextReceiptFixture(t)++ // Before the daemon reports, the reader gets an explicit null.+ var empty contextReceiptResponse+ getContextReceipt(t, taskID, testUserID).Want(http.StatusOK).JSON(&empty)+ if empty.Receipt != nil {+ t.Fatalf("receipt before report = %+v, want null", empty.Receipt)+ }++ reportContextReceipt(t, taskID, sampleContextReceipt()).Want(http.StatusNoContent)++ var got contextReceiptResponse+ getContextReceipt(t, taskID, testUserID).Want(http.StatusOK).JSON(&got)+ if got.Receipt == nil || got.Receipt.Runtime != "kiro" || len(got.Receipt.Sources) != 2 || got.RecordedAt == "" {+ t.Fatalf("receipt = %+v recorded_at=%q", got.Receipt, got.RecordedAt)+ }+ if s := got.Receipt.Sources[0]; s.Load != "verified_other_version" || s.VerifiedVersion != "2.13.0" || s.Path != "AGENTS.md" {+ t.Fatalf("brief row = %+v", s)+ }++ var stored string+ if err := testPool.QueryRow(context.Background(),+ `SELECT receipt::text FROM task_context_receipt WHERE task_id = $1 AND issue_id = $2`, taskID, issueID,+ ).Scan(&stored); err != nil {+ t.Fatalf("load stored receipt: %v", err)+ }+ if strings.Contains(stored, "the full brief text") {+ t.Fatalf("unknown field reached storage: %s", stored)+ }++ // A re-report (the fresh-session retry) replaces the receipt in place.+ retry := sampleContextReceipt()+ retry["resumed_session"] = false+ retry["fresh_retry"] = true+ reportContextReceipt(t, taskID, retry).Want(http.StatusNoContent)+ getContextReceipt(t, taskID, testUserID).Want(http.StatusOK).JSON(&got)+ if got.Receipt.ResumedSession || !got.Receipt.FreshRetry {+ t.Fatalf("retry receipt = %+v", got.Receipt)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM task_context_receipt WHERE task_id = $1`, taskID); n != 1 {+ t.Fatalf("rows after re-report = %d, want 1", n)+ }+}++func TestTaskContextReceipt_RejectsMalformed(t *testing.T) {+ _, taskID := contextReceiptFixture(t)++ noRuntime := sampleContextReceipt()+ delete(noRuntime, "runtime")+ reportContextReceipt(t, taskID, noRuntime).Want(http.StatusBadRequest)++ tooLong := sampleContextReceipt()+ tooLong["model"] = strings.Repeat("m", maxContextReceiptString+1)+ reportContextReceipt(t, taskID, tooLong).Want(http.StatusBadRequest)++ negative := sampleContextReceipt()+ negative["sources"] = []map[string]any{{"kind": "skill", "bytes": -1, "delivery": "file", "load": "unverified"}}+ reportContextReceipt(t, taskID, negative).Want(http.StatusBadRequest)++ reportContextReceipt(t, taskID, nil).Want(http.StatusBadRequest)++ if n := dbfx.Count(t, `SELECT count(*) FROM task_context_receipt WHERE task_id = $1`, taskID); n != 0 {+ t.Fatalf("rejected receipts stored %d rows", n)+ }+}++func TestTaskContextReceipt_OtherWorkspaceDaemonCannotReport(t *testing.T) {+ _, taskID := contextReceiptFixture(t)+ req := withURLParam(newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/context-receipt",+ map[string]any{"receipt": sampleContextReceipt()},+ "00000000-0000-0000-0000-000000000000", "attacker-daemon"), "taskId", taskID)+ testutil.Call(t, testHandler.ReportTaskContextReceipt, req).Want(http.StatusNotFound)+ if n := dbfx.Count(t, `SELECT count(*) FROM task_context_receipt WHERE task_id = $1`, taskID); n != 0 {+ t.Fatalf("foreign daemon stored %d rows", n)+ }+}++// The receipt is readable exactly where the run's transcript is: a member who+// cannot see the private project gets the same 404 as for a missing task.+func TestTaskContextReceipt_FollowsRunVisibility(t *testing.T) {+ f := newPrivateProjectFixture(t)+ agentID := seededHandlerTestAgent(t)+ taskID := dbfx.Task(t, agentID, testutil.Cols{"issue_id": f.secretIssue, "runtime_id": testRuntimeID})+ dbfx.Cleanup(t, `DELETE FROM task_context_receipt WHERE task_id = $1`, taskID)+ reportContextReceipt(t, taskID, sampleContextReceipt()).Want(http.StatusNoContent)++ getContextReceipt(t, taskID, f.outsider).Want(http.StatusNotFound)+ var got contextReceiptResponse+ getContextReceipt(t, taskID, f.insider).Want(http.StatusOK).JSON(&got)+ if got.Receipt == nil {+ t.Fatal("insider should read the receipt")+ }+}++func TestTaskContextReceipt_RemovedWithIssueAndTaskBatch(t *testing.T) {+ issueID, taskID := contextReceiptFixture(t)+ reportContextReceipt(t, taskID, sampleContextReceipt()).Want(http.StatusNoContent)+ if err := testHandler.Queries.DeleteIssue(context.Background(), db.DeleteIssueParams{+ ID: parseUUID(issueID), WorkspaceID: parseUUID(testWorkspaceID),+ }); err != nil {+ t.Fatalf("delete issue: %v", err)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM task_context_receipt WHERE task_id = $1`, taskID); n != 0 {+ t.Fatalf("receipt survived issue deletion (%d rows)", n)+ }++ _, batchTask := contextReceiptFixture(t, "batch")+ reportContextReceipt(t, batchTask, sampleContextReceipt()).Want(http.StatusNoContent)+ if err := testHandler.Queries.DeleteTaskBatch(context.Background(), []pgtype.UUID{parseUUID(batchTask)}); err != nil {+ t.Fatalf("delete task batch: %v", err)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM task_context_receipt WHERE task_id = $1`, batchTask); n != 0 {+ t.Fatalf("receipt survived task batch deletion (%d rows)", n)+ }+}++// Encoded body sanity: the reader sees mcp_servers / sources as arrays even+// when the daemon omitted them.+func TestTaskContextReceipt_NormalizesEmptyLists(t *testing.T) {+ _, taskID := contextReceiptFixture(t)+ reportContextReceipt(t, taskID, map[string]any{"schema_version": 1, "runtime": "claude"}).Want(http.StatusNoContent)+ rec := getContextReceipt(t, taskID, testUserID).Want(http.StatusOK)+ var raw struct {+ Receipt map[string]json.RawMessage `json:"receipt"`+ }+ rec.JSON(&raw)+ if string(raw.Receipt["mcp_servers"]) != "[]" || string(raw.Receipt["sources"]) != "[]" {+ t.Fatalf("receipt lists = mcp %s sources %s", raw.Receipt["mcp_servers"], raw.Receipt["sources"])+ }+}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex abb4c440e1..7da74c5728 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -135,6 +135,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"squad_member": workspaceDelete,"sys_cron_executions": workspaceDeleteKeep,"theme_store_download": workspaceDeleteKeep, // per registry theme, not workspace-owned+ "task_context_receipt": workspaceDelete,"task_message": workspaceDelete,"task_supplement": workspaceDelete,"task_supplement_capability": workspaceDelete,diff --git a/server/migrations/649_task_context_receipt.down.sql b/server/migrations/649_task_context_receipt.down.sqlnew file mode 100644index 0000000000..195ce76942--- /dev/null+++ b/server/migrations/649_task_context_receipt.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS task_context_receipt;diff --git a/server/migrations/649_task_context_receipt.up.sql b/server/migrations/649_task_context_receipt.up.sqlnew file mode 100644index 0000000000..07acf312c0--- /dev/null+++ b/server/migrations/649_task_context_receipt.up.sql@@ -0,0 +1,17 @@+-- Per-run context receipt (MUL-9013): which context sources the daemon handed+-- a run, with sizes, short hashes, delivery and load evidence. Metadata only;+-- the daemon never sends source content. One row per task, replaced when the+-- daemon re-reports for a fresh-session retry.+--+-- No foreign keys (repo rule): workspace teardown (DeleteTaskBatch and the+-- workspace leaf sweep) and issue deletion remove these rows in application+-- code. issue_id is copied from the task so issue deletion can find them+-- after the legacy issue -> agent_task_queue cascade has run.+CREATE TABLE IF NOT EXISTS task_context_receipt (+ task_id UUID PRIMARY KEY,+ workspace_id UUID NOT NULL,+ issue_id UUID,+ receipt JSONB NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/650_task_context_receipt_workspace_idx.down.sql b/server/migrations/650_task_context_receipt_workspace_idx.down.sqlnew file mode 100644index 0000000000..46dba84988--- /dev/null+++ b/server/migrations/650_task_context_receipt_workspace_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_task_context_receipt_workspace;diff --git a/server/migrations/650_task_context_receipt_workspace_idx.up.sql b/server/migrations/650_task_context_receipt_workspace_idx.up.sqlnew file mode 100644index 0000000000..7ac150271b--- /dev/null+++ b/server/migrations/650_task_context_receipt_workspace_idx.up.sql@@ -0,0 +1,3 @@+-- Serves the workspace teardown sweep of task_context_receipt.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_context_receipt_workspace+ ON task_context_receipt (workspace_id);diff --git a/server/migrations/651_task_context_receipt_issue_idx.down.sql b/server/migrations/651_task_context_receipt_issue_idx.down.sqlnew file mode 100644index 0000000000..71b153ab08--- /dev/null+++ b/server/migrations/651_task_context_receipt_issue_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_task_context_receipt_issue;diff --git a/server/migrations/651_task_context_receipt_issue_idx.up.sql b/server/migrations/651_task_context_receipt_issue_idx.up.sqlnew file mode 100644index 0000000000..a2cf8f03a4--- /dev/null+++ b/server/migrations/651_task_context_receipt_issue_idx.up.sql@@ -0,0 +1,3 @@+-- Serves issue deletion's sweep of task_context_receipt.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_context_receipt_issue+ ON task_context_receipt (issue_id) WHERE issue_id IS NOT NULL;diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex f858398ba7..1e383d5632 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -531,6 +531,9 @@ cleared_environment_commands AS (),cleared_environment_configs AS (DELETE FROM issue_environment_config WHERE issue_id IN (SELECT target.id FROM target)+),+cleared_task_context_receipts AS (+ DELETE FROM task_context_receipt WHERE issue_id IN (SELECT target.id FROM target))DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target)`@@ -556,6 +559,8 @@ type DeleteIssueParams struct {// when a caller passes a foreign issue_id with its own workspace_id (the issue// itself is correctly untouched, but the links are already gone) — the exact// cross-tenant leak the #1661 guard above exists to prevent.+// task_context_receipt has no FK; the issue's tasks go by the legacy cascade,+// so their receipts are swept here by the issue_id copied onto each row.func (q *Queries) DeleteIssue(ctx context.Context, arg DeleteIssueParams) error {_, err := q.db.Exec(ctx, deleteIssue, arg.ID, arg.WorkspaceID)return errdiff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex b14cc6fe77..c5d83b96b0 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1721,6 +1721,15 @@ type SysCronExecution struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`}+type TaskContextReceipt struct {+ TaskID pgtype.UUID `json:"task_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ Receipt []byte `json:"receipt"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type TaskMessage struct {ID pgtype.UUID `json:"id"`TaskID pgtype.UUID `json:"task_id"`diff --git a/server/pkg/db/generated/task_context_receipt.sql.go b/server/pkg/db/generated/task_context_receipt.sql.gonew file mode 100644index 0000000000..92245d9a0e--- /dev/null+++ b/server/pkg/db/generated/task_context_receipt.sql.go@@ -0,0 +1,66 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: task_context_receipt.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const getTaskContextReceipt = `-- name: GetTaskContextReceipt :one+SELECT task_id, workspace_id, receipt, created_at, updated_at+FROM task_context_receipt+WHERE task_id = $1+`++type GetTaskContextReceiptRow struct {+ TaskID pgtype.UUID `json:"task_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Receipt []byte `json:"receipt"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++func (q *Queries) GetTaskContextReceipt(ctx context.Context, taskID pgtype.UUID) (GetTaskContextReceiptRow, error) {+ row := q.db.QueryRow(ctx, getTaskContextReceipt, taskID)+ var i GetTaskContextReceiptRow+ err := row.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.Receipt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const upsertTaskContextReceipt = `-- name: UpsertTaskContextReceipt :exec+INSERT INTO task_context_receipt (task_id, workspace_id, issue_id, receipt)+VALUES ($1, $2, $3, $4)+ON CONFLICT (task_id) DO UPDATE+SET receipt = EXCLUDED.receipt,+ updated_at = now()+`++type UpsertTaskContextReceiptParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ Receipt []byte `json:"receipt"`+}++// One receipt per task (MUL-9013). A re-report for the same task — the+// fresh-session retry after a rejected resume — replaces the first.+func (q *Queries) UpsertTaskContextReceipt(ctx context.Context, arg UpsertTaskContextReceiptParams) error {+ _, err := q.db.Exec(ctx, upsertTaskContextReceipt,+ arg.TaskID,+ arg.WorkspaceID,+ arg.IssueID,+ arg.Receipt,+ )+ return err+}diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex 52e0b52993..c3b49c9d38 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -42,6 +42,9 @@ deleted_channel_task_deliveries AS (),deleted_draft_restores AS (DELETE FROM chat_draft_restore WHERE task_id IN (SELECT id FROM batch)+),+deleted_task_context_receipts AS (+ DELETE FROM task_context_receipt WHERE task_id IN (SELECT id FROM batch))DELETE FROM agent_task_queue WHERE id IN (SELECT id FROM batch)`@@ -316,6 +319,9 @@ deleted_orphan_task_supplements AS (deleted_orphan_task_supplement_capabilities AS (DELETE FROM task_supplement_capability WHERE workspace_id = $1),+deleted_orphan_task_context_receipts AS (+ DELETE FROM task_context_receipt WHERE workspace_id = $1+),deleted_hourly_dirty AS (DELETE FROM task_usage_hourly_dirty WHERE workspace_id = $1),diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 87f46279c0..4a1a3205d6 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -516,6 +516,11 @@ cleared_environment_commands AS (),cleared_environment_configs AS (DELETE FROM issue_environment_config WHERE issue_id IN (SELECT target.id FROM target)+),+-- task_context_receipt has no FK; the issue's tasks go by the legacy cascade,+-- so their receipts are swept here by the issue_id copied onto each row.+cleared_task_context_receipts AS (+ DELETE FROM task_context_receipt WHERE issue_id IN (SELECT target.id FROM target))DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target);diff --git a/server/pkg/db/queries/task_context_receipt.sql b/server/pkg/db/queries/task_context_receipt.sqlnew file mode 100644index 0000000000..075b2bf804--- /dev/null+++ b/server/pkg/db/queries/task_context_receipt.sql@@ -0,0 +1,13 @@+-- name: UpsertTaskContextReceipt :exec+-- One receipt per task (MUL-9013). A re-report for the same task — the+-- fresh-session retry after a rejected resume — replaces the first.+INSERT INTO task_context_receipt (task_id, workspace_id, issue_id, receipt)+VALUES (@task_id, @workspace_id, sqlc.narg(issue_id), @receipt)+ON CONFLICT (task_id) DO UPDATE+SET receipt = EXCLUDED.receipt,+ updated_at = now();++-- name: GetTaskContextReceipt :one+SELECT task_id, workspace_id, receipt, created_at, updated_at+FROM task_context_receipt+WHERE task_id = $1;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 8eac4ad6ee..6ace374cee 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -229,6 +229,9 @@ deleted_channel_task_deliveries AS (),deleted_draft_restores AS (DELETE FROM chat_draft_restore WHERE task_id IN (SELECT id FROM batch)+),+deleted_task_context_receipts AS (+ DELETE FROM task_context_receipt WHERE task_id IN (SELECT id FROM batch))DELETE FROM agent_task_queue WHERE id IN (SELECT id FROM batch);@@ -323,6 +326,9 @@ deleted_orphan_task_supplements AS (deleted_orphan_task_supplement_capabilities AS (DELETE FROM task_supplement_capability WHERE workspace_id = $1),+deleted_orphan_task_context_receipts AS (+ DELETE FROM task_context_receipt WHERE workspace_id = $1+),deleted_hourly_dirty AS (DELETE FROM task_usage_hourly_dirty WHERE workspace_id = $1),