Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(issues): per-issue metadata KV (MUL-2017) (#2845)
Bohan Jiang0c767c00525c
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 8524af28d6..93f3ae29bd 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -328,7 +328,14 @@ multica issue list --full-idmultica issue list --limit 20 --output json```-Table output shows a routable issue `KEY` such as `MUL-123`; copy that key into follow-up commands like `issue get`, `issue comment list`, `issue status`, or `--parent`. Add `--full-id` when you need canonical UUIDs. Available filters: `--status`, `--priority`, `--assignee` / `--assignee-id`, `--project`, `--limit`. Use `--assignee-id <uuid>` for unambiguous filtering when names overlap.+Table output shows a routable issue `KEY` such as `MUL-123`; copy that key into follow-up commands like `issue get`, `issue comment list`, `issue status`, or `--parent`. Add `--full-id` when you need canonical UUIDs. Available filters: `--status`, `--priority`, `--assignee` / `--assignee-id`, `--project`, `--metadata`, `--limit`. Use `--assignee-id <uuid>` for unambiguous filtering when names overlap.++Use `--metadata key=value` (repeatable; combined with AND) to filter by per-issue metadata. The value is JSON-parsed: `true`/`false` become bool, numbers become numbers, anything else is a string. Wrap as `'"42"'` to force a string when the value would otherwise sniff as a number:++```bash+multica issue list --metadata pipeline_status=waiting_review+multica issue list --metadata pr_number=482 --metadata is_blocked=true+```### Get Issue@@ -444,6 +451,33 @@ hand back root-only pages until the caller reaches the start of thethread / issue. Incremental polling stops at the first page whosecursor target falls before the watermark.+### Metadata++Per-issue metadata is a small KV map agents use to track pipeline state (PR number, pipeline status, waiting_on, ...). Keys match `^[a-zA-Z_][a-zA-Z0-9_.-]{0,63}$`, values are primitives (string / number / bool), max 50 keys per issue, blob capped at 8KB.++Don't pin runtime bookkeeping like `attempts`, large logs, secrets/tokens, or description/comment copies — see the agent runtime prompt for the full anti-pattern list.++```bash+# List every key on an issue+multica issue metadata list <issue-id>++# Read a single key+multica issue metadata get <issue-id> --key pipeline_status++# Write a single key — value auto-typed (true/false → bool, numbers → number, else string)+multica issue metadata set <issue-id> --key pipeline_status --value waiting_review+multica issue metadata set <issue-id> --key pr_number --value 482+multica issue metadata set <issue-id> --key is_blocked --value true++# Force a specific type when sniffing would pick the wrong one+multica issue metadata set <issue-id> --key code --value 42 --type string++# Remove a key+multica issue metadata delete <issue-id> --key pipeline_status+```++All writes are single-key atomic — concurrent agents writing different keys do not lose each other's updates. To query, use `multica issue list --metadata key=value` (see *List Issues* above).+### Subscribers```bashdiff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex fb2821864e..49aab78b5c 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -501,6 +501,9 @@ export class ApiClient {if (params?.creator_id) search.set("creator_id", params.creator_id);if (params?.project_id) search.set("project_id", params.project_id);if (params?.involves_user_id) search.set("involves_user_id", params.involves_user_id);+ if (params?.metadata && Object.keys(params.metadata).length > 0) {+ search.set("metadata", JSON.stringify(params.metadata));+ }if (params?.open_only) search.set("open_only", "true");if (params?.scheduled) search.set("scheduled", "true");const path = `/api/issues?${search}`;@@ -523,6 +526,9 @@ export class ApiClient {if (params.creator_id) search.set("creator_id", params.creator_id);if (params.project_id) search.set("project_id", params.project_id);if (params.involves_user_id) search.set("involves_user_id", params.involves_user_id);+ if (params.metadata && Object.keys(params.metadata).length > 0) {+ search.set("metadata", JSON.stringify(params.metadata));+ }if (params.assignee_filters?.length) {search.set("assignee_filters", params.assignee_filters.map((f) => `${f.type}:${f.id}`).join(","));}diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 7a0e254b17..5837796c19 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -5,6 +5,7 @@ import {DashboardUsageDailyListSchema,DuplicateIssueErrorBodySchema,EMPTY_USER,+ ListIssuesResponseSchema,RuntimeHourlyActivityListSchema,RuntimeUsageByAgentListSchema,RuntimeUsageByHourListSchema,@@ -13,6 +14,64 @@ import {} from "./schemas";import { parseWithFallback } from "./schema";+const baseIssue = {+ id: "11111111-1111-1111-1111-111111111111",+ workspace_id: "ws-1",+ number: 1,+ identifier: "MUL-1",+ title: "Test",+ description: null,+ status: "todo",+ priority: "medium",+ assignee_type: null,+ assignee_id: null,+ creator_type: "member",+ creator_id: "user-1",+ parent_issue_id: null,+ project_id: null,+ position: 0,+ start_date: null,+ due_date: null,+ metadata: {},+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+};++describe("IssueSchema (via ListIssuesResponseSchema)", () => {+ it("accepts a primitive metadata KV map", () => {+ const payload = {+ issues: [+ {+ ...baseIssue,+ metadata: { pipeline_status: "waiting", pr_number: 3, is_blocked: true },+ },+ ],+ total: 1,+ };+ const parsed = ListIssuesResponseSchema.parse(payload);+ expect(parsed.issues[0]?.metadata).toEqual({+ pipeline_status: "waiting",+ pr_number: 3,+ is_blocked: true,+ });+ });++ it("defaults metadata to {} when the server omits it (older backend)", () => {+ const { metadata: _omit, ...issueWithoutMetadata } = baseIssue;+ const payload = { issues: [issueWithoutMetadata], total: 1 };+ const parsed = ListIssuesResponseSchema.parse(payload);+ expect(parsed.issues[0]?.metadata).toEqual({});+ });++ it("rejects metadata with non-primitive values (nested object)", () => {+ const payload = {+ issues: [{ ...baseIssue, metadata: { nested: { x: 1 } } }],+ total: 1,+ };+ expect(ListIssuesResponseSchema.safeParse(payload).success).toBe(false);+ });+});+// The duplicate-issue branch in create-issue.tsx feeds ApiError.body// (typed as `unknown`) through this schema. Any future server drift that// loses the contract MUST fail the parse so the UI falls back to a normaldiff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex b73e1a0e95..8efb8dbd1b 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -136,6 +136,11 @@ export const CommentSchema = z.object({export const CommentsListSchema = z.array(CommentSchema);+// Metadata is primitive-only by API/DB contract. Stay lenient on shape:+// unknown keys land as `unknown` to a caller, but the field itself defaults+// to {} so consumers never need to nil-guard `issue.metadata`.+const IssueMetadataSchema = z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({});+const IssueSchema = z.object({id: z.string(),workspace_id: z.string(),@@ -154,6 +159,7 @@ const IssueSchema = z.object({position: z.number(),start_date: z.string().nullable(),due_date: z.string().nullable(),+ metadata: IssueMetadataSchema,reactions: z.array(z.unknown()).optional(),labels: z.array(z.unknown()).optional(),created_at: z.string(),diff --git a/packages/core/issues/queries.test.ts b/packages/core/issues/queries.test.tsindex 465deef714..6388aba834 100644--- a/packages/core/issues/queries.test.ts+++ b/packages/core/issues/queries.test.ts@@ -34,6 +34,7 @@ function makeIssue(idx: number): Issue {start_date: "2026-05-01T00:00:00Z",due_date: null,labels: [],+ metadata: {},created_at: "2025-01-01T00:00:00Z",updated_at: "2025-01-01T00:00:00Z",};diff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.tsindex a56c7af456..b9381d177f 100644--- a/packages/core/issues/ws-updaters.test.ts+++ b/packages/core/issues/ws-updaters.test.ts@@ -10,6 +10,7 @@ import {onIssueCreated,onIssueDeleted,onIssueLabelsChanged,+ onIssueMetadataChanged,onIssueUpdated,} from "./ws-updaters";import { issueKeys } from "./queries";@@ -71,6 +72,7 @@ const baseIssue: Issue = {position: 0,start_date: null,due_date: null,+ metadata: {},labels: [labelA],created_at: "2025-01-01T00:00:00Z",updated_at: "2025-01-01T00:00:00Z",@@ -177,6 +179,43 @@ describe("onIssueLabelsChanged", () => {});});+describe("onIssueMetadataChanged", () => {+ let qc: QueryClient;++ beforeEach(() => {+ qc = new QueryClient();+ });++ it("replaces metadata in both detail and list caches (no merge)", () => {+ qc.setQueryData<Issue>(issueKeys.detail(WS_ID, ISSUE_ID), {+ ...baseIssue,+ metadata: { pr_number: 1, stale: "yes" },+ });+ qc.setQueryData<ListIssuesCache>(issueKeys.list(WS_ID), {+ byStatus: {+ todo: {+ issues: [{ ...baseIssue, metadata: { pr_number: 1 } }],+ total: 1,+ },+ },+ });++ onIssueMetadataChanged(qc, WS_ID, ISSUE_ID, { pr_number: 2 });++ const detail = qc.getQueryData<Issue>(issueKeys.detail(WS_ID, ISSUE_ID));+ expect(detail?.metadata).toEqual({ pr_number: 2 });+ const list = qc.getQueryData<ListIssuesCache>(issueKeys.list(WS_ID));+ expect(list?.byStatus.todo?.issues[0]?.metadata).toEqual({ pr_number: 2 });+ });++ it("leaves untouched caches as undefined (no spurious writes)", () => {+ onIssueMetadataChanged(qc, WS_ID, ISSUE_ID, { foo: "bar" });++ expect(qc.getQueryData(issueKeys.detail(WS_ID, ISSUE_ID))).toBeUndefined();+ expect(qc.getQueryData(issueKeys.list(WS_ID))).toBeUndefined();+ });+});+describe("onIssueDeleted", () => {let qc: QueryClient;diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.tsindex cac7f90551..afc837234b 100644--- a/packages/core/issues/ws-updaters.ts+++ b/packages/core/issues/ws-updaters.ts@@ -7,7 +7,7 @@ import {patchIssueInBuckets,} from "./cache-helpers";import { cleanupDeletedIssueCaches } from "./delete-cache";-import type { Issue, IssueLabelsResponse, Label } from "../types";+import type { Issue, IssueLabelsResponse, IssueMetadata, Label } from "../types";import type { ListIssuesCache } from "../types";export function onIssueCreated(@@ -133,6 +133,30 @@ export function onIssueLabelsChanged(qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });}+/**+ * Apply a metadata snapshot to the issue detail + list + my-issues caches.+ * The server emits this whenever a single key is set or deleted, so the+ * payload is always the FULL post-mutation map — we replace, not merge.+ *+ * Used for the read-only metadata strip in issue detail. Updates that arrive+ * while no view is mounted still keep the caches accurate so the next render+ * shows the latest state without a refetch.+ */+export function onIssueMetadataChanged(+ qc: QueryClient,+ wsId: string,+ issueId: string,+ metadata: IssueMetadata,+) {+ qc.setQueryData<ListIssuesCache>(issueKeys.list(wsId), (old) =>+ old ? patchIssueInBuckets(old, issueId, { metadata }) : old,+ );+ qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>+ old ? { ...old, metadata } : old,+ );+ qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });+}+export function onIssueDeleted(qc: QueryClient,wsId: string,diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 4f18bde111..91a5165b0e 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -26,6 +26,7 @@ import {onIssueUpdated,onIssueDeleted,onIssueLabelsChanged,+ onIssueMetadataChanged,} from "../issues/ws-updaters";import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted } from "../inbox/ws-updaters";import { inboxKeys } from "../inbox/queries";@@ -44,6 +45,7 @@ import type {IssueCreatedPayload,IssueDeletedPayload,IssueLabelsChangedPayload,+ IssueMetadataChangedPayload,InboxNewPayload,CommentCreatedPayload,CommentUpdatedPayload,@@ -341,7 +343,7 @@ export function useRealtimeSync(// Event types handled by specific handlers below -- skip generic refreshconst specificEvents = new Set(["workspace:updated",- "issue:updated", "issue:created", "issue:deleted", "issue_labels:changed", "inbox:new",+ "issue:updated", "issue:created", "issue:deleted", "issue_labels:changed", "issue_metadata:changed", "inbox:new","comment:created", "comment:updated", "comment:deleted","comment:resolved", "comment:unresolved","activity:created",@@ -412,6 +414,13 @@ export function useRealtimeSync(if (wsId) onIssueLabelsChanged(qc, wsId, issue_id, labels ?? []);});+ const unsubIssueMetadataChanged = ws.on("issue_metadata:changed", (p) => {+ const { issue_id, metadata } = p as IssueMetadataChangedPayload;+ if (!issue_id) return;+ const wsId = getCurrentWsId();+ if (wsId) onIssueMetadataChanged(qc, wsId, issue_id, metadata ?? {});+ });+const unsubInboxNew = ws.on("inbox:new", async (p) => {const { item } = p as InboxNewPayload;if (!item) return;@@ -878,6 +887,7 @@ export function useRealtimeSync(unsubIssueCreated();unsubIssueDeleted();unsubIssueLabelsChanged();+ unsubIssueMetadataChanged();unsubInboxNew();unsubCommentCreated();unsubCommentUpdated();diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 9ca1f1c01d..3daa98845f 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -1,4 +1,4 @@-import type { Issue, IssueStatus, IssuePriority, IssueAssigneeType } from "./issue";+import type { Issue, IssueMetadata, IssueStatus, IssuePriority, IssueAssigneeType } from "./issue";import type { MemberRole } from "./workspace";import type { Project } from "./project";@@ -54,6 +54,8 @@ export interface ListIssuesParams {* disjoint result sets by construction.*/involves_user_id?: string;+ /** JSONB containment filter on `issue.metadata`. AND across keys. */+ metadata?: IssueMetadata;open_only?: boolean;/*** Restrict the result to issues with at least one of `start_date` /@@ -83,6 +85,8 @@ export interface ListGroupedIssuesParams {project_id?: string;/** See `ListIssuesParams.involves_user_id` — same semantics. */involves_user_id?: string;+ /** JSONB containment filter on `issue.metadata`. AND across keys. */+ metadata?: IssueMetadata;assignee_filters?: IssueActorRef[];include_no_assignee?: boolean;creator_filters?: IssueActorRef[];diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex a8a1458bca..62165ae16f 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -1,4 +1,4 @@-import type { Issue, IssueReaction } from "./issue";+import type { Issue, IssueMetadata, IssueReaction } from "./issue";import type { Agent } from "./agent";import type { InboxItem } from "./inbox";import type { Comment, Reaction } from "./comment";@@ -65,6 +65,7 @@ export type WSEventType =| "label:updated"| "label:deleted"| "issue_labels:changed"+ | "issue_metadata:changed"| "pin:created"| "pin:deleted"| "pin:reordered"@@ -102,6 +103,11 @@ export interface IssueLabelsChangedPayload {labels: Label[];}+export interface IssueMetadataChangedPayload {+ issue_id: string;+ metadata: IssueMetadata;+}+export interface AgentStatusPayload {agent: Agent;}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex a5fa932c44..2612ffefbf 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -1,4 +1,4 @@-export type { Issue, IssueStatus, IssuePriority, IssueAssigneeType, IssueReaction } from "./issue";+export type { Issue, IssueStatus, IssuePriority, IssueAssigneeType, IssueMetadata, IssueMetadataValue, IssueReaction } from "./issue";export type {Agent,AgentStatus,diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.tsindex 9affab9820..1a8ab9bb76 100644--- a/packages/core/types/issue.ts+++ b/packages/core/types/issue.ts@@ -22,6 +22,16 @@ export interface IssueReaction {created_at: string;}+/**+ * Per-issue metadata is a flat KV map agents use to record pipeline state+ * (PR number, pipeline_status, waiting_on, ...). Values are primitives only —+ * string / number / bool — enforced by both the API and the DB. Always+ * present in responses (empty object when unset) so reads don't need a+ * nil guard on the parent field.+ */+export type IssueMetadataValue = string | number | boolean;+export type IssueMetadata = Record<string, IssueMetadataValue>;+export interface Issue {id: string;workspace_id: string;@@ -40,6 +50,7 @@ export interface Issue {position: number;start_date: string | null;due_date: string | null;+ metadata: IssueMetadata;reactions?: IssueReaction[];labels?: Label[];created_at: string;diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex dd94abc89b..0813f1442e 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -405,6 +405,7 @@ const mockIssue: Issue = {position: 0,start_date: null,due_date: "2026-06-01T00:00:00Z",+ metadata: {},created_at: "2026-01-15T00:00:00Z",updated_at: "2026-01-20T00:00:00Z",};diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex c2558d79f9..28c28c67dd 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -651,6 +651,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trconst [detailsOpen, setDetailsOpen] = useState(true);const [parentIssueOpen, setParentIssueOpen] = useState(true);const [pullRequestsOpen, setPullRequestsOpen] = useState(true);+ const [metadataOpen, setMetadataOpen] = useState(true);const [tokenUsageOpen, setTokenUsageOpen] = useState(true);const githubSettings = useGitHubSettings();@@ -1385,6 +1386,33 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr</div>)}+ {/* Metadata — read-only KV strip. Agents write via the CLI / metadata+ API; UI editing is intentionally not in V1. Section hides itself+ when the issue has no keys to keep the sidebar quiet for the+ common case where metadata is never set. */}+ {Object.keys(issue.metadata ?? {}).length > 0 && (+ <div>+ <button+ className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors mb-2 hover:bg-accent/70 ${metadataOpen ? "" : "text-muted-foreground hover:text-foreground"}`}+ onClick={() => setMetadataOpen(!metadataOpen)}+ >+ {t(($) => $.detail.section_metadata)}+ <ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${metadataOpen ? "rotate-90" : ""}`} />+ </button>+ {metadataOpen && (+ <div className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 pl-2">+ {Object.entries(issue.metadata).map(([k, v]) => (+ <PropRow key={k} label={k} interactive={false}>+ <span className="truncate text-muted-foreground">+ {typeof v === "boolean" ? (v ? "true" : "false") : String(v)}+ </span>+ </PropRow>+ ))}+ </div>+ )}+ </div>+ )}+{/* Details */}<div><buttondiff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsxindex 17f92db580..4719955045 100644--- a/packages/views/issues/components/issues-page.test.tsx+++ b/packages/views/issues/components/issues-page.test.tsx@@ -337,6 +337,7 @@ const issueDefaults = {parent_issue_id: null,project_id: null,position: 0,+ metadata: {},};const mockIssues: Issue[] = [diff --git a/packages/views/issues/hooks/issue-delete-mutations.test.tsx b/packages/views/issues/hooks/issue-delete-mutations.test.tsxindex 5b4f58965b..d5587f3151 100644--- a/packages/views/issues/hooks/issue-delete-mutations.test.tsx+++ b/packages/views/issues/hooks/issue-delete-mutations.test.tsx@@ -62,6 +62,7 @@ const baseIssue: Issue = {position: 0,start_date: null,due_date: null,+ metadata: {},labels: [],created_at: "2026-01-01T00:00:00Z",updated_at: "2026-01-01T00:00:00Z",diff --git a/packages/views/issues/utils/filter.test.ts b/packages/views/issues/utils/filter.test.tsindex 5a2ef0c8ce..4f09b6b25d 100644--- a/packages/views/issues/utils/filter.test.ts+++ b/packages/views/issues/utils/filter.test.ts@@ -32,6 +32,7 @@ function makeIssue(overrides: Partial<Issue> = {}): Issue {position: 0,start_date: null,due_date: null,+ metadata: {},created_at: "2025-01-01T00:00:00Z",updated_at: "2025-01-01T00:00:00Z",...overrides,diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 188b25407c..eafeeaa55b 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -142,6 +142,7 @@"section_properties": "Properties","section_parent_issue": "Parent issue","section_pull_requests": "Pull requests",+ "section_metadata": "Metadata","section_details": "Details","section_token_usage": "Token usage","pull_requests_loading": "Loading…",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex b409a78240..67dae78ac3 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -141,6 +141,7 @@"section_properties": "属性","section_parent_issue": "父 issue","section_pull_requests": "Pull Request",+ "section_metadata": "元数据","section_details": "详情","section_token_usage": "Token 用量","pull_requests_loading": "加载中…",diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 2210b1a6cf..0c732a26b3 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -259,6 +259,7 @@ func init() {issueListCmd.Flags().String("assignee", "", "Filter by assignee name (member, agent, or squad; fuzzy match)")issueListCmd.Flags().String("assignee-id", "", "Filter by assignee UUID — member, agent, or squad (mutually exclusive with --assignee)")issueListCmd.Flags().String("project", "", "Filter by project ID")+ issueListCmd.Flags().StringSlice("metadata", nil, "Filter by metadata key=value (repeatable; combined with AND). Value is JSON-parsed: 'true'/'false' → bool, numbers → number, otherwise string. Wrap as '\"42\"' to force a string when the value would otherwise sniff as a number.")issueListCmd.Flags().Int("limit", 50, "Maximum number of issues to return")issueListCmd.Flags().Int("offset", 0, "Number of issues to skip (for pagination)")@@ -403,6 +404,13 @@ func runIssueList(cmd *cobra.Command, _ []string) error {}params.Set("project_id", project.ID)}+ if mdFlags, _ := cmd.Flags().GetStringSlice("metadata"); len(mdFlags) > 0 {+ filter, err := buildMetadataFilterQueryParam(mdFlags)+ if err != nil {+ return err+ }+ params.Set("metadata", filter)+ }path := "/api/issues"if len(params) > 0 {diff --git a/server/cmd/multica/cmd_issue_metadata.go b/server/cmd/multica/cmd_issue_metadata.gonew file mode 100644index 0000000000..d9fc69ece7--- /dev/null+++ b/server/cmd/multica/cmd_issue_metadata.go@@ -0,0 +1,362 @@+package main++import (+ "context"+ "encoding/json"+ "fmt"+ "os"+ "sort"+ "strconv"+ "strings"+ "time"++ "github.com/spf13/cobra"++ "github.com/multica-ai/multica/server/internal/cli"+)++// buildMetadataFilterQueryParam converts repeated `--metadata key=value`+// flags into the canonical JSON object passed as the `metadata` query+// parameter to /api/issues. Values are typed by the same rules as+// `metadata set --value` without --type — JSON-parsed when possible, else+// taken as a literal string. Duplicate keys are rejected; AND semantics+// require distinct keys.+func buildMetadataFilterQueryParam(pairs []string) (string, error) {+ if len(pairs) == 0 {+ return "", nil+ }+ out := make(map[string]any, len(pairs))+ for _, pair := range pairs {+ idx := strings.IndexByte(pair, '=')+ if idx <= 0 {+ return "", fmt.Errorf("--metadata %q must be in key=value form", pair)+ }+ key := pair[:idx]+ raw := pair[idx+1:]+ if _, dup := out[key]; dup {+ return "", fmt.Errorf("--metadata key %q given more than once; combine into a single filter", key)+ }+ encoded, err := parseMetadataValue(raw, "")+ if err != nil {+ return "", fmt.Errorf("--metadata %s: %w", key, err)+ }+ var v any+ if err := json.Unmarshal(encoded, &v); err != nil {+ return "", fmt.Errorf("--metadata %s: encode value: %w", key, err)+ }+ out[key] = v+ }+ buf, err := json.Marshal(out)+ if err != nil {+ return "", fmt.Errorf("encode metadata filter: %w", err)+ }+ return string(buf), nil+}++// multica issue metadata {list|get|set|delete} — KV map attached to each issue+// for agent pipeline state. See server/internal/handler/issue_metadata.go for+// the constraints (key regex, 50-key cap, primitive-only values, 8KB blob).++var issueMetadataCmd = &cobra.Command{+ Use: "metadata",+ Short: "Manage per-issue metadata (KV)",+}++var issueMetadataListCmd = &cobra.Command{+ Use: "list <issue-id>",+ Short: "List all metadata keys on an issue",+ Args: exactArgs(1),+ RunE: runIssueMetadataList,+}++var issueMetadataGetCmd = &cobra.Command{+ Use: "get <issue-id>",+ Short: "Get a single metadata key value",+ Args: exactArgs(1),+ RunE: runIssueMetadataGet,+}++var issueMetadataSetCmd = &cobra.Command{+ Use: "set <issue-id>",+ Short: "Set a single metadata key value",+ Long: `Set a single metadata key value. The value is JSON-parsed by default:+ --value true / --value false → bool+ --value 3 / --value 3.14 → number+ --value waiting → string+Use --type to force a specific type. Quote like '"42"' (JSON-escaped) to force+a string when the bare value would otherwise sniff as a number or bool.`,+ Args: exactArgs(1),+ RunE: runIssueMetadataSet,+}++var issueMetadataDeleteCmd = &cobra.Command{+ Use: "delete <issue-id>",+ Short: "Delete a single metadata key",+ Args: exactArgs(1),+ RunE: runIssueMetadataDelete,+}++func init() {+ issueMetadataCmd.AddCommand(issueMetadataListCmd)+ issueMetadataCmd.AddCommand(issueMetadataGetCmd)+ issueMetadataCmd.AddCommand(issueMetadataSetCmd)+ issueMetadataCmd.AddCommand(issueMetadataDeleteCmd)++ issueMetadataListCmd.Flags().String("output", "table", "Output format: table or json")+ issueMetadataGetCmd.Flags().String("output", "json", "Output format: table or json")+ issueMetadataGetCmd.Flags().String("key", "", "Metadata key (required)")+ issueMetadataSetCmd.Flags().String("output", "table", "Output format: table or json")+ issueMetadataSetCmd.Flags().String("key", "", "Metadata key (required)")+ issueMetadataSetCmd.Flags().String("value", "", "Metadata value (required)")+ issueMetadataSetCmd.Flags().String("type", "", "Force value type: string, number, or bool (default: auto-infer via JSON parsing)")+ issueMetadataDeleteCmd.Flags().String("output", "table", "Output format: table or json")+ issueMetadataDeleteCmd.Flags().String("key", "", "Metadata key (required)")++ issueCmd.AddCommand(issueMetadataCmd)+}++// parseMetadataValue converts a CLI --value flag (and optional --type) into+// the JSON-encoded payload sent to the server. Default sniffing: if the+// raw text parses as a JSON bool / number / string, that type is used; any+// other JSON shape (null, array, object) is rejected even under default+// because the server would reject it too.+//+// forcedType non-empty overrides sniffing: "string" wraps verbatim as a+// JSON string; "number" parses strictly as a number; "bool" requires the+// literal text "true" or "false".+func parseMetadataValue(raw, forcedType string) (json.RawMessage, error) {+ switch forcedType {+ case "string":+ buf, err := json.Marshal(raw)+ if err != nil {+ return nil, fmt.Errorf("encode string value: %w", err)+ }+ return buf, nil+ case "number":+ if _, err := strconv.ParseFloat(raw, 64); err != nil {+ return nil, fmt.Errorf("value %q is not a valid number", raw)+ }+ return json.RawMessage(raw), nil+ case "bool":+ if raw != "true" && raw != "false" {+ return nil, fmt.Errorf("value %q is not a valid bool (expected true or false)", raw)+ }+ return json.RawMessage(raw), nil+ case "":+ // auto-infer below+ default:+ return nil, fmt.Errorf("unknown --type %q (expected string, number, or bool)", forcedType)+ }++ // Auto-infer: try JSON parse, fall back to string.+ var v any+ if err := json.Unmarshal([]byte(raw), &v); err == nil {+ switch v.(type) {+ case string, bool, float64:+ return json.RawMessage(raw), nil+ }+ }+ buf, err := json.Marshal(raw)+ if err != nil {+ return nil, fmt.Errorf("encode string value: %w", err)+ }+ return buf, nil+}++func runIssueMetadataList(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ issueRef, err := resolveIssueRef(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve issue: %w", err)+ }++ var result map[string]any+ if err := client.GetJSON(ctx, "/api/issues/"+issueRef.ID+"/metadata", &result); err != nil {+ return fmt.Errorf("list metadata: %w", err)+ }+ metadata, _ := result["metadata"].(map[string]any)+ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, metadata)+ }+ printMetadataTable(metadata)+ return nil+}++func runIssueMetadataGet(cmd *cobra.Command, args []string) error {+ key, _ := cmd.Flags().GetString("key")+ if key == "" {+ return fmt.Errorf("--key is required")+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ issueRef, err := resolveIssueRef(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve issue: %w", err)+ }++ var result map[string]any+ if err := client.GetJSON(ctx, "/api/issues/"+issueRef.ID+"/metadata", &result); err != nil {+ return fmt.Errorf("get metadata: %w", err)+ }+ metadata, _ := result["metadata"].(map[string]any)+ value, present := metadata[key]+ if !present {+ return fmt.Errorf("key %q not found on issue", key)+ }++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, value)+ }+ headers := []string{"KEY", "VALUE", "TYPE"}+ rows := [][]string{{key, formatMetadataValue(value), metadataValueType(value)}}+ cli.PrintTable(os.Stdout, headers, rows)+ return nil+}++func runIssueMetadataSet(cmd *cobra.Command, args []string) error {+ key, _ := cmd.Flags().GetString("key")+ if key == "" {+ return fmt.Errorf("--key is required")+ }+ if !cmd.Flags().Changed("value") {+ return fmt.Errorf("--value is required")+ }+ rawValue, _ := cmd.Flags().GetString("value")+ forcedType, _ := cmd.Flags().GetString("type")+ value, err := parseMetadataValue(rawValue, forcedType)+ if err != nil {+ return err+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ issueRef, err := resolveIssueRef(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve issue: %w", err)+ }++ body := map[string]any{"value": value}+ var result map[string]any+ path := "/api/issues/" + issueRef.ID + "/metadata/" + key+ if err := client.PutJSON(ctx, path, body, &result); err != nil {+ return fmt.Errorf("set metadata: %w", err)+ }+ metadata, _ := result["metadata"].(map[string]any)++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, metadata)+ }+ printMetadataTable(metadata)+ return nil+}++func runIssueMetadataDelete(cmd *cobra.Command, args []string) error {+ key, _ := cmd.Flags().GetString("key")+ if key == "" {+ return fmt.Errorf("--key is required")+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ issueRef, err := resolveIssueRef(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve issue: %w", err)+ }++ path := "/api/issues/" + issueRef.ID + "/metadata/" + key+ if err := client.DeleteJSON(ctx, path); err != nil {+ return fmt.Errorf("delete metadata: %w", err)+ }++ // Refresh the metadata so the user sees the result.+ var result map[string]any+ output, _ := cmd.Flags().GetString("output")+ if err := client.GetJSON(ctx, "/api/issues/"+issueRef.ID+"/metadata", &result); err != nil {+ if output == "json" {+ return cli.PrintJSON(os.Stdout, map[string]any{"deleted": true})+ }+ fmt.Fprintln(os.Stdout, "Key deleted.")+ return nil+ }+ metadata, _ := result["metadata"].(map[string]any)+ if output == "json" {+ return cli.PrintJSON(os.Stdout, metadata)+ }+ printMetadataTable(metadata)+ return nil+}++func printMetadataTable(metadata map[string]any) {+ headers := []string{"KEY", "VALUE", "TYPE"}+ keys := make([]string, 0, len(metadata))+ for k := range metadata {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ rows := make([][]string, 0, len(keys))+ for _, k := range keys {+ v := metadata[k]+ rows = append(rows, []string{k, formatMetadataValue(v), metadataValueType(v)})+ }+ cli.PrintTable(os.Stdout, headers, rows)+}++func formatMetadataValue(v any) string {+ switch x := v.(type) {+ case string:+ return x+ case bool:+ if x {+ return "true"+ }+ return "false"+ case float64:+ // JSON numbers come back as float64; render integers without a+ // trailing ".0" for ergonomics.+ if x == float64(int64(x)) {+ return strconv.FormatInt(int64(x), 10)+ }+ return strconv.FormatFloat(x, 'f', -1, 64)+ default:+ buf, _ := json.Marshal(v)+ return string(buf)+ }+}++func metadataValueType(v any) string {+ switch v.(type) {+ case string:+ return "string"+ case bool:+ return "bool"+ case float64:+ return "number"+ default:+ return "unknown"+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 2c8a7f2c02..4ff4e890b2 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -409,6 +409,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/labels", h.ListLabelsForIssue)r.Post("/labels", h.AttachLabel)r.Delete("/labels/{labelId}", h.DetachLabel)+ r.Get("/metadata", h.ListIssueMetadata)+ r.Put("/metadata/{key}", h.SetIssueMetadataKey)+ r.Delete("/metadata/{key}", h.DeleteIssueMetadataKey)r.Get("/pull-requests", h.ListPullRequestsForIssue)})})diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex b200edf11d..4a0816a914 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -3216,3 +3216,273 @@ func TestInjectRuntimeConfigAssignmentTriggerMentionsRecent(t *testing.T) {}}}++// TestInjectRuntimeConfigIssueMetadataSectionScope locks in MUL-2017:+// the `## Issue Metadata` section (semantic guide + recommended keys ++// pin/clear rules) and the `metadata list` workflow step are emitted only+// when the task carries a real issue id (comment-triggered or+// assignment-triggered). Chat / quick-create / run-only autopilot don't+// have an issue, so injecting the section there would just guarantee a+// failed CLI call on every entry. The discovery line in Available+// Commands → Core is global and must appear everywhere so that the agent+// can still reach the commands if a future workflow path needs them.+func TestInjectRuntimeConfigIssueMetadataSectionScope(t *testing.T) {+ t.Parallel()++ // Discovery lines in Available Commands → Core must appear in EVERY+ // runtime config, regardless of trigger type. These are the single+ // discovery point for the CLI when an agent decides to read or write+ // metadata outside the numbered workflow.+ coreDiscoveryLines := []string{+ "multica issue metadata list <issue-id>",+ "multica issue metadata set <issue-id> --key <k> --value <v> [--type string|number|bool]",+ "multica issue metadata delete <issue-id> --key <k>",+ }++ type wantSection struct {+ // sentinel substrings that MUST appear when the Issue Metadata+ // section is in scope+ present []string+ // substrings that MUST NOT appear (would mean the section leaked+ // into a context where there's no issue id to act on)+ absent []string+ }++ withSection := wantSection{+ present: []string{+ "## Issue Metadata",+ "high-signal scratchpad",+ "**Read on entry.**",+ "**Write on exit.**",+ "**What NOT to pin.**",+ "**Recommended keys**",+ // Recommended-key list — both lea's killer-use-case keys+ // (pr_number, pipeline_status) and the broader set from+ // review must be named so the workspace converges on shared+ // vocabulary.+ "pr_url",+ "pr_number",+ "pipeline_status",+ "deploy_url",+ "external_issue_url",+ "waiting_on",+ "blocked_reason",+ "decision",+ // Safety boundaries — these are the negative rules that+ // keep metadata from rotting into a second description /+ // log dump.+ "No secrets, tokens, or API keys",+ "No logs",+ "runtime bookkeeping",+ "snake_case ASCII",+ },+ }+ withoutSection := wantSection{+ // We can't simply require `multica issue metadata list` absent+ // because the Available Commands → Core discovery line is+ // global (it uses `<issue-id>` placeholder text). What MUST be+ // absent is the semantic section itself plus the workflow-step+ // pointer back to it.+ absent: []string{+ "## Issue Metadata",+ "high-signal scratchpad",+ "**Read on entry.**",+ "**Write on exit.**",+ "See the `## Issue Metadata` section above",+ },+ }++ cases := []struct {+ name string+ ctx TaskContextForEnv+ provider string+ filename string+ // workflowStepPresent is matched when the section is in scope —+ // each entry must appear in the workflow numbered list to prove+ // the metadata read step is wired in.+ workflowStepPresent []string+ // workflowAbsent is matched in non-issue contexts to guarantee+ // no metadata-list step leaked into a workflow that has no+ // issue id.+ workflowAbsent []string+ want wantSection+ }{+ {+ name: "comment_triggered",+ ctx: TaskContextForEnv{+ IssueID: "issue-md-1",+ TriggerCommentID: "comment-md-1",+ },+ provider: "claude",+ filename: "CLAUDE.md",+ workflowStepPresent: []string{+ "multica issue metadata list issue-md-1 --output json",+ "See the `## Issue Metadata` section above",+ // Exit step must show both write and delete, not just+ // "set" — stale-key cleanup is the half that keeps+ // metadata from rotting.+ "multica issue metadata set",+ "multica issue metadata delete",+ "Before exiting",+ },+ want: withSection,+ },+ {+ name: "assignment_triggered",+ ctx: TaskContextForEnv{IssueID: "issue-md-2"},+ provider: "claude",+ filename: "CLAUDE.md",+ workflowStepPresent: []string{+ "multica issue metadata list issue-md-2 --output json",+ "See the `## Issue Metadata` section above",+ "multica issue metadata set",+ "multica issue metadata delete",+ "Before exiting",+ },+ want: withSection,+ },+ {+ name: "quick_create_no_metadata_section",+ ctx: TaskContextForEnv{+ QuickCreatePrompt: "create a task about X",+ },+ provider: "codex",+ filename: "AGENTS.md",+ want: withoutSection,+ },+ {+ name: "run_only_autopilot_no_metadata_section",+ ctx: TaskContextForEnv{+ AutopilotRunID: "run-md-1",+ AutopilotID: "autopilot-md-1",+ },+ provider: "codex",+ filename: "AGENTS.md",+ want: withoutSection,+ },+ {+ name: "chat_no_metadata_section",+ ctx: TaskContextForEnv{+ ChatSessionID: "chat-md-1",+ },+ provider: "claude",+ filename: "CLAUDE.md",+ want: withoutSection,+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ dir := t.TempDir()+ if _, err := InjectRuntimeConfig(dir, tc.provider, tc.ctx); err != nil {+ t.Fatalf("InjectRuntimeConfig failed: %v", err)+ }+ data, err := os.ReadFile(filepath.Join(dir, tc.filename))+ if err != nil {+ t.Fatalf("read %s: %v", tc.filename, err)+ }+ s := string(data)++ // Global Core discovery lines apply everywhere.+ for _, want := range coreDiscoveryLines {+ if !strings.Contains(s, want) {+ t.Errorf("Available Commands → Core missing %q\n---\n%s", want, s)+ }+ }++ for _, want := range tc.want.present {+ if !strings.Contains(s, want) {+ t.Errorf("expected %q in %s output\n---\n%s", want, tc.name, s)+ }+ }+ for _, banned := range tc.want.absent {+ if strings.Contains(s, banned) {+ t.Errorf("%s output should NOT contain %q\n---\n%s", tc.name, banned, s)+ }+ }+ for _, want := range tc.workflowStepPresent {+ if !strings.Contains(s, want) {+ t.Errorf("workflow step missing %q in %s\n---\n%s", want, tc.name, s)+ }+ }+ for _, banned := range tc.workflowAbsent {+ if strings.Contains(s, banned) {+ t.Errorf("%s workflow should NOT contain %q\n---\n%s", tc.name, banned, s)+ }+ }+ })+ }+}++// TestInjectRuntimeConfigIssueMetadataCodexFormattingUnchanged guarantees+// that the new metadata wiring does not break the codex-specific comment+// formatting rules (HEREDOC on Linux, --content-file on Windows). The+// comment-formatting block lives below the metadata write step in the+// workflow, so any reordering or accidental absorption of the codex+// section would surface here.+func TestInjectRuntimeConfigIssueMetadataCodexFormattingUnchanged(t *testing.T) {+ t.Parallel()++ oldGOOS := runtimeGOOS+ t.Cleanup(func() { runtimeGOOS = oldGOOS })++ t.Run("linux_heredoc", func(t *testing.T) {+ runtimeGOOS = "linux"+ dir := t.TempDir()+ ctx := TaskContextForEnv{+ IssueID: "issue-md-codex",+ TriggerCommentID: "comment-md-codex",+ }+ if _, err := InjectRuntimeConfig(dir, "codex", ctx); err != nil {+ t.Fatalf("InjectRuntimeConfig failed: %v", err)+ }+ data, err := os.ReadFile(filepath.Join(dir, "AGENTS.md"))+ if err != nil {+ t.Fatalf("read AGENTS.md: %v", err)+ }+ s := string(data)++ // Metadata wiring is present...+ if !strings.Contains(s, "## Issue Metadata") {+ t.Fatalf("Issue Metadata section missing\n---\n%s", s)+ }+ if !strings.Contains(s, "multica issue metadata list issue-md-codex --output json") {+ t.Fatalf("metadata list step missing\n---\n%s", s)+ }+ // ...AND the codex-specific stdin-only rule is still emitted.+ if !strings.Contains(s, "always use `--content-stdin` with a HEREDOC") {+ t.Fatalf("codex linux HEREDOC rule missing\n---\n%s", s)+ }+ // ...AND the per-turn reply instruction still points at this+ // turn's trigger comment id.+ if !strings.Contains(s, "--parent comment-md-codex") {+ t.Fatalf("reply instruction lost trigger comment id\n---\n%s", s)+ }+ })++ t.Run("windows_content_file", func(t *testing.T) {+ runtimeGOOS = "windows"+ dir := t.TempDir()+ ctx := TaskContextForEnv{+ IssueID: "issue-md-codex-win",+ TriggerCommentID: "comment-md-codex-win",+ }+ if _, err := InjectRuntimeConfig(dir, "codex", ctx); err != nil {+ t.Fatalf("InjectRuntimeConfig failed: %v", err)+ }+ data, err := os.ReadFile(filepath.Join(dir, "AGENTS.md"))+ if err != nil {+ t.Fatalf("read AGENTS.md: %v", err)+ }+ s := string(data)++ if !strings.Contains(s, "## Issue Metadata") {+ t.Fatalf("Issue Metadata section missing on windows\n---\n%s", s)+ }+ if !strings.Contains(s, "always write the comment body to a UTF-8 file") {+ t.Fatalf("codex Windows --content-file rule missing\n---\n%s", s)+ }+ })+}diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.goindex f44c185892..971cf467a5 100644--- a/server/internal/daemon/execenv/runtime_config.go+++ b/server/internal/daemon/execenv/runtime_config.go@@ -210,7 +210,10 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {// escaping correctly and can pick whichever flag suits their// content. The `--content-file` line in the menu doubles as a// pointer at the Windows-safe path.- b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-stdin | --content-file <path>] [--parent <comment-id>] [--attachment <path>]` — Post a comment. Pick the input mode that preserves your content; run `multica issue comment add --help` for details.\n\n")+ b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-stdin | --content-file <path>] [--parent <comment-id>] [--attachment <path>]` — Post a comment. Pick the input mode that preserves your content; run `multica issue comment add --help` for details.\n")+ b.WriteString("- `multica issue metadata list <issue-id> [--output json]` — List every metadata key pinned to an issue. Empty `{}` is normal.\n")+ b.WriteString("- `multica issue metadata set <issue-id> --key <k> --value <v> [--type string|number|bool]` — Pin (or overwrite) a single metadata key. The CLI auto-infers JSON primitives, so URLs and plain text are stored as strings — pass `--type number` or `--type bool` only when the semantic type matters.\n")+ b.WriteString("- `multica issue metadata delete <issue-id> --key <k>` — Remove a metadata key.\n\n")if provider == "codex" {b.WriteString("## Codex-Specific Comment Formatting\n\n")@@ -256,6 +259,20 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {}}+ // Issue Metadata semantics — emitted only for tasks that operate on a real+ // issue (comment-triggered or assignment-triggered). Chat / quick-create /+ // run-only autopilot don't carry an issue id and would just generate a+ // failed `metadata list` call on every entry.+ hasIssueContext := ctx.ChatSessionID == "" && ctx.QuickCreatePrompt == "" && ctx.AutopilotRunID == ""+ if hasIssueContext {+ b.WriteString("## Issue Metadata\n\n")+ b.WriteString("Each issue carries a small KV `metadata` bag — a high-signal scratchpad where agents pin facts that future runs will need to find without re-parsing 200 comments (PR URLs, deploy URLs, external links, who you're waiting on, the final decision on a debated point).\n\n")+ b.WriteString("- **Read on entry.** Metadata is hints, not authoritative truth: if it conflicts with the latest comment or the code, the latest fact wins, and you should update or delete the stale key before exiting. Empty `{}` and CLI failures are normal — do not stop or ask the user.\n")+ b.WriteString("- **Write on exit.** If this run produced a fact future agents will want one-glance access to — opened PR, deploy URL, external ticket, current blocker — pin it with `multica issue metadata set`. If a key you saw on entry is now stale (e.g. `pipeline_status=waiting_review` but the PR has merged), overwrite it with the new value or `multica issue metadata delete` it. Don't let metadata rot — that recreates the comment-archaeology problem this feature is meant to solve.\n")+ b.WriteString("- **What NOT to pin.** No secrets, tokens, or API keys. No logs, long quotes, or description / comment summaries — that's what description and comments are for. No runtime bookkeeping (`attempts`, run timestamps, agent ids) — metadata is the agent's editorial notebook, not a run log.\n")+ b.WriteString("- **Recommended keys** (reuse these names so queries stay consistent across the workspace; coin a new key only when none fits): `pr_url`, `pr_number`, `pipeline_status`, `deploy_url`, `external_issue_url`, `waiting_on`, `blocked_reason`, `decision`. Use snake_case ASCII.\n\n")+ }+b.WriteString("### Workflow\n\n")if ctx.ChatSessionID != "" {@@ -313,35 +330,39 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {// Comment-triggered: focus on reading and replyingb.WriteString("**This task was triggered by a NEW comment.** Your primary job is to respond to THIS specific comment, even if you have handled similar requests before in this session.\n\n")fmt.Fprintf(&b, "1. Run `multica issue get %s --output json` to understand the issue context\n", ctx.IssueID)- fmt.Fprintf(&b, "2. Read the triggering thread first — that is what this comment is actually about. Default to the 30 most recent replies in that thread: `multica issue comment list %s --thread %s --tail 30 --output json` returns the root + the 30 newest replies (root is always included, even at `--tail 0`).\n", ctx.IssueID, ctx.TriggerCommentID)+ fmt.Fprintf(&b, "2. Run `multica issue metadata list %s --output json` to see what prior agents pinned — best-effort, empty `{}` and CLI failures are normal. See the `## Issue Metadata` section above for what to look for.\n", ctx.IssueID)+ fmt.Fprintf(&b, "3. Read the triggering thread first — that is what this comment is actually about. Default to the 30 most recent replies in that thread: `multica issue comment list %s --thread %s --tail 30 --output json` returns the root + the 30 newest replies (root is always included, even at `--tail 0`).\n", ctx.IssueID, ctx.TriggerCommentID)b.WriteString(" - If 30 replies aren't enough, walk older replies in the same thread one page at a time using the stderr `Next reply cursor: --before <ts> --before-id <reply-id>` line — pass the same pair back as `--before <ts> --before-id <reply-id>` on the next call. Under `--thread --tail` the cursor walks older *replies*, not older threads.\n")fmt.Fprintf(&b, " - If you also need cross-thread background, pull the most recently active threads on the issue: `multica issue comment list %s --recent 20 --output json`. Under `--recent` the same `--before` / `--before-id` flags walk older *threads* instead of older replies, and the stderr line is `Next thread cursor: --before <ts> --before-id <root-id>`. Pass the pair back to scroll to older threads when 20 still isn't enough.\n", ctx.IssueID)b.WriteString(" - Avoid the unfiltered `multica issue comment list <issue-id> --output json` form on long-running issues — it dumps the entire flat timeline (cap 2000) and wastes context on chatter unrelated to the trigger. `--since <RFC3339-timestamp>` is still available for incremental polling against a known cursor and may combine with `--thread --tail` or `--recent`.\n")- fmt.Fprintf(&b, "3. Find the triggering comment (ID: `%s`) inside the thread you just read and understand what is being asked — do NOT confuse it with previous comments\n", ctx.TriggerCommentID)+ fmt.Fprintf(&b, "4. Find the triggering comment (ID: `%s`) inside the thread you just read and understand what is being asked — do NOT confuse it with previous comments\n", ctx.TriggerCommentID)if ctx.IsSquadLeader {- b.WriteString("4. **Decide whether a reply is warranted.** If you produced actual work this turn (investigated, fixed, answered a real question), post the result via step 6 — that is a normal reply, not a noise comment. If the triggering comment was a pure acknowledgment / thanks / sign-off from another agent AND you produced no work this turn, do NOT post a reply — and do NOT post a comment saying 'No reply needed' or similar. Simply exit with no output. Silence is a valid and preferred way to end agent-to-agent conversations.\n")+ b.WriteString("5. **Decide whether a reply is warranted.** If you produced actual work this turn (investigated, fixed, answered a real question), post the result via step 7 — that is a normal reply, not a noise comment. If the triggering comment was a pure acknowledgment / thanks / sign-off from another agent AND you produced no work this turn, do NOT post a reply — and do NOT post a comment saying 'No reply needed' or similar. Simply exit with no output. Silence is a valid and preferred way to end agent-to-agent conversations.\n")fmt.Fprintf(&b, " - **Squad leader rule:** If your evaluation outcome is `no_action`, call `multica squad activity %s no_action --reason \"...\"` and then EXIT IMMEDIATELY. DO NOT post any comment whose only purpose is to announce that you are taking no action, exiting silently, or acknowledging another agent. A comment like \"No action needed\" or \"Exiting silently\" is noise — the `squad activity` call already records your decision in the timeline.\n", ctx.IssueID)} else {- b.WriteString("4. **Decide whether a reply is warranted.** If you produced actual work this turn (investigated, fixed, answered a real question), post the result via step 6 — that is a normal reply, not a noise comment. If the triggering comment was a pure acknowledgment / thanks / sign-off from another agent AND you produced no work this turn, do NOT post a reply — and do NOT post a comment saying 'No reply needed' or similar. Simply exit with no output. Silence is a valid and preferred way to end agent-to-agent conversations.\n")+ b.WriteString("5. **Decide whether a reply is warranted.** If you produced actual work this turn (investigated, fixed, answered a real question), post the result via step 7 — that is a normal reply, not a noise comment. If the triggering comment was a pure acknowledgment / thanks / sign-off from another agent AND you produced no work this turn, do NOT post a reply — and do NOT post a comment saying 'No reply needed' or similar. Simply exit with no output. Silence is a valid and preferred way to end agent-to-agent conversations.\n")}- b.WriteString("5. If a reply IS warranted: do any requested work first, then **decide whether to include any `@mention` link.** The default is NO mention. Only mention when you are escalating to a human owner who is not yet involved, delegating a concrete new sub-task to another agent for the first time, or the user explicitly asked you to loop someone in. Never @mention the agent you are replying to as a thank-you or sign-off.\n")- b.WriteString("6. **If you reply, post it as a comment — this step is mandatory when you reply.** Text in your terminal or run logs is NOT delivered to the user. ")+ b.WriteString("6. If a reply IS warranted: do any requested work first, then **decide whether to include any `@mention` link.** The default is NO mention. Only mention when you are escalating to a human owner who is not yet involved, delegating a concrete new sub-task to another agent for the first time, or the user explicitly asked you to loop someone in. Never @mention the agent you are replying to as a thank-you or sign-off.\n")+ b.WriteString("7. **If you reply, post it as a comment — this step is mandatory when you reply.** Text in your terminal or run logs is NOT delivered to the user. ")b.WriteString(BuildCommentReplyInstructions(provider, ctx.IssueID, ctx.TriggerCommentID))- b.WriteString("7. Do NOT change the issue status unless the comment explicitly asks for it\n\n")+ b.WriteString("8. Before exiting: if this run produced a fact worth pinning (PR URL, deploy URL, external link, current blocker) or noticed a metadata key that is now stale, pin or clear it via `multica issue metadata set`/`delete`. Optional — only act when you actually have a high-signal change to record. See the `## Issue Metadata` section above.\n")+ b.WriteString("9. Do NOT change the issue status unless the comment explicitly asks for it\n\n")} else {// Assignment-triggered: defer to agent Skills for workflow specifics.b.WriteString("You are responsible for managing the issue status throughout your work.\n\n")fmt.Fprintf(&b, "1. Run `multica issue get %s --output json` to understand your task\n", ctx.IssueID)- fmt.Fprintf(&b, "2. Run `multica issue comment list %s --output json` to read the full comment history (returns all comments, capped server-side at 2000) — this is mandatory, not optional. Earlier comments often carry context the issue body lacks (e.g. which repo to work in, the prior agent's findings, the reason the issue was reassigned to you). Skipping this step is the most common cause of agents acting on stale or incomplete instructions. When the flat dump is too large to ingest in one shot, treat `--recent 20 --output json` plus the `--before` / `--before-id` cursor (from the stderr `Next thread cursor:` line) as a paging strategy: keep walking older threads until you have read enough history to satisfy this mandatory step. `--recent` is a way to read the full history page-by-page, not a shortcut that replaces it.\n", ctx.IssueID)- fmt.Fprintf(&b, "3. Run `multica issue status %s in_progress`\n", ctx.IssueID)- b.WriteString("4. Follow your Skills and Agent Identity to complete the task (write code, investigate, etc.)\n")+ fmt.Fprintf(&b, "2. Run `multica issue metadata list %s --output json` to see what prior agents pinned — best-effort, empty `{}` and CLI failures are normal. See the `## Issue Metadata` section above for what to look for.\n", ctx.IssueID)+ fmt.Fprintf(&b, "3. Run `multica issue comment list %s --output json` to read the full comment history (returns all comments, capped server-side at 2000) — this is mandatory, not optional. Earlier comments often carry context the issue body lacks (e.g. which repo to work in, the prior agent's findings, the reason the issue was reassigned to you). Skipping this step is the most common cause of agents acting on stale or incomplete instructions. When the flat dump is too large to ingest in one shot, treat `--recent 20 --output json` plus the `--before` / `--before-id` cursor (from the stderr `Next thread cursor:` line) as a paging strategy: keep walking older threads until you have read enough history to satisfy this mandatory step. `--recent` is a way to read the full history page-by-page, not a shortcut that replaces it.\n", ctx.IssueID)+ fmt.Fprintf(&b, "4. Run `multica issue status %s in_progress`\n", ctx.IssueID)+ b.WriteString("5. Follow your Skills and Agent Identity to complete the task (write code, investigate, etc.)\n")if ctx.IsSquadLeader {- fmt.Fprintf(&b, "5. **Post your final results as a comment** (unless your outcome is `no_action` — in that case, calling `multica squad activity %s no_action --reason \"...\"` alone is sufficient; you MUST exit without posting any comment. DO NOT post a comment announcing no_action or saying you are exiting silently): `multica issue comment add %s --content \"...\"`. Your results are only visible to the user if posted via this CLI call; text in your terminal or run logs is NOT delivered.\n", ctx.IssueID, ctx.IssueID)+ fmt.Fprintf(&b, "6. **Post your final results as a comment** (unless your outcome is `no_action` — in that case, calling `multica squad activity %s no_action --reason \"...\"` alone is sufficient; you MUST exit without posting any comment. DO NOT post a comment announcing no_action or saying you are exiting silently): `multica issue comment add %s --content \"...\"`. Your results are only visible to the user if posted via this CLI call; text in your terminal or run logs is NOT delivered.\n", ctx.IssueID, ctx.IssueID)} else {- fmt.Fprintf(&b, "5. **Post your final results as a comment — this step is mandatory**: `multica issue comment add %s --content \"...\"`. Your results are only visible to the user if posted via this CLI call; text in your terminal or run logs is NOT delivered.\n", ctx.IssueID)+ fmt.Fprintf(&b, "6. **Post your final results as a comment — this step is mandatory**: `multica issue comment add %s --content \"...\"`. Your results are only visible to the user if posted via this CLI call; text in your terminal or run logs is NOT delivered.\n", ctx.IssueID)}- fmt.Fprintf(&b, "6. When done, run `multica issue status %s in_review`\n", ctx.IssueID)- fmt.Fprintf(&b, "7. If blocked, run `multica issue status %s blocked` and post a comment explaining why\n\n", ctx.IssueID)+ b.WriteString("7. Before exiting: if this run produced a fact worth pinning (PR URL, deploy URL, external link, current blocker) or noticed a metadata key that is now stale, pin or clear it via `multica issue metadata set`/`delete`. Optional — only act when you actually have a high-signal change to record. See the `## Issue Metadata` section above.\n")+ fmt.Fprintf(&b, "8. When done, run `multica issue status %s in_review`\n", ctx.IssueID)+ fmt.Fprintf(&b, "9. If blocked, run `multica issue status %s blocked` and post a comment explaining why\n\n", ctx.IssueID)}// Parent / Sub-issue Protocol — best-effort convention, not a server-sidediff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex e43f51fdb4..5727a34f0c 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -261,6 +261,14 @@ func isUniqueViolation(err error) bool {return errors.As(err, &pgErr) && pgErr.Code == "23505"}+// isCheckViolation reports whether err is a PostgreSQL CHECK constraint+// violation (SQLSTATE 23514). Used to translate column-level CHECK failures+// into a 4xx instead of a generic 500.+func isCheckViolation(err error) bool {+ var pgErr *pgconn.PgError+ return errors.As(err, &pgErr) && pgErr.Code == "23514"+}+func requestUserID(r *http.Request) string {return r.Header.Get("X-User-ID")}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 21b254023f..0179c2a5e5 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -46,8 +46,12 @@ type IssueResponse struct {DueDate *string `json:"due_date"`CreatedAt string `json:"created_at"`UpdatedAt string `json:"updated_at"`- Reactions []IssueReactionResponse `json:"reactions,omitempty"`- Attachments []AttachmentResponse `json:"attachments,omitempty"`+ // Metadata is the per-issue KV map (see issue_metadata.go). Always emitted+ // (empty object when unset) so frontend code can `issue.metadata[key]`+ // without nil-guarding the parent field.+ Metadata map[string]any `json:"metadata"`+ Reactions []IssueReactionResponse `json:"reactions,omitempty"`+ Attachments []AttachmentResponse `json:"attachments,omitempty"`// Labels are bulk-attached by list/detail endpoints so the client can render// chips without an N+1 round-trip per row. Pointer + omitempty so paths that// don't load labels (e.g. UpdateIssue, batch UpdateIssues, the issue:updated@@ -79,6 +83,7 @@ func issueToResponse(i db.Issue, issuePrefix string) IssueResponse {DueDate: timestampToPtr(i.DueDate),CreatedAt: timestampToString(i.CreatedAt),UpdatedAt: timestampToString(i.UpdatedAt),+ Metadata: parseIssueMetadata(i.Metadata),}}@@ -105,6 +110,7 @@ func issueListRowToResponse(i db.ListIssuesRow, issuePrefix string) IssueResponsDueDate: timestampToPtr(i.DueDate),CreatedAt: timestampToString(i.CreatedAt),UpdatedAt: timestampToString(i.UpdatedAt),+ Metadata: parseIssueMetadata(i.Metadata),}}@@ -161,6 +167,7 @@ func openIssueRowToResponse(i db.ListOpenIssuesRow, issuePrefix string) IssueResDueDate: timestampToPtr(i.DueDate),CreatedAt: timestampToString(i.CreatedAt),UpdatedAt: timestampToString(i.UpdatedAt),+ Metadata: parseIssueMetadata(i.Metadata),}}@@ -755,6 +762,11 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {involvesUserFilter = id}+ metadataFilter, ok := parseMetadataFilterParam(w, r.URL.Query().Get("metadata"))+ if !ok {+ return+ }+// open_only=true returns all non-done/cancelled issues (no limit).if r.URL.Query().Get("open_only") == "true" {issues, err := h.Queries.ListOpenIssues(ctx, db.ListOpenIssuesParams{@@ -765,6 +777,7 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {CreatorID: creatorFilter,ProjectID: projectFilter,InvolvesUserID: involvesUserFilter,+ MetadataFilter: metadataFilter,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list issues")@@ -832,6 +845,7 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {ProjectID: projectFilter,InvolvesUserID: involvesUserFilter,Scheduled: scheduledFilter,+ MetadataFilter: metadataFilter,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list issues")@@ -849,6 +863,7 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {ProjectID: projectFilter,InvolvesUserID: involvesUserFilter,Scheduled: scheduledFilter,+ MetadataFilter: metadataFilter,})if err != nil {total = int64(len(issues))@@ -1041,6 +1056,11 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {}where = append(where, fmt.Sprintf("i.project_id = %s::uuid", addArg(id)))}+ if filter, ok := parseMetadataFilterParam(w, r.URL.Query().Get("metadata")); !ok {+ return+ } else if filter != nil {+ where = append(where, fmt.Sprintf("i.metadata @> %s::jsonb", addArg(string(filter))))+ }// Mirror the involves_user_id 4-branch UNION from sqlc's ListIssues /// ListOpenIssues / CountIssues. ListGroupedIssues is a hand-written dynamic// SQL builder that does not share parameters with sqlc, so the fragment is@@ -1182,7 +1202,7 @@ WITH ranked AS (i.id, i.workspace_id, i.title, i.description, i.status, i.priority,i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,i.parent_issue_id, i.position, i.due_date, i.created_at, i.updated_at,- i.number, i.project_id,+ i.number, i.project_id, i.metadata,COUNT(*) OVER (PARTITION BY i.assignee_type, i.assignee_id) AS group_total,ROW_NUMBER() OVER (PARTITION BY i.assignee_type, i.assignee_id@@ -1195,7 +1215,7 @@ SELECTid, workspace_id, title, description, status, priority,assignee_type, assignee_id, creator_type, creator_id,parent_issue_id, position, due_date, created_at, updated_at,- number, project_id, group_total+ number, project_id, metadata, group_totalFROM rankedWHERE rn > %s AND rn <= %s + %sORDER BY@@ -1238,6 +1258,7 @@ ORDER BY&row.UpdatedAt,&row.Number,&row.ProjectID,+ &row.Metadata,&row.GroupTotal,); err != nil {slog.Warn("ListGroupedIssues scan failed", "error", err)diff --git a/server/internal/handler/issue_metadata.go b/server/internal/handler/issue_metadata.gonew file mode 100644index 0000000000..2ff0fec698--- /dev/null+++ b/server/internal/handler/issue_metadata.go@@ -0,0 +1,241 @@+package handler++import (+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "regexp"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/logger"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// Per-issue metadata is a small JSONB KV map agents use to record pipeline+// state (PR number, pipeline_status, waiting_on, ...). Three rules govern+// the V1 surface — they're enforced both in the handler and at the DB:+//+// - keys match `^[a-zA-Z_][a-zA-Z0-9_.-]{0,63}$` (handler)+// - at most 50 keys per issue (handler)+// - values are primitive: string / number / bool (handler)+// - JSONB column is an object and ≤ 8KB (DB CHECK; defense in depth)+//+// All mutations are single-key atomic. UpdateIssue does NOT touch metadata —+// any whole-blob overwrite would race with concurrent agent writes (see the+// design discussion on MUL-2017).+const (+ maxIssueMetadataKeys = 50+)++var issueMetadataKeyRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_.-]{0,63}$`)++// SetIssueMetadataKeyRequest carries the JSON value to write under the key+// named in the URL. Value is a RawMessage so we can preserve numeric vs.+// string typing through to PostgreSQL — once decoded into `any`, JSON+// numbers all collapse to float64 and we'd lose integer fidelity.+type SetIssueMetadataKeyRequest struct {+ Value json.RawMessage `json:"value"`+}++func validateIssueMetadataKey(key string) error {+ if key == "" {+ return errors.New("key is required")+ }+ if !issueMetadataKeyRE.MatchString(key) {+ return errors.New("key must match ^[a-zA-Z_][a-zA-Z0-9_.-]{0,63}$")+ }+ return nil+}++// validateIssueMetadataValue rejects anything other than a primitive JSON+// scalar. Null, arrays, and objects are not allowed — the V1 surface is+// flat KV. Removing a key uses DELETE, not a null value.+func validateIssueMetadataValue(raw json.RawMessage) error {+ if len(raw) == 0 {+ return errors.New("value is required")+ }+ var v any+ if err := json.Unmarshal(raw, &v); err != nil {+ return fmt.Errorf("value must be valid JSON: %w", err)+ }+ switch v.(type) {+ case string, bool, float64:+ return nil+ case nil:+ return errors.New("value cannot be null (use DELETE to remove a key)")+ default:+ return errors.New("value must be a primitive: string, number, or bool")+ }+}++// parseIssueMetadata decodes the JSONB bytes from db.Issue.Metadata into a+// Go map suitable for response serialization. Empty or unparseable blobs+// degrade to an empty map — the DB CHECK guarantees object shape, so this+// path is only hit on rows somehow predating the migration.+func parseIssueMetadata(raw []byte) map[string]any {+ if len(raw) == 0 {+ return map[string]any{}+ }+ var out map[string]any+ if err := json.Unmarshal(raw, &out); err != nil || out == nil {+ return map[string]any{}+ }+ return out+}++// parseMetadataFilterParam reads the `metadata` query parameter (a JSON+// object) and returns it as the JSONB filter blob passed to ListIssues /+// CountIssues / ListOpenIssues. Empty input means "no filter" and returns+// a nil []byte, which the SQL layer interprets as "skip the @> check".+//+// Validates that the filter is itself a flat object of primitives, mirroring+// the constraints we apply at write time — querying for `{key: {nested}}`+// would never match since written values are primitive by construction.+func parseMetadataFilterParam(w http.ResponseWriter, raw string) ([]byte, bool) {+ if raw == "" {+ return nil, true+ }+ var parsed map[string]any+ if err := json.Unmarshal([]byte(raw), &parsed); err != nil {+ writeError(w, http.StatusBadRequest, "metadata filter must be a JSON object")+ return nil, false+ }+ for k, v := range parsed {+ if err := validateIssueMetadataKey(k); err != nil {+ writeError(w, http.StatusBadRequest, "metadata filter "+err.Error())+ return nil, false+ }+ switch v.(type) {+ case string, bool, float64:+ // ok+ default:+ writeError(w, http.StatusBadRequest, "metadata filter values must be primitives (string, number, bool)")+ return nil, false+ }+ }+ // Re-marshal so we send canonical JSON to PG (and not the raw, possibly+ // whitespace-padded user input).+ buf, err := json.Marshal(parsed)+ if err != nil {+ writeError(w, http.StatusBadRequest, "metadata filter is invalid")+ return nil, false+ }+ return buf, true+}++func (h *Handler) ListIssueMetadata(w http.ResponseWriter, r *http.Request) {+ issueID := chi.URLParam(r, "id")+ issue, ok := h.loadIssueForUser(w, r, issueID)+ if !ok {+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{"metadata": parseIssueMetadata(issue.Metadata)})+}++func (h *Handler) SetIssueMetadataKey(w http.ResponseWriter, r *http.Request) {+ issueID := chi.URLParam(r, "id")+ key := chi.URLParam(r, "key")+ if err := validateIssueMetadataKey(key); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }++ var req SetIssueMetadataKeyRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if err := validateIssueMetadataValue(req.Value); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }++ issue, ok := h.loadIssueForUser(w, r, issueID)+ if !ok {+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }++ // Enforce the key-count cap in the handler. The DB only guards size,+ // and a clear 4xx for "too many keys" beats a CHECK violation that+ // happens to fire on the size cap once enough keys accumulate.+ existing := parseIssueMetadata(issue.Metadata)+ if _, present := existing[key]; !present && len(existing) >= maxIssueMetadataKeys {+ writeError(w, http.StatusBadRequest, fmt.Sprintf("metadata cannot exceed %d keys", maxIssueMetadataKeys))+ return+ }++ updated, err := h.Queries.SetIssueMetadataKey(r.Context(), db.SetIssueMetadataKeyParams{+ ID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ Key: key,+ Value: []byte(req.Value),+ })+ if err != nil {+ if isCheckViolation(err) {+ writeError(w, http.StatusBadRequest, "metadata exceeds the 8KB size limit")+ return+ }+ slog.Warn("SetIssueMetadataKey failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID, "key", key)...)+ writeError(w, http.StatusInternalServerError, "failed to set metadata key")+ return+ }++ workspaceID := uuidToString(updated.WorkspaceID)+ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ metadata := parseIssueMetadata(updated.Metadata)+ h.publish(protocol.EventIssueMetadataChanged, workspaceID, actorType, actorID, map[string]any{+ "issue_id": uuidToString(updated.ID),+ "metadata": metadata,+ })+ writeJSON(w, http.StatusOK, map[string]any{"metadata": metadata})+}++func (h *Handler) DeleteIssueMetadataKey(w http.ResponseWriter, r *http.Request) {+ issueID := chi.URLParam(r, "id")+ key := chi.URLParam(r, "key")+ if err := validateIssueMetadataKey(key); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }++ issue, ok := h.loadIssueForUser(w, r, issueID)+ if !ok {+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }++ updated, err := h.Queries.DeleteIssueMetadataKey(r.Context(), db.DeleteIssueMetadataKeyParams{+ ID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ Key: key,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "issue not found")+ return+ }+ slog.Warn("DeleteIssueMetadataKey failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID, "key", key)...)+ writeError(w, http.StatusInternalServerError, "failed to delete metadata key")+ return+ }++ workspaceID := uuidToString(updated.WorkspaceID)+ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ metadata := parseIssueMetadata(updated.Metadata)+ h.publish(protocol.EventIssueMetadataChanged, workspaceID, actorType, actorID, map[string]any{+ "issue_id": uuidToString(updated.ID),+ "metadata": metadata,+ })+ writeJSON(w, http.StatusOK, map[string]any{"metadata": metadata})+}diff --git a/server/internal/handler/issue_metadata_test.go b/server/internal/handler/issue_metadata_test.gonew file mode 100644index 0000000000..fac1f797e7--- /dev/null+++ b/server/internal/handler/issue_metadata_test.go@@ -0,0 +1,265 @@+package handler++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "testing"+)++// Round-trip: set primitives of each type, list, get them back, delete, confirm gone.+func TestIssueMetadataSetGetDelete(t *testing.T) {+ issueID := createMetadataTestIssue(t, "Metadata round-trip")++ cases := []struct {+ key string+ value string // raw JSON value+ }{+ {"pipeline_status", `"waiting"`},+ {"pr_number", `482`},+ {"is_blocked", `true`},+ {"is_done", `false`},+ }++ for _, c := range cases {+ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/issues/"+issueID+"/metadata/"+c.key, json.RawMessage(`{"value":`+c.value+`}`))+ req = withURLParams(req, "id", issueID, "key", c.key)+ testHandler.SetIssueMetadataKey(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("Set %s=%s: expected 200, got %d: %s", c.key, c.value, w.Code, w.Body.String())+ }+ }++ // List returns every key with the right value type.+ w := httptest.NewRecorder()+ req := newRequest("GET", "/api/issues/"+issueID+"/metadata", nil)+ req = withURLParam(req, "id", issueID)+ testHandler.ListIssueMetadata(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("List metadata: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp struct {+ Metadata map[string]any `json:"metadata"`+ }+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode list response: %v", err)+ }+ if got := resp.Metadata["pipeline_status"]; got != "waiting" {+ t.Errorf("pipeline_status: expected \"waiting\", got %T %v", got, got)+ }+ if got := resp.Metadata["pr_number"]; got != float64(482) {+ t.Errorf("pr_number: expected number 482, got %T %v", got, got)+ }+ if got := resp.Metadata["is_blocked"]; got != true {+ t.Errorf("is_blocked: expected true, got %T %v", got, got)+ }+ if got := resp.Metadata["is_done"]; got != false {+ t.Errorf("is_done: expected false, got %T %v", got, got)+ }++ // Delete a key — refresh confirms it is gone, others remain.+ w = httptest.NewRecorder()+ req = newRequest("DELETE", "/api/issues/"+issueID+"/metadata/pipeline_status", nil)+ req = withURLParams(req, "id", issueID, "key", "pipeline_status")+ testHandler.DeleteIssueMetadataKey(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("Delete pipeline_status: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ w = httptest.NewRecorder()+ req = newRequest("GET", "/api/issues/"+issueID+"/metadata", nil)+ req = withURLParam(req, "id", issueID)+ testHandler.ListIssueMetadata(w, req)+ // Decode into a fresh struct — json.Decode into a non-nil map merges,+ // it does not replace, so reusing `resp` would keep deleted keys around.+ var afterDelete struct {+ Metadata map[string]any `json:"metadata"`+ }+ json.NewDecoder(w.Body).Decode(&afterDelete)+ if _, present := afterDelete.Metadata["pipeline_status"]; present {+ t.Errorf("after delete, pipeline_status should be gone; got %+v", afterDelete.Metadata)+ }+ if _, present := afterDelete.Metadata["pr_number"]; !present {+ t.Errorf("delete removed unrelated key; got %+v", afterDelete.Metadata)+ }+}++// Invalid keys / values / shapes are rejected with 400 — the regex, primitive,+// and "no null" rules must all hold.+func TestIssueMetadataValidation(t *testing.T) {+ issueID := createMetadataTestIssue(t, "Metadata validation")++ bad := []struct {+ name string+ key string+ rawBody string+ }{+ {"key starts with digit", "1attempts", `{"value":"x"}`},+ {"key has space", "foo bar", `{"value":"x"}`},+ {"value is null", "k", `{"value":null}`},+ {"value is array", "k", `{"value":[1,2]}`},+ {"value is object", "k", `{"value":{"a":1}}`},+ {"empty body", "k", ``},+ }+ for _, c := range bad {+ t.Run(c.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ // chi pulls the key from URL params (injected via withURLParams);+ // the raw URL needs to be a valid request line, so PathEscape any+ // chars (spaces, etc.) that would otherwise break httptest.NewRequest.+ req := newRequest("PUT", "/api/issues/"+issueID+"/metadata/"+url.PathEscape(c.key), json.RawMessage(c.rawBody))+ req = withURLParams(req, "id", issueID, "key", c.key)+ testHandler.SetIssueMetadataKey(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ })+ }+}++// The 8KB DB CHECK kicks in past a few hundred KV pairs of large strings; we+// blow it deliberately with one giant value to confirm the handler surfaces+// a 400 (not a generic 500).+func TestIssueMetadataSizeLimit(t *testing.T) {+ issueID := createMetadataTestIssue(t, "Metadata size limit")++ huge := strings.Repeat("a", 9000)+ body, _ := json.Marshal(map[string]any{"value": huge})+ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/issues/"+issueID+"/metadata/blob", body)+ req = withURLParams(req, "id", issueID, "key", "blob")+ testHandler.SetIssueMetadataKey(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 from size CHECK, got %d: %s", w.Code, w.Body.String())+ }+}++// The 50-key cap is enforced in the handler with a clear 400.+func TestIssueMetadataKeyCountCap(t *testing.T) {+ issueID := createMetadataTestIssue(t, "Metadata key count cap")++ for i := 0; i < maxIssueMetadataKeys; i++ {+ key := fmt.Sprintf("k_%d", i)+ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/issues/"+issueID+"/metadata/"+key, json.RawMessage(`{"value":"v"}`))+ req = withURLParams(req, "id", issueID, "key", key)+ testHandler.SetIssueMetadataKey(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("key #%d: expected 200, got %d: %s", i, w.Code, w.Body.String())+ }+ }+ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/issues/"+issueID+"/metadata/overflow", json.RawMessage(`{"value":"v"}`))+ req = withURLParams(req, "id", issueID, "key", "overflow")+ testHandler.SetIssueMetadataKey(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("overflow key: expected 400, got %d: %s", w.Code, w.Body.String())+ }++ // Updating an existing key past the cap is still allowed — only new keys+ // are blocked.+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/issues/"+issueID+"/metadata/k_0", json.RawMessage(`{"value":"v2"}`))+ req = withURLParams(req, "id", issueID, "key", "k_0")+ testHandler.SetIssueMetadataKey(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("update existing at cap: expected 200, got %d: %s", w.Code, w.Body.String())+ }+}++// ListIssues with `metadata` query param does JSONB containment filtering and+// returns only matching issues — the killer use case for autopilot.+func TestListIssuesMetadataFilter(t *testing.T) {+ waitingID := createMetadataTestIssue(t, "Waiting issue")+ doneID := createMetadataTestIssue(t, "Done issue")++ for issueID, status := range map[string]string{waitingID: "waiting_review", doneID: "deployed"} {+ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/issues/"+issueID+"/metadata/pipeline_status",+ json.RawMessage(`{"value":"`+status+`"}`))+ req = withURLParams(req, "id", issueID, "key", "pipeline_status")+ testHandler.SetIssueMetadataKey(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("seed %s: %d %s", issueID, w.Code, w.Body.String())+ }+ }++ w := httptest.NewRecorder()+ req := newRequest("GET", `/api/issues?metadata={"pipeline_status":"waiting_review"}`, nil)+ testHandler.ListIssues(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("List with filter: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var listResp struct {+ Issues []IssueResponse `json:"issues"`+ }+ json.NewDecoder(w.Body).Decode(&listResp)++ foundWaiting := false+ for _, iss := range listResp.Issues {+ if iss.ID == doneID {+ t.Errorf("filter leaked: deployed issue %s appeared in waiting_review result set", doneID)+ }+ if iss.ID == waitingID {+ foundWaiting = true+ if got, _ := iss.Metadata["pipeline_status"].(string); got != "waiting_review" {+ t.Errorf("waiting issue: pipeline_status not surfaced; got %v", iss.Metadata)+ }+ }+ }+ if !foundWaiting {+ t.Errorf("waiting issue %s missing from filter result; got %d issues", waitingID, len(listResp.Issues))+ }++ // Malformed filter → 400.+ w = httptest.NewRecorder()+ req = newRequest("GET", `/api/issues?metadata={not-json}`, nil)+ testHandler.ListIssues(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("malformed metadata: expected 400, got %d", w.Code)+ }+}++// New issues default to an empty metadata object — never null — so frontend+// reads like `issue.metadata[key]` never NPE.+func TestNewIssueDefaultsToEmptyMetadata(t *testing.T) {+ issueID := createMetadataTestIssue(t, "Default empty metadata")++ w := httptest.NewRecorder()+ req := newRequest("GET", "/api/issues/"+issueID, nil)+ req = withURLParam(req, "id", issueID)+ testHandler.GetIssue(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetIssue: %d %s", w.Code, w.Body.String())+ }+ var got IssueResponse+ json.NewDecoder(w.Body).Decode(&got)+ if got.Metadata == nil {+ t.Fatalf("Metadata is nil on a fresh issue; expected empty object")+ }+ if len(got.Metadata) != 0 {+ t.Fatalf("Metadata: expected empty, got %v", got.Metadata)+ }+}++func createMetadataTestIssue(t *testing.T, title string) string {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ "status": "todo",+ "priority": "medium",+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("createMetadataTestIssue: %d %s", w.Code, w.Body.String())+ }+ var issue IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&issue); err != nil {+ t.Fatalf("decode issue: %v", err)+ }+ return issue.ID+}diff --git a/server/migrations/105_issue_metadata.down.sql b/server/migrations/105_issue_metadata.down.sqlnew file mode 100644index 0000000000..bad7b48661--- /dev/null+++ b/server/migrations/105_issue_metadata.down.sql@@ -0,0 +1,4 @@+DROP INDEX IF EXISTS idx_issue_metadata_gin;+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_metadata_size_limit;+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_metadata_is_object;+ALTER TABLE issue DROP COLUMN IF EXISTS metadata;diff --git a/server/migrations/105_issue_metadata.up.sql b/server/migrations/105_issue_metadata.up.sqlnew file mode 100644index 0000000000..6a336a3cbe--- /dev/null+++ b/server/migrations/105_issue_metadata.up.sql@@ -0,0 +1,19 @@+-- Per-issue custom metadata: a small JSONB KV map agents use to record+-- pipeline state (PR number, pipeline_status, waiting_on, …) that doesn't+-- fit cleanly into the structured issue fields.+--+-- Application-level validation (handler) enforces key regex, key count+-- cap, and primitive-only values. The DB CHECKs below are defense-in-depth+-- against migrations or direct SQL writes that bypass the API surface.+ALTER TABLE issue ADD COLUMN metadata JSONB NOT NULL DEFAULT '{}'::jsonb;++ALTER TABLE issue ADD CONSTRAINT issue_metadata_is_object+ CHECK (jsonb_typeof(metadata) = 'object');++ALTER TABLE issue ADD CONSTRAINT issue_metadata_size_limit+ CHECK (pg_column_size(metadata) <= 8192);++-- GIN with jsonb_path_ops: smaller index, faster `@>` containment.+-- We only need containment queries (no `?` existence), so the path-ops+-- variant is the right trade.+CREATE INDEX idx_issue_metadata_gin ON issue USING GIN (metadata jsonb_path_ops);diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 9220a7ccba..9ffbd3817c 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -103,12 +103,13 @@ WHERE i.workspace_id = $1AND ($6::uuid IS NULL OR i.creator_id = $6)AND ($7::uuid IS NULL OR i.project_id = $7)AND ($8::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))+ AND ($9::jsonb IS NULL OR i.metadata @> $9::jsonb)AND (- $9::uuid IS NULL+ $10::uuid IS NULLOR (i.assignee_type = 'agent' AND i.assignee_id IN (SELECT a.id FROM agent aWHERE a.workspace_id = $1- AND a.owner_id = $9::uuid+ AND a.owner_id = $10::uuid))OR (i.assignee_type = 'squad' AND i.assignee_id IN (SELECT sm.squad_id@@ -116,14 +117,14 @@ WHERE i.workspace_id = $1JOIN squad s ON s.id = sm.squad_idWHERE s.workspace_id = $1AND sm.member_type = 'member'- AND sm.member_id = $9::uuid+ AND sm.member_id = $10::uuidUNIONSELECT s.idFROM squad sJOIN agent a ON a.id = s.leader_idWHERE s.workspace_id = $1AND a.workspace_id = $1- AND a.owner_id = $9::uuid+ AND a.owner_id = $10::uuidUNIONSELECT sm.squad_idFROM squad_member sm@@ -132,7 +133,7 @@ WHERE i.workspace_id = $1WHERE s.workspace_id = $1AND sm.member_type = 'agent'AND a.workspace_id = $1- AND a.owner_id = $9::uuid+ AND a.owner_id = $10::uuid)))`@@ -146,6 +147,7 @@ type CountIssuesParams struct {CreatorID pgtype.UUID `json:"creator_id"`ProjectID pgtype.UUID `json:"project_id"`Scheduled pgtype.Bool `json:"scheduled"`+ MetadataFilter []byte `json:"metadata_filter"`InvolvesUserID pgtype.UUID `json:"involves_user_id"`}@@ -160,6 +162,7 @@ func (q *Queries) CountIssues(ctx context.Context, arg CountIssuesParams) (int64arg.CreatorID,arg.ProjectID,arg.Scheduled,+ arg.MetadataFilter,arg.InvolvesUserID,)var count int64@@ -174,7 +177,7 @@ INSERT INTO issue (parent_issue_id, position, start_date, due_date, number, project_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata`type CreateIssueParams struct {@@ -238,6 +241,7 @@ func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue&i.OriginID,&i.FirstExecutedAt,&i.StartDate,+ &i.Metadata,)return i, err}@@ -251,7 +255,7 @@ INSERT INTO issue () VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,$16, $17-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata`type CreateIssueWithOriginParams struct {@@ -319,6 +323,7 @@ func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWith&i.OriginID,&i.FirstExecutedAt,&i.StartDate,+ &i.Metadata,)return i, err}@@ -332,8 +337,56 @@ func (q *Queries) DeleteIssue(ctx context.Context, id pgtype.UUID) error {return err}+const deleteIssueMetadataKey = `-- name: DeleteIssueMetadataKey :one+UPDATE issue SET+ metadata = metadata - $1::text,+ updated_at = now()+WHERE id = $2 AND workspace_id = $3+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata+`++type DeleteIssueMetadataKeyParams struct {+ Key string `json:"key"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Atomically removes a single key from the issue's metadata JSONB.+// Deleting a missing key is a no-op (still returns the row).+func (q *Queries) DeleteIssueMetadataKey(ctx context.Context, arg DeleteIssueMetadataKeyParams) (Issue, error) {+ row := q.db.QueryRow(ctx, deleteIssueMetadataKey, arg.Key, arg.ID, arg.WorkspaceID)+ var i Issue+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Title,+ &i.Description,+ &i.Status,+ &i.Priority,+ &i.AssigneeType,+ &i.AssigneeID,+ &i.CreatorType,+ &i.CreatorID,+ &i.ParentIssueID,+ &i.AcceptanceCriteria,+ &i.ContextRefs,+ &i.Position,+ &i.DueDate,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Number,+ &i.ProjectID,+ &i.OriginType,+ &i.OriginID,+ &i.FirstExecutedAt,+ &i.StartDate,+ &i.Metadata,+ )+ return i, err+}+const findActiveDuplicateIssue = `-- name: FindActiveDuplicateIssue :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata FROM issueWHERE workspace_id = $1AND status NOT IN ('done', 'cancelled')AND project_id IS NOT DISTINCT FROM $2::uuid@@ -382,12 +435,13 @@ func (q *Queries) FindActiveDuplicateIssue(ctx context.Context, arg FindActiveDu&i.OriginID,&i.FirstExecutedAt,&i.StartDate,+ &i.Metadata,)return i, err}const getIssue = `-- name: GetIssue :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata FROM issueWHERE id = $1`@@ -418,12 +472,13 @@ func (q *Queries) GetIssue(ctx context.Context, id pgtype.UUID) (Issue, error) {&i.OriginID,&i.FirstExecutedAt,&i.StartDate,+ &i.Metadata,)return i, err}const getIssueByNumber = `-- name: GetIssueByNumber :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata FROM issueWHERE workspace_id = $1 AND number = $2`@@ -459,12 +514,13 @@ func (q *Queries) GetIssueByNumber(ctx context.Context, arg GetIssueByNumberPara&i.OriginID,&i.FirstExecutedAt,&i.StartDate,+ &i.Metadata,)return i, err}const getIssueByOrigin = `-- name: GetIssueByOrigin :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata FROM issueWHERE workspace_id = $1AND origin_type = $2AND origin_id = $3@@ -509,12 +565,13 @@ func (q *Queries) GetIssueByOrigin(ctx context.Context, arg GetIssueByOriginPara&i.OriginID,&i.FirstExecutedAt,&i.StartDate,+ &i.Metadata,)return i, err}const getIssueInWorkspace = `-- name: GetIssueInWorkspace :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata FROM issueWHERE id = $1 AND workspace_id = $2`@@ -550,12 +607,13 @@ func (q *Queries) GetIssueInWorkspace(ctx context.Context, arg GetIssueInWorkspa&i.OriginID,&i.FirstExecutedAt,&i.StartDate,+ &i.Metadata,)return i, err}const listChildIssues = `-- name: ListChildIssues :many-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata FROM issueWHERE parent_issue_id = $1ORDER BY position ASC, created_at DESC`@@ -593,6 +651,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID&i.OriginID,&i.FirstExecutedAt,&i.StartDate,+ &i.Metadata,); err != nil {return nil, err}@@ -607,7 +666,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUIDconst listIssues = `-- name: ListIssues :manySELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadataFROM issue iWHERE i.workspace_id = $1AND ($4::text IS NULL OR i.status = $4)@@ -617,13 +676,14 @@ WHERE i.workspace_id = $1AND ($8::uuid IS NULL OR i.creator_id = $8)AND ($9::uuid IS NULL OR i.project_id = $9)AND ($10::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))+ AND ($11::jsonb IS NULL OR i.metadata @> $11::jsonb)AND (- $11::uuid IS NULL+ $12::uuid IS NULL-- (1) assignee is an agent owned by the userOR (i.assignee_type = 'agent' AND i.assignee_id IN (SELECT a.id FROM agent aWHERE a.workspace_id = $1- AND a.owner_id = $11::uuid+ AND a.owner_id = $12::uuid))-- (2)(3)(4) assignee is a squad related to the user — three relationsOR (i.assignee_type = 'squad' AND i.assignee_id IN (@@ -633,7 +693,7 @@ WHERE i.workspace_id = $1JOIN squad s ON s.id = sm.squad_idWHERE s.workspace_id = $1AND sm.member_type = 'member'- AND sm.member_id = $11::uuid+ AND sm.member_id = $12::uuidUNION-- (3) the squad's canonical leader is an agent owned by the user.-- We read squad.leader_id directly rather than relying on a@@ -644,7 +704,7 @@ WHERE i.workspace_id = $1JOIN agent a ON a.id = s.leader_idWHERE s.workspace_id = $1AND a.workspace_id = $1- AND a.owner_id = $11::uuid+ AND a.owner_id = $12::uuidUNION-- (4) the squad has an agent member owned by the userSELECT sm.squad_id@@ -654,7 +714,7 @@ WHERE i.workspace_id = $1WHERE s.workspace_id = $1AND sm.member_type = 'agent'AND a.workspace_id = $1- AND a.owner_id = $11::uuid+ AND a.owner_id = $12::uuid)))ORDER BY i.position ASC, i.created_at DESC@@ -672,6 +732,7 @@ type ListIssuesParams struct {CreatorID pgtype.UUID `json:"creator_id"`ProjectID pgtype.UUID `json:"project_id"`Scheduled pgtype.Bool `json:"scheduled"`+ MetadataFilter []byte `json:"metadata_filter"`InvolvesUserID pgtype.UUID `json:"involves_user_id"`}@@ -694,6 +755,7 @@ type ListIssuesRow struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`Number int32 `json:"number"`ProjectID pgtype.UUID `json:"project_id"`+ Metadata []byte `json:"metadata"`}// involves_user_id widens the assignee filter to surface issues where the user@@ -714,6 +776,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListIarg.CreatorID,arg.ProjectID,arg.Scheduled,+ arg.MetadataFilter,arg.InvolvesUserID,)if err != nil {@@ -742,6 +805,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListI&i.UpdatedAt,&i.Number,&i.ProjectID,+ &i.Metadata,); err != nil {return nil, err}@@ -756,7 +820,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListIconst listOpenIssues = `-- name: ListOpenIssues :manySELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadataFROM issue iWHERE i.workspace_id = $1AND i.status NOT IN ('done', 'cancelled')@@ -765,12 +829,13 @@ WHERE i.workspace_id = $1AND ($4::uuid[] IS NULL OR i.assignee_id = ANY($4::uuid[]))AND ($5::uuid IS NULL OR i.creator_id = $5)AND ($6::uuid IS NULL OR i.project_id = $6)+ AND ($7::jsonb IS NULL OR i.metadata @> $7::jsonb)AND (- $7::uuid IS NULL+ $8::uuid IS NULLOR (i.assignee_type = 'agent' AND i.assignee_id IN (SELECT a.id FROM agent aWHERE a.workspace_id = $1- AND a.owner_id = $7::uuid+ AND a.owner_id = $8::uuid))OR (i.assignee_type = 'squad' AND i.assignee_id IN (SELECT sm.squad_id@@ -778,14 +843,14 @@ WHERE i.workspace_id = $1JOIN squad s ON s.id = sm.squad_idWHERE s.workspace_id = $1AND sm.member_type = 'member'- AND sm.member_id = $7::uuid+ AND sm.member_id = $8::uuidUNIONSELECT s.idFROM squad sJOIN agent a ON a.id = s.leader_idWHERE s.workspace_id = $1AND a.workspace_id = $1- AND a.owner_id = $7::uuid+ AND a.owner_id = $8::uuidUNIONSELECT sm.squad_idFROM squad_member sm@@ -794,7 +859,7 @@ WHERE i.workspace_id = $1WHERE s.workspace_id = $1AND sm.member_type = 'agent'AND a.workspace_id = $1- AND a.owner_id = $7::uuid+ AND a.owner_id = $8::uuid)))ORDER BY i.position ASC, i.created_at DESC@@ -807,6 +872,7 @@ type ListOpenIssuesParams struct {AssigneeIds []pgtype.UUID `json:"assignee_ids"`CreatorID pgtype.UUID `json:"creator_id"`ProjectID pgtype.UUID `json:"project_id"`+ MetadataFilter []byte `json:"metadata_filter"`InvolvesUserID pgtype.UUID `json:"involves_user_id"`}@@ -829,6 +895,7 @@ type ListOpenIssuesRow struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`Number int32 `json:"number"`ProjectID pgtype.UUID `json:"project_id"`+ Metadata []byte `json:"metadata"`}// See ListIssues for the semantics of involves_user_id (mirrors the 4-branch@@ -841,6 +908,7 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)arg.AssigneeIds,arg.CreatorID,arg.ProjectID,+ arg.MetadataFilter,arg.InvolvesUserID,)if err != nil {@@ -869,6 +937,7 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)&i.UpdatedAt,&i.Number,&i.ProjectID,+ &i.Metadata,); err != nil {return nil, err}@@ -890,7 +959,6 @@ func (q *Queries) LockIssueDuplicateKey(ctx context.Context, dollar_1 string) er}const markIssueFirstExecuted = `-- name: MarkIssueFirstExecuted :one-UPDATE issueSET first_executed_at = now()WHERE id = $1 AND first_executed_at IS NULL@@ -905,7 +973,6 @@ type MarkIssueFirstExecutedRow struct {FirstExecutedAt pgtype.Timestamptz `json:"first_executed_at"`}-// SearchIssues: moved to handler (dynamic SQL for multi-word search support).// Flips first_executed_at from NULL to now() atomically. Returns the row if// this was the first time the issue was executed; no rows otherwise. The// analytics issue_executed event fires exactly when this returns a row —@@ -923,6 +990,63 @@ func (q *Queries) MarkIssueFirstExecuted(ctx context.Context, id pgtype.UUID) (Mreturn i, err}+const setIssueMetadataKey = `-- name: SetIssueMetadataKey :one++UPDATE issue SET+ metadata = jsonb_set(metadata, ARRAY[$1::text], $2::jsonb),+ updated_at = now()+WHERE id = $3 AND workspace_id = $4+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata+`++type SetIssueMetadataKeyParams struct {+ Key string `json:"key"`+ Value []byte `json:"value"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// SearchIssues: moved to handler (dynamic SQL for multi-word search support).+// Atomically sets a single key in the issue's metadata JSONB. The+// workspace_id filter is the authorization gate — handler resolves the+// issue first so this is also the tenant check.+func (q *Queries) SetIssueMetadataKey(ctx context.Context, arg SetIssueMetadataKeyParams) (Issue, error) {+ row := q.db.QueryRow(ctx, setIssueMetadataKey,+ arg.Key,+ arg.Value,+ arg.ID,+ arg.WorkspaceID,+ )+ var i Issue+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Title,+ &i.Description,+ &i.Status,+ &i.Priority,+ &i.AssigneeType,+ &i.AssigneeID,+ &i.CreatorType,+ &i.CreatorID,+ &i.ParentIssueID,+ &i.AcceptanceCriteria,+ &i.ContextRefs,+ &i.Position,+ &i.DueDate,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Number,+ &i.ProjectID,+ &i.OriginType,+ &i.OriginID,+ &i.FirstExecutedAt,+ &i.StartDate,+ &i.Metadata,+ )+ return i, err+}+const updateIssue = `-- name: UpdateIssue :oneUPDATE issue SETtitle = COALESCE($2, title),@@ -938,7 +1062,7 @@ UPDATE issue SETproject_id = $12,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata`type UpdateIssueParams struct {@@ -996,6 +1120,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue&i.OriginID,&i.FirstExecutedAt,&i.StartDate,+ &i.Metadata,)return i, err}@@ -1005,7 +1130,7 @@ UPDATE issue SETstatus = $2,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata`type UpdateIssueStatusParams struct {@@ -1040,6 +1165,7 @@ func (q *Queries) UpdateIssueStatus(ctx context.Context, arg UpdateIssueStatusPa&i.OriginID,&i.FirstExecutedAt,&i.StartDate,+ &i.Metadata,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex fedfe39f72..a14bab8d49 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -335,6 +335,7 @@ type Issue struct {OriginID pgtype.UUID `json:"origin_id"`FirstExecutedAt pgtype.Timestamptz `json:"first_executed_at"`StartDate pgtype.Timestamptz `json:"start_date"`+ Metadata []byte `json:"metadata"`}type IssueDependency struct {diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 41eecc10c0..818cf79751 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -7,7 +7,7 @@-- "Assigned to me"), and the two filters must produce disjoint result sets.SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadataFROM issue iWHERE i.workspace_id = $1AND (sqlc.narg('status')::text IS NULL OR i.status = sqlc.narg('status'))@@ -17,6 +17,7 @@ WHERE i.workspace_id = $1AND (sqlc.narg('creator_id')::uuid IS NULL OR i.creator_id = sqlc.narg('creator_id'))AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))AND (sqlc.narg('scheduled')::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))+ AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)AND (sqlc.narg('involves_user_id')::uuid IS NULL-- (1) assignee is an agent owned by the user@@ -137,7 +138,7 @@ DELETE FROM issue WHERE id = $1;-- filter; member-direct assignment is intentionally excluded).SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadataFROM issue iWHERE i.workspace_id = $1AND i.status NOT IN ('done', 'cancelled')@@ -146,6 +147,7 @@ WHERE i.workspace_id = $1AND (sqlc.narg('assignee_ids')::uuid[] IS NULL OR i.assignee_id = ANY(sqlc.narg('assignee_ids')::uuid[]))AND (sqlc.narg('creator_id')::uuid IS NULL OR i.creator_id = sqlc.narg('creator_id'))AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+ AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)AND (sqlc.narg('involves_user_id')::uuid IS NULLOR (i.assignee_type = 'agent' AND i.assignee_id IN (@@ -191,6 +193,7 @@ WHERE i.workspace_id = $1AND (sqlc.narg('creator_id')::uuid IS NULL OR i.creator_id = sqlc.narg('creator_id'))AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))AND (sqlc.narg('scheduled')::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))+ AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)AND (sqlc.narg('involves_user_id')::uuid IS NULLOR (i.assignee_type = 'agent' AND i.assignee_id IN (@@ -266,6 +269,25 @@ GROUP BY parent_issue_id;-- SearchIssues: moved to handler (dynamic SQL for multi-word search support).+-- name: SetIssueMetadataKey :one+-- Atomically sets a single key in the issue's metadata JSONB. The+-- workspace_id filter is the authorization gate — handler resolves the+-- issue first so this is also the tenant check.+UPDATE issue SET+ metadata = jsonb_set(metadata, ARRAY[sqlc.arg('key')::text], sqlc.arg('value')::jsonb),+ updated_at = now()+WHERE id = sqlc.arg('id') AND workspace_id = sqlc.arg('workspace_id')+RETURNING *;++-- name: DeleteIssueMetadataKey :one+-- Atomically removes a single key from the issue's metadata JSONB.+-- Deleting a missing key is a no-op (still returns the row).+UPDATE issue SET+ metadata = metadata - sqlc.arg('key')::text,+ updated_at = now()+WHERE id = sqlc.arg('id') AND workspace_id = sqlc.arg('workspace_id')+RETURNING *;+-- name: MarkIssueFirstExecuted :one-- Flips first_executed_at from NULL to now() atomically. Returns the row if-- this was the first time the issue was executed; no rows otherwise. Thediff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 8177f86e20..c34bb914ff 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -3,9 +3,10 @@ package protocol// Event types for WebSocket communication between server, web clients, and daemon.const (// Issue events- EventIssueCreated = "issue:created"- EventIssueUpdated = "issue:updated"- EventIssueDeleted = "issue:deleted"+ EventIssueCreated = "issue:created"+ EventIssueUpdated = "issue:updated"+ EventIssueDeleted = "issue:deleted"+ EventIssueMetadataChanged = "issue_metadata:changed"// Comment eventsEventCommentCreated = "comment:created"