Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7680: issue wakeup v2 — conditions, runaway protection, check-ins and visibility (#8807)
Jiayuan Zhang5ed09342af2e
diff --git a/apps/mobile/components/inbox/detail-label.tsx b/apps/mobile/components/inbox/detail-label.tsxindex 55a7b67a9b..7d577fd439 100644--- a/apps/mobile/components/inbox/detail-label.tsx+++ b/apps/mobile/components/inbox/detail-label.tsx@@ -56,6 +56,7 @@ const TYPE_KEY: Record<InboxItemType, string> = {quick_create_unconfirmed: "type.quick_create_unconfirmed",autopilot_paused: "type.autopilot_paused",autopilot_quota_exceeded: "type.autopilot_quota_exceeded",+ children_done: "type.children_done",};// due_date is a calendar day — format timezone-safely (no offset day shift).diff --git a/apps/mobile/locales/en/inbox.json b/apps/mobile/locales/en/inbox.jsonindex 0952a939ab..62520d96d6 100644--- a/apps/mobile/locales/en/inbox.json+++ b/apps/mobile/locales/en/inbox.json@@ -64,6 +64,7 @@"quick_create_failed": "Quick-create failed","quick_create_unconfirmed": "Quick-create needs a check","autopilot_paused": "Autopilot paused",+ "children_done": "Sub-issues finished","autopilot_quota_exceeded": "Autopilot run limit reached","set_status": "Set status to","set_priority": "Set priority to",diff --git a/apps/mobile/locales/zh-Hans/inbox.json b/apps/mobile/locales/zh-Hans/inbox.jsonindex 51c3da73dc..8f3b344d65 100644--- a/apps/mobile/locales/zh-Hans/inbox.json+++ b/apps/mobile/locales/zh-Hans/inbox.json@@ -64,6 +64,7 @@"quick_create_failed": "快速创建失败","quick_create_unconfirmed": "快速创建需要确认","autopilot_paused": "自动化已暂停",+ "children_done": "子任务已全部结束","autopilot_quota_exceeded": "自动化运行次数已达上限","set_status": "状态设为","set_priority": "优先级设为",diff --git a/docs/engineering/issue-wakeups.md b/docs/engineering/issue-wakeups.mdindex c9fac1517c..f6cec55cf5 100644--- a/docs/engineering/issue-wakeups.md+++ b/docs/engineering/issue-wakeups.md@@ -1,9 +1,11 @@# Issue wakeups-An agent can save an event subscription or a timer on an issue, finish its run,-and receive another ordinary run when the input arrives. Business completion is-still decided by the agent after reading current state. There is no sleeping-process, business-condition evaluator, or second run lifecycle.+An agent or a member can save an event subscription, a condition or a timer on+an issue; the agent finishes its run and receives another ordinary run when the+input arrives. The platform only compares facts it stores (a field value,+sub-issue status, a linked pull request's state); business completion is still+decided by the agent after reading current state. There is no sleeping process+or second run lifecycle.## Product contract@@ -53,9 +55,17 @@ multica issue wakeup create ISSUE --kind at --after 10m --instruction-file ./insmultica issue wakeup create ISSUE --kind every --every 1h --instruction-file ./instruction.mdmultica issue wakeup create ISSUE --kind cron --cron '0 * * * *' --timezone Asia/Shanghai --instruction-file ./instruction.mdmultica issue wakeup create ISSUE --kind event --event task.completed,task.failed,task.cancelled --task-id RUN --instruction-file ./instruction.md+multica issue wakeup create ISSUE --until-status in_review --instruction-file ./instruction.md+multica issue wakeup create ISSUE --until-pr checks --expires-in 2h --on-timeout wake --instruction-file ./instruction.md+multica issue wakeup create ISSUE --until-children-done --stage 1 --instruction-file ./instruction.md+multica issue wakeup create ISSUE --until-issue MUL-123 --until-issue-state done --instruction-file ./instruction.mdmultica issue wakeup list ISSUEmultica issue wakeup get ISSUE WAKEUP+multica issue wakeup runs ISSUE WAKEUP+multica issue wakeup trigger ISSUE WAKEUPmultica issue wakeup disable ISSUE WAKEUP+multica issue wakeup delete ISSUE WAKEUP+multica issue wakeup checkin ISSUE WAKEUP --note "CI still running"```Specify `--agent-id` for human callers; authenticated agents default to themselves.@@ -79,9 +89,9 @@ new configuration's recorded human principal.The scheduler checks approximately every 30 seconds. One-shot timers remainqueued while their runtime is offline. Repeating timers coalesce missed periodsinto one pending check and continue from the next future time; they do not replay-every historical tick. All runs retain normal comment delivery, including checks-that find no change. CI can be polled by the agent; CI push events are not claimed-as supported by this version.+every historical tick. Runs keep normal comment delivery, except that a run an+every/cron rule started may end with a check-in instead (see below). Linked pull+request conditions read the stored PR snapshot; there is no separate CI event.## Event catalog@@ -396,3 +406,230 @@ the subscription revision avoids invalidating receipts and queued work on a textedit. This additive endpoint needs no migration and does not change existingclients. Deploy the API before using the editor; an older API rejects the newendpoint and the editor keeps the unsaved text.+++## Deadlines, member-created rules and the child-done system rule++Rules can end on their own. `expires_in_seconds` is a relative wait stored in+`expiry_seconds`; re-enabling restarts it from now. `expires_at` is an absolute+end, typically a recurring check's end date; a passed absolute end cannot be+re-enabled without replacing the rule. Single-time (`at`) rules end when they+fire and take no deadline. Rules without either field keep the previous+open-ended behavior, so existing agent-created rules are unaffected.++The scheduler treats `enabled AND expires_at <= now()` as a candidate (partial+index 554). Under the usual rule lock, a reached deadline disables the rule and+sets `timed_out_at`; `disabled_at` stays NULL because it means "turned off by a+person" and claim-time checks refuse wakeup runs whose rule has `disabled_at`.+Inputs captured before the deadline still dispatch. `on_timeout=wake` (event+rules only) records one `wakeup.timeout` receipt, so the target runs once to+escalate, extend or stop; `end` (the default) ends without a run.++Members create rules from the issue sidebar with the existing create endpoint;+the form maps choices (a time, a recurring check with an end date, someone's+reply, an agent's run ending, or raw events) onto the same configuration an+agent sends. List responses add `created_by_agent`, `created_by_name` and the+redacted `source_agent_*` of the run that created a rule.++The parent-assignee wake on a closed sub-issue stage is the platform's+`child_done` system rule: an ordinary `issue_wakeup` row with `system_rule`+set (migration 555), one per parent (unique index 556). It shares the+condition, receipts, runaway protection, timeline entries, list and run model+of people's rules; what differs is owned by the platform:++- **Target.** `agent_id` and `created_by` are NULL. When it fires the rule+ resolves the parent's assignee: an agent gets a wakeup run, a squad's leader+ gets a leader-role run, a member gets a `children_done` inbox notification,+ and no assignee (or an agent that cannot run) only records the timeline+ entry. The run is accountable to the parent's own provenance, as a run its+ assignment would start, and it is not re-checked against a creator at claim+ time; claim requires the rule on and the agent runnable.+- **Condition.** `{"type":"children_done","each_stage":true}` (clients cannot+ set `each_stage`). It holds with fingerprint `stage:N` when stage N and every+ earlier stage are closed while a later stage waits, and with `all` when every+ sub-issue, staged or not, is closed; the last stage alone does not hold, so+ the wrap-up waits for unstaged sub-issues. A reopened sub-issue clears the+ fingerprint, so closing it again fires again. People's `children_done`+ conditions read the same sub-issue set (`childrenDone`).+- **Evaluation.** Not polled (`next_fire_at` stays NULL). Migration 558 adds+ `issue_child_event` and triggers on `issue` that record, in the writing+ transaction and for every writer, a sub-issue entering or leaving a closed+ status (built-in or custom done/closed category), joining or leaving a parent,+ or changing stage. The request that wrote it processes the rows right after+ commit (`ProcessChildEvents`: claim per parent, create the parent's rule if+ missing, give every sub-issue rule on the parent a `children.changed` hint,+ dispatch them, people's rules first); the `issue_child_event_sweep` job+ retries rows left unclaimed for 30 seconds or claimed for more than five+ minutes and deletes processed rows after a week. The rule also subscribes to+ `issue.status_changed` on the parent, so leaving backlog re-evaluates it.+- **Holds.** A parent in backlog is not woken and nothing is marked as seen:+ leaving backlog wakes the assignee once for what closed meanwhile. A closed+ parent keeps the rule (the platform never disables a system rule for a+ closed issue); it rests until the parent reopens.+- **Joining a waiting run.** If the target agent already has an unstarted run+ on the parent that runs as the person the rule's own run would (see "Repeat+ runs" below), the rule keeps its facts for that run instead of queuing a+ second one. Runaway protection is the hourly limit+ (12 runs, then `paused_reason=rate`); loop detection does not apply because+ stage hand-offs cross issues by design, and there is no fire cap.+- **Instruction.** The run's `[WAKEUP]` block carries the instruction and the+ observation (each stage's closed and cancelled counts, the closed stage, the+ next stage). The instruction is the issue's own (`instruction` on the row),+ else the workspace's (`system_wakeup_child_done_instruction`), else the+ built-in `ChildDoneDefaultInstruction`. The daemon tells the agent the rule is+ the platform's and not to change it. No system comment is posted; the+ `wakeup_triggered` entry (`rule=child_done`, `stage`, `total`, `target_*`,+ `outcome`: `woke`, `notified`, `merged` or `none`) is the record.++People manage it, agents cannot. `GET /api/issues/{id}/system-wakeups`+describes what the parent is waiting for (lowest open stage or every+sub-issue, remaining, target, why no run would start) with the row's `id`,+`revision`, `enabled`, `instruction`, `default_instruction`, `customized` and+`paused_reason`. `PUT /api/issues/{id}/system-wakeups/child_done` accepts a+partial body from a member (403 for an agent), creates the row if needed, sets+`customized_at`, clears a pause when turning it on, and records what already+holds so facts that closed while it was off do not fire. The ordinary+per-rule endpoints (update, enable, disable, instruction, trigger, delete)+reject system rows. The workspace default lives in the settings keys+`system_wakeup_child_done` (only an explicit `false` turns it off) and+`system_wakeup_child_done_instruction`, edited under Settings → Wakeups through+`GET /api/system-wakeups` and `PUT /api/system-wakeups/child_done` (owners and+admins). Changing the default applies to every rule nobody customized and the+platform did not pause, re-baselining the ones it turns on.++Open parents that predate the rule get it from the sweep job's one-time+backfill, with what already holds recorded so nothing fires. Whichever writer+creates a rule (the backfill or processing a change), sub-issues whose closing+is recorded in `issue_child_event` but not yet processed count as still open+in its baseline, so that closing still wakes the assignee. System rows do not count+toward the per-issue and per-workspace capacity (`guard_issue_wakeup_capacity`).++Migrations 553–560 are additive for existing rows. Deploy them before the+server and the server before clients; older clients ignore the new fields.+Issue and workspace deletion remove the rows with the issue's other wakeups+and `issue_child_event` rows.++## Repeat runs: acknowledged and merged firings++Runs are serialized per issue and agent (`ClaimAgentTask`), so a wakeup never+runs beside another run of its agent, but it can queue behind one and repeat it.+Pending runs are unique per issue, agent and scope (`comment_thread_id`, which+is the rule id for wakeup runs), so an assignment run, a comment run and each+rule's run used to queue separately. Every rule, the system rule included, now+checks two things before it creates a run:++- **Acknowledged.** Every input came from the target agent itself. An issue,+ comment, reaction or attachment event whose single actor is the agent never+ wakes it (task events, times, "wake now" and deadlines never count as the+ agent's own). A `condition.met` input counts when the rule is the platform's+ or its creating run belonged to the agent, and every run that caused it is+ the agent's unfinished run on this issue. Causes travel with the hints:+ captured events carry `source_task_id`, and `issue_child_event.source_task_id`+ records `multica.source_task_id` for closing, leaving and restaging (adding+ or reopening a sub-issue satisfies nothing and is ignored). A person's+ condition rule still runs after the agent's own change, because the running+ agent does not have its instruction. The inputs are consumed with a+ `wakeup_triggered` entry (`outcome=acknowledged`). This is the #8849 fix: a+ coordinator closing its own stage is not woken again while that run is going.+- **Merged.** The agent has a queued run on the issue that runs as the same+ person the rule's own run would: the rule's creator, or for `child_done` the+ person `childDoneRunAs` resolves from the parent. The rule then starts+ nothing and keeps its inputs (`FindWaitingIssueRun`); timers advance and a+ `once` rule stays on, as while its own run is claimed. When a daemon that+ advertises `joined-wakeups-v1` claims that run, `JoinWaitingWakeups` runs+ after every claim gate. For each waiting rule, locked with `SKIP LOCKED`, it+ checks that the rule is on, has no run of its own, targets this agent, runs+ as this run's originator, the creator may still use the agent, the inputs+ are not the agent's own and do not close a loop. It then reserves the inputs+ for the run (`issue_wakeup_receipt.task_id`, still unprocessed), adds the+ rule's chain to the run's `wakeup_chain` and appends `{wakeup_id,+ wakeup_revision, note}` to the run's `context.wakeup_joined`. The claim+ response carries the notes as `wakeup_joined`; the daemon renders them as a+ `[WAKEUP — joined this run]` block for every prompt kind.+- **Settling a merge.** Reserved inputs stay the rule's until the run starts.+ On the rule's next dispatch (`takenReceipts`): inputs of a run that has+ started are consumed into it, count as a firing (a `once` rule ends, a+ merge counts toward `max_fires` and can pause the rule there) and write a+ `wakeup_triggered` entry (`outcome=merged`, `task_id`); inputs of a run that+ ended without starting go back to the rule, which then handles them like+ any other input; inputs of a run that has not started yet keep waiting.+ Turning a rule off, deleting it or changing it discards its pending inputs,+ reserved ones included. A later claim of the same run (after a claim that+ did not go through) checks every entry again and drops the ones whose rule+ no longer has inputs reserved for it or may no longer reach the run.++Nothing is consumed before the run starts, so a rule never loses inputs to a+run that does not run them: if the waiting run is cancelled, fails before+starting, or an older daemon claims it, the rule still has its inputs and+starts its own run on a later tick. Joining skips the hourly run limit, which+counts the rule's own runs; every join needs a run some other trigger queued,+so joins alone cannot run away. The create form tells a member when a reply or+comment rule would wake the issue's agent assignee, whose comment-triggered run+it will join.++## Conditions, runaway protection and check-ins++**Conditions.** `condition` on the create/update body is a structured predicate+the scheduler evaluates:++| type | fields | holds when |+| --- | --- | --- |+| `issue_field` | `field=status`, `value` | this issue has that status key |+| `issue_field` | `field=assignee`, `assignee_type`, `assignee_id` | it is assigned to that member, agent or squad |+| `issue_field` | `field=label`, `label_id` | it has that label |+| `issue_field` | `field=property`, `property_id`, `value` | the property's stored value equals `value` |+| `children_done` | optional `stage` | every sub-issue (or every one up to that stage) is closed |+| `pull_request` | `event=checks_finished` or `merged` | a linked PR's checks finished on its current head, or it merged |+| `other_issue` | `issue_id`, `state=done`, `ended` or `in_review` | another issue in the workspace reaches that state |++A condition rule stays `kind=event`. Validation derives the same-issue events+that can change the fact (for example `issue.status_changed`) as hints: the+existing capture triggers record them, and dispatch consumes them only to+evaluate early. The scheduler also re-evaluates every 30 seconds. A satisfied+predicate becomes one `condition.met` receipt carrying the observed facts; the+fingerprint of those facts is kept in `condition_state`, so a repeating rule+fires again only after the predicate turned false or its facts changed (a new PR+head's result, another sub-issue set). States already true at registration fire+on the first check; finished checks from before registration are ignored. The+watched issue's identifier is stored in the condition for display.++**Runaway protection.** Repeating event rules default to `max_fires=20`+(1–1000, any repeating rule may set it); the run that reaches the cap is+created and the rule is paused with `paused_reason=max_fires`. Each wakeup run+stores `wakeup_chain`, the rules that led to it; a rule whose chain already+passes through it twice (a third pass without a person in between) is paused+with `loop`, and an event rule that already started 12 runs in the past hour is+paused with `rate`. Both also set `disabled_at`, so queued runs of the rule are+refused at claim. A member's action carries no source run and so starts a fresh+chain; "wake now" is exempt. Turning a rule back on clears the reason and+restarts the count. `GET /api/issue-wakeup-paused` lists paused rules on open+issues for board cues.++**Check-ins.** `POST /api/issues/{id}/wakeups/{wakeupID}/checkin` (`{ "note" }`,+at most 500 characters) is accepted only from the running task the rule+started, and only for every/cron rules. It stores `wakeup_checkin` in the+task's context and a `wakeup_checkin` activity; completion then skips the+synthesized fallback comment. Comment- and assignment-triggered runs are+unchanged. The `[WAKEUP]` block of a scheduled check gives the exact command,+and the runtime brief states the exception.++**Management.** `POST .../trigger` queues one run as if the rule fired+(creator or admin, refused while the rule is turned off or paused by a loop or+burst), `DELETE .../{wakeupID}` removes the rule and its pending inputs and+withdraws its unstarted runs, and `GET .../runs` returns the latest ten runs+with their triggers, check-in note and whether they commented.++**Timeline and lists.** The service writes `wakeup_created`,+`wakeup_triggered` (not for every/cron runs, which show as runs),+`wakeup_timed_out`, `wakeup_paused` and `wakeup_checkin` activities with a+snapshot of the rule, published after commit. The workspace list adds a+`source` filter and column (`member`, `agent`, `system`), a `paused` scope,+`runs_7d`, and the child-done system rule of each open parent still waiting on+sub-issues (a row once the rule exists; its target is the parent's assignee). The issue header shows what+the issue is waiting for and opens the Wakeups section; board cards say it in a+few words, or that a rule was paused.++Migrations 557–560 are additive (new columns, a table with its trigger, and two+concurrent indexes). Deploy them before the server and the server before the+clients; older clients ignore the new fields, and older servers read as "no+condition, not paused" in new clients.diff --git a/e2e/issue-wakeups.spec.ts b/e2e/issue-wakeups.spec.tsnew file mode 100644index 0000000000..49b9f4bec3--- /dev/null+++ b/e2e/issue-wakeups.spec.ts@@ -0,0 +1,170 @@+import "./env";++import { expect, test } from "@playwright/test";+import pg from "pg";+import { createTestApi } from "./helpers";++// Rule semantics live in the Go service and handler tests. This browser test+// covers the sidebar a member uses: the platform's child-done rule is visible+// and can be turned off, and a new wakeup can be created from the form.+test("members see the child-done system rule and create a wakeup", async ({ page }) => {+ test.setTimeout(120_000);+ const api = await createTestApi();+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ let runtimeId: string | undefined;+ let agentId: string | undefined;+ try {+ const workspace = (await api.getWorkspaces())[0]!;+ const user = await db.query<{ id: string }>(`SELECT id FROM "user" WHERE email = $1`, [api.getEmail()]);+ const userId = user.rows[0]!.id;+ const runtime = await db.query<{ id: string }>(+ `INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at)+ VALUES ($1, 'Wakeup verification', 'cloud', 'e2e_wakeups', 'online', 'E2E fixture', '{}'::jsonb, $2, now()) RETURNING id`,+ [workspace.id, userId],+ );+ runtimeId = runtime.rows[0]!.id;+ const agent = await db.query<{ id: string }>(+ `INSERT INTO agent (workspace_id, name, description, instructions, runtime_mode, runtime_config, runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id)+ VALUES ($1, 'Wakeup Emacs', '', '', 'cloud', '{}'::jsonb, $2, 'private', 'private', 1, $3) RETURNING id`,+ [workspace.id, runtimeId, userId],+ );+ agentId = agent.rows[0]!.id;+ const parent = await api.createIssue("Migrate attachments to multipart upload", { status: "in_progress" });+ // Assign without starting an unrelated assignment run.+ await db.query(`UPDATE issue SET assignee_type = 'agent', assignee_id = $1 WHERE id = $2`, [agentId, parent.id]);+ await api.createIssue("Design the multipart API", { parent_issue_id: parent.id, stage: 1, status: "done" });+ await api.createIssue("Measure attachment sizes", { parent_issue_id: parent.id, stage: 1, status: "in_progress" });+ await api.createIssue("Server-side multipart upload", { parent_issue_id: parent.id, stage: 2, status: "backlog" });++ await page.addInitScript((token) => {+ localStorage.setItem("multica_token", token!);+ localStorage.setItem("multica:chat:isOpen", "false");+ }, api.getToken());+ await page.setViewportSize({ width: 1440, height: 1000 });+ await page.goto(`/${workspace.slug}/issues/${parent.id}`, { waitUntil: "domcontentloaded" });++ const systemRule = page.getByRole("button", { name: /When stage 1's sub-issues all finish/ });+ await expect(systemRule).toBeVisible({ timeout: 45_000 });+ await expect(systemRule).toContainText("Wake assignee Wakeup Emacs · 1 to go");++ await page.getByRole("button", { name: "New wakeup" }).click();+ const form = page.getByRole("form", { name: "New wakeup" });+ await expect(form).toBeVisible();+ await form.getByRole("button", { name: /Choose a condition/ }).click();+ await page.getByRole("menuitem", { name: /Someone replies/ }).click();+ await form.getByLabel("What to do when woken").fill("Continue stage 2 with the confirmed plan.");+ await form.getByRole("button", { name: /Wait up to/ }).click();+ await page.getByRole("menuitemradio", { name: "3 days" }).click();+ await form.getByRole("button", { name: /^Create/ }).click();+ await expect(form).toBeHidden();++ const created = page.getByRole("button", { name: /When this issue receives a new comment/ });+ await expect(created).toBeVisible();+ await expect(created).toContainText("Wake Wakeup Emacs · Trigger once · 2d 23h left");+ const stored = await db.query<{ expiry_seconds: string; on_timeout: string; created_by: string }>(+ `SELECT expiry_seconds, on_timeout, created_by FROM issue_wakeup WHERE issue_id = $1 AND system_rule IS NULL`,+ [parent.id],+ );+ expect(stored.rows).toEqual([{ expiry_seconds: "259200", on_timeout: "wake", created_by: userId }]);++ await page.getByRole("switch", { name: "Wake the assignee when sub-issues finish" }).first().click();+ await expect(systemRule).toContainText("Turned off for this issue");+ const override = await db.query<{ enabled: boolean; customized: boolean }>(+ `SELECT enabled, customized_at IS NOT NULL AS customized FROM issue_wakeup WHERE issue_id = $1 AND system_rule = 'child_done'`,+ [parent.id],+ );+ expect(override.rows).toEqual([{ enabled: false, customized: true }]);+ } finally {+ await api.cleanup();+ if (agentId) await db.query(`DELETE FROM agent WHERE id = $1`, [agentId]);+ if (runtimeId) await db.query(`DELETE FROM agent_runtime WHERE id = $1`, [runtimeId]);+ await db.end();+ }+});++// A condition is checked by the platform: the issue header says what it waits+// for, the scheduler wakes the agent once it holds, and the timeline and the+// workspace list show the rule and its run.+test("a member waits for a condition the platform checks", async ({ page }) => {+ test.setTimeout(150_000);+ const api = await createTestApi();+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ let runtimeId: string | undefined;+ let agentId: string | undefined;+ try {+ const workspace = (await api.getWorkspaces())[0]!;+ const user = await db.query<{ id: string }>(`SELECT id FROM "user" WHERE email = $1`, [api.getEmail()]);+ const userId = user.rows[0]!.id;+ const runtime = await db.query<{ id: string }>(+ `INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at)+ VALUES ($1, 'Condition verification', 'cloud', 'e2e_wakeups', 'online', 'E2E fixture', '{}'::jsonb, $2, now()) RETURNING id`,+ [workspace.id, userId],+ );+ runtimeId = runtime.rows[0]!.id;+ const agent = await db.query<{ id: string }>(+ `INSERT INTO agent (workspace_id, name, description, instructions, runtime_mode, runtime_config, runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id)+ VALUES ($1, 'Condition Grok', '', '', 'cloud', '{}'::jsonb, $2, 'private', 'private', 1, $3) RETURNING id`,+ [workspace.id, runtimeId, userId],+ );+ agentId = agent.rows[0]!.id;+ const issue = await api.createIssue("Review the upload design", { status: "in_progress" });+ await db.query(`UPDATE issue SET assignee_type = 'agent', assignee_id = $1 WHERE id = $2`, [agentId, issue.id]);++ await page.addInitScript((token) => {+ localStorage.setItem("multica_token", token!);+ localStorage.setItem("multica:chat:isOpen", "false");+ }, api.getToken());+ await page.setViewportSize({ width: 1440, height: 1000 });+ await page.goto(`/${workspace.slug}/issues/${issue.id}`, { waitUntil: "domcontentloaded" });++ await page.getByRole("button", { name: "New wakeup" }).click({ timeout: 45_000 });+ const form = page.getByRole("form", { name: "New wakeup" });+ await form.getByRole("button", { name: /Choose a condition/ }).click();+ await page.getByRole("menuitem", { name: /A field changes to a value/ }).click();+ await form.getByRole("button", { name: /Choose a status/ }).click();+ await page.getByRole("menuitemradio", { name: "In Review" }).click();+ await form.getByLabel("What to do when woken").fill("Review the design once it is ready.");+ await form.getByRole("button", { name: /^Create/ }).click();+ await expect(form).toBeHidden();++ const rule = page.getByRole("button", { name: /When this issue moves to In Review/ });+ await expect(rule).toBeVisible();+ await expect(page.getByRole("button", { name: /Condition Grok: Waiting for In Review/ })).toBeVisible();+ const stored = await db.query<{ id: string; condition: unknown; event_types: string[] }>(+ `SELECT id, condition, event_types FROM issue_wakeup WHERE issue_id = $1`,+ [issue.id],+ );+ expect(stored.rows[0]).toMatchObject({+ condition: { type: "issue_field", field: "status", value: "in_review" },+ event_types: ["issue.status_changed"],+ });++ // The status change only prompts a check; the scheduler starts the run.+ await api.updateIssue(issue.id, { status: "in_review" });+ await expect+ .poll(+ async () =>+ (await db.query(`SELECT count(*)::int AS n FROM agent_task_queue WHERE context->>'wakeup_id' = $1`, [stored.rows[0]!.id])).rows[0]!.n,+ { timeout: 75_000, intervals: [2_000] },+ )+ .toBe(1);+ await expect(page.getByText("When this issue moves to In Review · woke Condition Grok")).toBeVisible({ timeout: 20_000 });++ await page.goto(`/${workspace.slug}/autopilots?tab=wakeups`, { waitUntil: "domcontentloaded" });+ await page.getByRole("button", { name: /^All/ }).click();+ const row = page.getByRole("row", { name: /Review the upload design/ });+ await expect(row).toContainText("When this issue moves to In Review");+ await expect(row).toContainText("1");+ await expect(page.getByRole("columnheader", { name: "Runs (7 days)" })).toBeVisible();+ } finally {+ await api.cleanup();+ if (agentId) {+ await db.query(`DELETE FROM agent_task_queue WHERE agent_id = $1`, [agentId]);+ await db.query(`DELETE FROM agent WHERE id = $1`, [agentId]);+ }+ if (runtimeId) await db.query(`DELETE FROM agent_runtime WHERE id = $1`, [runtimeId]);+ await db.end();+ }+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 2440ec15e3..28e6089071 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1,6 +1,6 @@-import type { IssueWakeup, IssueWakeupSummaryRow } from "../types/issue-wakeup";+import type { IssueWakeup, IssueWakeupInput, IssueWakeupSummaryRow, PausedWakeup, SystemWakeup, WakeupRun, WorkspaceSystemWakeup } from "../types/issue-wakeup";import type { WorkspaceWakeupPage, WorkspaceWakeupFilters } from "../types/issue-wakeup";-import { WorkspaceWakeupPageSchema, IssueWakeupSchema, IssueWakeupSummaryRowSchema } from "./schemas";+import { WorkspaceWakeupPageSchema, IssueWakeupSchema, IssueWakeupSummaryRowSchema, PausedWakeupSchema, SystemWakeupSchema, WakeupRunSchema, WorkspaceSystemWakeupSchema } from "./schemas";import type { InboxFilters } from "../inbox/filter-store";import type { ArchivedInboxPage, ArchivedInboxFacets } from "../types/inbox";import { configStore } from "../config";@@ -1283,6 +1283,52 @@ export class ApiClient {await this.fetch(`/api/issues/${encodeURIComponent(issueId)}/wakeups/${encodeURIComponent(wakeupId)}/instruction`, { method: "PATCH", body: JSON.stringify(input) });}+ async createIssueWakeup(issueId: string, input: IssueWakeupInput): Promise<void> {+ await this.fetch(`/api/issues/${encodeURIComponent(issueId)}/wakeups`, { method: "POST", body: JSON.stringify(input) });+ }++ async listIssueSystemWakeups(issueId: string): Promise<SystemWakeup[]> {+ const raw = await this.fetch<unknown>(`/api/issues/${encodeURIComponent(issueId)}/system-wakeups`);+ const parsed = parseWithFallback<SystemWakeup[] | null>(raw, SystemWakeupSchema.array(), null, { endpoint: "GET /api/issues/:id/system-wakeups" });+ if (!parsed) throw new Error("Could not load system wakeups");+ return parsed;+ }++ async listIssueWakeupRuns(issueId: string, wakeupId: string): Promise<WakeupRun[]> {+ const raw = await this.fetch<unknown>(`/api/issues/${encodeURIComponent(issueId)}/wakeups/${encodeURIComponent(wakeupId)}/runs`);+ const parsed = parseWithFallback<WakeupRun[] | null>(raw, WakeupRunSchema.array(), null, { endpoint: "GET /api/issues/:id/wakeups/:wakeupId/runs" });+ if (!parsed) throw new Error("Could not load wakeup runs");+ return parsed;+ }++ async listPausedWakeups(): Promise<PausedWakeup[]> {+ const raw = await this.fetch<unknown>("/api/issue-wakeup-paused");+ return parseWithFallback<PausedWakeup[]>(raw, PausedWakeupSchema.array(), [], { endpoint: "GET /api/issue-wakeup-paused" });+ }++ async triggerIssueWakeup(issueId: string, wakeupId: string): Promise<void> {+ await this.fetch(`/api/issues/${encodeURIComponent(issueId)}/wakeups/${encodeURIComponent(wakeupId)}/trigger`, { method: "POST" });+ }++ async deleteIssueWakeup(issueId: string, wakeupId: string): Promise<void> {+ await this.fetch(`/api/issues/${encodeURIComponent(issueId)}/wakeups/${encodeURIComponent(wakeupId)}`, { method: "DELETE" });+ }++ async updateIssueSystemWakeup(issueId: string, rule: SystemWakeup["rule"], input: { enabled?: boolean; instruction?: string }): Promise<void> {+ await this.fetch(`/api/issues/${encodeURIComponent(issueId)}/system-wakeups/${encodeURIComponent(rule)}`, { method: "PUT", body: JSON.stringify(input) });+ }++ async listWorkspaceSystemWakeups(): Promise<WorkspaceSystemWakeup[]> {+ const raw = await this.fetch<unknown>("/api/system-wakeups");+ const parsed = parseWithFallback<WorkspaceSystemWakeup[] | null>(raw, WorkspaceSystemWakeupSchema.array(), null, { endpoint: "GET /api/system-wakeups" });+ if (!parsed) throw new Error("Could not load system wakeups");+ return parsed;+ }++ async updateWorkspaceSystemWakeup(rule: WorkspaceSystemWakeup["rule"], input: { enabled?: boolean; instruction?: string }): Promise<void> {+ await this.fetch(`/api/system-wakeups/${encodeURIComponent(rule)}`, { method: "PUT", body: JSON.stringify(input) });+ }+async disableIssueWakeup(issueId: string, wakeupId: string): Promise<void> {await this.fetch(`/api/issues/${encodeURIComponent(issueId)}/wakeups/${encodeURIComponent(wakeupId)}/disable`, { method: "POST" });}diff --git a/packages/core/api/issue-wakeup.test.ts b/packages/core/api/issue-wakeup.test.tsindex 6de092cfdb..cd88bf5238 100644--- a/packages/core/api/issue-wakeup.test.ts+++ b/packages/core/api/issue-wakeup.test.ts@@ -50,6 +50,7 @@ it("preserves empty summaries", async () => {const inventoryFilters = {scope: "active",kind: "all",+ source: "",search: "",agent_id: "",offset: 0,@@ -83,7 +84,7 @@ it("preserves an empty page and its inventory counts", async () => {offset: 150,search: "CI & release",}),- ).resolves.toEqual(page);+ ).resolves.toEqual({ ...page, counts: { ...page.counts, paused: 0 } });expect(fetcher.mock.calls[0]![0]).toContain("search=CI+%26+release");expect(fetcher.mock.calls[0]![0]).toContain("offset=150");});@@ -154,3 +155,115 @@ it("edits instructions through the scoped endpoint and propagates conflicts", asfetch.mockResolvedValue(new Response('{"error":"conflict"}', { status: 409 }));await expect(client.editIssueWakeupInstruction("issue", "wake", input)).rejects.toThrow();});++it("parses rule deadlines and the creator, tolerating an unknown timeout action", async () => {+ const row = {+ id: "wake", issue_id: "issue", agent_id: "agent", agent_name: "Emacs", instruction: "x",+ kind: "event", mode: "once", event_types: ["comment.created"], filter_agent_id: null,+ filter_task_id: null, interval_seconds: null, cron_expression: null, timezone: "UTC",+ next_fire_at: null, enabled: true, disabled_at: null, last_task_id: null, last_error: null,+ expires_at: "2026-09-27T08:00:00Z", expiry_seconds: 259200, on_timeout: "escalate",+ timed_out_at: null, created_by_agent: true, created_by_name: "Jiayuan",+ source_agent_id: "agent", source_agent_name: "Emacs",+ };+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify([row]))));+ const [parsed] = await client.listIssueWakeups("issue");+ expect(parsed).toMatchObject({ expires_at: row.expires_at, expiry_seconds: 259200, on_timeout: null, created_by_agent: true, source_agent_name: "Emacs" });+});+it("creates a wakeup with its full configuration", async () => {+ const fetcher = vi.fn().mockResolvedValue(new Response("{}", { status: 201 }));+ vi.stubGlobal("fetch", fetcher);+ await client.createIssueWakeup("issue", { agent_id: "agent", instruction: "x", kind: "event", event_types: ["comment.created"], expires_in_seconds: 3600, on_timeout: "wake" });+ const [url, init] = fetcher.mock.calls[0]!;+ expect(String(url)).toContain("/api/issues/issue/wakeups");+ expect(init.method).toBe("POST");+ expect(JSON.parse(init.body)).toMatchObject({ expires_in_seconds: 3600, on_timeout: "wake" });+});+it("rejects malformed system wakeups instead of hiding the rule", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify([{ rule: "child_done", enabled: "yes" }]))));+ await expect(client.listIssueSystemWakeups("issue")).rejects.toThrow("Could not load system wakeups");+});+it("parses system wakeups and falls back on an unknown blocked reason", async () => {+ const rule = { rule: "child_done", enabled: true, instruction: "", staged: true, stage: 1, total: 2, remaining: 1, waiting: ["MUL-2"], target: { type: "agent", id: "a", name: "Emacs" }, blocked: "paused" };+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify([rule]))));+ // Fields a server may omit get defaults: the rule reads as on and not yet created.+ await expect(client.listIssueSystemWakeups("issue")).resolves.toEqual([{+ ...rule, blocked: "", workspace_default: true, id: "", revision: 0, default_instruction: "", customized: false, paused_reason: null,+ }]);+});+it("reads a member target and a pause, and drops an unknown target", async () => {+ const base = { id: "r", revision: 3, rule: "child_done", enabled: false, instruction: "", default_instruction: "Advance.", customized: true,+ staged: false, stage: null, total: 1, remaining: 1, waiting: [], blocked: "member_assignee", workspace_default: true };+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify([+ { ...base, paused_reason: "rate", target: { type: "member", id: "u", name: "Jiayuan" } },+ { ...base, paused_reason: "someday", target: { type: "robot", id: "x", name: "?" } },+ ]))));+ const [member, unknown] = await client.listIssueSystemWakeups("issue");+ expect(member).toMatchObject({ paused_reason: "rate", target: { type: "member", name: "Jiayuan" }, customized: true });+ expect(unknown).toMatchObject({ paused_reason: null, target: null });+});+it("reads workspace defaults and rejects a malformed list", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify([{ rule: "child_done", enabled: false, customized: 2 }]))));+ await expect(client.listWorkspaceSystemWakeups()).resolves.toEqual([+ { rule: "child_done", enabled: false, instruction: "", builtin_instruction: "", customized: 2 },+ ]);+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify([{ rule: "other" }]))));+ await expect(client.listWorkspaceSystemWakeups()).rejects.toThrow("Could not load system wakeups");+});+it("sends a workspace default change", async () => {+ const fetcher = vi.fn().mockResolvedValue(new Response("[]"));+ vi.stubGlobal("fetch", fetcher);+ await client.updateWorkspaceSystemWakeup("child_done", { enabled: false });+ const [url, init] = fetcher.mock.calls[0]!;+ expect(String(url)).toContain("/api/system-wakeups/child_done");+ expect(init.method).toBe("PUT");+ expect(JSON.parse(init.body)).toEqual({ enabled: false });+});++it("reads conditions, caps and pauses, and drops shapes it does not know", async () => {+ const base = {+ id: "w", issue_id: "i", agent_id: "a", agent_name: "Emacs", instruction: "go", kind: "event", mode: "continuous",+ event_types: ["issue.status_changed"], filter_agent_id: null, filter_task_id: null, interval_seconds: null,+ cron_expression: null, timezone: "UTC", next_fire_at: null, enabled: false, disabled_at: null,+ last_task_id: null, last_error: null,+ };+ const rows = [+ { ...base, condition: { type: "issue_field", field: "status", value: "in_review" }, max_fires: 20, fire_count: 20, paused_reason: "max_fires" },+ { ...base, id: "w2", condition: { type: "future_kind" }, paused_reason: "someday" },+ { ...base, id: "w3", condition: { type: "other_issue", issue_id: "x", state: "done", identifier: "MUL-2" } },+ ];+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify(rows))));+ const [known, unknown, other] = await client.listIssueWakeups("i");+ expect(known).toMatchObject({ condition: { field: "status", value: "in_review" }, max_fires: 20, fire_count: 20, paused_reason: "max_fires" });+ expect(unknown).toMatchObject({ condition: null, paused_reason: null });+ expect(other!.condition).toEqual({ type: "other_issue", issue_id: "x", state: "done", identifier: "MUL-2" });+});++it("reads system rule rows in the workspace list", async () => {+ const page = {+ items: [{+ id: "p", issue_id: "p", issue_title: "Parent", issue_identifier: "MUL-1", issue_closed: false, can_manage: true,+ active_runs: 0, task: null, agent_id: null, agent_name: "", instruction: undefined, kind: "event", mode: "continuous",+ event_types: [], filter_agent_id: null, filter_task_id: null, interval_seconds: null, cron_expression: null,+ timezone: "UTC", next_fire_at: null, enabled: true, disabled_at: null, last_task_id: null, last_error: null,+ revision: null, source: "system", rule: "child_done", system_stage: 2, system_remaining: 1, runs_7d: 3,+ }],+ total: 1, counts: { all: 1, active: 1, paused: 0, disabled: 0, ended: 0 }, agents: [],+ };+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify(page))));+ const result = await client.listWorkspaceWakeups(inventoryFilters);+ expect(result.items[0]).toMatchObject({ agent_id: "", source: "system", rule: "child_done", system_stage: 2, runs_7d: 3 });+ expect(result.items[0]!.revision).toBeUndefined();+});++it("loads a rule's runs and the paused list", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(new Response(JSON.stringify([+ { id: "r", status: "completed", created_at: "2026-09-24T00:00:00Z", started_at: null, completed_at: null, checkin_note: "ok", triggers: ["time.due"], commented: false },+ ]))).mockResolvedValueOnce(new Response(JSON.stringify([+ { issue_id: "i", id: "w", agent_id: "a", paused_reason: "loop" },+ ]))));+ await expect(client.listIssueWakeupRuns("i", "w")).resolves.toEqual([+ expect.objectContaining({ id: "r", checkin_note: "ok", triggers: ["time.due"], commented: false }),+ ]);+ await expect(client.listPausedWakeups()).resolves.toEqual([{ issue_id: "i", id: "w", agent_id: "a", paused_reason: "loop" }]);+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 2801bc3952..8526df45c9 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -3548,6 +3548,28 @@ export const EMPTY_JOIN_SHARE_LINK_RESPONSE: {workspace_slug: "",};+export const WakeupConditionSchema = z.union([+ z.object({ type: z.literal("issue_field"), field: z.literal("status"), value: z.string() }),+ z.object({ type: z.literal("issue_field"), field: z.literal("assignee"), assignee_type: z.enum(["member", "agent", "squad"]), assignee_id: z.string() }),+ z.object({ type: z.literal("issue_field"), field: z.literal("label"), label_id: z.string() }),+ z.object({ type: z.literal("issue_field"), field: z.literal("property"), property_id: z.string(), value: z.unknown() }),+ z.object({ type: z.literal("children_done"), stage: z.number().int().nullish() }),+ z.object({ type: z.literal("pull_request"), event: z.enum(["checks_finished", "merged"]) }),+ z.object({ type: z.literal("other_issue"), issue_id: z.string(), state: z.enum(["done", "ended", "in_review"]), identifier: z.string().optional() }),+]);++export const WakeupRunSchema = z.object({+ id: z.string(), status: z.string(), created_at: z.string(),+ started_at: z.string().nullable(), completed_at: z.string().nullable(),+ checkin_note: z.string().default(""), triggers: z.array(z.string()).default([]),+ commented: z.boolean().default(false),+});++export const PausedWakeupSchema = z.object({+ issue_id: z.string(), id: z.string(), agent_id: z.string(),+ paused_reason: z.enum(["max_fires", "loop", "rate"]).catch("rate"),+});+export const IssueWakeupSchema = z.object({id: z.string(), issue_id: z.string(), agent_id: z.string(), agent_name: z.string().default(""),instruction: z.string(), kind: z.enum(["event", "at", "every", "cron"]), mode: z.enum(["once", "continuous"]),@@ -3560,13 +3582,38 @@ export const IssueWakeupSchema = z.object({filter_actor_name: z.string().nullable().optional(),revision: z.number().int().positive().optional(),filter_agent_name: z.string().nullable().optional(), last_task_status: z.string().nullable().optional(),+ expires_at: z.string().nullish(), expiry_seconds: z.number().nullish(),+ on_timeout: z.enum(["wake", "end"]).nullish().catch(null), timed_out_at: z.string().nullish(),+ created_by_agent: z.boolean().optional(), created_by_name: z.string().nullish(),+ source_agent_id: z.string().nullish(), source_agent_name: z.string().nullish(),+ // An unknown condition shape from a newer server reads as "no condition".+ condition: WakeupConditionSchema.nullish().catch(null),+ max_fires: z.number().int().nullish(), fire_count: z.number().int().nonnegative().optional().catch(undefined),+ paused_reason: z.enum(["max_fires", "loop", "rate"]).nullish().catch(null),+});++export const SystemWakeupSchema = z.object({+ id: z.string().default(""), revision: z.number().int().nonnegative().default(0),+ rule: z.literal("child_done"), enabled: z.boolean(), instruction: z.string().default(""),+ default_instruction: z.string().default(""), customized: z.boolean().default(false),+ paused_reason: z.enum(["max_fires", "loop", "rate"]).nullish().catch(null).transform((v) => v ?? null),+ staged: z.boolean(), stage: z.number().int().nullable(), total: z.number().int().nonnegative(),+ remaining: z.number().int().nonnegative(), waiting: z.array(z.string()).default([]),+ target: z.object({ type: z.enum(["agent", "squad", "member"]), id: z.string(), name: z.string() }).nullable().catch(null),+ blocked: z.enum(["", "backlog", "member_assignee", "no_assignee"]).catch(""),+ workspace_default: z.boolean().default(true),+});++export const WorkspaceSystemWakeupSchema = z.object({+ rule: z.literal("child_done"), enabled: z.boolean().default(true), instruction: z.string().default(""),+ builtin_instruction: z.string().default(""), customized: z.number().int().nonnegative().default(0),});export const IssueWakeupSummaryRowSchema = IssueWakeupSchema.pick({id: true, issue_id: true, agent_id: true, agent_name: true, kind: true, mode: true,event_types: true, filter_task_id: true, filter_agent_name: true, interval_seconds: true,filter_actor_type: true, filter_actor_id: true, filter_actor_name: true,- cron_expression: true, timezone: true, next_fire_at: true,+ cron_expression: true, timezone: true, next_fire_at: true, condition: true,}).extend({ active_count: z.number().int().positive(), event_count: z.number().int().nonnegative() });export const WorkspaceWakeupPageSchema = z.object({@@ -3574,10 +3621,20 @@ export const WorkspaceWakeupPageSchema = z.object({issue_title: z.string(), issue_identifier: z.string(), issue_closed: z.boolean(),can_manage: z.boolean(), active_runs: z.number().int().nonnegative(),task: AgentTaskSchema.nullable(),+ // System rule rows have no target when the issue has no agent assignee,+ // and no revision.+ agent_id: z.string().nullish().transform((v) => v ?? ""),+ revision: z.number().int().positive().nullish().catch(undefined).transform((v) => v ?? undefined),+ source: z.enum(["member", "agent", "system"]).catch("member").default("member"),+ runs_7d: z.number().int().nonnegative().default(0),+ rule: z.literal("child_done").nullish().catch(null),+ system_stage: z.number().int().nullish(), system_remaining: z.number().int().nullish(),+ target_type: z.string().nullish(),})),total: z.number().int().nonnegative(),counts: z.object({active: z.number().int().nonnegative(), all: z.number().int().nonnegative(),+ paused: z.number().int().nonnegative().default(0),disabled: z.number().int().nonnegative(), ended: z.number().int().nonnegative(),}),agents: z.array(z.object({ id: z.string(), name: z.string() })),diff --git a/packages/core/issues/wakeups.ts b/packages/core/issues/wakeups.tsindex f8b42452c8..5f3b782e62 100644--- a/packages/core/issues/wakeups.ts+++ b/packages/core/issues/wakeups.ts@@ -3,7 +3,7 @@ import {useMutation,useQueryClient,} from "@tanstack/react-query";-import type { WorkspaceWakeupFilters } from "../types";+import type { IssueWakeupInput, SystemWakeup, WorkspaceSystemWakeup, WorkspaceWakeupFilters } from "../types";import { api } from "../api";import { issueKeys } from "./queries";@@ -25,24 +25,113 @@ export function issueWakeupsOptions(workspaceId: string, issueId: string) {});}+export function issueSystemWakeupsOptions(workspaceId: string, issueId: string) {+ return queryOptions({+ queryKey: ["issue-system-wakeups", workspaceId, issueId],+ queryFn: () => api.listIssueSystemWakeups(issueId),+ enabled: !!workspaceId && !!issueId,+ refetchInterval: 10_000,+ });+}++export function useCreateIssueWakeup(workspaceId: string, issueId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: (input: IssueWakeupInput) => api.createIssueWakeup(issueId, input),+ onSettled: () => invalidateIssueWakeups(client, workspaceId, issueId),+ });+}++export function useUpdateIssueSystemWakeup(workspaceId: string, issueId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: ({ rule, ...input }: { rule: SystemWakeup["rule"]; enabled?: boolean; instruction?: string }) =>+ api.updateIssueSystemWakeup(issueId, rule, input),+ onSettled: () =>+ Promise.all([+ client.invalidateQueries({ queryKey: issueSystemWakeupsOptions(workspaceId, issueId).queryKey }),+ client.invalidateQueries({ queryKey: ["workspace-wakeups", workspaceId] }),+ ]),+ });+}++/** Workspace defaults of the platform's rules, for Settings. */+export function workspaceSystemWakeupsOptions(workspaceId: string) {+ return queryOptions({+ queryKey: ["workspace-system-wakeups", workspaceId],+ queryFn: () => api.listWorkspaceSystemWakeups(),+ enabled: !!workspaceId,+ });+}++/** Changing a default reaches every issue that did not set its own. */+export function useUpdateWorkspaceSystemWakeup(workspaceId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: ({ rule, ...input }: { rule: WorkspaceSystemWakeup["rule"]; enabled?: boolean; instruction?: string }) =>+ api.updateWorkspaceSystemWakeup(rule, input),+ onSettled: () =>+ Promise.all([+ client.invalidateQueries({ queryKey: workspaceSystemWakeupsOptions(workspaceId).queryKey }),+ client.invalidateQueries({ queryKey: ["issue-system-wakeups", workspaceId] }),+ client.invalidateQueries({ queryKey: ["workspace-wakeups", workspaceId] }),+ ]),+ });+}++/** The latest runs a rule started, for its trigger history. */+export function issueWakeupRunsOptions(workspaceId: string, issueId: string, wakeupId: string) {+ return queryOptions({+ queryKey: ["issue-wakeup-runs", workspaceId, issueId, wakeupId],+ queryFn: () => api.listIssueWakeupRuns(issueId, wakeupId),+ enabled: !!workspaceId && !!issueId && !!wakeupId,+ staleTime: 10_000,+ });+}++/** Rules the platform paused on open issues, for board cues. */+export function pausedWakeupsOptions(workspaceId: string) {+ return queryOptions({+ queryKey: ["issue-wakeup-paused", workspaceId],+ queryFn: () => api.listPausedWakeups(),+ enabled: !!workspaceId,+ staleTime: 10_000,+ });+}++function invalidateIssueWakeups(client: ReturnType<typeof useQueryClient>, workspaceId: string, issueId: string) {+ return Promise.all([+ client.invalidateQueries({ queryKey: ["workspace-wakeups", workspaceId] }),+ client.invalidateQueries({ queryKey: issueWakeupsOptions(workspaceId, issueId).queryKey }),+ client.invalidateQueries({ queryKey: workspaceWakeupSummariesOptions(workspaceId).queryKey }),+ client.invalidateQueries({ queryKey: pausedWakeupsOptions(workspaceId).queryKey }),+ client.invalidateQueries({ queryKey: ["issue-wakeup-runs", workspaceId, issueId] }),+ client.invalidateQueries({ queryKey: issueKeys.tasks(issueId) }),+ ]);+}++/** "Wake now": one run of the rule, as if it fired. */+export function useTriggerIssueWakeup(workspaceId: string, issueId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: (id: string) => api.triggerIssueWakeup(issueId, id),+ onSettled: () => invalidateIssueWakeups(client, workspaceId, issueId),+ });+}++export function useDeleteIssueWakeup(workspaceId: string, issueId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: (id: string) => api.deleteIssueWakeup(issueId, id),+ onSettled: () => invalidateIssueWakeups(client, workspaceId, issueId),+ });+}+export function useDisableIssueWakeup(workspaceId: string, issueId: string) {const client = useQueryClient();return useMutation({mutationFn: (id: string) => api.disableIssueWakeup(issueId, id),- onSettled: async () => {- await Promise.all([- client.invalidateQueries({- queryKey: ["workspace-wakeups", workspaceId],- }),- client.invalidateQueries({- queryKey: issueWakeupsOptions(workspaceId, issueId).queryKey,- }),- client.invalidateQueries({- queryKey: workspaceWakeupSummariesOptions(workspaceId).queryKey,- }),- client.invalidateQueries({ queryKey: issueKeys.tasks(issueId) }),- ]);- },+ onSettled: () => invalidateIssueWakeups(client, workspaceId, issueId),});}@@ -58,20 +147,7 @@ export function useEnableIssueWakeup(workspaceId: string, issueId: string) {at?: string;rearm?: boolean;}) => api.enableIssueWakeup(issueId, id, input),- onSettled: async () => {- await Promise.all([- client.invalidateQueries({- queryKey: ["workspace-wakeups", workspaceId],- }),- client.invalidateQueries({- queryKey: issueWakeupsOptions(workspaceId, issueId).queryKey,- }),- client.invalidateQueries({- queryKey: workspaceWakeupSummariesOptions(workspaceId).queryKey,- }),- client.invalidateQueries({ queryKey: issueKeys.tasks(issueId) }),- ]);- },+ onSettled: () => invalidateIssueWakeups(client, workspaceId, issueId),});}@@ -125,6 +201,7 @@ export function useDisableWorkspaceWakeups(workspaceId: string) {client.invalidateQueries({queryKey: ["issue-wakeup-summaries", workspaceId],}),+ client.invalidateQueries({ queryKey: ["issue-wakeup-paused", workspaceId] }),...Array.from(new Set(rows.map((r) => r.issue_id))).map((id) =>client.invalidateQueries({ queryKey: issueKeys.tasks(id) }),),diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.tsindex 4d83c18cab..473ed003a8 100644--- a/packages/core/types/inbox.ts+++ b/packages/core/types/inbox.ts@@ -28,7 +28,10 @@ export type InboxItemType =// System notifications are intentionally issue-less. Keep them in the// same Inbox model so read/archive/realtime behavior remains consistent.| "autopilot_paused"- | "autopilot_quota_exceeded";+ | "autopilot_quota_exceeded"+ // Sub-issues of an issue assigned to the recipient closed (the child_done+ // system rule notifies a member assignee instead of waking an agent).+ | "children_done";/*** One workspace's unread inbox count in the cross-workspace summarydiff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 2dd4557c25..9e67ddad4f 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -339,6 +339,6 @@ export type {WorkspaceSubscriptionSeatReconcileResult,CreateWorkspaceSubscriptionPortalResponse,} from "./billing";-export type { IssueWakeup, WakeupPreview, IssueWakeupSummaryRow } from "./issue-wakeup";+export type { IssueWakeup, IssueWakeupInput, SystemWakeup, WorkspaceSystemWakeup, WakeupPreview, IssueWakeupSummaryRow, WakeupCondition, WakeupPausedReason, WakeupRun, PausedWakeup, WakeupSource } from "./issue-wakeup";export type { WorkspaceWakeup, WorkspaceWakeupPage, WorkspaceWakeupFilters, WakeupScope } from "./issue-wakeup";diff --git a/packages/core/types/issue-wakeup.ts b/packages/core/types/issue-wakeup.tsindex af886d5aee..c608fbc8e5 100644--- a/packages/core/types/issue-wakeup.ts+++ b/packages/core/types/issue-wakeup.ts@@ -23,6 +23,120 @@ export interface IssueWakeup {last_error: string | null;filter_agent_name?: string | null;last_task_status?: string | null;+ /** When the rule ends if nothing triggered it first. */+ expires_at?: string | null;+ /** Set for relative waits: re-enabling restarts the wait from now. */+ expiry_seconds?: number | null;+ on_timeout?: "wake" | "end" | null;+ /** The deadline, not a trigger or a person, ended the rule. */+ timed_out_at?: string | null;+ /** True when an agent run created the rule on behalf of created_by_name. */+ created_by_agent?: boolean;+ created_by_name?: string | null;+ source_agent_id?: string | null;+ source_agent_name?: string | null;+ /** A fact the platform checks itself; null for event and time rules. */+ condition?: WakeupCondition | null;+ /** Repeating rules stop after this many runs. */+ max_fires?: number | null;+ fire_count?: number;+ /** Why the platform, not a person, stopped the rule. */+ paused_reason?: WakeupPausedReason | null;+}++export type WakeupPausedReason = "max_fires" | "loop" | "rate";++/** Structured predicates the platform evaluates (see WakeupCondition in Go). */+export type WakeupCondition =+ | { type: "issue_field"; field: "status"; value: string }+ | { type: "issue_field"; field: "assignee"; assignee_type: "member" | "agent" | "squad"; assignee_id: string }+ | { type: "issue_field"; field: "label"; label_id: string }+ | { type: "issue_field"; field: "property"; property_id: string; value: unknown }+ | { type: "children_done"; stage?: number | null }+ | { type: "pull_request"; event: "checks_finished" | "merged" }+ | { type: "other_issue"; issue_id: string; state: "done" | "ended" | "in_review"; identifier?: string };++/** One run a rule started, for its trigger history. */+export interface WakeupRun {+ id: string;+ status: string;+ created_at: string;+ started_at: string | null;+ completed_at: string | null;+ /** Set when a scheduled check ended silently. */+ checkin_note: string;+ triggers: string[];+ commented: boolean;+}++/** A rule the platform paused on an open issue. */+export interface PausedWakeup {+ issue_id: string;+ id: string;+ agent_id: string;+ paused_reason: WakeupPausedReason;+}++/** Body accepted by POST /api/issues/:id/wakeups. */+export interface IssueWakeupInput {+ agent_id: string;+ instruction: string;+ kind: IssueWakeup["kind"];+ mode?: IssueWakeup["mode"];+ event_types?: string[];+ filter_agent_id?: string;+ filter_actor_type?: "member" | "agent";+ filter_actor_id?: string;+ at?: string;+ interval_seconds?: number;+ cron_expression?: string;+ timezone?: string;+ expires_at?: string;+ expires_in_seconds?: number;+ on_timeout?: "wake" | "end";+ condition?: WakeupCondition;+ max_fires?: number;+}++/**+ * A platform-defined wakeup on one issue. `child_done` wakes the parent's+ * assignee when a stage of its sub-issues closes while a later one waits, and+ * once more when every sub-issue is closed.+ */+export interface SystemWakeup {+ /** Empty until the rule exists on the issue (first sub-issue change or edit). */+ id: string;+ revision: number;+ rule: "child_done";+ enabled: boolean;+ /** Set on this issue; runs get `default_instruction` when it is empty. */+ instruction: string;+ default_instruction: string;+ /** A person changed the rule on this issue; it no longer follows the default. */+ customized: boolean;+ paused_reason: WakeupPausedReason | null;+ /** True while a stage is open; otherwise the rule waits for every sub-issue. */+ staged: boolean;+ stage: number | null;+ total: number;+ remaining: number;+ waiting: string[];+ target: { type: "agent" | "squad" | "member"; id: string; name: string } | null;+ /** Why no run would start now; a member assignee gets an inbox notification. */+ blocked: "" | "backlog" | "member_assignee" | "no_assignee";+ /** The workspace-wide setting, which applies until the issue sets its own. */+ workspace_default: boolean;+}++/** A platform rule's workspace default, edited in Settings. */+export interface WorkspaceSystemWakeup {+ rule: "child_done";+ enabled: boolean;+ /** The workspace's instruction; empty means runs get `builtin_instruction`. */+ instruction: string;+ builtin_instruction: string;+ /** Open issues whose rule a person changed; they ignore this default. */+ customized: number;}export type WakeupPreview = Pick<@@ -43,13 +157,15 @@ export type WakeupPreview = Pick<| "cron_expression"| "timezone"| "next_fire_at"+ | "condition">;export interface IssueWakeupSummaryRow extends WakeupPreview {active_count: number;event_count: number;}-export type WakeupScope = "active" | "all" | "disabled" | "ended";+export type WakeupScope = "active" | "all" | "paused" | "disabled" | "ended";+export type WakeupSource = "member" | "agent" | "system";export interface WorkspaceWakeup extends Omit<IssueWakeup, "instruction"> {issue_title: string;issue_identifier: string;@@ -57,6 +173,14 @@ export interface WorkspaceWakeup extends Omit<IssueWakeup, "instruction"> {can_manage: boolean;active_runs: number;task: import("./agent").AgentTask | null;+ source: WakeupSource;+ /** Runs the rule started in the last seven days. */+ runs_7d: number;+ /** Set on a system rule row, whose id is its issue's id. */+ rule?: SystemWakeup["rule"] | null;+ system_stage?: number | null;+ system_remaining?: number | null;+ target_type?: string | null;}export interface WorkspaceWakeupPage {items: WorkspaceWakeup[];@@ -67,6 +191,7 @@ export interface WorkspaceWakeupPage {export interface WorkspaceWakeupFilters {scope: WakeupScope;kind: "all" | "event" | "at" | "recurring";+ source: "" | WakeupSource;search: string;agent_id: string;offset: number;diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.tsindex d04c4fc016..dfe71f30ea 100644--- a/packages/core/types/issue.ts+++ b/packages/core/types/issue.ts@@ -205,8 +205,8 @@ export interface Issue {project_id: string | null;position: number;// Ordered barrier group among sibling sub-issues (null = unstaged). The- // parent assignee is notified/woken only when every sub-issue in a stage- // finishes; see server/internal/handler/issue_child_done.go.+ // parent assignee is woken when a stage closes while a later one waits;+ // see server/internal/service/issue_wakeup_system.go.stage: number | null;// Calendar days as date-only "YYYY-MM-DD" (no time, no timezone). Use the// helpers in @multica/core/issues/date to format/compare — never `new Date()`diff --git a/packages/views/autopilots/components/autopilots-page.test.tsx b/packages/views/autopilots/components/autopilots-page.test.tsxindex f1187b1828..b3160e1cf9 100644--- a/packages/views/autopilots/components/autopilots-page.test.tsx+++ b/packages/views/autopilots/components/autopilots-page.test.tsx@@ -14,6 +14,7 @@ vi.mock("@multica/core/paths", () => ({}));vi.mock("./workspace-wakeups", () => ({WorkspaceWakeups: () => <div>Wakeup inventory</div>,+ WorkspaceWakeupCreate: ({ open }: { open: boolean }) => (open ? <div>Wakeup create</div> : null),}));vi.mock("./autopilot-dialog", () => ({ AutopilotDialog: () => null }));@@ -59,6 +60,8 @@ it.each(["empty", "error"])(fireEvent.click(screen.getByRole("tab", { name: "Issue wakeups" }));expect(await screen.findByText("Wakeup inventory")).toBeVisible();expect(screen.queryByRole("button", { name: "New autopilot" })).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "New wakeup" }));+ expect(await screen.findByText("Wakeup create")).toBeVisible();fireEvent.click(screen.getByRole("tab", { name: "Autopilot" }),);diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsxindex a773dadb12..b4535b4b0a 100644--- a/packages/views/autopilots/components/autopilots-page.tsx+++ b/packages/views/autopilots/components/autopilots-page.tsx@@ -50,7 +50,7 @@ import {TabsTrigger,TabsContent,} from "@multica/ui/components/ui/tabs";-import { WorkspaceWakeups } from "./workspace-wakeups";+import { WorkspaceWakeupCreate, WorkspaceWakeups } from "./workspace-wakeups";import { useNavigation, useRowLink } from "../../navigation";import { ActorAvatar } from "../../common/actor-avatar";import { formatInTimeZone } from "../../common/format-in-time-zone";@@ -639,6 +639,7 @@ export function AutopilotsPage() {});const [createOpen, setCreateOpen] = useState(false);+ const [wakeupCreateOpen, setWakeupCreateOpen] = useState(false);const [selectedTemplate, setSelectedTemplate] =useState<AutopilotTemplate | null>(null);const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(@@ -809,12 +810,18 @@ export function AutopilotsPage() {title={t(($) => $.page.title)}count={tab === "autopilots" ? totalCount : undefined}actions={- tab === "autopilots" && (+ tab === "autopilots" ? (<CollectionPageHeaderActionicon={Plus}label={t(($) => $.page.new_autopilot)}onClick={() => openCreate()}/>+ ) : (+ <CollectionPageHeaderAction+ icon={Plus}+ label={t(($) => $.wakeups.create)}+ onClick={() => setWakeupCreateOpen(true)}+ />)}/>@@ -830,6 +837,7 @@ export function AutopilotsPage() {className="flex min-h-0 flex-col data-hidden:hidden"><WorkspaceWakeups key={wsId} />+ <WorkspaceWakeupCreate open={wakeupCreateOpen} onOpenChange={setWakeupCreateOpen} /></TabsContent><TabsContentvalue="autopilots"diff --git a/packages/views/autopilots/components/workspace-wakeups.test.tsx b/packages/views/autopilots/components/workspace-wakeups.test.tsxindex e1286a96b4..0c93866b87 100644--- a/packages/views/autopilots/components/workspace-wakeups.test.tsx+++ b/packages/views/autopilots/components/workspace-wakeups.test.tsx@@ -1,15 +1,20 @@import { beforeEach, expect, it, vi } from "vitest";import { fireEvent, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { ReactNode } from "react";import { api } from "@multica/core/api";import type {+ Issue,WorkspaceWakeup,WorkspaceWakeupFilters,} from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";-import { WorkspaceWakeups } from "./workspace-wakeups";+import { WorkspaceWakeupCreate, WorkspaceWakeups } from "./workspace-wakeups";+vi.mock("../../issues/components/wakeup-condition-names", () => ({+ useConditionNames: () => ({ status: (key: string) => key, label: () => undefined, property: () => undefined, actor: (_type: string, id: string) => id }),+}));vi.mock("../../common/use-viewing-timezone", () => ({useViewingTimezone: () => "UTC",}));@@ -20,6 +25,7 @@ vi.mock("@multica/core/api", () => ({enableIssueWakeup: vi.fn(),listIssueWakeups: vi.fn(),editIssueWakeupInstruction: vi.fn(),+ updateIssueSystemWakeup: vi.fn(),},}));@@ -47,6 +53,24 @@ vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));vi.mock("../../common/task-transcript", () => ({TranscriptButton: () => <button>Transcript</button>,}));+// The real picker reports the choice and then closes itself, in that order.+vi.mock("../../modals/issue-picker-modal", () => ({+ IssuePickerModal: ({ open, onSelect, onOpenChange }: { open: boolean; onSelect: (issue: Issue) => void; onOpenChange: (open: boolean) => void }) =>+ open ? (+ <div role="dialog" aria-label="Pick issue">+ <button onClick={() => { onSelect({ id: "issue-x", assignee_type: "agent", assignee_id: "agent-x" } as Issue); onOpenChange(false); }}>DEV-x</button>+ <button onClick={() => onOpenChange(false)}>Dismiss</button>+ </div>+ ) : null,+}));+vi.mock("../../issues/components/wakeup-create", () => ({+ WakeupCreateForm: ({ issueId, defaultAgentId, onClose }: { issueId: string; defaultAgentId: string; onClose: () => void }) => (+ <div>+ <p>{`Create for ${issueId} with ${defaultAgentId}`}</p>+ <button onClick={onClose}>Close form</button>+ </div>+ ),+}));let rows: WorkspaceWakeup[];let queries: WorkspaceWakeupFilters[];@@ -90,13 +114,15 @@ beforeEach(() => {disabled_at: null,last_task_id: null,last_error: null,+ source: "member" as const,+ runs_7d: 0,}));list.mockReset().mockImplementation(async (filters) => {queries.push(filters);return {items: rows,total: 60,- counts: { all: 60, active: 58, disabled: 1, ended: 1 },+ counts: { all: 60, active: 58, paused: 0, disabled: 1, ended: 1 },agents: [{ id: "a", name: "Agent a" },{ id: "b", name: "Agent b" },@@ -200,11 +226,12 @@ it("resets page and selection on scope or search changes and sends bounded pageexpect(screen.queryByRole("button", { name: "Turn off selected" }),).toBeNull();+ // Search runs once typing pauses; there is no submit button.fireEvent.change(screen.getByRole("searchbox"), {target: { value: "CI & release" },});- fireEvent.click(screen.getByRole("button", { name: "Search" }));await waitFor(() => expect(queries.at(-1)?.search).toBe("CI & release"));+ expect(queries.filter((q) => q.search).length).toBe(1);});it("makes read-only rules non-selectable and surfaces inventory failures", async () => {@@ -244,3 +271,98 @@ it("opens the shared prompt editor from a manageable row without loading all profireEvent.click(screen.getByRole("button", { name: "Save" }));await waitFor(() => expect(api.editIssueWakeupInstruction).toHaveBeenCalledWith("issue-a", "a", { instruction: "Inspect and summarize", expected_instruction: "Inspect the result", revision: 1 }));});++const updateSystem = vi.mocked(api.updateIssueSystemWakeup);+const systemRow = (): WorkspaceWakeup => ({+ ...rows[0]!,+ id: "parent",+ issue_id: "parent",+ issue_identifier: "DEV-P",+ issue_title: "Parent issue",+ agent_id: "a",+ agent_name: "Emacs",+ source: "system",+ rule: "child_done",+ system_stage: 1,+ system_remaining: 1,+ event_types: [],+ revision: undefined,+ runs_7d: 3,+});++it("lists the sub-issue system rule with its source and turns it off per issue", async () => {+ updateSystem.mockReset().mockResolvedValue(undefined);+ rows = [systemRow()];+ mount();+ const row = await screen.findByRole("row", { name: /Parent issue/ });+ expect(row).toHaveTextContent("When stage 1's sub-issues all finish");+ expect(row).toHaveTextContent("Assignee · Emacs");+ expect(row).toHaveTextContent("System");+ expect(row).toHaveTextContent("Until the issue ends");+ expect(row).toHaveTextContent("3");+ // A system rule is not part of batch selection.+ expect(within(row).queryByRole("checkbox")).toBeNull();+ fireEvent.click(within(row).getByRole("switch"));+ await waitFor(() => expect(updateSystem).toHaveBeenCalledWith("parent", "child_done", { enabled: false }));+});++it("shows who created a rule and how often it ran this week", async () => {+ rows[0] = { ...rows[0]!, source: "agent", source_agent_id: "a", source_agent_name: "Emacs", created_by_name: "Jiayuan", runs_7d: 4 };+ mount();+ const row = await screen.findByRole("row", { name: /Issue a/ });+ expect(row).toHaveTextContent("Emacs");+ expect(row).toHaveTextContent("4");+});++it("filters by source", async () => {+ const user = userEvent.setup();+ mount();+ await screen.findByRole("row", { name: /Issue a/ });+ await user.click(screen.getByRole("combobox", { name: "Source" }));+ await user.click(await screen.findByRole("option", { name: "System" }));+ await waitFor(() => expect(queries.at(-1)).toMatchObject({ source: "system", offset: 0 }));+});++it("warns about paused rules and jumps to them", async () => {+ const paused = { ...rows[1]!, id: "p", issue_identifier: "DEV-P", enabled: false, paused_reason: "rate" as const, event_types: ["comment.created"] };+ list.mockImplementation(async (filters) => {+ queries.push(filters);+ return {+ items: filters.scope === "paused" ? [paused] : rows,+ total: 2,+ counts: { all: 3, active: 2, paused: 1, disabled: 0, ended: 0 },+ agents: [],+ };+ });+ mount();+ const banner = await screen.findByRole("status");+ expect(banner).toHaveTextContent("1 wakeup was paused automatically: DEV-P");+ expect(banner).toHaveTextContent("more than 12 runs in an hour");+ fireEvent.click(within(banner).getByRole("button", { name: "View" }));+ await waitFor(() => expect(queries.at(-1)).toMatchObject({ scope: "paused", limit: 50 }));+});++it("opens the create form for the picked issue", async () => {+ const onOpenChange = vi.fn();+ const client = new QueryClient();+ const view = renderWithI18n(+ <QueryClientProvider client={client}>+ <WorkspaceWakeupCreate open onOpenChange={onOpenChange} />+ </QueryClientProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "DEV-x" }));+ // Regression: the picker's own close after a selection used to end the flow.+ expect(await screen.findByText("Create for issue-x with agent-x")).toBeVisible();+ expect(onOpenChange).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Close form" }));+ expect(onOpenChange).toHaveBeenCalledWith(false);+ view.unmount();+ onOpenChange.mockClear();+ renderWithI18n(+ <QueryClientProvider client={client}>+ <WorkspaceWakeupCreate open onOpenChange={onOpenChange} />+ </QueryClientProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));+ expect(onOpenChange).toHaveBeenCalledWith(false);+});diff --git a/packages/views/autopilots/components/workspace-wakeups.tsx b/packages/views/autopilots/components/workspace-wakeups.tsxindex 03588d1150..105f899a07 100644--- a/packages/views/autopilots/components/workspace-wakeups.tsx+++ b/packages/views/autopilots/components/workspace-wakeups.tsx@@ -1,8 +1,8 @@"use client";-import { useState } from "react";+import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";import { useQuery } from "@tanstack/react-query";-import { Bell, Clock3, AlertCircle } from "lucide-react";+import { Bell, Clock3, AlertCircle, ListChecks, Search, TriangleAlert } from "lucide-react";import { toast } from "sonner";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";@@ -11,11 +11,14 @@ import {useDisableWorkspaceWakeups,useDisableIssueWakeup,useEnableIssueWakeup,+ useUpdateIssueSystemWakeup,} from "@multica/core/issues/wakeups";import type {+ Issue,WorkspaceWakeup,WorkspaceWakeupFilters,} from "@multica/core/types";+import { Switch } from "@multica/ui/components/ui/switch";import { Button } from "@multica/ui/components/ui/button";import { Checkbox } from "@multica/ui/components/ui/checkbox";import { Input } from "@multica/ui/components/ui/input";@@ -42,27 +45,191 @@ import {DialogDescription,DialogFooter,} from "@multica/ui/components/ui/dialog";+import { cn } from "@multica/ui/lib/utils";import { AppLink } from "../../navigation";-import { useLocale, useT, useTimeAgo } from "../../i18n";+import { useLocale, useT } from "../../i18n";import { CollectionPageState } from "../../layout/collection-page";import { ActorAvatar } from "../../common/actor-avatar";import { TranscriptButton } from "../../common/task-transcript";import { useViewingTimezone } from "../../common/use-viewing-timezone";import { WakeupInstructionEditor } from "../../issues/components/wakeup-instruction-editor";import { WakeupControl } from "../../issues/components/wakeup-control";+import { WakeupCreateForm } from "../../issues/components/wakeup-create";+import { conditionIcon } from "../../issues/components/wakeups-section";+import { IssuePickerModal } from "../../modals/issue-picker-modal";import {isActiveWakeupRun,useWakeupText,} from "../../issues/components/wakeup-presentation";+// Per-row controls (selection, prompt editing, the last run's transcript)+// stay out of the way until the pointer or focus is on the row.+const rowIntent =+ "opacity-0 transition-opacity group-hover/row:opacity-100 group-focus-within/row:opacity-100";++/**+ * Identifier and title on one line; the whole cell opens the issue. The column+ * takes the width the others leave and truncates, so the table fits the page.+ */+function IssueCell({ row }: { row: WorkspaceWakeup }) {+ const paths = useWorkspacePaths();+ return (+ <TableCell className="w-full max-w-0">+ <AppLink+ href={paths.issueDetail(row.issue_id)}+ title={`${row.issue_identifier} ${row.issue_title}`}+ className="flex min-w-0 items-center gap-2 rounded-sm focus-visible:outline-2 focus-visible:outline-ring"+ >+ <span className="shrink-0 text-caption tabular-nums text-muted-foreground">{row.issue_identifier}</span>+ <span className="truncate">{row.issue_title}</span>+ </AppLink>+ </TableCell>+ );+}++function TriggerCell({ icon: Icon, label, detail }: { icon: typeof Bell; label: string; detail?: string }) {+ return (+ <TableCell className="max-w-64">+ <span className="flex min-w-0 items-center gap-1.5" title={detail ? `${label} · ${detail}` : label}>+ <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />+ <span className="truncate">{label}</span>+ </span>+ </TableCell>+ );+}++function AgentCell({ id, name, label }: { id: string; name: string; label?: string }) {+ return (+ <TableCell className="max-w-44">+ <span className="flex min-w-0 items-center gap-2">+ <ActorAvatar actorType="agent" actorId={id} name={name} size="sm" />+ <span className="truncate">{label ?? name}</span>+ </span>+ </TableCell>+ );+}++/** Who a rule came from: a member, an agent run, or the platform. */+function SourceCell({ row }: { row: WorkspaceWakeup }) {+ const { t } = useT("autopilots");+ if (row.source === "system") {+ return (+ <span className="rounded-xs bg-muted px-1.5 py-0.5 text-caption text-muted-foreground">+ {t(($) => $.wakeups.sources.system)}+ </span>+ );+ }+ const agent = row.source === "agent" && row.source_agent_id;+ return (+ <span className="flex min-w-0 items-center gap-2">+ <ActorAvatar+ actorType={agent ? "agent" : "member"}+ actorId={agent ? (row.source_agent_id ?? "") : ""}+ name={agent ? (row.source_agent_name ?? "") : (row.created_by_name ?? "")}+ size="sm"+ />+ <span className="truncate">{agent ? row.source_agent_name : row.created_by_name}</span>+ </span>+ );+}++/** Runs in the last seven days, and the current run when there is one. */+function RunsCell({ row }: { row: WorkspaceWakeup }) {+ const { t } = useT("autopilots");+ const { t: ti } = useT("issues");+ const text = useWakeupText();+ const status = row.task?.status;+ const active = isActiveWakeupRun(status);+ return (+ <TableCell>+ <div className="flex items-center gap-1 tabular-nums">+ <span>{row.runs_7d}</span>+ {row.task && active && (+ <>+ <span aria-hidden="true" className="text-muted-foreground">·</span>+ <span className="text-primary" title={row.active_runs > 1 ? t(($) => $.wakeups.active_runs, { count: row.active_runs }) : undefined}>+ {text.runState(status)}+ </span>+ </>+ )}+ {row.task && (+ <span className={cn(!active && rowIntent)}>+ <TranscriptButton task={row.task} agentName={row.agent_name} title={ti(($) => $.wakeups.last_run)} isLive={active} />+ </span>+ )}+ </div>+ </TableCell>+ );+}++function SelectCell({ checked, visible, disabled, label, onChange }: {+ checked: boolean;+ visible: boolean;+ disabled: boolean;+ label: string;+ onChange: () => void;+}) {+ return (+ <TableCell className="w-8 pl-4 pr-0">+ <div className={cn(rowIntent, visible && "opacity-100")}>+ <Checkbox checked={checked} onCheckedChange={onChange} disabled={disabled} aria-label={label} />+ </div>+ </TableCell>+ );+}++/** The sub-issue system rule on one parent issue. */+function SystemWakeupListRow({ row, busy }: { row: WorkspaceWakeup; busy: boolean }) {+ const { t } = useT("autopilots");+ const { t: ti } = useT("issues");+ const wsId = useWorkspaceId();+ const update = useUpdateIssueSystemWakeup(wsId, row.issue_id);+ const title =+ row.system_stage != null+ ? ti(($) => $.wakeups.system.title_stage, { stage: row.system_stage })+ : ti(($) => $.wakeups.system.title_all);+ return (+ <TableRow className="group/row">+ <TableCell className="w-8 pl-4 pr-0" />+ <IssueCell row={row} />+ <TriggerCell icon={ListChecks} label={title} />+ {row.agent_id ? (+ <AgentCell id={row.agent_id} name={row.agent_name} label={t(($) => $.wakeups.assignee_target, { name: row.agent_name })} />+ ) : (+ <TableCell className="text-muted-foreground">{t(($) => $.wakeups.no_target)}</TableCell>+ )}+ <TableCell>+ <SourceCell row={row} />+ </TableCell>+ <TableCell className="text-muted-foreground">{t(($) => $.wakeups.until_issue_ends)}</TableCell>+ <RunsCell row={row} />+ <TableCell className="w-px py-0 pr-4">+ <div className="flex min-h-11 items-center justify-end px-2">+ <Switch+ checked={row.enabled}+ disabled={busy || update.isPending}+ aria-label={`${row.issue_identifier} · ${ti(($) => $.wakeups.system.toggle)}`}+ onCheckedChange={(enabled) =>+ update.mutate({ rule: "child_done", enabled }, { onError: () => toast.error(ti(($) => $.wakeups.system.save_error)) })+ }+ />+ </div>+ </TableCell>+ </TableRow>+ );+}+function WakeupListRow({row,selected,+ selecting,onSelect,busy,}: {row: WorkspaceWakeup;selected: boolean;+ /** Some row is selected, so every checkbox stays visible. */+ selecting: boolean;onSelect: () => void;busy: boolean;}) {@@ -71,122 +238,50 @@ function WakeupListRow({const wsId = useWorkspaceId();const paths = useWorkspacePaths();const locale = useLocale();- const timeAgo = useTimeAgo();const text = useWakeupText();const viewTZ = useViewingTimezone();const disable = useDisableIssueWakeup(wsId, row.issue_id);const enable = useEnableIssueWakeup(wsId, row.issue_id);- const Icon = row.kind === "event" ? Bell : Clock3;- const next = text.state(row, row.issue_closed);- const status = row.task?.status;+ const Icon = conditionIcon(row.condition) ?? (row.kind === "event" ? Bell : Clock3);+ // While enabled, a rule reads as when it ends; otherwise as its state.+ const ends = row.enabled && !row.issue_closed+ ? (text.ending(row) ?? (row.mode === "once" ? t(($) => $.wakeups.fires_once) : text.state(row)))+ : (text.paused(row) ?? text.state(row, row.issue_closed));return (- <TableRow data-state={selected ? "selected" : undefined}>- <TableCell className="w-10 pl-4">- <Checkbox- checked={selected}- onCheckedChange={onSelect}- disabled={busy || !row.can_manage || !row.enabled}- aria-label={t(($) => $.wakeups.select_row, {- issue: row.issue_identifier,- agent: row.agent_name,- })}- />- </TableCell>- <TableCell className="max-w-72">- <AppLink- href={paths.issueDetail(row.issue_id)}- className="block rounded-sm focus-visible:outline-2 focus-visible:outline-ring"- >- <span className="block truncate font-medium" title={row.issue_title}>- {row.issue_title}- </span>- <span className="text-caption text-muted-foreground">- {row.issue_identifier}- </span>- </AppLink>- </TableCell>- <TableCell className="max-w-44">- <span className="flex items-center gap-2">- <ActorAvatar- actorType="agent"- actorId={row.agent_id}- name={row.agent_name}- size="sm"- />- <span className="truncate">{row.agent_name}</span>- </span>- </TableCell>- <TableCell className="max-w-64">- <span- className="flex items-center gap-1.5"- title={row.event_types- .map((event) =>- text.eventCondition(event, row),- )- .join(", ")}- >- <Icon className="size-3.5 shrink-0 text-muted-foreground" />- <span className="line-clamp-2 break-words">{text.trigger(row)}</span>- </span>- <span className="block truncate text-caption text-muted-foreground">- {row.kind === "cron" ? row.timezone : text.frequency(row)}- </span>+ <TableRow className="group/row" data-state={selected ? "selected" : undefined}>+ <SelectCell+ checked={selected}+ visible={selected || selecting}+ onChange={onSelect}+ disabled={busy || !row.can_manage || !row.enabled}+ label={t(($) => $.wakeups.select_row, { issue: row.issue_identifier, agent: row.agent_name })}+ />+ <IssueCell row={row} />+ <TriggerCell icon={Icon} label={text.trigger(row)} detail={row.kind === "cron" ? row.timezone : text.frequency(row)} />+ <AgentCell id={row.agent_id} name={row.agent_name} />+ <TableCell className="max-w-40">+ <SourceCell row={row} /></TableCell><TableCell className="max-w-48"><span- className="block truncate"+ className={cn("flex min-w-0 items-center gap-1.5", row.paused_reason && "text-warning")}title={row.next_fire_at && row.enabled? `${new Date(row.next_fire_at).toLocaleString(locale, { timeZone: viewTZ })} · ${viewTZ}`: undefined}>- {next}+ <span className="truncate">{ends}</span>+ {row.last_error && (+ <AppLink href={paths.issueDetail(row.issue_id)} className="shrink-0 text-caption text-destructive">+ {ti(($) => $.wakeups.needs_attention)}+ </AppLink>+ )}</span>- {row.last_error && (- <AppLink- href={paths.issueDetail(row.issue_id)}- className="text-caption text-destructive"- >- {ti(($) => $.wakeups.needs_attention)}- </AppLink>- )}</TableCell>- <TableCell>- {row.task ? (- <div className="flex items-center gap-1">- <div>- <span- className={- isActiveWakeupRun(status)- ? "text-primary"- : "text-muted-foreground"- }- >- {text.runState(status)}- </span>- <span className="block text-caption text-muted-foreground">- {row.active_runs > 1- ? t(($) => $.wakeups.active_runs, { count: row.active_runs })- : timeAgo(- row.task.completed_at ??- row.task.started_at ??- row.task.created_at,- )}- </span>- </div>- <TranscriptButton- task={row.task}- agentName={row.agent_name}- title={ti(($) => $.wakeups.last_run)}- isLive={isActiveWakeupRun(status)}- />- </div>- ) : (- <span className="text-muted-foreground">{text.runState()}</span>- )}- </TableCell>- <TableCell className="w-px">+ <RunsCell row={row} />+ {/* The controls are 44px targets, so this cell sets the row height. */}+ <TableCell className="w-px py-0 pr-4"><divclassName="flex items-center justify-end"title={@@ -197,54 +292,134 @@ function WakeupListRow({: undefined}>+ <span className={rowIntent}>+ <WakeupInstructionEditor+ workspaceId={wsId}+ issueId={row.issue_id}+ wakeupId={row.id}+ disabled={busy || !row.can_manage}+ triggerStyle="icon"+ />+ </span><WakeupControlwakeup={row}task={row.task ?? undefined}closed={row.issue_closed}- pending={- busy || !row.can_manage || disable.isPending || enable.isPending- }+ pending={busy || !row.can_manage || disable.isPending || enable.isPending}onDisable={() =>disable.mutate(row.id, {- onError: (err) =>- toast.error(- text.error(- err,- ti(($) => $.wakeups.disable_error),- ),- ),+ onError: (err) => toast.error(text.error(err, ti(($) => $.wakeups.disable_error))),})}onEnable={async (input = {}) => {- await enable.mutateAsync({- id: row.id,- revision: row.revision ?? 0,- ...input,- });+ await enable.mutateAsync({ id: row.id, revision: row.revision ?? 0, ...input });}}/></div></TableCell>- <TableCell className="w-px pl-0 pr-4">- <WakeupInstructionEditor- workspaceId={wsId}- issueId={row.issue_id}- wakeupId={row.id}- disabled={busy || !row.can_manage}- triggerStyle="icon"- />- </TableCell></TableRow>);}+/**+ * "New wakeup" from the workspace list: a wakeup belongs to one issue, so pick+ * it first, then fill in the same form as the issue sidebar.+ */+export function WorkspaceWakeupCreate({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {+ const { t } = useT("autopilots");+ const wsId = useWorkspaceId();+ const [issue, setIssue] = useState<Issue | null>(null);+ // The picker reports a selection and then closes itself; only a close+ // without a selection ends the flow.+ const picked = useRef(false);+ const close = () => {+ picked.current = false;+ setIssue(null);+ onOpenChange(false);+ };+ return (+ <>+ <IssuePickerModal+ open={open && !issue}+ onOpenChange={(next) => {+ if (!next && !picked.current) close();+ }}+ title={t(($) => $.wakeups.create_pick_issue)}+ description={t(($) => $.wakeups.create_pick_issue_description)}+ excludeIds={[]}+ isSelectable={(candidate) => candidate.status !== "done" && candidate.status !== "cancelled"}+ onSelect={(candidate) => {+ picked.current = true;+ setIssue(candidate);+ }}+ />+ <Dialog+ open={open && !!issue}+ onOpenChange={(next) => {+ if (!next) close();+ }}+ >+ <DialogContent className="sm:max-w-[460px]">+ {issue && (+ <WakeupCreateForm+ workspaceId={wsId}+ issueId={issue.id}+ defaultAgentId={issue.assignee_type === "agent" ? (issue.assignee_id ?? "") : ""}+ inDialog+ onClose={close}+ />+ )}+ </DialogContent>+ </Dialog>+ </>+ );+}++function FilterSelect<T extends string>({+ label,+ value,+ items,+ disabled,+ onChange,+}: {+ label: string;+ value: T;+ items: { value: T; label: string }[];+ disabled: boolean;+ onChange: (value: T) => void;+}) {+ return (+ <Select+ items={items}+ value={value}+ disabled={disabled}+ onValueChange={(next) => {+ const item = items.find((candidate) => candidate.value === next);+ if (item) onChange(item.value);+ }}+ >+ <SelectTrigger size="sm" className="max-w-44" aria-label={label}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {items.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}+export function WorkspaceWakeups() {const { t } = useT("autopilots");- const { t: ti } = useT("issues");const wsId = useWorkspaceId();+ const text = useWakeupText();const [filters, setFilters] = useState<WorkspaceWakeupFilters>({scope: "active",kind: "all",+ source: "",search: "",agent_id: "",offset: 0,@@ -258,249 +433,125 @@ export function WorkspaceWakeups() {succeeded: number;} | null>(null);const query = useQuery(workspaceWakeupsOptions(wsId, filters));+ // The newest rule the platform paused, for the banner above the list.+ const pausedQuery = useQuery({+ ...workspaceWakeupsOptions(wsId, { scope: "paused", kind: "all", source: "", search: "", agent_id: "", offset: 0, limit: 1 }),+ enabled: !!wsId && (query.data?.counts.paused ?? 0) > 0,+ });const batch = useDisableWorkspaceWakeups(wsId);const rows = query.data?.items ?? [];- const selectable = rows.filter((row) => row.enabled && row.can_manage);+ const selectable = rows.filter((row) => row.enabled && row.can_manage && row.source !== "system");const picked = selectable.filter((row) => selected.has(row.id));- const change = (patch: Partial<WorkspaceWakeupFilters>) => {+ const change = useCallback((patch: Partial<WorkspaceWakeupFilters>) => {setFilters((prev) => ({ ...prev, offset: 0, ...patch }));setSelected(new Set());setBatchResult(null);- };+ }, []);+ // Search as you type, once typing pauses.+ useEffect(() => {+ const next = search.trim();+ if (next === filters.search) return;+ const timer = setTimeout(() => change({ search: next }), 300);+ return () => clearTimeout(timer);+ }, [search, filters.search, change]);const kinds = [- { value: "all", label: t(($) => $.wakeups.all_triggers) },- { value: "event", label: t(($) => $.wakeups.event) },- { value: "at", label: t(($) => $.wakeups.at) },- { value: "recurring", label: t(($) => $.wakeups.recurring) },+ { value: "all" as const, label: t(($) => $.wakeups.all_triggers) },+ { value: "event" as const, label: t(($) => $.wakeups.event) },+ { value: "at" as const, label: t(($) => $.wakeups.at) },+ { value: "recurring" as const, label: t(($) => $.wakeups.recurring) },];const agents = [{ value: "", label: t(($) => $.wakeups.all_agents) },...(query.data?.agents ?? []).map((a) => ({ value: a.id, label: a.name })),];- return (- <>- <div className="flex shrink-0 flex-wrap items-center gap-2 border-b px-4 py-2">- <div- className="flex gap-1"- role="group"- aria-label={t(($) => $.wakeups.scope)}- >- {(["active", "all", "disabled", "ended"] as const).map((scope) => (- <Button- key={scope}- size="sm"- variant={filters.scope === scope ? "secondary" : "ghost"}- aria-pressed={filters.scope === scope}- disabled={batch.isPending}- onClick={() => change({ scope })}- >- {t(($) => $.wakeups.scopes[scope])}- <span className="ml-1 text-muted-foreground tabular-nums">- {query.data?.counts[scope] ?? "—"}- </span>- </Button>- ))}- </div>- <div className="ml-auto flex flex-wrap items-center gap-2">- <form- onSubmit={(event) => {- event.preventDefault();- change({ search: search.trim() });- }}- className="flex items-center gap-1"- >- <Input- type="search"- className="h-8 w-48"- value={search}- maxLength={256}- disabled={batch.isPending}- onChange={(event) => {- setSearch(event.target.value);- if (!event.target.value) change({ search: "" });- }}- aria-label={t(($) => $.wakeups.search)}- placeholder={t(($) => $.wakeups.search)}- />- <Button- size="sm"- variant="ghost"- type="submit"- disabled={batch.isPending}- >- {t(($) => $.wakeups.search_action)}- </Button>- </form>- <Select- items={kinds}- value={filters.kind}- disabled={batch.isPending}- onValueChange={(kind) => {- if (- kind === "all" ||- kind === "event" ||- kind === "at" ||- kind === "recurring"- )- change({ kind });- }}- >- <SelectTrigger size="sm" aria-label={t(($) => $.wakeups.trigger)}>- <SelectValue />- </SelectTrigger>- <SelectContent>- {kinds.map((item) => (- <SelectItem key={item.value} value={item.value}>- {item.label}- </SelectItem>- ))}- </SelectContent>- </Select>- <Select- items={agents}- value={filters.agent_id}- disabled={batch.isPending}- onValueChange={(agent_id) => {- if (agent_id !== null) change({ agent_id });- }}- >- <SelectTrigger- size="sm"- className="max-w-48"- aria-label={t(($) => $.wakeups.target_agent)}- >- <SelectValue />- </SelectTrigger>- <SelectContent>- {agents.map((item) => (- <SelectItem key={item.value} value={item.value}>- {item.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- </div>- {batchResult && (- <p- role="status"- className={`px-4 py-2 text-caption ${batchResult.failed.length ? "text-destructive" : "text-muted-foreground"}`}- >- {t(- ($) =>- batchResult.failed.length- ? $.wakeups.batch_partial- : $.wakeups.batch_success,- {- count: batchResult.succeeded,- succeeded: batchResult.succeeded,- failed: batchResult.failed.length,- },- )}- </p>- )}- {query.isError ? (- <CollectionPageState- icon={AlertCircle}- tone="destructive"- role="alert"- title={t(($) => $.wakeups.load_error)}- actions={+ const sources = [+ { value: "" as const, label: t(($) => $.wakeups.sources.all) },+ { value: "member" as const, label: t(($) => $.wakeups.sources.member) },+ { value: "agent" as const, label: t(($) => $.wakeups.sources.agent) },+ { value: "system" as const, label: t(($) => $.wakeups.sources.system) },+ ];+ const pausedCount = query.data?.counts.paused ?? 0;+ const latestPaused = pausedQuery.data?.items[0];+ const filtered = filters.scope !== "all" || !!filters.search || filters.kind !== "all" || !!filters.source || !!filters.agent_id;+ let body: ReactNode;+ if (query.isError) {+ body = (+ <CollectionPageState+ icon={AlertCircle}+ tone="destructive"+ role="alert"+ title={t(($) => $.wakeups.load_error)}+ actions={+ <Button variant="outline" size="sm" onClick={() => void query.refetch()}>+ {t(($) => $.page.retry)}+ </Button>+ }+ />+ );+ } else if (query.isPending) {+ body = <CollectionPageState icon={Clock3} title={t(($) => $.wakeups.loading)} />;+ } else if (!rows.length) {+ const hasAny = (query.data?.counts.all ?? 0) > 0;+ body = (+ <CollectionPageState+ icon={Bell}+ title={t(($) => (hasAny || filtered ? $.wakeups.empty_filtered : $.wakeups.empty))}+ actions={+ filtered && hasAny ? (<Buttonvariant="outline"size="sm"- onClick={() => void query.refetch()}+ onClick={() => {+ setSearch("");+ change({ scope: "all", kind: "all", source: "", search: "", agent_id: "" });+ }}>- {t(($) => $.page.retry)}+ {t(($) => $.wakeups.clear_filters)}</Button>- }- />- ) : query.isPending ? (- <CollectionPageState- icon={Clock3}- title={t(($) => $.wakeups.loading)}- />- ) : !rows.length ? (- <CollectionPageState- icon={Bell}- title={t(($) =>- (query.data?.counts.all ?? 0) > 0 ||- filters.search ||- filters.kind !== "all" ||- filters.agent_id- ? $.wakeups.empty_filtered- : $.wakeups.empty,- )}- actions={- (filters.scope !== "all" ||- !!filters.search ||- filters.kind !== "all" ||- !!filters.agent_id) &&- (query.data?.counts.all ?? 0) > 0 ? (- <Button- variant="outline"- size="sm"- onClick={() => {- setSearch("");- change({- scope: "all",- kind: "all",- search: "",- agent_id: "",- });- }}- >- {t(($) => $.wakeups.clear_filters)}- </Button>- ) : undefined- }- />- ) : (- <div className="min-h-0 flex-1 overflow-auto">- <Table className="min-w-[1050px]">- <TableHeader>- <TableRow>- <TableHead className="pl-4">+ ) : undefined+ }+ />+ );+ } else {+ const selecting = picked.length > 0;+ body = (+ <div className="min-h-0 flex-1 overflow-auto">+ <Table className="min-w-[900px]">+ <TableHeader>+ <TableRow className="group/row">+ <TableHead className="w-8 pl-4 pr-0">+ <div className={cn(rowIntent, selecting && "opacity-100")}><Checkboxdisabled={!selectable.length || batch.isPending}- checked={- picked.length > 0 && picked.length === selectable.length- }- indeterminate={- picked.length > 0 && picked.length < selectable.length- }+ checked={picked.length > 0 && picked.length === selectable.length}+ indeterminate={picked.length > 0 && picked.length < selectable.length}onCheckedChange={() =>- setSelected(- picked.length === selectable.length- ? new Set()- : new Set(selectable.map((row) => row.id)),- )+ setSelected(picked.length === selectable.length ? new Set() : new Set(selectable.map((row) => row.id)))}aria-label={t(($) => $.wakeups.select_page)}/>- </TableHead>- <TableHead>{t(($) => $.wakeups.issue)}</TableHead>- <TableHead>{t(($) => $.wakeups.target_agent)}</TableHead>- <TableHead>{t(($) => $.wakeups.trigger)}</TableHead>- <TableHead>{t(($) => $.wakeups.next)}</TableHead>- <TableHead>{t(($) => $.wakeups.wakeup_run)}</TableHead>- <TableHead className="w-px pr-4 text-right">- {t(($) => $.wakeups.enabled)}- </TableHead>- <TableHead className="w-px pl-0 pr-4">- <span className="sr-only">- {ti(($) => $.wakeups.edit_instruction)}- </span>- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {rows.map((row) => (+ </div>+ </TableHead>+ <TableHead>{t(($) => $.wakeups.issue)}</TableHead>+ <TableHead>{t(($) => $.wakeups.trigger)}</TableHead>+ <TableHead>{t(($) => $.wakeups.target_agent)}</TableHead>+ <TableHead>{t(($) => $.wakeups.source)}</TableHead>+ <TableHead>{t(($) => $.wakeups.ends)}</TableHead>+ <TableHead>{t(($) => $.wakeups.runs_7d)}</TableHead>+ <TableHead className="w-px pr-6 text-right">{t(($) => $.wakeups.enabled)}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.map((row) =>+ row.source === "system" ? (+ <SystemWakeupListRow key={`system-${row.id}`} row={row} busy={batch.isPending} />+ ) : (<WakeupListRowkey={row.id}row={row}busy={batch.isPending}selected={selected.has(row.id)}+ selecting={selecting}onSelect={() =>setSelected((prev) => {const next = new Set(prev);@@ -510,31 +561,98 @@ export function WorkspaceWakeups() {})}/>- ))}- </TableBody>- </Table>+ ),+ )}+ </TableBody>+ </Table>+ </div>+ );+ }+ return (+ <>+ {pausedCount > 0 && latestPaused && filters.scope !== "paused" && (+ <div+ role="status"+ className="mx-4 mt-3 flex items-center gap-2 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-caption"+ >+ <TriangleAlert className="size-4 shrink-0 text-destructive" aria-hidden="true" />+ <span className="min-w-0 flex-1">+ {t(($) => $.wakeups.banner, {+ count: pausedCount,+ issue: latestPaused.issue_identifier,+ condition: text.trigger(latestPaused),+ reason: text.pausedReason(latestPaused) ?? "",+ })}+ </span>+ <Button size="sm" variant="outline" onClick={() => change({ scope: "paused" })}>+ {t(($) => $.wakeups.banner_view)}+ </Button></div>)}+ {/* One row: scope on the left, the narrowing filters and search on the+ right. It only wraps on narrow windows. */}+ <div className="flex shrink-0 flex-wrap items-center gap-2 px-4 pb-2 pt-3">+ <div role="group" aria-label={t(($) => $.wakeups.scope)} className="flex shrink-0 items-center gap-0.5 rounded-lg bg-muted p-0.5">+ {(["active", "paused", "disabled", "ended", "all"] as const).map((scope) => {+ const active = filters.scope === scope;+ return (+ <button+ key={scope}+ type="button"+ aria-pressed={active}+ disabled={batch.isPending}+ onClick={() => change({ scope })}+ className={cn(+ "inline-flex h-7 items-center gap-1 rounded-md px-2.5 text-caption text-muted-foreground outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50",+ active && "bg-surface font-medium text-foreground shadow-[var(--surface-shadow)]",+ )}+ >+ {t(($) => $.wakeups.scopes[scope])}+ <span className="tabular-nums text-muted-foreground">{query.data?.counts[scope] ?? "—"}</span>+ </button>+ );+ })}+ </div>+ <div className="ml-auto flex items-center gap-2">+ <FilterSelect label={t(($) => $.wakeups.source)} value={filters.source} items={sources} disabled={batch.isPending} onChange={(source) => change({ source })} />+ <FilterSelect label={t(($) => $.wakeups.trigger)} value={filters.kind} items={kinds} disabled={batch.isPending} onChange={(kind) => change({ kind })} />+ <FilterSelect label={t(($) => $.wakeups.target_agent)} value={filters.agent_id} items={agents} disabled={batch.isPending} onChange={(agent_id) => change({ agent_id })} />+ <div className="relative">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" aria-hidden="true" />+ <Input+ type="search"+ className="h-8 w-52 pl-8"+ value={search}+ maxLength={256}+ disabled={batch.isPending}+ onChange={(event) => setSearch(event.target.value)}+ aria-label={t(($) => $.wakeups.search)}+ placeholder={t(($) => $.wakeups.search)}+ />+ </div>+ </div>+ </div>+ {batchResult && (+ <p+ role="status"+ className={`px-4 py-2 text-caption ${batchResult.failed.length ? "text-destructive" : "text-muted-foreground"}`}+ >+ {t(($) => (batchResult.failed.length ? $.wakeups.batch_partial : $.wakeups.batch_success), {+ count: batchResult.succeeded,+ succeeded: batchResult.succeeded,+ failed: batchResult.failed.length,+ })}+ </p>+ )}+ {body}<div className="mt-auto flex shrink-0 flex-wrap items-center gap-2 border-t px-4 py-2 text-caption text-muted-foreground">{picked.length > 0 && (<>- <span>- {t(($) => $.wakeups.selected, { count: picked.length })}- </span>- <Button- size="sm"- variant="outline"- disabled={batch.isPending}- onClick={() => setConfirmation(picked)}- >+ <span>{t(($) => $.wakeups.selected, { count: picked.length })}</span>+ <Button size="sm" variant="outline" disabled={batch.isPending} onClick={() => setConfirmation(picked)}>{t(($) => $.wakeups.disable_selected)}</Button>- <Button- size="sm"- variant="ghost"- disabled={batch.isPending}- onClick={() => setSelected(new Set())}- >+ <Button size="sm" variant="ghost" disabled={batch.isPending} onClick={() => setSelected(new Set())}>{t(($) => $.wakeups.clear)}</Button></>@@ -551,20 +669,14 @@ export function WorkspaceWakeups() {size="sm"variant="ghost"disabled={batch.isPending || !filters.offset}- onClick={() =>- change({ offset: Math.max(0, filters.offset - filters.limit) })- }+ onClick={() => change({ offset: Math.max(0, filters.offset - filters.limit) })}>{t(($) => $.wakeups.previous)}</Button><Buttonsize="sm"variant="ghost"- disabled={- batch.isPending ||- !query.data ||- filters.offset + filters.limit >= query.data.total- }+ disabled={batch.isPending || !query.data || filters.offset + filters.limit >= query.data.total}onClick={() => change({ offset: filters.offset + filters.limit })}>{t(($) => $.wakeups.next_page)}@@ -578,21 +690,11 @@ export function WorkspaceWakeups() {><DialogContent><DialogHeader>- <DialogTitle>- {t(($) => $.wakeups.confirm_title, {- count: confirmation.length,- })}- </DialogTitle>- <DialogDescription>- {t(($) => $.wakeups.confirm_body)}- </DialogDescription>+ <DialogTitle>{t(($) => $.wakeups.confirm_title, { count: confirmation.length })}</DialogTitle>+ <DialogDescription>{t(($) => $.wakeups.confirm_body)}</DialogDescription></DialogHeader><DialogFooter>- <Button- variant="outline"- disabled={batch.isPending}- onClick={() => setConfirmation([])}- >+ <Button variant="outline" disabled={batch.isPending} onClick={() => setConfirmation([])}>{t(($) => $.wakeups.cancel)}</Button><Button@@ -604,9 +706,7 @@ export function WorkspaceWakeups() {setConfirmation([]);}}>- {batch.isPending- ? t(($) => $.wakeups.disabling)- : t(($) => $.wakeups.confirm)}+ {batch.isPending ? t(($) => $.wakeups.disabling) : t(($) => $.wakeups.confirm)}</Button></DialogFooter></DialogContent>diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsxindex 6352940cce..fa7ead0225 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx@@ -808,7 +808,9 @@ export function AgentTranscriptDialog({// up front than the runtime/provider diagnostics, which live in the ⓘ popover.const triggerLabel = task.parent_task_id? t(($) => $.transcript.trigger_retry)- : task.kind === "comment" || task.trigger_comment_id+ : task.wakeup_id+ ? t(($) => $.transcript.trigger_wakeup)+ : task.kind === "comment" || task.trigger_comment_id? t(($) => $.transcript.trigger_comment): task.kind === "autopilot" || task.autopilot_run_id? t(($) => $.transcript.trigger_autopilot)diff --git a/packages/views/inbox/components/inbox-detail-label.tsx b/packages/views/inbox/components/inbox-detail-label.tsxindex 388f3e93b7..7fdafdc7bf 100644--- a/packages/views/inbox/components/inbox-detail-label.tsx+++ b/packages/views/inbox/components/inbox-detail-label.tsx@@ -37,6 +37,7 @@ export function useTypeLabels(): Record<InboxItemType, string> {quick_create_unconfirmed: t(($) => $.types.quick_create_unconfirmed),autopilot_paused: t(($) => $.types.autopilot_paused),autopilot_quota_exceeded: t(($) => $.types.autopilot_quota_exceeded),+ children_done: t(($) => $.types.children_done),};}@@ -136,6 +137,12 @@ export function InboxDetailLabel({ item }: { item: InboxItem }) {}case "autopilot_quota_exceeded":return <span>{t(($) => $.labels.autopilot_quota_blocked)}</span>;+ case "children_done": {+ // The stage arrives as a JSON number; details are typed as strings.+ const stage = details.stage != null ? String(details.stage) : "";+ if (stage) return <span>{t(($) => $.labels.children_done_stage, { stage })}</span>;+ return <span>{typeLabels[item.type]}</span>;+ }default:return <span>{typeLabels[item.type] ?? item.type}</span>;}diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex 969eb7486e..88084f76f9 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -61,6 +61,7 @@ import { useCommentAnnotations } from "./use-comment-annotations";import { useAttachmentVersions } from "./deliverables/attachment-versions";import { VersionBadge } from "./deliverables/version-badge";import { useRunCommentMotion } from "./use-run-comment-motion";+import { WakeupSourceChip } from "./wakeup-source-chip";const commentActionClassName ="text-muted-foreground aria-expanded:bg-transparent aria-expanded:hover:bg-muted dark:aria-expanded:hover:bg-muted/50";@@ -730,6 +731,10 @@ function CommentRow({<SteerBadge issueId={issueId} entry={entry} />{runHeader}+ {entry.actor_type === "agent" && entry.source_task_id && (+ <WakeupSourceChip issueId={issueId} taskId={entry.source_task_id} />+ )}+{isResolution && (<span className="text-caption font-medium text-success">{t(($) => $.comment.resolve.resolution_badge)}@@ -1234,6 +1239,9 @@ function CommentCardImpl({<SteerBadge issueId={issueId} entry={entry} />{renderRuns(entry.id, "header")}+ {entry.actor_type === "agent" && entry.source_task_id && (+ <WakeupSourceChip issueId={issueId} taskId={entry.source_task_id} />+ )}</>)}diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsxindex c3889d19cb..b73ff43d3a 100644--- a/packages/views/issues/components/execution-log-section.tsx+++ b/packages/views/issues/components/execution-log-section.tsx@@ -30,6 +30,7 @@ import { TerminateTaskConfirmDialog } from "./terminate-task-confirm-dialog";import { IssueUsageDialog } from "./issue-usage-dialog";import { TaskStatusIcon } from "./task-status-icon";import { useStatusLabel, useTriggerText } from "./task-run-labels";+import { WakeupRunLabel } from "./wakeup-source-chip";// Right-panel section that lists every agent run for this issue. Active// runs sit at the top (always visible when present); past runs (terminal@@ -363,7 +364,11 @@ export function ActiveTaskRow({// same change that adds incremental reporting + cache invalidation.return (<RowShell task={task}>- <TriggerText text={trigger} />+ {task.wakeup_id ? (+ <WakeupRunLabel task={task} fallback={trigger} render={(label) => <TriggerText text={label} />} />+ ) : (+ <TriggerText text={trigger} />+ )}<TaskCommentCoverage task={task} /><RowStatus title={label}>{task.status === "running" ? (@@ -505,7 +510,11 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {return (<RowShell task={task} title={rowTitle}>- <TriggerText text={trigger} />+ {task.wakeup_id ? (+ <WakeupRunLabel task={task} fallback={trigger} render={(label) => <TriggerText text={label} />} />+ ) : (+ <TriggerText text={trigger} />+ )}<TaskCommentCoverage task={task} /><RowStatus title={statusTitle}><TaskStatusIcon status={task.status} />diff --git a/packages/views/issues/components/issue-agent-activity-indicator.test.tsx b/packages/views/issues/components/issue-agent-activity-indicator.test.tsxindex efccc79692..8e29a0ce40 100644--- a/packages/views/issues/components/issue-agent-activity-indicator.test.tsx+++ b/packages/views/issues/components/issue-agent-activity-indicator.test.tsx@@ -6,8 +6,12 @@ import type { AgentTask } from "@multica/core/types";const mockState = vi.hoisted(() => ({snapshot: [] as unknown[],summaries: [] as unknown[],+ paused: [] as unknown[],}));+vi.mock("./wakeup-condition-names", () => ({+ useConditionNames: () => ({ status: (key: string) => key, label: () => undefined, property: () => undefined, actor: (_type: string, id: string) => id }),+}));vi.mock("../../common/use-viewing-timezone", () => ({useViewingTimezone: () => "UTC",}));@@ -90,6 +94,10 @@ vi.mock("@tanstack/react-query", async () => {: mockState.snapshot,};}+ if (opts.queryKey?.[0] === "issue-wakeup-paused")+ return {+ data: opts.select ? opts.select(mockState.paused) : mockState.paused,+ };if (opts.queryKey?.[0] === "issue-wakeup-summaries")return {data: opts.select@@ -122,6 +130,7 @@ function makeTask(overrides: Partial<AgentTask> = {}): AgentTask {}beforeEach(() => {+ mockState.paused = [];cleanup();mockState.snapshot = [makeTask()];mockState.summaries = [];@@ -180,10 +189,24 @@ it("shows waiting and aggregate count even without an active run", () => {mockState.snapshot = [];mockState.summaries = [eventSummary];render(<IssueAgentActivityIndicator issueId="issue-1" hoverCard={false} />);- expect(screen.getByText("Waiting for trigger")).toBeInTheDocument();+ // The cue says what the issue waits for, in a few words.+ expect(screen.getByText("Waiting for a run to end")).toBeInTheDocument();expect(screen.getByText("+1")).toBeInTheDocument();expect(screen.queryByTestId("agent-avatar-stack")).toBeNull();});+it("names the person a reply wait is for", () => {+ mockState.snapshot = [];+ mockState.summaries = [{ ...eventSummary, event_types: ["comment.created"], filter_actor_type: "member", filter_actor_id: "u1", filter_actor_name: "Jiayuan" }];+ render(<IssueAgentActivityIndicator issueId="issue-1" hoverCard={false} />);+ expect(screen.getByText("Waiting for Jiayuan to reply")).toBeInTheDocument();+});+it("flags a rule the platform paused when nothing else is waiting", () => {+ mockState.snapshot = [];+ mockState.summaries = [];+ mockState.paused = [{ issue_id: "issue-1", id: "wake-9", agent_id: "agent-1", paused_reason: "loop" }];+ render(<IssueAgentActivityIndicator issueId="issue-1" hoverCard={false} />);+ expect(screen.getByText("Wakeup paused")).toBeInTheDocument();+});it("prioritizes active runs, marking wakeup origin separately from future count", () => {mockState.snapshot = [makeTask(),diff --git a/packages/views/issues/components/issue-agent-activity-indicator.tsx b/packages/views/issues/components/issue-agent-activity-indicator.tsxindex b0f8523f0b..0bf55dc121 100644--- a/packages/views/issues/components/issue-agent-activity-indicator.tsx+++ b/packages/views/issues/components/issue-agent-activity-indicator.tsx@@ -1,7 +1,7 @@"use client";import { memo, useCallback, useMemo, useState } from "react";-import { Bell, Clock3 } from "lucide-react";+import { Bell, Clock3, TriangleAlert } from "lucide-react";import { useQuery } from "@tanstack/react-query";import { ShimmerText } from "@multica/ui/components/common/shimmer-text";import {@@ -11,8 +11,8 @@ import {} from "@multica/ui/components/ui/hover-card";import { useWorkspaceId } from "@multica/core/hooks";import { agentTaskSnapshotOptions } from "@multica/core/agents";-import type { AgentTask, IssueWakeupSummaryRow } from "@multica/core/types";-import { workspaceWakeupSummariesOptions } from "@multica/core/issues/wakeups";+import type { AgentTask, IssueWakeupSummaryRow, PausedWakeup } from "@multica/core/types";+import { pausedWakeupsOptions, workspaceWakeupSummariesOptions } from "@multica/core/issues/wakeups";import { cn } from "@multica/ui/lib/utils";import type { AvatarSize } from "@multica/ui/lib/avatar-size";import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";@@ -109,6 +109,14 @@ export const IssueAgentActivityIndicator = memo(...workspaceWakeupSummariesOptions(wsId),select: selectWakeups,});+ const selectPaused = useCallback(+ (rows: PausedWakeup[]) => rows.some((row) => row.issue_id === issueId),+ [issueId],+ );+ const { data: paused = false } = useQuery({+ ...pausedWakeupsOptions(wsId),+ select: selectPaused,+ });const select = useCallback((snapshot: AgentTask[]) => selectIssueTasks(snapshot, issueId),[issueId],@@ -137,14 +145,15 @@ export const IssueAgentActivityIndicator = memo(const hasTasks = agentIds.length > 0;const hoverTasks = [...groups.running, ...groups.queued];const wakeupTriggered = hoverTasks.some((task) => !!task.wakeup_id);- if (!hasTasks && !wakeupCount) return null;+ if (!hasTasks && !wakeupCount && !paused) return null;const isRunning = opacity === "full";- const waitingLabel =- wakeups[0]?.kind === "event"- ? t(($) => $.wakeups.waiting_event)- : wakeups[0]- ? text.trigger(wakeups[0])- : "";+ // One sentence of what the issue waits for; a paused rule speaks up only+ // when nothing else is waiting, because it needs someone to look.+ const waitingLabel = wakeups[0]+ ? text.waiting(wakeups[0])+ : paused+ ? t(($) => $.wakeups.wait.paused)+ : "";const label = hasTasks? isRunning? t(($) => $.agent_activity.status_running)@@ -185,12 +194,14 @@ export const IssueAgentActivityIndicator = memo(</>) : (<>- {wakeups[0]?.kind === "event" ? (+ {!wakeups[0] ? (+ <TriangleAlert className="size-3 text-destructive" aria-hidden="true" />+ ) : wakeups[0].kind === "event" ? (<Bell className="size-3 text-muted-foreground" aria-hidden="true" />) : (<Clock3 className="size-3 text-muted-foreground" aria-hidden="true" />)}- <span className="max-w-36 truncate text-micro text-muted-foreground">+ <span className={cn("max-w-36 truncate text-micro", wakeups[0] ? "text-muted-foreground" : "text-destructive")}>{waitingLabel}</span>{wakeupCount > 1 && (@@ -226,6 +237,11 @@ export const IssueAgentActivityIndicator = memo(</HoverCardTrigger><HoverCardContent align="end" className="w-72">{hasTasks && <AgentActivityHoverContent tasks={hoverTasks} />}+ {paused && !wakeupCount && (+ <p className={cn("text-caption text-destructive", hasTasks && "mt-2 border-t border-border pt-2")}>+ {t(($) => $.wakeups.wait.paused)}+ </p>+ )}{wakeupCount > 0 && (<divclassName={cn(diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex f0522b4321..e26f330972 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -2066,6 +2066,8 @@ describe("IssueDetail (shared)", () => {expect(screen.getByText(/set this issue to keep its status when PRs merge/i)).toBeInTheDocument();});+ // MUL-7680: the child-done system rule's comment is the woken agent's+ // instruction; people read one timeline line that can reveal it.it("renders activity rows with unknown status values without crashing", async () => {mockApiObj.listTimeline.mockResolvedValue([{diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 0632b95f4a..2d9b213601 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -40,6 +40,13 @@ import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@multica/uimport { Sheet, SheetContent } from "@multica/ui/components/ui/sheet";import { useIsMobile } from "@multica/ui/hooks/use-mobile";import { ContentEditor, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useEditorUpload, PreviewSequenceProvider, collectPreviewSequence } from "../../editor";+import {+ WAKEUP_ACTIVITY_ACTIONS,+ WakeupActivityIcon,+ formatWakeupActivity,+ wakeupActivityChip,+} from "./wakeup-activity";+import { useWakeupText } from "./wakeup-presentation";import type { ImageSequenceBlock } from "@multica/core/attachments/image-sequence";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import {@@ -100,6 +107,7 @@ import { ResolvedThreadBar } from "./resolved-thread-bar";import { ThreadMinimap, type ThreadMinimapThread } from "./thread-minimap";import { collectThreadParticipants, collectThreadReplies, deriveThreadResolution } from "./thread-utils";import { IssueAgentHeaderChip } from "./issue-agent-header-chip";+import { IssueWakeupHeaderChip } from "./issue-wakeup-header-chip";import { ExecutionLogSection } from "./execution-log-section";import { WakeupsSection } from "./wakeups-section";import { QuickActionsSection } from "./quick-actions-section";@@ -662,6 +670,7 @@ function ActivityBlock({timeAgo: (dateStr: string) => string;locale: string;}) {+ const wakeupText = useWakeupText();if (!expanded) {const count = entries.length;return (@@ -723,8 +732,12 @@ function ActivityBlock({const isStartDateChange = entry.action === "start_date_changed";const isDueDateChange = entry.action === "due_date_changed";+ const isWakeup = WAKEUP_ACTIVITY_ACTIONS.has(entry.action ?? "");+ const chip = isWakeup ? wakeupActivityChip(entry, t, wakeupText, getActorName) : null;let leadIcon: React.ReactNode;- if ((isStatusChange && details.to) || markedDuplicate || unmarkedDuplicate) {+ if (isWakeup) {+ leadIcon = <WakeupActivityIcon entry={entry} />;+ } else if ((isStatusChange && details.to) || markedDuplicate || unmarkedDuplicate) {const to = markedDuplicate ? "cancelled" : details.to;leadIcon = (<StatusIcon@@ -760,15 +773,27 @@ function ActivityBlock({{leadIcon}</div><div className="flex min-w-0 flex-1 items-center gap-1">- <span className="shrink-0 font-medium">- {entry.actor_name || getActorName(entry.actor_type, entry.actor_id)}- </span>+ {/* The platform's own entries read as a sentence without an actor. */}+ {!(isWakeup && entry.actor_type === "system") && (+ <span className="shrink-0 font-medium">+ {entry.actor_name || getActorName(entry.actor_type, entry.actor_id)}+ </span>+ )}<span className="truncate"><ActivityTextentry={entry}- text={formatActivity(entry, t, locale, getActorName, resolveStatusLabel)}+ text={+ isWakeup+ ? formatWakeupActivity(entry, t, wakeupText, getActorName)+ : formatActivity(entry, t, locale, getActorName, resolveStatusLabel)+ }/></span>+ {chip && (+ <span className="ml-auto inline-flex max-w-48 shrink-0 items-center gap-1 truncate rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">+ {chip}+ </span>+ )}{(entry.coalesced_count ?? 1) > 1 &&entry.action !== "task_completed" &&entry.action !== "task_failed" && (@@ -779,7 +804,7 @@ function ActivityBlock({<Tooltip><TooltipTriggerrender={- <span className="ml-auto shrink-0 cursor-default">+ <span className={cn("shrink-0 cursor-default", !chip && "ml-auto")}>{timeAgo(entry.created_at)}</span>}@@ -1660,10 +1685,14 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// - all other actions: within a 2-minute window// - squad_leader_evaluated: never coalesce; outcome/reason are audit dataconst COALESCE_MS = 2 * 60 * 1000;- const NO_TIME_LIMIT_ACTIONS = new Set(["task_completed", "task_failed"]);+ const NO_TIME_LIMIT_ACTIONS = new Set(["task_completed", "task_failed", "wakeup_checkin"]);// Duplicate marks name a different issue on every row.const NEVER_COALESCE_ACTIONS = new Set(["squad_leader_evaluated",+ "wakeup_created",+ "wakeup_triggered",+ "wakeup_timed_out",+ "wakeup_paused","duplicate_marked","duplicate_unmarked","duplicate_added",@@ -2534,6 +2563,17 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr});}, [beginDesktopSidebarToggle, isMobile, sidebarRef]);+ // The header's wakeup chip opens the sidebar and brings the Wakeups section+ // into view with focus on its heading.+ const openWakeups = useCallback(() => {+ if (!sidebarOpen) handleToggleSidebar();+ window.requestAnimationFrame(() => {+ const heading = document.getElementById(`issue-wakeups-${id}`);+ heading?.scrollIntoView({ block: "nearest" });+ heading?.focus({ preventScroll: true });+ });+ }, [handleToggleSidebar, id, sidebarOpen]);+useRightSidebarShortcut(rightSidebarShortcutTargetRef, handleToggleSidebar);useIssueDetailScrollRestore({@@ -2827,7 +2867,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trclick an action they cannot run, and the refusal is explained at runtime rather than by a silently shorter list. */}<QuickActionsSection issueId={issue.id} />- <WakeupsSection issueId={issue.id} closed={["done", "closed"].includes(resolveStatusCategory(issue.status))} />+ <WakeupsSection+ issueId={issue.id}+ closed={["done", "closed"].includes(resolveStatusCategory(issue.status))}+ defaultAgentId={issue.assignee_type === "agent" ? (issue.assignee_id ?? undefined) : undefined}+ /><PluginPanelSection issueId={issue.id} />{/* Parent issue — standalone section, only when the issue has a@@ -3119,6 +3163,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trit never overlaps the title (which truncates to make room).It self-hides when no agent is active. */}<IssueAgentHeaderChip issueId={id} />+ <IssueWakeupHeaderChip issueId={id} onOpen={openWakeups} />{onDone && !issueBehavesAsAny(issue, ["done", "closed"]) && (<Tooltip><TooltipTriggerdiff --git a/packages/views/issues/components/issue-usage-dialog.tsx b/packages/views/issues/components/issue-usage-dialog.tsxindex e61be2fc7b..c55cfb050a 100644--- a/packages/views/issues/components/issue-usage-dialog.tsx+++ b/packages/views/issues/components/issue-usage-dialog.tsx@@ -25,6 +25,7 @@ import {} from "../../runtimes/utils";import { KpiCard } from "../../runtimes/components/shared";import { useStatusLabel, useTriggerText } from "./task-run-labels";+import { WakeupRunLabel } from "./wakeup-source-chip";import { TaskStatusIcon } from "./task-status-icon";// Per-run cost breakdown for one issue — the surface the execution log's@@ -341,7 +342,9 @@ function RunRow({ task, maxTokens }: { task: AgentTask; maxTokens: number }) {<td className="!pl-0 !text-left"><div className="flex items-center gap-2"><ActorAvatar actorType="agent" actorId={task.agent_id} size="sm" enableHoverCard />- <span className="max-w-[13rem] truncate">{trigger}</span>+ <span className="max-w-[13rem] truncate">+ {task.wakeup_id ? <WakeupRunLabel task={task} fallback={trigger} render={(label) => label} /> : trigger}+ </span>{task.status === "running" ? (<span className="inline-flex shrink-0 items-center gap-1 text-micro text-info"><span className="h-1.5 w-1.5 rounded-full bg-info" />diff --git a/packages/views/issues/components/issue-wakeup-header-chip.test.tsx b/packages/views/issues/components/issue-wakeup-header-chip.test.tsxnew file mode 100644index 0000000000..d7667be4e7--- /dev/null+++ b/packages/views/issues/components/issue-wakeup-header-chip.test.tsx@@ -0,0 +1,79 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, screen } from "@testing-library/react";+import type { IssueWakeup, SystemWakeup } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { IssueWakeupHeaderChip, primaryWakeup } from "./issue-wakeup-header-chip";++let rules: IssueWakeup[] = [];+let system: SystemWakeup[] = [];+vi.mock("./wakeup-condition-names", () => ({+ useConditionNames: () => ({ status: (key: string) => key, label: () => undefined, property: () => undefined, actor: (_type: string, id: string) => id }),+}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));+vi.mock("@multica/core/issues", () => ({+ issueWakeupsOptions: () => ({ queryKey: ["wakeups"] }),+ issueSystemWakeupsOptions: () => ({ queryKey: ["system"] }),+}));+vi.mock("@tanstack/react-query", () => ({+ useQuery: ({ queryKey }: { queryKey: string[] }) => ({ data: queryKey[0] === "wakeups" ? rules : system }),+}));+vi.mock("../../common/use-viewing-timezone", () => ({ useViewingTimezone: () => "UTC" }));++const rule = (patch: Partial<IssueWakeup>): IssueWakeup => ({+ id: "w", issue_id: "issue", agent_id: "a", agent_name: "Emacs", instruction: "", kind: "event", mode: "once",+ event_types: ["comment.created"], filter_agent_id: null, filter_task_id: null, interval_seconds: null,+ cron_expression: null, timezone: "UTC", next_fire_at: null, enabled: true, disabled_at: null,+ last_task_id: null, last_error: null, ...patch,+});+const childDone: SystemWakeup = {+ id: "rule", revision: 1, default_instruction: "", customized: false, paused_reason: null,+ rule: "child_done", enabled: true, instruction: "", staged: true, stage: 2, total: 2, remaining: 1,+ waiting: [], target: { type: "agent", id: "a", name: "Grok" }, blocked: "", workspace_default: true,+};++beforeEach(() => {+ rules = [];+ system = [];+});++describe("primaryWakeup", () => {+ it("prefers a waiting rule, then the soonest schedule, then the system rule", () => {+ const later = rule({ id: "later", kind: "at", next_fire_at: "2030-01-02T00:00:00Z" });+ const sooner = rule({ id: "sooner", kind: "at", next_fire_at: "2030-01-01T00:00:00Z" });+ const reply = rule({ id: "reply" });+ expect(primaryWakeup([later, sooner, reply], [childDone])).toMatchObject({ kind: "rule", rule: { id: "reply" }, count: 4 });+ expect(primaryWakeup([later, sooner], [])).toMatchObject({ rule: { id: "sooner" }, count: 2 });+ expect(primaryWakeup([], [childDone])).toMatchObject({ kind: "system", count: 1 });+ expect(primaryWakeup([], [{ ...childDone, blocked: "backlog" }])).toBeNull();+ });++ it("falls back to a paused rule only when nothing else waits", () => {+ const paused = rule({ enabled: false, paused_reason: "loop" });+ expect(primaryWakeup([paused], [])).toMatchObject({ kind: "paused" });+ expect(primaryWakeup([paused, rule({ id: "live" })], [])).toMatchObject({ kind: "rule", rule: { id: "live" } });+ });+});++describe("IssueWakeupHeaderChip", () => {+ it("says who waits for what, counts the rest and opens the wakeups", () => {+ rules = [rule({ filter_actor_type: "member", filter_actor_id: "u", filter_actor_name: "Jiayuan" }), rule({ id: "w2", kind: "at", next_fire_at: "2030-01-01T00:00:00Z" })];+ system = [childDone];+ const onOpen = vi.fn();+ renderWithI18n(<IssueWakeupHeaderChip issueId="issue" onOpen={onOpen} />, { locale: "zh-Hans" });+ const chip = screen.getByRole("button", { name: /Emacs 在等 Jiayuan 回复 \+2/ });+ expect(chip).toHaveTextContent("Emacs 在等 Jiayuan 回复+2");+ fireEvent.click(chip);+ expect(onOpen).toHaveBeenCalled();+ });++ it("names the system rule's target stage", () => {+ system = [childDone];+ renderWithI18n(<IssueWakeupHeaderChip issueId="issue" onOpen={() => {}} />, { locale: "zh-Hans" });+ expect(screen.getByRole("button", { name: /Grok 在等第 2 阶段完成/ })).toBeVisible();+ });++ it("renders nothing when the issue waits for nothing", () => {+ const { container } = renderWithI18n(<IssueWakeupHeaderChip issueId="issue" onOpen={() => {}} />);+ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/packages/views/issues/components/issue-wakeup-header-chip.tsx b/packages/views/issues/components/issue-wakeup-header-chip.tsxnew file mode 100644index 0000000000..20253f349f--- /dev/null+++ b/packages/views/issues/components/issue-wakeup-header-chip.tsx@@ -0,0 +1,85 @@+"use client";++import { memo } from "react";+import { useQuery } from "@tanstack/react-query";+import { Bell, TriangleAlert } from "lucide-react";+import { issueSystemWakeupsOptions, issueWakeupsOptions } from "@multica/core/issues";+import type { IssueWakeup, SystemWakeup } from "@multica/core/types";+import { useWorkspaceId } from "@multica/core/hooks";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../../i18n";+import { useWakeupText } from "./wakeup-presentation";++/**+ * Picks what the header says an issue is waiting for: the first rule waiting+ * on an event or condition, else the soonest scheduled one, else the+ * sub-issue system rule. A rule the platform paused is shown only when+ * nothing else is waiting, because it needs someone to look at it.+ */+export function primaryWakeup(rules: readonly IssueWakeup[], system: readonly SystemWakeup[]) {+ const enabled = rules.filter((w) => w.enabled);+ const waiting = enabled.filter((w) => w.kind === "event");+ const scheduled = enabled+ .filter((w) => w.kind !== "event")+ .sort((a, b) => Date.parse(a.next_fire_at ?? "") - Date.parse(b.next_fire_at ?? ""));+ const systemRule = system.find((r) => r.enabled && !r.blocked && r.target);+ const count = enabled.length + (systemRule ? 1 : 0);+ const rule = waiting[0] ?? scheduled[0];+ if (rule) return { kind: "rule" as const, rule, count };+ if (systemRule) return { kind: "system" as const, rule: systemRule, count };+ const paused = rules.find((w) => !w.enabled && w.paused_reason);+ if (paused) return { kind: "paused" as const, rule: paused, count: 1 };+ return null;+}++/**+ * One line in the issue header saying what the issue is waiting for, e.g.+ * "Emacs is waiting for Jiayuan to reply +2". Opens the Wakeups section.+ */+export const IssueWakeupHeaderChip = memo(function IssueWakeupHeaderChip({+ issueId,+ onOpen,+}: {+ issueId: string;+ onOpen: () => void;+}) {+ const { t } = useT("issues");+ const wsId = useWorkspaceId();+ const text = useWakeupText();+ const { data: rules = [] } = useQuery(issueWakeupsOptions(wsId, issueId));+ const { data: system = [] } = useQuery(issueSystemWakeupsOptions(wsId, issueId));+ const primary = primaryWakeup(rules, system);+ if (!primary) return null;+ const label = String(+ primary.kind === "rule"+ ? text.headline(primary.rule)+ : primary.kind === "system"+ ? t(($) => $.wakeups.wait.header, {+ agent: primary.rule.target?.name ?? "",+ what:+ primary.rule.staged && primary.rule.stage !== null+ ? t(($) => $.wakeups.wait.children_stage, { stage: primary.rule.stage })+ : t(($) => $.wakeups.wait.children_all),+ })+ : t(($) => $.wakeups.wait.paused),+ );+ const Icon = primary.kind === "paused" ? TriangleAlert : Bell;+ return (+ <button+ type="button"+ onClick={onOpen}+ title={label}+ aria-label={`${label}${primary.count > 1 ? ` +${primary.count - 1}` : ""} · ${t(($) => $.wakeups.wait.open)}`}+ className={cn(+ "inline-flex h-7 max-w-72 min-w-0 items-center gap-1.5 rounded-full border border-border px-2.5 text-caption hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring",+ primary.kind === "paused" ? "text-warning" : "text-foreground",+ )}+ >+ <Icon className="size-3.5 shrink-0" aria-hidden="true" />+ <span className="min-w-0 truncate max-sm:hidden">{label}</span>+ {primary.count > 1 && (+ <span className="shrink-0 tabular-nums text-muted-foreground">+{primary.count - 1}</span>+ )}+ </button>+ );+});diff --git a/packages/views/issues/components/system-wakeup-row.tsx b/packages/views/issues/components/system-wakeup-row.tsxnew file mode 100644index 0000000000..36078ddd43--- /dev/null+++ b/packages/views/issues/components/system-wakeup-row.tsx@@ -0,0 +1,249 @@+"use client";++import { useId, useState } from "react";+import { ListChecks, Pencil } from "lucide-react";+import { toast } from "sonner";+import { useUpdateIssueSystemWakeup } from "@multica/core/issues";+import type { SystemWakeup } from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import { Switch } from "@multica/ui/components/ui/switch";+import { Textarea } from "@multica/ui/components/ui/textarea";+import {+ Popover,+ PopoverContent,+ PopoverTitle,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import { useT } from "../../i18n";+import { useWakeupText } from "./wakeup-presentation";++const MAX_INSTRUCTION_BYTES = 4000;++/** The platform's child-done wakeup, shown beside the rules people created. */+export function SystemWakeupRow({+ rule,+ workspaceId,+ issueId,+}: {+ rule: SystemWakeup;+ workspaceId: string;+ issueId: string;+}) {+ const { t } = useT("issues");+ const text = useWakeupText();+ const update = useUpdateIssueSystemWakeup(workspaceId, issueId);+ const title =+ rule.staged && rule.stage !== null+ ? t(($) => $.wakeups.system.title_stage, { stage: rule.stage })+ : t(($) => $.wakeups.system.title_all);+ const blocked = {+ "": null,+ backlog: t(($) => $.wakeups.system.blocked_backlog),+ member_assignee: t(($) => $.wakeups.system.blocked_member),+ no_assignee: t(($) => $.wakeups.system.blocked_none),+ }[rule.blocked];+ const paused = rule.paused_reason+ ? t(($) => $.wakeups.system.paused, {+ reason: text.pausedReason({ paused_reason: rule.paused_reason, max_fires: null, fire_count: 0 }) ?? "",+ })+ : null;+ const target =+ rule.target?.type === "member"+ ? t(($) => $.wakeups.system.notify_member, { name: rule.target.name })+ : t(($) => $.wakeups.system.wake_assignee, { name: rule.target?.name ?? "" });+ const summary =+ paused ??+ (!rule.enabled+ ? t(($) => $.wakeups.system.turned_off)+ : rule.blocked && rule.blocked !== "member_assignee"+ ? blocked+ : [target, t(($) => $.wakeups.system.remaining, { count: rule.remaining })].join(" · "));+ const save = (input: { enabled: boolean; instruction: string }) =>+ update.mutateAsync({ rule: rule.rule, ...input });+ const toggle = (enabled: boolean) =>+ void save({ enabled, instruction: rule.instruction }).catch(() =>+ toast.error(t(($) => $.wakeups.system.save_error)),+ );+ return (+ <div className="grid grid-cols-[minmax(0,1fr)_auto]" aria-busy={update.isPending}>+ <Popover>+ <PopoverTrigger+ render={+ <button+ type="button"+ className="col-span-2 col-start-1 row-start-1 grid min-w-0 grid-cols-subgrid rounded-md py-1.5 text-left text-caption hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring"+ />+ }+ >+ <span className="flex min-h-8 min-w-0 items-start gap-2 py-1 pl-2 pr-1">+ <ListChecks className="mt-px size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />+ <span className="line-clamp-2 min-w-0 break-words font-medium">{title}</span>+ <SystemBadge />+ </span>+ <span className={`col-span-2 min-w-0 break-words pl-7.5 pr-2 ${paused ? "text-warning" : "text-muted-foreground"}`}>+ {summary}+ </span>+ </PopoverTrigger>+ <PopoverContent align="end" className="max-h-[70dvh] w-80 max-w-[calc(100vw-2rem)] overflow-y-auto" keepMounted>+ <div className="flex items-start gap-2">+ <PopoverTitle className="flex-1">{title}</PopoverTitle>+ <SystemBadge />+ </div>+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-2 text-caption">+ <dt className="text-muted-foreground">{t(($) => $.wakeups.system.target_title)}</dt>+ <dd>+ {rule.target+ ? t(($) => $.wakeups.system.target_current, { name: rule.target.name })+ : t(($) => $.wakeups.system.target_none)}+ </dd>+ <dt className="text-muted-foreground">{t(($) => $.wakeups.system.progress_title)}</dt>+ <dd>+ {t(($) => $.wakeups.system.progress, { done: rule.total - rule.remaining, total: rule.total })}+ {rule.waiting.length > 0 &&+ ` · ${t(($) => $.wakeups.system.waiting_on, { ids: rule.waiting.join(", ") })}`}+ </dd>+ <dt className="text-muted-foreground">{t(($) => $.wakeups.system.skip_title)}</dt>+ <dd>{t(($) => $.wakeups.system.skip)}</dd>+ <dt className="text-muted-foreground">{t(($) => $.wakeups.source_title)}</dt>+ <dd>{t(($) => $.wakeups.system.source)}</dd>+ </dl>+ <InstructionEditor rule={rule} pending={update.isPending} onSave={save} />+ <div className="flex items-center gap-2 border-t border-border pt-2.5">+ <span className="flex-1 text-caption">{t(($) => $.wakeups.system.enable)}</span>+ <Switch+ checked={rule.enabled}+ disabled={update.isPending}+ aria-label={t(($) => $.wakeups.system.toggle)}+ onCheckedChange={toggle}+ />+ </div>+ <p className="text-caption text-muted-foreground">+ {rule.workspace_default ? t(($) => $.wakeups.system.default_on) : t(($) => $.wakeups.system.default_off)}+ </p>+ </PopoverContent>+ </Popover>+ <div className="z-10 col-start-2 row-start-1 flex min-h-11 items-center self-start px-2">+ <Switch+ checked={rule.enabled}+ disabled={update.isPending}+ aria-label={t(($) => $.wakeups.system.toggle)}+ onCheckedChange={toggle}+ />+ </div>+ </div>+ );+}++function SystemBadge() {+ const { t } = useT("issues");+ return (+ <span className="mt-px shrink-0 rounded-xs bg-muted px-1.5 text-micro font-medium text-muted-foreground">+ {t(($) => $.wakeups.system.badge)}+ </span>+ );+}++function InstructionEditor({+ rule,+ pending,+ onSave,+}: {+ rule: SystemWakeup;+ pending: boolean;+ onSave: (input: { enabled: boolean; instruction: string }) => Promise<unknown>;+}) {+ const { t } = useT("issues");+ const id = useId();+ const [editing, setEditing] = useState(false);+ const [value, setValue] = useState(rule.instruction);+ const [error, setError] = useState("");+ const label = t(($) => $.wakeups.system.instruction);+ if (!editing) {+ return (+ <div>+ <div className="flex items-center justify-between gap-2">+ <p className="text-caption font-medium">{label}</p>+ <Button+ variant="ghost"+ size="icon-xs"+ className="text-muted-foreground"+ aria-label={t(($) => $.wakeups.system.instruction_edit)}+ onClick={() => {+ setValue(rule.instruction);+ setError("");+ setEditing(true);+ }}+ >+ <Pencil aria-hidden="true" />+ </Button>+ </div>+ {rule.instruction ? (+ <p className="whitespace-pre-wrap break-words text-caption">{rule.instruction}</p>+ ) : (+ <div className="text-caption text-muted-foreground">+ <p>{t(($) => $.wakeups.system.instruction_default)}</p>+ <p className="mt-1 line-clamp-4 whitespace-pre-wrap break-words" title={rule.default_instruction}>+ {rule.default_instruction}+ </p>+ </div>+ )}+ </div>+ );+ }+ return (+ <form+ className="space-y-2"+ onSubmit={async (event) => {+ event.preventDefault();+ const instruction = value.trim();+ if (new TextEncoder().encode(instruction).length > MAX_INSTRUCTION_BYTES) {+ setError(t(($) => $.wakeups.system.instruction_invalid));+ return;+ }+ try {+ await onSave({ enabled: rule.enabled, instruction });+ setEditing(false);+ } catch {+ setError(t(($) => $.wakeups.system.save_error));+ }+ }}+ >+ <label htmlFor={id} className="text-caption font-medium">+ {label}+ </label>+ <Textarea+ id={id}+ rows={5}+ value={value}+ placeholder={rule.default_instruction || t(($) => $.wakeups.system.instruction_placeholder)}+ className="resize-y text-base md:text-caption"+ disabled={pending}+ aria-invalid={!!error}+ aria-describedby={error ? `${id}-error` : undefined}+ onChange={(event) => {+ setValue(event.target.value);+ setError("");+ }}+ onKeyDown={(event) => {+ if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && !event.nativeEvent.isComposing) {+ event.preventDefault();+ event.currentTarget.form?.requestSubmit();+ }+ }}+ />+ {error && (+ <p id={`${id}-error`} role="alert" className="text-caption text-destructive">+ {error}+ </p>+ )}+ <div className="flex justify-end gap-2">+ <Button type="button" variant="ghost" size="sm" disabled={pending} onClick={() => setEditing(false)}>+ {t(($) => $.wakeups.instruction_cancel)}+ </Button>+ <Button type="submit" size="sm" disabled={pending || value.trim() === rule.instruction}>+ {t(($) => (pending ? $.wakeups.instruction_saving : $.wakeups.instruction_save))}+ </Button>+ </div>+ </form>+ );+}diff --git a/packages/views/issues/components/task-run-labels.ts b/packages/views/issues/components/task-run-labels.tsindex fdd06dd112..371d043c4e 100644--- a/packages/views/issues/components/task-run-labels.ts+++ b/packages/views/issues/components/task-run-labels.ts@@ -33,6 +33,9 @@ export function useTriggerText(task: AgentTask): string {? t(($) => $.execution_log.trigger_retry_attempt_prefix, { attempt: task.attempt }): t(($) => $.execution_log.trigger_retry_prefix): "";+ // A wakeup run's stored summary is the rule's instruction; it reads as+ // the wakeup instead. WakeupRunLabel adds the rule's condition.+ if (task.wakeup_id) return retryPrefix + t(($) => $.wakeups.triggered_by_wakeup);if (task.trigger_summary) return retryPrefix + stripMentionMarkdown(task.trigger_summary);if (isRetry) {diff --git a/packages/views/issues/components/wakeup-activity.test.tsx b/packages/views/issues/components/wakeup-activity.test.tsxnew file mode 100644index 0000000000..21aa65a428--- /dev/null+++ b/packages/views/issues/components/wakeup-activity.test.tsx@@ -0,0 +1,82 @@+import { describe, expect, it, vi } from "vitest";+import { renderHook } from "@testing-library/react";+import type { TimelineEntry } from "@multica/core/types";+import { I18nProvider } from "@multica/core/i18n/react";+import { RESOURCES } from "../../test/i18n";+import { useT } from "../../i18n";+import { useWakeupText } from "./wakeup-presentation";+import { formatWakeupActivity, wakeupActivityChip } from "./wakeup-activity";++vi.mock("./wakeup-condition-names", () => ({+ useConditionNames: () => ({ status: (key: string) => key, label: () => undefined, property: () => undefined, actor: (_type: string, id: string) => id }),+}));+vi.mock("../../common/use-viewing-timezone", () => ({ useViewingTimezone: () => "UTC" }));++const names: Record<string, string> = { a: "Emacs", u: "Jiayuan", g: "Grok" };+const getActorName = (_type: string, id: string) => names[id] ?? id;+const entry = (action: string, details: Record<string, unknown>, patch: Partial<TimelineEntry> = {}): TimelineEntry =>+ ({ type: "activity", id: action, actor_type: "system", actor_id: "", action, details, created_at: "2026-09-24T00:00:00Z", ...patch }) as TimelineEntry;+const reply = { id: "w", kind: "event", mode: "once", event_types: ["comment.created"], agent_id: "a", filter_actor_type: "member", filter_actor_id: "u", created_by: "u" };++function helpers() {+ const { result } = renderHook(() => ({ t: useT("issues").t, text: useWakeupText() }), {+ wrapper: ({ children }) => (+ <I18nProvider locale="zh-Hans" resources={RESOURCES}>+ {children}+ </I18nProvider>+ ),+ });+ return result.current;+}++describe("wakeup timeline entries", () => {+ it("reads each entry as one sentence", () => {+ const { t, text } = helpers();+ const read = (e: TimelineEntry) => formatWakeupActivity(e, t, text, getActorName);+ expect(read(entry("wakeup_created", { wakeup: reply }, { actor_type: "agent", actor_id: "a" }))).toBe(+ "添加了唤醒:当此任务有新评论时(由 Jiayuan 触发)唤醒 Emacs",+ );+ expect(read(entry("wakeup_triggered", { wakeup: { ...reply, condition: { type: "pull_request", event: "checks_finished" } } }))).toBe(+ "当关联 PR 的 CI 结束时,唤醒了 Emacs",+ );+ expect(read(entry("wakeup_triggered", { wakeup: reply, events: ["wakeup.manual"], actor_type: "member", actor_id: "u" }))).toBe(+ "Jiayuan 立即唤醒了 Emacs",+ );+ expect(read(entry("wakeup_triggered", { rule: "child_done", stage: 1, total: 2, target_type: "agent", target_id: "a", outcome: "woke" }))).toBe(+ "第 1 阶段的 2 个子任务已全部结束,唤醒了 Emacs",+ );+ expect(read(entry("wakeup_triggered", { rule: "child_done", total: 3, target_type: "member", target_id: "u", outcome: "notified" }))).toBe(+ "3 个子任务已全部结束,已通知 Jiayuan",+ );+ expect(read(entry("wakeup_triggered", { rule: "child_done", total: 3, target_type: "agent", target_id: "a", outcome: "merged" }))).toBe(+ "3 个子任务已全部结束,并入了 Emacs 待开始的运行",+ );+ expect(read(entry("wakeup_triggered", { rule: "child_done", stage: 2, total: 1, outcome: "none" }))).toBe(+ "第 2 阶段的 1 个子任务已全部结束",+ );+ expect(read(entry("wakeup_triggered", { rule: "child_done", stage: 1, total: 2, target_type: "agent", target_id: "a", outcome: "acknowledged" }))).toBe(+ "第 1 阶段的 2 个子任务已全部结束,Emacs 正在处理,未重复唤醒",+ );+ expect(read(entry("wakeup_triggered", { wakeup: reply, outcome: "merged" }))).toBe(+ "当此任务有新评论时(由 Jiayuan 触发),并入了 Emacs 待开始的运行",+ );+ expect(read(entry("wakeup_triggered", { wakeup: reply, outcome: "acknowledged" }))).toBe(+ "当此任务有新评论时(由 Jiayuan 触发),由 Emacs 自己触发,未重复唤醒",+ );+ expect(read(entry("wakeup_timed_out", { wakeup: reply, woke: true }))).toContain("唤醒了 Emacs 处理超时");+ expect(read(entry("wakeup_paused", { wakeup: reply, reason: "loop" }))).toBe("已暂停:与其他唤醒规则互相触发");+ expect(read(entry("wakeup_checkin", { wakeup: reply, note: "进度 72%" }, { actor_type: "agent", actor_id: "g", coalesced_count: 3 }))).toBe(+ "静默检查 3 次 · 最近一次:进度 72%",+ );+ });++ it("tags an entry with the rule it came from", () => {+ const { t, text } = helpers();+ const chip = (e: TimelineEntry) => wakeupActivityChip(e, t, text, getActorName);+ expect(chip(entry("wakeup_triggered", { rule: "child_done" }))).toBe("系统规则");+ expect(chip(entry("wakeup_triggered", { wakeup: reply }))).toBe("Jiayuan 创建");+ expect(chip(entry("wakeup_triggered", { wakeup: { ...reply, created_by_agent_id: "a" } }))).toBe("Emacs 创建");+ expect(chip(entry("wakeup_created", { wakeup: reply }))).toBeNull();+ });++});diff --git a/packages/views/issues/components/wakeup-activity.tsx b/packages/views/issues/components/wakeup-activity.tsxnew file mode 100644index 0000000000..2aa9019126--- /dev/null+++ b/packages/views/issues/components/wakeup-activity.tsx@@ -0,0 +1,190 @@+"use client";++import { Bell, Clock3, Hourglass, ListChecks, RefreshCw, TriangleAlert } from "lucide-react";+import type { TimelineEntry, WakeupCondition, WakeupPreview } from "@multica/core/types";+import { useT } from "../../i18n";+import type { useWakeupText } from "./wakeup-presentation";+import { conditionIcon } from "./wakeups-section";++type IssuesT = ReturnType<typeof useT<"issues">>["t"];+type WakeupText = ReturnType<typeof useWakeupText>;+type ActorName = (type: string, id: string) => string;++/** Timeline entries the wakeup service and the child-done rule write. */+export const WAKEUP_ACTIVITY_ACTIONS = new Set([+ "wakeup_created",+ "wakeup_triggered",+ "wakeup_timed_out",+ "wakeup_paused",+ "wakeup_checkin",+]);++interface StoredPreview {+ id?: string;+ kind?: WakeupPreview["kind"];+ mode?: WakeupPreview["mode"];+ event_types?: string[];+ agent_id?: string;+ timezone?: string;+ condition?: WakeupCondition;+ filter_actor_type?: "member" | "agent";+ filter_actor_id?: string;+ filter_agent_id?: string;+ interval_seconds?: number;+ cron_expression?: string;+ next_fire_at?: string;+ created_by?: string;+ created_by_agent_id?: string;+}++interface WakeupDetails {+ wakeup?: StoredPreview;+ rule?: "child_done";+ stage?: number;+ total?: number;+ target_type?: string;+ target_id?: string;+ /**+ * woke (a run), notified (a member), merged (joined a run already waiting+ * to start), acknowledged (the agent's own action; no run), none.+ */+ outcome?: "woke" | "notified" | "merged" | "acknowledged" | "none";+ events?: string[];+ actor_type?: string;+ actor_id?: string;+ woke?: boolean;+ reason?: "max_fires" | "loop" | "rate";+ limit?: number;+ note?: string;+}++function detailsOf(entry: TimelineEntry): WakeupDetails {+ return (entry.details ?? {}) as WakeupDetails;+}++/**+ * The rule as it was when the entry was written, in the shape the wakeup text+ * helpers read. Names come from the workspace directory.+ */+function previewOf(stored: StoredPreview, getActorName: ActorName): WakeupPreview {+ return {+ id: stored.id ?? "",+ issue_id: "",+ agent_id: stored.agent_id ?? "",+ agent_name: stored.agent_id ? getActorName("agent", stored.agent_id) : "",+ kind: stored.kind ?? "event",+ mode: stored.mode ?? "once",+ event_types: stored.event_types ?? [],+ filter_task_id: null,+ filter_agent_name: stored.filter_agent_id ? getActorName("agent", stored.filter_agent_id) : null,+ filter_actor_type: stored.filter_actor_type ?? null,+ filter_actor_id: stored.filter_actor_id ?? null,+ filter_actor_name: stored.filter_actor_type && stored.filter_actor_id ? getActorName(stored.filter_actor_type, stored.filter_actor_id) : null,+ interval_seconds: stored.interval_seconds ?? null,+ cron_expression: stored.cron_expression ?? null,+ timezone: stored.timezone ?? "UTC",+ next_fire_at: stored.next_fire_at ?? null,+ condition: stored.condition ?? null,+ };+}++export function formatWakeupActivity(+ entry: TimelineEntry,+ t: IssuesT,+ text: WakeupText,+ getActorName: ActorName,+): string {+ const details = detailsOf(entry);+ const preview = details.wakeup ? previewOf(details.wakeup, getActorName) : null;+ const condition = preview ? text.trigger(preview) : "";+ const agent = preview?.agent_name ?? "";+ switch (entry.action) {+ case "wakeup_created":+ return t(($) => $.activity.wakeup_created, { condition, agent });+ case "wakeup_triggered": {+ if (details.rule === "child_done") {+ const count = details.total ?? 1;+ const closed = details.stage+ ? t(($) => $.activity.wakeup_child_done_stage, { stage: details.stage, count })+ : t(($) => $.activity.wakeup_child_done_all, { count });+ // The squad's leader ran, but the entry names the assignee people see.+ const name =+ details.target_type && details.target_id+ ? getActorName(details.target_type, details.target_id)+ : t(($) => $.activity.wakeup_assignee);+ const outcome = details.outcome ?? (details.target_type ? "woke" : "none");+ switch (outcome) {+ case "woke":+ return closed + t(($) => $.activity.wakeup_child_done_woke, { name });+ case "notified":+ return closed + t(($) => $.activity.wakeup_child_done_notified, { name });+ case "merged":+ return closed + t(($) => $.activity.wakeup_child_done_merged, { name });+ case "acknowledged":+ return closed + t(($) => $.activity.wakeup_child_done_acknowledged, { name });+ default:+ return closed;+ }+ }+ if (details.events?.length === 1 && details.events[0] === "wakeup.manual" && details.actor_id) {+ return t(($) => $.activity.wakeup_triggered_manual, { name: getActorName("member", details.actor_id), agent });+ }+ if (details.outcome === "merged") return t(($) => $.activity.wakeup_triggered_merged, { condition, agent });+ if (details.outcome === "acknowledged") return t(($) => $.activity.wakeup_triggered_acknowledged, { condition, agent });+ return t(($) => $.activity.wakeup_triggered, { condition, agent });+ }+ case "wakeup_timed_out":+ return details.woke+ ? t(($) => $.activity.wakeup_timed_out_wake, { condition, agent })+ : t(($) => $.activity.wakeup_timed_out_end, { condition });+ case "wakeup_paused":+ return text.paused({ paused_reason: details.reason ?? "rate", max_fires: details.limit ?? null, fire_count: details.limit ?? 0 }) ?? "";+ case "wakeup_checkin": {+ const count = entry.coalesced_count ?? 1;+ const note = details.note ?? "";+ return count > 1+ ? t(($) => $.activity.wakeup_checkin_coalesced, { count, note })+ : t(($) => $.activity.wakeup_checkin, { note });+ }+ default:+ return entry.action ?? "";+ }+}++/**+ * The small tag on the right of an entry that names the rule it came from:+ * the system rule, a schedule for check-ins, or who created the rule.+ */+export function wakeupActivityChip(+ entry: TimelineEntry,+ t: IssuesT,+ text: WakeupText,+ getActorName: ActorName,+): string | null {+ const details = detailsOf(entry);+ if (details.rule === "child_done") return t(($) => $.activity.wakeup_chip_system);+ if (entry.action === "wakeup_created" || !details.wakeup) return null;+ if (entry.action === "wakeup_checkin") return text.trigger(previewOf(details.wakeup, getActorName));+ const creator = details.wakeup.created_by_agent_id+ ? getActorName("agent", details.wakeup.created_by_agent_id)+ : details.wakeup.created_by+ ? getActorName("member", details.wakeup.created_by)+ : null;+ return creator ? t(($) => $.activity.wakeup_chip_created_by, { name: creator }) : null;+}++export function WakeupActivityIcon({ entry }: { entry: TimelineEntry }) {+ const details = detailsOf(entry);+ const className = "h-4 w-4 shrink-0 text-muted-foreground";+ if (details.rule === "child_done") return <ListChecks className={className} aria-hidden="true" />;+ switch (entry.action) {+ case "wakeup_timed_out":+ return <Hourglass className={className} aria-hidden="true" />;+ case "wakeup_paused":+ return <TriangleAlert className="h-4 w-4 shrink-0 text-warning" aria-hidden="true" />;+ case "wakeup_checkin":+ return <RefreshCw className={className} aria-hidden="true" />;+ }+ const Icon = conditionIcon(details.wakeup?.condition) ?? (details.wakeup?.kind && details.wakeup.kind !== "event" ? Clock3 : Bell);+ return <Icon className={className} aria-hidden="true" />;+}diff --git a/packages/views/issues/components/wakeup-condition-names.ts b/packages/views/issues/components/wakeup-condition-names.tsnew file mode 100644index 0000000000..76e3e29da0--- /dev/null+++ b/packages/views/issues/components/wakeup-condition-names.ts@@ -0,0 +1,28 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { useWorkspaceId } from "@multica/core/hooks";+import { labelListOptions } from "@multica/core/labels/queries";+import { propertyListOptions } from "@multica/core/properties/queries";+import { useActorName } from "@multica/core/workspace/hooks";+import { useStatusLabel } from "../utils/status-label";++/**+ * Names for the values a wakeup condition compares: status keys, labels,+ * properties and assignees. Reads the workspace catalogs issue pages already+ * load.+ */+export function useConditionNames() {+ const wsId = useWorkspaceId();+ // Built-in statuses read in the viewer's language; custom ones by name.+ const statusLabel = useStatusLabel(wsId);+ const { data: labels = [] } = useQuery({ ...labelListOptions(wsId), enabled: !!wsId });+ const { data: properties = [] } = useQuery({ ...propertyListOptions(wsId), enabled: !!wsId });+ const { getActorName } = useActorName();+ return {+ status: statusLabel,+ label: (id: string) => labels.find((l) => l.id === id)?.name,+ property: (id: string) => properties.find((p) => p.id === id),+ actor: (type: string, id: string) => getActorName(type, id),+ };+}diff --git a/packages/views/issues/components/wakeup-create.test.tsx b/packages/views/issues/components/wakeup-create.test.tsxnew file mode 100644index 0000000000..2f60b32005--- /dev/null+++ b/packages/views/issues/components/wakeup-create.test.tsx@@ -0,0 +1,187 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, screen, waitFor } from "@testing-library/react";+import { ApiError } from "@multica/core/api";+import { configureShortcutPlatform } from "@multica/core/shortcuts";+import { renderWithI18n } from "../../test/i18n";+import { WakeupCreate } from "./wakeup-create";++const create = vi.fn();+let assigneeAgent = "emacs";+vi.mock("./wakeup-condition-names", () => ({+ useConditionNames: () => ({ status: (key: string) => key, label: () => undefined, property: () => undefined, actor: (_type: string, id: string) => id }),+}));+vi.mock("@multica/core/issues", () => ({+ useCreateIssueWakeup: () => ({ mutateAsync: create, isPending: false }),+ childIssuesOptions: () => ({ queryKey: ["children"] }),+ issueDetailOptions: () => ({ queryKey: ["issue-detail"] }),+}));+vi.mock("@tanstack/react-query", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),+ useQuery: ({ queryKey }: { queryKey: unknown[] }) => ({+ data: JSON.stringify(queryKey).includes("members")+ ? [{ user_id: "user-j", name: "Jiayuan" }]+ : JSON.stringify(queryKey).includes("issue-detail")+ ? { id: "issue", assignee_type: "agent", assignee_id: assigneeAgent }+ : [+ { id: "emacs", name: "Emacs", archived_at: null, runtime_id: "rt" },+ { id: "grok", name: "Grok", archived_at: null, runtime_id: "rt" },+ ],+ }),+}));+vi.mock("@multica/core/agents", () => ({ isAgentRuntimeBound: () => true }));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => <span /> }));+vi.mock("../../common/use-viewing-timezone", () => ({ useViewingTimezone: () => "Asia/Shanghai" }));++async function renderForm(defaultAgentId = "emacs") {+ renderWithI18n(<WakeupCreate workspaceId="ws" issueId="issue" defaultAgentId={defaultAgentId} />, { locale: "zh-Hans" });+ fireEvent.click(screen.getByRole("button", { name: "新建唤醒" }));+ await screen.findByRole("form", { name: "新建唤醒" });+}++async function chooseCondition(label: string) {+ fireEvent.click(screen.getByRole("button", { name: /选择条件/ }));+ fireEvent.click(await screen.findByRole("menuitem", { name: new RegExp(label) }));+}++beforeEach(() => {+ assigneeAgent = "emacs";+ create.mockReset().mockResolvedValue(undefined);+ // The send shortcut is the primary modifier + Enter; pin the platform so+ // Cmd means primary on every CI runner.+ configureShortcutPlatform("macos");+});+afterEach(() => configureShortcutPlatform(null));++describe("WakeupCreateForm", () => {+ it("says a reply wait for the assignee joins the run a comment already starts", async () => {+ await renderForm();+ await chooseCondition("有人回复");+ expect(screen.getByText(/Emacs 是负责人,成员发评论时本来就会被触发/)).toBeVisible();+ });++ it("says nothing when the rule wakes someone other than the assignee", async () => {+ assigneeAgent = "grok";+ await renderForm();+ await chooseCondition("有人回复");+ expect(screen.queryByText(/是负责人,成员发评论时本来就会被触发/)).toBeNull();+ });++ it("asks for a condition before creating anything", async () => {+ await renderForm();+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));+ expect(screen.getByRole("alert")).toHaveTextContent("请选择条件");+ expect(create).not.toHaveBeenCalled();+ });++ it("creates a reply wait for the assignee with a deadline and timeout action", async () => {+ await renderForm();+ await chooseCondition("有人回复");+ expect(screen.getByRole("radiogroup", { name: "触发次数" })).toBeVisible();+ expect(screen.getByRole("button", { name: /最多等待: 7 天/ })).toBeVisible();+ expect(screen.getByRole("button", { name: /超时后: 唤醒 Emacs 处理/ })).toBeVisible();+ fireEvent.change(screen.getByLabelText("唤醒后要做什么"), { target: { value: "按回复继续实现阶段 2" } });+ fireEvent.click(screen.getByRole("radio", { name: "重复唤醒" }));+ // A repeating wait gets a cap on how many runs it may start.+ expect(screen.getByRole("button", { name: /最多触发: 20 次/ })).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));+ await waitFor(() =>+ expect(create).toHaveBeenCalledWith({+ agent_id: "emacs",+ instruction: "按回复继续实现阶段 2",+ kind: "event",+ mode: "continuous",+ max_fires: 20,+ event_types: ["comment.created"],+ expires_in_seconds: 604800,+ on_timeout: "wake",+ }),+ );+ await waitFor(() => expect(screen.queryByRole("form", { name: "新建唤醒" })).toBeNull());+ });++ it("requires an agent when the issue has no agent assignee", async () => {+ await renderForm("");+ await chooseCondition("在某个时间");+ fireEvent.change(screen.getByLabelText("唤醒后要做什么"), { target: { value: "看一下 CI" } });+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));+ expect(screen.getByRole("alert")).toHaveTextContent("请选择要唤醒的智能体");+ });++ it("gives a recurring check an end date and no timeout choice", async () => {+ await renderForm();+ await chooseCondition("定期检查");+ expect(screen.getByLabelText("截止")).toBeVisible();+ expect(screen.queryByRole("radiogroup")).toBeNull();+ fireEvent.change(screen.getByLabelText("唤醒后要做什么"), { target: { value: "巡检迁移任务" } });+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));+ await waitFor(() =>+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ kind: "cron", cron_expression: "0 9 * * *", timezone: "Asia/Shanghai", mode: "continuous" })),+ );+ });++ it("keeps the draft and explains a capacity refusal", async () => {+ create.mockRejectedValue(new ApiError("full", 400, "Bad Request", { code: "wakeup_capacity_exceeded" }));+ await renderForm();+ await chooseCondition("在某个时间");+ fireEvent.change(screen.getByLabelText("唤醒后要做什么"), { target: { value: "看一下 CI" } });+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));+ expect(await screen.findByRole("alert")).toHaveTextContent("已达上限");+ expect(screen.getByLabelText("唤醒后要做什么")).toHaveValue("看一下 CI");+ expect(screen.getByRole("form", { name: "新建唤醒" })).toBeVisible();+ });++ it("submits with Cmd+Enter", async () => {+ await renderForm();+ await chooseCondition("在某个时间");+ const input = screen.getByLabelText("唤醒后要做什么");+ fireEvent.change(input, { target: { value: "看一下 CI" } });+ fireEvent.keyDown(input, { key: "Enter", metaKey: true });+ await waitFor(() => expect(create).toHaveBeenCalledWith(expect.objectContaining({ kind: "at", mode: "once" })));+ });+});++describe("platform conditions in the form", () => {+ it("groups conditions by what they wait for", async () => {+ await renderForm();+ fireEvent.click(screen.getByRole("button", { name: /选择条件/ }));+ for (const label of ["字段变为某个值", "子任务完成", "关联 PR 的 CI 结束", "其他任务的状态变化"]) {+ expect(await screen.findByRole("menuitem", { name: new RegExp(label) })).toBeVisible();+ }+ for (const group of ["协作", "运行与子任务", "关联"]) expect(screen.getByText(group)).toBeVisible();+ });++ it("creates a sub-issue wait that the platform checks", async () => {+ await renderForm();+ await chooseCondition("子任务完成");+ expect(screen.getByRole("button", { name: /子任务完成: 全部子任务/ })).toBeVisible();+ fireEvent.change(screen.getByLabelText("唤醒后要做什么"), { target: { value: "汇总子任务结果" } });+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));+ await waitFor(() =>+ expect(create).toHaveBeenCalledWith(+ expect.objectContaining({ kind: "event", mode: "once", condition: { type: "children_done" }, expires_in_seconds: 604800 }),+ ),+ );+ expect(create.mock.calls[0]![0]).not.toHaveProperty("event_types");+ });++ it("waits for a linked PR's CI by default and can wait for the merge instead", async () => {+ await renderForm();+ await chooseCondition("关联 PR 的 CI 结束");+ fireEvent.click(screen.getByRole("button", { name: /关联 PR 的 CI 结束: CI 结束/ }));+ fireEvent.click(await screen.findByRole("menuitemradio", { name: "合并" }));+ fireEvent.change(screen.getByLabelText("唤醒后要做什么"), { target: { value: "发布" } });+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));+ await waitFor(() =>+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ condition: { type: "pull_request", event: "merged" } })),+ );+ });++ it("asks for the value a field has to reach", async () => {+ await renderForm();+ await chooseCondition("字段变为某个值");+ fireEvent.change(screen.getByLabelText("唤醒后要做什么"), { target: { value: "继续" } });+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));+ expect(screen.getByRole("alert")).toHaveTextContent("请选择一个值");+ expect(create).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/issues/components/wakeup-create.tsx b/packages/views/issues/components/wakeup-create.tsxnew file mode 100644index 0000000000..11ffe758c7--- /dev/null+++ b/packages/views/issues/components/wakeup-create.tsx@@ -0,0 +1,1035 @@+"use client";++import { useId, useMemo, useRef, useState, type ReactNode } from "react";+import { useQuery } from "@tanstack/react-query";+import {+ Bot,+ ChevronDown,+ CircleDashed,+ CircleDot,+ Clock3,+ GitPullRequest,+ Info,+ Link2,+ ListChecks,+ MessageSquare,+ Plus,+ RefreshCw,+ Zap,+ type LucideIcon,+} from "lucide-react";+import { childIssuesOptions, issueDetailOptions, useCreateIssueWakeup } from "@multica/core/issues";+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";+import { labelListOptions } from "@multica/core/labels/queries";+import { propertyListOptions } from "@multica/core/properties/queries";+import { isAgentRuntimeBound } from "@multica/core/agents";+import { ApiError } from "@multica/core/api";+import { agentListOptions, memberListOptions, squadListOptions } from "@multica/core/workspace/queries";+import { shortcutMatchesEvent, useShortcut } from "@multica/core/shortcuts";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import { Textarea } from "@multica/ui/components/ui/textarea";+import {+ Popover,+ PopoverContent,+ PopoverTitle,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import { DialogTitle } from "@multica/ui/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { cn } from "@multica/ui/lib/utils";+import { ActorAvatar } from "../../common/actor-avatar";+import { ShortcutKeycaps } from "../../common/shortcut-keycaps";+import { useViewingTimezone } from "../../common/use-viewing-timezone";+import { useT } from "../../i18n";+import { matchesPinyin } from "../../editor/extensions/pinyin-match";+import { PickerEmpty, PickerItem, PickerSection, PropertyPicker } from "./pickers/property-picker";+import { IssuePickerModal } from "../../modals/issue-picker-modal";+import { useStatusLabel } from "../utils/status-label";+import { useWakeupText } from "./wakeup-presentation";+import {+ WAKEUP_EVENT_TYPES,+ WAKEUP_MAX_FIRES,+ WAKEUP_WAIT_DAYS,+ buildWakeupInput,+ emptyWakeupDraft,+ isEventCondition,+ wakesAssigneeOnComments,+ type WakeupAtPreset,+ type WakeupCondition,+ type WakeupDraft,+ type WakeupDraftError,+ type WakeupField,+ type WakeupRecurrence,+} from "./wakeup-draft";++const pillClass =+ "inline-flex h-7 max-w-full min-w-0 items-center gap-1.5 rounded-md border border-surface-border bg-surface px-2 text-label outline-none hover:bg-accent focus-visible:ring-3 focus-visible:ring-ring/50 data-popup-open:bg-accent [&_svg]:shrink-0";++/**+ * Lets a member add a wakeup from the issue sidebar. It creates the same rule+ * an agent creates with `multica issue wakeup create`.+ */+export function WakeupCreate({+ workspaceId,+ issueId,+ defaultAgentId,+}: {+ workspaceId: string;+ issueId: string;+ defaultAgentId?: string;+}) {+ const { t } = useT("issues");+ const [open, setOpen] = useState(false);+ const busy = useRef(false);+ return (+ <Popover+ open={open}+ onOpenChange={(next) => {+ if (!busy.current) setOpen(next);+ }}+ >+ <PopoverTrigger+ render={+ <Button+ variant="ghost"+ size="icon-xs"+ className="text-muted-foreground"+ aria-label={t(($) => $.wakeups.create.open)}+ />+ }+ >+ <Plus aria-hidden="true" />+ </PopoverTrigger>+ <PopoverContent+ side="left"+ align="start"+ sideOffset={12}+ className="w-[420px] max-w-[calc(100vw-2rem)] gap-0 p-4"+ >+ {open && (+ <WakeupCreateForm+ workspaceId={workspaceId}+ issueId={issueId}+ defaultAgentId={defaultAgentId ?? ""}+ onBusy={(value) => (busy.current = value)}+ onClose={() => setOpen(false)}+ />+ )}+ </PopoverContent>+ </Popover>+ );+}++export function WakeupCreateForm({+ workspaceId,+ issueId,+ defaultAgentId,+ onBusy,+ onClose,+ inDialog = false,+}: {+ workspaceId: string;+ issueId: string;+ defaultAgentId: string;+ onBusy?: (busy: boolean) => void;+ onClose: () => void;+ /** Rendered in a dialog (the workspace list) rather than the sidebar popover. */+ inDialog?: boolean;+}) {+ const Title = inDialog ? DialogTitle : PopoverTitle;+ const { t } = useT("issues");+ const text = useWakeupText();+ const timezone = useViewingTimezone();+ const id = useId();+ const [draft, setDraft] = useState(() => emptyWakeupDraft(defaultAgentId, timezone));+ const [error, setError] = useState("");+ const create = useCreateIssueWakeup(workspaceId, issueId);+ const sendShortcut = useShortcut("send");+ const { data: agents = [] } = useQuery(agentListOptions(workspaceId));+ const { data: properties = [] } = useQuery(propertyListOptions(workspaceId));+ const { data: issue } = useQuery(issueDetailOptions(workspaceId, issueId));+ const update = (patch: Partial<WakeupDraft>) => {+ setDraft((prev) => ({ ...prev, ...patch }));+ setError("");+ };+ const agentName = agents.find((a) => a.id === draft.agentId)?.name;+ const draftErrors: Record<WakeupDraftError, string> = {+ missing_condition: t(($) => $.wakeups.create.missing_condition),+ missing_value: t(($) => $.wakeups.create.missing_value),+ missing_issue: t(($) => $.wakeups.create.missing_issue),+ missing_agent: t(($) => $.wakeups.create.missing_agent),+ missing_events: t(($) => $.wakeups.create.missing_events),+ instruction_invalid: t(($) => $.wakeups.instruction_invalid),+ future_time: t(($) => $.wakeups.future_time),+ until_future: t(($) => $.wakeups.create.until_future),+ };++ const submit = async () => {+ if (create.isPending) return;+ const propertyType =+ draft.field === "property" ? properties.find((p) => p.id === draft.fieldTarget)?.type : undefined;+ const result = buildWakeupInput(draft, new Date(), propertyType);+ if ("error" in result) {+ setError(draftErrors[result.error]);+ return;+ }+ onBusy?.(true);+ try {+ await create.mutateAsync(result.input);+ onClose();+ } catch (err) {+ const code =+ err instanceof ApiError && err.body && typeof err.body === "object" && "code" in err.body+ ? err.body.code+ : undefined;+ setError(+ code === "wakeup_capacity_exceeded"+ ? t(($) => $.wakeups.create.capacity_error)+ : text.error(err, t(($) => $.wakeups.create.error)),+ );+ } finally {+ onBusy?.(false);+ }+ };++ return (+ <form+ aria-labelledby={`${id}-title`}+ onSubmit={(event) => {+ event.preventDefault();+ void submit();+ }}+ onKeyDown={(event) => {+ if (sendShortcut && shortcutMatchesEvent(sendShortcut, event.nativeEvent) && !event.nativeEvent.isComposing) {+ event.preventDefault();+ void submit();+ }+ }}+ >+ <Title id={`${id}-title`} className="text-title-sm font-semibold">+ {t(($) => $.wakeups.create.title)}+ </Title>+ <div className="mt-3.5 grid grid-cols-[2.5rem_minmax(0,1fr)] items-center gap-y-2.5">+ <span className="text-label text-muted-foreground">{t(($) => $.wakeups.create.when)}</span>+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">+ <ConditionMenu value={draft.condition} onChange={(condition) => update({ condition })} />+ <ConditionParams draft={draft} workspaceId={workspaceId} issueId={issueId} update={update} onBusy={onBusy} />+ </div>+ <span className="text-label text-muted-foreground">{t(($) => $.wakeups.create.wake)}</span>+ <div className="flex min-w-0 items-center gap-1.5">+ <AgentChoice+ workspaceId={workspaceId}+ value={draft.agentId}+ onChange={(agentId) => update({ agentId })}+ placeholder={t(($) => $.wakeups.create.choose_agent)}+ />+ </div>+ </div>+ {wakesAssigneeOnComments(draft, issue?.assignee_type === "agent" ? (issue.assignee_id ?? null) : null) && (+ <p className="mt-2.5 rounded-md bg-muted/60 px-2.5 py-2 text-caption leading-5 text-muted-foreground">+ {t(($) => $.wakeups.create.assignee_comment_hint, { name: agentName ?? "" })}+ </p>+ )}+ {draft.condition === "at" && draft.atPreset === "custom" && (+ <Input+ type="datetime-local"+ aria-label={t(($) => $.wakeups.local_time, { timezone: Intl.DateTimeFormat().resolvedOptions().timeZone })}+ className="mt-2.5"+ value={draft.atCustom}+ onChange={(event) => update({ atCustom: event.target.value })}+ />+ )}+ <label htmlFor={`${id}-instruction`} className="mt-4 mb-1.5 block text-caption font-medium">+ {t(($) => $.wakeups.instruction_title)}+ </label>+ <Textarea+ id={`${id}-instruction`}+ rows={3}+ value={draft.instruction}+ placeholder={t(($) => $.wakeups.create.instruction_placeholder)}+ className="max-h-[30dvh] resize-y text-base md:text-label"+ onChange={(event) => update({ instruction: event.target.value })}+ />+ {draft.condition === "recurring" && (+ <div className="mt-4 grid grid-cols-[4.5rem_minmax(0,1fr)] items-center gap-y-2.5">+ <label htmlFor={`${id}-until`} className="text-caption text-muted-foreground">+ {t(($) => $.wakeups.create.until)}+ </label>+ <Input+ id={`${id}-until`}+ type="date"+ className="h-7 w-44"+ value={draft.until}+ onChange={(event) => update({ until: event.target.value })}+ />+ </div>+ )}+ {isEventCondition(draft.condition) && (+ <div className="mt-4 grid grid-cols-[4.5rem_minmax(0,1fr)] items-center gap-y-2.5">+ <span className="text-caption text-muted-foreground">{t(($) => $.wakeups.create.trigger_count)}</span>+ <Segmented+ label={t(($) => $.wakeups.create.trigger_count)}+ value={draft.mode}+ options={[+ { value: "once", label: t(($) => $.wakeups.once) },+ { value: "continuous", label: t(($) => $.wakeups.continuous) },+ ]}+ onChange={(mode) => update({ mode })}+ />+ {draft.mode === "continuous" && (+ <>+ <span className="text-caption text-muted-foreground">{t(($) => $.wakeups.create.max_fires)}</span>+ <div className="flex min-w-0">+ <PillMenu+ label={t(($) => $.wakeups.create.max_fires)}+ value={String(draft.maxFires)}+ options={WAKEUP_MAX_FIRES.map((count) => ({+ value: String(count),+ label: t(($) => $.wakeups.create.max_fires_times, { count }),+ }))}+ onChange={(value) => update({ maxFires: Number(value) })}+ />+ </div>+ </>+ )}+ <span className="text-caption text-muted-foreground">{t(($) => $.wakeups.create.max_wait)}</span>+ <div className="flex min-w-0">+ <PillMenu+ label={t(($) => $.wakeups.create.max_wait)}+ value={String(draft.waitDays)}+ options={WAKEUP_WAIT_DAYS.map((days) => ({+ value: String(days),+ label: t(($) => $.wakeups.create.wait_days, { count: days }),+ }))}+ onChange={(value) => update({ waitDays: Number(value) })}+ />+ </div>+ <span className="text-caption text-muted-foreground">{t(($) => $.wakeups.create.on_timeout)}</span>+ <div className="flex min-w-0">+ <PillMenu+ label={t(($) => $.wakeups.create.on_timeout)}+ value={draft.onTimeout}+ options={[+ {+ value: "wake",+ label: t(($) => $.wakeups.create.timeout_wake, {+ agent: agentName ?? t(($) => $.wakeups.create.the_agent),+ }),+ },+ { value: "end", label: t(($) => $.wakeups.create.timeout_end) },+ ]}+ onChange={(value) => update({ onTimeout: value as WakeupDraft["onTimeout"] })}+ />+ </div>+ </div>+ )}+ {error && (+ <p role="alert" className="mt-3 text-caption text-destructive">+ {error}+ </p>+ )}+ <div className="mt-4 flex items-center gap-2 border-t border-border pt-3">+ <span className="flex min-w-0 flex-1 items-center gap-1 text-caption text-muted-foreground">+ <Info className="size-3 shrink-0" aria-hidden="true" />+ {t(($) => $.wakeups.create.on_behalf)}+ </span>+ <Button type="button" variant="ghost" size="sm" disabled={create.isPending} onClick={onClose}>+ {t(($) => $.wakeups.create.cancel)}+ </Button>+ <Button type="submit" size="sm" disabled={create.isPending} aria-busy={create.isPending}>+ {t(($) => (create.isPending ? $.wakeups.create.submitting : $.wakeups.create.submit))}+ {sendShortcut && !create.isPending ? (+ <ShortcutKeycaps+ shortcut={sendShortcut}+ decorative+ className="ml-1 max-sm:hidden"+ keyClassName="border-background/30 bg-background/15 text-primary-foreground shadow-none"+ />+ ) : null}+ </Button>+ </div>+ </form>+ );+}++function ConditionMenu({+ value,+ onChange,+}: {+ value: WakeupCondition | null;+ onChange: (value: WakeupCondition) => void;+}) {+ const { t } = useT("issues");+ const items: Record<WakeupCondition, { icon: LucideIcon; label: string; hint: string }> = {+ at: { icon: Clock3, label: t(($) => $.wakeups.create.cond_at), hint: t(($) => $.wakeups.create.cond_at_hint) },+ recurring: { icon: RefreshCw, label: t(($) => $.wakeups.create.cond_recurring), hint: t(($) => $.wakeups.create.cond_recurring_hint) },+ reply: { icon: MessageSquare, label: t(($) => $.wakeups.create.cond_reply), hint: t(($) => $.wakeups.create.cond_reply_hint) },+ field: { icon: CircleDot, label: t(($) => $.wakeups.create.cond_field), hint: t(($) => $.wakeups.create.cond_field_hint) },+ run_end: { icon: Bot, label: t(($) => $.wakeups.create.cond_run_end), hint: t(($) => $.wakeups.create.cond_run_end_hint) },+ children: { icon: ListChecks, label: t(($) => $.wakeups.create.cond_children), hint: t(($) => $.wakeups.create.cond_children_hint) },+ pull_request: { icon: GitPullRequest, label: t(($) => $.wakeups.create.cond_pr), hint: t(($) => $.wakeups.create.cond_pr_hint) },+ other_issue: { icon: Link2, label: t(($) => $.wakeups.create.cond_issue), hint: t(($) => $.wakeups.create.cond_issue_hint) },+ custom: { icon: Zap, label: t(($) => $.wakeups.create.cond_custom), hint: t(($) => $.wakeups.create.cond_custom_hint, { count: WAKEUP_EVENT_TYPES.length }) },+ };+ const groups: [string, WakeupCondition[]][] = [+ [t(($) => $.wakeups.create.group_time), ["at", "recurring"]],+ [t(($) => $.wakeups.create.group_collaboration), ["reply", "field"]],+ [t(($) => $.wakeups.create.group_runs), ["run_end", "children"]],+ [t(($) => $.wakeups.create.group_linked), ["pull_request", "other_issue"]],+ ];+ const selected = value ? items[value] : null;+ const SelectedIcon = selected?.icon ?? CircleDashed;+ const option = (key: WakeupCondition) => {+ const Icon = items[key].icon;+ return (+ <DropdownMenuItem key={key} onClick={() => onChange(key)} className="gap-2 py-1.5">+ <Icon className="size-3.5 text-muted-foreground" aria-hidden="true" />+ <span>{items[key].label}</span>+ <span className="ml-auto pl-4 text-caption text-muted-foreground">{items[key].hint}</span>+ </DropdownMenuItem>+ );+ };+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={<button type="button" className={cn(pillClass, !value && "border-ring")} />}+ >+ <SelectedIcon className="size-3.5 text-muted-foreground" aria-hidden="true" />+ <span className={cn("truncate", !selected && "text-muted-foreground")}>+ {selected?.label ?? t(($) => $.wakeups.create.choose_condition)}+ </span>+ <ChevronDown className="size-3 text-muted-foreground" aria-hidden="true" />+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-[22rem]">+ {groups.map(([label, keys]) => (+ <DropdownMenuGroup key={label}>+ <DropdownMenuLabel>{label}</DropdownMenuLabel>+ {keys.map(option)}+ </DropdownMenuGroup>+ ))}+ <DropdownMenuSeparator />+ {option("custom")}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function ConditionParams({+ draft,+ workspaceId,+ issueId,+ update,+ onBusy,+}: {+ draft: WakeupDraft;+ workspaceId: string;+ issueId: string;+ update: (patch: Partial<WakeupDraft>) => void;+ onBusy?: (busy: boolean) => void;+}) {+ const { t } = useT("issues");+ const text = useWakeupText();+ switch (draft.condition) {+ case "field":+ return <FieldParams draft={draft} workspaceId={workspaceId} update={update} />;+ case "children":+ return <StageChoice workspaceId={workspaceId} issueId={issueId} value={draft.stage} onChange={(stage) => update({ stage })} />;+ case "pull_request":+ return (+ <PillMenu+ label={t(($) => $.wakeups.create.cond_pr)}+ value={draft.prEvent}+ options={[+ { value: "checks_finished", label: t(($) => $.wakeups.create.pr_checks) },+ { value: "merged", label: t(($) => $.wakeups.create.pr_merged) },+ ]}+ onChange={(prEvent) => update({ prEvent: prEvent as WakeupDraft["prEvent"] })}+ />+ );+ case "other_issue":+ return (+ <>+ <OtherIssueChoice issueId={issueId} value={draft.otherIssue} onChange={(otherIssue) => update({ otherIssue })} onBusy={onBusy} />+ <PillMenu+ label={t(($) => $.wakeups.create.cond_issue)}+ value={draft.otherState}+ options={[+ { value: "done", label: t(($) => $.wakeups.create.other_done) },+ { value: "ended", label: t(($) => $.wakeups.create.other_ended) },+ { value: "in_review", label: t(($) => $.wakeups.create.other_in_review) },+ ]}+ onChange={(otherState) => update({ otherState: otherState as WakeupDraft["otherState"] })}+ />+ </>+ );+ case "at":+ return (+ <PillMenu+ label={t(($) => $.wakeups.create.cond_at)}+ value={draft.atPreset}+ options={[+ { value: "10m", label: t(($) => $.wakeups.create.at_10m) },+ { value: "1h", label: t(($) => $.wakeups.create.at_1h) },+ { value: "tomorrow", label: t(($) => $.wakeups.create.at_tomorrow) },+ { value: "custom", label: t(($) => $.wakeups.create.at_custom) },+ ]}+ onChange={(atPreset) => update({ atPreset: atPreset as WakeupAtPreset })}+ />+ );+ case "recurring":+ return (+ <PillMenu+ label={t(($) => $.wakeups.create.cond_recurring)}+ value={draft.recurrence}+ options={[+ { value: "hourly", label: t(($) => $.wakeups.create.hourly) },+ { value: "daily", label: t(($) => $.wakeups.create.daily) },+ { value: "weekdays", label: t(($) => $.wakeups.create.weekdays) },+ ]}+ onChange={(recurrence) => update({ recurrence: recurrence as WakeupRecurrence })}+ />+ );+ case "reply":+ return <ActorChoice workspaceId={workspaceId} value={draft.replyActor} onChange={(replyActor) => update({ replyActor })} />;+ case "run_end":+ return (+ <AgentChoice+ workspaceId={workspaceId}+ value={draft.runAgentId}+ onChange={(runAgentId) => update({ runAgentId })}+ placeholder={t(($) => $.wakeups.create.any_agent)}+ allowAny+ />+ );+ case "custom":+ return (+ <DropdownMenu>+ <DropdownMenuTrigger render={<button type="button" className={pillClass} />}>+ <span className={cn(draft.events.length === 0 && "text-muted-foreground")}>+ {t(($) => $.wakeups.create.events_selected, { count: draft.events.length })}+ </span>+ <ChevronDown className="size-3 text-muted-foreground" aria-hidden="true" />+ </DropdownMenuTrigger>+ <DropdownMenuContent className="max-h-80 w-80">+ {WAKEUP_EVENT_TYPES.map((event) => (+ <DropdownMenuCheckboxItem+ key={event}+ checked={draft.events.includes(event)}+ closeOnClick={false}+ onCheckedChange={(checked) =>+ update({+ events: checked+ ? WAKEUP_EVENT_TYPES.filter((e) => e === event || draft.events.includes(e))+ : draft.events.filter((e) => e !== event),+ })+ }+ >+ {text.eventName(event)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+ default:+ return null;+ }+}++function PillMenu({+ label,+ value,+ options,+ onChange,+ placeholder,+}: {+ label: string;+ value: string;+ options: { value: string; label: string }[];+ onChange: (value: string) => void;+ /** Shown until a value is chosen. */+ placeholder?: string;+}) {+ const current = options.find((option) => option.value === value);+ return (+ <DropdownMenu>+ <DropdownMenuTrigger render={<button type="button" className={pillClass} aria-label={`${label}: ${current?.label ?? ""}`} />}>+ <span className={cn("truncate", !current && "text-muted-foreground")}>{current?.label ?? placeholder}</span>+ <ChevronDown className="size-3 text-muted-foreground" aria-hidden="true" />+ </DropdownMenuTrigger>+ <DropdownMenuContent className="max-h-80">+ <DropdownMenuRadioGroup value={value} onValueChange={(next) => onChange(String(next))}>+ {options.map((option) => (+ <DropdownMenuRadioItem key={option.value} value={option.value}>+ {option.label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function Segmented<T extends string>({+ label,+ value,+ options,+ onChange,+}: {+ label: string;+ value: T;+ options: { value: T; label: string }[];+ onChange: (value: T) => void;+}) {+ return (+ <div role="radiogroup" aria-label={label} className="inline-flex w-fit gap-0.5 rounded-lg bg-muted p-0.5">+ {options.map((option) => (+ <button+ key={option.value}+ type="button"+ role="radio"+ aria-checked={value === option.value}+ onClick={() => onChange(option.value)}+ className={cn(+ "h-6 rounded-md px-2.5 text-caption text-muted-foreground outline-none focus-visible:ring-3 focus-visible:ring-ring/50",+ value === option.value && "bg-surface font-medium text-foreground shadow-[var(--surface-shadow)]",+ )}+ >+ {option.label}+ </button>+ ))}+ </div>+ );+}++function useMatches() {+ const [filter, setFilter] = useState("");+ const query = filter.trim().toLowerCase();+ const matches = (name: string) => !query || name.toLowerCase().includes(query) || matchesPinyin(name, query);+ return { setFilter, matches };+}++function AgentChoice({+ workspaceId,+ value,+ onChange,+ placeholder,+ allowAny = false,+}: {+ workspaceId: string;+ value: string;+ onChange: (id: string) => void;+ placeholder: string;+ allowAny?: boolean;+}) {+ const [open, setOpen] = useState(false);+ const { setFilter, matches } = useMatches();+ const { data = [] } = useQuery(agentListOptions(workspaceId));+ const agents = useMemo(() => data.filter((a) => !a.archived_at), [data]);+ const selected = agents.find((a) => a.id === value);+ const pick = (id: string) => {+ onChange(id);+ setOpen(false);+ };+ return (+ <PropertyPicker+ open={open}+ onOpenChange={setOpen}+ width="w-56"+ align="start"+ searchable+ onSearchChange={setFilter}+ triggerRender={<button type="button" className={pillClass} />}+ trigger={+ <>+ {selected ? (+ <ActorAvatar actorType="agent" actorId={selected.id} size="sm" />+ ) : (+ <Bot className="size-3.5 text-muted-foreground" aria-hidden="true" />+ )}+ <span className={cn("truncate", !selected && "text-muted-foreground")}>{selected?.name ?? placeholder}</span>+ <ChevronDown className="size-3 text-muted-foreground" aria-hidden="true" />+ </>+ }+ >+ {allowAny && (+ <PickerItem selected={!value} onClick={() => pick("")}>+ <Bot className="size-3.5 text-muted-foreground" aria-hidden="true" />+ <span className="truncate">{placeholder}</span>+ </PickerItem>+ )}+ {agents.filter((a) => matches(a.name)).length === 0 && !allowAny ? (+ <PickerEmpty />+ ) : (+ agents+ .filter((a) => matches(a.name))+ .map((a) => (+ <PickerItem+ key={a.id}+ selected={a.id === value}+ disabled={!allowAny && !isAgentRuntimeBound(a)}+ onClick={() => pick(a.id)}+ >+ <ActorAvatar actorType="agent" actorId={a.id} size="sm" showStatusDot />+ <span className="truncate">{a.name}</span>+ </PickerItem>+ ))+ )}+ </PropertyPicker>+ );+}++function ActorChoice({+ workspaceId,+ value,+ onChange,+}: {+ workspaceId: string;+ value: WakeupDraft["replyActor"];+ onChange: (value: WakeupDraft["replyActor"]) => void;+}) {+ const { t } = useT("issues");+ const [open, setOpen] = useState(false);+ const { setFilter, matches } = useMatches();+ const { data: members = [] } = useQuery(memberListOptions(workspaceId));+ const { data: agentRows = [] } = useQuery(agentListOptions(workspaceId));+ const agents = agentRows.filter((a) => !a.archived_at);+ const name =+ value?.type === "member"+ ? members.find((m) => m.user_id === value.id)?.name+ : value?.type === "agent"+ ? agents.find((a) => a.id === value.id)?.name+ : undefined;+ const pick = (next: WakeupDraft["replyActor"]) => {+ onChange(next);+ setOpen(false);+ };+ const section = (label: string, rows: ReactNode[]) =>+ rows.length > 0 && <PickerSection label={label}>{rows}</PickerSection>;+ return (+ <PropertyPicker+ open={open}+ onOpenChange={setOpen}+ width="w-56"+ align="start"+ searchable+ onSearchChange={setFilter}+ triggerRender={<button type="button" className={pillClass} />}+ trigger={+ <>+ {value ? (+ <ActorAvatar actorType={value.type} actorId={value.id} size="sm" />+ ) : null}+ <span className="truncate">{name ?? t(($) => $.wakeups.create.anyone)}</span>+ <ChevronDown className="size-3 text-muted-foreground" aria-hidden="true" />+ </>+ }+ >+ <PickerItem selected={!value} onClick={() => pick(null)}>+ <span className="truncate">{t(($) => $.wakeups.create.anyone)}</span>+ </PickerItem>+ {section(+ t(($) => $.wakeups.create.members),+ members+ .filter((m) => matches(m.name))+ .map((m) => (+ <PickerItem+ key={m.user_id}+ selected={value?.type === "member" && value.id === m.user_id}+ onClick={() => pick({ type: "member", id: m.user_id })}+ >+ <ActorAvatar actorType="member" actorId={m.user_id} size="sm" />+ <span className="truncate">{m.name}</span>+ </PickerItem>+ )),+ )}+ {section(+ t(($) => $.wakeups.create.agents),+ agents+ .filter((a) => matches(a.name))+ .map((a) => (+ <PickerItem+ key={a.id}+ selected={value?.type === "agent" && value.id === a.id}+ onClick={() => pick({ type: "agent", id: a.id })}+ >+ <ActorAvatar actorType="agent" actorId={a.id} size="sm" />+ <span className="truncate">{a.name}</span>+ </PickerItem>+ )),+ )}+ </PropertyPicker>+ );+}++/** Field, then the value it has to reach. */+function FieldParams({+ draft,+ workspaceId,+ update,+}: {+ draft: WakeupDraft;+ workspaceId: string;+ update: (patch: Partial<WakeupDraft>) => void;+}) {+ const { t } = useT("issues");+ const statuses = useIssueStatuses(workspaceId);+ const statusLabel = useStatusLabel(workspaceId);+ const { data: labels = [] } = useQuery(labelListOptions(workspaceId));+ const { data: allProperties = [] } = useQuery(propertyListOptions(workspaceId));+ const properties = allProperties.filter((p) => !p.archived);+ const property = properties.find((p) => p.id === draft.fieldTarget);+ const choose = (field: WakeupField) => update({ field, fieldTarget: "", fieldValue: "", assignee: null });+ const fieldMenu = (+ <PillMenu+ label={t(($) => $.wakeups.create.field_kind)}+ value={draft.field}+ options={[+ { value: "status", label: t(($) => $.wakeups.create.field_status) },+ { value: "assignee", label: t(($) => $.wakeups.create.field_assignee) },+ { value: "label", label: t(($) => $.wakeups.create.field_label) },+ { value: "property", label: t(($) => $.wakeups.create.field_property) },+ ]}+ onChange={(field) => choose(field as WakeupField)}+ />+ );+ let value: ReactNode = null;+ if (draft.field === "status") {+ value = (+ <PillMenu+ label={t(($) => $.wakeups.create.choose_status)}+ placeholder={t(($) => $.wakeups.create.choose_status)}+ value={draft.fieldTarget}+ options={statuses.activeStatuses.map((s) => ({ value: s.key, label: statusLabel(s.key) }))}+ onChange={(fieldTarget) => update({ fieldTarget })}+ />+ );+ } else if (draft.field === "assignee") {+ value = <AssigneeChoice workspaceId={workspaceId} value={draft.assignee} onChange={(assignee) => update({ assignee })} />;+ } else if (draft.field === "label") {+ value = (+ <PillMenu+ label={t(($) => $.wakeups.create.choose_label)}+ placeholder={t(($) => $.wakeups.create.choose_label)}+ value={draft.fieldTarget}+ options={labels.map((l) => ({ value: l.id, label: l.name }))}+ onChange={(fieldTarget) => update({ fieldTarget })}+ />+ );+ } else {+ value = (+ <>+ <PillMenu+ label={t(($) => $.wakeups.create.choose_property)}+ placeholder={t(($) => $.wakeups.create.choose_property)}+ value={draft.fieldTarget}+ options={properties.map((p) => ({ value: p.id, label: p.name }))}+ onChange={(fieldTarget) => update({ fieldTarget, fieldValue: "" })}+ />+ {property &&+ (property.type === "select" || property.type === "multi_select" ? (+ <PillMenu+ label={property.name}+ placeholder={t(($) => $.wakeups.create.value_placeholder)}+ value={draft.fieldValue}+ options={(property.config.options ?? []).map((o) => ({ value: o.id, label: o.name }))}+ onChange={(fieldValue) => update({ fieldValue })}+ />+ ) : property.type === "checkbox" ? (+ <PillMenu+ label={property.name}+ placeholder={t(($) => $.wakeups.create.value_placeholder)}+ value={draft.fieldValue}+ options={[+ { value: "true", label: t(($) => $.wakeups.create.checked) },+ { value: "false", label: t(($) => $.wakeups.create.unchecked) },+ ]}+ onChange={(fieldValue) => update({ fieldValue })}+ />+ ) : (+ <Input+ aria-label={property.name}+ placeholder={t(($) => $.wakeups.create.value_placeholder)}+ type={property.type === "number" ? "number" : "text"}+ className="h-7 w-32 text-base md:text-label"+ value={draft.fieldValue}+ onChange={(event) => update({ fieldValue: event.target.value })}+ />+ ))}+ </>+ );+ }+ return (+ <>+ {fieldMenu}+ {value}+ </>+ );+}++/** Every sub-issue, or one of the stages this issue's sub-issues use. */+function StageChoice({+ workspaceId,+ issueId,+ value,+ onChange,+}: {+ workspaceId: string;+ issueId: string;+ value: number | null;+ onChange: (stage: number | null) => void;+}) {+ const { t } = useT("issues");+ const { data: children = [] } = useQuery(childIssuesOptions(workspaceId, issueId));+ const stages = [...new Set(children.map((c) => c.stage).filter((s): s is number => typeof s === "number"))].sort((a, b) => a - b);+ return (+ <PillMenu+ label={t(($) => $.wakeups.create.cond_children)}+ value={value === null ? "all" : String(value)}+ options={[+ { value: "all", label: t(($) => $.wakeups.create.children_all) },+ ...stages.map((stage) => ({ value: String(stage), label: t(($) => $.wakeups.create.children_stage, { stage }) })),+ ]}+ onChange={(next) => onChange(next === "all" ? null : Number(next))}+ />+ );+}++function OtherIssueChoice({+ issueId,+ value,+ onChange,+ onBusy,+}: {+ issueId: string;+ value: WakeupDraft["otherIssue"];+ onChange: (value: WakeupDraft["otherIssue"]) => void;+ onBusy?: (busy: boolean) => void;+}) {+ const { t } = useT("issues");+ const [open, setOpen] = useState(false);+ // The picker is a dialog over this popover; keep the popover open while it is.+ const toggle = (next: boolean) => {+ onBusy?.(next);+ setOpen(next);+ };+ return (+ <>+ <button type="button" className={pillClass} onClick={() => toggle(true)}>+ <Link2 className="size-3.5 text-muted-foreground" aria-hidden="true" />+ <span className={cn("truncate", !value && "text-muted-foreground")}>+ {value?.identifier ?? t(($) => $.wakeups.create.choose_issue)}+ </span>+ </button>+ <IssuePickerModal+ open={open}+ onOpenChange={toggle}+ title={t(($) => $.wakeups.create.pick_issue_title)}+ description={t(($) => $.wakeups.create.pick_issue_description)}+ excludeIds={[issueId]}+ onSelect={(issue) => {+ onChange({ id: issue.id, identifier: issue.identifier });+ toggle(false);+ }}+ />+ </>+ );+}++function AssigneeChoice({+ workspaceId,+ value,+ onChange,+}: {+ workspaceId: string;+ value: WakeupDraft["assignee"];+ onChange: (value: WakeupDraft["assignee"]) => void;+}) {+ const { t } = useT("issues");+ const [open, setOpen] = useState(false);+ const { setFilter, matches } = useMatches();+ const { data: members = [] } = useQuery(memberListOptions(workspaceId));+ const { data: agentRows = [] } = useQuery(agentListOptions(workspaceId));+ const { data: squads = [] } = useQuery(squadListOptions(workspaceId));+ const agents = agentRows.filter((a) => !a.archived_at);+ const name =+ value?.type === "member"+ ? members.find((m) => m.user_id === value.id)?.name+ : value?.type === "agent"+ ? agents.find((a) => a.id === value.id)?.name+ : value?.type === "squad"+ ? squads.find((s) => s.id === value.id)?.name+ : undefined;+ const pick = (next: WakeupDraft["assignee"]) => {+ onChange(next);+ setOpen(false);+ };+ const section = (label: string, rows: ReactNode[]) =>+ rows.length > 0 && <PickerSection label={label}>{rows}</PickerSection>;+ return (+ <PropertyPicker+ open={open}+ onOpenChange={setOpen}+ width="w-56"+ align="start"+ searchable+ onSearchChange={setFilter}+ triggerRender={<button type="button" className={pillClass} />}+ trigger={+ <>+ {value && value.type !== "squad" ? <ActorAvatar actorType={value.type} actorId={value.id} size="sm" /> : null}+ <span className={cn("truncate", !name && "text-muted-foreground")}>{name ?? t(($) => $.wakeups.create.choose_assignee)}</span>+ <ChevronDown className="size-3 text-muted-foreground" aria-hidden="true" />+ </>+ }+ >+ {section(+ t(($) => $.wakeups.create.members),+ members+ .filter((m) => matches(m.name))+ .map((m) => (+ <PickerItem+ key={m.user_id}+ selected={value?.type === "member" && value.id === m.user_id}+ onClick={() => pick({ type: "member", id: m.user_id })}+ >+ <ActorAvatar actorType="member" actorId={m.user_id} size="sm" />+ <span className="truncate">{m.name}</span>+ </PickerItem>+ )),+ )}+ {section(+ t(($) => $.wakeups.create.agents),+ agents+ .filter((a) => matches(a.name))+ .map((a) => (+ <PickerItem key={a.id} selected={value?.type === "agent" && value.id === a.id} onClick={() => pick({ type: "agent", id: a.id })}>+ <ActorAvatar actorType="agent" actorId={a.id} size="sm" />+ <span className="truncate">{a.name}</span>+ </PickerItem>+ )),+ )}+ {section(+ t(($) => $.wakeups.create.squads),+ squads+ .filter((s) => matches(s.name))+ .map((s) => (+ <PickerItem key={s.id} selected={value?.type === "squad" && value.id === s.id} onClick={() => pick({ type: "squad", id: s.id })}>+ <span className="truncate">{s.name}</span>+ </PickerItem>+ )),+ )}+ </PropertyPicker>+ );+}diff --git a/packages/views/issues/components/wakeup-draft.test.ts b/packages/views/issues/components/wakeup-draft.test.tsnew file mode 100644index 0000000000..aeab540099--- /dev/null+++ b/packages/views/issues/components/wakeup-draft.test.ts@@ -0,0 +1,133 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { buildWakeupInput, emptyWakeupDraft, wakesAssigneeOnComments, type WakeupDraft } from "./wakeup-draft";++const now = new Date(2026, 8, 24, 15, 0, 0);+const draft = (patch: Partial<WakeupDraft>): WakeupDraft => ({+ ...emptyWakeupDraft("agent", "Asia/Shanghai", now),+ instruction: "Check the result",+ ...patch,+});++describe("buildWakeupInput", () => {+ it("requires a condition, an agent and bounded instructions", () => {+ expect(buildWakeupInput(draft({}), now)).toEqual({ error: "missing_condition" });+ expect(buildWakeupInput(draft({ condition: "at", agentId: "" }), now)).toEqual({ error: "missing_agent" });+ expect(buildWakeupInput(draft({ condition: "at", instruction: " " }), now)).toEqual({ error: "instruction_invalid" });+ expect(buildWakeupInput(draft({ condition: "at", instruction: "字".repeat(4001) }), now)).toEqual({ error: "instruction_invalid" });+ });++ it("schedules a single time from a preset or a future custom time", () => {+ expect(buildWakeupInput(draft({ condition: "at", atPreset: "10m" }), now)).toEqual({+ input: { agent_id: "agent", instruction: "Check the result", kind: "at", mode: "once", at: new Date(2026, 8, 24, 15, 10).toISOString() },+ });+ const tomorrow = buildWakeupInput(draft({ condition: "at", atPreset: "tomorrow" }), now);+ expect(tomorrow).toMatchObject({ input: { at: new Date(2026, 8, 25, 9, 0).toISOString() } });+ expect(buildWakeupInput(draft({ condition: "at", atPreset: "custom", atCustom: "2026-09-24T14:00" }), now)).toEqual({ error: "future_time" });+ expect(buildWakeupInput(draft({ condition: "at", atPreset: "custom", atCustom: "" }), now)).toEqual({ error: "future_time" });+ });++ it("gives recurring checks an end date and the viewer's timezone", () => {+ const daily = buildWakeupInput(draft({ condition: "recurring", recurrence: "daily", until: "2026-09-30" }), now);+ expect(daily).toEqual({+ input: {+ agent_id: "agent", instruction: "Check the result", kind: "cron", cron_expression: "0 9 * * *",+ timezone: "Asia/Shanghai", mode: "continuous", expires_at: new Date(2026, 8, 30, 23, 59, 59).toISOString(),+ },+ });+ expect(buildWakeupInput(draft({ condition: "recurring", recurrence: "hourly", until: "2026-09-30" }), now)).toMatchObject({+ input: { kind: "every", interval_seconds: 3600 },+ });+ expect(buildWakeupInput(draft({ condition: "recurring", recurrence: "weekdays", until: "2026-09-30" }), now)).toMatchObject({+ input: { cron_expression: "0 9 * * 1-5" },+ });+ expect(buildWakeupInput(draft({ condition: "recurring", until: "2026-09-23" }), now)).toEqual({ error: "until_future" });+ });++ it("waits for a reply with a deadline and a timeout action", () => {+ expect(buildWakeupInput(draft({ condition: "reply", replyActor: { type: "member", id: "user" }, waitDays: 3 }), now)).toEqual({+ input: {+ agent_id: "agent", instruction: "Check the result", kind: "event", mode: "once",+ expires_in_seconds: 259200, on_timeout: "wake", event_types: ["comment.created"],+ filter_actor_type: "member", filter_actor_id: "user",+ },+ });+ const anyone = buildWakeupInput(draft({ condition: "reply", mode: "continuous", onTimeout: "end" }), now);+ expect(anyone).toMatchObject({ input: { mode: "continuous", on_timeout: "end" } });+ expect("input" in anyone && anyone.input.filter_actor_type).toBeFalsy();+ });++ it("waits for runs to end, optionally from one agent", () => {+ expect(buildWakeupInput(draft({ condition: "run_end", runAgentId: "emacs" }), now)).toMatchObject({+ input: { event_types: ["task.completed", "task.failed", "task.cancelled"], filter_agent_id: "emacs" },+ });+ });++ it("requires at least one custom event", () => {+ expect(buildWakeupInput(draft({ condition: "custom" }), now)).toEqual({ error: "missing_events" });+ expect(buildWakeupInput(draft({ condition: "custom", events: ["issue.labels_changed"] }), now)).toMatchObject({+ input: { event_types: ["issue.labels_changed"] },+ });+ });+});++describe("platform conditions", () => {+ const input = (patch: Partial<WakeupDraft>, propertyType?: string) => buildWakeupInput(draft(patch), now, propertyType);++ it("turns each condition choice into the predicate the platform checks", () => {+ expect(input({ condition: "field", field: "status", fieldTarget: "in_review" })).toMatchObject({+ input: { kind: "event", mode: "once", condition: { type: "issue_field", field: "status", value: "in_review" }, expires_in_seconds: 604800 },+ });+ expect(input({ condition: "field", field: "assignee", assignee: { type: "squad", id: "sq" } })).toMatchObject({+ input: { condition: { type: "issue_field", field: "assignee", assignee_type: "squad", assignee_id: "sq" } },+ });+ expect(input({ condition: "field", field: "label", fieldTarget: "lbl" })).toMatchObject({+ input: { condition: { type: "issue_field", field: "label", label_id: "lbl" } },+ });+ expect(input({ condition: "children", stage: 2 })).toMatchObject({ input: { condition: { type: "children_done", stage: 2 } } });+ expect(input({ condition: "children", stage: null })).toMatchObject({ input: { condition: { type: "children_done" } } });+ expect(input({ condition: "pull_request", prEvent: "merged" })).toMatchObject({ input: { condition: { type: "pull_request", event: "merged" } } });+ expect(input({ condition: "other_issue", otherIssue: { id: "i2", identifier: "MUL-2" }, otherState: "ended" })).toMatchObject({+ input: { condition: { type: "other_issue", issue_id: "i2", state: "ended" } },+ });+ // Conditions never send raw events.+ const children = input({ condition: "children" });+ expect("input" in children && children.input.event_types).toBeUndefined();+ });++ it("types a property value the way the property stores it", () => {+ const property = (fieldValue: string, type: string) =>+ input({ condition: "field", field: "property", fieldTarget: "p", fieldValue }, type);+ expect(property("opt-1", "select")).toMatchObject({ input: { condition: { property_id: "p", value: "opt-1" } } });+ expect(property("false", "checkbox")).toMatchObject({ input: { condition: { value: false } } });+ expect(property("3", "number")).toMatchObject({ input: { condition: { value: 3 } } });+ expect(property("3a", "number")).toMatchObject({ input: { condition: { value: "3a" } } });+ });++ it("asks for the missing value or issue", () => {+ expect(input({ condition: "field", field: "status" })).toEqual({ error: "missing_value" });+ expect(input({ condition: "field", field: "assignee" })).toEqual({ error: "missing_value" });+ expect(input({ condition: "field", field: "property", fieldTarget: "p", fieldValue: " " })).toEqual({ error: "missing_value" });+ expect(input({ condition: "other_issue" })).toEqual({ error: "missing_issue" });+ });++ it("caps a repeating wait and leaves a single one uncapped", () => {+ expect(input({ condition: "reply", mode: "continuous", maxFires: 10 })).toMatchObject({ input: { max_fires: 10 } });+ const once = input({ condition: "reply" });+ expect("input" in once && once.input.max_fires).toBeUndefined();+ });+});++describe("wakesAssigneeOnComments", () => {+ it("flags rules that wake the agent assignee on members' comments", () => {+ const reply = draft({ condition: "reply", agentId: "agent" });+ expect(wakesAssigneeOnComments(reply, "agent")).toBe(true);+ expect(wakesAssigneeOnComments({ ...reply, replyActor: { type: "member", id: "u" } }, "agent")).toBe(true);+ // Agents' comments do not start the assignee's runs.+ expect(wakesAssigneeOnComments({ ...reply, replyActor: { type: "agent", id: "a" } }, "agent")).toBe(false);+ expect(wakesAssigneeOnComments(draft({ condition: "custom", agentId: "agent", events: ["comment.created"] }), "agent")).toBe(true);+ expect(wakesAssigneeOnComments(draft({ condition: "custom", agentId: "agent", events: ["issue.status_changed"] }), "agent")).toBe(false);+ expect(wakesAssigneeOnComments(reply, "someone-else")).toBe(false);+ expect(wakesAssigneeOnComments(reply, null)).toBe(false);+ });+});diff --git a/packages/views/issues/components/wakeup-draft.ts b/packages/views/issues/components/wakeup-draft.tsnew file mode 100644index 0000000000..7ae741378d--- /dev/null+++ b/packages/views/issues/components/wakeup-draft.ts@@ -0,0 +1,258 @@+import type { IssueWakeupInput, WakeupCondition as PlatformCondition } from "@multica/core/types";++/** The 25 issue-scoped events, in catalog order. */+export const WAKEUP_EVENT_TYPES = [+ "task.queued",+ "task.dispatched",+ "task.started",+ "task.deferred",+ "task.waiting_local_directory",+ "task.completed",+ "task.failed",+ "task.cancelled",+ "issue.updated",+ "issue.status_changed",+ "issue.assignee_changed",+ "issue.parent_changed",+ "issue.project_changed",+ "issue.labels_changed",+ "issue.properties_changed",+ "issue.metadata_changed",+ "comment.created",+ "comment.updated",+ "comment.deleted",+ "comment.resolved",+ "comment.unresolved",+ "reaction.added",+ "reaction.removed",+ "attachment.attached",+ "attachment.detached",+] as const;++const RUN_END_EVENTS = ["task.completed", "task.failed", "task.cancelled"];++export type WakeupCondition =+ | "at"+ | "recurring"+ | "reply"+ | "field"+ | "run_end"+ | "children"+ | "pull_request"+ | "other_issue"+ | "custom";+export type WakeupField = "status" | "assignee" | "label" | "property";+export type WakeupAtPreset = "10m" | "1h" | "tomorrow" | "custom";+export type WakeupRecurrence = "hourly" | "daily" | "weekdays";+export const WAKEUP_WAIT_DAYS = [1, 3, 7, 30] as const;+export const WAKEUP_MAX_FIRES = [5, 10, 20, 50] as const;++/**+ * Whether the draft would wake the issue's agent assignee on members'+ * comments, which already run it. The server folds such a firing into that run.+ */+export function wakesAssigneeOnComments(draft: Pick<WakeupDraft, "condition" | "replyActor" | "events" | "agentId">, assigneeAgentId: string | null) {+ if (!assigneeAgentId || draft.agentId !== assigneeAgentId) return false;+ if (draft.condition === "reply") return draft.replyActor?.type !== "agent";+ return draft.condition === "custom" && draft.events.includes("comment.created");+}++export interface WakeupDraft {+ condition: WakeupCondition | null;+ atPreset: WakeupAtPreset;+ /** A `datetime-local` value, read in the browser's timezone. */+ atCustom: string;+ recurrence: WakeupRecurrence;+ /** A `date` value; the rule ends at the end of that local day. */+ until: string;+ /** Null waits for anyone's reply. */+ replyActor: { type: "member" | "agent"; id: string } | null;+ /** Empty waits for any agent's run. */+ runAgentId: string;+ events: string[];+ field: WakeupField;+ /** Status key, label id or property id, depending on the field. */+ fieldTarget: string;+ /** Property value; select options store their option id. */+ fieldValue: string;+ assignee: { type: "member" | "agent" | "squad"; id: string } | null;+ /** Null waits for every sub-issue. */+ stage: number | null;+ prEvent: "checks_finished" | "merged";+ otherIssue: { id: string; identifier: string } | null;+ otherState: "done" | "ended" | "in_review";+ maxFires: number;+ agentId: string;+ instruction: string;+ mode: "once" | "continuous";+ waitDays: number;+ onTimeout: "wake" | "end";+ /** IANA zone that gives daily schedules their meaning. */+ timezone: string;+}++export type WakeupDraftError =+ | "missing_condition"+ | "missing_value"+ | "missing_issue"+ | "missing_agent"+ | "missing_events"+ | "instruction_invalid"+ | "future_time"+ | "until_future";++function pad(n: number) {+ return String(n).padStart(2, "0");+}++export function localDate(date: Date) {+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;+}++export function emptyWakeupDraft(agentId: string, timezone: string, now = new Date()): WakeupDraft {+ const until = new Date(now);+ until.setDate(until.getDate() + 7);+ return {+ condition: null,+ atPreset: "1h",+ atCustom: "",+ recurrence: "daily",+ until: localDate(until),+ replyActor: null,+ runAgentId: "",+ events: [],+ field: "status",+ fieldTarget: "",+ fieldValue: "",+ assignee: null,+ stage: null,+ prEvent: "checks_finished",+ otherIssue: null,+ otherState: "done",+ maxFires: 20,+ agentId,+ instruction: "",+ mode: "once",+ waitDays: 7,+ onTimeout: "wake",+ timezone,+ };+}++/** Conditions that wait for something to happen, with a deadline. */+export function isEventCondition(condition: WakeupCondition | null) {+ return !!condition && condition !== "at" && condition !== "recurring";+}++/** A property value typed as the property stores it. */+export function propertyConditionValue(type: string | undefined, raw: string): unknown {+ if (type === "checkbox") return raw === "true";+ if (type === "number") {+ const n = Number(raw);+ return raw.trim() !== "" && Number.isFinite(n) ? n : raw;+ }+ return raw;+}++/** The platform-evaluated predicate for a condition choice, if it is one. */+export function platformCondition(+ d: WakeupDraft,+ propertyType?: string,+): { condition: PlatformCondition } | { error: WakeupDraftError } | null {+ switch (d.condition) {+ case "field":+ if (d.field === "assignee") {+ return d.assignee+ ? { condition: { type: "issue_field", field: "assignee", assignee_type: d.assignee.type, assignee_id: d.assignee.id } }+ : { error: "missing_value" };+ }+ if (!d.fieldTarget) return { error: "missing_value" };+ if (d.field === "status") return { condition: { type: "issue_field", field: "status", value: d.fieldTarget } };+ if (d.field === "label") return { condition: { type: "issue_field", field: "label", label_id: d.fieldTarget } };+ if (!d.fieldValue.trim()) return { error: "missing_value" };+ return {+ condition: {+ type: "issue_field",+ field: "property",+ property_id: d.fieldTarget,+ value: propertyConditionValue(propertyType, d.fieldValue.trim()),+ },+ };+ case "children":+ return { condition: d.stage ? { type: "children_done", stage: d.stage } : { type: "children_done" } };+ case "pull_request":+ return { condition: { type: "pull_request", event: d.prEvent } };+ case "other_issue":+ return d.otherIssue+ ? { condition: { type: "other_issue", issue_id: d.otherIssue.id, state: d.otherState } }+ : { error: "missing_issue" };+ default:+ return null;+ }+}++/** Maps what a person chose onto the wakeup API; the server re-validates. */+export function buildWakeupInput(+ d: WakeupDraft,+ now = new Date(),+ propertyType?: string,+): { input: IssueWakeupInput } | { error: WakeupDraftError } {+ if (!d.condition) return { error: "missing_condition" };+ if (!d.agentId) return { error: "missing_agent" };+ const instruction = d.instruction.trim();+ if (!instruction || new TextEncoder().encode(instruction).length > 12000) {+ return { error: "instruction_invalid" };+ }+ const base = { agent_id: d.agentId, instruction };+ switch (d.condition) {+ case "at": {+ let at: Date;+ if (d.atPreset === "10m") at = new Date(now.getTime() + 10 * 60_000);+ else if (d.atPreset === "1h") at = new Date(now.getTime() + 60 * 60_000);+ else if (d.atPreset === "tomorrow") {+ at = new Date(now);+ at.setDate(at.getDate() + 1);+ at.setHours(9, 0, 0, 0);+ } else at = new Date(d.atCustom);+ if (!Number.isFinite(at.getTime()) || at.getTime() <= now.getTime()) return { error: "future_time" };+ return { input: { ...base, kind: "at", mode: "once", at: at.toISOString() } };+ }+ case "recurring": {+ const end = new Date(`${d.until}T23:59:59`);+ if (!Number.isFinite(end.getTime()) || end.getTime() <= now.getTime()) return { error: "until_future" };+ const schedule: Pick<IssueWakeupInput, "kind" | "interval_seconds" | "cron_expression" | "timezone"> =+ d.recurrence === "hourly"+ ? { kind: "every", interval_seconds: 3600 }+ : { kind: "cron", cron_expression: d.recurrence === "daily" ? "0 9 * * *" : "0 9 * * 1-5", timezone: d.timezone };+ return { input: { ...base, ...schedule, mode: "continuous", expires_at: end.toISOString() } };+ }+ default: {+ const input: IssueWakeupInput = {+ ...base,+ kind: "event",+ mode: d.mode,+ expires_in_seconds: d.waitDays * 86400,+ on_timeout: d.onTimeout,+ };+ if (d.mode === "continuous") input.max_fires = d.maxFires;+ const platform = platformCondition(d, propertyType);+ if (platform && "error" in platform) return { error: platform.error };+ if (platform) {+ input.condition = platform.condition;+ } else if (d.condition === "reply") {+ input.event_types = ["comment.created"];+ if (d.replyActor) {+ input.filter_actor_type = d.replyActor.type;+ input.filter_actor_id = d.replyActor.id;+ }+ } else if (d.condition === "run_end") {+ input.event_types = RUN_END_EVENTS;+ if (d.runAgentId) input.filter_agent_id = d.runAgentId;+ } else {+ if (d.events.length === 0) return { error: "missing_events" };+ input.event_types = d.events;+ }+ return { input };+ }+ }+}diff --git a/packages/views/issues/components/wakeup-instruction-editor.test.tsx b/packages/views/issues/components/wakeup-instruction-editor.test.tsxindex b9c95dbf3f..c7ec242553 100644--- a/packages/views/issues/components/wakeup-instruction-editor.test.tsx+++ b/packages/views/issues/components/wakeup-instruction-editor.test.tsx@@ -6,6 +6,9 @@ import type { IssueWakeup } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";import { WakeupInstructionEditor } from "./wakeup-instruction-editor";+vi.mock("./wakeup-condition-names", () => ({+ useConditionNames: () => ({ status: (key: string) => key, label: () => undefined, property: () => undefined, actor: (_type: string, id: string) => id }),+}));vi.mock("../../common/use-viewing-timezone", () => ({useViewingTimezone: () => "UTC",}));diff --git a/packages/views/issues/components/wakeup-presentation.ts b/packages/views/issues/components/wakeup-presentation.tsindex cce0f034f0..3a5b756d95 100644--- a/packages/views/issues/components/wakeup-presentation.ts+++ b/packages/views/issues/components/wakeup-presentation.ts@@ -3,12 +3,14 @@import type {AgentTask,IssueWakeup,+ WakeupCondition,WakeupPreview,} from "@multica/core/types";import { useLocale, useT } from "../../i18n";import { useViewingTimezone } from "../../common/use-viewing-timezone";import { parseCron } from "../../autopilots/components/schedule-editor/cron-mapping";import { useDescribeSchedule } from "../../autopilots/components/schedule-editor/describe";+import { useConditionNames } from "./wakeup-condition-names";export function wakeupState(w: Omit<IssueWakeup, "instruction">,@@ -17,6 +19,8 @@ export function wakeupState() {if (closed) return "issue_closed";if (w.enabled) return w.kind === "event" ? "waiting" : "scheduled";+ if (w.paused_reason) return "paused";+ if (w.timed_out_at) return "timed_out";if (w.disabled_at) return "disabled";if (w.last_task_id) return "triggered";if (w.kind === "at" && w.next_fire_at && Date.parse(w.next_fire_at) <= now)@@ -84,6 +88,7 @@ export function formatWakeupTime(export function useWakeupText() {const { t } = useT("issues");const locale = useLocale();+ const names = useConditionNames();// Fire times are absolute instants: show them in the viewer's timezone.// A wakeup's stored timezone only defines cron semantics.const viewTZ = useViewingTimezone();@@ -199,7 +204,57 @@ export function useWakeupText() {? t(($) => $.wakeups.by_actor, { condition: label, agent: actor }): label;};+ const propertyValue = (c: Extract<WakeupCondition, { field: "property" }>) => {+ const property = names.property(c.property_id);+ const raw = c.value;+ if (typeof raw === "boolean") return raw ? t(($) => $.wakeups.cond.checked) : t(($) => $.wakeups.cond.unchecked);+ const option = property?.config.options?.find((o) => o.id === raw);+ return option?.name ?? String(raw);+ };+ // Every sentence form of a condition: "when it holds" for rules and+ // "waiting for it" for cards and the header.+ const conditionParts = (c: WakeupCondition) => {+ switch (c.type) {+ case "issue_field":+ switch (c.field) {+ case "status":+ return { key: "status" as const, values: { status: names.status(c.value) } };+ case "assignee":+ return { key: "assignee" as const, values: { name: names.actor(c.assignee_type, c.assignee_id) } };+ case "label":+ return { key: "label" as const, values: { label: names.label(c.label_id) ?? t(($) => $.wakeups.cond.unknown_label) } };+ case "property":+ return {+ key: "property" as const,+ values: {+ property: names.property(c.property_id)?.name ?? t(($) => $.wakeups.cond.unknown_property),+ value: propertyValue(c),+ },+ };+ }+ break;+ case "children_done":+ return c.stage ? { key: "children_stage" as const, values: { stage: c.stage } } : { key: "children_all" as const, values: {} };+ case "pull_request":+ return { key: c.event === "merged" ? ("pr_merged" as const) : ("pr_checks" as const), values: {} };+ case "other_issue":+ return {+ key: c.state === "ended" ? ("other_ended" as const) : c.state === "in_review" ? ("other_in_review" as const) : ("other_done" as const),+ values: { issue: c.identifier || t(($) => $.wakeups.cond.another_issue) },+ };+ }+ return { key: "children_all" as const, values: {} };+ };+ const condition = (c: WakeupCondition) => {+ const { key, values } = conditionParts(c);+ return String(t(($) => $.wakeups.cond[key], values as Record<string, string | number>));+ };+ const conditionWait = (c: WakeupCondition) => {+ const { key, values } = conditionParts(c);+ return String(t(($) => $.wakeups.wait[key], values as Record<string, string | number>));+ };const trigger = (w: WakeupPreview) => {+ if (w.condition) return condition(w.condition);if (w.kind === "every" || w.kind === "cron") return schedule(w);if (w.kind === "at")return w.next_fire_at@@ -233,6 +288,57 @@ export function useWakeupText() {? t(($) => $.wakeups.next_at, { time: time(w.next_fire_at) }): t(($) => $.wakeups.rule_states[key]);};+ // Time left before an unanswered wait ends; null once it has passed.+ const remaining = (value: string, now = Date.now()) => {+ const ms = Date.parse(value) - now;+ if (!Number.isFinite(ms) || ms <= 0) return null;+ const minute = 60_000, hour = 60 * minute, day = 24 * hour;+ const days = Math.floor(ms / day);+ const hours = Math.floor((ms % day) / hour);+ if (days >= 3) return t(($) => $.wakeups.remaining_days, { days });+ if (days >= 1) return t(($) => $.wakeups.remaining_days_hours, { days, hours });+ if (hours >= 1) return t(($) => $.wakeups.remaining_hours, { hours });+ return t(($) => $.wakeups.remaining_minutes, { minutes: Math.max(1, Math.ceil(ms / minute)) });+ };+ const date = (value: string) =>+ new Intl.DateTimeFormat(locale, { timeZone: viewTZ, month: "short", day: "numeric" }).format(new Date(value));+ // A relative wait reads as time left; a recurring schedule's end date reads+ // as "until <date>".+ const ending = (w: Omit<IssueWakeup, "instruction">) => {+ if (!w.enabled || !w.expires_at) return null;+ return w.kind === "event" || w.expiry_seconds+ ? remaining(w.expires_at)+ : t(($) => $.wakeups.until_date, { date: date(w.expires_at) });+ };+ // The row's second line: who is woken, how often, and when the rule ends.+ const summary = (w: Omit<IssueWakeup, "instruction">, closed = false) =>+ [+ t(($) => $.wakeups.wake_agent, { agent: w.agent_name }),+ w.kind === "event" || w.kind === "at" ? frequency(w) : state(w, closed),+ !w.enabled && (w.kind === "event" || w.kind === "at") ? state(w, closed) : null,+ closed ? null : ending(w),+ ]+ .filter(Boolean)+ .join(" · ");+ const source = (w: Omit<IssueWakeup, "instruction">) => {+ const name = w.created_by_name ?? "";+ return w.created_by_agent+ ? t(($) => $.wakeups.source_agent, {+ agent: w.source_agent_name || t(($) => $.wakeups.source_agent_unknown),+ name,+ })+ : t(($) => $.wakeups.source_member, { name });+ };+ const expiry = (w: Omit<IssueWakeup, "instruction">) => {+ if (!w.expires_at) return null;+ const at = time(w.expires_at);+ if (w.timed_out_at) return t(($) => $.wakeups.expiry_timed_out, { time: time(w.timed_out_at) });+ const then =+ w.on_timeout === "wake"+ ? t(($) => $.wakeups.timeout_then_wake, { agent: w.agent_name })+ : t(($) => $.wakeups.timeout_then_end);+ return `${t(($) => $.wakeups.expiry_at, { time: at })} · ${then}`;+ };const error = (err: unknown, fallback: string) => {const status =err && typeof err === "object" && "status" in err@@ -244,5 +350,55 @@ export function useWakeupText() {? t(($) => $.wakeups.conflict_error): fallback;};- return { eventName, eventCondition, actorName, trigger, schedule, frequency, runState, state, error };+ // What an issue is waiting for, in a few words, for cards and the header.+ const waiting = (w: WakeupPreview) => {+ if (w.condition) return conditionWait(w.condition);+ if (w.kind !== "event") {+ return w.next_fire_at+ ? t(($) => $.wakeups.wait.time, { time: time(w.next_fire_at), agent: w.agent_name })+ : schedule(w);+ }+ const event = w.event_types[0] ?? "";+ if (w.event_types.length === 1 && event === "comment.created") {+ return w.filter_actor_type+ ? t(($) => $.wakeups.wait.reply_from, { name: actorName(w) })+ : t(($) => $.wakeups.wait.reply_any);+ }+ if (w.event_types.every((e) => ["task.completed", "task.failed", "task.cancelled"].includes(e))) {+ return w.filter_agent_name+ ? t(($) => $.wakeups.wait.run_end, { agent: w.filter_agent_name })+ : t(($) => $.wakeups.wait.run_end_any);+ }+ return t(($) => $.wakeups.waiting_event);+ };+ // The header reads "<agent> is waiting…"; time rules already name the agent.+ const headline = (w: WakeupPreview) =>+ w.kind !== "event" && w.next_fire_at+ ? waiting(w)+ : t(($) => $.wakeups.wait.header, { agent: w.agent_name, what: waiting(w) });+ const paused = (w: Pick<IssueWakeup, "paused_reason" | "max_fires" | "fire_count">) =>+ w.paused_reason === "max_fires"+ ? t(($) => $.wakeups.paused.max_fires, { count: w.max_fires ?? w.fire_count ?? 0 })+ : w.paused_reason === "loop"+ ? t(($) => $.wakeups.paused.loop)+ : w.paused_reason === "rate"+ ? t(($) => $.wakeups.paused.rate)+ : null;+ // The bare reason, for sentences that already say the rule was paused.+ const pausedReason = (w: Pick<IssueWakeup, "paused_reason" | "max_fires" | "fire_count">) =>+ w.paused_reason === "max_fires"+ ? t(($) => $.wakeups.paused_reason.max_fires, { count: w.max_fires ?? w.fire_count ?? 0 })+ : w.paused_reason === "loop"+ ? t(($) => $.wakeups.paused_reason.loop)+ : w.paused_reason === "rate"+ ? t(($) => $.wakeups.paused_reason.rate)+ : null;+ const fires = (w: Pick<IssueWakeup, "max_fires" | "fire_count" | "mode">) => {+ const count = w.fire_count ?? 0;+ if (w.mode !== "continuous" || (!count && !w.max_fires)) return null;+ return w.max_fires+ ? t(($) => $.wakeups.detail.fires_max, { count, max: w.max_fires })+ : t(($) => $.wakeups.detail.fires, { count });+ };+ return { eventName, eventCondition, actorName, trigger, schedule, frequency, runState, state, error, remaining, ending, summary, source, expiry, condition, conditionWait, waiting, headline, paused, pausedReason, fires };}diff --git a/packages/views/issues/components/wakeup-source-chip.tsx b/packages/views/issues/components/wakeup-source-chip.tsxnew file mode 100644index 0000000000..8aa9b9f79a--- /dev/null+++ b/packages/views/issues/components/wakeup-source-chip.tsx@@ -0,0 +1,66 @@+"use client";++import { useCallback, type ReactNode } from "react";+import { useQuery } from "@tanstack/react-query";+import { Bell } from "lucide-react";+import { issueTasksOptions, issueWakeupsOptions } from "@multica/core/issues";+import type { AgentTask, IssueWakeup } from "@multica/core/types";+import { useWorkspaceId } from "@multica/core/hooks";+import { useT } from "../../i18n";+import { useWakeupText } from "./wakeup-presentation";++/** The wakeup that started a run, when the issue still has it. */+export function useRunWakeup(issueId: string, wakeupId?: string): IssueWakeup | undefined {+ const wsId = useWorkspaceId();+ const select = useCallback((rules: IssueWakeup[]) => rules.find((w) => w.id === wakeupId), [wakeupId]);+ const { data } = useQuery({ ...issueWakeupsOptions(wsId, issueId), enabled: !!wsId && !!issueId && !!wakeupId, select });+ return data;+}++/**+ * "Triggered by wakeup · <condition>" on a comment an agent posted from a run+ * that a wakeup started. Renders nothing for other comments.+ */+export function WakeupSourceChip({ issueId, taskId }: { issueId: string; taskId: string }) {+ const select = useCallback((tasks: AgentTask[]) => tasks.find((task) => task.id === taskId)?.wakeup_id, [taskId]);+ const { data: wakeupId } = useQuery({ ...issueTasksOptions(issueId), select });+ return wakeupId ? <WakeupSourceChipLabel issueId={issueId} wakeupId={wakeupId} /> : null;+}++function WakeupSourceChipLabel({ issueId, wakeupId }: { issueId: string; wakeupId: string }) {+ const { t } = useT("issues");+ const text = useWakeupText();+ const rule = useRunWakeup(issueId, wakeupId);+ const label = rule+ ? t(($) => $.execution_log.trigger_wakeup, { condition: text.trigger(rule) })+ : t(($) => $.wakeups.triggered_by_wakeup);+ return (+ <span+ className="inline-flex min-w-0 max-w-64 items-center gap-1 rounded-sm bg-muted px-1.5 py-0.5 text-micro text-muted-foreground"+ title={label}+ >+ <Bell className="size-3 shrink-0" aria-hidden="true" />+ <span className="truncate">{label}</span>+ </span>+ );+}++/**+ * A wakeup run's trigger label with the rule's condition, e.g. "Wakeup · When+ * a linked PR's CI finishes". Mounted only for wakeup runs, so other run+ * lists never load the issue's rules.+ */+export function WakeupRunLabel({+ task,+ fallback,+ render,+}: {+ task: AgentTask;+ fallback: string;+ render: (label: string) => ReactNode;+}) {+ const { t } = useT("issues");+ const text = useWakeupText();+ const rule = useRunWakeup(task.issue_id, task.wakeup_id);+ return render(rule ? t(($) => $.execution_log.trigger_wakeup, { condition: text.trigger(rule) }) : fallback);+}diff --git a/packages/views/issues/components/wakeups-section.test.tsx b/packages/views/issues/components/wakeups-section.test.tsxindex 87a85fe60a..394d01b4fe 100644--- a/packages/views/issues/components/wakeups-section.test.tsx+++ b/packages/views/issues/components/wakeups-section.test.tsx@@ -1,26 +1,49 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, screen, waitFor } from "@testing-library/react";-import type { IssueWakeup } from "@multica/core/types";+import { fireEvent, screen, waitFor, within } from "@testing-library/react";+import type { IssueWakeup, SystemWakeup } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";import { WakeupsSection } from "./wakeups-section";const mutate = vi.fn();const enable = vi.fn();+const updateSystem = vi.fn();+const trigger = vi.fn();+const remove = vi.fn();+let runs: unknown[] = [];+let systemRules: SystemWakeup[] = [];let pending = false;let wakeup: IssueWakeup;let status = "queued";let viewTZ = "UTC";+vi.mock("./wakeup-condition-names", () => ({+ useConditionNames: () => ({ status: (key: string) => key, label: () => undefined, property: () => undefined, actor: (_type: string, id: string) => id }),+}));vi.mock("@multica/core/paths", () => ({useCurrentWorkspace: () => ({ id: "ws" }),}));vi.mock("@multica/core/issues", () => ({issueWakeupsOptions: () => ({ queryKey: ["wakeups"] }),issueTasksOptions: () => ({ queryKey: ["tasks"] }),+ issueSystemWakeupsOptions: () => ({ queryKey: ["system"] }),useDisableIssueWakeup: () => ({ mutate, isPending: false }),useEnableIssueWakeup: () => ({ mutateAsync: enable, isPending: pending }),+ useCreateIssueWakeup: () => ({ mutateAsync: vi.fn(), isPending: false }),+ useUpdateIssueSystemWakeup: () => ({ mutateAsync: updateSystem, isPending: false }),+ useTriggerIssueWakeup: () => ({ mutate: trigger, isPending: false }),+ useDeleteIssueWakeup: () => ({ mutate: remove, isPending: false }),+ issueWakeupRunsOptions: () => ({ queryKey: ["runs"] }),}));vi.mock("@tanstack/react-query", () => ({useQuery: ({ queryKey }: { queryKey: string[] }) => ({- data: queryKey[0] === "wakeups" ? [wakeup] : [{ id: "task", status }],+ data:+ queryKey[0] === "wakeups"+ ? [wakeup]+ : queryKey[0] === "system"+ ? systemRules+ : queryKey[0] === "tasks"+ ? [{ id: "task", status }]+ : queryKey[0] === "runs"+ ? runs+ : [],}),}));vi.mock("../../common/use-viewing-timezone", () => ({@@ -34,6 +57,11 @@ vi.mock("./wakeup-instruction-editor", () => ({}));beforeEach(() => {mutate.mockReset();+ trigger.mockReset();+ remove.mockReset();+ runs = [];+ updateSystem.mockReset().mockResolvedValue(undefined);+ systemRules = [];enable.mockReset().mockResolvedValue(undefined);pending = false;status = "queued";@@ -301,3 +329,150 @@ it("keeps a redacted actor restriction visible without exposing an ID", () => {renderWithI18n(<WakeupsSection issueId="issue" />);expect(screen.getByRole("button", { name: /triggered by Selected agent/ })).toBeInTheDocument();});++describe("v2 sidebar", () => {+ it("offers a new-wakeup button on open issues only", () => {+ const { unmount } = renderWithI18n(<WakeupsSection issueId="issue" />);+ expect(screen.getByRole("button", { name: "New wakeup" })).toBeVisible();+ unmount();+ renderWithI18n(<WakeupsSection issueId="issue" closed />);+ expect(screen.queryByRole("button", { name: "New wakeup" })).toBeNull();+ });++ it("describes a wait's deadline in the row and who created it in details", async () => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(new Date("2026-09-24T08:00:00Z"));+ try {+ Object.assign(wakeup, {+ kind: "event", mode: "once", event_types: ["comment.created"], interval_seconds: null,+ filter_actor_type: "member", filter_actor_id: "u", filter_actor_name: "Jiayuan",+ expires_at: "2026-09-27T06:00:00Z", expiry_seconds: 259200, on_timeout: "wake",+ created_by_agent: true, created_by_name: "Jiayuan", source_agent_name: "Emacs",+ });+ renderWithI18n(<WakeupsSection issueId="issue" />, { locale: "zh-Hans" });+ const row = screen.getByRole("button", { name: /由 Jiayuan 触发/ });+ expect(row).toHaveTextContent("唤醒 Emacs · 仅触发一次 · 还剩 2 天 22 小时");+ fireEvent.click(row);+ await waitFor(() => expect(screen.getByText(/来源/)).toHaveTextContent("Emacs 创建(代表 Jiayuan)"));+ expect(screen.getByText(/有效期/)).toHaveTextContent("超时后唤醒 Emacs 处理");+ } finally {+ vi.useRealTimers();+ }+ });++ it("marks a rule ended by its deadline as timed out", () => {+ Object.assign(wakeup, {+ kind: "event", mode: "once", event_types: ["comment.created"], enabled: false,+ expires_at: "2020-01-01T00:00:00Z", timed_out_at: "2020-01-01T00:00:30Z",+ });+ status = "completed";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ fireEvent.click(screen.getByRole("button", { name: "Wakeup history 1" }));+ expect(screen.getByRole("button", { name: /Wake Emacs/ })).toHaveTextContent("Timed out");+ });++ it("shows the child-done system rule and turns it off for this issue", async () => {+ systemRules = [{+ id: "rule", revision: 1, default_instruction: "Advance the next stage.", customized: false, paused_reason: null,+ rule: "child_done", workspace_default: true, enabled: true, instruction: "", staged: true, stage: 1, total: 2, remaining: 1,+ waiting: ["MUL-7704"], target: { type: "agent", id: "a", name: "Emacs" }, blocked: "",+ }];+ renderWithI18n(<WakeupsSection issueId="issue" />, { locale: "zh-Hans" });+ const row = screen.getByRole("button", { name: /当第 1 阶段的子任务全部结束时/ });+ expect(row).toHaveTextContent("系统");+ expect(row).toHaveTextContent("唤醒负责人 Emacs · 还差 1 个");+ expect(screen.getByRole("button", { name: /唤醒 2/ })).toBeVisible();+ fireEvent.click(screen.getAllByRole("switch", { name: "子任务结束时唤醒负责人" })[0]!);+ await waitFor(() => expect(updateSystem).toHaveBeenCalledWith({ rule: "child_done", enabled: false, instruction: "" }));+ });++ it("says a member assignee is notified instead of woken", () => {+ systemRules = [{+ id: "rule", revision: 1, default_instruction: "Advance the next stage.", customized: false, paused_reason: null,+ rule: "child_done", workspace_default: true, enabled: true, instruction: "", staged: false, stage: null, total: 3, remaining: 2,+ waiting: [], target: { type: "member", id: "u", name: "Jiayuan" }, blocked: "member_assignee",+ }];+ renderWithI18n(<WakeupsSection issueId="issue" />);+ expect(screen.getByRole("button", { name: /When all sub-issues finish/ })).toHaveTextContent("Notify Jiayuan in their inbox · 2 to go");+ });++ it("shows the default instruction and saves one for this issue", async () => {+ systemRules = [{+ id: "rule", revision: 1, default_instruction: "Advance the next stage.", customized: false, paused_reason: null,+ rule: "child_done", workspace_default: true, enabled: true, instruction: "", staged: false, stage: null, total: 1, remaining: 1,+ waiting: ["MUL-2"], target: { type: "agent", id: "a", name: "Emacs" }, blocked: "",+ }];+ renderWithI18n(<WakeupsSection issueId="issue" />);+ fireEvent.click(screen.getByRole("button", { name: /When all sub-issues finish/ }));+ expect(await screen.findByText("Advance the next stage.")).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Edit instruction" }));+ const input = screen.getByLabelText("What to do when woken");+ expect(input).toHaveAttribute("placeholder", "Advance the next stage.");+ fireEvent.change(input, { target: { value: "Ask Jiayuan first" } });+ fireEvent.submit(input.closest("form")!);+ await waitFor(() => expect(updateSystem).toHaveBeenCalledWith({ rule: "child_done", enabled: true, instruction: "Ask Jiayuan first" }));+ });+});++describe("conditions, limits and history", () => {+ it("reads a platform condition as its own sentence, without the hint events", async () => {+ Object.assign(wakeup, {+ kind: "event", mode: "once", event_types: ["issue.status_changed"], interval_seconds: null,+ condition: { type: "issue_field", field: "status", value: "in_review" },+ });+ renderWithI18n(<WakeupsSection issueId="issue" />, { locale: "zh-Hans" });+ const row = screen.getByRole("button", { name: /当状态变为in_review时/ });+ fireEvent.click(row);+ await screen.findByRole("dialog");+ expect(screen.queryByText(/以下任一事件发生时/)).toBeNull();+ });++ it("says why the platform paused a rule and how many times it fired", async () => {+ Object.assign(wakeup, {+ kind: "event", mode: "continuous", event_types: ["comment.created"], interval_seconds: null,+ enabled: false, paused_reason: "max_fires", max_fires: 5, fire_count: 5,+ });+ status = "completed";+ renderWithI18n(<WakeupsSection issueId="issue" />);+ fireEvent.click(screen.getByRole("button", { name: "Wakeup history 1" }));+ const row = screen.getByRole("button", { name: /Wake Emacs/ });+ expect(row).toHaveTextContent("Paused automatically");+ expect(row).toHaveTextContent("Stopped after reaching 5 runs");+ fireEvent.click(row);+ expect(await screen.findByText("Triggered 5 of at most 5 times")).toBeVisible();+ expect(screen.getByText(/Turn it back on to resume/)).toBeVisible();+ });++ it("lists the rule's runs, with a silent check's note", async () => {+ runs = [+ { id: "r2", status: "completed", created_at: "2026-09-24T01:00:00Z", started_at: null, completed_at: null, checkin_note: "Progress 38%", triggers: ["time.due"], commented: false },+ { id: "r1", status: "completed", created_at: "2026-09-23T01:00:00Z", started_at: null, completed_at: null, checkin_note: "", triggers: ["time.due"], commented: true },+ ];+ renderWithI18n(<WakeupsSection issueId="issue" />, { locale: "zh-Hans" });+ fireEvent.click(screen.getByRole("button", { name: /每小时唤醒/ }));+ expect(await screen.findByText("触发记录")).toBeVisible();+ expect(screen.getByText("静默检查")).toBeVisible();+ expect(screen.getByText(/Progress 38%/)).toBeVisible();+ expect(screen.getByText("运行成功 · 发表了评论")).toBeVisible();+ });++ it("wakes the agent now and deletes the rule after confirmation", async () => {+ renderWithI18n(<WakeupsSection issueId="issue" />);+ fireEvent.click(screen.getByRole("button", { name: /Wake every hour/ }));+ fireEvent.click(await screen.findByRole("button", { name: "Wake now" }));+ expect(trigger).toHaveBeenCalledWith("wake", expect.anything());+ fireEvent.click(screen.getByRole("button", { name: "Delete" }));+ const confirm = await screen.findByRole("alertdialog");+ expect(confirm).toHaveTextContent("Emacs is no longer woken by it");+ fireEvent.click(within(confirm).getByRole("button", { name: "Delete" }));+ expect(remove).toHaveBeenCalledWith("wake", expect.anything());+ });++ it("offers neither action on an ended issue", async () => {+ renderWithI18n(<WakeupsSection issueId="issue" closed />);+ fireEvent.click(screen.getByRole("button", { name: /Wake every hour/ }));+ await screen.findByRole("dialog");+ expect(screen.queryByRole("button", { name: "Wake now" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Delete" })).toBeNull();+ });+});diff --git a/packages/views/issues/components/wakeups-section.tsx b/packages/views/issues/components/wakeups-section.tsxindex 4e0160248a..373d32397e 100644--- a/packages/views/issues/components/wakeups-section.tsx+++ b/packages/views/issues/components/wakeups-section.tsx@@ -2,15 +2,19 @@import { useState } from "react";import { useQuery } from "@tanstack/react-query";-import { Bell, Clock3, ChevronRight } from "lucide-react";+import { Bell, Clock3, ChevronRight, GitPullRequest, Link2, ListChecks, CircleDot, Play } from "lucide-react";import { toast } from "sonner";import {+ issueSystemWakeupsOptions,+ issueWakeupRunsOptions,issueWakeupsOptions,+ useDeleteIssueWakeup,useDisableIssueWakeup,useEnableIssueWakeup,+ useTriggerIssueWakeup,issueTasksOptions,} from "@multica/core/issues";-import type { AgentTask, IssueWakeup } from "@multica/core/types";+import type { AgentTask, IssueWakeup, WakeupCondition } from "@multica/core/types";import { useCurrentWorkspace } from "@multica/core/paths";import {Popover,@@ -18,18 +22,128 @@ import {PopoverContent,PopoverTitle,} from "@multica/ui/components/ui/popover";+import { Button } from "@multica/ui/components/ui/button";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";import { WakeupInstructionEditor } from "./wakeup-instruction-editor";import { WakeupControl } from "./wakeup-control";+import { WakeupCreate } from "./wakeup-create";+import { SystemWakeupRow } from "./system-wakeup-row";import { TranscriptButton } from "../../common/task-transcript";import { useViewingTimezone } from "../../common/use-viewing-timezone";-import { useT } from "../../i18n";+import { useLocale, useT } from "../../i18n";import {+ formatWakeupTime,isCurrentWakeup,isActiveWakeupRun,useWakeupText,wakeupRun,} from "./wakeup-presentation";+/** The glyph a rule's condition reads with in lists and the timeline. */+export function conditionIcon(condition?: WakeupCondition | null) {+ switch (condition?.type) {+ case "children_done":+ return ListChecks;+ case "pull_request":+ return GitPullRequest;+ case "other_issue":+ return Link2;+ case "issue_field":+ return CircleDot;+ default:+ return null;+ }+}++/** The rule's latest runs: what fired, and what came of it. */+function WakeupHistory({ wakeup }: { wakeup: IssueWakeup }) {+ const { t } = useT("issues");+ const locale = useLocale();+ const viewTZ = useViewingTimezone();+ const workspaceId = useCurrentWorkspace()?.id ?? "";+ const text = useWakeupText();+ const { data: runs, isError } = useQuery(issueWakeupRunsOptions(workspaceId, wakeup.issue_id, wakeup.id));+ return (+ <div className="space-y-1.5">+ <p className="text-caption font-medium">{t(($) => $.wakeups.detail.history_title)}</p>+ {isError ? (+ <p className="text-caption text-muted-foreground">{t(($) => $.wakeups.detail.history_error)}</p>+ ) : runs && runs.length === 0 ? (+ <p className="text-caption text-muted-foreground">{t(($) => $.wakeups.detail.history_empty)}</p>+ ) : (+ <ul className="space-y-1">+ {(runs ?? []).map((run) => (+ <li key={run.id} className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 text-caption">+ <span className="tabular-nums text-muted-foreground">{formatWakeupTime(run.created_at, locale, viewTZ)}</span>+ <span className="min-w-0 break-words">+ {run.checkin_note ? (+ <>+ <span>{t(($) => $.wakeups.detail.run_checkin)}</span>+ <span className="text-muted-foreground"> · {run.checkin_note}</span>+ </>+ ) : run.commented ? (+ t(($) => $.wakeups.detail.run_commented, { state: text.runState(run.status) })+ ) : (+ text.runState(run.status)+ )}+ </span>+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}++function DeleteWakeup({ wakeup, onDeleted }: { wakeup: IssueWakeup; onDeleted: () => void }) {+ const { t } = useT("issues");+ const text = useWakeupText();+ const workspaceId = useCurrentWorkspace()?.id ?? "";+ const remove = useDeleteIssueWakeup(workspaceId, wakeup.issue_id);+ const [open, setOpen] = useState(false);+ return (+ <AlertDialog open={open} onOpenChange={(next) => !remove.isPending && setOpen(next)}>+ <Button variant="ghost" size="sm" className="ml-auto text-destructive hover:text-destructive" onClick={() => setOpen(true)}>+ {t(($) => $.wakeups.detail.delete)}+ </Button>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $.wakeups.detail.delete_title)}</AlertDialogTitle>+ <AlertDialogDescription>{t(($) => $.wakeups.detail.delete_body, { agent: wakeup.agent_name })}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={remove.isPending}>{t(($) => $.wakeups.create.cancel)}</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ disabled={remove.isPending}+ onClick={(event) => {+ event.preventDefault();+ remove.mutate(wakeup.id, {+ onSuccess: () => {+ setOpen(false);+ onDeleted();+ },+ onError: (err) => toast.error(text.error(err, t(($) => $.wakeups.detail.delete_error))),+ });+ }}+ >+ {remove.isPending ? t(($) => $.wakeups.detail.deleting) : t(($) => $.wakeups.detail.delete)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}+function WakeupRow({wakeup,task,@@ -53,13 +167,17 @@ function WakeupRow({const viewTZ = useViewingTimezone();const status = task?.status ?? wakeup.last_task_status;const activeRun = isActiveWakeupRun(status);- const Icon = wakeup.kind === "event" ? Bell : Clock3;+ const Icon = conditionIcon(wakeup.condition) ?? (wakeup.kind === "event" ? Bell : Clock3);+ const [detailOpen, setDetailOpen] = useState(false);+ const trigger = useTriggerIssueWakeup(workspaceId, wakeup.issue_id);+ const paused = text.paused(wakeup);+ const fires = text.fires(wakeup);return (<divclassName="grid grid-cols-[minmax(0,1fr)_auto]"aria-busy={pending}>- <Popover>+ <Popover open={detailOpen} onOpenChange={setDetailOpen}><PopoverTriggerrender={<button@@ -68,25 +186,18 @@ function WakeupRow({/>}>- <span className="flex min-h-8 min-w-0 items-center gap-2 pl-2 pr-1">+ <span className="flex min-h-8 min-w-0 items-start gap-2 py-1 pl-2 pr-1"><Icon- className="size-3.5 shrink-0 text-muted-foreground"+ className="mt-px size-3.5 shrink-0 text-muted-foreground"aria-hidden="true"/>- <span className="truncate font-medium">+ <span className="line-clamp-2 min-w-0 break-words font-medium">{text.trigger(wakeup)}</span></span><span className="col-span-2 min-w-0 break-words pl-7.5 pr-2"><span className="block text-muted-foreground">- {t(($) => $.wakeups.wake_agent, { agent: wakeup.agent_name })} ·{" "}- {wakeup.kind === "event" || wakeup.kind === "at"- ? text.frequency(wakeup)- : text.state(wakeup, closed)}- {!wakeup.enabled &&- (wakeup.kind === "event" || wakeup.kind === "at") && (- <> · {text.state(wakeup, closed)}</>- )}+ {text.summary(wakeup, closed)}</span>{status && (<span className="block text-muted-foreground">@@ -104,6 +215,7 @@ function WakeupRow({{t(($) => $.wakeups.stopped_running)}</span>)}+ {paused && <span className="block text-warning">{paused}</span>}{wakeup.last_error && (<span className="block text-destructive">{t(($) => $.wakeups.needs_attention)}@@ -125,6 +237,22 @@ function WakeupRow({{t(($) => $.wakeups.scope_title)}:{" "}{t(($) => $.wakeups.scope_current)}</p>+ {wakeup.created_by_name && (+ <p className="break-words text-caption text-muted-foreground">+ {t(($) => $.wakeups.source_title)}: {text.source(wakeup)}+ </p>+ )}+ {wakeup.expires_at && (+ <p className="break-words text-caption text-muted-foreground">+ {t(($) => $.wakeups.expiry_title)}: {text.expiry(wakeup)}+ </p>+ )}+ {fires && <p className="text-caption text-muted-foreground">{fires}</p>}+ {paused && (+ <p className="break-words text-caption text-warning">+ {paused} · {t(($) => $.wakeups.paused.hint)}+ </p>+ )}<div className="flex items-center justify-between gap-2"><p className="text-caption font-medium">{t(($) => $.wakeups.instruction_title)}</p><WakeupInstructionEditor workspaceId={workspaceId} issueId={wakeup.issue_id} wakeupId={wakeup.id} />@@ -132,7 +260,7 @@ function WakeupRow({<p className="whitespace-pre-wrap break-words text-caption">{wakeup.instruction}</p>- {wakeup.kind === "event" && (+ {wakeup.kind === "event" && !wakeup.condition && (<p className="break-words text-caption text-muted-foreground">{t(($) => $.wakeups.any_event)}:{" "}{wakeup.event_types@@ -193,6 +321,28 @@ function WakeupRow({/></div>)}+ {detailOpen && <WakeupHistory wakeup={wakeup} />}+ {!closed && (+ <div className="flex items-center gap-1 border-t border-border pt-2.5">+ {!wakeup.disabled_at && (+ <Button+ variant="outline"+ size="sm"+ disabled={trigger.isPending}+ onClick={() =>+ trigger.mutate(wakeup.id, {+ onSuccess: () => toast.success(t(($) => $.wakeups.detail.wake_now_done, { agent: wakeup.agent_name })),+ onError: (err) => toast.error(text.error(err, t(($) => $.wakeups.detail.wake_now_error))),+ })+ }+ >+ <Play aria-hidden="true" />+ {t(($) => $.wakeups.detail.wake_now)}+ </Button>+ )}+ <DeleteWakeup wakeup={wakeup} onDeleted={() => setDetailOpen(false)} />+ </div>+ )}</PopoverContent></Popover><div className="z-10 col-start-2 row-start-1 self-start">@@ -212,9 +362,12 @@ function WakeupRow({export function WakeupsSection({issueId,closed = false,+ defaultAgentId,}: {issueId: string;closed?: boolean;+ /** Preselected target for a new wakeup: the issue's agent assignee. */+ defaultAgentId?: string;}) {const { t } = useT("issues");const workspaceId = useCurrentWorkspace()?.id ?? "";@@ -226,10 +379,12 @@ export function WakeupsSection({refetch,} = useQuery(issueWakeupsOptions(workspaceId, issueId));const { data: tasks = [] } = useQuery(issueTasksOptions(issueId));+ const { data: systemRules = [] } = useQuery(issueSystemWakeupsOptions(workspaceId, issueId));const text = useWakeupText();const disable = useDisableIssueWakeup(workspaceId, issueId);const enable = useEnableIssueWakeup(workspaceId, issueId);- if (!data.length && !isError) return null;+ // Open issues always show the section so people can add a wakeup.+ if (closed && !data.length && !isError) return null;const current = data.filter((w) => isCurrentWakeup(w, wakeupRun(w, tasks)));const history = data.filter((w) => !isCurrentWakeup(w, wakeupRun(w, tasks)));const row = (wakeup: IssueWakeup) => (@@ -263,21 +418,27 @@ export function WakeupsSection({);return (<section>- <button- type="button"- aria-expanded={open}- onClick={() => setOpen(!open)}- className="mb-1 flex min-h-9 w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium hover:bg-accent/70 focus-visible:outline-2 focus-visible:outline-ring"- >- {t(($) => $.wakeups.title)}{" "}- <span className="text-muted-foreground tabular-nums">- {current.length}- </span>- <ChevronRight- className={`size-3 text-muted-foreground ${open ? "rotate-90" : ""}`}- aria-hidden="true"- />- </button>+ <div className="mb-1 flex items-center gap-1">+ <button+ type="button"+ id={`issue-wakeups-${issueId}`}+ aria-expanded={open}+ onClick={() => setOpen(!open)}+ className="flex min-h-9 flex-1 items-center gap-1 rounded-md px-2 py-1 text-caption font-medium hover:bg-accent/70 focus-visible:outline-2 focus-visible:outline-ring"+ >+ {t(($) => $.wakeups.title)}{" "}+ <span className="text-muted-foreground tabular-nums">+ {current.length + systemRules.length}+ </span>+ <ChevronRight+ className={`size-3 text-muted-foreground ${open ? "rotate-90" : ""}`}+ aria-hidden="true"+ />+ </button>+ {!closed && (+ <WakeupCreate workspaceId={workspaceId} issueId={issueId} defaultAgentId={defaultAgentId} />+ )}+ </div>{open && (<div>{isError && (@@ -294,6 +455,10 @@ export function WakeupsSection({{t(($) => $.wakeups.closed_hint)}</p>)}+ {!closed &&+ systemRules.map((rule) => (+ <SystemWakeupRow key={rule.rule} rule={rule} workspaceId={workspaceId} issueId={issueId} />+ ))}{current.map(row)}{history.length > 0 && (<>diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 5cfbacc427..34e41b9d04 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -910,7 +910,8 @@"tool_kind_command": "Commands","tool_kind_write": "Edits","tool_kind_read": "Reads",- "tool_kind_misc": "Other"+ "tool_kind_misc": "Other",+ "trigger_wakeup": "Wakeup"},"task_failure": {"cancelled_by_system": "Cancelled by the system",diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.jsonindex 52771fa43d..d3db6e12bc 100644--- a/packages/views/locales/en/autopilots.json+++ b/packages/views/locales/en/autopilots.json@@ -479,7 +479,6 @@"scope": "Scope","issue": "Issue","trigger": "Trigger",- "next": "Wakeup state","enabled": "Enabled","all_triggers": "All triggers","event": "Event",@@ -487,7 +486,6 @@"recurring": "Recurring","all_agents": "All agents","search": "Search issues or agents",- "search_action": "Search","running": "Running","active_runs": "{{count}} active runs","issue_closed": "Issue closed",@@ -513,13 +511,32 @@"active": "Waiting or executing","all": "All","disabled": "Turned off",- "ended": "Ended"+ "ended": "Ended",+ "paused": "Paused"},"target_agent": "Wake agent",- "wakeup_run": "Runs from wakeup","empty_filtered": "No matching wakeups","clear_filters": "Clear filters","batch_success": "Turned off {{count}} wakeup rules",- "batch_partial": "Turned off {{succeeded}}; {{failed}} failed. Failed items remain selected for retry."+ "batch_partial": "Turned off {{succeeded}}; {{failed}} failed. Failed items remain selected for retry.",+ "source": "Source",+ "sources": {+ "all": "Source: All",+ "member": "Members",+ "agent": "Agents",+ "system": "System"+ },+ "runs_7d": "Runs (7 days)",+ "ends": "Ends",+ "until_issue_ends": "Until the issue ends",+ "fires_once": "Triggers once",+ "assignee_target": "Assignee · {{name}}",+ "no_target": "No agent assignee",+ "banner_one": "{{count}} wakeup was paused automatically: {{issue}} “{{condition}}” — {{reason}}",+ "banner_other": "{{count}} wakeups were paused automatically. Latest: {{issue}} “{{condition}}” — {{reason}}",+ "banner_view": "View",+ "create": "New wakeup",+ "create_pick_issue": "Choose the issue to add a wakeup to",+ "create_pick_issue_description": "The wakeup belongs to this issue and ends with it."}}diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex 736f050468..d4ee657b8e 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -80,6 +80,7 @@"quick_create_failed": "Create with agent failed","quick_create_unconfirmed": "Create with agent unconfirmed","autopilot_paused": "Autopilot paused",+ "children_done": "Sub-issues finished","autopilot_quota_exceeded": "Autopilot run limit reached"},"labels": {@@ -94,7 +95,8 @@"reacted_to_comment": "Reacted {{emoji}} to your comment","created_with_agent": "Created with agent: {{identifier}}","failed_with_detail": "Failed: {{detail}}",- "autopilot_quota_blocked": "Run blocked because the limit was reached"+ "autopilot_quota_blocked": "Run blocked because the limit was reached",+ "children_done_stage": "Stage {{stage}}'s sub-issues finished"},"toasts": {"source_context_retry_started": "Retry started with the original context",diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex bacc007b0b..8d11947b2d 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -524,7 +524,28 @@"duplicate_removed": "unmarked {{identifier}} as a duplicate of this issue","status_changed_pr": "changed status from {{from}} to {{to}} after every linked PR merged ({{prs}})","pr_auto_complete_disabled": "set this issue to keep its status when PRs merge",- "pr_auto_complete_enabled": "set this issue to change status when PRs merge again"+ "pr_auto_complete_enabled": "set this issue to change status when PRs merge again",+ "wakeup_created": "added a wakeup: {{condition}} · wake {{agent}}",+ "wakeup_triggered": "{{condition}} · woke {{agent}}",+ "wakeup_triggered_merged": "{{condition}} · joined {{agent}}'s waiting run",+ "wakeup_triggered_acknowledged": "{{condition}} · {{agent}} did this itself; not woken again",+ "wakeup_triggered_manual": "{{name}} woke {{agent}} now",+ "wakeup_child_done_stage_one": "Stage {{stage}}'s sub-issue finished",+ "wakeup_child_done_stage_other": "Stage {{stage}}'s {{count}} sub-issues all finished",+ "wakeup_child_done_all_one": "The sub-issue finished",+ "wakeup_child_done_all_other": "All {{count}} sub-issues finished",+ "wakeup_child_done_woke": " · woke {{name}}",+ "wakeup_child_done_notified": " · notified {{name}}",+ "wakeup_child_done_merged": " · joined {{name}}'s waiting run",+ "wakeup_child_done_acknowledged": " · {{name}} is already on it; not woken again",+ "wakeup_assignee": "the assignee",+ "wakeup_timed_out_wake": "{{condition}} did not happen in time · woke {{agent}} to handle it",+ "wakeup_timed_out_end": "Wakeup ended at its deadline: {{condition}}",+ "wakeup_checkin": "silent check: {{note}}",+ "wakeup_checkin_coalesced_one": "{{count}} silent check · latest: {{note}}",+ "wakeup_checkin_coalesced_other": "{{count}} silent checks · latest: {{note}}",+ "wakeup_chip_created_by": "{{name}}'s wakeup",+ "wakeup_chip_system": "System rule"},"comment": {"add_reaction": "Add reaction",@@ -729,7 +750,8 @@"source_backfill": "Backfilled attribution","source_unattributed": "No responsible member resolved"},- "usage_total_tooltip": "Token usage for this issue — click for the per-run breakdown"+ "usage_total_tooltip": "Token usage for this issue — click for the per-run breakdown",+ "trigger_wakeup": "Wakeup · {{condition}}"},"usage_detail": {"title": "Usage breakdown",@@ -997,7 +1019,7 @@"disable": "Turn off wakeup for {{agent}}","disable_error": "Could not turn off wakeup","source_run": "Run being monitored",- "source_agent": "Agent being monitored",+ "source_agent": "{{agent}}, on behalf of {{name}}","next": "Next:","last_run": "View run record","run_completed": "Run completed",@@ -1108,7 +1130,9 @@"triggered": "Triggered","expired": "Expired","inactive": "Not enabled",- "issue_closed": "Issue ended; wakeups stopped"+ "issue_closed": "Issue ended; wakeups stopped",+ "timed_out": "Timed out",+ "paused": "Paused automatically"},"run_states": {"queued": "Queued",@@ -1121,7 +1145,213 @@"cancelled": "Cancelled"},"hourly": "Wake every hour",- "today_time": "Today {{time}}"+ "today_time": "Today {{time}}",+ "remaining_days": "{{days}} days left",+ "remaining_days_hours": "{{days}}d {{hours}}h left",+ "remaining_hours": "{{hours}}h left",+ "remaining_minutes": "{{minutes}} min left",+ "until_date": "until {{date}}",+ "source_title": "Created by",+ "source_member": "{{name}}",+ "source_agent_unknown": "an agent",+ "expiry_title": "Ends",+ "expiry_at": "{{time}}",+ "expiry_timed_out": "Timed out at {{time}}",+ "timeout_then_wake": "Then wake {{agent}} to handle it",+ "timeout_then_end": "Then end without a run",+ "create": {+ "open": "New wakeup",+ "title": "New wakeup",+ "when": "When",+ "wake": "Wake",+ "choose_condition": "Choose a condition",+ "choose_agent": "Choose an agent",+ "group_time": "Time",+ "group_collaboration": "Collaboration",+ "group_runs": "Runs and sub-issues",+ "cond_at": "At a time",+ "cond_at_hint": "In 10 min, tomorrow 09:00",+ "cond_recurring": "Check regularly",+ "cond_recurring_hint": "Hourly or daily, with an end date",+ "cond_reply": "Someone replies",+ "cond_reply_hint": "Anyone, or a specific person",+ "cond_run_end": "An agent's run ends",+ "cond_run_end_hint": "Succeeded, failed or cancelled",+ "cond_custom": "Custom events…",+ "cond_custom_hint": "{{count}} raw events",+ "at_10m": "In 10 minutes",+ "at_1h": "In 1 hour",+ "at_tomorrow": "Tomorrow 09:00",+ "at_custom": "Pick a time",+ "hourly": "Every hour",+ "daily": "Every day 09:00",+ "weekdays": "Weekdays 09:00",+ "until": "Until",+ "anyone": "Anyone",+ "members": "Members",+ "agents": "Agents",+ "any_agent": "Any agent",+ "events_selected": "{{count}} events",+ "instruction_placeholder": "For example: check the result and continue if it looks right",+ "trigger_count": "Triggers",+ "max_wait": "Wait up to",+ "wait_days_one": "{{count}} day",+ "wait_days_other": "{{count}} days",+ "on_timeout": "Then",+ "timeout_wake": "Wake {{agent}} to handle it",+ "timeout_end": "End without a run",+ "the_agent": "the agent",+ "on_behalf": "Runs act on your behalf",+ "submit": "Create",+ "submitting": "Creating…",+ "cancel": "Cancel",+ "error": "Could not create the wakeup. Check the settings and try again.",+ "capacity_error": "This issue or workspace already has the maximum number of enabled wakeups.",+ "missing_condition": "Choose a condition.",+ "missing_agent": "Choose an agent to wake.",+ "missing_events": "Choose at least one event.",+ "until_future": "Choose an end date after today.",+ "closed": "Completed or canceled issues cannot get new wakeups.",+ "group_linked": "Linked",+ "cond_field": "A field changes to a value",+ "cond_field_hint": "Status, assignee, label, property",+ "cond_children": "Sub-issues finish",+ "cond_children_hint": "All of them, or one stage",+ "cond_pr": "A linked PR's CI finishes",+ "cond_pr_hint": "Or it merges",+ "cond_issue": "Another issue's status",+ "cond_issue_hint": "e.g. when it is done",+ "field_status": "Status",+ "field_assignee": "Assignee",+ "field_label": "Label",+ "field_property": "Property",+ "field_kind": "Field",+ "choose_status": "Choose a status",+ "choose_assignee": "Choose an assignee",+ "choose_label": "Choose a label",+ "choose_property": "Choose a property",+ "value_placeholder": "Value",+ "squads": "Squads",+ "children_all": "All sub-issues",+ "children_stage": "Stage {{stage}}",+ "pr_checks": "CI finishes",+ "pr_merged": "It merges",+ "choose_issue": "Choose an issue",+ "pick_issue_title": "Watch an issue",+ "pick_issue_description": "Wake the agent when this issue reaches the state you choose.",+ "other_done": "is done",+ "other_ended": "is done or cancelled",+ "other_in_review": "moves to In Review",+ "max_fires": "Up to",+ "max_fires_times_one": "{{count}} time",+ "max_fires_times_other": "{{count}} times",+ "missing_value": "Choose a value.",+ "missing_issue": "Choose an issue.",+ "checked": "Checked",+ "unchecked": "Unchecked",+ "assignee_comment_hint": "{{name}} is the assignee and already runs when a member comments. This rule joins that run instead of starting another; add it only to give that run an extra instruction."+ },+ "system": {+ "badge": "System",+ "title_stage": "When stage {{stage}}'s sub-issues all finish",+ "title_all": "When all sub-issues finish",+ "wake_assignee": "Wake assignee {{name}}",+ "remaining_one": "{{count}} to go",+ "remaining_other": "{{count}} to go",+ "blocked_backlog": "Issue is in backlog; no wakeup for now",+ "blocked_member": "Assignee is a member; they get an inbox notification",+ "blocked_none": "No agent assignee; nobody is woken",+ "turned_off": "Turned off for this issue",+ "target_title": "Wakes",+ "target_current": "Assignee (currently {{name}})",+ "target_none": "The assignee: an agent or squad is woken, a member is notified",+ "progress_title": "Progress",+ "progress": "{{done}}/{{total}} finished",+ "waiting_on": "waiting on {{ids}}",+ "skip_title": "Skipped when",+ "skip": "The issue is in backlog; it catches up once the issue leaves backlog",+ "source": "System rule · on for issues with sub-issues",+ "enable": "On for this issue",+ "toggle": "Wake the assignee when sub-issues finish",+ "save_error": "Could not save the system rule.",+ "default_on": "On by default in this workspace. Change the default in Settings → Wakeups.",+ "default_off": "Off by default in this workspace. Change the default in Settings → Wakeups.",+ "notify_member": "Notify {{name}} in their inbox",+ "instruction": "What to do when woken",+ "instruction_edit": "Edit instruction",+ "instruction_default": "Not set on this issue; uses the default:",+ "instruction_placeholder": "Leave empty to use the default",+ "instruction_invalid": "Keep the instruction within 4,000 bytes.",+ "paused": "Paused: {{reason}}"+ },+ "cond": {+ "status": "When this issue moves to {{status}}",+ "assignee": "When this issue is assigned to {{name}}",+ "label": "When this issue gets the label {{label}}",+ "property": "When {{property}} is {{value}}",+ "children_all": "When all sub-issues finish",+ "children_stage": "When stage {{stage}}'s sub-issues all finish",+ "pr_checks": "When a linked PR's CI finishes",+ "pr_merged": "When a linked PR merges",+ "other_done": "When {{issue}} is done",+ "other_ended": "When {{issue}} is done or cancelled",+ "other_in_review": "When {{issue}} moves to In Review",+ "another_issue": "another issue",+ "unknown_label": "a deleted label",+ "unknown_property": "a deleted property",+ "checked": "checked",+ "unchecked": "unchecked"+ },+ "wait": {+ "reply_from": "Waiting for {{name}} to reply",+ "reply_any": "Waiting for a reply",+ "run_end": "Waiting for {{agent}}'s run",+ "run_end_any": "Waiting for a run to end",+ "status": "Waiting for {{status}}",+ "assignee": "Waiting for {{name}} to be assigned",+ "label": "Waiting for the label {{label}}",+ "property": "Waiting for {{property}} = {{value}}",+ "children_all": "Waiting for sub-issues",+ "children_stage": "Waiting for stage {{stage}}",+ "pr_checks": "Waiting for CI",+ "pr_merged": "Waiting for the PR to merge",+ "other_done": "Waiting for {{issue}}",+ "other_ended": "Waiting for {{issue}} to end",+ "other_in_review": "Waiting for {{issue}} to reach review",+ "time": "{{time}} · wakes {{agent}}",+ "header": "{{agent}}: {{what}}",+ "paused": "Wakeup paused",+ "open": "Show wakeups"+ },+ "paused": {+ "max_fires": "Stopped after reaching {{count}} runs",+ "loop": "Paused: it kept waking rules that woke it again",+ "rate": "Paused: more than 12 runs in an hour",+ "hint": "Turn it back on to resume; the count starts over."+ },+ "detail": {+ "fires_one": "Triggered {{count}} time",+ "fires_other": "Triggered {{count}} times",+ "fires_max": "Triggered {{count}} of at most {{max}} times",+ "history_title": "Trigger history",+ "history_empty": "Not triggered yet",+ "history_error": "Could not load the history",+ "run_checkin": "Silent check",+ "run_commented": "{{state}} · commented",+ "wake_now": "Wake now",+ "wake_now_done": "{{agent}} will run shortly",+ "wake_now_error": "Could not wake the agent",+ "delete": "Delete",+ "delete_title": "Delete this wakeup?",+ "delete_body": "{{agent}} is no longer woken by it, and its runs that have not started are withdrawn. A run already started keeps going.",+ "deleting": "Deleting…",+ "delete_error": "Could not delete the wakeup"+ },+ "paused_reason": {+ "max_fires": "reached its limit of {{count}} runs",+ "loop": "it kept waking rules that woke it again",+ "rate": "more than 12 runs in an hour"+ }},"duplicates": {"banner_prefix": "Duplicate of",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex b3fe8fdd39..136349db31 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -81,6 +81,24 @@"pr_auto_complete_badge": "Set when PRs merge","built_in_locked": "Built-in statuses drive system behavior, so they can't be edited or archived. You can still reorder them."},+ "wakeups": {+ "description": "Platform rules that apply to every issue. Each issue can change them in its Wakeups section.",+ "child_done_title": "When sub-issues finish",+ "child_done_description": "Wakes the parent's assignee when a stage finishes and a later stage is waiting, and once more when every sub-issue is closed. A member assignee gets an inbox notification instead.",+ "enabled": "On by default",+ "instruction": "Default instruction",+ "instruction_hint": "Sent to the woken agent. Leave empty to use the built-in instruction below.",+ "instruction_placeholder": "Leave empty to use the built-in instruction",+ "builtin": "Built-in instruction",+ "instruction_invalid": "Keep the instruction within 4,000 bytes.",+ "save": "Save",+ "saving": "Saving…",+ "save_error": "Could not save the default.",+ "customized_one": "{{count}} open issue has its own setting and ignores this default.",+ "customized_other": "{{count}} open issues have their own setting and ignore this default.",+ "admin_only": "Only owners and admins can change these defaults.",+ "load_error": "Could not load wakeup defaults."+ },"quick_actions": {"title": "Quick Actions","description": "Run a preset agent and prompt from an issue's sidebar.",@@ -379,6 +397,7 @@"members": "Members","labels": "Labels","issue_statuses": "Issue Statuses",+ "wakeups": "Wakeups","properties": "Properties","quick_actions": "Quick Actions","plugins": "Plugins",diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.jsonindex c927ec6cc7..3f40cc016c 100644--- a/packages/views/locales/fr/agents.json+++ b/packages/views/locales/fr/agents.json@@ -910,7 +910,8 @@"tool_kind_command": "Commandes","tool_kind_write": "Modifications","tool_kind_read": "Lectures",- "tool_kind_misc": "Autres"+ "tool_kind_misc": "Autres",+ "trigger_wakeup": "Réveil"},"task_failure": {"cancelled_by_system": "Annulée par le système",diff --git a/packages/views/locales/fr/autopilots.json b/packages/views/locales/fr/autopilots.jsonindex deea859a91..75d1b3dc1f 100644--- a/packages/views/locales/fr/autopilots.json+++ b/packages/views/locales/fr/autopilots.json@@ -479,7 +479,6 @@"scope": "Périmètre","issue": "Tâche","trigger": "Déclencheur",- "next": "État du réveil","enabled": "Activé","all_triggers": "Tous les déclencheurs","event": "Événement",@@ -487,7 +486,6 @@"recurring": "Récurrent","all_agents": "Tous les agents","search": "Rechercher des tâches ou agents",- "search_action": "Rechercher","running": "En cours","active_runs": "{{count}} exécutions actives","issue_closed": "Tâche fermée",@@ -513,13 +511,32 @@"active": "En attente ou en cours","all": "Tous","disabled": "Désactivés",- "ended": "Terminés"+ "ended": "Terminés",+ "paused": "En pause"},"target_agent": "Agent à réveiller",- "wakeup_run": "Exécutions du réveil","empty_filtered": "Aucun réveil correspondant","clear_filters": "Effacer les filtres","batch_success": "{{count}} règles désactivées",- "batch_partial": "{{succeeded}} désactivées ; {{failed}} échecs. Les éléments en échec restent sélectionnés pour réessayer."+ "batch_partial": "{{succeeded}} désactivées ; {{failed}} échecs. Les éléments en échec restent sélectionnés pour réessayer.",+ "source": "Source",+ "sources": {+ "all": "Source : toutes",+ "member": "Membres",+ "agent": "Agents",+ "system": "Système"+ },+ "runs_7d": "Exécutions (7 jours)",+ "ends": "Fin",+ "until_issue_ends": "Jusqu’à la fin de la tâche",+ "fires_once": "Se déclenche une fois",+ "assignee_target": "Responsable · {{name}}",+ "no_target": "Aucun agent responsable",+ "banner_one": "{{count}} réveil mis en pause automatiquement : {{issue}} « {{condition}} » — {{reason}}",+ "banner_other": "{{count}} réveils mis en pause automatiquement. Dernier : {{issue}} « {{condition}} » — {{reason}}",+ "banner_view": "Voir",+ "create": "Nouveau réveil",+ "create_pick_issue": "Choisissez la tâche où ajouter un réveil",+ "create_pick_issue_description": "Le réveil appartient à cette tâche et s’arrête avec elle."}}diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.jsonindex 4411ac5262..35654d390d 100644--- a/packages/views/locales/fr/inbox.json+++ b/packages/views/locales/fr/inbox.json@@ -80,6 +80,7 @@"quick_create_failed": "Échec de la création avec un agent","quick_create_unconfirmed": "Création avec un agent non confirmée","autopilot_paused": "Automatisation en pause",+ "children_done": "Sous-tâches terminées","autopilot_quota_exceeded": "Limite d'exécutions d'automatisation atteinte"},"labels": {@@ -94,7 +95,8 @@"reacted_to_comment": "A réagi {{emoji}} à votre commentaire","created_with_agent": "Créé avec un agent : {{identifier}}","failed_with_detail": "Échec : {{detail}}",- "autopilot_quota_blocked": "Exécution bloquée car la limite a été atteinte"+ "autopilot_quota_blocked": "Exécution bloquée car la limite a été atteinte",+ "children_done_stage": "Sous-tâches de l’étape {{stage}} terminées"},"toasts": {"source_context_retry_started": "Nouvelle tentative démarrée avec le contexte d'origine",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex cc592abe38..fb77576c08 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -524,7 +524,28 @@"duplicate_removed": "a retiré la marque de doublon de {{identifier}}","status_changed_pr": "a changé le statut de {{from}} à {{to}} après la fusion de toutes les PR liées ({{prs}})","pr_auto_complete_disabled": "a configuré cette tâche pour garder son statut à la fusion des PR",- "pr_auto_complete_enabled": "a de nouveau fait changer le statut de cette tâche à la fusion des PR"+ "pr_auto_complete_enabled": "a de nouveau fait changer le statut de cette tâche à la fusion des PR",+ "wakeup_created": "a ajouté un réveil : {{condition}} · réveiller {{agent}}",+ "wakeup_triggered": "{{condition}} · {{agent}} réveillé",+ "wakeup_triggered_merged": "{{condition}} · ajouté à l’exécution en attente de {{agent}}",+ "wakeup_triggered_acknowledged": "{{condition}} · déclenché par {{agent}} lui-même ; pas de nouveau réveil",+ "wakeup_triggered_manual": "{{name}} a réveillé {{agent}} maintenant",+ "wakeup_child_done_stage_one": "La sous-tâche de l’étape {{stage}} est terminée",+ "wakeup_child_done_stage_other": "Les {{count}} sous-tâches de l’étape {{stage}} sont terminées",+ "wakeup_child_done_all_one": "La sous-tâche est terminée",+ "wakeup_child_done_all_other": "Les {{count}} sous-tâches sont terminées",+ "wakeup_child_done_woke": " · {{name}} réveillé",+ "wakeup_child_done_notified": " · {{name}} notifié",+ "wakeup_child_done_merged": " · ajouté à l’exécution en attente de {{name}}",+ "wakeup_child_done_acknowledged": " · {{name}} s’en occupe déjà ; pas de nouveau réveil",+ "wakeup_assignee": "le responsable",+ "wakeup_timed_out_wake": "{{condition}} n’est pas arrivé à temps · {{agent}} réveillé pour gérer",+ "wakeup_timed_out_end": "Réveil terminé à échéance : {{condition}}",+ "wakeup_checkin": "vérification silencieuse : {{note}}",+ "wakeup_checkin_coalesced_one": "{{count}} vérification silencieuse · dernière : {{note}}",+ "wakeup_checkin_coalesced_other": "{{count}} vérifications silencieuses · dernière : {{note}}",+ "wakeup_chip_created_by": "Réveil de {{name}}",+ "wakeup_chip_system": "Règle système"},"comment": {"add_reaction": "Ajouter une réaction",@@ -729,7 +750,8 @@"source_backfill": "Attribution reconstituée","source_unattributed": "Aucun membre responsable identifié"},- "usage_total_tooltip": "Consommation de tokens pour cette tâche — cliquez pour le détail par exécution"+ "usage_total_tooltip": "Consommation de tokens pour cette tâche — cliquez pour le détail par exécution",+ "trigger_wakeup": "Réveil · {{condition}}"},"usage_detail": {"title": "Détail de la consommation",@@ -997,7 +1019,7 @@"disable": "Désactiver le réveil de {{agent}}","disable_error": "Impossible de désactiver le réveil","source_run": "Exécution surveillée",- "source_agent": "Agent surveillé",+ "source_agent": "{{agent}}, pour {{name}}","next": "Prochain :","last_run": "Voir l’exécution","run_completed": "Exécution terminée",@@ -1108,7 +1130,9 @@"triggered": "Déclenché","expired": "Expiré","inactive": "Non activé",- "issue_closed": "Tâche terminée ; réveils arrêtés"+ "issue_closed": "Tâche terminée ; réveils arrêtés",+ "timed_out": "Expirée",+ "paused": "Mis en pause automatiquement"},"run_states": {"queued": "En file",@@ -1121,7 +1145,213 @@"cancelled": "Annulée"},"hourly": "Réveil chaque heure",- "today_time": "Aujourd’hui {{time}}"+ "today_time": "Aujourd’hui {{time}}",+ "remaining_days": "{{days}} j restants",+ "remaining_days_hours": "{{days}} j {{hours}} h restants",+ "remaining_hours": "{{hours}} h restantes",+ "remaining_minutes": "{{minutes}} min restantes",+ "until_date": "jusqu’au {{date}}",+ "source_title": "Créée par",+ "source_member": "{{name}}",+ "source_agent_unknown": "un agent",+ "expiry_title": "Fin",+ "expiry_at": "{{time}}",+ "expiry_timed_out": "Expirée le {{time}}",+ "timeout_then_wake": "Puis réveiller {{agent}} pour s’en occuper",+ "timeout_then_end": "Puis terminer sans exécution",+ "create": {+ "open": "Nouveau réveil",+ "title": "Nouveau réveil",+ "when": "Quand",+ "wake": "Réveiller",+ "choose_condition": "Choisir une condition",+ "choose_agent": "Choisir un agent",+ "group_time": "Temps",+ "group_collaboration": "Collaboration",+ "group_runs": "Exécutions et sous-tâches",+ "cond_at": "À une heure donnée",+ "cond_at_hint": "Dans 10 min, demain 09:00",+ "cond_recurring": "Vérifier régulièrement",+ "cond_recurring_hint": "Toutes les heures ou chaque jour, avec une date de fin",+ "cond_reply": "Quelqu’un répond",+ "cond_reply_hint": "N’importe qui, ou une personne précise",+ "cond_run_end": "L’exécution d’un agent se termine",+ "cond_run_end_hint": "Réussie, échouée ou annulée",+ "cond_custom": "Événements personnalisés…",+ "cond_custom_hint": "{{count}} événements bruts",+ "at_10m": "Dans 10 minutes",+ "at_1h": "Dans 1 heure",+ "at_tomorrow": "Demain 09:00",+ "at_custom": "Choisir une heure",+ "hourly": "Toutes les heures",+ "daily": "Chaque jour 09:00",+ "weekdays": "Jours ouvrés 09:00",+ "until": "Jusqu’au",+ "anyone": "N’importe qui",+ "members": "Membres",+ "agents": "Agents",+ "any_agent": "N’importe quel agent",+ "events_selected": "{{count}} événements",+ "instruction_placeholder": "Par exemple : vérifier le résultat et continuer s’il est correct",+ "trigger_count": "Déclenchements",+ "max_wait": "Attendre au plus",+ "wait_days_one": "{{count}} jour",+ "wait_days_other": "{{count}} jours",+ "on_timeout": "Ensuite",+ "timeout_wake": "Réveiller {{agent}}",+ "timeout_end": "Terminer sans exécution",+ "the_agent": "l’agent",+ "on_behalf": "Les exécutions agissent en votre nom",+ "submit": "Créer",+ "submitting": "Création…",+ "cancel": "Annuler",+ "error": "Impossible de créer le réveil. Vérifiez les réglages et réessayez.",+ "capacity_error": "Cette tâche ou cet espace a atteint le nombre maximal de réveils actifs.",+ "missing_condition": "Choisissez une condition.",+ "missing_agent": "Choisissez l’agent à réveiller.",+ "missing_events": "Choisissez au moins un événement.",+ "until_future": "Choisissez une date de fin postérieure à aujourd’hui.",+ "closed": "Impossible d’en créer sur une tâche terminée ou annulée.",+ "group_linked": "Liés",+ "cond_field": "Un champ prend une valeur",+ "cond_field_hint": "Statut, responsable, libellé, propriété",+ "cond_children": "Les sous-tâches se terminent",+ "cond_children_hint": "Tous, ou une étape",+ "cond_pr": "La CI d’une PR liée se termine",+ "cond_pr_hint": "Ou sa fusion",+ "cond_issue": "Le statut d’une autre tâche",+ "cond_issue_hint": "p. ex. quand il est terminé",+ "field_status": "Statut",+ "field_assignee": "Responsable",+ "field_label": "Libellé",+ "field_property": "Propriété",+ "field_kind": "Champ",+ "choose_status": "Choisir un statut",+ "choose_assignee": "Choisir un responsable",+ "choose_label": "Choisir un libellé",+ "choose_property": "Choisir une propriété",+ "value_placeholder": "Valeur",+ "squads": "Équipes",+ "children_all": "Toutes les sous-tâches",+ "children_stage": "Étape {{stage}}",+ "pr_checks": "Fin de la CI",+ "pr_merged": "Fusion",+ "choose_issue": "Choisir une tâche",+ "pick_issue_title": "Suivre une tâche",+ "pick_issue_description": "Réveille l’agent quand cette tâche atteint l’état choisi.",+ "other_done": "est terminée",+ "other_ended": "est terminée ou annulée",+ "other_in_review": "passe en revue",+ "max_fires": "Au plus",+ "max_fires_times_one": "{{count}} fois",+ "max_fires_times_other": "{{count}} fois",+ "missing_value": "Choisissez une valeur.",+ "missing_issue": "Choisissez une tâche.",+ "checked": "Cochée",+ "unchecked": "Décochée",+ "assignee_comment_hint": "{{name}} est le responsable et s’exécute déjà quand un membre commente. Cette règle rejoint cette exécution au lieu d’en lancer une autre ; ajoutez-la seulement pour lui donner une instruction de plus."+ },+ "system": {+ "badge": "Système",+ "title_stage": "Quand les sous-tâches de l’étape {{stage}} sont toutes terminées",+ "title_all": "Quand toutes les sous-tâches sont terminées",+ "wake_assignee": "Réveiller le responsable {{name}}",+ "remaining_one": "encore {{count}}",+ "remaining_other": "encore {{count}}",+ "blocked_backlog": "Tâche en backlog ; pas de réveil pour l’instant",+ "blocked_member": "Responsable humain ; il reçoit une notification",+ "blocked_none": "Aucun agent responsable ; personne n’est réveillé",+ "turned_off": "Désactivé pour cette tâche",+ "target_title": "Réveille",+ "target_current": "Responsable (actuellement {{name}})",+ "target_none": "Le responsable : un agent ou une équipe est réveillé, un humain est notifié",+ "progress_title": "Avancement",+ "progress": "{{done}}/{{total}} terminés",+ "waiting_on": "en attente de {{ids}}",+ "skip_title": "Ignoré quand",+ "skip": "La tâche est en backlog ; rattrapé à sa sortie du backlog",+ "source": "Règle système · active pour les tâches avec sous-tâches",+ "enable": "Activé pour cette tâche",+ "toggle": "Réveiller le responsable à la fin des sous-tâches",+ "save_error": "Impossible d’enregistrer la règle système.",+ "default_on": "Activé par défaut dans cet espace. Modifiez la valeur par défaut dans Paramètres → Réveils.",+ "default_off": "Désactivé par défaut dans cet espace. Modifiez la valeur par défaut dans Paramètres → Réveils.",+ "notify_member": "Notifier {{name}} dans sa boîte de réception",+ "instruction": "Que faire au réveil",+ "instruction_edit": "Modifier l’instruction",+ "instruction_default": "Non définie sur cette tâche ; instruction par défaut :",+ "instruction_placeholder": "Laisser vide pour l’instruction par défaut",+ "instruction_invalid": "Limitez l’instruction à 4 000 octets.",+ "paused": "En pause : {{reason}}"+ },+ "cond": {+ "status": "Quand cette tâche passe à {{status}}",+ "assignee": "Quand cette tâche est attribuée à {{name}}",+ "label": "Quand cette tâche reçoit le libellé {{label}}",+ "property": "Quand {{property}} vaut {{value}}",+ "children_all": "Quand toutes les sous-tâches sont terminées",+ "children_stage": "Quand les sous-tâches de l’étape {{stage}} sont terminées",+ "pr_checks": "Quand la CI d’une PR liée se termine",+ "pr_merged": "Quand une PR liée est fusionnée",+ "other_done": "Quand {{issue}} est terminée",+ "other_ended": "Quand {{issue}} est terminée ou annulée",+ "other_in_review": "Quand {{issue}} passe en revue",+ "another_issue": "une autre tâche",+ "unknown_label": "un libellé supprimé",+ "unknown_property": "une propriété supprimée",+ "checked": "cochée",+ "unchecked": "décochée"+ },+ "wait": {+ "reply_from": "Attend la réponse de {{name}}",+ "reply_any": "Attend une réponse",+ "run_end": "Attend la fin de l’exécution de {{agent}}",+ "run_end_any": "Attend la fin d’une exécution",+ "status": "Attend le statut {{status}}",+ "assignee": "Attend l’attribution à {{name}}",+ "label": "Attend le libellé {{label}}",+ "property": "Attend {{property}} = {{value}}",+ "children_all": "Attend les sous-tâches",+ "children_stage": "Attend l’étape {{stage}}",+ "pr_checks": "Attend la CI",+ "pr_merged": "Attend la fusion de la PR",+ "other_done": "Attend {{issue}}",+ "other_ended": "Attend la fin de {{issue}}",+ "other_in_review": "Attend la revue de {{issue}}",+ "time": "{{time}} · réveille {{agent}}",+ "header": "{{agent}} : {{what}}",+ "paused": "Réveil en pause",+ "open": "Voir les réveils"+ },+ "paused": {+ "max_fires": "Arrêté après {{count}} exécutions",+ "loop": "En pause : il réveillait des règles qui le réveillaient à leur tour",+ "rate": "En pause : plus de 12 exécutions en une heure",+ "hint": "Réactivez-le pour reprendre ; le compteur repart de zéro."+ },+ "detail": {+ "fires_one": "Déclenché {{count}} fois",+ "fires_other": "Déclenché {{count}} fois",+ "fires_max": "Déclenché {{count}} fois sur {{max}} au plus",+ "history_title": "Historique",+ "history_empty": "Pas encore déclenché",+ "history_error": "Impossible de charger l’historique",+ "run_checkin": "Vérification silencieuse",+ "run_commented": "{{state}} · a commenté",+ "wake_now": "Réveiller maintenant",+ "wake_now_done": "{{agent}} va s’exécuter sous peu",+ "wake_now_error": "Impossible de réveiller l’agent",+ "delete": "Supprimer",+ "delete_title": "Supprimer ce réveil ?",+ "delete_body": "{{agent}} ne sera plus réveillé, et ses exécutions non démarrées sont retirées. Une exécution déjà lancée continue.",+ "deleting": "Suppression…",+ "delete_error": "Impossible de supprimer le réveil"+ },+ "paused_reason": {+ "max_fires": "limite de {{count}} exécutions atteinte",+ "loop": "il réveillait des règles qui le réveillaient à leur tour",+ "rate": "plus de 12 exécutions en une heure"+ }},"duplicates": {"banner_prefix": "Doublon de",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex bc76570bbf..7659b9c036 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -81,6 +81,24 @@"pr_auto_complete_badge": "Définie à la fusion des PR","built_in_locked": "Les états intégrés pilotent le comportement du système : ils ne peuvent être ni modifiés ni archivés, mais vous pouvez les réordonner."},+ "wakeups": {+ "description": "Règles de la plateforme appliquées à chaque tâche. Chaque tâche peut les modifier dans sa section Réveils.",+ "child_done_title": "À la fin des sous-tâches",+ "child_done_description": "Réveille le responsable de la tâche parente quand une étape se termine alors qu’une étape suivante attend, puis une fois de plus quand toutes les sous-tâches sont fermées. Un responsable humain reçoit une notification à la place.",+ "enabled": "Activé par défaut",+ "instruction": "Instruction par défaut",+ "instruction_hint": "Envoyée à l’agent réveillé. Laissez vide pour utiliser l’instruction intégrée ci-dessous.",+ "instruction_placeholder": "Laisser vide pour l’instruction intégrée",+ "builtin": "Instruction intégrée",+ "instruction_invalid": "Limitez l’instruction à 4 000 octets.",+ "save": "Enregistrer",+ "saving": "Enregistrement…",+ "save_error": "Impossible d’enregistrer la valeur par défaut.",+ "customized_one": "{{count}} tâche ouverte a son propre réglage et ignore cette valeur par défaut.",+ "customized_other": "{{count}} tâches ouvertes ont leur propre réglage et ignorent cette valeur par défaut.",+ "admin_only": "Seuls les propriétaires et administrateurs peuvent modifier ces valeurs.",+ "load_error": "Impossible de charger les valeurs par défaut des réveils."+ },"quick_actions": {"title": "Actions rapides","description": "Lancez un agent et un prompt prédéfinis depuis la barre latérale d’une tâche.",@@ -379,6 +397,7 @@"members": "Membres","labels": "Étiquettes","issue_statuses": "États des tâches",+ "wakeups": "Réveils","properties": "Propriétés","quick_actions": "Actions rapides","plugins": "Plugins",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex daa62c718d..f4d31a5465 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -789,7 +789,8 @@"tool_kind_command": "コマンド","tool_kind_write": "編集","tool_kind_read": "読み取り",- "tool_kind_misc": "その他"+ "tool_kind_misc": "その他",+ "trigger_wakeup": "起動"},"task_failure": {"cancelled_by_system": "システムによってキャンセルされました",diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.jsonindex 62e1365a00..4c577a0520 100644--- a/packages/views/locales/ja/autopilots.json+++ b/packages/views/locales/ja/autopilots.json@@ -476,7 +476,6 @@"scope": "範囲","issue": "タスク","trigger": "トリガー",- "next": "ウェイクアップ状態","enabled": "有効","all_triggers": "すべてのトリガー","event": "イベント",@@ -484,7 +483,6 @@"recurring": "繰り返し","all_agents": "すべてのエージェント","search": "タスク・エージェントを検索",- "search_action": "検索","running": "実行中","active_runs": "{{count}} 件の実行が進行中","issue_closed": "タスクは終了済み",@@ -510,13 +508,31 @@"active": "起動待ち・実行中","all": "すべて","disabled": "無効",- "ended": "終了"+ "ended": "終了",+ "paused": "一時停止中"},"target_agent": "起動するエージェント",- "wakeup_run": "起動後の実行","empty_filtered": "一致するルールがありません","clear_filters": "フィルターを解除","batch_success": "{{count}} 件のルールを無効化しました",- "batch_partial": "{{succeeded}} 件を無効化、{{failed}} 件が失敗しました。失敗した項目を選択したまま再試行できます。"+ "batch_partial": "{{succeeded}} 件を無効化、{{failed}} 件が失敗しました。失敗した項目を選択したまま再試行できます。",+ "source": "作成元",+ "sources": {+ "all": "作成元:すべて",+ "member": "メンバー",+ "agent": "エージェント",+ "system": "システム"+ },+ "runs_7d": "直近 7 日の実行",+ "ends": "期限",+ "until_issue_ends": "タスク終了まで",+ "fires_once": "一度だけ起動",+ "assignee_target": "担当者 · {{name}}",+ "no_target": "エージェントの担当者なし",+ "banner_other": "{{count}} 件の起動が自動で一時停止しました:{{issue}}「{{condition}}」— {{reason}}",+ "banner_view": "表示",+ "create": "起動を追加",+ "create_pick_issue": "起動を追加するタスクを選択",+ "create_pick_issue_description": "起動はこのタスクに属し、タスクの終了とともに終わります。"}}diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex 16c404e698..e5b00c829c 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -78,6 +78,7 @@"quick_create_failed": "エージェントでの作成に失敗","quick_create_unconfirmed": "エージェントでの作成結果は未確認","autopilot_paused": "自動化を一時停止しました",+ "children_done": "サブタスクがすべて終わりました","autopilot_quota_exceeded": "自動化の実行上限に達しました"},"labels": {@@ -92,7 +93,8 @@"reacted_to_comment": "あなたのコメントに {{emoji}} のリアクションをしました","created_with_agent": "エージェントで作成: {{identifier}}","failed_with_detail": "失敗: {{detail}}",- "autopilot_quota_blocked": "上限に達したため実行をブロックしました"+ "autopilot_quota_blocked": "上限に達したため実行をブロックしました",+ "children_done_stage": "ステージ {{stage}} のサブタスクがすべて終わりました"},"toasts": {"source_context_retry_started": "元のコンテキストで再試行を開始しました",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex f974f65156..e6598b4e31 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -515,7 +515,25 @@"duplicate_removed": "{{identifier}} の重複マークを解除しました","status_changed_pr": "関連するすべての PR がマージされたため({{prs}})、ステータスを {{from}} から {{to}} に変更しました","pr_auto_complete_disabled": "このタスクを PR マージでステータスを変えないように設定しました",- "pr_auto_complete_enabled": "このタスクの PR マージ後のステータス変更を再開しました"+ "pr_auto_complete_enabled": "このタスクの PR マージ後のステータス変更を再開しました",+ "wakeup_created": "起動を追加しました:{{condition}} · {{agent}} を起こす",+ "wakeup_triggered": "{{condition}} · {{agent}} を起こしました",+ "wakeup_triggered_merged": "{{condition}}({{agent}} の開始待ちの実行に合流しました)",+ "wakeup_triggered_acknowledged": "{{condition}}({{agent}} 自身の操作のため、再度は起こしていません)",+ "wakeup_triggered_manual": "{{name}} が {{agent}} を今すぐ起こしました",+ "wakeup_child_done_stage_other": "ステージ {{stage}} の {{count}} 件のサブタスクがすべて終わりました",+ "wakeup_child_done_all_other": "{{count}} 件のサブタスクがすべて終わりました",+ "wakeup_child_done_woke": "({{name}} を起こしました)",+ "wakeup_child_done_notified": "({{name}} に通知しました)",+ "wakeup_child_done_merged": "({{name}} の開始待ちの実行に合流しました)",+ "wakeup_child_done_acknowledged": "({{name}} が対応中のため、再度は起こしていません)",+ "wakeup_assignee": "担当者",+ "wakeup_timed_out_wake": "期限までに起きませんでした({{condition}})· {{agent}} を起こして対応させました",+ "wakeup_timed_out_end": "期限で起動が終了しました:{{condition}}",+ "wakeup_checkin": "サイレントチェック:{{note}}",+ "wakeup_checkin_coalesced_other": "サイレントチェック {{count}} 回 · 最新:{{note}}",+ "wakeup_chip_created_by": "{{name}} が作成",+ "wakeup_chip_system": "システムルール"},"comment": {"add_reaction": "リアクションを追加",@@ -704,7 +722,8 @@"source_backfill": "バックフィルされた帰属","source_unattributed": "責任メンバーを解決できません"},- "usage_total_tooltip": "このタスクのトークン使用量 — クリックで実行ごとの内訳"+ "usage_total_tooltip": "このタスクのトークン使用量 — クリックで実行ごとの内訳",+ "trigger_wakeup": "起動 · {{condition}}"},"usage_detail": {"title": "使用量の内訳",@@ -965,7 +984,7 @@"disable": "{{agent}} のウェイクアップを停止","disable_error": "停止できませんでした","source_run": "監視対象の実行",- "source_agent": "監視対象のエージェント",+ "source_agent": "{{agent}} が作成({{name}} の代理)","next": "次回:","last_run": "実行記録を見る","run_completed": "実行完了",@@ -1076,7 +1095,9 @@"triggered": "起動済み","expired": "期限切れ","inactive": "未有効化",- "issue_closed": "タスク終了により無効"+ "issue_closed": "タスク終了により無効",+ "timed_out": "タイムアウト",+ "paused": "自動で一時停止"},"run_states": {"queued": "キュー待ち",@@ -1089,7 +1110,209 @@"cancelled": "キャンセル済み"},"hourly": "毎時起動",- "today_time": "今日 {{time}}"+ "today_time": "今日 {{time}}",+ "remaining_days": "残り {{days}} 日",+ "remaining_days_hours": "残り {{days}} 日 {{hours}} 時間",+ "remaining_hours": "残り {{hours}} 時間",+ "remaining_minutes": "残り {{minutes}} 分",+ "until_date": "{{date}} まで",+ "source_title": "作成者",+ "source_member": "{{name}} が作成",+ "source_agent_unknown": "エージェント",+ "expiry_title": "期限",+ "expiry_at": "{{time}} に終了",+ "expiry_timed_out": "{{time}} にタイムアウト",+ "timeout_then_wake": "期限後に {{agent}} を起こして対応",+ "timeout_then_end": "期限後はそのまま終了",+ "create": {+ "open": "新しいウェイクアップ",+ "title": "新しいウェイクアップ",+ "when": "条件",+ "wake": "起こす",+ "choose_condition": "条件を選択",+ "choose_agent": "エージェントを選択",+ "group_time": "時間",+ "group_collaboration": "コラボレーション",+ "group_runs": "実行とサブタスク",+ "cond_at": "指定した時刻",+ "cond_at_hint": "10 分後、明日 09:00",+ "cond_recurring": "定期チェック",+ "cond_recurring_hint": "毎時・毎日、終了日を設定",+ "cond_reply": "誰かが返信",+ "cond_reply_hint": "誰でも、または特定の人",+ "cond_run_end": "エージェントの実行が終了",+ "cond_run_end_hint": "成功・失敗・キャンセル",+ "cond_custom": "カスタムイベント…",+ "cond_custom_hint": "{{count}} 種類の元イベント",+ "at_10m": "10 分後",+ "at_1h": "1 時間後",+ "at_tomorrow": "明日 09:00",+ "at_custom": "時刻を指定",+ "hourly": "毎時",+ "daily": "毎日 09:00",+ "weekdays": "平日 09:00",+ "until": "終了日",+ "anyone": "誰でも",+ "members": "メンバー",+ "agents": "エージェント",+ "any_agent": "任意のエージェント",+ "events_selected": "{{count}} 件のイベント",+ "instruction_placeholder": "例:結果を確認し、問題なければ次へ進む",+ "trigger_count": "トリガー回数",+ "max_wait": "最大待機",+ "wait_days_other": "{{count}} 日",+ "on_timeout": "期限後",+ "timeout_wake": "{{agent}} を起こして対応",+ "timeout_end": "そのまま終了",+ "the_agent": "エージェント",+ "on_behalf": "起動された実行はあなたの代理として動きます",+ "submit": "作成",+ "submitting": "作成中…",+ "cancel": "キャンセル",+ "error": "ウェイクアップを作成できませんでした。設定を確認して再試行してください。",+ "capacity_error": "このタスクまたはワークスペースの有効なウェイクアップは上限に達しています。",+ "missing_condition": "条件を選択してください。",+ "missing_agent": "起こすエージェントを選択してください。",+ "missing_events": "イベントを 1 つ以上選択してください。",+ "until_future": "終了日は今日より後にしてください。",+ "closed": "完了またはキャンセルされたタスクには作成できません。",+ "group_linked": "関連",+ "cond_field": "フィールドが特定の値になる",+ "cond_field_hint": "ステータス、担当者、ラベル、プロパティ",+ "cond_children": "サブタスクが終わる",+ "cond_children_hint": "すべて、または 1 ステージ",+ "cond_pr": "関連 PR の CI が終わる",+ "cond_pr_hint": "マージも選べます",+ "cond_issue": "別のタスクのステータス",+ "cond_issue_hint": "例:完了したとき",+ "field_status": "ステータス",+ "field_assignee": "担当者",+ "field_label": "ラベル",+ "field_property": "プロパティ",+ "field_kind": "フィールド",+ "choose_status": "ステータスを選択",+ "choose_assignee": "担当者を選択",+ "choose_label": "ラベルを選択",+ "choose_property": "プロパティを選択",+ "value_placeholder": "値",+ "squads": "スクワッド",+ "children_all": "すべてのサブタスク",+ "children_stage": "ステージ {{stage}}",+ "pr_checks": "CI 終了",+ "pr_merged": "マージ",+ "choose_issue": "タスクを選択",+ "pick_issue_title": "見守るタスク",+ "pick_issue_description": "このタスクが選んだ状態になったらエージェントを起こします。",+ "other_done": "完了",+ "other_ended": "完了またはキャンセル",+ "other_in_review": "レビュー中になる",+ "max_fires": "最大",+ "max_fires_times_other": "{{count}} 回",+ "missing_value": "値を選択してください。",+ "missing_issue": "タスクを選択してください。",+ "checked": "オン",+ "unchecked": "オフ",+ "assignee_comment_hint": "{{name}} は担当者のため、メンバーのコメントですでに起きます。このルールはその実行に合流し、別の実行は始めません。追加の指示を渡したいときだけ使ってください。"+ },+ "system": {+ "badge": "システム",+ "title_stage": "ステージ {{stage}} のサブタスクがすべて終わったとき",+ "title_all": "サブタスクがすべて終わったとき",+ "wake_assignee": "担当者 {{name}} を起こす",+ "remaining_other": "残り {{count}} 件",+ "blocked_backlog": "バックログ中のため起こしません",+ "blocked_member": "担当者がメンバーのため、受信トレイに通知します",+ "blocked_none": "エージェントの担当者がいないため起こしません",+ "turned_off": "このタスクではオフ",+ "target_title": "起こす対象",+ "target_current": "担当者(現在 {{name}})",+ "target_none": "担当者:エージェントやスクワッドは起こし、メンバーには通知します",+ "progress_title": "進捗",+ "progress": "{{done}}/{{total}} 完了",+ "waiting_on": "残り {{ids}}",+ "skip_title": "発火しない場合",+ "skip": "タスクがバックログ中。外れたときに一度だけ補います",+ "source": "システムルール · サブタスクがあると有効",+ "enable": "このタスクで有効",+ "toggle": "サブタスク完了時に担当者を起こす",+ "save_error": "システムルールを保存できませんでした。",+ "default_on": "ワークスペースでは既定でオン。既定値は「設定 → ウェイクアップ」で変更できます。",+ "default_off": "ワークスペースでは既定でオフ。既定値は「設定 → ウェイクアップ」で変更できます。",+ "notify_member": "{{name}} に受信トレイで通知",+ "instruction": "起きたあとにすること",+ "instruction_edit": "指示を編集",+ "instruction_default": "このタスクでは未設定のため、既定の指示を使います:",+ "instruction_placeholder": "空欄のままなら既定の指示を使います",+ "instruction_invalid": "指示は 4,000 バイト以内にしてください。",+ "paused": "一時停止中:{{reason}}"+ },+ "cond": {+ "status": "ステータスが{{status}}になったとき",+ "assignee": "担当者が {{name}} になったとき",+ "label": "ラベル {{label}} が付いたとき",+ "property": "{{property}} が {{value}} になったとき",+ "children_all": "サブタスクがすべて終わったとき",+ "children_stage": "ステージ {{stage}} のサブタスクがすべて終わったとき",+ "pr_checks": "関連 PR の CI が終わったとき",+ "pr_merged": "関連 PR がマージされたとき",+ "other_done": "{{issue}} が完了したとき",+ "other_ended": "{{issue}} が完了またはキャンセルされたとき",+ "other_in_review": "{{issue}} がレビュー中になったとき",+ "another_issue": "別のタスク",+ "unknown_label": "削除されたラベル",+ "unknown_property": "削除されたプロパティ",+ "checked": "オン",+ "unchecked": "オフ"+ },+ "wait": {+ "reply_from": "{{name}} の返信待ち",+ "reply_any": "返信待ち",+ "run_end": "{{agent}} の実行終了待ち",+ "run_end_any": "実行終了待ち",+ "status": "{{status}} 待ち",+ "assignee": "担当者 {{name}} 待ち",+ "label": "ラベル {{label}} 待ち",+ "property": "{{property}} = {{value}} 待ち",+ "children_all": "サブタスク待ち",+ "children_stage": "ステージ {{stage}} 待ち",+ "pr_checks": "CI 待ち",+ "pr_merged": "PR のマージ待ち",+ "other_done": "{{issue}} の完了待ち",+ "other_ended": "{{issue}} の終了待ち",+ "other_in_review": "{{issue}} のレビュー待ち",+ "time": "{{time}} に {{agent}} を起こす",+ "header": "{{agent}}:{{what}}",+ "paused": "起動を一時停止中",+ "open": "起動を表示"+ },+ "paused": {+ "max_fires": "{{count}} 回起動して上限に達したため停止",+ "loop": "一時停止:別のルールと互いに起こし合っていました",+ "rate": "一時停止:1 時間に 12 回を超えて起動",+ "hint": "オンに戻すと再開し、回数はリセットされます。"+ },+ "detail": {+ "fires_other": "{{count}} 回起動",+ "fires_max": "{{count}} 回起動(最大 {{max}} 回)",+ "history_title": "起動履歴",+ "history_empty": "まだ起動していません",+ "history_error": "履歴を読み込めませんでした",+ "run_checkin": "サイレントチェック",+ "run_commented": "{{state}} · コメントあり",+ "wake_now": "今すぐ起こす",+ "wake_now_done": "{{agent}} をまもなく起動します",+ "wake_now_error": "起こせませんでした",+ "delete": "削除",+ "delete_title": "この起動を削除しますか?",+ "delete_body": "{{agent}} は起こされなくなり、未開始の実行は取り消されます。開始済みの実行は続きます。",+ "deleting": "削除中…",+ "delete_error": "削除できませんでした"+ },+ "paused_reason": {+ "max_fires": "上限の {{count}} 回に到達",+ "loop": "別のルールと互いに起こし合っていました",+ "rate": "1 時間に 12 回を超えて起動"+ }},"duplicates": {"banner_prefix": "重複元:",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 1580efbfc7..09f9af4ed4 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -81,6 +81,23 @@"pr_auto_complete_badge": "PR のマージで自動設定","built_in_locked": "組み込みステータスはシステムの動作に使われるため、編集やアーカイブはできません。並び順は変更できます。"},+ "wakeups": {+ "description": "すべてのタスクに適用されるプラットフォームのルールです。各タスクの「ウェイクアップ」セクションで個別に変更できます。",+ "child_done_title": "サブタスクが終わったとき",+ "child_done_description": "あるステージが終わり、後のステージが待っているときに親タスクの担当者を起こし、すべてのサブタスクが終わったときにもう一度起こします。担当者がメンバーの場合は受信トレイに通知します。",+ "enabled": "既定でオン",+ "instruction": "既定の指示",+ "instruction_hint": "起こしたエージェントに送られます。空欄のままなら下の組み込みの指示を使います。",+ "instruction_placeholder": "空欄なら組み込みの指示を使います",+ "builtin": "組み込みの指示",+ "instruction_invalid": "指示は 4,000 バイト以内にしてください。",+ "save": "保存",+ "saving": "保存中…",+ "save_error": "既定値を保存できませんでした。",+ "customized_other": "進行中の {{count}} 件のタスクが個別の設定を使っており、この既定値に従いません。",+ "admin_only": "既定値を変更できるのはオーナーと管理者だけです。",+ "load_error": "ウェイクアップの既定値を読み込めませんでした。"+ },"quick_actions": {"title": "クイックアクション","description": "タスクのサイドバーから、設定済みのエージェントとプロンプトを実行します。",@@ -379,6 +396,7 @@"members": "メンバー","labels": "ラベル","issue_statuses": "タスクステータス",+ "wakeups": "ウェイクアップ","properties": "プロパティ","quick_actions": "クイックアクション","plugins": "プラグイン",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex 2a206c585d..ddbc3087c7 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -797,7 +797,8 @@"tool_kind_command": "명령","tool_kind_write": "편집","tool_kind_read": "읽기",- "tool_kind_misc": "기타"+ "tool_kind_misc": "기타",+ "trigger_wakeup": "깨우기"},"task_failure": {"cancelled_by_system": "시스템에서 취소함",diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.jsonindex 006c7014c5..2d683371ad 100644--- a/packages/views/locales/ko/autopilots.json+++ b/packages/views/locales/ko/autopilots.json@@ -476,7 +476,6 @@"scope": "범위","issue": "작업","trigger": "트리거",- "next": "깨우기 상태","enabled": "활성화","all_triggers": "모든 트리거","event": "이벤트",@@ -484,7 +483,6 @@"recurring": "반복","all_agents": "모든 에이전트","search": "작업 또는 에이전트 검색",- "search_action": "검색","running": "실행 중","active_runs": "진행 중인 실행 {{count}}개","issue_closed": "종료된 작업",@@ -510,13 +508,31 @@"active": "깨우기 대기 또는 실행 중","all": "전체","disabled": "꺼짐",- "ended": "종료됨"+ "ended": "종료됨",+ "paused": "일시중지됨"},"target_agent": "깨울 에이전트",- "wakeup_run": "깨운 후 실행","empty_filtered": "일치하는 깨우기가 없습니다","clear_filters": "필터 지우기","batch_success": "깨우기 규칙 {{count}}개를 껐습니다",- "batch_partial": "{{succeeded}}개를 껐고 {{failed}}개는 실패했습니다. 실패 항목은 선택된 상태로 남아 다시 시도할 수 있습니다."+ "batch_partial": "{{succeeded}}개를 껐고 {{failed}}개는 실패했습니다. 실패 항목은 선택된 상태로 남아 다시 시도할 수 있습니다.",+ "source": "만든 곳",+ "sources": {+ "all": "만든 곳: 전체",+ "member": "멤버",+ "agent": "에이전트",+ "system": "시스템"+ },+ "runs_7d": "최근 7일 실행",+ "ends": "종료",+ "until_issue_ends": "태스크 종료 시까지",+ "fires_once": "한 번 실행",+ "assignee_target": "담당자 · {{name}}",+ "no_target": "에이전트 담당자 없음",+ "banner_other": "깨우기 {{count}}개가 자동으로 일시중지됨: {{issue}} “{{condition}}” — {{reason}}",+ "banner_view": "보기",+ "create": "깨우기 추가",+ "create_pick_issue": "깨우기를 추가할 태스크 선택",+ "create_pick_issue_description": "깨우기는 이 태스크에 속하며 태스크가 끝나면 함께 끝납니다."}}diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex 1a706a846c..1a23d044b3 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -78,6 +78,7 @@"quick_create_failed": "에이전트 생성 실패","quick_create_unconfirmed": "에이전트 생성 결과 미확인","autopilot_paused": "자동화 일시 중지됨",+ "children_done": "하위 태스크가 모두 끝났습니다","autopilot_quota_exceeded": "자동화 실행 한도 도달"},"labels": {@@ -92,7 +93,8 @@"reacted_to_comment": "내 댓글에 {{emoji}} 반응을 남겼습니다","created_with_agent": "에이전트가 생성: {{identifier}}","failed_with_detail": "실패: {{detail}}",- "autopilot_quota_blocked": "한도에 도달하여 실행이 차단됨"+ "autopilot_quota_blocked": "한도에 도달하여 실행이 차단됨",+ "children_done_stage": "{{stage}}단계 하위 태스크가 모두 끝났습니다"},"toasts": {"source_context_retry_started": "원본 컨텍스트로 재시도를 시작했습니다",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 40e917938d..adcf98d0de 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -515,7 +515,25 @@"duplicate_removed": "{{identifier}}의 중복 표시를 해제했습니다","status_changed_pr": "연결된 PR이 모두 병합되어({{prs}}) 상태를 {{from}}에서 {{to}}로 변경했습니다","pr_auto_complete_disabled": "이 태스크가 PR 병합 시 상태를 유지하도록 설정했습니다",- "pr_auto_complete_enabled": "이 태스크의 PR 병합 후 상태 변경을 다시 켰습니다"+ "pr_auto_complete_enabled": "이 태스크의 PR 병합 후 상태 변경을 다시 켰습니다",+ "wakeup_created": "깨우기를 추가했습니다: {{condition}} · {{agent}} 깨우기",+ "wakeup_triggered": "{{condition}} · {{agent}}을(를) 깨웠습니다",+ "wakeup_triggered_merged": "{{condition}} · {{agent}}의 대기 중인 실행에 합쳤습니다",+ "wakeup_triggered_acknowledged": "{{condition}} · {{agent}} 자신의 작업이라 다시 깨우지 않았습니다",+ "wakeup_triggered_manual": "{{name}}이(가) {{agent}}을(를) 바로 깨웠습니다",+ "wakeup_child_done_stage_other": "{{stage}}단계 하위 태스크 {{count}}개가 모두 끝났습니다",+ "wakeup_child_done_all_other": "하위 태스크 {{count}}개가 모두 끝났습니다",+ "wakeup_child_done_woke": " · {{name}}을(를) 깨웠습니다",+ "wakeup_child_done_notified": " · {{name}}에게 알렸습니다",+ "wakeup_child_done_merged": " · {{name}}의 대기 중인 실행에 합쳤습니다",+ "wakeup_child_done_acknowledged": " · {{name}}이(가) 이미 처리 중이라 다시 깨우지 않았습니다",+ "wakeup_assignee": "담당자",+ "wakeup_timed_out_wake": "기한 내에 일어나지 않음({{condition}}) · {{agent}}을(를) 깨워 처리하게 했습니다",+ "wakeup_timed_out_end": "기한이 되어 깨우기가 종료됨: {{condition}}",+ "wakeup_checkin": "조용한 확인: {{note}}",+ "wakeup_checkin_coalesced_other": "조용한 확인 {{count}}회 · 최근: {{note}}",+ "wakeup_chip_created_by": "{{name}} 생성",+ "wakeup_chip_system": "시스템 규칙"},"comment": {"add_reaction": "반응 추가",@@ -704,7 +722,8 @@"source_backfill": "백필된 귀속","source_unattributed": "책임 멤버를 확인할 수 없음"},- "usage_total_tooltip": "이 태스크의 토큰 사용량 — 클릭하면 실행별 내역"+ "usage_total_tooltip": "이 태스크의 토큰 사용량 — 클릭하면 실행별 내역",+ "trigger_wakeup": "깨우기 · {{condition}}"},"usage_detail": {"title": "사용량 내역",@@ -965,7 +984,7 @@"disable": "{{agent}} 깨우기 끄기","disable_error": "깨우기를 끌 수 없습니다","source_run": "감시할 실행",- "source_agent": "감시할 에이전트",+ "source_agent": "{{agent}} 생성 ({{name}} 대리)","next": "다음:","last_run": "실행 기록 보기","run_completed": "실행 완료",@@ -1009,7 +1028,7 @@"reschedule": "시간 다시 설정","future_time": "미래 시간을 선택하세요.","local_time": "시간 ({{timezone}})",- "closed_hint": "이슈가 완료되거나 취소되어 활성화할 수 없습니다.",+ "closed_hint": "태스크가 완료되거나 취소되어 활성화할 수 없습니다.","completed": "완료됨","expired": "만료됨","disabled_state": "꺼짐",@@ -1076,7 +1095,9 @@"triggered": "트리거됨","expired": "만료됨","inactive": "비활성",- "issue_closed": "작업 종료로 깨우기 중지됨"+ "issue_closed": "작업 종료로 깨우기 중지됨",+ "timed_out": "시간 초과",+ "paused": "자동으로 일시중지됨"},"run_states": {"queued": "대기열에 있음",@@ -1089,7 +1110,209 @@"cancelled": "취소됨"},"hourly": "매시간 깨우기",- "today_time": "오늘 {{time}}"+ "today_time": "오늘 {{time}}",+ "remaining_days": "{{days}}일 남음",+ "remaining_days_hours": "{{days}}일 {{hours}}시간 남음",+ "remaining_hours": "{{hours}}시간 남음",+ "remaining_minutes": "{{minutes}}분 남음",+ "until_date": "{{date}}까지",+ "source_title": "만든 사람",+ "source_member": "{{name}} 생성",+ "source_agent_unknown": "에이전트",+ "expiry_title": "종료",+ "expiry_at": "{{time}}에 종료",+ "expiry_timed_out": "{{time}}에 시간 초과",+ "timeout_then_wake": "시간 초과 시 {{agent}}를 깨워 처리",+ "timeout_then_end": "시간 초과 시 그대로 종료",+ "create": {+ "open": "새 웨이크업",+ "title": "새 웨이크업",+ "when": "조건",+ "wake": "깨울 대상",+ "choose_condition": "조건 선택",+ "choose_agent": "에이전트 선택",+ "group_time": "시간",+ "group_collaboration": "협업",+ "group_runs": "실행과 하위 태스크",+ "cond_at": "특정 시각",+ "cond_at_hint": "10분 후, 내일 09:00",+ "cond_recurring": "정기 확인",+ "cond_recurring_hint": "매시간·매일, 종료일 필요",+ "cond_reply": "누군가 답글",+ "cond_reply_hint": "누구나 또는 특정인",+ "cond_run_end": "에이전트 실행 종료",+ "cond_run_end_hint": "성공, 실패 또는 취소",+ "cond_custom": "사용자 지정 이벤트…",+ "cond_custom_hint": "원시 이벤트 {{count}}종",+ "at_10m": "10분 후",+ "at_1h": "1시간 후",+ "at_tomorrow": "내일 09:00",+ "at_custom": "시간 지정",+ "hourly": "매시간",+ "daily": "매일 09:00",+ "weekdays": "평일 09:00",+ "until": "종료일",+ "anyone": "누구나",+ "members": "멤버",+ "agents": "에이전트",+ "any_agent": "모든 에이전트",+ "events_selected": "이벤트 {{count}}개",+ "instruction_placeholder": "예: 결과를 확인하고 문제없으면 다음 단계로 진행",+ "trigger_count": "트리거 횟수",+ "max_wait": "최대 대기",+ "wait_days_other": "{{count}}일",+ "on_timeout": "시간 초과 시",+ "timeout_wake": "{{agent}}를 깨워 처리",+ "timeout_end": "그대로 종료",+ "the_agent": "에이전트",+ "on_behalf": "시작된 실행은 사용자를 대신해 동작합니다",+ "submit": "만들기",+ "submitting": "만드는 중…",+ "cancel": "취소",+ "error": "웨이크업을 만들 수 없습니다. 설정을 확인하고 다시 시도하세요.",+ "capacity_error": "이 태스크 또는 워크스페이스의 활성 웨이크업이 한도에 도달했습니다.",+ "missing_condition": "조건을 선택하세요.",+ "missing_agent": "깨울 에이전트를 선택하세요.",+ "missing_events": "이벤트를 하나 이상 선택하세요.",+ "until_future": "종료일은 오늘 이후여야 합니다.",+ "closed": "완료되었거나 취소된 태스크에는 만들 수 없습니다.",+ "group_linked": "연결",+ "cond_field": "필드가 특정 값으로 바뀜",+ "cond_field_hint": "상태, 담당자, 레이블, 속성",+ "cond_children": "하위 태스크 완료",+ "cond_children_hint": "전체 또는 한 단계",+ "cond_pr": "연결된 PR의 CI 종료",+ "cond_pr_hint": "병합도 선택 가능",+ "cond_issue": "다른 태스크의 상태",+ "cond_issue_hint": "예: 완료되면",+ "field_status": "상태",+ "field_assignee": "담당자",+ "field_label": "레이블",+ "field_property": "속성",+ "field_kind": "필드",+ "choose_status": "상태 선택",+ "choose_assignee": "담당자 선택",+ "choose_label": "레이블 선택",+ "choose_property": "속성 선택",+ "value_placeholder": "값",+ "squads": "스쿼드",+ "children_all": "모든 하위 태스크",+ "children_stage": "{{stage}}단계",+ "pr_checks": "CI 종료",+ "pr_merged": "병합",+ "choose_issue": "태스크 선택",+ "pick_issue_title": "지켜볼 태스크",+ "pick_issue_description": "이 태스크가 선택한 상태가 되면 에이전트를 깨웁니다.",+ "other_done": "완료",+ "other_ended": "완료 또는 취소",+ "other_in_review": "검토 중으로 바뀜",+ "max_fires": "최대",+ "max_fires_times_other": "{{count}}회",+ "missing_value": "값을 선택하세요.",+ "missing_issue": "태스크를 선택하세요.",+ "checked": "선택됨",+ "unchecked": "선택 안 됨",+ "assignee_comment_hint": "{{name}}은(는) 담당자라 멤버가 댓글을 달면 이미 실행됩니다. 이 규칙은 그 실행에 합쳐지고 새 실행을 만들지 않습니다. 추가 지시가 필요할 때만 사용하세요."+ },+ "system": {+ "badge": "시스템",+ "title_stage": "{{stage}}단계 하위 태스크가 모두 끝나면",+ "title_all": "하위 태스크가 모두 끝나면",+ "wake_assignee": "담당자 {{name}} 깨우기",+ "remaining_other": "{{count}}개 남음",+ "blocked_backlog": "백로그 상태라 지금은 깨우지 않음",+ "blocked_member": "담당자가 멤버라 받은편지함으로 알립니다",+ "blocked_none": "에이전트 담당자가 없어 깨우지 않음",+ "turned_off": "이 태스크에서 꺼짐",+ "target_title": "깨울 대상",+ "target_current": "담당자 (현재 {{name}})",+ "target_none": "담당자: 에이전트나 스쿼드는 깨우고, 멤버에게는 알립니다",+ "progress_title": "진행",+ "progress": "{{done}}/{{total}} 완료",+ "waiting_on": "남은 항목 {{ids}}",+ "skip_title": "건너뛰는 경우",+ "skip": "태스크가 백로그일 때. 백로그를 벗어나면 한 번 보충합니다",+ "source": "시스템 규칙 · 하위 태스크가 있으면 적용",+ "enable": "이 태스크에서 사용",+ "toggle": "하위 태스크 완료 시 담당자 깨우기",+ "save_error": "시스템 규칙을 저장할 수 없습니다.",+ "default_on": "워크스페이스 기본값은 켜짐입니다. 기본값은 설정 → 깨우기에서 바꿀 수 있습니다.",+ "default_off": "워크스페이스 기본값은 꺼짐입니다. 기본값은 설정 → 깨우기에서 바꿀 수 있습니다.",+ "notify_member": "받은편지함으로 {{name}}에게 알림",+ "instruction": "깨운 뒤 할 일",+ "instruction_edit": "지시 편집",+ "instruction_default": "이 태스크에는 설정되지 않아 기본 지시를 사용합니다:",+ "instruction_placeholder": "비워 두면 기본 지시를 사용합니다",+ "instruction_invalid": "지시는 4,000바이트 이내로 입력하세요.",+ "paused": "일시 중지됨: {{reason}}"+ },+ "cond": {+ "status": "상태가 {{status}}(으)로 바뀌면",+ "assignee": "담당자가 {{name}}(으)로 바뀌면",+ "label": "{{label}} 레이블이 붙으면",+ "property": "{{property}}이(가) {{value}}이면",+ "children_all": "하위 태스크가 모두 끝나면",+ "children_stage": "{{stage}}단계 하위 태스크가 모두 끝나면",+ "pr_checks": "연결된 PR의 CI가 끝나면",+ "pr_merged": "연결된 PR이 병합되면",+ "other_done": "{{issue}}이(가) 완료되면",+ "other_ended": "{{issue}}이(가) 완료되거나 취소되면",+ "other_in_review": "{{issue}}이(가) 검토 중으로 바뀌면",+ "another_issue": "다른 태스크",+ "unknown_label": "삭제된 레이블",+ "unknown_property": "삭제된 속성",+ "checked": "선택됨",+ "unchecked": "선택 안 됨"+ },+ "wait": {+ "reply_from": "{{name}}의 답글 대기",+ "reply_any": "답글 대기",+ "run_end": "{{agent}} 실행 종료 대기",+ "run_end_any": "실행 종료 대기",+ "status": "{{status}} 대기",+ "assignee": "담당자 {{name}} 지정 대기",+ "label": "{{label}} 레이블 대기",+ "property": "{{property}} = {{value}} 대기",+ "children_all": "하위 태스크 대기",+ "children_stage": "{{stage}}단계 대기",+ "pr_checks": "CI 대기",+ "pr_merged": "PR 병합 대기",+ "other_done": "{{issue}} 완료 대기",+ "other_ended": "{{issue}} 종료 대기",+ "other_in_review": "{{issue}} 검토 대기",+ "time": "{{time}}에 {{agent}} 깨우기",+ "header": "{{agent}}: {{what}}",+ "paused": "깨우기 일시중지됨",+ "open": "깨우기 보기"+ },+ "paused": {+ "max_fires": "{{count}}회 실행해 한도에 도달해 중지됨",+ "loop": "일시중지: 다른 규칙과 서로 깨우고 있었습니다",+ "rate": "일시중지: 1시간에 12회 넘게 실행됨",+ "hint": "다시 켜면 재개되고 횟수는 초기화됩니다."+ },+ "detail": {+ "fires_other": "{{count}}회 실행",+ "fires_max": "{{count}}회 실행 (최대 {{max}}회)",+ "history_title": "실행 기록",+ "history_empty": "아직 실행되지 않음",+ "history_error": "기록을 불러올 수 없습니다",+ "run_checkin": "조용한 확인",+ "run_commented": "{{state}} · 댓글 남김",+ "wake_now": "지금 깨우기",+ "wake_now_done": "곧 {{agent}}이(가) 실행됩니다",+ "wake_now_error": "깨울 수 없습니다",+ "delete": "삭제",+ "delete_title": "이 깨우기를 삭제할까요?",+ "delete_body": "더 이상 {{agent}}을(를) 깨우지 않으며 시작되지 않은 실행은 취소됩니다. 이미 시작된 실행은 계속됩니다.",+ "deleting": "삭제 중…",+ "delete_error": "삭제할 수 없습니다"+ },+ "paused_reason": {+ "max_fires": "한도 {{count}}회에 도달",+ "loop": "다른 규칙과 서로 깨우고 있었습니다",+ "rate": "1시간에 12회 넘게 실행됨"+ }},"duplicates": {"banner_prefix": "중복 원본:",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 5b12a18254..c9c848ce7e 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -81,6 +81,23 @@"pr_auto_complete_badge": "PR 병합 시 자동 설정","built_in_locked": "기본 상태는 시스템 동작에 쓰이므로 편집하거나 보관할 수 없습니다. 순서는 바꿀 수 있습니다."},+ "wakeups": {+ "description": "모든 태스크에 적용되는 플랫폼 규칙입니다. 각 태스크의 깨우기 섹션에서 따로 바꿀 수 있습니다.",+ "child_done_title": "하위 태스크가 끝나면",+ "child_done_description": "한 단계가 끝나고 다음 단계가 기다리고 있으면 상위 태스크 담당자를 깨우고, 모든 하위 태스크가 끝나면 한 번 더 깨웁니다. 담당자가 멤버면 받은편지함으로 알립니다.",+ "enabled": "기본으로 켜기",+ "instruction": "기본 지시",+ "instruction_hint": "깨운 에이전트에게 전달됩니다. 비워 두면 아래 기본 제공 지시를 사용합니다.",+ "instruction_placeholder": "비워 두면 기본 제공 지시를 사용합니다",+ "builtin": "기본 제공 지시",+ "instruction_invalid": "지시는 4,000바이트 이내로 입력하세요.",+ "save": "저장",+ "saving": "저장 중…",+ "save_error": "기본값을 저장하지 못했습니다.",+ "customized_other": "진행 중인 태스크 {{count}}개가 자체 설정을 사용해 이 기본값을 따르지 않습니다.",+ "admin_only": "소유자와 관리자만 기본값을 바꿀 수 있습니다.",+ "load_error": "깨우기 기본값을 불러오지 못했습니다."+ },"quick_actions": {"title": "퀵 액션","description": "태스크 사이드바에서 미리 설정한 에이전트와 프롬프트를 실행합니다.",@@ -379,6 +396,7 @@"members": "멤버","labels": "레이블","issue_statuses": "태스크 상태",+ "wakeups": "깨우기","properties": "속성","quick_actions": "퀵 액션","plugins": "플러그인",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 9201492fd3..b679f65d9c 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -891,7 +891,8 @@"tool_kind_command": "命令","tool_kind_write": "编辑","tool_kind_read": "读取",- "tool_kind_misc": "其他"+ "tool_kind_misc": "其他",+ "trigger_wakeup": "唤醒触发"},"task_failure": {"cancelled_by_system": "已由系统取消",diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.jsonindex 317f262364..7603f66ac8 100644--- a/packages/views/locales/zh-Hans/autopilots.json+++ b/packages/views/locales/zh-Hans/autopilots.json@@ -476,7 +476,6 @@"scope": "范围","issue": "任务","trigger": "触发条件",- "next": "唤醒状态","enabled": "开启","all_triggers": "所有触发方式","event": "事件",@@ -484,7 +483,6 @@"recurring": "周期","all_agents": "所有智能体","search": "搜索任务或智能体",- "search_action": "搜索","running": "运行中","active_runs": "{{count}} 个运行未结束","issue_closed": "任务已关闭",@@ -510,13 +508,31 @@"active": "待唤醒或执行中","all": "全部","disabled": "已关闭",- "ended": "已结束"+ "ended": "已结束",+ "paused": "已暂停"},"target_agent": "唤醒对象",- "wakeup_run": "唤醒后的运行","empty_filtered": "没有匹配的唤醒","clear_filters": "清除筛选","batch_success": "已关闭 {{count}} 条唤醒",- "batch_partial": "已关闭 {{succeeded}} 条,{{failed}} 条失败;失败项仍保留选中,可重试。"+ "batch_partial": "已关闭 {{succeeded}} 条,{{failed}} 条失败;失败项仍保留选中,可重试。",+ "source": "来源",+ "sources": {+ "all": "来源:全部",+ "member": "成员",+ "agent": "智能体",+ "system": "系统"+ },+ "runs_7d": "近 7 天运行",+ "ends": "有效期",+ "until_issue_ends": "任务结束前",+ "fires_once": "触发一次",+ "assignee_target": "负责人 · {{name}}",+ "no_target": "没有智能体负责人",+ "banner_other": "{{count}} 条唤醒已自动暂停:{{issue}}「{{condition}}」——{{reason}}",+ "banner_view": "查看",+ "create": "新建唤醒",+ "create_pick_issue": "选择要添加唤醒的任务",+ "create_pick_issue_description": "唤醒属于该任务,并随任务结束而停止。"}}diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex 6aff9140b6..03271e5cf0 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -78,6 +78,7 @@"quick_create_failed": "通过智能体创建失败","quick_create_unconfirmed": "通过智能体创建结果未确认","autopilot_paused": "自动化已暂停",+ "children_done": "子任务已全部结束","autopilot_quota_exceeded": "自动化执行次数已用完"},"labels": {@@ -92,7 +93,8 @@"reacted_to_comment": "用 {{emoji}} 回应了你的评论","created_with_agent": "通过智能体创建:{{identifier}}","failed_with_detail": "失败:{{detail}}",- "autopilot_quota_blocked": "执行已被阻止:额度已用完"+ "autopilot_quota_blocked": "执行已被阻止:额度已用完",+ "children_done_stage": "第 {{stage}} 阶段的子任务已全部结束"},"toasts": {"source_context_retry_started": "已使用原始上下文开始重试",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex d21e989384..99ec88b06d 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -515,7 +515,25 @@"duplicate_removed": "取消了 {{identifier}} 对这个任务的重复标记","status_changed_pr": "所有关联 PR 均已合并({{prs}}),状态从 {{from}} 改为 {{to}}","pr_auto_complete_disabled": "设置此任务合并后不改状态",- "pr_auto_complete_enabled": "恢复了此任务合并后改状态"+ "pr_auto_complete_enabled": "恢复了此任务合并后改状态",+ "wakeup_created": "添加了唤醒:{{condition}}唤醒 {{agent}}",+ "wakeup_triggered": "{{condition}},唤醒了 {{agent}}",+ "wakeup_triggered_merged": "{{condition}},并入了 {{agent}} 待开始的运行",+ "wakeup_triggered_acknowledged": "{{condition}},由 {{agent}} 自己触发,未重复唤醒",+ "wakeup_triggered_manual": "{{name}} 立即唤醒了 {{agent}}",+ "wakeup_child_done_stage_other": "第 {{stage}} 阶段的 {{count}} 个子任务已全部结束",+ "wakeup_child_done_all_other": "{{count}} 个子任务已全部结束",+ "wakeup_child_done_woke": ",唤醒了 {{name}}",+ "wakeup_child_done_notified": ",已通知 {{name}}",+ "wakeup_child_done_merged": ",并入了 {{name}} 待开始的运行",+ "wakeup_child_done_acknowledged": ",{{name}} 正在处理,未重复唤醒",+ "wakeup_assignee": "负责人",+ "wakeup_timed_out_wake": "等待超时({{condition}}),唤醒了 {{agent}} 处理超时",+ "wakeup_timed_out_end": "唤醒已到期结束:{{condition}}",+ "wakeup_checkin": "静默检查:{{note}}",+ "wakeup_checkin_coalesced_other": "静默检查 {{count}} 次 · 最近一次:{{note}}",+ "wakeup_chip_created_by": "{{name}} 创建",+ "wakeup_chip_system": "系统规则"},"comment": {"add_reaction": "添加表情回应",@@ -704,7 +722,8 @@"source_backfill": "回填的归因","source_unattributed": "未解析到责任成员"},- "usage_total_tooltip": "这个任务的 token 用量——点击查看每次运行的明细"+ "usage_total_tooltip": "这个任务的 token 用量——点击查看每次运行的明细",+ "trigger_wakeup": "由唤醒触发 · {{condition}}"},"usage_detail": {"title": "用量明细",@@ -965,7 +984,7 @@"disable": "关闭 {{agent}} 的唤醒","disable_error": "无法关闭唤醒","source_run": "监听的运行",- "source_agent": "监听的智能体",+ "source_agent": "{{agent}} 创建(代表 {{name}})","next": "下次:","last_run": "查看运行记录","run_completed": "运行完成",@@ -1076,7 +1095,9 @@"triggered": "已触发","expired": "已过期","inactive": "未启用",- "issue_closed": "任务已结束,唤醒已停用"+ "issue_closed": "任务已结束,唤醒已停用",+ "timed_out": "已超时",+ "paused": "已自动暂停"},"run_states": {"queued": "排队中",@@ -1089,7 +1110,209 @@"cancelled": "已取消"},"hourly": "每小时唤醒",- "today_time": "今天 {{time}}"+ "today_time": "今天 {{time}}",+ "remaining_days": "还剩 {{days}} 天",+ "remaining_days_hours": "还剩 {{days}} 天 {{hours}} 小时",+ "remaining_hours": "还剩 {{hours}} 小时",+ "remaining_minutes": "还剩 {{minutes}} 分钟",+ "until_date": "至 {{date}}",+ "source_title": "来源",+ "source_member": "{{name}} 创建",+ "source_agent_unknown": "智能体",+ "expiry_title": "有效期",+ "expiry_at": "{{time}} 结束",+ "expiry_timed_out": "已于 {{time}} 超时",+ "timeout_then_wake": "超时后唤醒 {{agent}} 处理",+ "timeout_then_end": "超时后直接结束",+ "create": {+ "open": "新建唤醒",+ "title": "新建唤醒",+ "when": "当",+ "wake": "唤醒",+ "choose_condition": "选择条件",+ "choose_agent": "选择智能体",+ "group_time": "时间",+ "group_collaboration": "协作",+ "group_runs": "运行与子任务",+ "cond_at": "在某个时间",+ "cond_at_hint": "10 分钟后、明天 09:00",+ "cond_recurring": "定期检查",+ "cond_recurring_hint": "每小时、每天,需设截止日",+ "cond_reply": "有人回复",+ "cond_reply_hint": "任何人或指定的人",+ "cond_run_end": "智能体的运行结束",+ "cond_run_end_hint": "成功、失败或取消",+ "cond_custom": "自定义事件…",+ "cond_custom_hint": "{{count}} 种原始事件",+ "at_10m": "10 分钟后",+ "at_1h": "1 小时后",+ "at_tomorrow": "明天 09:00",+ "at_custom": "自定义时间",+ "hourly": "每小时",+ "daily": "每天 09:00",+ "weekdays": "工作日 09:00",+ "until": "截止",+ "anyone": "任何人",+ "members": "成员",+ "agents": "智能体",+ "any_agent": "任意智能体",+ "events_selected": "{{count}} 个事件",+ "instruction_placeholder": "例如:检查结果,没有问题就继续下一步",+ "trigger_count": "触发次数",+ "max_wait": "最多等待",+ "wait_days_other": "{{count}} 天",+ "on_timeout": "超时后",+ "timeout_wake": "唤醒 {{agent}} 处理",+ "timeout_end": "直接结束",+ "the_agent": "智能体",+ "on_behalf": "唤醒后的运行将代表你执行",+ "submit": "创建",+ "submitting": "创建中…",+ "cancel": "取消",+ "error": "无法创建唤醒,请检查设置后重试。",+ "capacity_error": "此任务或工作区开启的唤醒已达上限。",+ "missing_condition": "请选择条件。",+ "missing_agent": "请选择要唤醒的智能体。",+ "missing_events": "请至少选择一个事件。",+ "until_future": "截止日需晚于今天。",+ "closed": "任务已完成或取消,不能新建唤醒。",+ "group_linked": "关联",+ "cond_field": "字段变为某个值",+ "cond_field_hint": "状态、负责人、标签、属性",+ "cond_children": "子任务完成",+ "cond_children_hint": "全部完成或某个阶段完成",+ "cond_pr": "关联 PR 的 CI 结束",+ "cond_pr_hint": "也可选合并",+ "cond_issue": "其他任务的状态变化",+ "cond_issue_hint": "例如完成时",+ "field_status": "状态",+ "field_assignee": "负责人",+ "field_label": "标签",+ "field_property": "属性",+ "field_kind": "字段",+ "choose_status": "选择状态",+ "choose_assignee": "选择负责人",+ "choose_label": "选择标签",+ "choose_property": "选择属性",+ "value_placeholder": "值",+ "squads": "小队",+ "children_all": "全部子任务",+ "children_stage": "第 {{stage}} 阶段",+ "pr_checks": "CI 结束",+ "pr_merged": "合并",+ "choose_issue": "选择任务",+ "pick_issue_title": "选择要关注的任务",+ "pick_issue_description": "该任务达到所选状态时唤醒智能体。",+ "other_done": "完成",+ "other_ended": "完成或取消",+ "other_in_review": "进入审核中",+ "max_fires": "最多触发",+ "max_fires_times_other": "{{count}} 次",+ "missing_value": "请选择一个值。",+ "missing_issue": "请选择一个任务。",+ "checked": "已勾选",+ "unchecked": "未勾选",+ "assignee_comment_hint": "{{name}} 是负责人,成员发评论时本来就会被触发。这条规则会并入那次运行,不会多跑一次;只有想追加指令时才需要它。"+ },+ "system": {+ "badge": "系统",+ "title_stage": "当第 {{stage}} 阶段的子任务全部结束时",+ "title_all": "当子任务全部结束时",+ "wake_assignee": "唤醒负责人 {{name}}",+ "remaining_other": "还差 {{count}} 个",+ "blocked_backlog": "任务在待规划中,暂不唤醒",+ "blocked_member": "负责人是成员,会收到收件箱通知",+ "blocked_none": "没有智能体负责人,不会唤醒",+ "turned_off": "已在此任务上关闭",+ "target_title": "唤醒",+ "target_current": "负责人(当前 {{name}})",+ "target_none": "负责人:智能体或小队会被唤醒,成员会收到通知",+ "progress_title": "进度",+ "progress": "{{done}}/{{total}} 已结束",+ "waiting_on": "还差 {{ids}}",+ "skip_title": "不会触发",+ "skip": "任务在待规划中;移出后会补一次",+ "source": "系统规则 · 有子任务时自动生效",+ "enable": "在此任务上启用",+ "toggle": "子任务结束时唤醒负责人",+ "save_error": "无法保存系统规则。",+ "default_on": "工作区默认开启,可在「设置 → 唤醒」中修改默认值。",+ "default_off": "工作区默认关闭,可在「设置 → 唤醒」中修改默认值。",+ "notify_member": "通过收件箱通知 {{name}}",+ "instruction": "唤醒后要做什么",+ "instruction_edit": "编辑指令",+ "instruction_default": "此任务未设置,使用默认指令:",+ "instruction_placeholder": "留空则使用默认指令",+ "instruction_invalid": "指令最多 4,000 字节。",+ "paused": "已暂停:{{reason}}"+ },+ "cond": {+ "status": "当状态变为{{status}}时",+ "assignee": "当负责人变为 {{name}} 时",+ "label": "当加上标签 {{label}} 时",+ "property": "当 {{property}} 为 {{value}} 时",+ "children_all": "当子任务全部结束时",+ "children_stage": "当第 {{stage}} 阶段的子任务全部结束时",+ "pr_checks": "当关联 PR 的 CI 结束时",+ "pr_merged": "当关联 PR 合并时",+ "other_done": "当 {{issue}} 完成时",+ "other_ended": "当 {{issue}} 完成或取消时",+ "other_in_review": "当 {{issue}} 进入审核中时",+ "another_issue": "另一个任务",+ "unknown_label": "已删除的标签",+ "unknown_property": "已删除的属性",+ "checked": "已勾选",+ "unchecked": "未勾选"+ },+ "wait": {+ "reply_from": "等 {{name}} 回复",+ "reply_any": "等回复",+ "run_end": "等 {{agent}} 的运行结束",+ "run_end_any": "等运行结束",+ "status": "等状态变为{{status}}",+ "assignee": "等负责人变为 {{name}}",+ "label": "等标签 {{label}}",+ "property": "等 {{property}} 变为 {{value}}",+ "children_all": "等子任务完成",+ "children_stage": "等第 {{stage}} 阶段完成",+ "pr_checks": "等 CI 结束",+ "pr_merged": "等 PR 合并",+ "other_done": "等 {{issue}} 完成",+ "other_ended": "等 {{issue}} 结束",+ "other_in_review": "等 {{issue}} 进入审核",+ "time": "{{time}} 唤醒 {{agent}}",+ "header": "{{agent}} 在{{what}}",+ "paused": "唤醒已自动暂停",+ "open": "查看唤醒"+ },+ "paused": {+ "max_fires": "已触发 {{count}} 次,达到上限后暂停",+ "loop": "已暂停:与其他唤醒规则互相触发",+ "rate": "已暂停:1 小时内触发超过 12 次",+ "hint": "重新开启后恢复,次数重新计算。"+ },+ "detail": {+ "fires_other": "已触发 {{count}} 次",+ "fires_max": "已触发 {{count}} 次,最多 {{max}} 次",+ "history_title": "触发记录",+ "history_empty": "尚未触发",+ "history_error": "无法加载触发记录",+ "run_checkin": "静默检查",+ "run_commented": "{{state}} · 发表了评论",+ "wake_now": "立即唤醒",+ "wake_now_done": "已唤醒 {{agent}}",+ "wake_now_error": "无法立即唤醒",+ "delete": "删除",+ "delete_title": "删除这条唤醒?",+ "delete_body": "删除后不再唤醒 {{agent}},尚未开始的运行会被撤回。已经开始的运行会继续。",+ "deleting": "正在删除…",+ "delete_error": "无法删除唤醒"+ },+ "paused_reason": {+ "max_fires": "达到 {{count}} 次上限",+ "loop": "与其他唤醒规则互相触发",+ "rate": "1 小时内触发超过 12 次"+ }},"duplicates": {"banner_prefix": "重复于",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 9787aa0cb4..f92c7a0cae 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -81,6 +81,23 @@"pr_auto_complete_badge": "PR 合并后自动进入","built_in_locked": "内置状态驱动系统行为,不能编辑或归档,但可以调整顺序。"},+ "wakeups": {+ "description": "平台对所有任务生效的规则。每个任务可以在自己的「唤醒」区域单独修改。",+ "child_done_title": "子任务结束时",+ "child_done_description": "某个阶段的子任务全部结束、且后面还有阶段在等待时,唤醒父任务的负责人;全部子任务结束时再唤醒一次。负责人是成员时,改为发送收件箱通知。",+ "enabled": "默认开启",+ "instruction": "默认指令",+ "instruction_hint": "发给被唤醒的智能体。留空则使用下方的内置指令。",+ "instruction_placeholder": "留空则使用内置指令",+ "builtin": "内置指令",+ "instruction_invalid": "指令最多 4,000 字节。",+ "save": "保存",+ "saving": "保存中…",+ "save_error": "无法保存默认值。",+ "customized_other": "{{count}} 个进行中的任务使用了自己的设置,不跟随此默认值。",+ "admin_only": "只有所有者和管理员可以修改默认值。",+ "load_error": "无法加载唤醒默认值。"+ },"quick_actions": {"title": "快捷操作","description": "在任务侧栏运行预设的智能体和提示词。",@@ -379,6 +396,7 @@"members": "成员","labels": "标签","issue_statuses": "任务状态",+ "wakeups": "唤醒","properties": "属性","quick_actions": "快捷操作","plugins": "插件",diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsxindex 28e61c3249..f933b307c1 100644--- a/packages/views/settings/components/settings-page.tsx+++ b/packages/views/settings/components/settings-page.tsx@@ -2,6 +2,7 @@import React, { useEffect, useMemo, useRef, useState } from "react";import {+ AlarmClock,Bell,Blocks,CircleDot,@@ -59,6 +60,7 @@ import { SETTINGS_ANCHOR_ATTR } from "./settings-layout";import { searchSettings } from "./settings-search";import { HighlightText } from "../../search/highlight-text";import { useSettingsSearchIndex } from "./use-settings-search-index";+import { WakeupsTab } from "./wakeups-tab";import { CollapsedNavTrigger } from "../../layout/page-header";import { useT } from "../../i18n";@@ -210,6 +212,10 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {<IssueStatusesTab />,{ wide: true, adminOnly: true },),+ entry("wakeups", t(($) => $.page.tabs.wakeups), AlarmClock, <WakeupsTab />, {+ wide: true,+ adminOnly: true,+ }),entry("labels", t(($) => $.page.tabs.labels), Tags, <LabelsTab />, {wide: true,}),diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.tsindex a83cc6e73c..6e126cd8e6 100644--- a/packages/views/settings/components/use-settings-search-index.ts+++ b/packages/views/settings/components/use-settings-search-index.ts@@ -140,6 +140,12 @@ export function useSettingsSearchIndex({ tab: "workspace", anchor: "delete", title: t(($) => $.workspace.delete_title) },{ tab: "members", anchor: "invitations", title: t(($) => $.members.pending_label) },{ tab: "members", anchor: "links", title: t(($) => $.members.share_links_label) },+ {+ tab: "wakeups",+ anchor: "child-done",+ title: t(($) => $.wakeups.child_done_title),+ description: t(($) => $.wakeups.child_done_description),+ },{tab: "labels",title: t(($) => $.page.tabs.labels),diff --git a/packages/views/settings/components/wakeups-tab.test.tsx b/packages/views/settings/components/wakeups-tab.test.tsxnew file mode 100644index 0000000000..125f300782--- /dev/null+++ b/packages/views/settings/components/wakeups-tab.test.tsx@@ -0,0 +1,62 @@+import { beforeEach, expect, it, vi } from "vitest";+import { fireEvent, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { api } from "@multica/core/api";+import { renderWithI18n } from "../../test/i18n";+import { WakeupsTab } from "./wakeups-tab";++vi.mock("@multica/core/api", () => ({+ api: { listWorkspaceSystemWakeups: vi.fn(), updateWorkspaceSystemWakeup: vi.fn() },+}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: (selector: (s: unknown) => unknown) => selector({ user: { id: "u" } }),+}));+let role = "admin";+vi.mock("@multica/core/workspace/queries", () => ({+ memberListOptions: () => ({ queryKey: ["members", "ws"], queryFn: async () => [{ user_id: "u", role }] }),+}));++const list = vi.mocked(api.listWorkspaceSystemWakeups);+const update = vi.mocked(api.updateWorkspaceSystemWakeup);++function mount() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ return renderWithI18n(+ <QueryClientProvider client={client}>+ <WakeupsTab />+ </QueryClientProvider>,+ );+}++beforeEach(() => {+ role = "admin";+ list.mockReset().mockResolvedValue([+ { rule: "child_done", enabled: true, instruction: "", builtin_instruction: "Advance the next stage.", customized: 2 },+ ]);+ update.mockReset().mockResolvedValue(undefined);+});++it("turns the sub-issue rule's default off and saves a workspace instruction", async () => {+ mount();+ const toggle = await screen.findByRole("switch", { name: "On by default" });+ expect(screen.getByText("2 open issues have their own setting and ignore this default.")).toBeVisible();+ fireEvent.click(toggle);+ await waitFor(() => expect(update).toHaveBeenCalledWith("child_done", { enabled: false }));++ const input = screen.getByRole("textbox", { name: "Default instruction" });+ expect(screen.getByText("Advance the next stage.")).toBeVisible();+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();+ fireEvent.change(input, { target: { value: " Wrap up in the parent. " } });+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ await waitFor(() => expect(update).toHaveBeenCalledWith("child_done", { instruction: "Wrap up in the parent." }));+});++it("shows the defaults read-only to members who cannot change them", async () => {+ role = "member";+ mount();+ expect(await screen.findByText("Only owners and admins can change these defaults.")).toBeVisible();+ expect(screen.getByRole("switch", { name: "On by default" })).toHaveAttribute("aria-disabled", "true");+ expect(screen.getByRole("textbox", { name: "Default instruction" })).toBeDisabled();+ expect(screen.queryByRole("button", { name: "Save" })).toBeNull();+});diff --git a/packages/views/settings/components/wakeups-tab.tsx b/packages/views/settings/components/wakeups-tab.tsxnew file mode 100644index 0000000000..6a715bc878--- /dev/null+++ b/packages/views/settings/components/wakeups-tab.tsx@@ -0,0 +1,145 @@+"use client";++import { useEffect, useId, useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { useWorkspaceId } from "@multica/core/hooks";+import { useAuthStore } from "@multica/core/auth";+import { memberListOptions } from "@multica/core/workspace/queries";+import { useUpdateWorkspaceSystemWakeup, workspaceSystemWakeupsOptions } from "@multica/core/issues";+import type { WorkspaceSystemWakeup } from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import { Switch } from "@multica/ui/components/ui/switch";+import { Textarea } from "@multica/ui/components/ui/textarea";+import { useT } from "../../i18n";+import { SettingsCard, SettingsRow, SettingsSection, SettingsTab } from "./settings-layout";++const MAX_INSTRUCTION_BYTES = 4000;++/**+ * Workspace defaults of the platform's wakeup rules. Each issue can change+ * its own rule in its Wakeups section; those issues stop following these+ * defaults.+ */+export function WakeupsTab() {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const { data: rules = [], isError } = useQuery(workspaceSystemWakeupsOptions(wsId));+ const { data: members = [] } = useQuery(memberListOptions(wsId));+ const currentUser = useAuthStore((s) => s.user);+ const canManage = useMemo(() => {+ const role = members.find((m) => m.user_id === currentUser?.id)?.role;+ return role === "owner" || role === "admin";+ }, [members, currentUser]);+ const childDone = rules.find((rule) => rule.rule === "child_done");+ return (+ <SettingsTab title={t(($) => $.page.tabs.wakeups)} description={t(($) => $.wakeups.description)}>+ {isError && (+ <p role="alert" className="text-caption text-destructive">+ {t(($) => $.wakeups.load_error)}+ </p>+ )}+ {childDone && <ChildDoneDefault rule={childDone} canManage={canManage} />}+ {childDone && !canManage && <p className="text-caption text-muted-foreground">{t(($) => $.wakeups.admin_only)}</p>}+ </SettingsTab>+ );+}++function ChildDoneDefault({ rule, canManage }: { rule: WorkspaceSystemWakeup; canManage: boolean }) {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const update = useUpdateWorkspaceSystemWakeup(wsId);+ const id = useId();+ const [instruction, setInstruction] = useState(rule.instruction);+ const [error, setError] = useState("");+ // A save elsewhere (another tab, another admin) replaces an untouched draft.+ useEffect(() => setInstruction(rule.instruction), [rule.instruction]);+ const dirty = instruction.trim() !== rule.instruction;+ const save = async (input: { enabled?: boolean; instruction?: string }) => {+ try {+ await update.mutateAsync({ rule: rule.rule, ...input });+ } catch {+ toast.error(t(($) => $.wakeups.save_error));+ throw new Error("save failed");+ }+ };+ return (+ <SettingsSection+ anchor="child-done"+ title={t(($) => $.wakeups.child_done_title)}+ description={t(($) => $.wakeups.child_done_description)}+ >+ <SettingsCard>+ <SettingsRow+ label={<label htmlFor={`${id}-enabled`}>{t(($) => $.wakeups.enabled)}</label>}+ description={rule.customized > 0 ? t(($) => $.wakeups.customized, { count: rule.customized }) : undefined}+ >+ <Switch+ id={`${id}-enabled`}+ checked={rule.enabled}+ disabled={!canManage || update.isPending}+ aria-busy={update.isPending || undefined}+ onCheckedChange={(enabled) => void save({ enabled }).catch(() => undefined)}+ />+ </SettingsRow>+ <form+ className="space-y-2 px-4 py-3.5"+ onSubmit={(event) => {+ event.preventDefault();+ const next = instruction.trim();+ if (new TextEncoder().encode(next).length > MAX_INSTRUCTION_BYTES) {+ setError(t(($) => $.wakeups.instruction_invalid));+ return;+ }+ void save({ instruction: next }).catch(() => undefined);+ }}+ >+ <label htmlFor={`${id}-instruction`} className="text-body font-medium">+ {t(($) => $.wakeups.instruction)}+ </label>+ <p id={`${id}-hint`} className="text-caption leading-5 text-muted-foreground">+ {t(($) => $.wakeups.instruction_hint)}+ </p>+ <Textarea+ id={`${id}-instruction`}+ rows={3}+ value={instruction}+ placeholder={t(($) => $.wakeups.instruction_placeholder)}+ disabled={!canManage || update.isPending}+ aria-describedby={error ? `${id}-hint ${id}-error` : `${id}-hint`}+ aria-invalid={!!error}+ className="resize-y text-base md:text-body"+ onChange={(event) => {+ setInstruction(event.target.value);+ setError("");+ }}+ onKeyDown={(event) => {+ if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && !event.nativeEvent.isComposing) {+ event.preventDefault();+ event.currentTarget.form?.requestSubmit();+ }+ }}+ />+ {error && (+ <p id={`${id}-error`} role="alert" className="text-caption text-destructive">+ {error}+ </p>+ )}+ {rule.builtin_instruction && (+ <div className="rounded-md bg-muted/60 px-3 py-2 text-caption leading-5 text-muted-foreground">+ <p className="font-medium">{t(($) => $.wakeups.builtin)}</p>+ <p className="mt-0.5 whitespace-pre-wrap break-words">{rule.builtin_instruction}</p>+ </div>+ )}+ {canManage && (+ <div className="flex justify-end">+ <Button type="submit" size="sm" disabled={!dirty || update.isPending}>+ {update.isPending ? t(($) => $.wakeups.saving) : t(($) => $.wakeups.save)}+ </Button>+ </div>+ )}+ </form>+ </SettingsCard>+ </SettingsSection>+ );+}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 28369826f2..b960628142 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -148,6 +148,10 @@ var concurrentIndexCleanups = map[string]string{"546_issue_pr_automation_workspace_index": "idx_issue_pr_automation_workspace","547_issue_pull_request_exclusion_workspace_index": "idx_issue_pull_request_exclusion_workspace","548_task_supplement_comment_task_index": "task_supplement_comment_task_uidx",+ "554_wakeup_expiry_index": "issue_wakeup_expiry_idx",+ "556_wakeup_system_rule_index": "issue_wakeup_system_rule_idx",+ "559_issue_child_event_id": "issue_child_event_id_idx",+ "560_issue_child_event_pending": "issue_child_event_pending_idx","510_wakeup_id": "issue_wakeup_id_idx","511_wakeup_issue": "issue_wakeup_issue_idx","512_wakeup_due": "issue_wakeup_due_idx",diff --git a/server/cmd/multica/cmd_issue_wakeup.go b/server/cmd/multica/cmd_issue_wakeup.goindex 49e9d1ba08..d942469bd7 100644--- a/server/cmd/multica/cmd_issue_wakeup.go+++ b/server/cmd/multica/cmd_issue_wakeup.go@@ -8,6 +8,7 @@ import ("net/http""net/url""os"+ "strings""time""github.com/multica-ai/multica/server/internal/cli"@@ -20,22 +21,39 @@ func init() { issueCmd.AddCommand(newIssueWakeupCommand()) }func newIssueWakeupCommand() *cobra.Command {wake := &cobra.Command{Use: "wakeup", Short: "Manage event and time wakeups that start ordinary runs"}wake.AddCommand(&cobra.Command{Use: "events", Short: "List supported event types and filters", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error {- return cli.PrintJSON(os.Stdout, map[string]any{"event_types": eventcontract.WakeupTypes, "platform_only_event_types": eventcontract.LifecycleTypes, "platform_only_reason": "Creation precedes subscription; deletion withdraws the issue's wakeups. Cross-issue subscriptions are not supported.", "scope": "current issue", "filters": []string{"filter_agent_id (task events; legacy mutation alias)", "filter_task_id (task events only)", "filter_actor_type + filter_actor_id (member or agent; mutation events only)"}, "modes": []string{"once (default)", "continuous"}, "loop_protection": "Events from the registering run and runs started by the same rule are excluded when source identity is available. Cross-rule cycles are not prevented; avoid mutually triggering continuous comment subscriptions."})+ return cli.PrintJSON(os.Stdout, map[string]any{"event_types": eventcontract.WakeupTypes, "platform_only_event_types": eventcontract.LifecycleTypes, "platform_only_reason": "Creation precedes subscription; deletion withdraws the issue's wakeups. Cross-issue subscriptions are not supported.", "scope": "current issue", "filters": []string{"filter_agent_id (task events; legacy mutation alias)", "filter_task_id (task events only)", "filter_actor_type + filter_actor_id (member or agent; mutation events only)"}, "modes": []string{"once (default)", "continuous"}, "conditions": []string{"--until-status KEY", "--until-assignee member|agent|squad:ID", "--until-label LABEL_ID", "--until-property PROPERTY_ID=VALUE", "--until-children-done [--stage N]", "--until-pr checks|merged", "--until-issue ISSUE [--until-issue-state done|ended|in_review]"}, "loop_protection": "Events from the registering run and runs started by the same rule are excluded when source identity is available. Repeating rules stop after --max-fires runs (default 20 for continuous event rules). A rule is paused when its trigger chain passes through it a third time without a person in between, or when it starts more than 12 runs in an hour."})}})- for _, action := range []string{"list", "get", "disable", "create", "update"} {+ for _, action := range []string{"list", "get", "disable", "create", "update", "trigger", "delete", "checkin", "runs"} {action := actioncount := 1- if action == "get" || action == "disable" || action == "update" {+ if action != "list" && action != "create" {count = 2}use := action + " <issue-id>"if count == 2 {use += " <wakeup-id>"}- c := &cobra.Command{Use: use, Args: cobra.ExactArgs(count), Short: action + " issue wakeups", RunE: func(cmd *cobra.Command, args []string) error { return runIssueWakeup(cmd, args, action) }}+ short := action + " issue wakeups"+ switch action {+ case "trigger":+ short = "Wake the target now, as if the rule fired"+ case "delete":+ short = "Delete a wakeup and withdraw its runs that have not started"+ case "checkin":+ short = "End a scheduled check silently (every/cron runs only)"+ c := &cobra.Command{Use: use, Args: cobra.ExactArgs(count), Short: short, RunE: func(cmd *cobra.Command, args []string) error { return runIssueWakeup(cmd, args, action) }}+ c.Long = "Run this from a run that an every or cron wakeup started, when the check found nothing that needs a reply. The note is shown on the rule and in the issue timeline, and the run then posts no comment. Anything else still ends with a comment."+ c.Flags().String("note", "", "What the check found, e.g. \"CI still running\" (up to 500 characters)")+ wake.AddCommand(c)+ continue+ case "runs":+ short = "List the latest runs a wakeup started"+ }+ c := &cobra.Command{Use: use, Args: cobra.ExactArgs(count), Short: short, RunE: func(cmd *cobra.Command, args []string) error { return runIssueWakeup(cmd, args, action) }}c.Flags().String("output", "json", "Output format (json or table)")if action == "create" || action == "update" {c.Long = "Create or replace the complete configuration. Events default to once; every/cron use continuous. Updating explicitly re-enables the configuration. Runs use normal comment delivery."+ c.Long += " Give waits an end with --expires-in or --expires-at; --on-timeout wake runs the target once if the deadline passes first."c.Long += " For task events, use --task-id for one run or --filter-agent-id for its agent. For comment/issue/reaction/attachment changes, use --filter-actor-type member|agent with --filter-actor-id. To wait for a person to comment, use --event comment.created --filter-actor-type member --filter-actor-id USER_ID. Actor filters identify who made the change, not the original author of an edited comment. Without a source filter, all matching events on this issue can wake the target."c.Flags().String("agent-id", "", "Agent to wake (defaults to authenticated agent)")c.Flags().String("instruction", "", "Instruction for the next run")@@ -53,6 +71,20 @@ func newIssueWakeupCommand() *cobra.Command {c.Flags().String("every", "", "Fixed interval, e.g. 1h (minimum 1m)")c.Flags().String("cron", "", "Five-field cron expression")c.Flags().String("timezone", "UTC", "IANA timezone for cron")+ c.Flags().String("expires-in", "", "End the rule after this wait, e.g. 72h; restarts when re-enabled (event, every, cron)")+ c.Flags().String("expires-at", "", "End the rule at this RFC3339 time (event, every, cron)")+ c.Flags().String("on-timeout", "", "At the deadline: end (default) or wake (event rules run the target once to handle it)")+ c.Long += " Conditions let the platform check stored facts itself and wake the target only when they hold: use one --until-* flag instead of --event. A condition that already holds fires on the next check, except --until-pr checks, which waits for a newer finished result."+ c.Flags().String("until-status", "", "Condition: this issue's status becomes KEY")+ c.Flags().String("until-assignee", "", "Condition: this issue is assigned to member|agent|squad:ID")+ c.Flags().String("until-label", "", "Condition: this issue has the label LABEL_ID")+ c.Flags().String("until-property", "", "Condition: property PROPERTY_ID equals VALUE (PROPERTY_ID=VALUE; VALUE may be JSON)")+ c.Flags().Bool("until-children-done", false, "Condition: every sub-issue is closed (or those up to --stage)")+ c.Flags().Int32("stage", 0, "With --until-children-done: wait for this stage and earlier ones")+ c.Flags().String("until-pr", "", "Condition: a linked pull request's checks finish (checks) or it merges (merged)")+ c.Flags().String("until-issue", "", "Condition: another issue in this workspace reaches --until-issue-state")+ c.Flags().String("until-issue-state", "done", "With --until-issue: done, ended (done or cancelled) or in_review")+ c.Flags().Int32("max-fires", 0, "Repeating rules: stop after this many runs (1-1000; continuous event rules default to 20)")}wake.AddCommand(c)}@@ -94,9 +126,44 @@ func runIssueWakeup(cmd *cobra.Command, args []string, action string) error {var row map[string]anyerr = client.PostJSON(ctx, path+"/"+url.PathEscape(args[1])+"/disable", map[string]any{}, &row)result = row+ } else if action == "trigger" {+ if err = client.PostJSON(ctx, path+"/"+url.PathEscape(args[1])+"/trigger", map[string]any{}, nil); err != nil {+ return err+ }+ result = map[string]any{"id": args[1], "triggered": true}+ } else if action == "delete" {+ if err = client.DeleteJSON(ctx, path+"/"+url.PathEscape(args[1])); err != nil {+ return err+ }+ result = map[string]any{"id": args[1], "deleted": true}+ } else if action == "checkin" {+ note, _ := cmd.Flags().GetString("note")+ if note == "" {+ return fmt.Errorf("--note is required")+ }+ if err = client.PostJSON(ctx, path+"/"+url.PathEscape(args[1])+"/checkin", map[string]any{"note": note}, nil); err != nil {+ return err+ }+ fmt.Fprintln(os.Stderr, "Checked in; this run will not post a comment.")+ return nil+ } else if action == "runs" {+ var rows []map[string]any+ if err = client.GetJSON(ctx, path+"/"+url.PathEscape(args[1])+"/runs", &rows); err != nil {+ return err+ }+ output, _ := cmd.Flags().GetString("output")+ if output == "table" {+ cells := [][]string{}+ for _, r := range rows {+ cells = append(cells, []string{strVal(r, "id"), strVal(r, "status"), strVal(r, "created_at"), strVal(r, "checkin_note")})+ }+ cli.PrintTable(os.Stdout, []string{"RUN", "STATUS", "CREATED", "CHECK-IN"}, cells)+ return nil+ }+ return cli.PrintJSON(os.Stdout, rows)} else {body := map[string]any{}- for flag, key := range map[string]string{"agent-id": "agent_id", "kind": "kind", "mode": "mode", "filter-agent-id": "filter_agent_id", "filter-actor-type": "filter_actor_type", "filter-actor-id": "filter_actor_id", "task-id": "filter_task_id", "parent": "parent_comment_id", "at": "at", "cron": "cron_expression", "timezone": "timezone"} {+ for flag, key := range map[string]string{"agent-id": "agent_id", "kind": "kind", "mode": "mode", "filter-agent-id": "filter_agent_id", "filter-actor-type": "filter_actor_type", "filter-actor-id": "filter_actor_id", "task-id": "filter_task_id", "parent": "parent_comment_id", "at": "at", "cron": "cron_expression", "timezone": "timezone", "expires-at": "expires_at", "on-timeout": "on_timeout"} {v, _ := cmd.Flags().GetString(flag)if v != "" {body[key] = v@@ -111,7 +178,17 @@ func runIssueWakeup(cmd *cobra.Command, args []string, action string) error {if len(ev) > 0 {body["event_types"] = ev}- for flag, key := range map[string]string{"after": "after_seconds", "every": "interval_seconds"} {+ condition, e := wakeupConditionFromFlags(ctx, cmd, client)+ if e != nil {+ return e+ }+ if condition != nil {+ body["condition"] = condition+ }+ if n, _ := cmd.Flags().GetInt32("max-fires"); n != 0 {+ body["max_fires"] = n+ }+ for flag, key := range map[string]string{"after": "after_seconds", "every": "interval_seconds", "expires-in": "expires_in_seconds"} {v, _ := cmd.Flags().GetString(flag)if v != "" {d, e := time.ParseDuration(v)@@ -174,3 +251,66 @@ func isWakeupSourceBusy(err error) bool {}return json.Unmarshal([]byte(httpErr.Body), &body) == nil && body.Code == "wakeup_source_busy"}++// wakeupConditionFromFlags builds the one platform-evaluated condition the+// --until-* flags describe, or nil when none is set.+func wakeupConditionFromFlags(ctx context.Context, cmd *cobra.Command, client *cli.APIClient) (map[string]any, error) {+ var conditions []map[string]any+ if v, _ := cmd.Flags().GetString("until-status"); v != "" {+ conditions = append(conditions, map[string]any{"type": "issue_field", "field": "status", "value": v})+ }+ if v, _ := cmd.Flags().GetString("until-assignee"); v != "" {+ kind, id, ok := strings.Cut(v, ":")+ if !ok || id == "" {+ return nil, fmt.Errorf("--until-assignee takes member|agent|squad:ID")+ }+ conditions = append(conditions, map[string]any{"type": "issue_field", "field": "assignee", "assignee_type": kind, "assignee_id": id})+ }+ if v, _ := cmd.Flags().GetString("until-label"); v != "" {+ conditions = append(conditions, map[string]any{"type": "issue_field", "field": "label", "label_id": v})+ }+ if v, _ := cmd.Flags().GetString("until-property"); v != "" {+ id, raw, ok := strings.Cut(v, "=")+ if !ok || id == "" || raw == "" {+ return nil, fmt.Errorf("--until-property takes PROPERTY_ID=VALUE")+ }+ var value any = raw+ if json.Valid([]byte(raw)) {+ value = json.RawMessage(raw)+ }+ conditions = append(conditions, map[string]any{"type": "issue_field", "field": "property", "property_id": id, "value": value})+ }+ stage, _ := cmd.Flags().GetInt32("stage")+ if done, _ := cmd.Flags().GetBool("until-children-done"); done {+ c := map[string]any{"type": "children_done"}+ if stage != 0 {+ c["stage"] = stage+ }+ conditions = append(conditions, c)+ } else if stage != 0 {+ return nil, fmt.Errorf("--stage requires --until-children-done")+ }+ if v, _ := cmd.Flags().GetString("until-pr"); v != "" {+ event := map[string]string{"checks": "checks_finished", "merged": "merged"}[v]+ if event == "" {+ return nil, fmt.Errorf("--until-pr takes checks or merged")+ }+ conditions = append(conditions, map[string]any{"type": "pull_request", "event": event})+ }+ if v, _ := cmd.Flags().GetString("until-issue"); v != "" {+ ref, err := resolveIssueRef(ctx, client, v)+ if err != nil {+ return nil, err+ }+ state, _ := cmd.Flags().GetString("until-issue-state")+ conditions = append(conditions, map[string]any{"type": "other_issue", "issue_id": ref.ID, "state": state})+ }+ switch len(conditions) {+ case 0:+ return nil, nil+ case 1:+ return conditions[0], nil+ default:+ return nil, fmt.Errorf("use one --until-* condition per wakeup")+ }+}diff --git a/server/cmd/multica/cmd_issue_wakeup_test.go b/server/cmd/multica/cmd_issue_wakeup_test.goindex f3fc9f8968..d29ccbd5d3 100644--- a/server/cmd/multica/cmd_issue_wakeup_test.go+++ b/server/cmd/multica/cmd_issue_wakeup_test.go@@ -113,3 +113,118 @@ func TestIssueWakeupCLIActorFilter(t *testing.T) {}}}++func TestIssueWakeupCLISendsExpiry(t *testing.T) {+ t.Chdir(t.TempDir())+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Error(err)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "wake", "enabled": true})+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")+ cmd := newIssueWakeupCommand()+ cmd.SetArgs([]string{"create", "a57c0511-1ebc-471d-a314-438ca16cc75d", "--event", "comment.created", "--instruction", "follow up", "--expires-in", "72h", "--on-timeout", "wake"})+ if err := cmd.Execute(); err != nil {+ t.Fatal(err)+ }+ if body["expires_in_seconds"] != float64(259200) || body["on_timeout"] != "wake" {+ t.Fatalf("unexpected body %+v", body)+ }+}++func TestIssueWakeupCLIConditionsAndManagement(t *testing.T) {+ t.Chdir(t.TempDir())+ const issue = "a57c0511-1ebc-471d-a314-438ca16cc75d"+ type call struct {+ method, path string+ body map[string]any+ }+ var calls []call+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ calls = append(calls, call{r.Method, r.URL.Path, body})+ switch {+ case r.Method == "GET":+ _ = json.NewEncoder(w).Encode([]map[string]any{{"id": "run", "status": "completed", "checkin_note": "fine"}})+ case r.Method == "POST" && r.URL.Path == "/api/issues/"+issue+"/wakeups":+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "wake"})+ default:+ w.WriteHeader(http.StatusNoContent)+ }+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")+ run := func(args ...string) error {+ cmd := newIssueWakeupCommand()+ cmd.SetArgs(args)+ cmd.SilenceUsage, cmd.SilenceErrors = true, true+ return cmd.Execute()+ }+ for _, tc := range []struct {+ args []string+ want string+ }{+ {[]string{"--until-status", "in_review"}, `{"field":"status","type":"issue_field","value":"in_review"}`},+ {[]string{"--until-property", "p1=\"approved\""}, `{"field":"property","property_id":"p1","type":"issue_field","value":"approved"}`},+ {[]string{"--until-property", "p1=approved"}, `{"field":"property","property_id":"p1","type":"issue_field","value":"approved"}`},+ {[]string{"--until-children-done", "--stage", "2"}, `{"stage":2,"type":"children_done"}`},+ {[]string{"--until-pr", "checks", "--mode", "continuous", "--max-fires", "5"}, `{"event":"checks_finished","type":"pull_request"}`},+ {[]string{"--until-assignee", "agent:a1"}, `{"assignee_id":"a1","assignee_type":"agent","field":"assignee","type":"issue_field"}`},+ } {+ calls = nil+ if err := run(append([]string{"create", issue, "--instruction", "go"}, tc.args...)...); err != nil {+ t.Fatalf("%v: %v", tc.args, err)+ }+ got, _ := json.Marshal(calls[len(calls)-1].body["condition"])+ if string(got) != tc.want {+ t.Errorf("%v: condition %s, want %s", tc.args, got, tc.want)+ }+ if tc.args[0] == "--until-pr" && calls[len(calls)-1].body["max_fires"] != float64(5) {+ t.Errorf("max_fires not sent: %+v", calls[len(calls)-1].body)+ }+ }+ for _, bad := range [][]string{+ {"--until-status", "done", "--until-label", "l1"},+ {"--stage", "2"},+ {"--until-pr", "reviews"},+ {"--until-assignee", "a1"},+ } {+ if err := run(append([]string{"create", issue, "--instruction", "go"}, bad...)...); err == nil {+ t.Errorf("%v accepted", bad)+ }+ }+ calls = nil+ for _, args := range [][]string{+ {"trigger", issue, "w1"},+ {"delete", issue, "w1"},+ {"checkin", issue, "w1", "--note", "CI still running"},+ {"runs", issue, "w1"},+ } {+ if err := run(args...); err != nil {+ t.Fatalf("%v: %v", args, err)+ }+ }+ want := []string{"POST /api/issues/" + issue + "/wakeups/w1/trigger", "DELETE /api/issues/" + issue + "/wakeups/w1", "POST /api/issues/" + issue + "/wakeups/w1/checkin", "GET /api/issues/" + issue + "/wakeups/w1/runs"}+ if len(calls) != len(want) {+ t.Fatalf("calls %+v", calls)+ }+ for i, c := range calls {+ if c.method+" "+c.path != want[i] {+ t.Errorf("call %d = %s %s, want %s", i, c.method, c.path, want[i])+ }+ }+ if calls[2].body["note"] != "CI still running" {+ t.Errorf("check-in body %+v", calls[2].body)+ }+ if err := run("checkin", issue, "w1"); err == nil {+ t.Error("check-in without a note accepted")+ }+}diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 06164306ee..5c7f3567b7 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -828,6 +828,9 @@ func main() {if err := schedulerMgr.Register(scheduler.IssueWakeupJob(&service.IssueWakeupService{Tasks: taskSvc})); err != nil {slog.Error("scheduler: register issue wakeups", "error", err)}+ if err := schedulerMgr.Register(scheduler.ChildEventSweepJob(&service.IssueWakeupService{Tasks: taskSvc})); err != nil {+ slog.Error("scheduler: register child-done sweep", "error", err)+ }if err := schedulerMgr.Register(scheduler.AutopilotScheduleDispatchJob(pool, queries, autopilotSvc)); err != nil {slog.Warn("scheduler: failed to register autopilot_schedule_dispatch job", "error", err)}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex ed44405c8c..bb6ef22848 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2022,6 +2022,12 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/wakeups/{wakeupID}/disable", h.DisableIssueWakeup)r.Post("/wakeups/{wakeupID}/enable", h.EnableIssueWakeup)r.Patch("/wakeups/{wakeupID}/instruction", h.EditIssueWakeupInstruction)+ r.Delete("/wakeups/{wakeupID}", h.DeleteIssueWakeup)+ r.Post("/wakeups/{wakeupID}/trigger", h.TriggerIssueWakeup)+ r.Post("/wakeups/{wakeupID}/checkin", h.CheckInIssueWakeup)+ r.Get("/wakeups/{wakeupID}/runs", h.ListIssueWakeupRuns)+ r.Get("/system-wakeups", h.ListIssueSystemWakeups)+ r.Put("/system-wakeups/{rule}", h.UpdateIssueSystemWakeup)r.Get("/active-task", h.GetActiveTaskForIssue)r.Post("/tasks/{taskId}/cancel", h.CancelTask)r.With(handler.RequireHumanActor).Post("/tasks/{taskId}/supplements", h.CreateTaskSupplement)@@ -2357,6 +2363,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/api/agent-task-snapshot", h.ListWorkspaceAgentTaskSnapshot)r.Get("/api/issue-wakeup-summaries", h.ListWorkspaceWakeupSummaries)r.Get("/api/issue-wakeups", h.ListWorkspaceWakeups)+ r.Get("/api/issue-wakeup-paused", h.ListPausedWakeups)+ r.Get("/api/system-wakeups", h.ListWorkspaceSystemWakeups)+ r.Put("/api/system-wakeups/{rule}", h.UpdateWorkspaceSystemWakeup)// Independent workspace-level list backing the issues-header// "agents working" chip and its assignee-id Table filter.diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex cd9a5957e0..66c8321702 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -213,6 +213,7 @@ func daemonCommonCapabilities() []string {protocol.DaemonCapabilityRPCV1,protocol.DaemonCapabilityPlatformSkillV1,protocol.DaemonCapabilityCheckoutKeepsWorkV1,+ protocol.DaemonCapabilityJoinedWakeupsV1,}}diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.goindex bab777aafb..e9d56b5e1c 100644--- a/server/internal/daemon/client_test.go+++ b/server/internal/daemon/client_test.go@@ -55,6 +55,9 @@ func TestClient_IdentityHeaders_PostJSON(t *testing.T) {// (MUL-7034). Dropping it silently sends those retries back to a// fresh directory, losing the continuity nothing else would flag.protocol.DaemonCapabilityCheckoutKeepsWorkV1,+ // Without it the server never hands this daemon the wakeups that+ // waited for its run; they start runs of their own instead.+ protocol.DaemonCapabilityJoinedWakeupsV1,} {if !capabilities[want] {t.Errorf("X-Client-Capabilities missing %q: %v", want, capabilities)diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 7e41e81251..201286b6e3 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -99,7 +99,7 @@ func writeHeader(b *strings.Builder) {// a fresh review decision.func writeBackgroundTaskSafetySlim(b *strings.Builder) {b.WriteString("## Background Task Safety\n\n")- b.WriteString("Multica marks the task terminal the moment your top-level turn exits — any run-owned work still active is orphaned, its result lost, and the final comment you meant to post never sends. There is no background-completion wakeup, whatever a tool response promises. Never background-and-yield: collect required results inside foreground tool calls that block to completion, run unobservable work synchronously, and never end a turn \"standing by\" for something to finish — that message becomes your final output.\n\n")+ b.WriteString("Multica marks the task terminal the moment your top-level turn exits — any run-owned work still active is orphaned, its result lost, and the final comment you meant to post never sends. There is no background-completion wakeup, whatever a tool response promises; an issue wakeup (`multica issue wakeup create`) is different — the platform stores it and starts a new run later. Never background-and-yield: collect required results inside foreground tool calls that block to completion, run unobservable work synchronously, and never end a turn \"standing by\" for something to finish — that message becomes your final output.\n\n")b.WriteString("External systems triggered by your completed actions — CI, GitHub Actions after a successful push — are not run-owned: do not wait for them, and do not run `gh pr checks --watch`, `gh run watch`, or sleep/retry polls. A repo's merge gate (\"CI must be green before merge\") is NOT your delivery acceptance criteria. Deliver what you have — \"Local tests pass; CI running: <PR link>\" is a complete hand-off. The one exception: when the trigger comment or the issue's acceptance criteria explicitly ask for the CI result, collect it as ONE foreground blocking call (`gh pr checks <pr> --watch`) inside this same turn.\n\n")b.WriteString("A user explicitly asking for a local service to stay available after the turn is a persistent service handoff, not background-and-yield — allowed only when the running service itself is the requested deliverable. Detach its lifecycle from this run first (durable logs, a recorded cleanup handle such as PID/profile), verify readiness, and reply with the URL, logs, and stop instructions. Without a supervisor, describe survival as best-effort, not guaranteed.\n\n")b.WriteString("Never terminate `multica` or `multica.exe` by executable name: a long-lived matching process may be the workspace daemon. Cancel only the exact child PID you started, and before terminating it compare that PID with `multica daemon status --output json`; never kill it if it is the reported daemon PID.\n\n")@@ -264,7 +264,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("- `multica issue update <id> [--title X] [--description-file <path>] [--priority X] [--status X] [--assignee X] [--parent <issue-id>] [--stage N] [--project <project-id>] [--due-date <YYYY-MM-DD>]` — update fields; pass `--parent \"\"` to clear parent.\n")b.WriteString("- `multica issue assign <id> (--to X | --to-id <uuid> | --unassign)` — change ownership; assigning to an agent can start a run.\n")writeIssueStatusCommand(b, ctx)- b.WriteString("- `multica issue wakeup <create|list|get|update|disable|events>` — persist an event or time wakeup on this issue, then finish the current run. Use `--event comment.created --filter-actor-type member --filter-actor-id USER_ID` to wait for a specific member to comment. See `multica issue wakeup --help` and the multica-platform issues reference.\n")+ b.WriteString("- `multica issue wakeup <create|list|get|update|disable|trigger|delete|runs|events>` — persist an event, condition or time wakeup on this issue, then finish the current run. When the platform can check the fact itself, use a condition (`--until-status`, `--until-pr checks`, `--until-children-done`, `--until-issue`) so no run starts before it holds. Use `--event comment.created --filter-actor-type member --filter-actor-id USER_ID` to wait for a specific member to comment. See `multica issue wakeup --help` and the multica-platform issues reference.\n")b.WriteString("- `multica issue children <id> [--output json]` — list a parent's sub-issues grouped by stage.\n")b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-file <path> | --content-stdin] [--parent <comment-id>] [--attachment <path>]` — post a comment. Agent-authored bodies MUST use `--content-file`; see `## Comment Formatting` for why. `multica issue comment add --help` for full flags.\n")b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>] [--fresh]` — repository checkout on a dedicated branch. Re-running it keeps an existing checkout that has uncommitted or unpushed work, or is already on this task's branch, and only fetches. `--fresh` discards uncommitted and untracked files and starts a new branch; commits stay on the old branch, but push any you still need first.\n\n")@@ -750,7 +750,7 @@ func writeWorkflowAutopilot(b *strings.Builder) {// the re-trigger (member update / stage barrier) that confirms the overall// goal is met. Flipping the parent on the dispatch turn would mark unfinished// multi-stage work as ready for review; see the Squad Operating Protocol and-// child-done system comments.+// the sub-issue wakeup (service/issue_wakeup_system.go).//// ctx.IsSquadLeader is a PER-TASK role, not agent configuration: branching on// it here does move brief bytes when the same agent runs leader one turn and@@ -1013,7 +1013,7 @@ func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {} else {b.WriteString("⚠️ **Final results MUST be delivered via `multica issue comment add`.** The user does NOT see your terminal output or run logs — only comments on the issue.\n\n")}- b.WriteString("**Post exactly ONE comment per run — your final result, before this turn exits.** Do NOT post progress updates or plans along the way.\n\n")+ b.WriteString("**Post exactly ONE comment per run — your final result, before this turn exits.** Do NOT post progress updates or plans along the way. Only a scheduled wakeup check whose `[WAKEUP]` block offers `multica issue wakeup checkin` may check in instead of commenting, when it found nothing that needs a reply.\n\n")b.WriteString("Keep comments concise and natural — state the outcome, not the process.\n\n")b.WriteString("**Delivering files here:** pass `--attachment <path>` to `multica issue comment add` (repeatable) — the only way a screenshot or artifact reaches the reader.\n")writeInlineBlocksPolicy(b)diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex 8b0aea6af6..b8ce727c51 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -69,9 +69,20 @@ func perTurnContextBlocks(task Task, opts promptOpts) string {}b.WriteString(execenv.BuildOnBehalfOfBlock(task.InitiatorName, task.InitiatorEmail))b.WriteString(execenv.BuildConnectedAppsBlock(task.ConnectedApps))+ b.WriteString(buildJoinedWakeupsBlock(task.WakeupJoined))return b.String()}+// buildJoinedWakeupsBlock carries wakeups that fired while this run was+// waiting to start. The server folded them into this run instead of queuing a+// second run of the same agent on the issue, so this run handles them too.+func buildJoinedWakeupsBlock(notes string) string {+ if strings.TrimSpace(notes) == "" {+ return ""+ }+ return "[WAKEUP — joined this run]\n" + strings.TrimSpace(notes) + "\n\n"+}+// promptOpts carries per-run facts the claimed Task does not: things only the// daemon's own execution context can answer. Kept behind PromptOption so the// common BuildPrompt(task, provider) call sites stay unchanged.@@ -202,9 +213,14 @@ func buildPromptBody(task Task, provider string) string {if task.WakeupID != "" {var b strings.Builderfmt.Fprintf(&b, "You are running as a local coding agent for a Multica workspace.\n\nYour assigned issue ID is: %s\n\n[WAKEUP]\n%s\n\n", task.IssueID, task.HandoffNote)- fmt.Fprintf(&b, "Start by running `multica issue get %s --output json`, then read current run/comment state. Decide whether the instruction's goal is met; the trigger reports a fact, not business completion. This is an ordinary run with normal result delivery.\n", task.IssueID)+ fmt.Fprintf(&b, "Start by running `multica issue get %s --output json`, then read current run/comment state. Decide whether the instruction's goal is met; the trigger reports a fact, not business completion. This is an ordinary run with normal result delivery, except where the [WAKEUP] block offers a check-in.\n", task.IssueID)fmt.Fprintf(&b, "Scan comment threads with `multica issue comment list %s --roots-only --summary --compact --output json`, then expand relevant threads with `--thread <id> --tail 30`.\n", task.IssueID)- fmt.Fprintf(&b, "Inspect this configuration with `multica issue wakeup get %s %s --output json`. If recurring work is no longer needed, disable it with `multica issue wakeup disable %s %s`.\n", task.IssueID, task.WakeupID, task.IssueID, task.WakeupID)+ if task.WakeupSystemRule != "" {+ // Platform rules belong to the issue, not to a run; members manage them.+ fmt.Fprintf(&b, "This wakeup is the platform's sub-issue rule for this issue. Do not try to change or disable it; members manage it on the issue.\n")+ } else {+ fmt.Fprintf(&b, "Inspect this configuration with `multica issue wakeup get %s %s --output json`. If recurring work is no longer needed, disable it with `multica issue wakeup disable %s %s`.\n", task.IssueID, task.WakeupID, task.IssueID, task.WakeupID)+ }if task.TriggerCommentID != "" {fmt.Fprintf(&b, "Post your result using `multica issue comment add %s --parent %s --content-file ./reply.md --output table && rm ./reply.md`. This is the original delivery thread, not a new comment trigger.\n", task.IssueID, task.TriggerCommentID)}diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.goindex 966518e90e..9e13f0a8e7 100644--- a/server/internal/daemon/prompt_test.go+++ b/server/internal/daemon/prompt_test.go@@ -2236,3 +2236,21 @@ func TestBuildPromptIssueStateFallsBackToTheRead(t *testing.T) {})}}++// A wakeup the server folded into this run reaches the agent whatever started+// the run, and nothing is added when none joined.+func TestPromptCarriesJoinedWakeups(t *testing.T) {+ note := "Wakeup w1 fired while this run was waiting to start. Instruction:\nSummarize the discussion"+ for name, task := range map[string]Task{+ "assignment": {IssueID: "issue-1", WakeupJoined: note},+ "comment": {IssueID: "issue-1", TriggerCommentID: "c1", TriggerCommentContent: "please look", WakeupJoined: note},+ } {+ out := BuildPrompt(task, "claude")+ if !strings.Contains(out, "[WAKEUP — joined this run]\n"+note) {+ t.Errorf("%s prompt lacks the joined wakeup:\n%s", name, out)+ }+ }+ if out := BuildPrompt(Task{IssueID: "issue-1"}, "claude"); strings.Contains(out, "joined this run") {+ t.Errorf("prompt without joined wakeups mentions them:\n%s", out)+ }+}diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex 40542c62fd..aae6a3722a 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -147,7 +147,9 @@ type Task struct {QuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids,omitempty"` // attachments uploaded in the quick-create prompt and bound by issue createQuickCreateSourceContext json.RawMessage `json:"quick_create_source_context,omitempty"` // immutable historical context, separate from the new instructionWakeupID string `json:"wakeup_id,omitempty"`- HandoffNote string `json:"handoff_note,omitempty"` // legacy assignment handoff instruction; rendered only in the per-turn prompt+ WakeupSystemRule string `json:"wakeup_system_rule,omitempty"` // a platform rule (e.g. child_done) started the run+ WakeupJoined string `json:"wakeup_joined,omitempty"` // wakeups that joined this run instead of queuing their own+ HandoffNote string `json:"handoff_note,omitempty"` // legacy assignment handoff instruction; rendered only in the per-turn promptSquadID string `json:"squad_id,omitempty"` // when the picker was a squad, the squad's UUID; Agent is still the resolved leaderSquadName string `json:"squad_name,omitempty"` // display name for the picker squad, used in prompt textdiff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 36532d19c7..fc6f50c9db 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -512,6 +512,8 @@ type AgentTaskResponse struct {QuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids,omitempty"` // attachment ids uploaded in the quick-create prompt and bound on issue createQuickCreateSourceContext json.RawMessage `json:"quick_create_source_context,omitempty"` // immutable historical context for source-context quick-createWakeupID string `json:"wakeup_id,omitempty"`+ WakeupSystemRule string `json:"wakeup_system_rule,omitempty"` // set when a platform rule (e.g. child_done) started the run+ WakeupJoined string `json:"wakeup_joined,omitempty"` // wakeups that fired while this run waited to start and joined it instead of queuing their ownHandoffNote string `json:"handoff_note,omitempty"` // legacy assignment handoff instruction retained for installed clients; rendered by the daemon only in the per-turn promptSquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leaderSquadName string `json:"squad_name,omitempty"` // display name for the picker squad@@ -819,7 +821,8 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {branchName = t.BranchName.String}var wakeupContext struct {- ID string `json:"wakeup_id"`+ ID string `json:"wakeup_id"`+ SystemRule string `json:"wakeup_system"`}_ = json.Unmarshal(t.Context, &wakeupContext)handoffNote := ""@@ -856,6 +859,8 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {TriggerSummary: textToPtr(t.TriggerSummary),HandoffNote: handoffNote,WakeupID: wakeupContext.ID,+ WakeupSystemRule: wakeupContext.SystemRule,+ WakeupJoined: service.JoinedWakeupNotes(t.Context),WorkDir: workDir,RelativeWorkDir: relativeWorkDir(workDir, workspaceID, uuidToString(t.ID)),DurableWorkDir: durableWorkDir,diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex d973a10222..247482d153 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -3638,6 +3638,19 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu}}+ // Wakeup rules that waited for this run hand it their inputs now, after+ // every gate passed, and only for a daemon that renders them; otherwise+ // they keep their inputs and start their own run.+ if requestHasClientCapability(r, protocol.DaemonCapabilityJoinedWakeupsV1) {+ joined, err := (&service.IssueWakeupService{Tasks: h.TaskService}).JoinWaitingWakeups(r.Context(), *task)+ if err != nil {+ slog.Warn("daemon claim: waiting wakeups keep their inputs", "task_id", uuidToString(task.ID), "error", err)+ } else {+ task.Context = joined+ resp.WakeupJoined = service.JoinedWakeupNotes(joined)+ }+ }+// Hydrate attribution only after every source/workspace/version gate has// passed so a rejected claim cannot receive another user's profile data.// The existing flat initiator fields carry the run's authorization human todiff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.goindex 4e00deb5fb..7951189cda 100644--- a/server/internal/handler/github_test.go+++ b/server/internal/handler/github_test.go@@ -2133,7 +2133,7 @@ func TestGitHubInstallationBroadcastRedaction(t *testing.T) {// must-fix: a merged PR is the dominant path by which a sub-issue actually// reaches `done`, and that path goes through maybeAutoCompleteIssue — not the// HTTP UpdateIssue / BatchUpdateIssues handlers that originally wired up-// notifyParentOfChildDone. Without the helper call inside maybeAutoCompleteIssue,+// the child-done processing. Without the helper call inside maybeAutoCompleteIssue,// the parent receives nothing when a child is closed by merging its PR.// This test fires a `pull_request closed merged` webhook against a child// issue and verifies the parent gets exactly one platform-generated system@@ -2225,32 +2225,12 @@ func TestWebhook_MergedPR_ChildWithParent_NotifiesParent(t *testing.T) {t.Fatalf("expected child status 'done', got %q", updatedChild.Status)}- // Parent must have received exactly one platform-generated system comment.- var sysCount int- dbfx.QueryRow(t,- `SELECT count(*) FROM comment WHERE issue_id = $1 AND author_type = 'system'`,- parent.ID,- ).Scan(&sysCount)- if sysCount != 1 {- t.Fatalf("expected 1 system comment on parent after PR-merge auto-done, got %d", sysCount)- }-- var content string- dbfx.QueryRow(t,- `SELECT content FROM comment WHERE issue_id = $1 AND author_type = 'system' LIMIT 1`,- parent.ID,- ).Scan(&content)- if !strings.Contains(content, child.Identifier) {- t.Errorf("system comment should reference child identifier %q, got: %s", child.Identifier, content)- }- // Parent has no assignee in this fixture, so the routing mentions stay- // absent. Behavior for assigned parents is covered in- // issue_child_done_test.go (MUL-2538 Option C).- for _, banned := range []string{"mention://agent/", "mention://member/", "mention://squad/"} {- if strings.Contains(content, banned) {- t.Errorf("system comment must not include %q mention (parent unassigned), got: %s", banned, content)- }+ // The merge closed the child through the PR path; the parent's rule+ // recorded it once, like a manual status change.+ if entries := childDoneEntries(t, parent.ID); len(entries) != 1 || entries[0].Outcome != "none" {+ t.Fatalf("expected 1 child_done entry on the parent after PR-merge auto-done, got %+v", entries)}+ t.Cleanup(func() { cleanupChildDoneIssue(parent.ID) })}// generateTestRSAKeyPEM returns the shared RSA-2048 test key's PKCS#1 PEMdiff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex f453d546fe..05cae67638 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -75,8 +75,8 @@ type IssueResponse struct {ProjectID *string `json:"project_id"`Position float64 `json:"position"`// Stage groups sub-issues under the same parent into ordered barrier- // groups (null = unstaged). See issue_child_done.go for how a closed- // stage gates the child-done -> parent wake.+ // groups (null = unstaged). See service/issue_wakeup_system.go for how a+ // closed stage wakes the parent's assignee.Stage *int32 `json:"stage"`StartDate *string `json:"start_date"`DueDate *string `json:"due_date"`@@ -4088,13 +4088,11 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, req.HandoffNote)}- // Platform-driven parent notification: when this issue transitions into- // `done` and has a parent, post a top-level system comment on the parent- // (MUL-2538 — replaces the agent-prompt rule that caused self-mention- // loops in PR #2918). The helper guards on transition + parent state and- // fails best-effort.- if statusChanged {- h.notifyParentOfChildDone(r.Context(), prevIssue, issue)+ // Sub-issue rules on the parent (the child_done system rule and sub-issue+ // conditions): the write recorded the change; process it now. A failure+ // is retried by the scheduler sweep.+ if statusChanged || prevIssue.ParentIssueID != issue.ParentIssueID || prevIssue.Stage != issue.Stage {+ h.processChildEvents(r.Context(), issue.ParentIssueID, prevIssue.ParentIssueID)}writeJSON(w, http.StatusOK, resp)@@ -4599,10 +4597,10 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {// One Resolver for the whole batch — a per-issue filler would query the// catalog once per custom-status row. (MUL-6243)fillBatch := h.newStatusCategoryFiller(r.Context(), wsUUID)- // Children that transitioned into a terminal status this batch, collected so- // the parent/stage notification is evaluated once against the final state- // after the loop (MUL-4155) rather than per-child mid-batch.- var childDoneCompleted []db.Issue+ // Parents whose sub-issues changed this batch. Their rules are evaluated+ // once after the loop against the final state (MUL-4155), not per child+ // against a mid-batch snapshot.+ var changedParents []pgtype.UUIDfor _, issueID := range req.IssueIDs {issueUUID, err := util.ParseUUID(issueID)if err != nil {@@ -4823,37 +4821,18 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {// No status change — not even → cancelled — cancels active tasks here,// mirroring UpdateIssue (MUL-4465). See that handler for the rationale.- // Platform-driven parent notification, mirrored from UpdateIssue- // (MUL-2538) but DEFERRED to after the loop. Evaluating the stage- // barrier here, per-child, would read a mid-batch sibling snapshot and- // fire a stale "advance Stage N+1" wake when one batch closes several- // stages at once (MUL-4155). Collect the terminal transitions and let- // notifyParentsOfBatchChildDone below evaluate each parent once against- // the batch's final committed state. Same transition guard as- // notifyParentOfChildDone: a non-terminal -> terminal move on a child.- // Resolve both sides to the canonical status they inherit before the- // terminal test, so a batch that moves the last child onto a CUSTOM- // done/cancelled status still enters the stage barrier below. A literal- // comparison here left childDoneCompleted empty and silently skipped- // notifyParentsOfBatchChildDone entirely. (MUL-6243)- if statusChanged && issue.ParentIssueID.Valid {- prevTerminal := isTerminalChildStatus(- issuestatus.Effective(r.Context(), h.Queries, prevIssue.WorkspaceID, prevIssue.Status))- nowTerminal := isTerminalChildStatus(- issuestatus.Effective(r.Context(), h.Queries, issue.WorkspaceID, issue.Status))- if !prevTerminal && nowTerminal {- childDoneCompleted = append(childDoneCompleted, issue)- }+ if statusChanged || prevIssue.ParentIssueID != issue.ParentIssueID || prevIssue.Stage != issue.Stage {+ changedParents = append(changedParents, issue.ParentIssueID, prevIssue.ParentIssueID)}updated++}- // Aggregate parent/stage notification over the whole batch's final state so- // each affected parent gets at most one accurate comment + wake, independent- // of issue_ids order (MUL-4155). Best-effort; failure does not abort the- // batch. Single-issue UpdateIssue is unchanged and still notifies inline.- h.notifyParentsOfBatchChildDone(r.Context(), childDoneCompleted)+ // Each write recorded its sub-issue change; processing claims them per+ // parent, so each parent is evaluated once against the batch's final+ // state, independent of issue_ids order (MUL-4155). A failure is retried+ // by the sweep.+ h.processChildEvents(r.Context(), changedParents...)slog.Info("batch update issues", append(logger.RequestAttrs(r), "count", updated)...)writeJSON(w, http.StatusOK, map[string]any{"updated": updated})diff --git a/server/internal/handler/issue_batch_test.go b/server/internal/handler/issue_batch_test.goindex 746b872b11..a2a1aef591 100644--- a/server/internal/handler/issue_batch_test.go+++ b/server/internal/handler/issue_batch_test.go@@ -262,12 +262,10 @@ func newStagedBatchFixture(t *testing.T) stagedBatchFixture {fx.stage2 = []IssueResponse{mkChild(2), mkChild(2)}t.Cleanup(func() {- ctx := context.Background()- testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, parent.ID)for _, c := range append(append([]IssueResponse{}, fx.stage1...), fx.stage2...) {- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, c.ID)+ cleanupChildDoneIssue(c.ID)}- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, parent.ID)+ cleanupChildDoneIssue(parent.ID)})return fx@@ -287,68 +285,24 @@ func batchSetStatus(t *testing.T, ids []string, status string) {}}-// systemCommentIDOn returns the id of the single (latest) system comment on issueID.-func systemCommentIDOn(t *testing.T, issueID string) string {- t.Helper()- var id string- if err := testPool.QueryRow(context.Background(),- `SELECT id::text FROM comment- WHERE issue_id = $1 AND author_type = 'system'- ORDER BY created_at DESC LIMIT 1`,- issueID,- ).Scan(&id); err != nil {- t.Fatalf("read system comment id: %v", err)- }- return id-}--// triggerCommentIDForAgentTask returns the trigger_comment_id of the single-// pending task on issueID for agentID.-func triggerCommentIDForAgentTask(t *testing.T, issueID, agentID string) string {- t.Helper()- var id string- if err := testPool.QueryRow(context.Background(),- `SELECT trigger_comment_id::text FROM agent_task_queue- WHERE issue_id = $1 AND agent_id = $2- AND status IN ('queued','dispatched','running')- ORDER BY created_at DESC LIMIT 1`,- issueID, agentID,- ).Scan(&id); err != nil {- t.Fatalf("read task trigger_comment_id: %v", err)- }- return id-}--// TestBatchChildDoneCrossStage_OneComment is the MUL-4155 core. A single batch-// that finishes children across two stages must produce exactly ONE accurate-// system comment on the parent — announcing the highest stage closed by the-// final state, never a stale "Stage 2 is next" — and the parent assignee's-// single wake must be pinned to that final comment, regardless of id order.-func TestBatchChildDoneCrossStage_OneComment(t *testing.T) {+// TestBatchChildDoneCrossStage_OneWake is the MUL-4155 core. A single batch+// that finishes children across two stages must wake the parent once, from+// the final state: every sub-issue closed, never a stale "Stage 2 is next",+// regardless of id order.+func TestBatchChildDoneCrossStage_OneWake(t *testing.T) {assertFinal := func(t *testing.T, parentID, agentID string) {t.Helper()- if got := countSystemCommentsOn(t, parentID); got != 1 {- t.Fatalf("expected exactly 1 system comment on parent, got %d", got)- }- content, _, _, _ := systemCommentOn(t, parentID)- if !strings.Contains(content, "Stage 2 of this issue is complete") {- t.Errorf("expected the comment to announce the top closed stage (Stage 2), got: %s", content)- }- if !strings.Contains(content, "Stage 1: 2/2 done; Stage 2: 2/2 done") {- t.Errorf("expected the final-state stage summary, got: %s", content)+ entries := childDoneEntries(t, parentID)+ if len(entries) != 1 || entries[0].Stage != nil || entries[0].Total != 4 || entries[0].Outcome != "woke" {+ t.Fatalf("entries = %+v, want one wrap-up wake", entries)}- // The bug: a mid-batch snapshot told the parent to advance a stage this- // same batch had already finished.- if strings.Contains(content, "is next") || strings.Contains(content, "(next)") {- t.Errorf("comment must not carry a stale next-stage instruction, got: %s", content)+ runs := childDoneRuns(t, parentID)+ if len(runs) != 1 || runs[0].ID != entries[0].TaskID || strings.Contains(runs[0].Note, "next_stage") || !strings.Contains(runs[0].Note, `"all":true`) {+ t.Fatalf("runs = %+v, want one run for the final state", runs)}- // Exactly one wake, pinned to the final comment.if got := countPendingTasksForAgent(t, parentID, agentID); got != 1 {t.Fatalf("expected exactly 1 pending parent task, got %d", got)}- if trig, want := triggerCommentIDForAgentTask(t, parentID, agentID), systemCommentIDOn(t, parentID); trig != want {- t.Errorf("parent wake pinned to %s, want the final comment %s", trig, want)- }}t.Run("forward order [stage1, stage2]", func(t *testing.T) {@@ -365,46 +319,29 @@ func TestBatchChildDoneCrossStage_OneComment(t *testing.T) {}// TestBatchChildDoneCrossStage_Cancelled — cancelling every stage in one batch-// is terminal too, but the notification must distinguish cancellation from-// successful completion while still emitting one accurate final comment.+// closes them too; the facts count the cancellations apart from finished work.func TestBatchChildDoneCrossStage_Cancelled(t *testing.T) {fx := newStagedBatchFixture(t)batchSetStatus(t, []string{fx.stage1[0].ID, fx.stage1[1].ID, fx.stage2[0].ID, fx.stage2[1].ID}, "cancelled")- if got := countSystemCommentsOn(t, fx.parent.ID); got != 1 {- t.Fatalf("expected exactly 1 system comment on parent, got %d", got)- }- content, _, _, _ := systemCommentOn(t, fx.parent.ID)- if !strings.Contains(content, "Stage 2 of this issue is closed") {- t.Errorf("expected Stage 2 closed announcement for cancelled work, got: %s", content)- }- if !strings.Contains(content, "Stage 1: 0/2 done, 2 cancelled; Stage 2: 0/2 done, 2 cancelled") {- t.Errorf("expected cancelled children to be counted separately from done, got: %s", content)- }- if strings.Contains(content, "is next") || strings.Contains(content, "(next)") {- t.Errorf("comment must not carry a stale next-stage instruction, got: %s", content)+ runs := childDoneRuns(t, fx.parent.ID)+ if len(runs) != 1 || !strings.Contains(runs[0].Note, `"cancelled":4`) || strings.Contains(runs[0].Note, "next_stage") {+ t.Fatalf("runs = %+v, want one wake counting 4 cancellations", runs)}}// TestBatchChildDoneClosesLowerStageOnly — when a batch finishes only the lower-// stage (a later stage still has open children), the parent must be told Stage 1-// is complete AND accurately pointed at Stage 2 as next. Guards against-// over-suppressing the legitimate advance instruction.+// stage, the parent is told Stage 1 closed and pointed at Stage 2.func TestBatchChildDoneClosesLowerStageOnly(t *testing.T) {fx := newStagedBatchFixture(t)batchSetStatus(t, []string{fx.stage1[0].ID, fx.stage1[1].ID}, "done")- if got := countSystemCommentsOn(t, fx.parent.ID); got != 1 {- t.Fatalf("expected exactly 1 system comment on parent, got %d", got)- }- content, _, _, _ := systemCommentOn(t, fx.parent.ID)- if !strings.Contains(content, "Stage 1 of this issue is complete") {- t.Errorf("expected Stage 1 completion announcement, got: %s", content)- }- if !strings.Contains(content, "Stage 2: 0/2 done (next)") {- t.Errorf("expected accurate next-stage progress, got: %s", content)+ entries := childDoneEntries(t, fx.parent.ID)+ if len(entries) != 1 || entries[0].Stage == nil || *entries[0].Stage != 1 || entries[0].Total != 2 {+ t.Fatalf("entries = %+v, want stage 1", entries)}- if !strings.Contains(content, "Stage 2 is next") {- t.Errorf("expected the advance-to-next-stage instruction, got: %s", content)+ runs := childDoneRuns(t, fx.parent.ID)+ if len(runs) != 1 || !strings.Contains(runs[0].Note, `"next_stage":2`) {+ t.Fatalf("runs = %+v, want the next stage named", runs)}}diff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.godeleted file mode 100644index e7345aa015..0000000000--- a/server/internal/handler/issue_child_done.go+++ /dev/null@@ -1,988 +0,0 @@-package handler--import (- "context"- "fmt"- "log/slog"- "sort"- "strconv"- "strings"-- "github.com/jackc/pgx/v5/pgtype"- "github.com/multica-ai/multica/server/internal/issuestatus"- "github.com/multica-ai/multica/server/internal/service"- db "github.com/multica-ai/multica/server/pkg/db/generated"- "github.com/multica-ai/multica/server/pkg/dbid"- "github.com/multica-ai/multica/server/pkg/protocol"-)--// notifyParentOfChildDone posts a top-level system comment on the parent-// issue when a child issue transitions from non-done into done. This replaces-// the agent-prompt rule that previously made child agents post the-// notification themselves (PR #2918 user feedback — the agent rule caused-// self-mention loops, planner ping-pong, and accidental `MUL-` prefix-// hardcoding because the agent did not always know the workspace prefix).-//-// Guards on whether the comment fires at all:-// - the child must transition from a non-terminal status INTO a terminal one-// (done or cancelled). Repeat saves of an already-terminal child do not-// re-fire; only the entering transition does. Cancelled counts because a-// cancelled sibling never finishes and so closes its stage (see the entry-// guard and isTerminalChildStatus).-// - issue.ParentIssueID must be set-// - parent must not be "done" or "cancelled" — the parent is already-// closed and a notification has no follow-up to drive-// - parent must not be "backlog" — a parent parked in backlog is being-// deliberately held for later; waking its assignee (which can then-// promote sibling backlog sub-issues into todo) is exactly the-// unwanted auto-activation reported in #4320 / MUL-3497. A parked-// parent stays inert until the user explicitly moves it out of backlog.-// - parent assignee must not be a member (human). Humans read their-// issues manually; an automated system comment is pure noise for them-// and there is nothing to "trigger" on a human assignee. Skipping the-// comment entirely (Bohan's call on MUL-2538) also sidesteps the-// mention question — no comment, no mention, no inbox row.-// - the completion must close a STAGE barrier (MUL-3508). Sub-issues under-// a parent can be grouped into ordered stages via issue.stage; the-// notification + wake fire only when every sibling in the lowest-// unfinished stage is terminal (stageBarrierClosed). An unstaged sibling-// set is one implicit stage, so this fires once when the last sub-issue-// finishes instead of on every child — the default fix for the-// fire-on-every-child cascade reported in #4320. The woken assignee-// decides whether to promote the next stage (agent-driven advancement);-// the server only detects the barrier and wakes.-//-// The comment is inserted directly via db.Queries (not through the-// CreateComment HTTP handler) so it bypasses the generic on_comment trigger-// path. When the parent has an agent or squad assignee, the comment body-// embeds a single `mention://{agent,squad}/<id>` link that targets the-// parent assignee — Bohan's product call on MUL-2538 ("system child-done-// comment 无脑 mention parent assignee,member/squad/agent 都覆盖", later-// narrowed to skip member assignees outright). To keep the platform in-// control of side effects, the cmd/server notification + subscriber-// listeners still skip system comments wholesale, so smuggled mentions from-// the child title cannot light up unrelated members. The parent assignee's-// own trigger is fired explicitly by dispatchParentAssigneeTrigger below,-// with the idempotency guard documented there.-//-// Errors are logged at warn level and swallowed: this is a best-effort-// notification on the side of a successful status update; failing it must-// not roll back the user's status change.-func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Issue) {- if !issue.ParentIssueID.Valid {- return- }- // Fire on a transition INTO a terminal status (done OR cancelled), not only- // `done`. A cancelled child can close a stage too: isTerminalChildStatus- // treats cancelled as terminal (a cancelled sibling never finishes, so it- // must not hold the stage open), so the barrier has to be evaluated when the- // last open child of a stage is cancelled. Keying on the transition also- // makes a later cancelled -> done edit a no-op (terminal -> terminal), which- // avoids a lagging duplicate wake.- // Both sides of the transition are resolved to the canonical status they- // inherit, so a move into a custom done/cancelled status fires the barrier- // exactly like a move into Done or Cancelled. (MUL-6243)- effective := h.childStatusResolver(ctx)- prevStatus, err := effective(prev)- if err != nil {- slog.Warn("child done: failed to resolve previous child status", "error", err, "child_id", uuidToString(issue.ID))- return- }- nowStatus, err := effective(issue)- if err != nil {- slog.Warn("child done: failed to resolve child status", "error", err, "child_id", uuidToString(issue.ID))- return- }- prevTerminal := isTerminalChildStatus(prevStatus)- nowTerminal := isTerminalChildStatus(nowStatus)- if prevTerminal || !nowTerminal {- return- }- parent, err := h.Queries.GetIssue(ctx, issue.ParentIssueID)- if err != nil {- slog.Warn("child done: failed to load parent",- "error", err,- "child_id", uuidToString(issue.ID),- "parent_id", uuidToString(issue.ParentIssueID))- return- }- // Custom terminal statuses close this out. Only the fixed backlog key parks it,- // exactly like Done/Cancelled and Backlog do. (MUL-6243)- parentStatus, err := effective(parent)- if err != nil {- slog.Warn("child done: failed to resolve parent status", "error", err, "parent_id", uuidToString(parent.ID))- return- }- if parentStatus == "done" || parentStatus == "cancelled" {- return- }- // A parent parked in backlog is deliberately held for later. Posting the- // system comment would wake its assignee, and the woken agent can then- // promote sibling backlog sub-issues into todo — the surprise auto-- // activation reported in #4320 / MUL-3497. Skip the whole notification so- // a backlog parent stays inert until the user explicitly promotes it.- if parentStatus == "backlog" {- return- }- // Human-assigned parents read their own timeline; an automated system- // comment is just noise and there is no agent task to trigger. Skip the- // whole notification (comment + mention + inbox row) — MUL-2538.- if parent.AssigneeType.Valid && parent.AssigneeType.String == "member" {- return- }-- // Stage barrier (MUL-3508 / discussion #4320). The notification + assignee- // wake fire only when this completion *closes a stage* — i.e. every sibling- // in the lowest unfinished stage is now terminal. An unstaged sibling set is- // one implicit stage, so this collapses to "wake once when the last- // sub-issue finishes" instead of the old fire-on-every-child behavior that- // caused the surprise cascade. A completion that does not close a stage is- // silent: no comment, no wake. ListChildIssues already reflects this child's- // committed terminal status (the status update commits before this runs).- children, err := h.Queries.ListChildIssues(ctx, parent.ID)- if err != nil {- slog.Warn("child done: failed to list siblings for stage barrier",- "error", err,- "child_id", uuidToString(issue.ID),- "parent_id", uuidToString(parent.ID))- return- }- statuses, err := resolveChildStatuses(children, effective)- if err != nil {- slog.Warn("child done: failed to resolve sibling statuses", "error", err, "parent_id", uuidToString(parent.ID))- return- }- if !stageBarrierClosed(children, issue, statuses.isTerminal) {- return- }- staged := siblingsAreStaged(children)- // When the set is staged and the barrier closed, the completed child is- // guaranteed to carry a stage (stageBarrierClosed returns false for an- // unstaged completed child in a staged set), so issue.Stage.Int32 is safe.- var closedStage int32- if staged {- closedStage = issue.Stage.Int32- }- h.postChildDoneComment(ctx, parent, issue, children, staged, closedStage, false, statuses, nil)-}--// notifyParentsOfBatchChildDone emits child-done parent notifications for a-// whole batch AFTER every status write has committed. `completed` is the set of-// children that transitioned non-terminal -> terminal during the batch.-//-// Evaluating the stage barrier per-child inside the batch loop used the-// mid-batch sibling snapshot, so a batch that closed several stages at once-// fired one comment per intermediate stage: the first (stale) comment pinned the-// parent assignee's wake to an already-superseded "advance Stage N+1"-// instruction while the accurate final wake was swallowed by the pending-task-// dedup, and the outcome depended on issue_ids order (MUL-4155). Aggregating-// here makes the result order-independent — each affected parent gets at most-// one comment built from the final state, plus one wake pinned to that comment.-//-// Best-effort, mirroring notifyParentOfChildDone: a failure on one parent is-// logged and skipped; it never rolls back the committed batch.-func (h *Handler) notifyParentsOfBatchChildDone(ctx context.Context, completed []db.Issue) {- if len(completed) == 0 {- return- }-- // Group the completed children by parent, preserving first-seen order so the- // emitted comments (and any test assertions) are deterministic.- type parentGroup struct {- parentID pgtype.UUID- children []db.Issue- }- var groups []*parentGroup- index := map[string]*parentGroup{}- for _, c := range completed {- if !c.ParentIssueID.Valid {- continue- }- key := uuidToString(c.ParentIssueID)- g, ok := index[key]- if !ok {- g = &parentGroup{parentID: c.ParentIssueID}- index[key] = g- groups = append(groups, g)- }- g.children = append(g.children, c)- }-- effective := h.childStatusResolver(ctx)- for _, g := range groups {- parent, err := h.Queries.GetIssue(ctx, g.parentID)- if err != nil {- slog.Warn("batch child done: failed to load parent",- "error", err, "parent_id", uuidToString(g.parentID))- continue- }- // Same parent guards as the single path (see notifyParentOfChildDone).- parentStatus, err := effective(parent)- if err != nil {- slog.Warn("batch child done: failed to resolve parent status", "error", err, "parent_id", uuidToString(parent.ID))- continue- }- if parentStatus == "done" || parentStatus == "cancelled" {- continue- }- if parentStatus == "backlog" {- continue- }- if parent.AssigneeType.Valid && parent.AssigneeType.String == "member" {- continue- }-- children, err := h.Queries.ListChildIssues(ctx, parent.ID)- if err != nil {- slog.Warn("batch child done: failed to list siblings for stage barrier",- "error", err, "parent_id", uuidToString(parent.ID))- continue- }-- statuses, err := resolveChildStatuses(children, effective)- if err != nil {- slog.Warn("batch child done: failed to resolve sibling statuses", "error", err, "parent_id", uuidToString(parent.ID))- continue- }- batch := len(g.children) > 1- if !siblingsAreStaged(children) {- // Unstaged: one implicit stage. Fire once iff every child is terminal- // in the final state. stageBarrierClosed ignores `completed` on the- // unstaged path, so any completed child stands in for the barrier check.- if !stageBarrierClosed(children, g.children[0], statuses.isTerminal) {- continue- }- h.postChildDoneComment(ctx, parent, g.children[0], children, false, 0, batch, statuses, g.children)- continue- }-- // Staged: announce the HIGHEST stage among this batch's completed children- // whose barrier is closed in the final state. This is what makes the- // result order-independent — whether the caller sent [stage1, stage2] or- // [stage2, stage1], the final committed state is identical, so the same- // top stage wins and stageProgressSummary's "Stage N is next" reflects- // reality rather than a mid-batch snapshot. A lower closed stage would- // re-introduce the stale "advance the next stage" instruction the bug was- // about.- rep, found := highestClosedBatchStage(children, g.children, statuses.isTerminal)- if !found {- continue- }- h.postChildDoneComment(ctx, parent, rep, children, true, rep.Stage.Int32, batch, statuses, g.children)- }-}--// highestClosedBatchStage selects the first completed child in the highest-// closed stage of a staged sibling set. The terminal predicate must come from-// a pre-resolved child-status snapshot: all required statuses must be known-// before selection. A stage S is closed iff no non-terminal staged sibling has-// stage <= S, so finding the earliest open stage once reduces selection from-// O(N*K) to O(N+K).-func highestClosedBatchStage(children, completed []db.Issue, isTerminal func(db.Issue) bool) (db.Issue, bool) {- var lowestCompleted pgtype.Int4- for _, c := range completed {- if c.Stage.Valid && (!lowestCompleted.Valid || c.Stage.Int32 < lowestCompleted.Int32) {- lowestCompleted = c.Stage- }- }- if !lowestCompleted.Valid {- return db.Issue{}, false- }- var firstOpen pgtype.Int4- for _, c := range children {- if !c.Stage.Valid {- continue // Unstaged siblings were not resolved and cannot block a stage.- }- if !isTerminal(c) {- if c.Stage.Int32 <= lowestCompleted.Int32 {- return db.Issue{}, false // This sibling blocks every candidate; do not scan the rest.- }- if !firstOpen.Valid || c.Stage.Int32 < firstOpen.Int32 {- firstOpen = c.Stage- }- }- }- var rep db.Issue- found := false- for _, c := range completed {- if !c.Stage.Valid || (firstOpen.Valid && c.Stage.Int32 >= firstOpen.Int32) {- continue- }- if !found || c.Stage.Int32 > rep.Stage.Int32 {- found = true- rep = c- }- }- return rep, found-}--// postChildDoneComment builds and posts the parent's child-done system comment-// for a closed stage barrier, then dispatches the parent-assignee trigger. It-// assumes every guard in notifyParentOfChildDone / notifyParentsOfBatchChildDone-// has already passed and that `completed` is a terminal child whose barrier is-// closed within `children` (the final sibling set).-//-// `completed` is the representative terminal child named in the comment.-// `staged`/`closedStage` describe the closed barrier (closedStage is unused for-// an unstaged set). `batch` selects batch-aware wording. `batchCompleted` is the-// set that transitioned to terminal in this batch; it is nil for single updates.-func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed db.Issue, children []db.Issue, staged bool, closedStage int32, batch bool, statuses resolvedChildStatuses, batchCompleted []db.Issue) {- prefix := h.getIssuePrefix(ctx, completed.WorkspaceID)- identifier := prefix + "-" + strconv.Itoa(int(completed.Number))- childID := uuidToString(completed.ID)- title := sanitizeChildTitleForSystemComment(completed.Title)- parentID := uuidToString(parent.ID)- completedStatus := statuses.status(completed)-- // Build the parent-assignee mention prefix. Empty when the parent has no- // assignee or the assignee row is missing (deleted member, archived- // agent the workspace lost track of, etc.).- mentionPrefix := h.buildParentAssigneeMention(ctx, parent)-- var content string- if staged {- stageCancelledCount := countStageCancelled(children, closedStage, statuses.status)- stageCancelled := stageCancelledCount > 0- advanceHasCancelled := stageCancelled- if batch {- // A single batch can close several stages. Always preserve cancellation- // already present in the named stage, and also account for lower stages- // newly cancelled by this same batch without repeating older lower-stage- // warnings.- advanceHasCancelled = stageCancelled || batchClosedScopeHasCancelled(children, batchCompleted, closedStage, statuses.status)- }- summary, nextStage := stageProgressSummary(children, closedStage, statuses.status)- advance := stageAdvanceInstruction(nextStage, parentID, stageCancelledCount, advanceHasCancelled)- if !stageCancelled {- // Keep the historical no-cancellation wording byte-identical for the- // named stage. A lower stage cancelled in the same batch can still add- // the dependency warning through advanceHasCancelled above.- if batch {- content = fmt.Sprintf(- "%sStage %d of this issue is complete — its sub-issues just finished together in a batch update, most recently [%s](mention://issue/%s) — \"%s\". Stage progress — %s.%s",- mentionPrefix, closedStage, identifier, childID, title, summary, advance,- )- } else {- content = fmt.Sprintf(- "%sStage %d of this issue is complete — its last sub-issue [%s](mention://issue/%s) — \"%s\" — just finished. Stage progress — %s.%s",- mentionPrefix, closedStage, identifier, childID, title, summary, advance,- )- }- } else if batch {- lastAction := "finished"- if completedStatus == "cancelled" {- lastAction = "was cancelled"- }- content = fmt.Sprintf(- "%sStage %d of this issue is closed — its sub-issues reached terminal states together in a batch update; most recently, [%s](mention://issue/%s) — \"%s\" — %s. Stage progress — %s.%s",- mentionPrefix, closedStage, identifier, childID, title, lastAction, summary, advance,- )- } else {- lastAction := "just finished"- if completedStatus == "cancelled" {- lastAction = "was just cancelled"- }- content = fmt.Sprintf(- "%sStage %d of this issue is closed — its last sub-issue [%s](mention://issue/%s) — \"%s\" — %s. Stage progress — %s.%s",- mentionPrefix, closedStage, identifier, childID, title, lastAction, summary, advance,- )- }- } else {- hasCancelled := anyCancelledChildren(children, statuses.status)- if !hasCancelled {- // Keep the historical no-cancellation wording byte-identical.- if batch {- content = fmt.Sprintf(- "%sAll sub-issues are complete — they just finished together in a batch update, most recently [%s](mention://issue/%s) — \"%s\". Continue the parent: synthesize the children's results and move it forward, or — if nothing remains — run `multica issue status %s in_review` to mark the parent ready for review.",- mentionPrefix, identifier, childID, title, parentID,- )- } else {- content = fmt.Sprintf(- "%sAll sub-issues are complete — the last one, [%s](mention://issue/%s) — \"%s\", just finished. Continue the parent: synthesize the children's results and move it forward, or — if nothing remains — run `multica issue status %s in_review` to mark the parent ready for review.",- mentionPrefix, identifier, childID, title, parentID,- )- }- } else {- lastAction := "finished"- if completedStatus == "cancelled" {- lastAction = "was cancelled"- }- warning := unstagedCancellationInstruction()- if !batch {- lastAction = "just finished"- if completedStatus == "cancelled" {- lastAction = "was just cancelled"- }- content = fmt.Sprintf(- "%sAll sub-issues are closed — the last one, [%s](mention://issue/%s) — \"%s\", %s.%s Continue the parent: synthesize the children's results and move it forward, or — if nothing remains — run `multica issue status %s in_review` to mark the parent ready for review.",- mentionPrefix, identifier, childID, title, lastAction, warning, parentID,- )- } else {- content = fmt.Sprintf(- "%sAll sub-issues are closed — they reached terminal states together in a batch update; most recently, [%s](mention://issue/%s) — \"%s\" — %s.%s Continue the parent: synthesize the children's results and move it forward, or — if nothing remains — run `multica issue status %s in_review` to mark the parent ready for review.",- mentionPrefix, identifier, childID, title, lastAction, warning, parentID,- )- }- }- }-- // author_type='system', author_id=zero UUID. The zero UUID is a valid 16- // byte value and the column is NOT NULL; frontend code should branch on- // author_type === 'system' rather than on the UUID value.- created, err := h.Queries.CreateComment(ctx, db.CreateCommentParams{- ID: dbid.NewV7(),- IssueID: parent.ID,- WorkspaceID: parent.WorkspaceID,- AuthorType: "system",- AuthorID: pgtype.UUID{Valid: true},- Content: content,- Type: "system",- ParentID: pgtype.UUID{Valid: false},- })- if err != nil {- slog.Warn("child done: create system comment failed",- "error", err,- "child_id", childID,- "parent_id", uuidToString(parent.ID))- return- }- comment := created.Comment()-- h.publish(protocol.EventCommentCreated, uuidToString(parent.WorkspaceID), "system", "", map[string]any{- "comment": commentToResponse(comment, nil, nil),- "issue_title": parent.Title,- "issue_assignee_type": textToPtr(parent.AssigneeType),- "issue_assignee_id": uuidToPtr(parent.AssigneeID),- "issue_status": parent.Status,- "issue_revision": created.IssueRevision,- })-- // Dispatch the explicit trigger / inbox row for the parent assignee.- // Listener-level mention parsing is intentionally NOT involved (the- // notification + subscriber listeners both short-circuit on- // author_type='system'); this keeps smuggled mentions from the child- // title inert and gives the platform a single place to apply the loop- // and idempotency guards.- h.dispatchParentAssigneeTrigger(ctx, parent, comment)-}--// isTerminalChildStatus reports whether a child issue status counts as-// "finished" for stage-barrier purposes. Cancelled counts as terminal: a-// cancelled sibling will never complete, so it must not hold a stage open.-//-// Takes a CANONICAL status. Callers that hold a raw `issue.status` must pass it-// through childStatusResolver first, so a custom status in the done or-// cancelled category closes a stage exactly like Done and Cancelled do.-func isTerminalChildStatus(status string) bool {- return status == "done" || status == "cancelled"-}--// childStatusResolver shares each workspace's catalog across the guards,-// sibling scans and progress summary of one completion notification pass.-// It must not outlive that pass: later notifications need a fresh catalog.-//-// Resolve without rewriting the issue rows, which also supply the original-// user-selected status to downstream rendering. Built-in keys need no I/O.-// Unlike display-oriented Resolver callers, this side-effecting path must-// reject unresolved custom keys: parent or sibling rows can be newer than the-// catalog snapshot. A miss must not bypass a parked/terminal parent's guard.-func (h *Handler) childStatusResolver(ctx context.Context) func(db.Issue) (string, error) {- resolvers := make(map[pgtype.UUID]*issuestatus.Resolver)- return func(c db.Issue) (string, error) {- if issuestatus.IsBuiltIn(c.Status) {- return c.Status, nil- }- resolver := resolvers[c.WorkspaceID]- if resolver == nil {- resolver = issuestatus.NewResolver(c.WorkspaceID)- resolvers[c.WorkspaceID] = resolver- }- status := resolver.Effective(ctx, h.issueStatusCatalog(), c.Status)- if err := resolver.Err(); err != nil {- return "", err- }- if !issuestatus.IsCategory(resolver.Category(ctx, h.issueStatusCatalog(), c.Status)) {- return "", fmt.Errorf("unresolved status %q in workspace %s", c.Status, uuidToString(c.WorkspaceID))- }- return status, nil- }-}--// resolvedChildStatuses keeps the canonical status of every child needed by-// the barrier and comment builders. Keeping the three-state information here-// (open / done / cancelled) prevents the reporting path from mistaking-// "terminal" for "done" while still letting the barrier ask its narrower-// terminality question.-type resolvedChildStatuses map[pgtype.UUID]string--func (s resolvedChildStatuses) status(child db.Issue) string {- return s[child.ID]-}--func (s resolvedChildStatuses) isTerminal(child db.Issue) bool {- return isTerminalChildStatus(s.status(child))-}--// resolveChildStatuses checks every status needed by the stage barrier and-// progress summary before either can produce a notification. Stored status-// keys stay untouched; the returned snapshot contains their canonical values.-func resolveChildStatuses(children []db.Issue, effective func(db.Issue) (string, error)) (resolvedChildStatuses, error) {- statuses := make(resolvedChildStatuses, len(children))- staged := siblingsAreStaged(children)- for _, child := range children {- if staged && !child.Stage.Valid {- continue // Neither stage helper considers unstaged siblings.- }- status, err := effective(child)- if err != nil {- return nil, fmt.Errorf("resolve child %s status %q: %w", uuidToString(child.ID), child.Status, err)- }- statuses[child.ID] = status- }- return statuses, nil-}--// siblingsAreStaged reports whether any child in the set carries an explicit-// stage. A set with no stages is treated as a single implicit stage.-func siblingsAreStaged(children []db.Issue) bool {- for _, c := range children {- if c.Stage.Valid {- return true- }- }- return false-}--// stageBarrierClosed reports whether the completion of `completed` closed a-// stage barrier among `children` — the full sibling set under one parent,-// already reflecting completed's terminal status.-//-// - Unstaged sibling set (no child carries a stage): a single implicit-// stage. The barrier closes only when every child is terminal — the "wake-// once when the last sub-issue finishes" default.-// - Staged sibling set: only children that carry a stage form stages.-// Unstaged children do NOT participate (matches migration 123: a NULL-// stage does not take part in staged grouping) — completing one closes-// nothing, and a non-terminal unstaged child never holds a stage open.-// The completed child's stage S closes when every *staged* child with-// stage <= S is terminal (frontier closure). Later stages are normally-// parked in `backlog`, so they cannot fire out of order; the caller's-// idempotency guard collapses any duplicate wake.-func stageBarrierClosed(children []db.Issue, completed db.Issue, isTerminal func(db.Issue) bool) bool {- if !siblingsAreStaged(children) {- for _, c := range children {- if !isTerminal(c) {- return false- }- }- return true- }- // Staged set: an unstaged completed child belongs to no stage, so it closes- // nothing.- if !completed.Stage.Valid {- return false- }- s := completed.Stage.Int32- for _, c := range children {- if !c.Stage.Valid {- continue // unstaged children are ignored by the frontier- }- if c.Stage.Int32 <= s && !isTerminal(c) {- return false- }- }- return true-}--// stageProgressSummary renders a compact per-stage breakdown for the-// child-done system comment. `done` counts only genuinely completed children;-// canonical `cancelled` children are surfaced separately. nextStage is the-// lowest stage above closedStage that still has non-terminal children, or 0-// when none remain. Unstaged children are skipped.-func stageProgressSummary(children []db.Issue, closedStage int32, statusOf func(db.Issue) string) (summary string, nextStage int32) {- type agg struct{ total, done, cancelled, terminal int }- byStage := map[int32]*agg{}- order := []int32{}- for _, c := range children {- if !c.Stage.Valid {- continue // unstaged children do not belong to any stage- }- s := c.Stage.Int32- a, ok := byStage[s]- if !ok {- a = &agg{}- byStage[s] = a- order = append(order, s)- }- a.total++- switch statusOf(c) {- case "done":- a.done++- a.terminal++- case "cancelled":- a.cancelled++- a.terminal++- }- }- sort.Slice(order, func(i, j int) bool { return order[i] < order[j] })- parts := make([]string, 0, len(order))- for _, s := range order {- a := byStage[s]- label := fmt.Sprintf("Stage %d: %d/%d done", s, a.done, a.total)- if a.cancelled > 0 {- label += fmt.Sprintf(", %d cancelled", a.cancelled)- }- if nextStage == 0 && s > closedStage && a.terminal < a.total {- nextStage = s- label += " (next)"- }- parts = append(parts, label)- }- return strings.Join(parts, "; "), nextStage-}--// countStageCancelled counts the cancelled children of one stage. The advance-// instruction reports the number rather than the fact, because the agent it is-// written for has to decide whether the next stage can start without that work:-// "2 sub-issues cancelled" is checkable against the layout, "includes cancelled-// items" is not.-func countStageCancelled(children []db.Issue, stage int32, statusOf func(db.Issue) string) int {- n := 0- for _, child := range children {- if child.Stage.Valid && child.Stage.Int32 == stage && statusOf(child) == "cancelled" {- n++- }- }- return n-}--// subIssueCount renders a sub-issue count with the right plural.-func subIssueCount(n int) string {- if n == 1 {- return "1 sub-issue"- }- return fmt.Sprintf("%d sub-issues", n)-}--// batchClosedScopeHasCancelled reports whether this batch newly cancelled work-// in any stage up to the highest closed stage represented by the aggregated-// notification. It reads stage/status from the final sibling snapshot, using-// the batch rows only as an ID set, so a concurrently moved child cannot make a-// stale stage number leak into the decision.-func batchClosedScopeHasCancelled(children, batchCompleted []db.Issue, closedStage int32, statusOf func(db.Issue) string) bool {- completedIDs := make(map[pgtype.UUID]struct{}, len(batchCompleted))- for _, child := range batchCompleted {- completedIDs[child.ID] = struct{}{}- }- for _, child := range children {- if _, ok := completedIDs[child.ID]; !ok {- continue- }- if child.Stage.Valid && child.Stage.Int32 <= closedStage && statusOf(child) == "cancelled" {- return true- }- }- return false-}--func anyCancelledChildren(children []db.Issue, statusOf func(db.Issue) string) bool {- for _, child := range children {- if statusOf(child) == "cancelled" {- return true- }- }- return false-}--// stageAdvanceInstruction returns the trailing instruction appended to a-// staged child-done system comment, given the next stage with pending work-// among the sub-issues that currently exist (nextStage, 0 = none).-//-// - nextStage > 0: a later stage with unfinished work already exists, so-// point the leader at it.-// - nextStage == 0: no later stage exists *among the sub-issues created so-// far*. This deliberately does NOT assert that the workflow is finished.-// The server has no declarative workflow model — stages are agent-driven-// and often created lazily (stage N+1's sub-issues are only written after-// stage N produces the inputs they depend on), so an intermediate stage in-// such a pipeline reaches nextStage == 0 exactly like a true final stage-// does. The old wording ("This was the final stage. Wrap up the parent")-// asserted a finality the server cannot know and pushed leaders to wrap up-// mid-workflow (MUL-4062 / #4927). The message now names both possibilities-// and hands the create-next-vs-wrap-up decision back to the leader.-// - stageCancelled: how many sub-issues of the stage this comment names were-// cancelled. Non-zero also means the headline above calls the stage-// `closed` rather than complete, so the instruction says "Closing" to-// match rather than contradicting its own comment with "Completing".-// - scopeCancelled: whether anything the update closed was cancelled, which-// for a batch includes lower stages that carry no count of their own. It-// decides whether the warning renders at all; stageCancelled decides-// whether the warning can be specific. The server still does not decide-// the dependency question itself either way.-func stageAdvanceInstruction(nextStage int32, parentID string, stageCancelled int, scopeCancelled bool) string {- var instruction string- if nextStage > 0 {- instruction = fmt.Sprintf(- " Stage %d is next. Review the full layout with `multica issue children %s`, and if Stage %d's dependencies are satisfied promote its `backlog` sub-issues to `todo` to continue. Read each sub-issue's description first and only promote items whose stated dependencies are already met — do not rely on this parent's higher-level breakdown alone. If a description conflicts with that breakdown, leave it `backlog` and post a comment to confirm first.",- nextStage, parentID, nextStage,- )- } else {- verb := "Completing"- if stageCancelled > 0 {- verb = "Closing"- }- instruction = fmt.Sprintf(" %s this stage does not mean the whole issue is done. Decide whether the issue is actually complete — if so, synthesize the results and run `multica issue status %s in_review` to mark the parent ready for review — or whether the next stage still needs to be created, in which case create that stage and its sub-issues now.", verb, parentID)- }- if !scopeCancelled {- return instruction- }- // Only the named stage has a count attached to it. A batch that also closed- // lower stages has no single stage to name, so it keeps the general warning- // rather than reporting a number that would not match any one stage.- if stageCancelled == 0 {- return instruction + " The just-closed work includes cancelled items: confirm that the cancelled work is not a dependency of whatever comes next before advancing. If unsure, do not promote or create the next stage yet; post a comment to confirm first."- }- if nextStage > 0 {- return instruction + fmt.Sprintf(" The stage that just closed has %s cancelled: confirm that the cancelled work is not something Stage %d depends on before advancing. If unsure, do not promote yet; post a comment to confirm first.", subIssueCount(stageCancelled), nextStage)- }- return instruction + fmt.Sprintf(" The stage that just closed has %s cancelled: confirm that the cancelled work is not a dependency of whatever comes next before advancing. If unsure, do not create the next stage yet; post a comment to confirm first.", subIssueCount(stageCancelled))-}--func unstagedCancellationInstruction() string {- return " Before moving the parent forward, confirm that the cancelled work is not required by whatever comes next. If unsure, leave the parent as-is and post a comment to confirm first."-}--// sanitizeChildTitleForSystemComment removes mention-style markdown from a-// child issue's title before it is embedded into the parent's system-// comment. Smuggled mentions are already harmless on the listener path-// (notification + subscriber listeners both skip system comments), but the-// timeline still renders the title verbatim — stripping the markdown keeps-// the rendered comment readable and stops a maliciously titled child issue-// from looking like a directive ("@all please look").-func sanitizeChildTitleForSystemComment(title string) string {- // Replace any markdown link target so the regex no longer matches it,- // while preserving the human-readable label text. `]` and `(` are the- // minimum delimiters of the mention regex; replacing the `(` is enough- // to break the match without mangling the label.- cleaned := strings.ReplaceAll(title, "](mention://", "] (mention-stripped://")- return cleaned-}--// buildParentAssigneeMention returns the markdown prefix that the system-// comment should lead with, including a trailing space, so the body reads-// like a normal mention-led comment. Returns the empty string when the-// parent has no assignee or the assignee row could not be loaded.-func (h *Handler) buildParentAssigneeMention(ctx context.Context, parent db.Issue) string {- if !parent.AssigneeType.Valid || !parent.AssigneeID.Valid {- return ""- }- label, ok := h.resolveAssigneeMentionLabel(ctx, parent.WorkspaceID, parent.AssigneeType.String, parent.AssigneeID)- if !ok {- return ""- }- return fmt.Sprintf("[@%s](mention://%s/%s) ", label, parent.AssigneeType.String, uuidToString(parent.AssigneeID))-}--// resolveAssigneeMentionLabel returns the label text to render inside the-// mention link. The label is for human display only — the mention regex-// keys off the URL path, not the label — but a sensible fallback keeps the-// rendered comment legible if the frontend has not pre-loaded the assignee.-// Returns ok=false when the assignee row cannot be loaded; the caller-// should then omit the mention entirely rather than emit a broken link.-func (h *Handler) resolveAssigneeMentionLabel(ctx context.Context, workspaceID pgtype.UUID, assigneeType string, assigneeID pgtype.UUID) (string, bool) {- switch assigneeType {- case "agent":- agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{- ID: assigneeID,- WorkspaceID: workspaceID,- })- if err != nil {- return "", false- }- return sanitizeMentionLabel(agent.Name), true- case "squad":- squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{- ID: assigneeID,- WorkspaceID: workspaceID,- })- if err != nil {- return "", false- }- return sanitizeMentionLabel(squad.Name), true- }- return "", false-}--// sanitizeMentionLabel strips characters that would break the mention-// markdown if a name contained them. The mention regex is non-greedy on the-// label, so a stray `]` would short-circuit it. Names with `]` are-// vanishingly rare but cheap to defend against.-func sanitizeMentionLabel(name string) string {- cleaned := strings.ReplaceAll(name, "]", "")- cleaned = strings.TrimSpace(cleaned)- if cleaned == "" {- return "assignee"- }- return cleaned-}--// dispatchParentAssigneeTrigger fires the explicit side effect that pairs-// with the @mention link in the system comment body — an agent task for-// agent or squad-leader assignees. Member assignees never reach this code-// path; notifyParentOfChildDone skips them outright. The generic comment-// listener is intentionally bypassed (it short-circuits on-// author_type='system'), so this is the single place where the platform-// applies the idempotency guard for the child-done notification.-//-// Side-effect semantics (intentionally narrower than a normal @mention):-// - agent parent: one EnqueueTaskForMention on the parent assignee, same-// trigger surface as a real @-mention so dedupe and readiness checks-// match what users already rely on.-// - squad parent: one EnqueueTaskForSquadLeader on the squad LEADER only.-// Unlike a human @squad mention, this does NOT fan out to squad members-// — child-done is a coordination signal, the leader decides whether-// and how to wake the rest of the squad. Documented here so reviewers-// don't read "system mention" as inheriting the full member fan-out. The-// actor that closed the child is irrelevant to routing: the target is the-// parent's own leader, chosen (and permission-checked) at squad-assign-// time, so no actor identity is threaded in — see triggerChildDoneSquad.-// - notification_preference is not consulted: this is a platform routing-// signal targeted at the assignee that already owns the parent, not a-// general notification. Per-user mute settings are evaluated by the-// downstream agent_task / inbox pipeline once the task is dispatched.-// - notification_listeners.go short-circuits on author_type='system', so-// subscriber emails and member-inbox rows from smuggled mentions in the-// child title are inert — only the explicit dispatch below runs.-//-// Guards applied here:-// - No-op when the parent has no assignee row.-// - NO self-trigger guard on either the agent OR the squad path. Waking the-// parent assignee when one of its children finishes is a serial sub-task-// handoff across two DIFFERENT issues, not a self-loop — legitimate per-// isAgentRunningOnIssue and the @mention self-trigger path-// (computeMentionedAgentCommentTriggers). The squad path used to skip a-// same-squad or shared-leader child on the theory that the leader had-// already observed the work through its own coordination cycle on the-// child. That stranded the common pattern where a squad decomposes its-// parent into sub-issues assigned to its own squad: the stage-barrier-// system comment lands on the PARENT carrying the "advance the next stage /-// wrap up" instruction, which a child-side wake never delivers — so the-// parent silently stalled in in_progress (MUL-3969). The squad path now-// mirrors the agent path (MUL-2808): always dispatch, bounded only by-// idempotency.-// - Idempotency: HasPendingTaskForIssueAndAgent dedupes rapid-fire enqueues-// for the same parent (e.g. two children finishing back-to-back). It also-// bounds any re-trigger, since a leader waking on the parent does not by-// itself push a child back into a terminal transition.-// - Readiness: archived agents / missing runtimes are silently skipped-// so a closed-out agent does not surface as a phantom assignee.-func (h *Handler) dispatchParentAssigneeTrigger(ctx context.Context, parent db.Issue, systemComment db.Comment) {- if !parent.AssigneeType.Valid || !parent.AssigneeID.Valid {- return- }-- switch parent.AssigneeType.String {- case "agent":- h.triggerChildDoneAgent(ctx, parent, systemComment.ID)- case "squad":- h.triggerChildDoneSquad(ctx, parent, systemComment.ID)- }-}--// triggerChildDoneAgent enqueues a mention-style task for the parent's-// agent assignee.-//-// There is intentionally NO same-agent self-trigger guard here, unlike the-// squad path. Waking the parent agent when one of its children finishes is a-// serial sub-task handoff between two DIFFERENT issues, which the platform-// loop model treats as legitimate ("not a loop and must fire" — see-// isAgentRunningOnIssue); only re-entering the SAME issue is a loop. A lone-// agent that decomposes its parent into sub-issues it owns itself has no-// other wake path, so the old "child owner == parent agent" guard silently-// stranded those parents (MUL-2808). Runaway re-triggering is prevented by-// the HasPendingTaskForIssueAndAgent dedup below, exactly as the @mention-// self-trigger path relies on it (see computeMentionedAgentCommentTriggers).-func (h *Handler) triggerChildDoneAgent(ctx context.Context, parent db.Issue, triggerCommentID pgtype.UUID) {- agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{- ID: parent.AssigneeID,- WorkspaceID: parent.WorkspaceID,- })- if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {- return- }-- hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{- IssueID: parent.ID,- AgentID: parent.AssigneeID,- // Key dedup on the reviewed head (TEN-356).- HeadSha: h.TaskService.ResolveIssueReviewSHAParam(ctx, parent.ID),- })- if err != nil || hasPending {- return- }-- if _, err := h.TaskService.EnqueueTaskForMention(ctx, parent, parent.AssigneeID, triggerCommentID, service.OriginDerived); err != nil {- slog.Warn("child done: enqueue parent agent task failed",- "error", err,- "parent_id", uuidToString(parent.ID),- "agent_id", uuidToString(parent.AssigneeID))- }-}--// triggerChildDoneSquad enqueues a leader-role task for the parent's squad-// assignee. It mirrors the agent path (see triggerChildDoneAgent) exactly:-//-// - NO self-trigger guard: even when the finished child is owned by the same-// squad or by another squad sharing this leader, the leader must still be-// woken on the PARENT to advance the next stage or wrap up. The prior-// same-squad / shared-leader guards assumed the leader had already observed-// the child via its own coordination cycle, but that wake lands on the-// CHILD and never carries the parent-level stage-barrier instruction, so it-// stranded the common "squad decomposes its parent into sub-issues assigned-// to its own squad" pattern (MUL-3969).-// - NO leader-invocation gate. Waking the parent's OWN squad leader on-// child-done is a coordination handoff on an issue the leader already owns,-// not a fresh invocation — invocation permission was already enforced when-// the parent was assigned to the squad (validateAssigneePair). The agent-// path has never gated this. Re-checking it here on behalf of the child's-// completer — an agent/system actor with no resolvable human originator —-// failed closed for the DEFAULT private leader, silently stranding every-// process-squad pipeline after its first stage while direct-to-leader-agent-// parents advanced fine (MUL-4063 / GH #4928). Removed so agent and squad-// child-done follow one path; if invocation permission is ever reintroduced-// it must be added to BOTH paths together.-//-// Re-triggering is bounded by the HasPendingTaskForIssueAndAgent idempotency-// check below, exactly as the agent path relies on it.-func (h *Handler) triggerChildDoneSquad(ctx context.Context, parent db.Issue, triggerCommentID pgtype.UUID) {- squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{- ID: parent.AssigneeID,- WorkspaceID: parent.WorkspaceID,- })- if err != nil {- return- }-- agent, err := h.Queries.GetAgent(ctx, squad.LeaderID)- if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {- return- }-- hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{- IssueID: parent.ID,- AgentID: squad.LeaderID,- // Key dedup on the reviewed head (TEN-356).- HeadSha: h.TaskService.ResolveIssueReviewSHAParam(ctx, parent.ID),- })- if err != nil || hasPending {- return- }-- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, parent, squad.LeaderID, squad.ID, triggerCommentID, service.OriginDerived); err != nil {- slog.Warn("child done: enqueue parent squad leader task failed",- "error", err,- "parent_id", uuidToString(parent.ID),- "squad_id", uuidToString(squad.ID),- "leader_id", uuidToString(squad.LeaderID))- }-}diff --git a/server/internal/handler/issue_child_done_batch_stage_test.go b/server/internal/handler/issue_child_done_batch_stage_test.godeleted file mode 100644index 080edd3d74..0000000000--- a/server/internal/handler/issue_child_done_batch_stage_test.go+++ /dev/null@@ -1,326 +0,0 @@-package handler--import (- "fmt"- "math"- "math/rand/v2"- "net/http"- "reflect"- "slices"- "strings"- "testing"-- "github.com/jackc/pgx/v5/pgtype"- "github.com/multica-ai/multica/server/internal/events"- "github.com/multica-ai/multica/server/internal/testutil"- db "github.com/multica-ai/multica/server/pkg/db/generated"- "github.com/multica-ai/multica/server/pkg/protocol"-)--// repeatedBatchStage is the pre-optimization staged selection loop. Keep the-// per-candidate scan here as an oracle and benchmark, not a production fallback.-func repeatedBatchStage(children, completed []db.Issue, terminal func(db.Issue) bool) (db.Issue, bool) {- var rep db.Issue- found := false- for _, c := range completed {- if !c.Stage.Valid || !stageBarrierClosed(children, c, terminal) {- continue- }- if !found || c.Stage.Int32 > rep.Stage.Int32 {- rep, found = c, true- }- }- return rep, found-}--func TestHighestClosedBatchStage(t *testing.T) {- for _, tc := range []struct {- name string- children []db.Issue- candidates []int- want int // Index in children, or -1 for no closed stage.- }{- {"empty", nil, nil, -1},- {"no_candidates", []db.Issue{child(1, "done")}, nil, -1},- {"same_stage_first_seen", []db.Issue{child(1, "done"), child(1, "cancelled")}, []int{1, 0, 1}, 1},- {"same_stage_open", []db.Issue{child(1, "done"), child(1, "in_progress")}, []int{0}, -1},- {"earlier_stage_open", []db.Issue{child(7, "done"), child(2, "backlog")}, []int{0}, -1},- {"later_stage_open", []db.Issue{child(7, "todo"), child(2, "cancelled")}, []int{1}, 1},- {"several_stages_close", []db.Issue{child(20, "done"), child(2, "done"), child(7, "cancelled"), child(20, "done")}, []int{1, 3, 2, 0}, 3},- {"only_lower_stage_in_batch", []db.Issue{child(2, "done"), child(7, "done")}, []int{0}, 0},- {"gap_before_open_stage", []db.Issue{child(20, "done"), child(2, "done"), child(7, "backlog")}, []int{0, 1}, 1},- {"ignore_unstaged_sibling", []db.Issue{child(0, "missing"), child(7, "cancelled")}, []int{1}, 1},- {"unstaged_closes_nothing", []db.Issue{child(7, "done"), child(0, "done")}, []int{1}, -1},- {"mixed_candidates", []db.Issue{child(0, "done"), child(7, "done"), child(2, "done")}, []int{0, 2, 1}, 1},- {"max_stage_closed", []db.Issue{child(math.MaxInt32, "done")}, []int{0}, 0},- {"max_stage_open", []db.Issue{child(math.MaxInt32, "backlog"), child(7, "done")}, []int{1}, 1},- {"zero_is_not_a_sentinel", []db.Issue{{Stage: pgtype.Int4{Int32: 0, Valid: true}, Status: "done"}, child(1, "todo")}, []int{0}, 0},- } {- t.Run(tc.name, func(t *testing.T) {- for i := range tc.children {- tc.children[i].Number = int32(i + 1)- }- var completed []db.Issue- for _, i := range tc.candidates {- completed = append(completed, tc.children[i])- }- terminal := func(c db.Issue) bool {- if !c.Stage.Valid {- t.Fatal("staged selection must not inspect an unresolved unstaged sibling")- }- return literalTerminalChild(c)- }- got, found := highestClosedBatchStage(tc.children, completed, terminal)- if found != (tc.want >= 0) || (found && !reflect.DeepEqual(got, tc.children[tc.want])) {- t.Fatalf("representative number=%d, found=%t; want child index %d", got.Number, found, tc.want)- }- old, oldFound := repeatedBatchStage(tc.children, completed, terminal)- if found != oldFound || (found && !reflect.DeepEqual(got, old)) {- t.Fatal("selection differs from the repeated-scan algorithm")- }- })- }-}--func TestHighestClosedBatchStageRandomizedEquivalence(t *testing.T) {- rng := rand.New(rand.NewPCG(23, 8192))- stages := []int32{0, 1, 2, 7, 20, math.MaxInt32}- statuses := []string{"backlog", "todo", "in_progress", "done", "cancelled"}- // The edge cases are pinned by TestHighestClosedBatchStage; 500 iterations- // retain strong coverage of uncommon combinations while keeping the- // quadratic oracle well below the old 2,000-iteration cost under -race.- for iteration := range 500 {- children := make([]db.Issue, rng.IntN(40))- for i := range children {- children[i] = child(stages[rng.IntN(len(stages))], statuses[rng.IntN(len(statuses))])- children[i].Number = int32(i + 1)- }- if len(children) > 0 {- children[0].Stage = pgtype.Int4{Int32: 1, Valid: true} // The production caller handles unstaged sets separately.- }- var completed []db.Issue- if len(children) > 0 {- for range rng.IntN(2*len(children) + 1) {- c := children[rng.IntN(len(children))]- c.Status = "done"- // Candidate rows precede the final sibling read: a concurrent- // edit may have changed a child's stage or reopened its status.- if rng.IntN(4) == 0 {- c.Stage = child(stages[rng.IntN(len(stages))], "done").Stage- }- completed = append(completed, c)- }- }- rng.Shuffle(len(children), func(i, j int) { children[i], children[j] = children[j], children[i] })- beforeChildren, beforeCompleted := slices.Clone(children), slices.Clone(completed)- got, found := highestClosedBatchStage(children, completed, literalTerminalChild)- want, wantFound := repeatedBatchStage(children, completed, literalTerminalChild)- if found != wantFound || (found && !reflect.DeepEqual(got, want)) {- t.Fatalf("iteration %d: got number=%d stage=%v found=%t; want number=%d stage=%v found=%t", iteration, got.Number, got.Stage, found, want.Number, want.Stage, wantFound)- }- if !reflect.DeepEqual(children, beforeChildren) || !reflect.DeepEqual(completed, beforeCompleted) {- t.Fatalf("iteration %d: selection mutated its input", iteration)- }- }-}--func TestHighestClosedBatchStageLinearWork(t *testing.T) {- // Exact probe counts pin linear against quadratic at any size; at 1000 the- // quadratic reference alone cost a million callbacks under -race.- for _, n := range []int{10, 100} {- t.Run(fmt.Sprint(n), func(t *testing.T) {- children := make([]db.Issue, n)- for i := range children {- children[i] = child(1, "done")- children[i].Number = int32(i + 1)- }- // Count actual in-memory sibling probes AFTER status resolution,- // not catalog calls (which #8192 already reduced to one per pass).- probes := 0- terminal := func(c db.Issue) bool { probes++; return literalTerminalChild(c) }- got, found := highestClosedBatchStage(children, children, terminal)- if !found || got.Number != 1 || probes != n {- t.Fatalf("number=%d found=%t probes=%d; want first child and %d probes", got.Number, found, probes, n)- }- probes = 0- repeatedBatchStage(children, children, terminal)- if probes != n*n {- t.Fatalf("baseline probes=%d, want %d", probes, n*n)- }- })- }-}--func TestHighestClosedBatchStageEarlyExit(t *testing.T) {- children := make([]db.Issue, 1000)- for i := range children {- children[i] = child(1, "done")- }- children[0].Status = "in_progress"- for _, completed := range [][]db.Issue{nil, {child(0, "done")}, children[1:2], children[1:3]} {- probes := 0- _, found := highestClosedBatchStage(children, completed, func(c db.Issue) bool {- probes++- return literalTerminalChild(c)- })- want := 0- if len(completed) > 0 && completed[0].Stage.Valid {- want = 1- }- if found || probes != want {- t.Fatalf("candidates=%v: found=%t probes=%d, want no closed stage and %d probes", completed, found, probes, want)- }- }-}--func TestBatchChildDonePreservesRepresentativeAndParentOrder(t *testing.T) {- for _, staged := range []bool{false, true} {- for _, status := range []string{"done", "cancelled", "approved", "wont_do"} {- t.Run(fmt.Sprintf("staged=%t/%s", staged, status), func(t *testing.T) {- ws := dbfx.Workspace(t, "Batch stage selection", "batch-stage-selection", testutil.Cols{"issue_prefix": "BST"})- fx := testutil.New(testPool, ws, testUserID)- fx.Member(t, ws, testUserID, "owner")- fx.Insert(t, "issue_status", testutil.Cols{"workspace_id": ws, "key": "approved", "name": "Approved", "category": "done", "color": "#123456"})- fx.Insert(t, "issue_status", testutil.Cols{"workspace_id": ws, "key": "wont_do", "name": "Won't Do", "category": "closed", "color": "#654321"})- var parents, agents []string- var children [][]string- for p := range 2 {- agent := fx.Agent(t, fmt.Sprintf("Parent agent %d", p), fx.Runtime(t, fmt.Sprintf("Runtime %d", p)))- parent := fx.Issue(t, "Parent", testutil.Cols{"status": "in_progress", "assignee_type": "agent", "assignee_id": agent})- parents, agents = append(parents, parent), append(agents, agent)- fx.Cleanup(t, "DELETE FROM comment WHERE issue_id = $1", parent)- fx.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id = $1", parent)- var ids []string- for _, stage := range []int{2, 7, 7} {- cols := testutil.Cols{"status": "in_progress", "parent_issue_id": parent}- if staged {- cols["stage"] = stage- }- ids = append(ids, fx.Issue(t, "Child", cols))- }- children = append(children, ids)- if staged {- fx.Issue(t, "Next stage", testutil.Cols{"status": "backlog", "parent_issue_id": parent, "stage": 20})- fx.Issue(t, "Unstaged unknown status", testutil.Cols{"status": "missing", "parent_issue_id": parent})- }- }- h := *testHandler- h.Bus = events.New()- var notified []string- h.Bus.Subscribe(protocol.EventCommentCreated, func(e events.Event) {- payload, ok := e.Payload.(map[string]any)- if !ok {- t.Errorf("unexpected comment payload %T", e.Payload)- return- }- comment, ok := payload["comment"].(CommentResponse)- if !ok {- t.Errorf("unexpected comment response %T", payload["comment"])- return- }- notified = append(notified, comment.IssueID)- })- // Interleave parents, visit higher stages before lower ones, and- // choose the second child in the highest stage first.- ids := []string{children[1][2], children[0][0], children[1][0], children[0][2], children[1][1], children[0][1]}- request := testutil.WithHeaders(testutil.JSONRequest(http.MethodPatch, "/api/issues/batch", map[string]any{- "issue_ids": ids, "updates": map[string]any{"status": status},- }), "X-User-ID", testUserID, "X-Workspace-ID", ws)- var response struct {- Updated int `json:"updated"`- }- testutil.Call(t, h.BatchUpdateIssues, request).Want(http.StatusOK).JSON(&response)- if response.Updated != len(ids) {- t.Fatalf("updated=%d, want %d", response.Updated, len(ids))- }- if !slices.Equal(notified, []string{parents[1], parents[0]}) {- t.Fatalf("notification order=%v, want second parent then first", notified)- }- cancelledLike := status == "cancelled" || status == "wont_do"- for p, parent := range parents {- if countSystemCommentsOn(t, parent) != 1 || countPendingTasksForAgent(t, parent, agents[p]) != 1 {- t.Fatal("each parent must receive exactly one comment and one pending run")- }- rep := children[p][2]- if !staged && p == 0 {- rep = children[p][0] // Unstaged groups retain their first completed child.- }- content, _, _, _ := systemCommentOn(t, parent)- if !strings.Contains(content, "together in a batch update") || !strings.Contains(content, "](mention://issue/"+rep+")") {- t.Fatalf("lost batch wording or first representative: %s", content)- }- if staged {- if cancelledLike {- if !strings.Contains(content, "Stage 7 of this issue is closed") ||- !strings.Contains(content, "Stage 2: 0/1 done, 1 cancelled; Stage 7: 0/2 done, 2 cancelled; Stage 20: 0/1 done (next)") ||- !strings.Contains(content, "Stage 20 is next") ||- !strings.Contains(content, "has 2 sub-issues cancelled") ||- !strings.Contains(content, "not something Stage 20 depends on") {- t.Fatalf("inaccurate cancelled-stage summary: %s", content)- }- } else if !strings.Contains(content, "Stage 7 of this issue is complete") || !strings.Contains(content, "Stage 2: 1/1 done; Stage 7: 2/2 done; Stage 20: 0/1 done (next)") || !strings.Contains(content, "Stage 20 is next") {- t.Fatalf("inaccurate final-state summary: %s", content)- }- }- if !staged {- if cancelledLike {- if !strings.Contains(content, "All sub-issues are closed") || !strings.Contains(content, "confirm that the cancelled work is not required") {- t.Fatalf("inaccurate unstaged cancellation summary: %s", content)- }- } else if !strings.Contains(content, "All sub-issues are complete") {- t.Fatalf("lost unstaged completion: %s", content)- }- }- if got, want := triggerCommentIDForAgentTask(t, parent, agents[p]), systemCommentIDOn(t, parent); got != want {- t.Fatalf("run trigger=%s, want final comment %s", got, want)- }- }- })- }- }-}--func BenchmarkBatchStageSelection(b *testing.B) {- for _, n := range []int{1, 10, 100, 1000, 10000} {- children := make([]db.Issue, n)- for i := range children {- children[i] = child(1, "done")- children[i].ID = parseUUID(fmt.Sprintf("00000000-0000-0000-0000-%012x", i+1))- }- completed := slices.Clone(children)- for _, shape := range []struct {- name string- count int- firstStatus string- want bool- }{- {"same_stage_all_complete", n, "done", true},- {"single_candidate", 1, "done", true},- {"first_sibling_reopened", n, "in_progress", false},- {"two_candidates_first_sibling_reopened", min(2, n), "in_progress", false},- } {- children[0].Status = shape.firstStatus- // Both algorithms use the same pre-resolved snapshot as production.- // Fixture construction and status resolution are outside the timed loop.- statuses, err := resolveChildStatuses(children, func(c db.Issue) (string, error) { return c.Status, nil })- if err != nil {- b.Fatal(err)- }- terminal := statuses.isTerminal- for _, tc := range []struct {- name string- pick func([]db.Issue, []db.Issue, func(db.Issue) bool) (db.Issue, bool)- }{{"repeated", repeatedBatchStage}, {"linear", highestClosedBatchStage}} {- b.Run(fmt.Sprintf("%s/N=%d/%s", shape.name, n, tc.name), func(b *testing.B) {- b.ReportAllocs()- for b.Loop() {- rep, found := tc.pick(children, completed[:shape.count], terminal)- if found != shape.want || (found && rep.ID != children[0].ID) {- b.Fatal("incorrect barrier or representative")- }- }- })- }- }- }-}diff --git a/server/internal/handler/issue_child_done_cancelled_batch_review_test.go b/server/internal/handler/issue_child_done_cancelled_batch_review_test.godeleted file mode 100644index 2534fdfb2a..0000000000--- a/server/internal/handler/issue_child_done_cancelled_batch_review_test.go+++ /dev/null@@ -1,69 +0,0 @@-package handler--import (- "context"- "encoding/json"- "net/http/httptest"- "strings"- "testing"- "time"-)--func TestBatchChildDoneNamedStageHistoricalCancellationStillWarns(t *testing.T) {- fx := newStagedBatchFixture(t)-- // Add a third Stage 2 child so one can already be cancelled while at least- // two remaining children transition to done together in the closing batch.- cw := httptest.NewRecorder()- creq := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "batch-stage historical-cancel child " + time.Now().Format(time.RFC3339Nano),- "status": "in_progress",- "parent_issue_id": fx.parent.ID,- })- testHandler.CreateIssue(cw, creq)- if cw.Code != 201 {- t.Fatalf("create extra child: expected 201, got %d: %s", cw.Code, cw.Body.String())- }- var extra IssueResponse- if err := json.NewDecoder(cw.Body).Decode(&extra); err != nil {- t.Fatalf("decode extra child: %v", err)- }- if _, err := testPool.Exec(context.Background(),- `UPDATE issue SET stage = $2 WHERE id = $1`, extra.ID, 2); err != nil {- t.Fatalf("set extra child stage: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, extra.ID)- })-- // This cancellation is historical by the time the later batch closes Stage 2.- // Stage 1 is still open, so it must not emit a parent completion comment yet.- batchSetStatus(t, []string{fx.stage2[0].ID}, "cancelled")- if got := countSystemCommentsOn(t, fx.parent.ID); got != 0 {- t.Fatalf("historical cancellation must not close the blocked stage, got %d comments", got)- }-- // Close Stage 1 and finish the two remaining Stage 2 children in one batch.- // The named Stage 2 already contains the cancelled child above, so the final- // advance instruction must still include the dependency-confirmation warning.- batchSetStatus(t, []string{- fx.stage1[0].ID,- fx.stage1[1].ID,- fx.stage2[1].ID,- extra.ID,- }, "done")-- if got := countSystemCommentsOn(t, fx.parent.ID); got != 1 {- t.Fatalf("expected exactly 1 final system comment, got %d", got)- }- content, _, _, _ := systemCommentOn(t, fx.parent.ID)- if !strings.Contains(content, "Stage 2 of this issue is closed") {- t.Errorf("expected Stage 2 closed announcement, got: %s", content)- }- if !strings.Contains(content, "Stage 2: 2/3 done, 1 cancelled") {- t.Errorf("expected final Stage 2 cancellation summary, got: %s", content)- }- if !strings.Contains(content, "confirm that the cancelled work is not a dependency") {- t.Errorf("expected cancellation dependency warning, got: %s", content)- }-}diff --git a/server/internal/handler/issue_child_done_cancelled_test.go b/server/internal/handler/issue_child_done_cancelled_test.godeleted file mode 100644index 1d5e11ae24..0000000000--- a/server/internal/handler/issue_child_done_cancelled_test.go+++ /dev/null@@ -1,158 +0,0 @@-package handler--import (- "strings"- "testing"-- "github.com/jackc/pgx/v5/pgtype"- db "github.com/multica-ai/multica/server/pkg/db/generated"-)--func TestStageProgressSummarySeparatesCancelledFromDone(t *testing.T) {- children := []db.Issue{- child(1, "done"),- child(2, "cancelled"), child(2, "cancelled"),- child(3, "backlog"),- }-- summary, next := stageProgressSummary(children, 2, literalChildStatus)- want := "Stage 1: 1/1 done; Stage 2: 0/2 done, 2 cancelled; Stage 3: 0/1 done (next)"- if summary != want {- t.Fatalf("summary = %q, want %q", summary, want)- }- if next != 3 {- t.Fatalf("nextStage = %d, want 3", next)- }-}--func TestResolvedChildStatusesKeepCanonicalCancelled(t *testing.T) {- doneID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}- cancelledID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}- children := []db.Issue{- {ID: doneID, Status: "approved", Stage: pgtype.Int4{Int32: 1, Valid: true}},- {ID: cancelledID, Status: "wont_do", Stage: pgtype.Int4{Int32: 1, Valid: true}},- }-- statuses, err := resolveChildStatuses(children, func(c db.Issue) (string, error) {- switch c.Status {- case "approved":- return "done", nil- case "wont_do":- return "cancelled", nil- default:- return c.Status, nil- }- })- if err != nil {- t.Fatal(err)- }- if got := statuses.status(children[1]); got != "cancelled" {- t.Fatalf("canonical status = %q, want cancelled", got)- }- if !statuses.isTerminal(children[1]) {- t.Fatal("canonical cancelled status must still close the barrier")- }-- summary, _ := stageProgressSummary(children, 1, statuses.status)- if want := "Stage 1: 1/2 done, 1 cancelled"; summary != want {- t.Fatalf("summary = %q, want %q", summary, want)- }-}--func TestBatchClosedScopeHasCancelled(t *testing.T) {- stage2Cancelled := child(2, "cancelled")- stage2Cancelled.ID = pgtype.UUID{Bytes: [16]byte{2}, Valid: true}- stage7Done := child(7, "done")- stage7Done.ID = pgtype.UUID{Bytes: [16]byte{7}, Valid: true}- stage20Cancelled := child(20, "cancelled")- stage20Cancelled.ID = pgtype.UUID{Bytes: [16]byte{20}, Valid: true}- children := []db.Issue{stage2Cancelled, stage7Done, stage20Cancelled}- statusOf := func(c db.Issue) string { return c.Status }-- t.Run("lower stage cancelled in the same batch warns", func(t *testing.T) {- if !batchClosedScopeHasCancelled(children, []db.Issue{stage2Cancelled, stage7Done}, 7, statusOf) {- t.Fatal("expected cancellation in a lower stage closed by the same batch to be reported")- }- })-- t.Run("later unopened stage cancellation is ignored", func(t *testing.T) {- if batchClosedScopeHasCancelled(children, []db.Issue{stage7Done, stage20Cancelled}, 7, statusOf) {- t.Fatal("a cancellation above the highest closed stage must not affect the current advance decision")- }- })-- t.Run("historical lower-stage cancellation is not repeated", func(t *testing.T) {- if batchClosedScopeHasCancelled(children, []db.Issue{stage7Done}, 7, statusOf) {- t.Fatal("a lower-stage cancellation outside this batch must not re-trigger the warning")- }- })-}--// A batch can close lower stages alongside the one the comment names. Those-// carry no count of their own, so the warning stays general rather than-// reporting a number that belongs to no single stage.-func TestStageAdvanceInstructionWarnsOnCancelledWork(t *testing.T) {- got := stageAdvanceInstruction(3, "parent-id", 0, true)- for _, want := range []string{- "Stage 3 is next",- "confirm that the cancelled work is not a dependency",- "do not promote or create the next stage yet",- "post a comment to confirm first",- } {- if !strings.Contains(got, want) {- t.Fatalf("instruction missing %q: %s", want, got)- }- }-}--// When the cancellations are in the stage this comment is about, the agent-// deciding whether to promote gets the two facts it can act on: how many-// sub-issues were cancelled, and which stage has to not depend on them.-func TestStageAdvanceInstructionNamesCountAndDependentStage(t *testing.T) {- got := stageAdvanceInstruction(3, "parent-id", 2, true)- for _, want := range []string{- "Stage 3 is next",- "has 2 sub-issues cancelled",- "not something Stage 3 depends on",- "post a comment to confirm first",- } {- if !strings.Contains(got, want) {- t.Fatalf("instruction missing %q: %s", want, got)- }- }- if strings.Contains(got, "includes cancelled items") {- t.Fatalf("named stage must not fall back to the general warning: %s", got)- }-}--func TestStageAdvanceInstructionSingularCancellation(t *testing.T) {- got := stageAdvanceInstruction(3, "parent-id", 1, true)- if !strings.Contains(got, "has 1 sub-issue cancelled") {- t.Fatalf("want singular sub-issue, got %q", got)- }- if strings.Contains(got, "1 sub-issues") {- t.Fatalf("plural leaked into the singular case: %s", got)- }-}--// The headline above this instruction calls a stage with cancelled work-// `closed`, not complete. With no next stage the instruction opens the very-// next sentence, so it has to use the same word.-func TestStageAdvanceInstructionSaysClosingWhenStageWasCancelled(t *testing.T) {- got := stageAdvanceInstruction(0, "parent-id", 2, true)- if !strings.Contains(got, "Closing this stage does not mean") {- t.Fatalf("want Closing to match the headline, got %q", got)- }- if strings.Contains(got, "Completing this stage") {- t.Fatalf("stage closed with cancelled work must not read as completed: %s", got)- }-}--// A lower stage cancelled by the same batch must not change the verb: the-// stage this comment names did complete.-func TestStageAdvanceInstructionKeepsCompletingForBatchScopeOnly(t *testing.T) {- got := stageAdvanceInstruction(0, "parent-id", 0, true)- if !strings.Contains(got, "Completing this stage does not mean") {- t.Fatalf("named stage completed, want Completing, got %q", got)- }-}diff --git a/server/internal/handler/issue_child_done_resolver_test.go b/server/internal/handler/issue_child_done_resolver_test.godeleted file mode 100644index 98870c46f6..0000000000--- a/server/internal/handler/issue_child_done_resolver_test.go+++ /dev/null@@ -1,517 +0,0 @@-package handler--import (- "context"- "errors"- "fmt"- "strings"- "testing"-- "github.com/jackc/pgx/v5/pgtype"- "github.com/multica-ai/multica/server/internal/issuestatus"- "github.com/multica-ai/multica/server/internal/testutil"- db "github.com/multica-ai/multica/server/pkg/db/generated"-)--type childDoneCatalog struct {- issuestatus.Querier- reads map[pgtype.UUID]int- pointReads int- fail bool- failNext map[pgtype.UUID]bool- afterRead func()-}--func (c *childDoneCatalog) ListIssueStatusEntries(ctx context.Context, arg db.ListIssueStatusEntriesParams) ([]db.IssueStatus, error) {- c.reads[arg.WorkspaceID]++- if c.failNext[arg.WorkspaceID] {- delete(c.failNext, arg.WorkspaceID)- return nil, errors.New("test transient catalog failure")- }- if c.fail {- return nil, errors.New("test catalog unavailable")- }- entries, err := c.Querier.ListIssueStatusEntries(ctx, arg)- if err == nil && c.afterRead != nil {- afterRead := c.afterRead- c.afterRead = nil- afterRead()- }- return entries, err-}--func (c *childDoneCatalog) GetIssueStatusEntryByKey(ctx context.Context, arg db.GetIssueStatusEntryByKeyParams) (db.IssueStatus, error) {- c.pointReads++- if c.fail {- return db.IssueStatus{}, errors.New("test catalog unavailable")- }- return c.Querier.GetIssueStatusEntryByKey(ctx, arg)-}--func TestChildDoneStatusResolver(t *testing.T) {- ctx := context.Background()- for _, batch := range []bool{false, true} {- for _, staged := range []bool{false, true} {- for _, mode := range []string{"custom", "builtins", "unknown", "unavailable"} {- t.Run(fmt.Sprintf("batch=%t/staged=%t/%s", batch, staged, mode), func(t *testing.T) {- catalog := &childDoneCatalog{Querier: testHandler.Queries, reads: map[pgtype.UUID]int{}, fail: mode == "unavailable"}- h := *testHandler- h.IssueStatusCatalog = catalog- var completed []db.Issue- type expectedParent struct {- id string- comments int- }- var parents []expectedParent- var workspaces []pgtype.UUID- for workspace := 0; workspace < 2; workspace++ {- ws := dbfx.Workspace(t, "Child resolver", fmt.Sprintf("child-resolver-%t-%t-%s-%d", batch, staged, mode, workspace), testutil.Cols{"issue_prefix": "CHD"})- workspaces = append(workspaces, parseUUID(ws))- fixture := testutil.New(testPool, ws, testUserID)- for key, category := range map[string]string{"approved": "done", "dropped": "closed", "review": "started"} {- if workspace == 1 && key == "approved" {- category = "started"- }- cols := testutil.Cols{"workspace_id": ws, "key": key, "name": key, "category": category, "color": "#123456"}- if key == "dropped" {- cols["archived_at"] = testutil.Raw("now()")- }- fixture.Insert(t, "issue_status", cols)- }- parentCount := 1- if batch {- parentCount = 2- }- for range parentCount {- parentStatus := "review"- statuses := []string{"approved", "dropped", "approved"}- wantComments := 0- if mode == "builtins" {- parentStatus = "in_progress"- statuses = []string{"done", "cancelled", "done"}- wantComments = 1- } else if mode == "custom" && workspace == 0 {- wantComments = 1- } else if mode == "unknown" {- statuses[0] = "missing"- }- parentID := fixture.Issue(t, "Resolver parent", testutil.Cols{"status": parentStatus})- parents = append(parents, expectedParent{parentID, wantComments})- for _, status := range statuses {- cols := testutil.Cols{"parent_issue_id": parentID, "status": status}- if staged {- cols["stage"] = 1- }- id := fixture.Issue(t, "Resolver child", cols)- row, err := h.Queries.GetIssue(ctx, parseUUID(id))- if err != nil {- t.Fatal(err)- }- completed = append(completed, row)- }- if staged {- fixture.Issue(t, "Parked next stage", testutil.Cols{"parent_issue_id": parentID, "status": "backlog", "stage": 2})- }- fixture.Cleanup(t, "DELETE FROM comment WHERE issue_id = $1", parentID)- }- if !batch {- last := completed[len(completed)-1]- prev := last- prev.Status = "in_progress"- h.notifyParentOfChildDone(ctx, prev, last)- }- }- if batch {- h.notifyParentsOfBatchChildDone(ctx, completed)- }- wantReads := 1- if mode == "builtins" {- wantReads = 0- }- for _, ws := range workspaces {- if got := catalog.reads[ws]; got != wantReads {- t.Errorf("workspace %s catalog reads = %d, want %d", uuidToString(ws), got, wantReads)- }- }- if catalog.pointReads != 0 {- t.Errorf("per-key reads = %d, want 0", catalog.pointReads)- }- for _, parent := range parents {- if got := countSystemCommentsOn(t, parent.id); got != parent.comments {- t.Errorf("parent %s comments = %d, want %d", parent.id, got, parent.comments)- }- if staged && parent.comments == 1 {- var content string- dbfx.QueryRow(t, "SELECT content FROM comment WHERE issue_id = $1 AND author_type = 'system'", parent.id).Scan(&content)- if !strings.Contains(content, "Stage 1") || !strings.Contains(content, "Stage 2") {- t.Errorf("lost stage progress: %s", content)- }- }- }- })- }- }- }-}--func TestChildStatusResolverRefreshesForNextPass(t *testing.T) {- ctx := context.Background()- ws := dbfx.Workspace(t, "Resolver refresh", "child-resolver-refresh")- catalog := &childDoneCatalog{Querier: testHandler.Queries, reads: map[pgtype.UUID]int{}}- h := *testHandler- h.IssueStatusCatalog = catalog- issue := db.Issue{WorkspaceID: parseUUID(ws), Status: "approved"}- first := h.childStatusResolver(ctx)- if _, err := first(issue); err == nil {- t.Fatal("unknown key must prevent side effects")- }- dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": ws, "key": "approved", "name": "Approved", "category": "done", "color": "#123456"})- if _, err := first(issue); err == nil {- t.Fatal("one pass must not refresh a missing key")- }- if got, err := h.childStatusResolver(ctx)(issue); got != "done" || err != nil {- t.Fatalf("next pass did not refresh: %q, err=%v", got, err)- }- if issue.Status != "approved" {- t.Fatal("resolver mutated the raw status")- }- if catalog.reads[issue.WorkspaceID] != 2 || catalog.pointReads != 0 {- t.Fatalf("catalog counts: %+v, point=%d", catalog.reads, catalog.pointReads)- }-}--func TestChildDoneCatalogSnapshotPredatesParent(t *testing.T) {- ctx := context.Background()- for _, batch := range []bool{false, true} {- for _, category := range []string{"unstarted", "done", "closed"} {- t.Run(fmt.Sprintf("batch=%t/%s", batch, category), func(t *testing.T) {- ws := dbfx.Workspace(t, "New parent status", "child-status-snapshot")- fx := testutil.New(testPool, ws, testUserID)- for key, category := range map[string]string{"working": "started", "parked": "unstarted"} {- fx.Insert(t, "issue_status", testutil.Cols{"workspace_id": ws, "key": key, "name": key, "category": category, "color": "#123456"})- }- agentID := fx.Agent(t, "Parent assignee", fx.Runtime(t, "Parent runtime"))- parentID := fx.Issue(t, "Parent", testutil.Cols{"status": "in_progress", "assignee_type": "agent", "assignee_id": agentID})- fx.Cleanup(t, "DELETE FROM comment WHERE issue_id = $1", parentID)- fx.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id = $1", parentID)- childID := fx.Issue(t, "Completed child", testutil.Cols{"parent_issue_id": parentID, "status": "done", "stage": 1})- fx.Issue(t, "Later stage", testutil.Cols{"parent_issue_id": parentID, "status": "backlog", "stage": 2})- child, err := testHandler.Queries.GetIssue(ctx, parseUUID(childID))- if err != nil {- t.Fatal(err)- }- previous := child- previous.Status = "working"- var completed []db.Issue- if batch {- // An earlier parent group loads the shared catalog before the- // affected parent row is read. This parked group stays silent.- firstParent := fx.Issue(t, "Earlier parked parent", testutil.Cols{"status": "parked"})- fx.Cleanup(t, "DELETE FROM comment WHERE issue_id = $1", firstParent)- firstID := fx.Issue(t, "Earlier completed child", testutil.Cols{"parent_issue_id": firstParent, "status": "done"})- first, err := testHandler.Queries.GetIssue(ctx, parseUUID(firstID))- if err != nil {- t.Fatal(err)- }- completed = append(completed, first)- }- completed = append(completed, child)- newKey := "new_" + category- catalog := &childDoneCatalog{- Querier: testHandler.Queries, reads: map[pgtype.UUID]int{},- afterRead: func() {- // Commit both changes after materializing the catalog rows,- // but before GetIssue reads the affected parent. No sleeps or- // read errors: only the snapshot is older than the parent row.- fx.Insert(t, "issue_status", testutil.Cols{"workspace_id": ws, "key": newKey, "name": newKey, "category": category, "color": "#123456"})- fx.Exec(t, "UPDATE issue SET status = $1 WHERE id = $2", newKey, parentID)- },- }- h := *testHandler- h.IssueStatusCatalog = catalog- if batch {- h.notifyParentsOfBatchChildDone(ctx, completed)- } else {- h.notifyParentOfChildDone(ctx, previous, child)- }- if catalog.afterRead != nil {- t.Fatal("test did not mutate the parent after the catalog read")- }- if got := countSystemCommentsOn(t, parentID); got != 0 {- t.Errorf("parent in newly created %s status received %d comments, want none", category, got)- }- if got := countPendingTasksForAgent(t, parentID, agentID); got != 0 {- t.Errorf("parent in newly created %s status received %d queued runs, want none", category, got)- }- if catalog.reads[parseUUID(ws)] != 1 || catalog.pointReads != 0 {- t.Errorf("snapshot miss must not re-read: catalog=%+v, point=%d", catalog.reads, catalog.pointReads)- }- parent, err := h.Queries.GetIssue(ctx, parseUUID(parentID))- if err != nil {- t.Fatal(err)- }- if parent.Status != newKey {- t.Errorf("stored parent status = %q, want %q", parent.Status, newKey)- }- })- }- }-}--func TestChildDoneUnknownStatusSkipsNotification(t *testing.T) {- ctx := context.Background()- for _, batch := range []bool{false, true} {- for _, tc := range []struct {- name, previous, current, parent string- siblingStage int- }{- {name: "previous_child", previous: "missing", current: "done", parent: "in_progress"},- {name: "current_child", previous: "in_progress", current: "missing", parent: "in_progress"},- {name: "parent", previous: "in_progress", current: "done", parent: "missing"},- {name: "deleted_parent_status", previous: "in_progress", current: "done", parent: "missing"},- {name: "stage_barrier", previous: "in_progress", current: "done", parent: "in_progress", siblingStage: 1},- {name: "progress_summary", previous: "in_progress", current: "done", parent: "in_progress", siblingStage: 2},- } {- if batch && (tc.previous == "missing" || tc.current == "missing") {- continue // Transition filtering belongs to BatchUpdateIssues, not its notifier.- }- t.Run(fmt.Sprintf("batch=%t/%s", batch, tc.name), func(t *testing.T) {- ws := dbfx.Workspace(t, "Unknown notification status", "child-status-unknown")- fx := testutil.New(testPool, ws, testUserID)- if tc.name == "deleted_parent_status" {- id := fx.Insert(t, "issue_status", testutil.Cols{"workspace_id": ws, "key": "missing", "name": "Deleted", "category": "unstarted", "color": "#123456"})- fx.Exec(t, "DELETE FROM issue_status WHERE id = $1", id)- }- agentID := fx.Agent(t, "Parent assignee", fx.Runtime(t, "Parent runtime"))- parentID := fx.Issue(t, "Parent", testutil.Cols{"status": tc.parent, "assignee_type": "agent", "assignee_id": agentID})- fx.Cleanup(t, "DELETE FROM comment WHERE issue_id = $1", parentID)- fx.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id = $1", parentID)- cols := testutil.Cols{"parent_issue_id": parentID, "status": tc.current}- if tc.siblingStage != 0 {- cols["stage"] = 1- fx.Issue(t, "Unknown-status sibling", testutil.Cols{"parent_issue_id": parentID, "status": "missing", "stage": tc.siblingStage})- }- childID := fx.Issue(t, "Completed child", cols)- child, err := testHandler.Queries.GetIssue(ctx, parseUUID(childID))- if err != nil {- t.Fatal(err)- }- previous := child- previous.Status = tc.previous- catalog := &childDoneCatalog{Querier: testHandler.Queries, reads: map[pgtype.UUID]int{}}- h := *testHandler- h.IssueStatusCatalog = catalog- if batch {- h.notifyParentsOfBatchChildDone(ctx, []db.Issue{child})- } else {- h.notifyParentOfChildDone(ctx, previous, child)- }- if got := countSystemCommentsOn(t, parentID); got != 0 {- t.Errorf("unknown status produced %d comments, want none", got)- }- if got := countPendingTasksForAgent(t, parentID, agentID); got != 0 {- t.Errorf("unknown status queued %d parent runs, want none", got)- }- if catalog.reads[parseUUID(ws)] != 1 || catalog.pointReads != 0 {- t.Errorf("unknown status triggered extra reads: catalog=%+v, point=%d", catalog.reads, catalog.pointReads)- }- stored, err := h.Queries.GetIssue(ctx, child.ID)- if err != nil {- t.Fatal(err)- }- if stored.Status != tc.current {- t.Errorf("notification changed committed child status to %q, want %q", stored.Status, tc.current)- }- })- }- }-}--func TestBatchChildDoneUnknownStatusIsolation(t *testing.T) {- ctx := context.Background()- ws := dbfx.Workspace(t, "Missing key", "child-missing-key")- otherWS := dbfx.Workspace(t, "Known key", "child-known-key")- for _, workspace := range []string{ws, otherWS} {- dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": workspace, "key": "working", "name": "Working", "category": "started", "color": "#123456"})- }- dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": otherWS, "key": "missing", "name": "Known elsewhere", "category": "started", "color": "#123456"})- cases := []struct {- workspace, status string- want int- }{- {ws, "missing", 0},- {ws, "working", 1}, // A missing key must not poison this workspace's valid catalog.- {ws, "in_progress", 1},- {otherWS, "missing", 1}, // The same key resolves independently in another workspace.- }- var completed []db.Issue- var parents, agents []string- for i, tc := range cases {- fx := testutil.New(testPool, tc.workspace, testUserID)- agentID := fx.Agent(t, fmt.Sprintf("Parent assignee %d", i), fx.Runtime(t, fmt.Sprintf("Parent runtime %d", i)))- parentID := fx.Issue(t, "Batch parent", testutil.Cols{"status": tc.status, "assignee_type": "agent", "assignee_id": agentID})- parents = append(parents, parentID)- agents = append(agents, agentID)- fx.Cleanup(t, "DELETE FROM comment WHERE issue_id = $1", parentID)- fx.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id = $1", parentID)- childID := fx.Issue(t, "Batch child", testutil.Cols{"parent_issue_id": parentID, "status": "done"})- child, err := testHandler.Queries.GetIssue(ctx, parseUUID(childID))- if err != nil {- t.Fatal(err)- }- completed = append(completed, child)- }- catalog := &childDoneCatalog{Querier: testHandler.Queries, reads: map[pgtype.UUID]int{}}- h := *testHandler- h.IssueStatusCatalog = catalog- h.notifyParentsOfBatchChildDone(ctx, completed)- for i, tc := range cases {- if got := countSystemCommentsOn(t, parents[i]); got != tc.want {- t.Errorf("group %d (%s): %d comments, want %d", i, tc.status, got, tc.want)- }- if got := countPendingTasksForAgent(t, parents[i], agents[i]); got != tc.want {- t.Errorf("group %d (%s): %d queued runs, want %d", i, tc.status, got, tc.want)- }- }- if catalog.reads[parseUUID(ws)] != 1 || catalog.reads[parseUUID(otherWS)] != 1 || catalog.pointReads != 0 {- t.Errorf("catalog counts: %+v, point=%d", catalog.reads, catalog.pointReads)- }-}--func TestChildDoneCatalogFailureSkipsNotification(t *testing.T) {- ctx := context.Background()- for _, batch := range []bool{false, true} {- for _, tc := range []struct {- name, previous, current, parent string- siblingStage int- }{- {name: "child_transition", previous: "working", current: "done", parent: "parked"},- {name: "child_cancellation", previous: "working", current: "cancelled", parent: "parked"},- {name: "parent_backlog", previous: "in_progress", current: "done", parent: "parked"},- {name: "parent_terminal", previous: "in_progress", current: "done", parent: "approved"},- {name: "stage_barrier", previous: "in_progress", current: "done", parent: "in_progress", siblingStage: 1},- {name: "progress_summary", previous: "in_progress", current: "done", parent: "in_progress", siblingStage: 2},- } {- if batch && tc.previous == "working" {- continue // The batch notifier receives already-collected transitions.- }- t.Run(fmt.Sprintf("batch=%t/%s", batch, tc.name), func(t *testing.T) {- ws := dbfx.Workspace(t, "Transient status read", "child-status-failure")- fx := testutil.New(testPool, ws, testUserID)- for key, category := range map[string]string{"working": "started", "parked": "unstarted", "approved": "done"} {- fx.Insert(t, "issue_status", testutil.Cols{"workspace_id": ws, "key": key, "name": key, "category": category, "color": "#123456"})- }- agentID := fx.Agent(t, "Parent assignee", fx.Runtime(t, "Parent runtime"))- parentID := fx.Issue(t, "Parent", testutil.Cols{"status": tc.parent, "assignee_type": "agent", "assignee_id": agentID})- fx.Cleanup(t, "DELETE FROM comment WHERE issue_id = $1", parentID)- fx.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id = $1", parentID)- childCols := testutil.Cols{"parent_issue_id": parentID, "status": tc.current}- if tc.siblingStage != 0 {- childCols["stage"] = 1- fx.Issue(t, "Custom-status sibling", testutil.Cols{"parent_issue_id": parentID, "status": "approved", "stage": tc.siblingStage})- }- childID := fx.Issue(t, "Completed child", childCols)- child, err := testHandler.Queries.GetIssue(ctx, parseUUID(childID))- if err != nil {- t.Fatal(err)- }- previous := child- previous.Status = tc.previous- catalog := &childDoneCatalog{- Querier: testHandler.Queries, reads: map[pgtype.UUID]int{},- failNext: map[pgtype.UUID]bool{parseUUID(ws): true},- }- h := *testHandler- h.IssueStatusCatalog = catalog- notify := func() {- if batch {- h.notifyParentsOfBatchChildDone(ctx, []db.Issue{child})- } else {- h.notifyParentOfChildDone(ctx, previous, child)- }- }- notify()- if got := countSystemCommentsOn(t, parentID); got != 0 {- t.Errorf("failed catalog read posted %d comments, want none", got)- }- if got := countPendingTasksForAgent(t, parentID, agentID); got != 0 {- t.Errorf("failed catalog read queued %d parent runs, want none", got)- }- if got := catalog.reads[parseUUID(ws)]; got != 1 {- t.Errorf("failed pass made %d catalog reads, want 1", got)- }- // A subsequent notification pass gets a fresh catalog. This is not an- // automatic retry of the already-committed child status update.- notify()- want := 0- if tc.parent == "in_progress" || tc.parent == "parked" {- want = 1- }- if got := countSystemCommentsOn(t, parentID); got != want {- t.Errorf("after recovery: %d comments, want %d", got, want)- }- if got := countPendingTasksForAgent(t, parentID, agentID); got != want {- t.Errorf("after recovery: %d parent runs, want %d", got, want)- }- if catalog.reads[parseUUID(ws)] != 2 || catalog.pointReads != 0 {- t.Errorf("catalog counts: %+v, point=%d", catalog.reads, catalog.pointReads)- }- })- }- }-}--func TestBatchChildDoneCatalogFailureIsolation(t *testing.T) {- ctx := context.Background()- failedWS := dbfx.Workspace(t, "Failed catalog", "child-failed-catalog")- healthyWS := dbfx.Workspace(t, "Healthy catalog", "child-healthy-catalog")- for _, ws := range []string{failedWS, healthyWS} {- fx := testutil.New(testPool, ws, testUserID)- for key, category := range map[string]string{"working": "started", "parked": "unstarted"} {- fx.Insert(t, "issue_status", testutil.Cols{"workspace_id": ws, "key": key, "name": key, "category": category, "color": "#123456"})- }- }- cases := []struct {- workspace, status string- want int- }{- {failedWS, "working", 0}, // First read fails; skip this parent.- {failedWS, "parked", 0}, // Cached failure must not bypass this guard.- {healthyWS, "working", 1},- {failedWS, "in_progress", 1}, // Built-in-only groups need no catalog.- }- var completed []db.Issue- var parents []string- for _, tc := range cases {- fx := testutil.New(testPool, tc.workspace, testUserID)- parentID := fx.Issue(t, "Batch parent", testutil.Cols{"status": tc.status})- parents = append(parents, parentID)- fx.Cleanup(t, "DELETE FROM comment WHERE issue_id = $1", parentID)- childID := fx.Issue(t, "Batch child", testutil.Cols{"parent_issue_id": parentID, "status": "done"})- child, err := testHandler.Queries.GetIssue(ctx, parseUUID(childID))- if err != nil {- t.Fatal(err)- }- completed = append(completed, child)- }- catalog := &childDoneCatalog{- Querier: testHandler.Queries, reads: map[pgtype.UUID]int{},- failNext: map[pgtype.UUID]bool{parseUUID(failedWS): true},- }- h := *testHandler- h.IssueStatusCatalog = catalog- h.notifyParentsOfBatchChildDone(ctx, completed)- for i, tc := range cases {- if got := countSystemCommentsOn(t, parents[i]); got != tc.want {- t.Errorf("group %d (%s): %d comments, want %d", i, tc.status, got, tc.want)- }- }- for _, ws := range []string{failedWS, healthyWS} {- if got := catalog.reads[parseUUID(ws)]; got != 1 {- t.Errorf("workspace %s made %d catalog reads, want 1", ws, got)- }- }- if catalog.pointReads != 0 {- t.Errorf("per-key reads = %d, want 0", catalog.pointReads)- }-}diff --git a/server/internal/handler/issue_child_done_stage_test.go b/server/internal/handler/issue_child_done_stage_test.godeleted file mode 100644index 3d9b7f43e3..0000000000--- a/server/internal/handler/issue_child_done_stage_test.go+++ /dev/null@@ -1,243 +0,0 @@-package handler--import (- "strings"- "testing"-- "github.com/jackc/pgx/v5/pgtype"- db "github.com/multica-ai/multica/server/pkg/db/generated"-)--// child builds a sibling row with the given stage (0 = unstaged/NULL) and-// status, the only two fields the stage-barrier logic reads.-func child(stage int32, status string) db.Issue {- c := db.Issue{Status: status}- if stage != 0 {- c.Stage = pgtype.Int4{Int32: stage, Valid: true}- }- return c-}--func TestStageBarrierClosed_Unstaged(t *testing.T) {- tests := []struct {- name string- children []db.Issue- want bool- }{- {- name: "last child still leaves a sibling open",- children: []db.Issue{child(0, "done"), child(0, "in_progress")},- want: false,- },- {- name: "every child terminal closes the single implicit stage",- children: []db.Issue{child(0, "done"), child(0, "done")},- want: true,- },- {- name: "a backlog sibling holds the barrier open (no surprise cascade)",- children: []db.Issue{child(0, "done"), child(0, "backlog")},- want: false,- },- {- name: "cancelled counts as terminal",- children: []db.Issue{child(0, "done"), child(0, "cancelled")},- want: true,- },- }- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- // completed is one of the terminal children; identity doesn't matter- // for the unstaged path.- if got := stageBarrierClosed(tt.children, child(0, "done"), literalTerminalChild); got != tt.want {- t.Fatalf("stageBarrierClosed = %v, want %v", got, tt.want)- }- })- }-}--func TestStageBarrierClosed_Staged(t *testing.T) {- // Three stages: 1 has two children, 2 has two, 3 has one.- t.Run("stage 1 not fully done does not fire", func(t *testing.T) {- children := []db.Issue{- child(1, "done"), child(1, "in_progress"),- child(2, "backlog"), child(2, "backlog"),- child(3, "backlog"),- }- if stageBarrierClosed(children, child(1, "done"), literalTerminalChild) {- t.Fatal("expected barrier not closed while stage 1 has an open child")- }- })-- t.Run("closing stage 1 fires even though later stages are parked", func(t *testing.T) {- children := []db.Issue{- child(1, "done"), child(1, "done"),- child(2, "backlog"), child(2, "backlog"),- child(3, "backlog"),- }- if !stageBarrierClosed(children, child(1, "done"), literalTerminalChild) {- t.Fatal("expected stage 1 barrier to close")- }- })-- t.Run("closing stage 2 fires when stages 1 and 2 are terminal", func(t *testing.T) {- children := []db.Issue{- child(1, "done"), child(1, "done"),- child(2, "done"), child(2, "done"),- child(3, "backlog"),- }- if !stageBarrierClosed(children, child(2, "done"), literalTerminalChild) {- t.Fatal("expected stage 2 barrier to close")- }- })-- t.Run("final stage closes once its child finishes", func(t *testing.T) {- children := []db.Issue{- child(1, "done"), child(1, "done"),- child(2, "done"), child(2, "done"),- child(3, "done"),- }- if !stageBarrierClosed(children, child(3, "done"), literalTerminalChild) {- t.Fatal("expected final stage barrier to close")- }- })-}--func TestStageProgressSummary(t *testing.T) {- children := []db.Issue{- child(1, "done"), child(1, "done"), child(1, "done"),- child(2, "backlog"), child(2, "backlog"), child(2, "backlog"), child(2, "backlog"),- child(3, "backlog"), child(3, "backlog"),- }- summary, next := stageProgressSummary(children, 1, literalChildStatus)- want := "Stage 1: 3/3 done; Stage 2: 0/4 done (next); Stage 3: 0/2 done"- if summary != want {- t.Fatalf("summary = %q, want %q", summary, want)- }- if next != 2 {- t.Fatalf("nextStage = %d, want 2", next)- }-}--func TestStageProgressSummary_FinalStageNoNext(t *testing.T) {- children := []db.Issue{- child(1, "done"), child(1, "done"),- child(2, "done"),- }- _, next := stageProgressSummary(children, 2, literalChildStatus)- if next != 0 {- t.Fatalf("nextStage = %d, want 0 (no further stages)", next)- }-}--func TestStageProgressSummary_SkipsUnstaged(t *testing.T) {- // An unstaged child must not appear as "Stage 0" nor inflate any stage.- children := []db.Issue{- child(0, "backlog"), // unstaged — ignored- child(1, "done"), child(1, "done"),- child(2, "backlog"),- }- summary, next := stageProgressSummary(children, 1, literalChildStatus)- want := "Stage 1: 2/2 done; Stage 2: 0/1 done (next)"- if summary != want {- t.Fatalf("summary = %q, want %q", summary, want)- }- if next != 2 {- t.Fatalf("nextStage = %d, want 2", next)- }-}--// stageAdvanceInstruction must point at a known next stage when one exists,-// and — the core of MUL-4062 — must NOT assert finality when no later stage-// exists yet, because a lazily-created intermediate stage reaches nextStage==0-// exactly like a true final stage does.-func TestStageAdvanceInstruction(t *testing.T) {- const parentID = "parent-uuid"-- t.Run("a known next stage points the leader at it", func(t *testing.T) {- got := stageAdvanceInstruction(3, parentID, 0, false)- if !strings.Contains(got, "Stage 3 is next") {- t.Fatalf("expected next-stage instruction, got %q", got)- }- })-- t.Run("no created next stage does not assert finality", func(t *testing.T) {- got := stageAdvanceInstruction(0, parentID, 0, false)- // Regression guard for MUL-4062: an intermediate stage in a lazily- // created workflow also reaches nextStage==0, so the message must not- // claim this was definitively the final stage.- if strings.Contains(got, "This was the final stage") {- t.Fatalf("must not assert finality when the workflow shape is unknown, got %q", got)- }- // It must make clear that finishing the stage != the whole issue is- // done, and hand both paths (wrap up / create the next stage) to the- // leader. The explicit in_review command marks the wrap-up moment;- // the write itself is authorized by the standing status-ownership- // grant (MUL-6300), not by this ask.- if !strings.Contains(got, "does not mean the whole issue is done") {- t.Fatalf("expected stage-done != issue-done framing, got %q", got)- }- if !strings.Contains(got, "next stage") {- t.Fatalf("expected create-next-stage guidance, got %q", got)- }- if !strings.Contains(got, "multica issue status "+parentID+" in_review") {- t.Fatalf("expected explicit in_review instruction for confirmed completion, got %q", got)- }- })-}--// A stage can close because its last open child is *cancelled*, not only-// done — a cancelled sibling never finishes, so it must not hold the stage open.-func TestStageBarrierClosed_CancelledClosesStage(t *testing.T) {- t.Run("staged: cancelling the last open child closes the stage", func(t *testing.T) {- children := []db.Issue{- child(1, "done"), child(1, "cancelled"),- child(2, "backlog"),- }- if !stageBarrierClosed(children, child(1, "cancelled"), literalTerminalChild) {- t.Fatal("expected the stage to close when its last open child is cancelled")- }- })- t.Run("unstaged: cancel of the last open child closes the implicit stage", func(t *testing.T) {- children := []db.Issue{child(0, "done"), child(0, "cancelled")}- if !stageBarrierClosed(children, child(0, "cancelled"), literalTerminalChild) {- t.Fatal("expected the implicit stage to close on cancel")- }- })-}--// In a staged set, unstaged children do not participate in the frontier:-// they neither hold a stage open nor close anything on their own completion.-func TestStageBarrierClosed_UnstagedIgnoredInStagedSet(t *testing.T) {- t.Run("a non-terminal unstaged child does not block stage 1", func(t *testing.T) {- children := []db.Issue{- child(1, "done"), child(1, "done"),- child(0, "backlog"), // unstaged, still open — must NOT block- }- if !stageBarrierClosed(children, child(1, "done"), literalTerminalChild) {- t.Fatal("expected stage 1 to close; an unstaged child must not hold it open")- }- })- t.Run("completing an unstaged child in a staged set closes nothing", func(t *testing.T) {- children := []db.Issue{- child(1, "backlog"),- child(0, "done"), // the just-completed unstaged child- }- if stageBarrierClosed(children, child(0, "done"), literalTerminalChild) {- t.Fatal("an unstaged child's completion must not fire a stage barrier")- }- })-}--func literalChildStatus(c db.Issue) string {- return c.Status-}--// literalTerminalChild is the pre-MUL-6243 terminal test: it reads the status-// literal directly, with no catalog resolution. The stage-barrier logic these-// tests cover is pure and operates on CANONICAL statuses, so pinning it with a-// literal predicate keeps them testing the barrier itself rather than status-// resolution (which has its own coverage in issue_status_test.go).-func literalTerminalChild(c db.Issue) bool {- return isTerminalChildStatus(c.Status)-}diff --git a/server/internal/handler/issue_child_done_test.go b/server/internal/handler/issue_child_done_test.goindex 1613f11387..2ed1f75a7d 100644--- a/server/internal/handler/issue_child_done_test.go+++ b/server/internal/handler/issue_child_done_test.go@@ -3,16 +3,21 @@ package handlerimport ("context""encoding/json"+ "fmt""net/http""net/http/httptest""strings""testing""time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil")-// childDoneFixture creates a parent + child pair so the parent-notification-// tests can drive the child's status changes independently. Cleanup is-// registered on the test so the rows are removed even on test failure.+// childDoneFixture creates a parent + child pair so the child_done system rule+// tests can drive the child's status changes independently. Cleanup removes+// everything the rule writes, even on test failure.type childDoneFixture struct {parent IssueResponsechild IssueResponse@@ -34,6 +39,7 @@ func newChildDoneFixture(t *testing.T, parentStatus string) childDoneFixture {if err := json.NewDecoder(w.Body).Decode(&parent); err != nil {t.Fatalf("decode parent: %v", err)}+ t.Cleanup(func() { cleanupChildDoneIssue(parent.ID) })w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{@@ -49,17 +55,26 @@ func newChildDoneFixture(t *testing.T, parentStatus string) childDoneFixture {if err := json.NewDecoder(w.Body).Decode(&child); err != nil {t.Fatalf("decode child: %v", err)}-- t.Cleanup(func() {- ctx := context.Background()- // Cascades through comment.- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, child.ID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, parent.ID)- })+ t.Cleanup(func() { cleanupChildDoneIssue(child.ID) })return childDoneFixture{parent: parent, child: child}}+func cleanupChildDoneIssue(id string) {+ ctx := context.Background()+ for _, sql := range []string{+ `DELETE FROM agent_task_queue WHERE issue_id = $1`,+ `DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id = $1)`,+ `DELETE FROM issue_wakeup WHERE issue_id = $1`,+ `DELETE FROM issue_child_event WHERE parent_id = $1 OR child_id = $1`,+ `DELETE FROM inbox_item WHERE issue_id = $1`,+ `DELETE FROM activity_log WHERE issue_id = $1`,+ `DELETE FROM issue WHERE id = $1`,+ } {+ testPool.Exec(ctx, sql, id)+ }+}+// updateChildStatus drives an UpdateIssue HTTP call against the child issue.func updateChildStatus(t *testing.T, childID, status string) {t.Helper()@@ -73,493 +88,471 @@ func updateChildStatus(t *testing.T, childID, status string) {}}-// countSystemCommentsOn returns the number of platform-generated comments on-// the given issue. The schema CHECK was widened in migration 107 to allow-// author_type='system'; this query is the canary that the migration applied-// and the helper inserts with the right author identity.-func countSystemCommentsOn(t *testing.T, issueID string) int {+// setIssueAssigneeDirect writes the assignee columns directly, without the+// assignment trigger's side effects. The rule reads the parent's assignee when+// it fires, so this is enough to drive each target type.+func setIssueAssigneeDirect(t *testing.T, issueID, assigneeType, assigneeID string) {t.Helper()- var n int+ if _, err := testPool.Exec(context.Background(),+ `UPDATE issue SET assignee_type = $2, assignee_id = $3 WHERE id = $1`,+ issueID, assigneeType, assigneeID,+ ); err != nil {+ t.Fatalf("set parent assignee: %v", err)+ }+}++func handlerTestAgentID(t *testing.T) string {+ t.Helper()+ var agentID stringif err := testPool.QueryRow(context.Background(),- `SELECT count(*) FROM comment WHERE issue_id = $1 AND author_type = 'system'`,- issueID,- ).Scan(&n); err != nil {- t.Fatalf("count system comments: %v", err)+ `SELECT id FROM agent WHERE workspace_id = $1 AND name = $2`,+ testWorkspaceID, "Handler Test Agent",+ ).Scan(&agentID); err != nil {+ t.Fatalf("locate test agent: %v", err)}- return n+ return agentID}-func systemCommentOn(t *testing.T, issueID string) (content, authorIDStr string, parentNull bool, typeStr string) {+func countPendingTasksForAgent(t *testing.T, issueID, agentID string) int {t.Helper()- row := testPool.QueryRow(context.Background(),- `SELECT content, author_id::text, parent_id IS NULL, type- FROM comment- WHERE issue_id = $1 AND author_type = 'system'- ORDER BY created_at DESC- LIMIT 1`,- issueID)- if err := row.Scan(&content, &authorIDStr, &parentNull, &typeStr); err != nil {- t.Fatalf("read system comment: %v", err)- }- return+ return dbfx.Count(t, `SELECT count(*) FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running')`, issueID, agentID)}-// TestChildDoneNotifiesParent — the happy path for an unassigned parent. A-// child transitioning from a non-done status into `done` while its parent is-// open must produce exactly one top-level platform-generated comment on the-// parent. The comment must reference the child by its workspace-specific-// identifier (NOT a hardcoded `MUL-` prefix — that was the bug PR #2918-// review called out). When the parent has no assignee, the body must NOT-// carry any agent/member/squad mention either; the assignee-mention is the-// only mention we ever inject (see MUL-2538 Option C — covered separately-// in TestChildDoneMentionsParentAssignee_* below).-func TestChildDoneNotifiesParent(t *testing.T) {- fx := newChildDoneFixture(t, "in_progress")+func countInboxItems(t *testing.T, recipientUserID, issueID string) int {+ t.Helper()+ return dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE recipient_id = $1 AND issue_id = $2`, recipientUserID, issueID)+}- updateChildStatus(t, fx.child.ID, "done")+// childDoneEntry is one timeline entry the rule wrote on the parent.+type childDoneEntry struct {+ Stage *int32 `json:"stage"`+ Total int `json:"total"`+ Outcome string `json:"outcome"`+ TargetType string `json:"target_type"`+ TargetID string `json:"target_id"`+ TaskID string `json:"task_id"`+}- if got := countSystemCommentsOn(t, fx.parent.ID); got != 1 {- t.Fatalf("expected exactly 1 system comment on parent, got %d", got)+func childDoneEntries(t *testing.T, parentID string) []childDoneEntry {+ t.Helper()+ rows, err := testPool.Query(context.Background(), `SELECT details FROM activity_log+ WHERE issue_id = $1 AND action = 'wakeup_triggered' AND details->>'rule' = 'child_done'+ ORDER BY created_at, id`, parentID)+ if err != nil {+ t.Fatalf("read child_done entries: %v", err)+ }+ defer rows.Close()+ entries := []childDoneEntry{}+ for rows.Next() {+ var raw []byte+ var entry childDoneEntry+ if err := rows.Scan(&raw); err != nil {+ t.Fatal(err)+ }+ if err := json.Unmarshal(raw, &entry); err != nil {+ t.Fatal(err)+ }+ entries = append(entries, entry)}- content, authorID, parentNull, typeStr := systemCommentOn(t, fx.parent.ID)+ return entries+}- if !parentNull {- t.Errorf("system comment must be top-level (parent_id IS NULL)")- }- if typeStr != "system" {- t.Errorf("system comment type should be 'system', got %q", typeStr)- }- if authorID != "00000000-0000-0000-0000-000000000000" {- t.Errorf("system comment author_id should be the zero UUID sentinel, got %q", authorID)- }+type childDoneRunRow struct {+ ID, AgentID, SquadID, Note, Status, WakeupID string+ Leader bool+}- // Identifier substring must use the real workspace prefix (HAN-, seeded- // in TestMain), never MUL-.- if !strings.Contains(content, fx.child.Identifier) {- t.Errorf("expected comment to contain child identifier %q, got: %s", fx.child.Identifier, content)+// childDoneRuns lists the runs the parent's rule started, oldest first.+func childDoneRuns(t *testing.T, parentID string) []childDoneRunRow {+ t.Helper()+ rows, err := testPool.Query(context.Background(), `SELECT id::text, agent_id::text, COALESCE(squad_id::text, ''),+ COALESCE(handoff_note, ''), status, context->>'wakeup_id', COALESCE(is_leader_task, false)+ FROM agent_task_queue WHERE issue_id = $1 AND context->>'wakeup_system' = 'child_done'+ ORDER BY created_at, id`, parentID)+ if err != nil {+ t.Fatalf("read child_done runs: %v", err)+ }+ defer rows.Close()+ runs := []childDoneRunRow{}+ for rows.Next() {+ var r childDoneRunRow+ if err := rows.Scan(&r.ID, &r.AgentID, &r.SquadID, &r.Note, &r.Status, &r.WakeupID, &r.Leader); err != nil {+ t.Fatal(err)+ }+ runs = append(runs, r)}- if strings.Contains(content, "MUL-") {- t.Errorf("comment must not hardcode MUL- prefix, got: %s", content)+ return runs+}++// runWakeupTick is one scheduler pass over ready wakeups.+func runWakeupTick(t *testing.T) {+ t.Helper()+ if err := (&service.IssueWakeupService{Tasks: testHandler.TaskService}).Tick(context.Background()); err != nil {+ t.Logf("wakeup tick: %v", err)}+}++// The parent's agent is woken by an ordinary wakeup run: the platform's+// instruction and the stage facts ride in its [WAKEUP] block, and the+// timeline entry names the run.+func TestChildDoneWakesAgentAssignee(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ agentID := handlerTestAgentID(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)- // The comment must contain the safe issue mention. With no parent- // assignee, none of the routing mentions should appear either.- if !strings.Contains(content, "mention://issue/"+fx.child.ID) {- t.Errorf("expected mention://issue/<child-id> link in comment, got: %s", content)+ updateChildStatus(t, fx.child.ID, "done")++ runs := childDoneRuns(t, fx.parent.ID)+ if len(runs) != 1 || runs[0].AgentID != agentID || runs[0].Leader || runs[0].WakeupID == "" {+ t.Fatalf("runs = %+v, want one run for the parent's agent", runs)}- for _, banned := range []string{"mention://agent/", "mention://member/", "mention://squad/"} {- if strings.Contains(content, banned) {- t.Errorf("parent has no assignee but comment included %q mention, got: %s", banned, content)+ for _, want := range []string{service.ChildDoneDefaultInstruction, "condition.met", `"all":true`} {+ if !strings.Contains(runs[0].Note, want) {+ t.Errorf("wakeup note lacks %q:\n%s", want, runs[0].Note)}}+ entries := childDoneEntries(t, fx.parent.ID)+ if len(entries) != 1 || entries[0].Outcome != "woke" || entries[0].TargetType != "agent" || entries[0].TargetID != agentID ||+ entries[0].TaskID != runs[0].ID || entries[0].Stage != nil || entries[0].Total != 1 {+ t.Fatalf("entries = %+v", entries)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1 AND author_type = 'system'`, fx.parent.ID); n != 0 {+ t.Fatalf("the rule posted %d system comments; it records a timeline entry instead", n)+ }}-// TestChildDoneNotificationIsIdempotent — re-saving an already-done child-// must NOT fire a second notification. UpdateIssue is called with the same-// status='done' twice; only the first call is a transition and should-// produce a comment.-func TestChildDoneNotificationIsIdempotent(t *testing.T) {+// Without an assignee there is nobody to wake; the milestone is still on the+// parent's timeline.+func TestChildDoneRecordsWithoutAssignee(t *testing.T) {fx := newChildDoneFixture(t, "in_progress")-updateChildStatus(t, fx.child.ID, "done")- if got := countSystemCommentsOn(t, fx.parent.ID); got != 1 {- t.Fatalf("after first done: expected 1 comment, got %d", got)+ entries := childDoneEntries(t, fx.parent.ID)+ if len(entries) != 1 || entries[0].Outcome != "none" || entries[0].TargetType != "" {+ t.Fatalf("entries = %+v", entries)}+ if runs := childDoneRuns(t, fx.parent.ID); len(runs) != 0 {+ t.Fatalf("runs = %+v, want none", runs)+ }+}- // Second save of done — should be a no-op transition.+// Re-saving an already-done child is not a new fact.+func TestChildDoneNotificationIsIdempotent(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ updateChildStatus(t, fx.child.ID, "done")updateChildStatus(t, fx.child.ID, "done")- if got := countSystemCommentsOn(t, fx.parent.ID); got != 1 {- t.Fatalf("after second done: expected still 1 comment (idempotent), got %d", got)+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 1 {+ t.Fatalf("entries = %d, want 1", got)}}-// TestChildReopenAndDoneFiresAgain — done → in_progress → done IS a real-// new completion event and should produce a second notification. This-// captures the "reopen + done counts as a new event" line from MUL-2538.+// done → in_progress → done is a new completion (MUL-2538).func TestChildReopenAndDoneFiresAgain(t *testing.T) {fx := newChildDoneFixture(t, "in_progress")-updateChildStatus(t, fx.child.ID, "done")updateChildStatus(t, fx.child.ID, "in_progress")updateChildStatus(t, fx.child.ID, "done")+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 2 {+ t.Fatalf("entries = %d, want 2 after reopen and done", got)+ }+}- if got := countSystemCommentsOn(t, fx.parent.ID); got != 2 {- t.Fatalf("expected 2 system comments after reopen+done cycle, got %d", got)+// A closed parent has nothing left to drive.+func TestChildDoneSkippedWhenParentClosed(t *testing.T) {+ for _, status := range []string{"done", "cancelled"} {+ t.Run(status, func(t *testing.T) {+ fx := newChildDoneFixture(t, status)+ updateChildStatus(t, fx.child.ID, "done")+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 0 {+ t.Errorf("parent %s received %d entries", status, got)+ }+ })}}-// TestChildDoneSkippedWhenParentDone — when the parent is already at a-// terminal status, there is nothing for the parent assignee to advance to,-// so the notification must NOT fire.-func TestChildDoneSkippedWhenParentDone(t *testing.T) {- fx := newChildDoneFixture(t, "done")+// A parent parked in backlog is not woken (#4320 / MUL-3497), and nothing is+// marked as seen: leaving backlog wakes the assignee once for what closed+// meanwhile, and parking again does not repeat it.+func TestChildDoneHeldWhileParentInBacklog(t *testing.T) {+ fx := newChildDoneFixture(t, "backlog")+ agentID := handlerTestAgentID(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)updateChildStatus(t, fx.child.ID, "done")-- if got := countSystemCommentsOn(t, fx.parent.ID); got != 0 {- t.Errorf("parent at 'done' should not receive notification, got %d comments", got)+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 0 {+ t.Fatalf("parked parent received %d entries", got)}-}-// TestChildDoneSkippedWhenParentCancelled — same as above for cancelled.-func TestChildDoneSkippedWhenParentCancelled(t *testing.T) {- fx := newChildDoneFixture(t, "cancelled")+ dbfx.Exec(t, `UPDATE issue SET status = 'todo' WHERE id = $1`, fx.parent.ID)+ runWakeupTick(t)+ entries := childDoneEntries(t, fx.parent.ID)+ if len(entries) != 1 || entries[0].Outcome != "woke" {+ t.Fatalf("leaving backlog: entries = %+v, want one wake", entries)+ }- updateChildStatus(t, fx.child.ID, "done")+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE issue_id = $1`, fx.parent.ID)+ dbfx.Exec(t, `UPDATE issue SET status = 'backlog' WHERE id = $1`, fx.parent.ID)+ runWakeupTick(t)+ dbfx.Exec(t, `UPDATE issue SET status = 'todo' WHERE id = $1`, fx.parent.ID)+ runWakeupTick(t)+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 1 {+ t.Fatalf("parking again repeated the wake: %d entries", got)+ }+}- if got := countSystemCommentsOn(t, fx.parent.ID); got != 0 {- t.Errorf("parent at 'cancelled' should not receive notification, got %d comments", got)+// An issue without a parent creates no rule anywhere.+func TestChildDoneSkippedWhenNoParent(t *testing.T) {+ orphan := dbfx.Issue(t, "orphan child-done", testutil.Cols{"status": "in_progress"})+ t.Cleanup(func() { cleanupChildDoneIssue(orphan) })+ updateChildStatus(t, orphan, "done")+ if n := dbfx.Count(t, `SELECT count(*) FROM issue_wakeup WHERE issue_id = $1`, orphan); n != 0 {+ t.Fatalf("orphan got %d rules", n)}}-// TestChildDoneSkippedWhenParentBacklog — a parent deliberately parked in-// `backlog` must not be woken when a child completes. Waking it would-// re-activate the parent assignee, which can then promote sibling backlog-// sub-issues into todo — the surprise auto-activation reported in #4320 /-// MUL-3497. No system comment, no trigger, until the user explicitly moves-// the parent out of backlog.-func TestChildDoneSkippedWhenParentBacklog(t *testing.T) {- fx := newChildDoneFixture(t, "backlog")+// A member assignee reads an inbox notification instead of a run.+func TestChildDoneNotifiesMemberAssignee(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ var userID string+ dbfx.QueryRow(t, `SELECT user_id FROM member WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&userID)+ setIssueAssigneeDirect(t, fx.parent.ID, "member", userID)updateChildStatus(t, fx.child.ID, "done")- if got := countSystemCommentsOn(t, fx.parent.ID); got != 0 {- t.Errorf("parent at 'backlog' should not receive notification, got %d comments", got)+ if n := dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE recipient_id = $1 AND issue_id = $2 AND type = 'children_done'`, userID, fx.parent.ID); n != 1 {+ t.Fatalf("children_done inbox items = %d, want 1", n)+ }+ if runs := childDoneRuns(t, fx.parent.ID); len(runs) != 0 {+ t.Fatalf("member parent started runs: %+v", runs)+ }+ entries := childDoneEntries(t, fx.parent.ID)+ if len(entries) != 1 || entries[0].Outcome != "notified" || entries[0].TargetType != "member" || entries[0].TargetID != userID {+ t.Fatalf("entries = %+v", entries)}}-// TestChildDoneSkippedWhenNoParent — an issue with no parent_issue_id must-// not produce any system comment on anything.-func TestChildDoneSkippedWhenNoParent(t *testing.T) {- w := httptest.NewRecorder()- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "orphan child-done " + time.Now().Format(time.RFC3339Nano),- "status": "in_progress",- })- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("create orphan: expected 201, got %d: %s", w.Code, w.Body.String())- }- var orphan IssueResponse- json.NewDecoder(w.Body).Decode(&orphan)- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, orphan.ID)- })+// A squad parent wakes its leader in the leader role; it does not fan out to+// members.+func TestChildDoneWakesSquadLeader(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ sq := newSquadCommentTriggerFixture(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "squad", sq.SquadID)- // Sanity baseline — there should be zero system comments anywhere in- // the workspace attributable to this orphan transition. We can only- // check that the orphan didn't somehow get one itself, but combined- // with the no-parent code path returning early, that is sufficient.- updateChildStatus(t, orphan.ID, "done")+ updateChildStatus(t, fx.child.ID, "done")- if got := countSystemCommentsOn(t, orphan.ID); got != 0 {- t.Errorf("orphan must not receive a self-notification, got %d system comments", got)+ runs := childDoneRuns(t, fx.parent.ID)+ if len(runs) != 1 || runs[0].AgentID != sq.LeaderID || !runs[0].Leader || runs[0].SquadID != sq.SquadID {+ t.Fatalf("runs = %+v, want one leader run", runs)}}-// setIssueAssigneeDirect bypasses UpdateIssue (and its assignment trigger-// side effects) by writing to the assignee columns directly. The child-done-// notification helper reads the parent row through GetIssue at fire time,-// so a direct UPDATE is enough to drive the dispatch under each assignee-// type without queuing a parallel agent task at setup.-func setIssueAssigneeDirect(t *testing.T, issueID, assigneeType, assigneeID string) {- t.Helper()- if _, err := testPool.Exec(context.Background(),- `UPDATE issue SET assignee_type = $2, assignee_id = $3 WHERE id = $1`,- issueID, assigneeType, assigneeID,- ); err != nil {- t.Fatalf("set parent assignee: %v", err)+// Waking the parent's assignee is a hand-off between two different issues,+// never a self-loop, whoever owned the finished child (MUL-2808, MUL-3969).+func TestChildDoneWakesAssigneeWhoeverOwnedTheChild(t *testing.T) {+ cases := map[string]func(t *testing.T, fx childDoneFixture) string{+ "same agent owns the child": func(t *testing.T, fx childDoneFixture) string {+ agentID := handlerTestAgentID(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)+ setIssueAssigneeDirect(t, fx.child.ID, "agent", agentID)+ return agentID+ },+ "child squad led by the parent's agent": func(t *testing.T, fx childDoneFixture) string {+ sq := newSquadCommentTriggerFixture(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", sq.LeaderID)+ setIssueAssigneeDirect(t, fx.child.ID, "squad", sq.SquadID)+ return sq.LeaderID+ },+ "two squads share a leader": func(t *testing.T, fx childDoneFixture) string {+ sq := newSquadCommentTriggerFixture(t)+ other := dbfx.Squad(t, "Child Done Shared Leader Squad", sq.LeaderID)+ setIssueAssigneeDirect(t, fx.parent.ID, "squad", sq.SquadID)+ setIssueAssigneeDirect(t, fx.child.ID, "squad", other)+ return sq.LeaderID+ },+ "same squad owns the child": func(t *testing.T, fx childDoneFixture) string {+ sq := newSquadCommentTriggerFixture(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "squad", sq.SquadID)+ setIssueAssigneeDirect(t, fx.child.ID, "squad", sq.SquadID)+ return sq.LeaderID+ },+ }+ for name, setup := range cases {+ t.Run(name, func(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ agentID := setup(t, fx)+ updateChildStatus(t, fx.child.ID, "done")+ if got := countPendingTasksForAgent(t, fx.parent.ID, agentID); got != 1 {+ t.Fatalf("pending parent runs for the assignee = %d, want 1", got)+ }+ })}}-func parentSystemCommentContent(t *testing.T, issueID string) string {+func createUnstagedChild(t *testing.T, parentID, status string) IssueResponse {t.Helper()- if got := countSystemCommentsOn(t, issueID); got != 1 {- t.Fatalf("expected exactly 1 system comment on parent, got %d", got)+ w := httptest.NewRecorder()+ testHandler.CreateIssue(w, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "unstaged child " + time.Now().Format(time.RFC3339Nano), "status": status, "parent_issue_id": parentID,+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("create unstaged child: %d %s", w.Code, w.Body.String())}- content, _, _, _ := systemCommentOn(t, issueID)- return content-}--func countPendingTasksForAgent(t *testing.T, issueID, agentID string) int {- t.Helper()- var n int- if err := testPool.QueryRow(context.Background(),- `SELECT count(*) FROM agent_task_queue- WHERE issue_id = $1 AND agent_id = $2- AND status IN ('queued', 'dispatched', 'running')`,- issueID, agentID,- ).Scan(&n); err != nil {- t.Fatalf("count pending tasks: %v", err)- }- return n-}--func countInboxItems(t *testing.T, recipientUserID, issueID string) int {- t.Helper()- var n int- if err := testPool.QueryRow(context.Background(),- `SELECT count(*) FROM inbox_item- WHERE recipient_id = $1 AND issue_id = $2`,- recipientUserID, issueID,- ).Scan(&n); err != nil {- t.Fatalf("count inbox items: %v", err)+ var child IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&child); err != nil {+ t.Fatal(err)}- return n+ t.Cleanup(func() { cleanupChildDoneIssue(child.ID) })+ return child}-// TestChildDoneMentionsParentAssignee_Agent verifies the MUL-2538 Option C-// happy path for an agent parent assignee: the system comment carries a-// `mention://agent/<id>` link AND a real mention-style task is enqueued on-// the parent. The trigger fires through TaskService.EnqueueTaskForMention,-// so the dedupe + readiness checks match the @-mention path users already-// rely on.-func TestChildDoneMentionsParentAssignee_Agent(t *testing.T) {+// Each stage that closes while a later one waits wakes the assignee with the+// next stage named; the last stage alone does not, because the wrap-up also+// waits for unstaged sub-issues.+func TestChildDoneStagesThenWrapUp(t *testing.T) {fx := newChildDoneFixture(t, "in_progress")-- var agentID string- if err := testPool.QueryRow(context.Background(),- `SELECT id FROM agent WHERE workspace_id = $1 AND name = $2`,- testWorkspaceID, "Handler Test Agent",- ).Scan(&agentID); err != nil {- t.Fatalf("locate test agent: %v", err)- }+ agentID := handlerTestAgentID(t)setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)- t.Cleanup(func() {- testPool.Exec(context.Background(),- `DELETE FROM agent_task_queue WHERE issue_id = $1`, fx.parent.ID)- })+ dbfx.Exec(t, `UPDATE issue SET stage = 1 WHERE id = $1`, fx.child.ID)+ second := createStagedChild(t, fx.parent.ID, 1, "in_progress")+ last := createStagedChild(t, fx.parent.ID, 2, "backlog")+ loose := createUnstagedChild(t, fx.parent.ID, "todo")+ completeRuns := func() {+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE issue_id = $1`, fx.parent.ID)+ }updateChildStatus(t, fx.child.ID, "done")-- content := parentSystemCommentContent(t, fx.parent.ID)- wantMention := "mention://agent/" + agentID- if !strings.Contains(content, wantMention) {- t.Errorf("expected %q in system comment, got: %s", wantMention, content)+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 0 {+ t.Fatalf("half a stage fired %d entries", got)}- if got := countPendingTasksForAgent(t, fx.parent.ID, agentID); got != 1 {- t.Errorf("expected 1 pending task for parent agent, got %d", got)+ updateChildStatus(t, second.ID, "cancelled")+ entries := childDoneEntries(t, fx.parent.ID)+ if len(entries) != 1 || entries[0].Stage == nil || *entries[0].Stage != 1 || entries[0].Total != 2 || entries[0].Outcome != "woke" {+ t.Fatalf("stage 1: entries = %+v", entries)}-}--// TestChildDoneSkippedWhenParentMember verifies the MUL-2538 follow-up: a-// human parent assignee should NOT receive the platform-generated system-// comment at all. Humans read their own timeline manually; the automated-// notification is pure noise and skipping it also removes the question of-// whether to mention/inbox-row the member.-//-// The assignee row uses `user_id` (NOT `member.id`) — that is the-// production invariant validated by validateAssigneePair for member-// assignees (see server/internal/handler/issue.go), so the fixture must-// match or it would be exercising a state that cannot occur for real.-func TestChildDoneSkippedWhenParentMember(t *testing.T) {- fx := newChildDoneFixture(t, "in_progress")-- var userID string- if err := testPool.QueryRow(context.Background(),- `SELECT user_id FROM member WHERE workspace_id = $1 LIMIT 1`,- testWorkspaceID,- ).Scan(&userID); err != nil {- t.Fatalf("locate workspace member: %v", err)+ runs := childDoneRuns(t, fx.parent.ID)+ if len(runs) != 1 || !strings.Contains(runs[0].Note, `"next_stage":2`) || !strings.Contains(runs[0].Note, `"cancelled":1`) {+ t.Fatalf("stage 1 run does not name stage 2 and the cancellation: %+v", runs)}- setIssueAssigneeDirect(t, fx.parent.ID, "member", userID)- t.Cleanup(func() {- testPool.Exec(context.Background(),- `DELETE FROM inbox_item WHERE issue_id = $1`, fx.parent.ID)- })+ completeRuns()- updateChildStatus(t, fx.child.ID, "done")-- if got := countSystemCommentsOn(t, fx.parent.ID); got != 0 {- t.Errorf("parent with member assignee should not receive a system comment, got %d", got)+ updateChildStatus(t, last.ID, "done")+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 1 {+ t.Fatalf("the last stage fired while an unstaged sub-issue was open: %d entries", got)}- if got := countInboxItems(t, userID, fx.parent.ID); got != 0 {- t.Errorf("parent with member assignee should not receive an inbox row, got %d", got)+ updateChildStatus(t, loose.ID, "done")+ entries = childDoneEntries(t, fx.parent.ID)+ if len(entries) != 2 || entries[1].Stage != nil || entries[1].Total != 4 {+ t.Fatalf("wrap-up: entries = %+v", entries)}}-// TestChildDoneMentionsParentAssignee_Squad verifies the squad branch: the-// system comment carries a `mention://squad/<id>` link and the squad-// leader receives a leader-role task. Reuses the squad fixture helper from-// squad_comment_trigger_test.go.-func TestChildDoneMentionsParentAssignee_Squad(t *testing.T) {- fx := newChildDoneFixture(t, "in_progress")- sq := newSquadCommentTriggerFixture(t)-- setIssueAssigneeDirect(t, fx.parent.ID, "squad", sq.SquadID)- t.Cleanup(func() {- testPool.Exec(context.Background(),- `DELETE FROM agent_task_queue WHERE issue_id = $1`, fx.parent.ID)- })-- updateChildStatus(t, fx.child.ID, "done")-- content := parentSystemCommentContent(t, fx.parent.ID)- wantMention := "mention://squad/" + sq.SquadID- if !strings.Contains(content, wantMention) {- t.Errorf("expected %q in system comment, got: %s", wantMention, content)- }- if got := countPendingTasksForAgent(t, fx.parent.ID, sq.LeaderID); got != 1 {- t.Errorf("expected 1 pending leader task for parent squad, got %d", got)+// Another run of the same agent that has not started yet reads the current+// sub-issues when it does, so the rule hands it the stage facts when it is+// claimed instead of queuing a second run. Claimed by a daemon that cannot+// render them, the rule wakes the agent with its own run.+func TestChildDoneJoinsPendingRun(t *testing.T) {+ for _, rendersJoined := range []bool{true, false} {+ t.Run(fmt.Sprintf("renders joined wakeups %t", rendersJoined), func(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ agentID := handlerTestAgentID(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)+ waiting := dbfx.Task(t, agentID, testutil.Cols{"issue_id": fx.parent.ID, "runtime_id": testRuntimeID, "status": "queued", "originator_user_id": testUserID, "accountable_user_id": testUserID})++ updateChildStatus(t, fx.child.ID, "done")+ if entries := childDoneEntries(t, fx.parent.ID); len(entries) != 0 {+ t.Fatalf("entries before the claim = %+v", entries)+ }+ if got := countPendingTasksForAgent(t, fx.parent.ID, agentID); got != 1 {+ t.Fatalf("pending runs = %d, want the existing one only", got)+ }++ notes := claimRun(t, waiting, rendersJoined)+ startRun(t, waiting)+ runWakeupTick(t)+ entries := childDoneEntries(t, fx.parent.ID)+ if !rendersJoined {+ if notes != "" || len(entries) != 1 || entries[0].Outcome != "woke" || len(childDoneRuns(t, fx.parent.ID)) != 1 {+ t.Fatalf("notes = %q entries = %+v", notes, entries)+ }+ return+ }+ if !strings.Contains(notes, service.ChildDoneDefaultInstruction) || !strings.Contains(notes, `"all":true`) {+ t.Fatalf("joined notes = %q", notes)+ }+ if len(entries) != 1 || entries[0].Outcome != "merged" || entries[0].TaskID != waiting || len(childDoneRuns(t, fx.parent.ID)) != 0 {+ t.Fatalf("entries = %+v", entries)+ }+ })}}-// TestChildDoneTriggersParentAgentWhenSameAgentOwnsChild — when the parent-// agent assignee is the SAME agent that owns the just-finished child, the-// parent agent must still be triggered (MUL-2808). A child finishing and-// waking its parent is a serial sub-task handoff between two different-// issues, not a self-loop — and the lone-agent decomposition pattern (one-// agent owns both the parent and the sub-issues it created) has no other-// wake path. The comment is created AND exactly one task is enqueued on the-// parent; runaway re-triggering is bounded by the HasPendingTaskForIssueAndAgent-// dedup, not by suppressing the trigger.-func TestChildDoneTriggersParentAgentWhenSameAgentOwnsChild(t *testing.T) {+// A person's sub-issue condition and the system rule describe the same fact:+// the assignee runs once.+func TestChildDoneAndConditionRuleWakeOnce(t *testing.T) {fx := newChildDoneFixture(t, "in_progress")-- var agentID string- if err := testPool.QueryRow(context.Background(),- `SELECT id FROM agent WHERE workspace_id = $1 AND name = $2`,- testWorkspaceID, "Handler Test Agent",- ).Scan(&agentID); err != nil {- t.Fatalf("locate test agent: %v", err)- }- // Both child and parent assigned to the same agent. Setting the child- // assignee via direct SQL avoids the assignment-trigger side effect- // that would otherwise queue an unrelated task on the child.+ agentID := handlerTestAgentID(t)setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)- setIssueAssigneeDirect(t, fx.child.ID, "agent", agentID)- t.Cleanup(func() {- testPool.Exec(context.Background(),- `DELETE FROM agent_task_queue WHERE issue_id IN ($1, $2)`,- fx.parent.ID, fx.child.ID)- })+ svc := service.IssueWakeupService{Tasks: testHandler.TaskService}+ if _, err := svc.Create(context.Background(), parseUUID(fx.parent.ID), parseUUID(testUserID), pgtype.UUID{}, service.WakeupInput{+ AgentID: agentID, Instruction: "Summarize the children", Kind: "event", Condition: json.RawMessage(`{"type":"children_done"}`),+ }); err != nil {+ t.Fatal(err)+ }updateChildStatus(t, fx.child.ID, "done")- content := parentSystemCommentContent(t, fx.parent.ID)- if !strings.Contains(content, "mention://agent/"+agentID) {- t.Errorf("expected parent-assignee mention in system comment, got: %s", content)- }if got := countPendingTasksForAgent(t, fx.parent.ID, agentID); got != 1 {- t.Errorf("expected 1 pending task on parent (serial sub-task handoff), got %d", got)+ t.Fatalf("pending runs = %d, want 1", got)}-}--// TestChildDoneTriggersParentAgentWhenChildSquadSharesLeader — parent is-// assigned to agent A directly; the finished child is assigned to a squad-// whose leader is also agent A. Because the parent is an AGENT, dispatch-// routes through the agent path, which (post-MUL-2808) has no self-trigger-// guard: A coordinates the parent and must be woken to advance it when the-// child completes, regardless of who executed the child. The squad path now-// behaves identically: MUL-3969 removed its old same-squad / shared-leader-// guards, so BOTH sides being squads that share a leader also wakes the leader-// (see TestChildDoneWakesLeaderWhenParentAndChildSquadsShareLeader).-func TestChildDoneTriggersParentAgentWhenChildSquadSharesLeader(t *testing.T) {- fx := newChildDoneFixture(t, "in_progress")- sq := newSquadCommentTriggerFixture(t)-- // Parent agent == squad leader, child assigned to the squad.- setIssueAssigneeDirect(t, fx.parent.ID, "agent", sq.LeaderID)- setIssueAssigneeDirect(t, fx.child.ID, "squad", sq.SquadID)- t.Cleanup(func() {- testPool.Exec(context.Background(),- `DELETE FROM agent_task_queue WHERE issue_id IN ($1, $2)`,- fx.parent.ID, fx.child.ID)- })-- updateChildStatus(t, fx.child.ID, "done")-- content := parentSystemCommentContent(t, fx.parent.ID)- if !strings.Contains(content, "mention://agent/"+sq.LeaderID) {- t.Errorf("expected parent-agent mention in system comment, got: %s", content)+ var run string+ dbfx.QueryRow(t, `SELECT id FROM agent_task_queue WHERE issue_id = $1 AND context->>'wakeup_system' IS NULL AND context->>'wakeup_id' IS NOT NULL`, fx.parent.ID).Scan(&run)+ if notes := claimRun(t, run, true); !strings.Contains(notes, service.ChildDoneDefaultInstruction) {+ t.Fatalf("the person's run lacks the system rule: %q", notes)}- if got := countPendingTasksForAgent(t, fx.parent.ID, sq.LeaderID); got != 1 {- t.Errorf("expected 1 pending task on parent (serial sub-task handoff), got %d", got)+ startRun(t, run)+ runWakeupTick(t)+ entries := childDoneEntries(t, fx.parent.ID)+ if len(entries) != 1 || entries[0].Outcome != "merged" || entries[0].TaskID != run {+ t.Fatalf("system entries = %+v", entries)}}-// TestChildDoneWakesLeaderWhenParentAndChildSquadsShareLeader — cross-squad-// shared-leader case. Parent is squad A, child is squad B, both squads have-// the same leader agent. The squad path used to suppress the leader wake here-// (effectiveChildAgentOwner reduced both sides to the shared leader), but that-// guard was removed in MUL-3969: waking the leader on the PARENT is a serial-// sub-task handoff across two DIFFERENT issues, not a self-loop, and it is the-// only signal that carries the parent-level stage-barrier instruction. The-// leader must now be woken exactly once; runaway re-triggering is bounded by-// the HasPendingTaskForIssueAndAgent idempotency check.-func TestChildDoneWakesLeaderWhenParentAndChildSquadsShareLeader(t *testing.T) {+// The system rule shares runaway protection: past the hourly limit it pauses+// with a visible reason instead of starting another run.+func TestChildDoneRateLimitPausesRule(t *testing.T) {fx := newChildDoneFixture(t, "in_progress")- parentSquad := newSquadCommentTriggerFixture(t)-- // Spin up a SECOND squad that reuses the same leader as parentSquad.- ctx := context.Background()- var childSquadID string- if err := testPool.QueryRow(ctx, `- INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)- VALUES ($1, $2, '', $3, $4)- RETURNING id- `, testWorkspaceID, "Child Done Shared Leader Squad", parentSquad.LeaderID, testUserID).- Scan(&childSquadID); err != nil {- t.Fatalf("create second squad: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, childSquadID)- })-- setIssueAssigneeDirect(t, fx.parent.ID, "squad", parentSquad.SquadID)- setIssueAssigneeDirect(t, fx.child.ID, "squad", childSquadID)- t.Cleanup(func() {- testPool.Exec(context.Background(),- `DELETE FROM agent_task_queue WHERE issue_id IN ($1, $2)`,- fx.parent.ID, fx.child.ID)- })-+ agentID := handlerTestAgentID(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)updateChildStatus(t, fx.child.ID, "done")-- content := parentSystemCommentContent(t, fx.parent.ID)- if !strings.Contains(content, "mention://squad/"+parentSquad.SquadID) {- t.Errorf("expected parent-squad mention in system comment, got: %s", content)+ runs := childDoneRuns(t, fx.parent.ID)+ if len(runs) != 1 {+ t.Fatalf("first close: runs = %+v", runs)}- if got := countPendingTasksForAgent(t, fx.parent.ID, parentSquad.LeaderID); got != 1 {- t.Errorf("expected 1 pending leader task on parent (shared-leader guard removed, MUL-3969), got %d", got)+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE issue_id = $1`, fx.parent.ID)+ for range 12 {+ dbfx.Task(t, agentID, testutil.Cols{"issue_id": fx.parent.ID, "runtime_id": testRuntimeID, "status": "completed",+ "context": fmt.Sprintf(`{"wakeup_id":%q}`, runs[0].WakeupID)})}-}--// TestChildDoneWakesLeaderWhenChildIsSameSquad — the MUL-3969 repro. Parent-// and the just-finished child are BOTH assigned to the same squad (the common-// "a squad decomposes its parent into sub-issues it works itself" pattern).-// The old same-squad guard suppressed the leader wake, so the stage-barrier-// system comment landed on the parent but the "wrap up / advance" instruction-// was never delivered to the leader and the parent silently stalled in-// in_progress. The leader must now be woken exactly once.-func TestChildDoneWakesLeaderWhenChildIsSameSquad(t *testing.T) {- fx := newChildDoneFixture(t, "in_progress")- sq := newSquadCommentTriggerFixture(t)-- setIssueAssigneeDirect(t, fx.parent.ID, "squad", sq.SquadID)- setIssueAssigneeDirect(t, fx.child.ID, "squad", sq.SquadID)- t.Cleanup(func() {- testPool.Exec(context.Background(),- `DELETE FROM agent_task_queue WHERE issue_id IN ($1, $2)`,- fx.parent.ID, fx.child.ID)- })+ updateChildStatus(t, fx.child.ID, "in_progress")updateChildStatus(t, fx.child.ID, "done")- content := parentSystemCommentContent(t, fx.parent.ID)- if !strings.Contains(content, "mention://squad/"+sq.SquadID) {- t.Errorf("expected parent-squad mention in system comment, got: %s", content)+ var paused pgtype.Text+ var enabled bool+ dbfx.QueryRow(t, `SELECT paused_reason, enabled FROM issue_wakeup WHERE issue_id = $1 AND system_rule = 'child_done'`, fx.parent.ID).Scan(&paused, &enabled)+ if paused.String != "rate" || enabled {+ t.Fatalf("rule paused=%q enabled=%v, want paused for rate", paused.String, enabled)}- if got := countPendingTasksForAgent(t, fx.parent.ID, sq.LeaderID); got != 1 {- t.Errorf("expected 1 pending leader task for same-squad child (MUL-3969), got %d", got)+ if got := countPendingTasksForAgent(t, fx.parent.ID, agentID); got != 0 {+ t.Fatalf("a paused rule started %d runs", got)}}-// TestStageLeaderPrepareTimeoutRetryCanAdvanceNextStage covers the full server-// half of MUL-4923's recovery chain: a stage barrier wakes the squad leader,-// the pre-start attempt fails with the daemon's timeout reason, the atomic-// retry preserves leader/squad/trigger provenance, and that retry can promote-// the parked next stage as the leader actor.+// TestStageLeaderPrepareTimeoutRetryCanAdvanceNextStage covers the server half+// of MUL-4923's recovery chain: a stage barrier wakes the squad leader, the+// pre-start attempt fails with the daemon's timeout reason, the atomic retry+// preserves the leader, squad and wakeup provenance, and that retry can+// promote the parked next stage as the leader actor.func TestStageLeaderPrepareTimeoutRetryCanAdvanceNextStage(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")@@ -569,9 +562,7 @@ func TestStageLeaderPrepareTimeoutRetryCanAdvanceNextStage(t *testing.T) {sq := newSquadCommentTriggerFixture(t)setIssueAssigneeDirect(t, fx.parent.ID, "squad", sq.SquadID)setIssueAssigneeDirect(t, fx.child.ID, "squad", sq.SquadID)- if _, err := testPool.Exec(ctx, `UPDATE issue SET stage = 1 WHERE id = $1`, fx.child.ID); err != nil {- t.Fatalf("set stage 1: %v", err)- }+ dbfx.Exec(t, `UPDATE issue SET stage = 1 WHERE id = $1`, fx.child.ID)// Stage 2 exists but is deliberately parked. The server wakes the leader at// the Stage 1 barrier; only the leader decides to promote this child.@@ -592,69 +583,33 @@ func TestStageLeaderPrepareTimeoutRetryCanAdvanceNextStage(t *testing.T) {if err := json.NewDecoder(w.Body).Decode(&stage2); err != nil {t.Fatalf("decode stage 2: %v", err)}- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id IN ($1, $2)`, fx.parent.ID, stage2.ID)- testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, stage2.ID)- })+ t.Cleanup(func() { cleanupChildDoneIssue(stage2.ID) })updateChildStatus(t, fx.child.ID, "done")- content := parentSystemCommentContent(t, fx.parent.ID)- if !strings.Contains(content, "Stage 2 is next") {- t.Fatalf("stage barrier comment does not identify Stage 2: %s", content)- }-- var originalID, originalSquadID, originalTriggerID string- var originalLeader bool- if err := testPool.QueryRow(ctx, `- SELECT id::text, is_leader_task, squad_id::text, trigger_comment_id::text- FROM agent_task_queue- WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'- ORDER BY created_at DESC- LIMIT 1- `, fx.parent.ID, sq.LeaderID).Scan(&originalID, &originalLeader, &originalSquadID, &originalTriggerID); err != nil {- t.Fatalf("load Stage 1 leader wake: %v", err)- }- if !originalLeader || originalSquadID != sq.SquadID || originalTriggerID == "" {- t.Fatalf("leader wake provenance = leader:%v squad:%q trigger:%q", originalLeader, originalSquadID, originalTriggerID)- }- if _, err := testPool.Exec(ctx, `- UPDATE agent_task_queue- SET status = 'dispatched', dispatched_at = now()- WHERE id = $1- `, originalID); err != nil {- t.Fatalf("dispatch original leader task: %v", err)- }-- if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(originalID), "task preparation timed out after 5m0s", "", "", "", "timeout", false, "", ""); err != nil {+ runs := childDoneRuns(t, fx.parent.ID)+ if len(runs) != 1 || !runs[0].Leader || runs[0].SquadID != sq.SquadID || !strings.Contains(runs[0].Note, `"next_stage":2`) {+ t.Fatalf("stage barrier wake = %+v, want a leader run naming stage 2", runs)+ }+ original := runs[0]+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE id = $1`, original.ID)+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(original.ID), "task preparation timed out after 5m0s", "", "", "", "timeout", false, "", ""); err != nil {t.Fatalf("fail original leader task: %v", err)}- var retryID, retryStatus, retrySquadID, retryTriggerID string+ var retryID, retryStatus, retrySquadID, retryWakeupID stringvar retryLeader boolvar retryAttempt int32- if err := testPool.QueryRow(ctx, `- SELECT id::text, status, is_leader_task, squad_id::text,- trigger_comment_id::text, attempt- FROM agent_task_queue- WHERE parent_task_id = $1- `, originalID).Scan(&retryID, &retryStatus, &retryLeader, &retrySquadID, &retryTriggerID, &retryAttempt); err != nil {- t.Fatalf("load automatic retry: %v", err)- }- if retryStatus != "queued" || retryAttempt != 2 || !retryLeader || retrySquadID != originalSquadID || retryTriggerID != originalTriggerID {- t.Fatalf("retry provenance = status:%q attempt:%d leader:%v squad:%q trigger:%q; want queued attempt 2 with original leader context",- retryStatus, retryAttempt, retryLeader, retrySquadID, retryTriggerID)- }- if _, err := testPool.Exec(ctx, `- UPDATE agent_task_queue- SET status = 'running', dispatched_at = now(), started_at = now()- WHERE id = $1- `, retryID); err != nil {- t.Fatalf("start retry leader task: %v", err)+ dbfx.QueryRow(t, `SELECT id::text, status, is_leader_task, squad_id::text, COALESCE(context->>'wakeup_id', ''), attempt+ FROM agent_task_queue WHERE parent_task_id = $1`, original.ID).+ Scan(&retryID, &retryStatus, &retryLeader, &retrySquadID, &retryWakeupID, &retryAttempt)+ if retryStatus != "queued" || retryAttempt != 2 || !retryLeader || retrySquadID != original.SquadID || retryWakeupID != original.WakeupID {+ t.Fatalf("retry provenance = status:%q attempt:%d leader:%v squad:%q wakeup:%q; want queued attempt 2 with the original leader context",+ retryStatus, retryAttempt, retryLeader, retrySquadID, retryWakeupID)}+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'running', dispatched_at = now(), started_at = now() WHERE id = $1`, retryID)// Act through the normal issue handler with the retry task as the agent- // identity. This is the operation the Stage handoff prompt asks the leader- // to perform, and proves the retry was not demoted to a generic worker.+ // identity: the operation the stage wake asks the leader to perform.w = httptest.NewRecorder()req = newRequest("PUT", "/api/issues/"+stage2.ID, map[string]any{"status": "todo"})req.Header.Set("X-Agent-ID", sq.LeaderID)@@ -665,9 +620,7 @@ func TestStageLeaderPrepareTimeoutRetryCanAdvanceNextStage(t *testing.T) {t.Fatalf("retry leader promote Stage 2: expected 200, got %d: %s", w.Code, w.Body.String())}var stage2Status string- if err := testPool.QueryRow(ctx, `SELECT status FROM issue WHERE id = $1`, stage2.ID).Scan(&stage2Status); err != nil {- t.Fatalf("load promoted Stage 2: %v", err)- }+ dbfx.QueryRow(t, `SELECT status FROM issue WHERE id = $1`, stage2.ID).Scan(&stage2Status)if stage2Status != "todo" {t.Fatalf("Stage 2 status = %q, want todo", stage2Status)}diff --git a/server/internal/handler/issue_child_event.go b/server/internal/handler/issue_child_event.gonew file mode 100644index 0000000000..5fb78d5080--- /dev/null+++ b/server/internal/handler/issue_child_event.go@@ -0,0 +1,16 @@+package handler++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+)++// processChildEvents runs the sub-issue rules of these parents (the child_done+// system rule and people's sub-issue conditions) right after a write. The+// write recorded its sub-issue changes in its own transaction; a failure here+// is retried by the scheduler sweep.+func (h *Handler) processChildEvents(ctx context.Context, parentIDs ...pgtype.UUID) {+ _ = (&service.IssueWakeupService{Tasks: h.TaskService}).ProcessChildEvents(ctx, parentIDs...)+}diff --git a/server/internal/handler/issue_status_test.go b/server/internal/handler/issue_status_test.goindex 36097e2082..16fd24c426 100644--- a/server/internal/handler/issue_status_test.go+++ b/server/internal/handler/issue_status_test.go@@ -1051,10 +1051,9 @@ func mustCreateIssue(t *testing.T, title, status string) pgtype.UUID {}// TestBatchCustomTerminalStatusEntersStageBarrier is the regression guard for-// the batch stage-barrier prefilter. It compared status literals, so a batch-// that moved the last child onto a CUSTOM done status left childDoneCompleted-// empty and skipped the parent notification entirely — the already-fixed-// barrier logic downstream never ran.+// the batch stage barrier with a custom closed status (MUL-6243): moving the+// last child onto a CUSTOM done status must close the parent's barrier like+// the built-in done status.func TestBatchCustomTerminalStatusEntersStageBarrier(t *testing.T) {ctx := context.Background()createTestCustomStatus(t, "batch_done_s", issuestatus.Done)@@ -1074,15 +1073,11 @@ func TestBatchCustomTerminalStatusEntersStageBarrier(t *testing.T) {t.Fatalf("batch update: %d %s", rec.Code, rec.Body.String())}- // The observable effect of entering the barrier is the system comment on- // the parent. Without the fix the batch is silent.- var comments int- if err := testPool.QueryRow(ctx,- `SELECT count(*) FROM comment WHERE issue_id = $1`, parent).Scan(&comments); err != nil {- t.Fatalf("count parent comments: %v", err)- }- if comments == 0 {- t.Error("moving the last child to a custom done status did not close the stage barrier")+ // The observable effect of closing the barrier is the rule's entry on the+ // parent. Without the fix the batch is silent.+ t.Cleanup(func() { cleanupChildDoneIssue(uuidToString(parent)) })+ if entries := childDoneEntries(t, uuidToString(parent)); len(entries) != 1 {+ t.Errorf("moving the last child to a custom done status did not close the stage barrier: %+v", entries)}}diff --git a/server/internal/handler/issue_system_wakeup.go b/server/internal/handler/issue_system_wakeup.gonew file mode 100644index 0000000000..5ac4460e36--- /dev/null+++ b/server/internal/handler/issue_system_wakeup.go@@ -0,0 +1,327 @@+package handler++import (+ "encoding/json"+ "errors"+ "log/slog"+ "net/http"+ "strconv"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/service"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// The child_done system rule is an issue_wakeup row owned by the platform (see+// service.SystemRuleChildDone). These endpoints show what one parent is+// waiting for and let people change the rule on that issue, and set its+// workspace default. People's own rules use the ordinary wakeup endpoints.++type systemWakeupTarget struct {+ Type string `json:"type"`+ ID string `json:"id"`+ Name string `json:"name"`+}++type systemWakeupResponse struct {+ // ID and Revision are empty until the rule exists on this issue; it is+ // created with the first sub-issue change or the first edit.+ ID string `json:"id"`+ Revision int64 `json:"revision"`+ Rule string `json:"rule"`+ Enabled bool `json:"enabled"`+ // Instruction is set on this issue; DefaultInstruction is what runs+ // receive when it is empty (the workspace's, else the platform's).+ Instruction string `json:"instruction"`+ DefaultInstruction string `json:"default_instruction"`+ Customized bool `json:"customized"`+ PausedReason *string `json:"paused_reason"`+ // Staged is true while a stage is open; Stage is the lowest open one.+ // Otherwise the rule waits for every sub-issue.+ Staged bool `json:"staged"`+ Stage *int32 `json:"stage"`+ Total int `json:"total"`+ Remaining int `json:"remaining"`+ // Identifiers of the unfinished sub-issues in scope, at most five.+ Waiting []string `json:"waiting"`+ Target *systemWakeupTarget `json:"target"`+ // Blocked says why the rule would not start a run right now: "backlog",+ // "member_assignee" (it notifies the member instead) or "no_assignee".+ Blocked string `json:"blocked"`+ // WorkspaceDefault is the rule's workspace-wide setting, which applies+ // until the issue sets its own.+ WorkspaceDefault bool `json:"workspace_default"`+}++// childDoneSystemWakeup describes what the parent is waiting for. It returns+// nil when there is nothing left to wait for: no sub-issues, every sub-issue+// closed, or the parent itself closed.+func (h *Handler) childDoneSystemWakeup(r *http.Request, parent db.Issue) (*systemWakeupResponse, error) {+ ctx := r.Context()+ categories := map[string]string{}+ closed := func(status string) (bool, error) {+ category, ok := categories[status]+ if !ok {+ var err error+ if category, err = issuestatus.CategoryWithError(ctx, h.Queries, parent.WorkspaceID, status); err != nil {+ return false, err+ }+ categories[status] = category+ }+ return category == "done" || category == "closed", nil+ }+ if isClosed, err := closed(parent.Status); err != nil || isClosed {+ return nil, err+ }+ children, err := h.Queries.ListChildIssues(ctx, parent.ID)+ if err != nil || len(children) == 0 {+ return nil, err+ }+ open := make([]db.Issue, 0, len(children))+ var stage pgtype.Int4+ for _, c := range children {+ isClosed, err := closed(c.Status)+ if err != nil {+ return nil, err+ }+ if isClosed {+ continue+ }+ open = append(open, c)+ if c.Stage.Valid && (!stage.Valid || c.Stage.Int32 < stage.Int32) {+ stage = c.Stage+ }+ }+ if len(open) == 0 {+ return nil, nil+ }+ out := &systemWakeupResponse{Rule: service.SystemRuleChildDone, Staged: stage.Valid, Waiting: []string{}}+ if stage.Valid {+ out.Stage = &stage.Int32+ }+ prefix := h.getIssuePrefix(ctx, parent.WorkspaceID)+ for _, c := range children {+ if stage.Valid && (!c.Stage.Valid || c.Stage.Int32 != stage.Int32) {+ continue+ }+ out.Total+++ }+ for _, c := range open {+ if stage.Valid && (!c.Stage.Valid || c.Stage.Int32 != stage.Int32) {+ continue+ }+ out.Remaining+++ if len(out.Waiting) < 5 {+ out.Waiting = append(out.Waiting, prefix+"-"+strconv.Itoa(int(c.Number)))+ }+ }+ ws, err := h.Queries.GetWorkspace(ctx, parent.WorkspaceID)+ if err != nil {+ return nil, err+ }+ out.WorkspaceDefault, _ = service.SystemWakeupDefault(ws.Settings)+ out.Enabled = out.WorkspaceDefault+ out.DefaultInstruction = service.ChildDoneInstruction("", ws.Settings)+ rule, err := h.Queries.GetSystemWakeup(ctx, db.GetSystemWakeupParams{IssueID: parent.ID, SystemRule: pgtype.Text{String: service.SystemRuleChildDone, Valid: true}})+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return nil, err+ }+ if err == nil {+ out.ID, out.Revision, out.Enabled, out.Instruction = uuidToString(rule.ID), rule.Revision, rule.Enabled, rule.Instruction+ out.Customized = rule.CustomizedAt.Valid+ if rule.PausedReason.Valid {+ out.PausedReason = &rule.PausedReason.String+ }+ }+ switch {+ case !parent.AssigneeType.Valid || !parent.AssigneeID.Valid:+ out.Blocked = "no_assignee"+ case parent.AssigneeType.String == "member":+ out.Blocked = "member_assignee"+ if user, e := h.Queries.GetUser(ctx, parent.AssigneeID); e == nil {+ out.Target = &systemWakeupTarget{Type: "member", ID: uuidToString(user.ID), Name: user.Name}+ }+ case parent.AssigneeType.String == "agent":+ if agent, e := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: parent.AssigneeID, WorkspaceID: parent.WorkspaceID}); e == nil {+ out.Target = &systemWakeupTarget{Type: "agent", ID: uuidToString(agent.ID), Name: agent.Name}+ }+ case parent.AssigneeType.String == "squad":+ if squad, e := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: parent.AssigneeID, WorkspaceID: parent.WorkspaceID}); e == nil {+ out.Target = &systemWakeupTarget{Type: "squad", ID: uuidToString(squad.ID), Name: squad.Name}+ }+ }+ if out.Blocked == "" && issuestatus.Effective(ctx, h.Queries, parent.WorkspaceID, parent.Status) == "backlog" {+ out.Blocked = "backlog"+ }+ if out.Blocked == "" && out.Target == nil {+ out.Blocked = "no_assignee"+ }+ return out, nil+}++func (h *Handler) listSystemWakeups(r *http.Request, issue db.Issue) ([]systemWakeupResponse, error) {+ rules := []systemWakeupResponse{}+ childDone, err := h.childDoneSystemWakeup(r, issue)+ if err != nil {+ return nil, err+ }+ if childDone != nil {+ rules = append(rules, *childDone)+ }+ return rules, nil+}++func (h *Handler) ListIssueSystemWakeups(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ rules, err := h.listSystemWakeups(r, issue)+ if err != nil {+ slog.Warn("list system wakeups failed", "error", err, "issue_id", uuidToString(issue.ID))+ writeError(w, 500, "could not load system wakeups")+ return+ }+ writeJSON(w, 200, rules)+}++// systemWakeupHuman requires a person: agents cannot change platform rules.+// Any workspace member who can see the issue may change it on that issue:+// the rule wakes the issue's own assignee, whose invocation was already+// authorized when the issue was assigned.+func (h *Handler) systemWakeupHuman(w http.ResponseWriter, r *http.Request, workspaceID string) (db.Member, bool) {+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)+ if actorType != "member" {+ writeError(w, 403, "only members can change system wakeups")+ return db.Member{}, false+ }+ member, err := h.getWorkspaceMember(r.Context(), actorID, workspaceID)+ if err != nil {+ writeError(w, 403, "wakeup permission denied")+ return db.Member{}, false+ }+ return member, true+}++// UpdateIssueSystemWakeup turns a platform rule on or off for one issue and+// sets its instruction. Omitted fields keep their value, so a list can toggle+// the rule without reading its instruction.+func (h *Handler) UpdateIssueSystemWakeup(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ if chi.URLParam(r, "rule") != service.SystemRuleChildDone {+ writeError(w, 404, "system wakeup not found")+ return+ }+ var in service.SystemWakeupInput+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16384))+ dec.DisallowUnknownFields()+ if err := dec.Decode(&in); err != nil {+ writeError(w, 400, "invalid system wakeup body")+ return+ }+ if _, ok := h.systemWakeupHuman(w, r, uuidToString(issue.WorkspaceID)); !ok {+ return+ }+ if _, err := (&service.IssueWakeupService{Tasks: h.TaskService}).UpdateChildDoneRule(r.Context(), issue.ID, in); err != nil {+ if errors.Is(err, service.ErrWakeupInput) {+ writeError(w, 400, err.Error())+ return+ }+ slog.Warn("update system wakeup failed", "error", err, "issue_id", uuidToString(issue.ID))+ writeError(w, 500, "could not save system wakeup")+ return+ }+ rules, err := h.listSystemWakeups(r, issue)+ if err != nil {+ writeError(w, 500, "could not load system wakeups")+ return+ }+ writeJSON(w, 200, rules)+}++type workspaceSystemWakeupResponse struct {+ Rule string `json:"rule"`+ Enabled bool `json:"enabled"`+ // Instruction is the workspace's; empty means runs get BuiltinInstruction.+ Instruction string `json:"instruction"`+ BuiltinInstruction string `json:"builtin_instruction"`+ // Customized counts open issues whose rule a person changed; they no+ // longer follow this default.+ Customized int64 `json:"customized"`+}++func (h *Handler) workspaceSystemWakeups(r *http.Request, workspaceID pgtype.UUID) ([]workspaceSystemWakeupResponse, error) {+ ws, err := h.Queries.GetWorkspace(r.Context(), workspaceID)+ if err != nil {+ return nil, err+ }+ customized, err := h.Queries.CountCustomizedSystemWakeups(r.Context(), db.CountCustomizedSystemWakeupsParams{WorkspaceID: workspaceID, SystemRule: pgtype.Text{String: service.SystemRuleChildDone, Valid: true}})+ if err != nil {+ return nil, err+ }+ enabled, instruction := service.SystemWakeupDefault(ws.Settings)+ return []workspaceSystemWakeupResponse{{+ Rule: service.SystemRuleChildDone, Enabled: enabled, Instruction: instruction,+ BuiltinInstruction: service.ChildDoneDefaultInstruction, Customized: customized,+ }}, nil+}++// ListWorkspaceSystemWakeups returns the workspace default of each platform rule.+func (h *Handler) ListWorkspaceSystemWakeups(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ if _, ok := h.workspaceMember(w, r, workspaceID); !ok {+ return+ }+ rules, err := h.workspaceSystemWakeups(r, parseUUID(workspaceID))+ if err != nil {+ writeError(w, 500, "could not load system wakeups")+ return+ }+ writeJSON(w, 200, rules)+}++// UpdateWorkspaceSystemWakeup sets a platform rule's workspace default. Rules+// nobody changed on their issue follow it right away. Owners and admins only.+func (h *Handler) UpdateWorkspaceSystemWakeup(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ if chi.URLParam(r, "rule") != service.SystemRuleChildDone {+ writeError(w, 404, "system wakeup not found")+ return+ }+ var in service.SystemWakeupInput+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16384))+ dec.DisallowUnknownFields()+ if err := dec.Decode(&in); err != nil {+ writeError(w, 400, "invalid system wakeup body")+ return+ }+ member, ok := h.systemWakeupHuman(w, r, workspaceID)+ if !ok {+ return+ }+ if !roleAllowed(member.Role, "owner", "admin") {+ writeError(w, 403, "only owners and admins can change workspace defaults")+ return+ }+ if _, err := (&service.IssueWakeupService{Tasks: h.TaskService}).SetChildDoneDefault(r.Context(), parseUUID(workspaceID), in.Enabled, in.Instruction); err != nil {+ if errors.Is(err, service.ErrWakeupInput) {+ writeError(w, 400, err.Error())+ return+ }+ slog.Warn("update workspace system wakeup failed", "error", err, "workspace_id", workspaceID)+ writeError(w, 500, "could not save system wakeup")+ return+ }+ rules, err := h.workspaceSystemWakeups(r, parseUUID(workspaceID))+ if err != nil {+ writeError(w, 500, "could not load system wakeups")+ return+ }+ writeJSON(w, 200, rules)+}diff --git a/server/internal/handler/issue_system_wakeup_test.go b/server/internal/handler/issue_system_wakeup_test.gonew file mode 100644index 0000000000..cf4dfe05ce--- /dev/null+++ b/server/internal/handler/issue_system_wakeup_test.go@@ -0,0 +1,226 @@+package handler++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+)++func createStagedChild(t *testing.T, parentID string, stage int, status string) IssueResponse {+ t.Helper()+ w := httptest.NewRecorder()+ testHandler.CreateIssue(w, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "staged child " + time.Now().Format(time.RFC3339Nano), "status": status,+ "parent_issue_id": parentID, "stage": stage,+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("create staged child: %d %s", w.Code, w.Body.String())+ }+ var child IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&child); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { cleanupChildDoneIssue(child.ID) })+ return child+}++func listSystemWakeupsFor(t *testing.T, issueID string) []systemWakeupResponse {+ t.Helper()+ w := httptest.NewRecorder()+ testHandler.ListIssueSystemWakeups(w, withURLParam(newRequest("GET", "/api/issues/"+issueID+"/system-wakeups", nil), "id", issueID))+ if w.Code != http.StatusOK {+ t.Fatalf("list system wakeups: %d %s", w.Code, w.Body.String())+ }+ var rules []systemWakeupResponse+ if err := json.NewDecoder(w.Body).Decode(&rules); err != nil {+ t.Fatal(err)+ }+ return rules+}++func putChildDoneRule(t *testing.T, issueID string, body map[string]any, headers ...string) *httptest.ResponseRecorder {+ t.Helper()+ w := httptest.NewRecorder()+ req := withURLParams(newRequest("PUT", "/api/issues/"+issueID+"/system-wakeups/child_done", body), "id", issueID, "rule", "child_done")+ for i := 0; i+1 < len(headers); i += 2 {+ req.Header.Set(headers[i], headers[i+1])+ }+ testHandler.UpdateIssueSystemWakeup(w, req)+ return w+}++func TestSystemWakeupDescribesUnstagedWait(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ rules := listSystemWakeupsFor(t, fx.parent.ID)+ if len(rules) != 1 {+ t.Fatalf("expected the child-done rule, got %+v", rules)+ }+ rule := rules[0]+ if rule.Rule != "child_done" || !rule.Enabled || rule.Staged || rule.Stage != nil || rule.Total != 1 || rule.Remaining != 1 {+ t.Fatalf("unexpected rule: %+v", rule)+ }+ if len(rule.Waiting) != 1 || rule.Waiting[0] != fx.child.Identifier || rule.Blocked != "no_assignee" || rule.DefaultInstruction != service.ChildDoneDefaultInstruction {+ t.Fatalf("waiting/blocked: %+v", rule)+ }+ updateChildStatus(t, fx.child.ID, "done")+ if rules = listSystemWakeupsFor(t, fx.parent.ID); len(rules) != 0 {+ t.Fatalf("finished sub-issues still reported: %+v", rules)+ }+ if rules = listSystemWakeupsFor(t, fx.child.ID); len(rules) != 0 {+ t.Fatalf("issue without sub-issues reports a rule: %+v", rules)+ }+}++func TestSystemWakeupDescribesLowestOpenStage(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ // The fixture child is unstaged; staged siblings form the stages.+ createStagedChild(t, fx.parent.ID, 1, "done")+ open := createStagedChild(t, fx.parent.ID, 1, "in_progress")+ later := createStagedChild(t, fx.parent.ID, 2, "backlog")+ rules := listSystemWakeupsFor(t, fx.parent.ID)+ if len(rules) != 1 || !rules[0].Staged || rules[0].Stage == nil || *rules[0].Stage != 1 {+ t.Fatalf("expected stage 1: %+v", rules)+ }+ if rules[0].Total != 2 || rules[0].Remaining != 1 || rules[0].Waiting[0] != open.Identifier {+ t.Fatalf("stage progress: %+v", rules[0])+ }+ // Once every stage closed, the rule waits for the unstaged sub-issue.+ updateChildStatus(t, open.ID, "done")+ updateChildStatus(t, later.ID, "done")+ rules = listSystemWakeupsFor(t, fx.parent.ID)+ if len(rules) != 1 || rules[0].Staged || rules[0].Stage != nil || rules[0].Remaining != 1 || rules[0].Waiting[0] != fx.child.Identifier {+ t.Fatalf("expected the unstaged wait: %+v", rules)+ }+}++// Turning the rule off for one issue stops it there; an instruction set on the+// issue replaces the default in the run the assignee reads.+func TestSystemWakeupOverrideControlsChildDone(t *testing.T) {+ t.Run("disabled", func(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ if w := putChildDoneRule(t, fx.parent.ID, map[string]any{"enabled": false, "instruction": ""}); w.Code != http.StatusOK {+ t.Fatalf("disable: %d %s", w.Code, w.Body.String())+ }+ if rules := listSystemWakeupsFor(t, fx.parent.ID); len(rules) != 1 || rules[0].Enabled || !rules[0].Customized || rules[0].ID == "" {+ t.Fatalf("override not reported: %+v", rules)+ }+ updateChildStatus(t, fx.child.ID, "done")+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 0 {+ t.Fatalf("disabled rule still fired: %d entries", got)+ }+ })+ t.Run("instruction", func(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", handlerTestAgentID(t))+ if w := putChildDoneRule(t, fx.parent.ID, map[string]any{"instruction": " Ask Jiayuan to confirm the window first. "}); w.Code != http.StatusOK {+ t.Fatalf("save: %d %s", w.Code, w.Body.String())+ }+ updateChildStatus(t, fx.child.ID, "done")+ runs := childDoneRuns(t, fx.parent.ID)+ if len(runs) != 1 || !strings.Contains(runs[0].Note, "Instruction:\nAsk Jiayuan to confirm the window first.\n") || strings.Contains(runs[0].Note, service.ChildDoneDefaultInstruction) {+ t.Fatalf("issue instruction not delivered: %+v", runs)+ }+ })+ t.Run("validation", func(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ if w := putChildDoneRule(t, fx.parent.ID, map[string]any{"enabled": true, "instruction": strings.Repeat("x", 4001)}); w.Code != http.StatusBadRequest {+ t.Fatalf("oversized instruction: %d", w.Code)+ }+ if w := putChildDoneRule(t, fx.parent.ID, map[string]any{"enabled": true, "extra": 1}); w.Code != http.StatusBadRequest {+ t.Fatalf("unknown field: %d", w.Code)+ }+ w := httptest.NewRecorder()+ testHandler.UpdateIssueSystemWakeup(w, withURLParams(newRequest("PUT", "/api/issues/"+fx.parent.ID+"/system-wakeups/other", map[string]any{"enabled": true}), "id", fx.parent.ID, "rule", "other"))+ if w.Code != http.StatusNotFound {+ t.Fatalf("unknown rule: %d", w.Code)+ }+ })+ t.Run("agents cannot change it", func(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ agentID := handlerTestAgentID(t)+ run := dbfx.Task(t, agentID, testutil.Cols{"issue_id": fx.parent.ID, "runtime_id": testRuntimeID, "status": "running"})+ if w := putChildDoneRule(t, fx.parent.ID, map[string]any{"enabled": false}, "X-Agent-ID", agentID, "X-Task-ID", run, "X-Actor-Source", "task_token"); w.Code != http.StatusForbidden {+ t.Fatalf("agent change: %d %s", w.Code, w.Body.String())+ }+ })+ t.Run("not through the person's rule endpoints", func(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ if w := putChildDoneRule(t, fx.parent.ID, map[string]any{"enabled": true}); w.Code != http.StatusOK {+ t.Fatalf("create rule: %d", w.Code)+ }+ id := listSystemWakeupsFor(t, fx.parent.ID)[0].ID+ for name, handler := range map[string]http.HandlerFunc{"disable": testHandler.DisableIssueWakeup, "delete": testHandler.DeleteIssueWakeup, "trigger": testHandler.TriggerIssueWakeup} {+ rec := httptest.NewRecorder()+ handler(rec, withURLParams(newRequest("POST", "/", nil), "id", fx.parent.ID, "wakeupID", id))+ if rec.Code != http.StatusForbidden {+ t.Fatalf("%s a system rule: %d %s", name, rec.Code, rec.Body.String())+ }+ }+ })+}++// The workspace default applies to every rule nobody changed on its issue;+// owners and admins set it.+func TestWorkspaceSystemWakeupDefault(t *testing.T) {+ var settings []byte+ dbfx.QueryRow(t, "SELECT settings FROM workspace WHERE id=$1", testWorkspaceID).Scan(&settings)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), "UPDATE workspace SET settings=$2 WHERE id=$1", testWorkspaceID, settings)+ })+ follows := newChildDoneFixture(t, "in_progress")+ custom := newChildDoneFixture(t, "in_progress")+ if w := putChildDoneRule(t, custom.parent.ID, map[string]any{"enabled": true}); w.Code != http.StatusOK {+ t.Fatalf("customize: %d", w.Code)+ }+ if _, err := (&service.IssueWakeupService{Tasks: testHandler.TaskService}).BackfillChildDoneRules(context.Background(), 1000); err != nil {+ t.Fatal(err)+ }+ put := func(body map[string]any, user string) *httptest.ResponseRecorder {+ req := withURLParam(newRequest("PUT", "/api/system-wakeups/child_done", body), "rule", "child_done")+ req.Header.Set("X-User-ID", user)+ rec := httptest.NewRecorder()+ testHandler.UpdateWorkspaceSystemWakeup(rec, req)+ return rec+ }+ outsider := dbfx.User(t, "plain member", fmt.Sprintf("plain-%[email protected]", time.Now().UnixNano()))+ dbfx.Member(t, testWorkspaceID, outsider, "member")+ if rec := put(map[string]any{"enabled": false}, outsider); rec.Code != http.StatusForbidden {+ t.Fatalf("plain member changed the default: %d", rec.Code)+ }+ rec := put(map[string]any{"enabled": false, "instruction": "Wrap up in the parent."}, testUserID)+ if rec.Code != http.StatusOK {+ t.Fatalf("set default: %d %s", rec.Code, rec.Body.String())+ }+ var defaults []workspaceSystemWakeupResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &defaults); err != nil || len(defaults) != 1 || defaults[0].Enabled ||+ defaults[0].Instruction != "Wrap up in the parent." || defaults[0].BuiltinInstruction != service.ChildDoneDefaultInstruction || defaults[0].Customized < 1 {+ t.Fatalf("defaults = %+v (%v)", defaults, err)+ }+ if rules := listSystemWakeupsFor(t, follows.parent.ID); len(rules) != 1 || rules[0].Enabled || rules[0].DefaultInstruction != "Wrap up in the parent." {+ t.Fatalf("uncustomized rule did not follow the default: %+v", rules)+ }+ if rules := listSystemWakeupsFor(t, custom.parent.ID); len(rules) != 1 || !rules[0].Enabled {+ t.Fatalf("customized rule followed the default: %+v", rules)+ }+ updateChildStatus(t, follows.child.ID, "done")+ if got := len(childDoneEntries(t, follows.parent.ID)); got != 0 {+ t.Fatalf("rule off by default fired: %d", got)+ }+ // Turning the default back on does not fire for what closed meanwhile.+ if rec := put(map[string]any{"enabled": true}, testUserID); rec.Code != http.StatusOK {+ t.Fatalf("enable default: %d", rec.Code)+ }+ dbfx.Exec(t, "UPDATE issue SET status='in_review' WHERE id=$1", follows.parent.ID)+ runWakeupTick(t)+ if got := len(childDoneEntries(t, follows.parent.ID)); got != 0 {+ t.Fatalf("re-enabling fired for an old fact: %d", got)+ }+}diff --git a/server/internal/handler/issue_triage_guard.go b/server/internal/handler/issue_triage_guard.goindex b3ddaa945f..2c88a1412e 100644--- a/server/internal/handler/issue_triage_guard.go+++ b/server/internal/handler/issue_triage_guard.go@@ -24,7 +24,7 @@ import (// a separate action that links rather than re-parents, so a Triage entry// hanging off a parent is a half-state the product never asks for;// - a child in Triage carries a proposed status, so it is never terminal.-// stageBarrierClosed would wait on it forever — holding the whole sibling+// the child_done stage frontier would wait on it forever — holding the whole sibling// set, or one stage's frontier — and ChildIssueProgress would count it in// the denominator. Both read through parent_issue_id, so refusing the write// is what keeps them out of reach.diff --git a/server/internal/handler/issue_wakeup.go b/server/internal/handler/issue_wakeup.goindex c21505f41f..6f069c4da6 100644--- a/server/internal/handler/issue_wakeup.go+++ b/server/internal/handler/issue_wakeup.go@@ -29,7 +29,7 @@ func (h *Handler) ListWorkspaceWakeups(w http.ResponseWriter, r *http.Request) {if kind == "" {kind = "all"}- if scope != "active" && scope != "all" && scope != "disabled" && scope != "ended" {+ if scope != "active" && scope != "all" && scope != "paused" && scope != "disabled" && scope != "ended" {writeError(w, 400, "invalid wakeup scope")return}@@ -48,6 +48,11 @@ func (h *Handler) ListWorkspaceWakeups(w http.ResponseWriter, r *http.Request) {*dst = v}}+ source := params.Get("source")+ if source != "" && source != "member" && source != "agent" && source != "system" {+ writeError(w, 400, "invalid wakeup source")+ return+ }search := strings.TrimSpace(params.Get("search"))if len(search) > 256 {writeError(w, 400, "search too long")@@ -87,7 +92,7 @@ func (h *Handler) ListWorkspaceWakeups(w http.ResponseWriter, r *http.Request) {}result, err := h.Queries.ListWorkspaceWakeups(r.Context(), db.ListWorkspaceWakeupsParams{WorkspaceID: parseUUID(workspaceID), AgentIds: ids, MemberID: managerID, IsAdmin: isAdmin,- Scope: scope, Kind: kind, AgentID: agentID, Search: search, PageLimit: int32(limit), PageOffset: int32(page),+ Scope: scope, Kind: kind, Source: source, AgentID: agentID, Search: search, PageLimit: int32(limit), PageOffset: int32(page),})if err != nil {wakeupError(w, err)@@ -172,10 +177,16 @@ func (h *Handler) ListWorkspaceWakeupSummaries(w http.ResponseWriter, r *http.RewakeupError(w, err)return}- if rows == nil {- rows = []db.ListWorkspaceWakeupSummaryRowsRow{}+ // The condition is JSON; sqlc cannot type it through the window CTE.+ type summaryRow struct {+ db.ListWorkspaceWakeupSummaryRowsRow+ Condition json.RawMessage `json:"condition"`}- writeJSON(w, 200, rows)+ out := make([]summaryRow, 0, len(rows))+ for _, row := range rows {+ out = append(out, summaryRow{ListWorkspaceWakeupSummaryRowsRow: row, Condition: json.RawMessage(row.Condition)})+ }+ writeJSON(w, 200, out)}func (h *Handler) CreateIssueWakeup(w http.ResponseWriter, r *http.Request) {@@ -318,3 +329,163 @@ func (h *Handler) EditIssueWakeupInstruction(w http.ResponseWriter, r *http.Requ}w.WriteHeader(http.StatusNoContent)}++// wakeupMember resolves the human a management request acts for, the same way+// as the create and disable endpoints.+func (h *Handler) wakeupMember(w http.ResponseWriter, r *http.Request, issue db.Issue) (pgtype.UUID, bool) {+ actorType, actorID := h.resolveActor(r, requestUserID(r), uuidToString(issue.WorkspaceID))+ originator := h.invokeOriginatorFromRequest(r, actorType, actorID)+ if originator == "" {+ writeError(w, 403, "a human originator is required")+ return pgtype.UUID{}, false+ }+ return parseUUID(originator), true+}++// TriggerIssueWakeup is "wake now": one run of the rule, as if it fired.+func (h *Handler) TriggerIssueWakeup(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "wakeupID"), "wakeup id")+ if !ok {+ return+ }+ member, ok := h.wakeupMember(w, r, issue)+ if !ok {+ return+ }+ svc := service.IssueWakeupService{Tasks: h.TaskService}+ if err := svc.Trigger(r.Context(), issue.ID, id, member); err != nil {+ wakeupError(w, err)+ return+ }+ w.WriteHeader(http.StatusNoContent)+}++func (h *Handler) DeleteIssueWakeup(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "wakeupID"), "wakeup id")+ if !ok {+ return+ }+ member, ok := h.wakeupMember(w, r, issue)+ if !ok {+ return+ }+ svc := service.IssueWakeupService{Tasks: h.TaskService}+ if err := svc.Delete(r.Context(), issue.ID, id, member); err != nil {+ wakeupError(w, err)+ return+ }+ w.WriteHeader(http.StatusNoContent)+}++// CheckInIssueWakeup ends a scheduled check silently: the calling run, which+// the rule itself started, records a note instead of posting a comment.+func (h *Handler) CheckInIssueWakeup(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "wakeupID"), "wakeup id")+ if !ok {+ return+ }+ var in struct {+ Note string `json:"note"`+ }+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8192))+ dec.DisallowUnknownFields()+ if err := dec.Decode(&in); err != nil {+ writeError(w, 400, "invalid check-in body")+ return+ }+ actorType, actorID := h.resolveActor(r, requestUserID(r), uuidToString(issue.WorkspaceID))+ task := h.wakeupSourceTaskID(r)+ if actorType != "agent" || !task.Valid {+ writeError(w, 403, "only the run a wakeup started can check in")+ return+ }+ svc := service.IssueWakeupService{Tasks: h.TaskService}+ if err := svc.CheckIn(r.Context(), issue.ID, id, task, actorID, in.Note); err != nil {+ wakeupError(w, err)+ return+ }+ w.WriteHeader(http.StatusNoContent)+}++type wakeupRunResponse struct {+ ID string `json:"id"`+ Status string `json:"status"`+ CreatedAt string `json:"created_at"`+ StartedAt *string `json:"started_at"`+ CompletedAt *string `json:"completed_at"`+ CheckinNote string `json:"checkin_note"`+ Triggers []string `json:"triggers"`+ Commented bool `json:"commented"`+}++// ListIssueWakeupRuns returns a rule's latest runs for its trigger history.+func (h *Handler) ListIssueWakeupRuns(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "wakeupID"), "wakeup id")+ if !ok {+ return+ }+ rule, err := h.Queries.GetIssueWakeup(r.Context(), db.GetIssueWakeupParams{ID: id, WorkspaceID: issue.WorkspaceID})+ if err != nil || rule.IssueID != issue.ID {+ writeError(w, 404, "wakeup not found")+ return+ }+ rows, err := h.Queries.ListWakeupRuns(r.Context(), db.ListWakeupRunsParams{WakeupID: uuidToString(id), IssueID: issue.ID})+ if err != nil {+ wakeupError(w, err)+ return+ }+ out := make([]wakeupRunResponse, 0, len(rows))+ for _, row := range rows {+ triggers := row.Triggers+ if triggers == nil {+ triggers = []string{}+ }+ out = append(out, wakeupRunResponse{+ ID: uuidToString(row.ID), Status: row.Status, CreatedAt: timestampToString(row.CreatedAt),+ StartedAt: timestampToPtr(row.StartedAt), CompletedAt: timestampToPtr(row.CompletedAt),+ CheckinNote: row.CheckinNote, Triggers: triggers, Commented: row.Commented,+ })+ }+ writeJSON(w, 200, out)+}++// ListPausedWakeups names the open issues whose rules the platform paused, for+// board cues.+func (h *Handler) ListPausedWakeups(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ if _, ok := h.workspaceMember(w, r, workspaceID); !ok {+ return+ }+ rows, err := h.Queries.ListPausedWakeupIssues(r.Context(), parseUUID(workspaceID))+ if err != nil {+ wakeupError(w, err)+ return+ }+ type paused struct {+ IssueID string `json:"issue_id"`+ ID string `json:"id"`+ AgentID string `json:"agent_id"`+ Reason string `json:"paused_reason"`+ }+ out := make([]paused, 0, len(rows))+ for _, row := range rows {+ out = append(out, paused{IssueID: uuidToString(row.IssueID), ID: uuidToString(row.ID), AgentID: uuidToString(row.AgentID), Reason: row.PausedReason.String})+ }+ writeJSON(w, 200, out)+}diff --git a/server/internal/handler/issue_wakeup_join_test.go b/server/internal/handler/issue_wakeup_join_test.gonew file mode 100644index 0000000000..81d5bff670--- /dev/null+++ b/server/internal/handler/issue_wakeup_join_test.go@@ -0,0 +1,260 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// actAsRun makes a request come from an agent's run, as the CLI does inside a+// task.+func actAsRun(req *http.Request, agentID, taskID string) *http.Request {+ req.Header.Set("X-Agent-ID", agentID)+ req.Header.Set("X-Task-ID", taskID)+ req.Header.Set("X-Actor-Source", "task_token")+ return req+}++func setStatusAsRun(t *testing.T, issueID, status, agentID, taskID string) {+ t.Helper()+ w := httptest.NewRecorder()+ req := withURLParam(newRequest("PUT", "/api/issues/"+issueID, map[string]any{"status": status}), "id", issueID)+ if agentID != "" {+ req = actAsRun(req, agentID, taskID)+ }+ testHandler.UpdateIssue(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("set status %q: %d %s", status, w.Code, w.Body.String())+ }+}++func commentOn(t *testing.T, issueID, content, agentID, taskID string) {+ t.Helper()+ w := httptest.NewRecorder()+ req := withURLParam(newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{"content": content}), "id", issueID)+ if agentID != "" {+ req = actAsRun(req, agentID, taskID)+ }+ testHandler.CreateComment(w, req)+ if w.Code != http.StatusCreated && w.Code != http.StatusOK {+ t.Fatalf("comment: %d %s", w.Code, w.Body.String())+ }+}++func wakeupRunsOf(t *testing.T, wakeupID string) int {+ t.Helper()+ return dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id' = $1`, wakeupID)+}++func lastWakeupOutcome(t *testing.T, issueID string) (outcome, taskID string) {+ t.Helper()+ var raw []byte+ dbfx.QueryRow(t, `SELECT details FROM activity_log WHERE issue_id = $1 AND action = 'wakeup_triggered'+ ORDER BY created_at DESC, id DESC LIMIT 1`, issueID).Scan(&raw)+ var details struct {+ Outcome string `json:"outcome"`+ TaskID string `json:"task_id"`+ }+ _ = json.Unmarshal(raw, &details)+ return details.Outcome, details.TaskID+}++// claimRun claims a queued run as a daemon does and returns what its prompt+// gets from wakeups that joined it. Only a daemon that advertises+// joined-wakeups-v1 takes them along.+func claimRun(t *testing.T, taskID string, rendersJoined bool) string {+ t.Helper()+ ctx := context.Background()+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = clock_timestamp() WHERE id = $1`, taskID)+ task, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ runtime, err := testHandler.Queries.GetAgentRuntime(ctx, task.RuntimeID)+ if err != nil {+ t.Fatal(err)+ }+ req := newDaemonTokenRequest("POST", "/claim", nil, testWorkspaceID, "joined-wakeups-test")+ if rendersJoined {+ req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityJoinedWakeupsV1)+ }+ resp, _, _, _, _, failure := testHandler.buildClaimedTaskResponse(req, &task, runtime, uuidToString(task.RuntimeID), testWorkspaceID)+ if failure != nil {+ t.Fatalf("claim: %+v", failure)+ }+ return resp.WakeupJoined+}++// startRun marks a claimed run started, as the daemon's start call does.+func startRun(t *testing.T, taskID string) {+ t.Helper()+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'running', started_at = clock_timestamp() WHERE id = $1`, taskID)+}++func createRule(t *testing.T, issueID, agentID string, source pgtype.UUID, in service.WakeupInput) string {+ t.Helper()+ in.AgentID = agentID+ w, err := (&service.IssueWakeupService{Tasks: testHandler.TaskService}).Create(context.Background(), parseUUID(issueID), parseUUID(testUserID), source, in)+ if err != nil {+ t.Fatal(err)+ }+ return uuidToString(w.ID)+}++// #8849: the parent's agent closes the last sub-issue of a stage from its own+// run on the parent. That run knows, so the rule records the stage without+// queuing a second run; once that run has ended, or when someone else closes+// the stage, the agent is woken as before.+func TestChildDoneDoesNotWakeTheRunThatClosedTheStage(t *testing.T) {+ cases := []struct {+ name string+ runStatus string+ byAgent bool+ wantRuns int+ wantEntry string+ }{+ {"own run still going", "running", true, 0, "acknowledged"},+ {"own run already ended", "completed", true, 1, "woke"},+ {"someone else closed it", "running", false, 1, "woke"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ agentID := handlerTestAgentID(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)+ run := dbfx.Task(t, agentID, testutil.Cols{"issue_id": fx.parent.ID, "runtime_id": testRuntimeID, "status": tc.runStatus})+ if tc.byAgent {+ setStatusAsRun(t, fx.child.ID, "done", agentID, run)+ } else {+ updateChildStatus(t, fx.child.ID, "done")+ }+ if runs := childDoneRuns(t, fx.parent.ID); len(runs) != tc.wantRuns {+ t.Fatalf("runs = %+v, want %d", runs, tc.wantRuns)+ }+ if entries := childDoneEntries(t, fx.parent.ID); len(entries) != 1 || entries[0].Outcome != tc.wantEntry {+ t.Fatalf("entries = %+v, want %s", entries, tc.wantEntry)+ }+ })+ }+}++// A comment from the agent itself never wakes it; a member's comment does.+func TestWakeupSkipsTheAgentsOwnComment(t *testing.T) {+ issue := dbfx.Issue(t, "own comment")+ t.Cleanup(func() { cleanupChildDoneIssue(issue) })+ agentID := handlerTestAgentID(t)+ rule := createRule(t, issue, agentID, pgtype.UUID{}, service.WakeupInput{Instruction: "Reply to new comments", Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}})+ run := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issue, "runtime_id": testRuntimeID, "status": "running"})++ commentOn(t, issue, "Deployed the fix.", agentID, run)+ runWakeupTick(t)+ if n := wakeupRunsOf(t, rule); n != 0 {+ t.Fatalf("the agent's own comment started %d runs", n)+ }+ if outcome, _ := lastWakeupOutcome(t, issue); outcome != "acknowledged" {+ t.Fatalf("outcome = %q, want acknowledged", outcome)+ }++ commentOn(t, issue, "Can you double-check staging?", "", "")+ runWakeupTick(t)+ if n := wakeupRunsOf(t, rule); n != 1 {+ t.Fatalf("a member's comment started %d runs, want 1", n)+ }+}++// A rule that fires while its agent already has a run waiting on the issue+// keeps its inputs for that run: no second run, and the run carries the+// instruction and every fact once it is claimed.+func TestWakeupJoinsTheAgentsWaitingRun(t *testing.T) {+ issue := dbfx.Issue(t, "join waiting run")+ t.Cleanup(func() { cleanupChildDoneIssue(issue) })+ agentID := handlerTestAgentID(t)+ setIssueAssigneeDirect(t, issue, "agent", agentID)+ waiting := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issue, "runtime_id": testRuntimeID, "status": "queued", "originator_user_id": testUserID, "accountable_user_id": testUserID})+ rule := createRule(t, issue, agentID, pgtype.UUID{}, service.WakeupInput{Instruction: "Summarize the discussion", Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}})++ commentOn(t, issue, "Here is more context.", "", "")+ runWakeupTick(t)+ commentOn(t, issue, "One more thing.", "", "")+ runWakeupTick(t)+ if n := wakeupRunsOf(t, rule); n != 0 {+ t.Fatalf("the rule queued %d runs of its own", n)+ }++ notes := claimRun(t, waiting, true)+ if strings.Count(notes, "Wakeup "+rule) != 1 || !strings.Contains(notes, "Summarize the discussion") || strings.Count(notes, "comment.created") != 2 {+ t.Fatalf("joined notes = %q", notes)+ }+ startRun(t, waiting)+ runWakeupTick(t)+ outcome, taskID := lastWakeupOutcome(t, issue)+ if outcome != "merged" || taskID != waiting {+ t.Fatalf("outcome = %q task = %q, want merged into %s", outcome, taskID, waiting)+ }+ if n := wakeupRunsOf(t, rule); n != 0 {+ t.Fatalf("the rule queued %d runs of its own", n)+ }+}++// A daemon that cannot render joined wakeups claims the waiting run without+// them; the rule then starts its own run.+func TestWakeupRunsOnItsOwnAfterAnOlderDaemonsClaim(t *testing.T) {+ issue := dbfx.Issue(t, "older daemon")+ t.Cleanup(func() { cleanupChildDoneIssue(issue) })+ agentID := handlerTestAgentID(t)+ waiting := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issue, "runtime_id": testRuntimeID, "status": "queued", "originator_user_id": testUserID, "accountable_user_id": testUserID})+ rule := createRule(t, issue, agentID, pgtype.UUID{}, service.WakeupInput{Instruction: "Summarize the discussion", Kind: "event", EventTypes: []string{"comment.created"}})++ commentOn(t, issue, "Here is more context.", "", "")+ runWakeupTick(t)+ if notes := claimRun(t, waiting, false); notes != "" {+ t.Fatalf("an older daemon's claim got %q", notes)+ }+ runWakeupTick(t)+ if n := wakeupRunsOf(t, rule); n != 1 {+ t.Fatalf("runs of the rule = %d, want 1", n)+ }+}++// A condition the agent's own unfinished run satisfied does not wake it when+// the agent set up the rule; a person's rule still does, because the running+// agent does not have that instruction.+func TestConditionRuleAndTheAgentsOwnChange(t *testing.T) {+ cases := []struct {+ name string+ ownRule bool+ wantRuns int+ }{+ {"rule the agent set up", true, 0},+ {"rule a person set up", false, 1},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ issue := dbfx.Issue(t, "own condition", testutil.Cols{"status": "in_progress"})+ t.Cleanup(func() { cleanupChildDoneIssue(issue) })+ agentID := handlerTestAgentID(t)+ var source pgtype.UUID+ if tc.ownRule {+ earlier := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issue, "runtime_id": testRuntimeID, "status": "completed"})+ source = parseUUID(earlier)+ }+ rule := createRule(t, issue, agentID, source, service.WakeupInput{Instruction: "Run the release checklist", Kind: "event",+ Condition: json.RawMessage(`{"type":"issue_field","field":"status","value":"in_review"}`)})+ runWakeupTick(t) // records the starting state+ run := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issue, "runtime_id": testRuntimeID, "status": "running"})+ setStatusAsRun(t, issue, "in_review", agentID, run)+ runWakeupTick(t)+ if n := wakeupRunsOf(t, rule); n != tc.wantRuns {+ t.Fatalf("runs = %d, want %d", n, tc.wantRuns)+ }+ })+ }+}diff --git a/server/internal/handler/issue_wakeup_v2_test.go b/server/internal/handler/issue_wakeup_v2_test.gonew file mode 100644index 0000000000..308685b336--- /dev/null+++ b/server/internal/handler/issue_wakeup_v2_test.go@@ -0,0 +1,273 @@+package handler++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// A status write outside the HTTP handlers still records the child's change+// in its own transaction; the sweep turns it into the parent's wake exactly+// once.+func TestChildDoneRecordedByAnyWriterAndSweptOnce(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ sweep := func() {+ t.Helper()+ if err := (&service.IssueWakeupService{Tasks: testHandler.TaskService}).SweepChildEvents(context.Background()); err != nil {+ t.Fatal(err)+ }+ }+ dbfx.Exec(t, "UPDATE issue SET status='done' WHERE id=$1", fx.child.ID)+ if n := dbfx.Count(t, "SELECT count(*) FROM issue_child_event WHERE parent_id=$1 AND child_id=$2 AND kind='closed' AND processed_at IS NULL", fx.parent.ID, fx.child.ID); n != 1 {+ t.Fatalf("recorded closings = %d, want 1", n)+ }+ // Moving between closed statuses is not a change the rule cares about.+ dbfx.Exec(t, "UPDATE issue SET status='cancelled' WHERE id=$1", fx.child.ID)+ if n := dbfx.Count(t, "SELECT count(*) FROM issue_child_event WHERE parent_id=$1 AND kind IN ('closed','reopened')", fx.parent.ID); n != 1 {+ t.Fatalf("closed-to-closed recorded %d changes, want 1", n)+ }+ // Fresh rows belong to the request that wrote them; the sweep waits.+ sweep()+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 0 {+ t.Fatalf("sweep took a fresh change: %d entries", got)+ }+ dbfx.Exec(t, "UPDATE issue_child_event SET created_at=created_at-interval '1 minute' WHERE parent_id=$1", fx.parent.ID)+ sweep()+ sweep()+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 1 {+ t.Fatalf("swept change fired %d entries, want 1", got)+ }+ if n := dbfx.Count(t, "SELECT count(*) FROM issue_child_event WHERE parent_id=$1 AND processed_at IS NULL", fx.parent.ID); n != 0 {+ t.Fatalf("%d changes left pending", n)+ }+}++// The request path processes its own change; a later sweep finds nothing.+func TestChildDoneRequestPathLeavesNothingToSweep(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ updateChildStatus(t, fx.child.ID, "done")+ dbfx.Exec(t, "UPDATE issue_child_event SET created_at=created_at-interval '1 hour',claimed_at=claimed_at-interval '1 hour' WHERE parent_id=$1", fx.parent.ID)+ if err := (&service.IssueWakeupService{Tasks: testHandler.TaskService}).SweepChildEvents(context.Background()); err != nil {+ t.Fatal(err)+ }+ if got := len(childDoneEntries(t, fx.parent.ID)); got != 1 {+ t.Fatalf("request plus sweep fired %d entries, want 1", got)+ }+}++// A rule created while the workspace default is off stays off until the+// issue sets its own.+func TestChildDoneWorkspaceDefault(t *testing.T) {+ var settings []byte+ dbfx.QueryRow(t, "SELECT settings FROM workspace WHERE id=$1", testWorkspaceID).Scan(&settings)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), "UPDATE workspace SET settings=$2 WHERE id=$1", testWorkspaceID, settings)+ })+ dbfx.Exec(t, `UPDATE workspace SET settings=settings||'{"system_wakeup_child_done":false}' WHERE id=$1`, testWorkspaceID)++ off := newChildDoneFixture(t, "in_progress")+ if rules := listSystemWakeupsFor(t, off.parent.ID); len(rules) != 1 || rules[0].Enabled || rules[0].WorkspaceDefault {+ t.Fatalf("workspace default not applied: %+v", rules)+ }+ updateChildStatus(t, off.child.ID, "done")+ if got := len(childDoneEntries(t, off.parent.ID)); got != 0 {+ t.Fatalf("rule off by default still fired: %d", got)+ }+ // The issue's own setting wins over the default; a partial body keeps+ // the instruction.+ on := newChildDoneFixture(t, "in_progress")+ if w := putChildDoneRule(t, on.parent.ID, map[string]any{"instruction": "Check the window first."}); w.Code != http.StatusOK {+ t.Fatalf("save instruction: %d %s", w.Code, w.Body.String())+ }+ if w := putChildDoneRule(t, on.parent.ID, map[string]any{"enabled": true}); w.Code != http.StatusOK {+ t.Fatalf("enable: %d %s", w.Code, w.Body.String())+ }+ if rules := listSystemWakeupsFor(t, on.parent.ID); len(rules) != 1 || !rules[0].Enabled || rules[0].Instruction != "Check the window first." {+ t.Fatalf("override: %+v", rules)+ }+ updateChildStatus(t, on.child.ID, "done")+ if got := len(childDoneEntries(t, on.parent.ID)); got != 1 {+ t.Fatalf("issue override on: %d entries, want 1", got)+ }+}++type workspaceWakeupRow struct {+ ID string `json:"id"`+ IssueID string `json:"issue_id"`+ Source string `json:"source"`+ Rule *string `json:"rule"`+ SystemStage *int `json:"system_stage"`+ SystemRemaining *int `json:"system_remaining"`+ Revision *int64 `json:"revision"`+ Enabled bool `json:"enabled"`+ PausedReason *string `json:"paused_reason"`+ Runs7d int `json:"runs_7d"`+ CanManage bool `json:"can_manage"`+ Condition any `json:"condition"`+}++func listWorkspaceWakeupRows(t *testing.T, query string) ([]workspaceWakeupRow, map[string]int) {+ t.Helper()+ rec := httptest.NewRecorder()+ testHandler.ListWorkspaceWakeups(rec, newRequest("GET", "/api/issue-wakeups?"+query, nil))+ if rec.Code != 200 {+ t.Fatalf("list %s: %d %s", query, rec.Code, rec.Body.String())+ }+ var out struct {+ Items []workspaceWakeupRow `json:"items"`+ Counts map[string]int `json:"counts"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {+ t.Fatal(err)+ }+ return out.Items, out.Counts+}++func TestWorkspaceWakeupsListSourcesSystemRulesAndPaused(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ createStagedChild(t, fx.parent.ID, 1, "done")+ createStagedChild(t, fx.parent.ID, 1, "todo")+ createStagedChild(t, fx.parent.ID, 2, "backlog")+ agent := dbfx.Agent(t, "list target", testRuntimeID)+ issue := dbfx.Issue(t, "list rules")+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id=$1)", issue)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)+ dbfx.Cleanup(t, "DELETE FROM activity_log WHERE issue_id=$1", issue)+ svc := service.IssueWakeupService{Tasks: testHandler.TaskService}+ create := func(in service.WakeupInput) string {+ t.Helper()+ in.AgentID, in.Instruction = agent, "check"+ w, err := svc.Create(context.Background(), parseUUID(issue), parseUUID(testUserID), pgtype.UUID{}, in)+ if err != nil {+ t.Fatal(err)+ }+ return uuidToString(w.ID)+ }+ member := create(service.WakeupInput{Kind: "event", Condition: json.RawMessage(`{"type":"issue_field","field":"status","value":"in_review"}`)})+ paused := create(service.WakeupInput{Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}})+ dbfx.Exec(t, "UPDATE issue_wakeup SET enabled=false,paused_reason='rate',disabled_at=now() WHERE id=$1", paused)+ for range 2 {+ dbfx.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testRuntimeID, "status": "completed", "context": fmt.Sprintf(`{"wakeup_id":%q}`, paused)})+ }++ if w := putChildDoneRule(t, fx.parent.ID, map[string]any{"instruction": "Advance the next stage."}); w.Code != http.StatusOK {+ t.Fatalf("create system rule: %d", w.Code)+ }+ rows, counts := listWorkspaceWakeupRows(t, "scope=all&limit=100")+ byID := map[string]workspaceWakeupRow{}+ var system workspaceWakeupRow+ ok := false+ for _, r := range rows {+ byID[r.ID] = r+ if r.IssueID == fx.parent.ID && r.Source == "system" {+ system, ok = r, true+ }+ }+ if !ok || system.Rule == nil || *system.Rule != "child_done" || system.SystemStage == nil || *system.SystemStage != 1 ||+ system.SystemRemaining == nil || *system.SystemRemaining != 1 || !system.Enabled || !system.CanManage || system.Revision == nil {+ t.Fatalf("system row: %+v (found %t)", system, ok)+ }+ if byID[member].Source != "member" || byID[member].Condition == nil {+ t.Fatalf("member row: %+v", byID[member])+ }+ if byID[paused].PausedReason == nil || *byID[paused].PausedReason != "rate" || byID[paused].Runs7d != 2 {+ t.Fatalf("paused row: %+v", byID[paused])+ }+ if counts["paused"] < 1 {+ t.Fatalf("paused count missing: %+v", counts)+ }+ rows, _ = listWorkspaceWakeupRows(t, "scope=paused&limit=100")+ for _, r := range rows {+ if r.PausedReason == nil {+ t.Fatalf("paused scope returned %+v", r)+ }+ }+ rows, _ = listWorkspaceWakeupRows(t, "scope=all&source=system&limit=100")+ for _, r := range rows {+ if r.Source != "system" {+ t.Fatalf("system filter returned %+v", r)+ }+ }+ rec := httptest.NewRecorder()+ testHandler.ListWorkspaceWakeups(rec, newRequest("GET", "/api/issue-wakeups?source=robots", nil))+ if rec.Code != 400 {+ t.Fatalf("bad source accepted: %d", rec.Code)+ }+ rec = httptest.NewRecorder()+ testHandler.ListPausedWakeups(rec, newRequest("GET", "/api/issue-wakeup-paused", nil))+ var pausedRows []struct {+ IssueID string `json:"issue_id"`+ ID string `json:"id"`+ Reason string `json:"paused_reason"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &pausedRows); err != nil || rec.Code != 200 {+ t.Fatalf("paused list %d: %s", rec.Code, rec.Body.String())+ }+ found := false+ for _, r := range pausedRows {+ found = found || (r.ID == paused && r.IssueID == issue && r.Reason == "rate")+ }+ if !found {+ t.Fatalf("paused rule missing: %+v", pausedRows)+ }+}++func TestIssueWakeupManagementEndpoints(t *testing.T) {+ issue := dbfx.Issue(t, "wakeup management")+ agent := dbfx.Agent(t, "management target", testRuntimeID)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id=$1)", issue)+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)+ dbfx.Cleanup(t, "DELETE FROM activity_log WHERE issue_id=$1", issue)+ dbfx.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id=$1", issue)+ svc := service.IssueWakeupService{Tasks: testHandler.TaskService}+ w, err := svc.Create(context.Background(), parseUUID(issue), parseUUID(testUserID), pgtype.UUID{}, service.WakeupInput{AgentID: agent, Kind: "every", IntervalSeconds: 3600, Instruction: "check staging"})+ if err != nil {+ t.Fatal(err)+ }+ id := uuidToString(w.ID)+ call := func(handler http.HandlerFunc, method string, body any, headers map[string]string) *httptest.ResponseRecorder {+ t.Helper()+ req := withURLParams(newRequest(method, "/", body), "id", issue, "wakeupID", id)+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ rec := httptest.NewRecorder()+ handler(rec, req)+ return rec+ }+ if rec := call(testHandler.TriggerIssueWakeup, "POST", nil, nil); rec.Code != http.StatusNoContent {+ t.Fatalf("wake now: %d %s", rec.Code, rec.Body.String())+ }+ var run string+ dbfx.QueryRow(t, "SELECT id::text FROM agent_task_queue WHERE context->>'wakeup_id'=$1", id).Scan(&run)+ dbfx.Exec(t, "UPDATE agent_task_queue SET status='running',started_at=now() WHERE id=$1", run)+ // A member cannot check in for the run.+ if rec := call(testHandler.CheckInIssueWakeup, "POST", map[string]any{"note": "fine"}, map[string]string{"X-Task-ID": run}); rec.Code != http.StatusForbidden {+ t.Fatalf("member check-in: %d %s", rec.Code, rec.Body.String())+ }+ agentHeaders := map[string]string{"X-Task-ID": run, "X-Agent-ID": agent, "X-Actor-Source": "task_token"}+ if rec := call(testHandler.CheckInIssueWakeup, "POST", map[string]any{"note": "Nothing changed"}, agentHeaders); rec.Code != http.StatusNoContent {+ t.Fatalf("agent check-in: %d %s", rec.Code, rec.Body.String())+ }+ rec := call(testHandler.ListIssueWakeupRuns, "GET", nil, nil)+ var runs []wakeupRunResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &runs); err != nil || rec.Code != 200 {+ t.Fatalf("runs %d: %s", rec.Code, rec.Body.String())+ }+ if len(runs) != 1 || runs[0].ID != run || runs[0].CheckinNote != "Nothing changed" || len(runs[0].Triggers) != 1 || runs[0].Triggers[0] != "wakeup.manual" {+ t.Fatalf("runs: %+v", runs)+ }+ if rec := call(testHandler.DeleteIssueWakeup, "DELETE", nil, nil); rec.Code != http.StatusNoContent {+ t.Fatalf("delete: %d %s", rec.Code, rec.Body.String())+ }+ if rec := call(testHandler.ListIssueWakeupRuns, "GET", nil, nil); rec.Code != http.StatusNotFound {+ t.Fatalf("runs of a deleted rule: %d", rec.Code)+ }+}diff --git a/server/internal/handler/pr_auto_complete.go b/server/internal/handler/pr_auto_complete.goindex 459ad7cbfa..354dd0ed20 100644--- a/server/internal/handler/pr_auto_complete.go+++ b/server/internal/handler/pr_auto_complete.go@@ -286,7 +286,9 @@ func (h *Handler) maybeAutoCompleteIssue(ctx context.Context, workspaceID, issueh.broadcastCancelledWakeups(ctx, updated.WorkspaceID, cancelledWakeups)// A merged PR is the most common way a sub-issue reaches done; the parent// hears about it on the same path as a manual status change.- h.notifyParentOfChildDone(ctx, issue, updated)+ if updated.ParentIssueID.Valid {+ h.processChildEvents(ctx, updated.ParentIssueID)+ }prefix := h.getIssuePrefix(ctx, issue.WorkspaceID)resp := issueToResponse(updated, prefix)diff --git a/server/internal/handler/squad_briefing.go b/server/internal/handler/squad_briefing.goindex 4e1fcb250c..c5054255ff 100644--- a/server/internal/handler/squad_briefing.go+++ b/server/internal/handler/squad_briefing.go@@ -105,8 +105,8 @@ Your responsibilities, in order:// job is the owning/guest permission boundary, drawn at the Agent Identity// layer (Instruction Precedence puts it above the workflow). The owning// leader needs the standing wrap-up instruction below — the @mention-dispatch-// shape (no child issues, so no child-done system comment) never produces a-// comment that asks for in_review, so without it the parent would sit in+// shape (no child issues, so no sub-issue wakeup) never produces a+// trigger that asks for in_review, so without it the parent would sit in// in_progress forever; the guest leader gets the prohibition instead// (squadParentStatusNotOwned). Both compositions are pinned by// handler/squad_parent_status_contract_test.go.diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex bcb456d62e..75049d9488 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -73,6 +73,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"issue": workspaceDelete,"issue_wakeup": workspaceDelete,"issue_wakeup_receipt": workspaceDelete,+ "issue_child_event": workspaceDelete,"issue_view": workspaceDelete,"issue_view_preference": workspaceDelete,"issue_dependency": workspaceDelete,diff --git a/server/internal/scheduler/jobs_child_done.go b/server/internal/scheduler/jobs_child_done.gonew file mode 100644index 0000000000..b6c9bf3b88--- /dev/null+++ b/server/internal/scheduler/jobs_child_done.go@@ -0,0 +1,37 @@+package scheduler++import (+ "context"+ "log/slog"+ "sync/atomic"+ "time"+)++type ChildEventSweeper interface {+ SweepChildEvents(context.Context) error+ BackfillChildDoneRules(context.Context, int32) (int, error)+}++// ChildEventSweepJob processes sub-issue changes that a write recorded but did+// not finish processing (a crash, a deploy, a transient database error); the+// rows themselves are the durable queue. Until every open parent has its+// child_done rule, it also creates rules for parents that predate it.+func ChildEventSweepJob(sweeper ChildEventSweeper) JobSpec {+ var backfilled atomic.Bool+ return JobSpec{+ Name: "issue_child_event_sweep", Cadence: 30 * time.Second, CatchUpMode: CatchUpLatestOnly, CatchUpWindow: time.Hour,+ RunTimeout: 45 * time.Second, StaleTimeout: time.Minute, HeartbeatInterval: 10 * time.Second,+ AllowStaleReentry: true, MaxAttempts: 1, Scopes: StaticScopes(ScopeGlobal),+ Handler: func(ctx context.Context, _ HandlerInput) (HandlerResult, error) {+ if !backfilled.Load() {+ created, err := sweeper.BackfillChildDoneRules(ctx, 200)+ if err != nil {+ slog.Warn("child_done backfill failed; will retry", "error", err)+ } else if created == 0 {+ backfilled.Store(true)+ }+ }+ return HandlerResult{}, sweeper.SweepChildEvents(ctx)+ },+ }+}diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex a86e015c09..af9d03a9b4 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -235,7 +235,7 @@ archived statuses remain readable via an explicit status filter.later re-trigger confirms the overall goal is met.- **`in_review`** is an accepted issue status. Some workflows use it while a PRis open and awaiting review; moving to it is an explicit mutation.-- **`done`** on a child issue posts a system comment on its parent.+- **`done`** on a child issue can wake its parent's assignee (see Stages).- **`cancelled`** is a terminal, user-driven decision to close the issue. Like`done` it enqueues no new agent work, but it does **not** stop tasks already inflight — a run in progress keeps going. To stop a running task, cancel the@@ -308,12 +308,13 @@ Creating every serial step as `todo` enqueues the whole chain at once.### Stages: order sub-issues into barrier groups`--stage <N>` (N >= 1) groups sub-issues under the same parent into ordered-stages. The server **tries once to wake the parent assignee when a whole stage-finishes** — i.e. every sub-issue in the lowest unfinished stage has reached a-terminal status (`done`/`cancelled`); a notification that fails is not replayed.-A completion that does not close a stage is silent (no comment, no wake). A-sibling set with **no** stages is one implicit stage, so the parent is woken-once when the *last* sub-issue finishes — not on every child.+stages. The platform's sub-issue wakeup **wakes the parent assignee when a stage+closes while a later stage is waiting** — every sub-issue up to that stage has+reached a terminal status (`done`/`cancelled`) — and **once more when every+sub-issue, staged or not, is closed**. A completion that closes nothing is+silent. A sibling set with **no** stages wakes the parent once, when the *last*+sub-issue finishes. A parent in `backlog` is not woken; it catches up once it+leaves backlog. A member assignee gets an inbox notification instead of a run.Advancement is agent-driven: the server only detects the closed barrier andwakes the parent assignee, who then decides whether to promote the next stage's@@ -327,8 +328,9 @@ multica issue create --title "Build" --parent <id> --assignee <agent> --stamultica issue create --title "Ship" --parent <id> --assignee <agent> --stage 3 --status backlog```-When both Stage 1 sub-issues finish you (the parent assignee) are woken with a-"Stage 1 complete" comment. Inspect the layout, then promote the next stage:+When both Stage 1 sub-issues finish you (the parent assignee) are woken by the+sub-issue wakeup; its `[WAKEUP]` block lists every stage and names the next one.+Inspect the layout, then promote the next stage:```bashmultica issue children <parent-id> # sub-issues grouped by stage@@ -420,6 +422,8 @@ current run. A wakeup persists on the issue; it is not a sleeping process.- `wakeup update <issue> <id>` uses the same flags as create and replaces the whole configuration, explicitly re-enabling it. Supply all intended fields. Old unclaimed work is withdrawn.- `wakeup disable <issue> <id>` stops future triggers and withdraws unclaimed work. Users can also turn it off in the issue sidebar. Closing/cancelling/completing the issue disables its wakeups; reopening does not restore them.- `--parent <comment-id>` keeps result delivery in the original thread.+- Give waits an end: `--expires-in 72h` (restarts if the rule is re-enabled) or `--expires-at <RFC3339>`. With `--on-timeout wake`, an event rule runs the target once with a `wakeup.timeout` fact when the deadline passes first; the default `end` stops quietly. Recurring checks should carry an end date.+- Members create the same rules from the issue sidebar. The parent's stage wake (see Stages above) appears there as a system rule; a member may turn it off for one issue or set its instruction, which your `[WAKEUP]` block then carries.Read current state with issue get, comment list, and run inspection beforejudging business completion. For CI, use the existing GitHub tools from a time@@ -430,6 +434,11 @@ continuous configuration. Every wakeup runs under ordinary execution and commentdelivery rules, even when a periodic check finds no change.Self-trigger protection excludes the registering run and runs started by the-same rule when their source identity is available. It does not prevent cycles-between different rules. Avoid mutually triggering continuous comment subscriptions;-when waiting for a person's reply, filter that member explicitly.+same rule when their source identity is available. Your own comments and issue+changes never wake you, and a condition your own unfinished run satisfies does+not wake you when you or the platform set the rule up. A wakeup that fires+while a run of yours for the same person is waiting to start on the issue+joins that run instead of starting another: its instruction and facts appear+in that run's `[WAKEUP — joined this run]` block, so handle them there. None of this prevents+cycles between different rules. Avoid mutually triggering continuous comment+subscriptions; when waiting for a person's reply, filter that member explicitly.diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.goindex c64b15d011..85f82eff32 100644--- a/server/internal/service/builtin_skills_test.go+++ b/server/internal/service/builtin_skills_test.go@@ -485,7 +485,7 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {// playbook — if they leave, the brief pointer dangles."todo starts work now, backlog parks it","`--stage <N>`",- "when a whole stage finishes",+ "wakes the parent assignee when a stage","multica issue status <child-id> todo",// MUL-6966 phase 1 retired the metadata write discipline// along with the brief section that pointed here. What thediff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex 7a3c3d0404..d6e015f639 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -90,7 +90,7 @@ type IssueCreateParams struct {Properties map[pgtype.UUID]json.RawMessageAllowDuplicate bool// Stage groups this issue into an ordered barrier group under its parent- // (NULL = unstaged). See issue_child_done.go for the staged-barrier wake.+ // (NULL = unstaged). See issue_wakeup_system.go for the staged-barrier wake.Stage pgtype.Int4// SourceContext is set only by the comment-scoped manual create endpoint.// Its immutable snapshot and cloned attachment rows commit in the samediff --git a/server/internal/service/issue_wakeup.go b/server/internal/service/issue_wakeup.goindex 90b3565db6..be17fa9053 100644--- a/server/internal/service/issue_wakeup.go+++ b/server/internal/service/issue_wakeup.go@@ -43,6 +43,63 @@ type WakeupInput struct {IntervalSeconds int64 `json:"interval_seconds"`CronExpression string `json:"cron_expression"`Timezone string `json:"timezone"`+ // A wakeup ends at an absolute deadline (expires_at) or after a relative+ // wait (expires_in_seconds) that restarts whenever the rule is re-enabled.+ // on_timeout is "end" (default) or, for event rules, "wake": run the target+ // once more to handle the missed deadline.+ ExpiresAt *time.Time `json:"expires_at"`+ ExpiresInSeconds int64 `json:"expires_in_seconds"`+ OnTimeout string `json:"on_timeout"`+ // Condition is a platform-evaluated predicate (see WakeupCondition). The+ // rule stays kind=event; its hint events are derived from the condition.+ Condition json.RawMessage `json:"condition"`+ // MaxFires caps how many runs a repeating rule may start. Repeating event+ // rules default to wakeupDefaultMaxFires.+ MaxFires int32 `json:"max_fires"`+}++func hasWakeupCondition(raw json.RawMessage) bool {+ return len(raw) > 0 && string(raw) != "null"+}++const maxWakeupSeconds = 31536000++// Expiry validates and resolves the rule's end. A single-time wakeup ends+// when it fires, so it takes no deadline. Relative waits are stored as a+// duration so enabling the rule again restarts the wait from "now".+func (s *IssueWakeupService) Expiry(in *WakeupInput, now time.Time) (pgtype.Timestamptz, pgtype.Int8, error) {+ bad := func(msg string) (pgtype.Timestamptz, pgtype.Int8, error) {+ return pgtype.Timestamptz{}, pgtype.Int8{}, fmt.Errorf("%w: %s", ErrWakeupInput, msg)+ }+ hasExpiry := in.ExpiresAt != nil || in.ExpiresInSeconds != 0+ switch {+ case in.OnTimeout != "" && in.OnTimeout != "end" && in.OnTimeout != "wake":+ return bad("on_timeout must be end or wake")+ case in.Kind == "at" && (hasExpiry || in.OnTimeout != ""):+ return bad("a single-time wakeup ends when it fires; it takes no deadline")+ case in.ExpiresAt != nil && in.ExpiresInSeconds != 0:+ return bad("provide expires_at or expires_in_seconds, not both")+ case !hasExpiry && in.OnTimeout != "":+ return bad("on_timeout requires a deadline")+ case in.OnTimeout == "wake" && in.Kind != "event":+ return bad("only event wakeups can wake the target on timeout")+ case !hasExpiry:+ return pgtype.Timestamptz{}, pgtype.Int8{}, nil+ }+ if in.OnTimeout == "" {+ in.OnTimeout = "end"+ }+ if in.ExpiresInSeconds != 0 {+ if in.ExpiresInSeconds < 60 || in.ExpiresInSeconds > maxWakeupSeconds {+ return bad("expires_in_seconds must be between 60 and 31536000")+ }+ return pgtype.Timestamptz{Time: now.Add(time.Duration(in.ExpiresInSeconds) * time.Second), Valid: true}, pgtype.Int8{Int64: in.ExpiresInSeconds, Valid: true}, nil+ }+ at := in.ExpiresAt.UTC()+ if !at.After(now) || at.Sub(now) > maxWakeupSeconds*time.Second {+ return bad("expires_at must be in the future and within one year")+ }+ return pgtype.Timestamptz{Time: at, Valid: true}, pgtype.Int8{}, nil}type IssueWakeupService struct{ Tasks *TaskService }@@ -84,8 +141,23 @@ func (s *IssueWakeupService) Validate(in *WakeupInput, now time.Time) (pgtype.Ti}}}+ if in.MaxFires != 0 && (in.MaxFires < 1 || in.MaxFires > 1000 || in.Mode != "continuous") {+ return bad("max_fires must be 1–1000 on a repeating rule")+ }+ if hasWakeupCondition(in.Condition) && in.Kind != "event" {+ return bad("conditions use kind event")+ }switch in.Kind {case "event":+ if hasWakeupCondition(in.Condition) {+ if len(in.EventTypes) > 0 || in.FilterAgentID != "" || in.FilterTaskID != "" || in.FilterActorType != "" || in.FilterActorID != "" {+ return bad("a condition cannot be combined with events or filters")+ }+ if in.AfterSeconds != 0 || in.At != nil || in.IntervalSeconds != 0 || in.CronExpression != "" {+ return bad("event wakeups cannot contain a schedule")+ }+ return pgtype.Timestamptz{}, nil+ }if len(in.EventTypes) == 0 || len(in.EventTypes) > len(WakeupEventTypes) {return bad("select at least one supported event")}@@ -240,7 +312,7 @@ func (s *IssueWakeupService) EditInstruction(ctx context.Context, issueID, id, mif w.IssueID != issue.ID || w.WorkspaceID != issue.WorkspaceID {return pgx.ErrNoRows}- if w.CreatedBy != member && membership.Role != "owner" && membership.Role != "admin" {+ if w.SystemRule.Valid || (w.CreatedBy != member && membership.Role != "owner" && membership.Role != "admin") {return ErrWakeupForbidden}agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: w.AgentID, WorkspaceID: issue.WorkspaceID})@@ -307,6 +379,9 @@ func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source,if old.IssueID != issueID || old.WorkspaceID != issue.WorkspaceID {return out, pgx.ErrNoRows}+ if old.SystemRule.Valid {+ return out, ErrWakeupForbidden+ }if enable.Revision < 1 {return out, fmt.Errorf("%w: revision is required", ErrWakeupInput)}@@ -319,7 +394,19 @@ func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source,}return ""}- in = WakeupInput{AgentID: optionalID(old.AgentID), Instruction: old.Instruction, Kind: old.Kind, Mode: old.Mode, EventTypes: old.EventTypes, FilterAgentID: optionalID(old.FilterAgentID), FilterTaskID: optionalID(old.FilterTaskID), FilterActorType: old.FilterActorType.String, FilterActorID: optionalID(old.FilterActorID), ParentCommentID: optionalID(old.ParentCommentID), IntervalSeconds: old.IntervalSeconds.Int64, CronExpression: old.CronExpression.String, Timezone: old.Timezone}+ in = WakeupInput{AgentID: optionalID(old.AgentID), Instruction: old.Instruction, Kind: old.Kind, Mode: old.Mode, EventTypes: old.EventTypes, FilterAgentID: optionalID(old.FilterAgentID), FilterTaskID: optionalID(old.FilterTaskID), FilterActorType: old.FilterActorType.String, FilterActorID: optionalID(old.FilterActorID), ParentCommentID: optionalID(old.ParentCommentID), IntervalSeconds: old.IntervalSeconds.Int64, CronExpression: old.CronExpression.String, Timezone: old.Timezone, OnTimeout: old.OnTimeout.String}+ // A relative wait restarts from now; an absolute deadline is kept and+ // must still be in the future.+ if len(old.Condition) > 0 {+ in.Condition, in.EventTypes = json.RawMessage(old.Condition), nil+ }+ in.MaxFires = old.MaxFires.Int32+ if old.ExpirySeconds.Valid {+ in.ExpiresInSeconds = old.ExpirySeconds.Int64+ } else if old.ExpiresAt.Valid {+ deadline := old.ExpiresAt.Time+ in.ExpiresAt = &deadline+ }if enable.At != nil && old.Kind != "at" {return out, fmt.Errorf("%w: only single-time wakeups accept a new time", ErrWakeupInput)}@@ -352,6 +439,25 @@ func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source,if err != nil {return out, err}+ expiresAt, expirySeconds, err := s.Expiry(&in, now)+ if err != nil {+ return out, err+ }+ onTimeout := pgtype.Text{String: in.OnTimeout, Valid: in.OnTimeout != ""}+ var condition []byte+ if hasWakeupCondition(in.Condition) {+ normalized, hints, e := validateCondition(ctx, tx, issue, in.Condition)+ if e != nil {+ return out, e+ }+ condition, in.EventTypes = normalized, hints+ // The scheduler evaluates the condition on its first tick.+ next = pgtype.Timestamptz{Time: now, Valid: true}+ }+ maxFires := pgtype.Int4{Int32: in.MaxFires, Valid: in.MaxFires > 0}+ if !maxFires.Valid && in.Kind == "event" && in.Mode == "continuous" {+ maxFires = pgtype.Int4{Int32: wakeupDefaultMaxFires, Valid: true}+ }agentID, err := wakeupUUID(in.AgentID)if err != nil || !agentID.Valid {return out, fmt.Errorf("%w: agent_id is required", ErrWakeupInput)@@ -418,6 +524,9 @@ func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source,if old.IssueID != issueID || old.WorkspaceID != issue.WorkspaceID {return out, pgx.ErrNoRows}+ if old.SystemRule.Valid {+ return out, ErrWakeupForbidden+ }membership, e := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: member, WorkspaceID: issue.WorkspaceID})if e != nil {return out, ErrWakeupForbidden@@ -451,9 +560,9 @@ func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source,return out, fmt.Errorf("%w: run and agent filters disagree", ErrWakeupInput)}}- params := db.CreateIssueWakeupParams{ID: dbid.NewV7(), WorkspaceID: issue.WorkspaceID, IssueID: issue.ID, AgentID: agent.ID, CreatedBy: member, SourceTaskID: source, ParentCommentID: parent, Instruction: in.Instruction, Kind: in.Kind, Mode: in.Mode, EventTypes: append([]string{}, in.EventTypes...), FilterAgentID: filterAgent, FilterTaskID: filterTask, FilterActorType: pgtype.Text{String: in.FilterActorType, Valid: in.FilterActorType != ""}, FilterActorID: filterActor, IntervalSeconds: pgtype.Int8{Int64: in.IntervalSeconds, Valid: in.IntervalSeconds > 0}, CronExpression: pgtype.Text{String: in.CronExpression, Valid: in.CronExpression != ""}, Timezone: in.Timezone, NextFireAt: next}+ params := db.CreateIssueWakeupParams{ID: dbid.NewV7(), WorkspaceID: issue.WorkspaceID, IssueID: issue.ID, AgentID: agent.ID, CreatedBy: member, SourceTaskID: source, ParentCommentID: parent, Instruction: in.Instruction, Kind: in.Kind, Mode: in.Mode, EventTypes: append([]string{}, in.EventTypes...), FilterAgentID: filterAgent, FilterTaskID: filterTask, FilterActorType: pgtype.Text{String: in.FilterActorType, Valid: in.FilterActorType != ""}, FilterActorID: filterActor, IntervalSeconds: pgtype.Int8{Int64: in.IntervalSeconds, Valid: in.IntervalSeconds > 0}, CronExpression: pgtype.Text{String: in.CronExpression, Valid: in.CronExpression != ""}, Timezone: in.Timezone, NextFireAt: next, ExpiresAt: expiresAt, ExpirySeconds: expirySeconds, OnTimeout: onTimeout, Condition: condition, MaxFires: maxFires}if existingID.Valid {- _, err = tx.Exec(ctx, `UPDATE issue_wakeup SET agent_id=$2,created_by=$3,source_task_id=$4,parent_comment_id=$5,instruction=$6,kind=$7,mode=$8,event_types=$9,filter_agent_id=$10,filter_task_id=$11,interval_seconds=$12,cron_expression=$13,timezone=$14,next_fire_at=$15,filter_actor_type=$16,filter_actor_id=$17,enabled=true,disabled_at=NULL,revision=revision+1,last_task_id=NULL,last_error=NULL,updated_at=now() WHERE id=$1`, existingID, params.AgentID, member, source, parent, in.Instruction, in.Kind, in.Mode, params.EventTypes, filterAgent, filterTask, params.IntervalSeconds, params.CronExpression, in.Timezone, next, params.FilterActorType, filterActor)+ _, err = tx.Exec(ctx, `UPDATE issue_wakeup SET agent_id=$2,created_by=$3,source_task_id=$4,parent_comment_id=$5,instruction=$6,kind=$7,mode=$8,event_types=$9,filter_agent_id=$10,filter_task_id=$11,interval_seconds=$12,cron_expression=$13,timezone=$14,next_fire_at=$15,filter_actor_type=$16,filter_actor_id=$17,expires_at=$18,expiry_seconds=$19,on_timeout=$20,timed_out_at=NULL,condition=$21,max_fires=$22,condition_state='',fire_count=0,paused_reason=NULL,enabled=true,disabled_at=NULL,revision=revision+1,last_task_id=NULL,last_error=NULL,updated_at=now() WHERE id=$1`, existingID, params.AgentID, member, source, parent, in.Instruction, in.Kind, in.Mode, params.EventTypes, filterAgent, filterTask, params.IntervalSeconds, params.CronExpression, in.Timezone, next, params.FilterActorType, filterActor, expiresAt, expirySeconds, onTimeout, condition, maxFires)if err == nil {out, err = q.LockIssueWakeup(ctx, existingID)}@@ -463,6 +572,26 @@ func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source,if err != nil {return out, err}+ if len(out.Condition) > 0 && conditionFiresOnChange(out.Condition) {+ if err = baselineCondition(ctx, tx, q, out, now); err != nil {+ return out, err+ }+ }+ var activities []wakeupActivity+ if !existingID.Valid {+ actorType, actorID := "member", member+ if source.Valid {+ var agentID pgtype.UUID+ if e := tx.QueryRow(ctx, "SELECT agent_id FROM agent_task_queue WHERE id=$1", source).Scan(&agentID); e == nil && agentID.Valid {+ actorType, actorID = "agent", agentID+ }+ }+ created, e := recordWakeupActivity(ctx, q, out, wakeupActivityCreated, actorType, actorID, nil)+ if e != nil {+ return out, e+ }+ activities = append(activities, created)+ }// Subscribe and inspect the concrete source under the same row lock. This// closes the already-terminal race even if the caller exits immediately.if filterTask.Valid && slices.Contains([]string{"completed", "failed", "cancelled"}, target.Status) && slices.Contains(in.EventTypes, eventcontract.TaskEvent(target.Status)) {@@ -489,6 +618,7 @@ func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source,if err = tx.Commit(ctx); err != nil {return out, err}+ s.publishWakeupActivities(activities...)return out, nil}@@ -530,7 +660,11 @@ func (s *IssueWakeupService) Tick(ctx context.Context) error {}// Outcome writes must not turn a busy rule row into another batch-wide// wait. Use the batch context, not dispatch's expired per-rule context.- if err = s.dispatch(ctx, w); err != nil {+ dispatch := s.dispatch+ if w.SystemRule.Valid {+ dispatch = s.dispatchSystem+ }+ if err = dispatch(ctx, w); err != nil {errs = append(errs, fmt.Errorf("wakeup %s: %w", util.UUIDToString(w.ID), err))outcomeCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)_ = s.Tasks.Queries.NoteWakeupFailure(outcomeCtx, db.NoteWakeupFailureParams{ID: w.ID, LastError: pgtype.Text{String: truncateForSummary(err.Error(), 500), Valid: true}})@@ -639,7 +773,57 @@ func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup)}return tx.Commit(ctx)}- if w.Enabled && w.Kind != "event" && next.Valid && !next.Time.After(now) {+ // Timeline entries are written with the rule's changes and published only+ // once they commit.+ var activities []wakeupActivity+ commit := func() error {+ if err := tx.Commit(ctx); err != nil {+ return err+ }+ s.publishWakeupActivities(activities...)+ return nil+ }+ note := func(action string, details map[string]any) error {+ a, err := recordWakeupActivity(ctx, q, w, action, "system", pgtype.UUID{}, details)+ if err == nil {+ activities = append(activities, a)+ }+ return err+ }+ markTimedOut := func() error {+ if err := q.MarkWakeupTimedOut(ctx, w.ID); err != nil {+ return err+ }+ return note(wakeupActivityTimedOut, map[string]any{"woke": w.Kind == "event" && w.OnTimeout.String == "wake"})+ }+ // Reaching the deadline ends the rule. Inputs captured before it still+ // dispatch; an event rule may also wake the target once to handle the+ // missed deadline.+ timedOut := w.Enabled && w.ExpiresAt.Valid && !w.ExpiresAt.Time.After(now)+ if timedOut {+ enabled = false+ next = pgtype.Timestamptz{}+ if w.Kind == "event" && w.OnTimeout.String == "wake" {+ deadline := w.ExpiresAt.Time.UTC().Format(time.RFC3339)+ payload, _ := json.Marshal(map[string]any{"expires_at": deadline, "event_types": w.EventTypes,+ "note": "The deadline passed before a subscribed event arrived. Read current state, then escalate, extend or stop."})+ if _, err = q.RecordWakeupReceipt(ctx, db.RecordWakeupReceiptParams{ID: dbid.NewV7(), WakeupID: w.ID, Revision: w.Revision, EventKey: "timeout:" + deadline, EventType: wakeupTimeoutEventType, Payload: payload}); err != nil {+ return err+ }+ }+ }+ // A condition rule turns its hint events and scheduled checks into at most+ // one condition.met input; a rule that ended only drops the hints.+ if len(w.Condition) > 0 {+ if w.Enabled && !timedOut {+ if next, err = pollCondition(ctx, tx, q, w, now); err != nil {+ return err+ }+ } else if _, _, err = consumeConditionHints(ctx, tx, w.ID); err != nil {+ return err+ }+ }+ if w.Enabled && !timedOut && w.Kind != "event" && next.Valid && !next.Time.After(now) {planned := next.Timeswitch w.Kind {case "at":@@ -683,7 +867,12 @@ func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup)if err := q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: w.Enabled, NextFireAt: next, LastError: waiting}); err != nil {return err}- return tx.Commit(ctx)+ if timedOut {+ if err := markTimedOut(); err != nil {+ return err+ }+ }+ return commit()}if err != nil && !errors.Is(err, pgx.ErrNoRows) {return err@@ -693,25 +882,171 @@ func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup)if err != nil {return err}+ // Inputs a claimed run took along count once that run starts; until then+ // they wait with it, and they come back if it ends without starting.+ receipts, _, taken, err := takenReceipts(ctx, q, receipts)+ if err != nil {+ return err+ }+ for _, run := range taken {+ if err = q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: receiptIDs(run.receipts), TaskID: run.task.ID}); err != nil {+ return err+ }+ if err = q.CountWakeupFires(ctx, w.ID); err != nil {+ return err+ }+ w.FireCount+++ w.LastTaskID = run.task.ID+ details := wakeupTriggerDetails(run.task, run.receipts)+ details["outcome"] = wakeupOutcomeMerged+ if err = note(wakeupActivityTriggered, details); err != nil {+ return err+ }+ }+ if len(taken) > 0 {+ // A once rule has fired, and one at its cap stops after this firing,+ // as after a run of its own; later inputs are dropped with it.+ switch {+ case w.Mode == "once":+ if err = q.DiscardWakeupReceipts(ctx, w.ID); err != nil {+ return err+ }+ if err = q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: false, LastTaskID: w.LastTaskID}); err != nil {+ return err+ }+ if timedOut {+ if err = markTimedOut(); err != nil {+ return err+ }+ }+ return commit()+ case w.Enabled && w.MaxFires.Valid && w.FireCount >= w.MaxFires.Int32:+ if err = q.DiscardWakeupReceipts(ctx, w.ID); err != nil {+ return err+ }+ if err = q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: w.Enabled, NextFireAt: next, LastTaskID: w.LastTaskID}); err != nil {+ return err+ }+ if err = q.PauseIssueWakeup(ctx, db.PauseIssueWakeupParams{ID: w.ID, PausedReason: pgtype.Text{String: wakeupPausedMaxFires, Valid: true}, BlockRuns: false}); err != nil {+ return err+ }+ if err = note(wakeupActivityPaused, map[string]any{"reason": wakeupPausedMaxFires, "limit": w.MaxFires.Int32}); err != nil {+ return err+ }+ return commit()+ }+ if err = q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: w.Enabled, NextFireAt: next, LastTaskID: w.LastTaskID}); err != nil {+ return err+ }+ }if len(receipts) == 0 {- return tx.Commit(ctx)+ if timedOut {+ if err = markTimedOut(); err != nil {+ return err+ }+ }+ return commit()}ids := make([]pgtype.UUID, 0, len(receipts))+ manual := truefor _, r := range receipts {ids = append(ids, r.ID)+ manual = manual && r.EventType == wakeupManualEventType}if w.Mode == "once" {enabled = false+ next = pgtype.Timestamptz{}}- note, evidence := mergeWakeupEvidence(w, task, receipts)+ // A firing the agent already knows about starts no run. One that a run of+ // the agent waiting to start can take along keeps its inputs for that run+ // (JoinWaitingWakeups).+ if !taskExists {+ self, err := acknowledgedBySelf(ctx, q, w, w.AgentID, issue.ID, receipts)+ if err != nil {+ return err+ }+ if self {+ if err = q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: ids}); err != nil {+ return err+ }+ if err = q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: enabled, NextFireAt: next}); err != nil {+ return err+ }+ if timedOut {+ if err = markTimedOut(); err != nil {+ return err+ }+ }+ details := wakeupTriggerDetails(db.AgentTaskQueue{}, receipts)+ details["outcome"] = wakeupOutcomeAcknowledged+ delete(details, "task_id")+ if err = note(wakeupActivityTriggered, details); err != nil {+ return err+ }+ return commit()+ }+ waiting, err := hasWaitingRun(ctx, q, issue.ID, w.AgentID, w.CreatedBy)+ if err != nil {+ return err+ }+ if waiting {+ // As while its own run is claimed: timers advance, inputs stay,+ // and a once rule stays on until its input is handed over.+ if err = q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: w.Enabled, NextFireAt: next}); err != nil {+ return err+ }+ if timedOut {+ if err = markTimedOut(); err != nil {+ return err+ }+ }+ return commit()+ }+ }+ var chain []string+ if !taskExists {+ var loop bool+ if chain, loop, err = wakeupChain(ctx, q, w, receipts); err != nil {+ return err+ }+ // Runaway protection covers event-driven rules; schedules are bounded+ // by their own interval and deadline. A person's "wake now" is exempt.+ if !manual && w.Kind == "event" {+ reason := ""+ if loop {+ reason = wakeupPausedLoop+ } else {+ recent, e := q.CountRecentWakeupTasks(ctx, db.CountRecentWakeupTasksParams{WakeupID: util.UUIDToString(w.ID), IssueID: w.IssueID, Since: pgtype.Timestamptz{Time: now.Add(-time.Hour), Valid: true}})+ if e != nil {+ return e+ }+ if recent >= wakeupHourlyRunLimit {+ reason = wakeupPausedRate+ }+ }+ if reason != "" {+ if err = q.PauseIssueWakeup(ctx, db.PauseIssueWakeupParams{ID: w.ID, PausedReason: pgtype.Text{String: reason, Valid: true}, BlockRuns: true}); err != nil {+ return err+ }+ if err = q.DiscardWakeupReceipts(ctx, w.ID); err != nil {+ return err+ }+ if err = note(wakeupActivityPaused, map[string]any{"reason": reason, "limit": wakeupHourlyRunLimit}); err != nil {+ return err+ }+ return commit()+ }+ }+ }+ noteText, evidence := mergeWakeupEvidence(w, task, receipts)if taskExists {- task, err = q.ReplaceWakeupEvidence(ctx, db.ReplaceWakeupEvidenceParams{ID: task.ID, HandoffNote: pgtype.Text{String: note, Valid: true}, WakeupEvidence: evidence})+ task, err = q.ReplaceWakeupEvidence(ctx, db.ReplaceWakeupEvidenceParams{ID: task.ID, HandoffNote: pgtype.Text{String: noteText, Valid: true}, WakeupEvidence: evidence})} else {if err = guardIssueNotInTriage(ctx, q, issue.ID, OriginNamed); err != nil {return err}- contextJSON, _ := json.Marshal(map[string]any{"wakeup_id": util.UUIDToString(w.ID), "wakeup_revision": w.Revision, "wakeup_evidence": evidence})- task, err = q.CreateWakeupTask(ctx, db.CreateWakeupTaskParams{ID: dbid.NewV7(), AgentID: w.AgentID, RuntimeID: agent.RuntimeID, IssueID: w.IssueID, Priority: priorityToInt(issue.Priority), TriggerCommentID: w.ParentCommentID, TriggerSummary: pgtype.Text{String: "Wakeup: " + truncateForSummary(w.Instruction, 160), Valid: true}, HandoffNote: pgtype.Text{String: note, Valid: true}, OriginatorUserID: w.CreatedBy, AccountableUserID: w.CreatedBy, OriginatorSource: pgtype.Text{String: "trigger_owner", Valid: true}, TriggerEvidenceKind: pgtype.Text{String: "issue_wakeup", Valid: true}, TriggerEvidenceRefID: w.ID, DelegatedFromTaskID: w.SourceTaskID, WakeupContext: contextJSON, RuntimeMcpOverlay: overlay.Overlay, RuntimeConnectedApps: overlay.ConnectedApps})+ contextJSON, _ := json.Marshal(map[string]any{"wakeup_id": util.UUIDToString(w.ID), "wakeup_revision": w.Revision, "wakeup_evidence": evidence, "wakeup_chain": chain})+ task, err = q.CreateWakeupTask(ctx, db.CreateWakeupTaskParams{ID: dbid.NewV7(), AgentID: w.AgentID, RuntimeID: agent.RuntimeID, IssueID: w.IssueID, Priority: priorityToInt(issue.Priority), TriggerCommentID: w.ParentCommentID, TriggerSummary: pgtype.Text{String: "Wakeup: " + truncateForSummary(w.Instruction, 160), Valid: true}, HandoffNote: pgtype.Text{String: noteText, Valid: true}, OriginatorUserID: w.CreatedBy, AccountableUserID: w.CreatedBy, OriginatorSource: pgtype.Text{String: "trigger_owner", Valid: true}, TriggerEvidenceKind: pgtype.Text{String: "issue_wakeup", Valid: true}, TriggerEvidenceRefID: w.ID, DelegatedFromTaskID: w.SourceTaskID, WakeupContext: contextJSON, RuntimeMcpOverlay: overlay.Overlay, RuntimeConnectedApps: overlay.ConnectedApps})}if err != nil {return err@@ -722,7 +1057,33 @@ func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup)if err = q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: enabled, NextFireAt: next, LastTaskID: task.ID}); err != nil {return err}- if err = tx.Commit(ctx); err != nil {+ if timedOut {+ if err = markTimedOut(); err != nil {+ return err+ }+ }+ if !taskExists {+ if err = q.CountWakeupFires(ctx, w.ID); err != nil {+ return err+ }+ // Schedules speak for themselves in the run list; triggers from events,+ // conditions, a single time or a person get a timeline entry.+ if w.Kind != "every" && w.Kind != "cron" {+ if err = note(wakeupActivityTriggered, wakeupTriggerDetails(task, receipts)); err != nil {+ return err+ }+ }+ // The run that reaches the cap is legitimate; the rule stops after it.+ if enabled && w.MaxFires.Valid && w.FireCount+1 >= w.MaxFires.Int32 {+ if err = q.PauseIssueWakeup(ctx, db.PauseIssueWakeupParams{ID: w.ID, PausedReason: pgtype.Text{String: wakeupPausedMaxFires, Valid: true}, BlockRuns: false}); err != nil {+ return err+ }+ if err = note(wakeupActivityPaused, map[string]any{"reason": wakeupPausedMaxFires, "limit": w.MaxFires.Int32}); err != nil {+ return err+ }+ }+ }+ if err = commit(); err != nil {return err}s.Tasks.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)@@ -769,7 +1130,7 @@ func (s *IssueWakeupService) Disable(ctx context.Context, issueID, id, member pgif out.IssueID != issue.ID || out.WorkspaceID != issue.WorkspaceID {return db.IssueWakeup{}, pgx.ErrNoRows}- if out.CreatedBy != member && membership.Role != "owner" && membership.Role != "admin" {+ if out.SystemRule.Valid || (out.CreatedBy != member && membership.Role != "owner" && membership.Role != "admin") {return db.IssueWakeup{}, ErrWakeupForbidden}_, err = tx.Exec(ctx, "UPDATE issue_wakeup SET enabled=false,disabled_at=COALESCE(disabled_at,now()),updated_at=now() WHERE id=$1", id)@@ -817,6 +1178,18 @@ func (s *IssueWakeupService) CheckClaim(ctx context.Context, task db.AgentTaskQuif err != nil {return err}+ if w.SystemRule.Valid {+ // A system rule's run targets the assignee resolved when it fired; it+ // is claimable while the rule is on and that agent can still run.+ if !w.Enabled || w.DisabledAt.Valid || w.Revision != source.Revision || w.IssueID != task.IssueID {+ return ErrWakeupForbidden+ }+ agent, err := s.Tasks.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: task.AgentID, WorkspaceID: w.WorkspaceID})+ if errors.Is(err, pgx.ErrNoRows) || (err == nil && (agent.ArchivedAt.Valid || !agent.RuntimeID.Valid)) {+ return ErrWakeupForbidden+ }+ return err+ }if w.DisabledAt.Valid || w.Revision != source.Revision || w.IssueID != task.IssueID || w.AgentID != task.AgentID || w.CreatedBy != task.OriginatorUserID {return ErrWakeupForbidden}diff --git a/server/internal/service/issue_wakeup_activity.go b/server/internal/service/issue_wakeup_activity.gonew file mode 100644index 0000000000..503eb05d87--- /dev/null+++ b/server/internal/service/issue_wakeup_activity.go@@ -0,0 +1,224 @@+package service++import (+ "context"+ "encoding/json"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// Runaway protection. A rule that starts this many runs within an hour, or+// whose trigger chain leads back to itself, is paused with a visible reason.+const (+ wakeupHourlyRunLimit = 12+ wakeupDefaultMaxFires = 20+ wakeupChainLimit = 32+ wakeupLoopRepeats = 2+ wakeupActivityCreated = "wakeup_created"+ wakeupActivityTriggered = "wakeup_triggered"+ wakeupActivityTimedOut = "wakeup_timed_out"+ wakeupActivityCheckin = "wakeup_checkin"+ wakeupActivityPaused = "wakeup_paused"+ wakeupPausedLoop = "loop"+ wakeupPausedRate = "rate"+ wakeupPausedMaxFires = "max_fires"+ wakeupTimeoutEventType = "wakeup.timeout"+ wakeupManualEventType = "wakeup.manual"+ wakeupConditionEventType = "condition.met"+)++// wakeupPreview is the rule snapshot stored with timeline entries, so the+// entry still reads correctly after the rule changes or is deleted.+func wakeupPreview(w db.IssueWakeup) map[string]any {+ preview := map[string]any{+ "id": util.UUIDToString(w.ID), "kind": w.Kind, "mode": w.Mode, "event_types": w.EventTypes,+ "agent_id": util.UUIDToString(w.AgentID), "timezone": w.Timezone,+ }+ if len(w.Condition) > 0 {+ preview["condition"] = json.RawMessage(w.Condition)+ }+ if w.FilterActorType.Valid {+ preview["filter_actor_type"] = w.FilterActorType.String+ preview["filter_actor_id"] = util.UUIDToString(w.FilterActorID)+ }+ if w.FilterAgentID.Valid {+ preview["filter_agent_id"] = util.UUIDToString(w.FilterAgentID)+ }+ if w.IntervalSeconds.Valid {+ preview["interval_seconds"] = w.IntervalSeconds.Int64+ }+ if w.CronExpression.Valid {+ preview["cron_expression"] = w.CronExpression.String+ }+ if w.NextFireAt.Valid && len(w.Condition) == 0 {+ preview["next_fire_at"] = w.NextFireAt.Time.UTC().Format(time.RFC3339)+ }+ if w.ExpiresAt.Valid {+ preview["expires_at"] = w.ExpiresAt.Time.UTC().Format(time.RFC3339)+ }+ return preview+}++// wakeupActivity is written inside the rule's transaction and published after+// commit, so the timeline never shows an entry whose change rolled back.+type wakeupActivity struct {+ row db.ActivityLog+ actorType string+ actorID string+ details json.RawMessage+}++func recordWakeupActivity(ctx context.Context, q *db.Queries, w db.IssueWakeup, action, actorType string, actorID pgtype.UUID, details map[string]any) (wakeupActivity, error) {+ if details == nil {+ details = map[string]any{}+ }+ preview := wakeupPreview(w)+ // Who the rule belongs to, for the entry's source: the agent whose run+ // created it, else the member.+ preview["created_by"] = util.UUIDToString(w.CreatedBy)+ if w.SourceTaskID.Valid {+ if source, err := q.GetAgentTask(ctx, w.SourceTaskID); err == nil {+ preview["created_by_agent_id"] = util.UUIDToString(source.AgentID)+ }+ }+ details["wakeup"] = preview+ raw, _ := json.Marshal(details)+ row, err := q.CreateActivity(ctx, db.CreateActivityParams{+ ID: dbid.NewV7(), WorkspaceID: w.WorkspaceID, IssueID: w.IssueID,+ ActorType: pgtype.Text{String: actorType, Valid: true}, ActorID: actorID,+ Action: action, Details: raw,+ })+ if err != nil {+ return wakeupActivity{}, err+ }+ id := ""+ if actorID.Valid {+ id = util.UUIDToString(actorID)+ }+ return wakeupActivity{row: row, actorType: actorType, actorID: id, details: raw}, nil+}++func (s *IssueWakeupService) publishWakeupActivities(activities ...wakeupActivity) {+ if s.Tasks == nil || s.Tasks.Bus == nil {+ return+ }+ for _, a := range activities {+ if !a.row.ID.Valid {+ continue+ }+ s.Tasks.Bus.Publish(events.Event{+ Type: protocol.EventActivityCreated, WorkspaceID: util.UUIDToString(a.row.WorkspaceID),+ ActorType: a.actorType, ActorID: a.actorID,+ Payload: map[string]any{+ "issue_id": util.UUIDToString(a.row.IssueID),+ "entry": map[string]any{+ "type": "activity", "id": util.UUIDToString(a.row.ID),+ "actor_type": a.actorType, "actor_id": a.actorID, "action": a.row.Action,+ "details": a.details, "created_at": a.row.CreatedAt.Time.UTC().Format(time.RFC3339Nano),+ },+ },+ })+ }+}++// wakeupChain returns the causal chain for a new run of w: the rules that+// started the runs whose events triggered it, oldest first, ending with w.+// Of several source runs the one that passed through w most often wins. A+// chain that already passes through w wakeupLoopRepeats times means rules are+// waking each other without a person in between; a member's own action+// carries no source run and so starts a fresh chain. Allowing a repeat keeps a+// short review loop between two agents working.+func wakeupChain(ctx context.Context, q *db.Queries, w db.IssueWakeup, receipts []db.IssueWakeupReceipt) ([]string, bool, error) {+ var ids []pgtype.UUID+ seen := map[string]bool{}+ for _, r := range receipts {+ var refs struct {+ SourceTaskID string `json:"source_task_id"`+ TaskID string `json:"task_id"`+ }+ _ = json.Unmarshal(r.Payload, &refs)+ for _, ref := range []string{refs.SourceTaskID, refs.TaskID} {+ if ref == "" || seen[ref] {+ continue+ }+ seen[ref] = true+ if id, err := util.ParseUUID(ref); err == nil {+ ids = append(ids, id)+ }+ }+ }+ self := util.UUIDToString(w.ID)+ count := func(chain []string) int {+ n := 0+ for _, id := range chain {+ if id == self {+ n+++ }+ }+ return n+ }+ var upstream []string+ if len(ids) > 0 {+ rows, err := q.ListWakeupChains(ctx, ids)+ if err != nil {+ return nil, false, err+ }+ for _, row := range rows {+ var chain []string+ _ = json.Unmarshal(row.Chain, &chain)+ if row.WakeupID != "" && (len(chain) == 0 || chain[len(chain)-1] != row.WakeupID) {+ chain = append(chain, row.WakeupID)+ }+ if upstream == nil || count(chain) > count(upstream) || (count(chain) == count(upstream) && len(chain) > len(upstream)) {+ upstream = chain+ }+ }+ }+ if count(upstream) >= wakeupLoopRepeats {+ return upstream, true, nil+ }+ chain := append(append([]string{}, upstream...), self)+ if len(chain) > wakeupChainLimit {+ chain = chain[len(chain)-wakeupChainLimit:]+ }+ return chain, false, nil+}++// wakeupTriggerDetails summarizes what woke the rule for its timeline entry:+// the event types, how many facts were merged, the condition observation and,+// for "wake now", who asked. References only, like the receipts themselves.+func wakeupTriggerDetails(task db.AgentTaskQueue, receipts []db.IssueWakeupReceipt) map[string]any {+ details := map[string]any{"task_id": util.UUIDToString(task.ID)}+ events := []string{}+ seen := map[string]bool{}+ count := int64(0)+ for _, r := range receipts {+ if !seen[r.EventType] {+ seen[r.EventType] = true+ events = append(events, r.EventType)+ }+ var payload struct {+ Count int64 `json:"coalesced_count"`+ Observed json.RawMessage `json:"observed"`+ ActorType string `json:"actor_type"`+ ActorID string `json:"actor_id"`+ }+ _ = json.Unmarshal(r.Payload, &payload)+ count += max(payload.Count, 1)+ if len(payload.Observed) > 0 {+ details["observed"] = payload.Observed+ }+ if payload.ActorType == "member" || payload.ActorType == "agent" {+ details["actor_type"], details["actor_id"] = payload.ActorType, payload.ActorID+ }+ }+ details["events"] = events+ details["count"] = count+ return details+}diff --git a/server/internal/service/issue_wakeup_condition.go b/server/internal/service/issue_wakeup_condition.gonew file mode 100644index 0000000000..23a2b26bd7--- /dev/null+++ b/server/internal/service/issue_wakeup_condition.go@@ -0,0 +1,554 @@+package service++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "slices"+ "sort"+ "strings"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+)++// conditionPollInterval bounds how long a platform-evaluated condition can+// stay satisfied before its rule notices. Same-issue field conditions also+// subscribe to the matching event, so they usually react on the next tick.+const conditionPollInterval = 30 * time.Second++// WakeupCondition is a structured predicate the platform evaluates itself, so+// a rule only wakes its agent when the predicate becomes true. It compares+// stored facts (a field value, sub-issue status, a linked pull request's+// state); it does not interpret business meaning.+type WakeupCondition struct {+ // issue_field | children_done | pull_request | other_issue+ Type string `json:"type"`+ // issue_field: status | assignee | label | property+ Field string `json:"field,omitempty"`+ Value json.RawMessage `json:"value,omitempty"`+ AssigneeType string `json:"assignee_type,omitempty"`+ AssigneeID string `json:"assignee_id,omitempty"`+ LabelID string `json:"label_id,omitempty"`+ PropertyID string `json:"property_id,omitempty"`+ // children_done: a stage number, or every sub-issue when omitted.+ Stage *int32 `json:"stage,omitempty"`+ // EachStage is the child_done system rule's reading of children_done:+ // every stage closing while a later one waits, then every sub-issue+ // closing. Only the platform sets it.+ EachStage bool `json:"each_stage,omitempty"`+ // pull_request: checks_finished | merged+ Event string `json:"event,omitempty"`+ // other_issue: the watched issue and done | ended | in_review. The+ // identifier is recorded for display; clients never set it.+ IssueID string `json:"issue_id,omitempty"`+ State string `json:"state,omitempty"`+ Identifier string `json:"identifier,omitempty"`+}++var errBadCondition = errors.New("invalid condition")++func badCondition(msg string) error {+ return fmt.Errorf("%w: %w: %s", ErrWakeupInput, errBadCondition, msg)+}++// validateCondition normalizes a condition against the issue's workspace and+// returns the same-issue events that should trigger an early evaluation.+func validateCondition(ctx context.Context, tx pgx.Tx, issue db.Issue, raw json.RawMessage) (json.RawMessage, []string, error) {+ var c WakeupCondition+ dec := json.NewDecoder(bytes.NewReader(raw))+ dec.DisallowUnknownFields()+ if err := dec.Decode(&c); err != nil {+ return nil, nil, badCondition("unreadable condition")+ }+ ws := issue.WorkspaceID+ exists := func(sql string, args ...any) (bool, error) {+ var ok bool+ err := tx.QueryRow(ctx, "SELECT EXISTS("+sql+")", args...).Scan(&ok)+ return ok, err+ }+ uuidArg := func(s, what string) (pgtype.UUID, error) {+ id, err := util.ParseUUID(s)+ if err != nil {+ return id, badCondition(what + " must be a UUID")+ }+ return id, nil+ }+ var events []string+ var out WakeupCondition+ switch c.Type {+ case "issue_field":+ out = WakeupCondition{Type: c.Type, Field: c.Field}+ switch c.Field {+ case "status":+ var status string+ if json.Unmarshal(c.Value, &status) != nil || status == "" {+ return nil, nil, badCondition("status value must be a status key")+ }+ if !issuestatus.IsBuiltIn(status) {+ ok, err := exists("SELECT 1 FROM issue_status WHERE workspace_id=$1 AND key=$2", ws, status)+ if err != nil {+ return nil, nil, err+ }+ if !ok {+ return nil, nil, badCondition("unknown status")+ }+ }+ out.Value, _ = json.Marshal(status)+ events = []string{"issue.status_changed"}+ case "assignee":+ id, err := uuidArg(c.AssigneeID, "assignee_id")+ if err != nil {+ return nil, nil, err+ }+ var ok bool+ switch c.AssigneeType {+ case "member":+ ok, err = exists("SELECT 1 FROM member WHERE workspace_id=$1 AND user_id=$2", ws, id)+ case "agent":+ ok, err = exists("SELECT 1 FROM agent WHERE workspace_id=$1 AND id=$2", ws, id)+ case "squad":+ ok, err = exists("SELECT 1 FROM squad WHERE workspace_id=$1 AND id=$2", ws, id)+ default:+ return nil, nil, badCondition("assignee_type must be member, agent or squad")+ }+ if err != nil {+ return nil, nil, err+ }+ if !ok {+ return nil, nil, badCondition("unknown assignee")+ }+ out.AssigneeType, out.AssigneeID = c.AssigneeType, util.UUIDToString(id)+ events = []string{"issue.assignee_changed"}+ case "label":+ id, err := uuidArg(c.LabelID, "label_id")+ if err != nil {+ return nil, nil, err+ }+ ok, err := exists("SELECT 1 FROM issue_label WHERE workspace_id=$1 AND id=$2", ws, id)+ if err != nil {+ return nil, nil, err+ }+ if !ok {+ return nil, nil, badCondition("unknown label")+ }+ out.LabelID = util.UUIDToString(id)+ events = []string{"issue.labels_changed"}+ case "property":+ id, err := uuidArg(c.PropertyID, "property_id")+ if err != nil {+ return nil, nil, err+ }+ ok, err := exists("SELECT 1 FROM issue_property WHERE workspace_id=$1 AND id=$2 AND archived_at IS NULL", ws, id)+ if err != nil {+ return nil, nil, err+ }+ if !ok {+ return nil, nil, badCondition("unknown property")+ }+ value := canonicalWakeupPayload(c.Value)+ if len(c.Value) == 0 || string(value) == "null" || len(value) > 1024 {+ return nil, nil, badCondition("property value must be a JSON value within 1 KB")+ }+ out.PropertyID, out.Value = util.UUIDToString(id), value+ events = []string{"issue.properties_changed"}+ default:+ return nil, nil, badCondition("field must be status, assignee, label or property")+ }+ case "children_done":+ if c.EachStage {+ return nil, nil, badCondition("each_stage is reserved for the platform's sub-issue rule")+ }+ if c.Stage != nil && (*c.Stage < 1 || *c.Stage > 1000) {+ return nil, nil, badCondition("stage must be a positive number")+ }+ out = WakeupCondition{Type: c.Type, Stage: c.Stage}+ case "pull_request":+ if c.Event != "checks_finished" && c.Event != "merged" {+ return nil, nil, badCondition("event must be checks_finished or merged")+ }+ out = WakeupCondition{Type: c.Type, Event: c.Event}+ case "other_issue":+ id, err := uuidArg(c.IssueID, "issue_id")+ if err != nil {+ return nil, nil, err+ }+ if id == issue.ID {+ return nil, nil, badCondition("watch another issue, not this one")+ }+ if c.State != "done" && c.State != "ended" && c.State != "in_review" {+ return nil, nil, badCondition("state must be done, ended or in_review")+ }+ var identifier string+ err = tx.QueryRow(ctx, "SELECT ws.issue_prefix||'-'||i.number FROM issue i JOIN workspace ws ON ws.id=i.workspace_id WHERE i.workspace_id=$1 AND i.id=$2", ws, id).Scan(&identifier)+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, nil, badCondition("unknown issue")+ }+ if err != nil {+ return nil, nil, err+ }+ out = WakeupCondition{Type: c.Type, IssueID: util.UUIDToString(id), State: c.State, Identifier: identifier}+ default:+ return nil, nil, badCondition("type must be issue_field, children_done, pull_request or other_issue")+ }+ normalized, _ := json.Marshal(out)+ return normalized, events, nil+}++// evaluateCondition reports whether the predicate holds, a fingerprint of the+// satisfying facts (so a rule fires when they change, not on every tick) and a+// small observation for the woken agent's trigger facts.+func evaluateCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWakeup) (bool, string, map[string]any, error) {+ var c WakeupCondition+ if err := json.Unmarshal(w.Condition, &c); err != nil {+ return false, "", nil, err+ }+ switch c.Type {+ case "issue_field":+ var status, assigneeType string+ var assigneeID pgtype.UUID+ var property json.RawMessage+ var labeled bool+ err := tx.QueryRow(ctx, `SELECT status,COALESCE(assignee_type,''),assignee_id,COALESCE(properties->($2::text),'null'::jsonb),+ EXISTS(SELECT 1 FROM issue_to_label l WHERE l.issue_id=issue.id AND l.label_id::text=$3::text)+ FROM issue WHERE id=$1`, w.IssueID, c.PropertyID, c.LabelID).Scan(&status, &assigneeType, &assigneeID, &property, &labeled)+ if err != nil {+ return false, "", nil, err+ }+ switch c.Field {+ case "status":+ var want string+ _ = json.Unmarshal(c.Value, &want)+ return status == want, "status:" + status, map[string]any{"status": status}, nil+ case "assignee":+ met := assigneeType == c.AssigneeType && util.UUIDToString(assigneeID) == c.AssigneeID+ return met, "assignee:" + assigneeType + ":" + util.UUIDToString(assigneeID), map[string]any{"assignee_type": assigneeType, "assignee_id": util.UUIDToString(assigneeID)}, nil+ case "label":+ return labeled, "label", map[string]any{"label_id": c.LabelID, "attached": labeled}, nil+ case "property":+ value := canonicalWakeupPayload(property)+ return bytes.Equal(value, canonicalWakeupPayload(c.Value)), "property:" + string(value), map[string]any{"property_id": c.PropertyID, "value": json.RawMessage(value)}, nil+ }+ case "children_done":+ children, err := loadSubIssues(ctx, tx, q, w.IssueID, w.WorkspaceID)+ if err != nil {+ return false, "", nil, err+ }+ met, fingerprint, observed := childrenDone(c, children)+ return met, fingerprint, observed, nil+ case "pull_request":+ rows, err := tx.Query(ctx, `SELECT pr.pr_number,pr.state,COALESCE(pr.snapshot_head_sha,''),COALESCE(pr.checks_rollup_state,'')+ FROM github_pull_request pr JOIN issue_pull_request ipr ON ipr.pull_request_id=pr.id WHERE ipr.issue_id=$1`, w.IssueID)+ if err != nil {+ return false, "", nil, err+ }+ var keys []string+ var prs []map[string]any+ for rows.Next() {+ var number int32+ var state, head, checks string+ if err = rows.Scan(&number, &state, &head, &checks); err != nil {+ rows.Close()+ return false, "", nil, err+ }+ switch c.Event {+ case "merged":+ if state == "merged" {+ keys = append(keys, fmt.Sprintf("%d", number))+ prs = append(prs, map[string]any{"number": number, "state": state})+ }+ case "checks_finished":+ if head != "" && slices.Contains([]string{"SUCCESS", "FAILURE", "ERROR"}, checks) {+ keys = append(keys, fmt.Sprintf("%d@%s:%s", number, head, checks))+ prs = append(prs, map[string]any{"number": number, "head_sha": head, "checks": strings.ToLower(checks)})+ }+ }+ }+ rows.Close()+ if err = rows.Err(); err != nil {+ return false, "", nil, err+ }+ sort.Strings(keys)+ return len(keys) > 0, "pr:" + strings.Join(keys, ","), map[string]any{"pull_requests": prs}, nil+ case "other_issue":+ var status string+ var number int32+ err := tx.QueryRow(ctx, "SELECT status,number FROM issue WHERE id=$1 AND workspace_id=$2", c.IssueID, w.WorkspaceID).Scan(&status, &number)+ if errors.Is(err, pgx.ErrNoRows) {+ return false, "", map[string]any{"deleted": true}, nil+ }+ if err != nil {+ return false, "", nil, err+ }+ category, err := issuestatus.CategoryWithError(ctx, q, w.WorkspaceID, status)+ if err != nil {+ return false, "", nil, err+ }+ var met bool+ switch c.State {+ case "done":+ met = category == "done"+ case "ended":+ met = category == "done" || category == "closed"+ case "in_review":+ met = status == "in_review"+ }+ return met, "issue:" + status, map[string]any{"issue_id": c.IssueID, "status": status}, nil+ }+ return false, "", nil, fmt.Errorf("unknown condition type %q", c.Type)+}++// conditionHintSQL selects the event receipts a condition rule subscribes to.+// They only prompt an early evaluation and never become run inputs.+const conditionHintSQL = "wakeup_id=$1 AND processed_at IS NULL AND event_type NOT IN ('condition.met','wakeup.timeout','wakeup.manual')"++// consumeConditionHints marks the pending hints processed. It also returns the+// agent runs that caused them, or nil when any hint came from elsewhere (a+// person, the platform, or several merged events), so a satisfied condition+// can tell whether the target agent brought it about itself.+func consumeConditionHints(ctx context.Context, tx pgx.Tx, id pgtype.UUID) (bool, []string, error) {+ rows, err := tx.Query(ctx, "UPDATE issue_wakeup_receipt SET processed_at=now() WHERE "+conditionHintSQL+" RETURNING payload", id)+ if err != nil {+ return false, nil, err+ }+ defer rows.Close()+ hinted, complete := false, true+ var causes []string+ for rows.Next() {+ var raw []byte+ if err = rows.Scan(&raw); err != nil {+ return false, nil, err+ }+ hinted = true+ var p struct {+ SourceTaskID string `json:"source_task_id"`+ SourceTaskIDs []string `json:"source_task_ids"`+ Count int64 `json:"coalesced_count"`+ }+ _ = json.Unmarshal(raw, &p)+ switch {+ case p.Count <= 1 && p.SourceTaskID != "":+ causes = append(causes, p.SourceTaskID)+ case len(p.SourceTaskIDs) > 0:+ causes = append(causes, p.SourceTaskIDs...)+ default:+ complete = false+ }+ }+ if err = rows.Err(); err != nil {+ return false, nil, err+ }+ if !complete {+ causes = nil+ }+ return hinted, causes, nil+}++// pollCondition evaluates a condition rule when it is due or a related event+// arrived, and returns the next scheduled evaluation. A newly satisfied+// predicate becomes one condition.met input for the ordinary dispatch below.+func pollCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWakeup, now time.Time) (pgtype.Timestamptz, error) {+ hinted, causes, err := consumeConditionHints(ctx, tx, w.ID)+ if err != nil {+ return w.NextFireAt, err+ }+ if !hinted && w.NextFireAt.Valid && w.NextFireAt.Time.After(now) {+ return w.NextFireAt, nil+ }+ met, fingerprint, observed, err := evaluateCondition(ctx, tx, q, w)+ if err != nil {+ return w.NextFireAt, err+ }+ // condition_state dedups a satisfied predicate; each new satisfaction+ // gets its own receipt key.+ state := w.ConditionState+ if met && fingerprint != state {+ if err = recordConditionMet(ctx, q, w, observed, causes, now); err != nil {+ return w.NextFireAt, err+ }+ state = fingerprint+ } else if !met {+ state = ""+ }+ next := pgtype.Timestamptz{Time: now.Add(conditionPollInterval), Valid: true}+ return next, q.SetWakeupConditionState(ctx, db.SetWakeupConditionStateParams{ID: w.ID, ConditionState: state, NextFireAt: next})+}++// conditionFiresOnChange reports whether facts already true at registration+// are ignored. Finished checks usually belong to the head the agent just+// replaced, so a checks condition waits for a newer result; states such as a+// status value, finished sub-issues or a merged PR fire as soon as they hold.+func conditionFiresOnChange(raw []byte) bool {+ var c WakeupCondition+ _ = json.Unmarshal(raw, &c)+ return c.Type == "pull_request" && c.Event == "checks_finished"+}++// baselineCondition records which facts already satisfy a new or re-enabled+// rule, so it wakes the agent when they change rather than immediately.+func baselineCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWakeup, now time.Time) error {+ met, fingerprint, _, err := evaluateCondition(ctx, tx, q, w)+ if err != nil {+ return err+ }+ if !met {+ fingerprint = ""+ }+ return q.SetWakeupConditionState(ctx, db.SetWakeupConditionStateParams{ID: w.ID, ConditionState: fingerprint, NextFireAt: pgtype.Timestamptz{Time: now.Add(conditionPollInterval), Valid: true}})+}++// subIssue is one sub-issue as the children_done condition reads it. Closed+// covers the done and closed status categories; Cancelled is closed without+// finishing.+type subIssue struct {+ ID pgtype.UUID+ Stage pgtype.Int4+ Closed bool+ Cancelled bool+}++func loadSubIssues(ctx context.Context, tx pgx.Tx, q *db.Queries, parent, workspace pgtype.UUID) ([]subIssue, error) {+ rows, err := tx.Query(ctx, "SELECT id,status,stage FROM issue WHERE parent_issue_id=$1 AND workspace_id=$2 ORDER BY id", parent, workspace)+ if err != nil {+ return nil, err+ }+ var children []subIssue+ var statuses []string+ for rows.Next() {+ var ch subIssue+ var status string+ if err = rows.Scan(&ch.ID, &status, &ch.Stage); err != nil {+ rows.Close()+ return nil, err+ }+ children = append(children, ch)+ statuses = append(statuses, status)+ }+ rows.Close()+ if err = rows.Err(); err != nil {+ return nil, err+ }+ categories := map[string]string{}+ for i, status := range statuses {+ category, ok := categories[status]+ if !ok {+ if category, err = issuestatus.CategoryWithError(ctx, q, workspace, status); err != nil {+ return nil, err+ }+ categories[status] = category+ }+ children[i].Closed = category == "done" || category == "closed"+ children[i].Cancelled = category == "closed"+ }+ return children, nil+}++// childrenDone evaluates a children_done condition. A stage condition waits+// for every staged sub-issue up to that stage; without a stage it waits for+// every sub-issue, staged or not.+func childrenDone(c WakeupCondition, children []subIssue) (bool, string, map[string]any) {+ if c.EachStage {+ return stageProgress(children)+ }+ total, done, inStage := 0, 0, 0+ for _, ch := range children {+ if c.Stage != nil && (!ch.Stage.Valid || ch.Stage.Int32 > *c.Stage) {+ continue+ }+ if c.Stage != nil && ch.Stage.Int32 == *c.Stage {+ inStage+++ }+ total+++ if ch.Closed {+ done+++ }+ }+ met := total > 0 && done == total && (c.Stage == nil || inStage > 0)+ return met, fmt.Sprintf("children:%d", total), map[string]any{"finished": done, "total": total}+}++type stageCount struct {+ Stage int32 `json:"stage,omitempty"`+ Total int `json:"total"`+ Closed int `json:"closed"`+ Cancelled int `json:"cancelled"`+}++// stageProgress is the system rule's reading. It holds when a stage and every+// earlier one are closed while a later stage still waits (fingerprint+// stage:N), and when every sub-issue, staged or not, is closed (all). The last+// stage closing on its own does not hold: the wrap-up also waits for unstaged+// sub-issues. The observation lists every stage for the woken agent.+func stageProgress(children []subIssue) (bool, string, map[string]any) {+ counts := map[int32]*stageCount{}+ var stages []int32+ unstaged := stageCount{}+ closed, cancelled := 0, 0+ for _, ch := range children {+ sc := &unstaged+ if ch.Stage.Valid {+ if counts[ch.Stage.Int32] == nil {+ counts[ch.Stage.Int32] = &stageCount{Stage: ch.Stage.Int32}+ stages = append(stages, ch.Stage.Int32)+ }+ sc = counts[ch.Stage.Int32]+ }+ sc.Total+++ if ch.Closed {+ sc.Closed+++ closed+++ }+ if ch.Cancelled {+ sc.Cancelled+++ cancelled+++ }+ }+ slices.Sort(stages)+ list := make([]stageCount, 0, len(stages))+ var closedStage, nextStage int32+ frontier, waiting := false, false+ for _, stage := range stages {+ sc := *counts[stage]+ list = append(list, sc)+ if waiting {+ continue+ }+ if sc.Closed < sc.Total {+ nextStage, waiting = stage, true+ continue+ }+ closedStage, frontier = stage, true+ }+ observed := map[string]any{"total": len(children), "closed": closed, "cancelled": cancelled, "stages": list}+ if unstaged.Total > 0 {+ observed["unstaged"] = unstaged+ }+ switch {+ case len(children) > 0 && closed == len(children):+ observed["all"] = true+ return true, "all", observed+ case frontier && waiting:+ observed["stage"], observed["next_stage"] = closedStage, nextStage+ return true, fmt.Sprintf("stage:%d", closedStage), observed+ }+ return false, "", observed+}++// recordConditionMet turns a newly satisfied condition into one run input. It+// names the agent runs whose changes satisfied it, when all of them are known.+func recordConditionMet(ctx context.Context, q *db.Queries, w db.IssueWakeup, observed map[string]any, causes []string, now time.Time) error {+ facts := map[string]any{"condition": json.RawMessage(w.Condition), "observed": observed, "observed_at": now.UTC().Format(time.RFC3339)}+ if len(causes) > 0 {+ facts["source_task_ids"] = causes+ }+ payload, _ := json.Marshal(facts)+ _, err := q.RecordWakeupReceipt(ctx, db.RecordWakeupReceiptParams{ID: dbid.NewV7(), WakeupID: w.ID, Revision: w.Revision, EventKey: "condition:" + now.UTC().Format(time.RFC3339Nano), EventType: wakeupConditionEventType, Payload: payload})+ return err+}diff --git a/server/internal/service/issue_wakeup_condition_test.go b/server/internal/service/issue_wakeup_condition_test.gonew file mode 100644index 0000000000..64f1890c10--- /dev/null+++ b/server/internal/service/issue_wakeup_condition_test.go@@ -0,0 +1,217 @@+package service++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// conditionFixture is wakeFixture plus cleanup for the timeline entries rules+// write.+func conditionFixture(t *testing.T) (principalFixture, *IssueWakeupService, pgtype.UUID, string) {+ t.Helper()+ f, s, issue, agent := wakeFixture(t)+ f.Cleanup(t, "DELETE FROM activity_log WHERE issue_id=$1", issue)+ return f, s, issue, agent+}++// wakeTick makes the rule due and dispatches it, as the scheduler would.+func wakeTick(t *testing.T, f principalFixture, s *IssueWakeupService, id pgtype.UUID) db.IssueWakeup {+ t.Helper()+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '1 second' WHERE id=$1 AND next_fire_at IS NOT NULL", id)+ w, err := f.q.LocklessWakeup(context.Background(), id)+ if err != nil {+ t.Fatal(err)+ }+ wakeDispatch(t, s, w)+ w, err = f.q.LocklessWakeup(context.Background(), id)+ if err != nil {+ t.Fatal(err)+ }+ return w+}++func wakeRuns(t *testing.T, f principalFixture, id pgtype.UUID) int {+ t.Helper()+ return f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(id))+}++func condition(t *testing.T, v map[string]any) json.RawMessage {+ t.Helper()+ raw, err := json.Marshal(v)+ if err != nil {+ t.Fatal(err)+ }+ return raw+}++func TestWakeupConditionFieldValueWakesOnceWhenItHolds(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Instruction: "Review when ready",+ Condition: condition(t, map[string]any{"type": "issue_field", "field": "status", "value": "in_review"})})+ if len(w.EventTypes) != 1 || w.EventTypes[0] != "issue.status_changed" || w.Mode != "once" {+ t.Fatalf("condition rule = %+v", w)+ }+ // Not yet true: no run, no matter how often it is evaluated.+ wakeTick(t, f, s, w.ID)+ wakeSetStatus(t, f, issue, "in_progress")+ wakeTick(t, f, s, w.ID)+ if n := wakeRuns(t, f, w.ID); n != 0 {+ t.Fatalf("unmet condition started %d runs", n)+ }+ // The matching status change is a hint; the platform evaluates it.+ wakeSetStatus(t, f, issue, "in_review")+ got := wakeTick(t, f, s, w.ID)+ if n := wakeRuns(t, f, w.ID); n != 1 {+ t.Fatalf("met condition started %d runs, want 1", n)+ }+ if got.Enabled {+ t.Fatal("a once condition must be consumed")+ }+ task, err := f.q.GetAgentTask(context.Background(), got.LastTaskID)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(task.HandoffNote.String, "condition.met") || !strings.Contains(task.HandoffNote.String, `"status":"in_review"`) {+ t.Fatalf("trigger facts missing the observation: %s", task.HandoffNote.String)+ }+ // Status-change hints never reach the agent as separate facts.+ if strings.Contains(task.HandoffNote.String, "issue.status_changed") {+ t.Fatalf("hint leaked into the run: %s", task.HandoffNote.String)+ }+ if n := f.Count(t, "SELECT count(*) FROM activity_log WHERE issue_id=$1 AND action='wakeup_triggered'", issue); n != 1 {+ t.Fatalf("trigger timeline entries = %d, want 1", n)+ }+ if n := f.Count(t, "SELECT count(*) FROM activity_log WHERE issue_id=$1 AND action='wakeup_created'", issue); n != 1 {+ t.Fatalf("created timeline entries = %d, want 1", n)+ }+}++func TestWakeupConditionRepeatsOnlyWhenItBecomesTrueAgain(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ label := f.Insert(t, "issue_label", testutil.Cols{"workspace_id": f.WorkspaceID, "name": "approved", "color": "#123456"})+ f.Cleanup(t, "DELETE FROM issue_to_label WHERE label_id=$1", label)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", Instruction: "Ship it",+ Condition: condition(t, map[string]any{"type": "issue_field", "field": "label", "label_id": label})})+ if !w.MaxFires.Valid || w.MaxFires.Int32 != wakeupDefaultMaxFires {+ t.Fatalf("repeating rule cap = %+v, want default", w.MaxFires)+ }+ f.Exec(t, "INSERT INTO issue_to_label(issue_id,label_id) VALUES($1,$2)", issue, label)+ wakeTick(t, f, s, w.ID)+ wakeTick(t, f, s, w.ID)+ if n := wakeRuns(t, f, w.ID); n != 1 {+ t.Fatalf("a condition that stays true fired %d times, want 1", n)+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='completed',completed_at=now() WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID))+ f.Exec(t, "DELETE FROM issue_to_label WHERE issue_id=$1 AND label_id=$2", issue, label)+ wakeTick(t, f, s, w.ID)+ f.Exec(t, "INSERT INTO issue_to_label(issue_id,label_id) VALUES($1,$2)", issue, label)+ got := wakeTick(t, f, s, w.ID)+ if n := wakeRuns(t, f, w.ID); n != 2 {+ t.Fatalf("re-satisfied condition fired %d times total, want 2", n)+ }+ if !got.Enabled || got.FireCount != 2 {+ t.Fatalf("continuous rule after two fires: enabled=%t fire_count=%d", got.Enabled, got.FireCount)+ }+}++func TestWakeupConditionChildrenAndOtherIssue(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ first := f.Issue(t, "Stage 1 child", testutil.Cols{"parent_issue_id": issue, "status": "todo", "stage": 1})+ f.Issue(t, "Stage 2 child", testutil.Cols{"parent_issue_id": issue, "status": "todo", "stage": 2})+ other := f.Issue(t, "Blocking issue", testutil.Cols{"status": "in_progress"})+ stage := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Instruction: "Start stage 2",+ Condition: condition(t, map[string]any{"type": "children_done", "stage": 1})})+ watch := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Instruction: "Continue after the blocker",+ Condition: condition(t, map[string]any{"type": "other_issue", "issue_id": other, "state": "done"})})+ wakeTick(t, f, s, stage.ID)+ wakeTick(t, f, s, watch.ID)+ if wakeRuns(t, f, stage.ID)+wakeRuns(t, f, watch.ID) != 0 {+ t.Fatal("unmet conditions started runs")+ }+ var watched WakeupCondition+ _ = json.Unmarshal(watch.Condition, &watched)+ if !strings.Contains(watched.Identifier, "-") {+ t.Fatalf("watched issue identifier not recorded: %s", watch.Condition)+ }+ f.Exec(t, "UPDATE issue SET status='cancelled' WHERE id=$1", first)+ f.Exec(t, "UPDATE issue SET status='done' WHERE id=$1", other)+ wakeTick(t, f, s, stage.ID)+ wakeTick(t, f, s, watch.ID)+ // Both hold for the same agent: the second waits for the first one's run+ // and joins it when it is claimed, instead of queuing another behind it.+ if wakeRuns(t, f, stage.ID) != 1 || wakeRuns(t, f, watch.ID) != 0 {+ t.Fatalf("stage runs=%d, other-issue runs=%d, want one shared run", wakeRuns(t, f, stage.ID), wakeRuns(t, f, watch.ID))+ }+ var shared string+ f.QueryRow(t, "SELECT id FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(stage.ID)).Scan(&shared)+ if notes := wakeClaim(t, f, s, shared); !strings.Contains(notes, "Continue after the blocker") || !strings.Contains(notes, `"state":"done"`) {+ t.Fatalf("shared run lacks the joined rule: %q", notes)+ }+}++func TestWakeupConditionPullRequestChecksWaitForNewResult(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ ctx := context.Background()+ var pr string+ if err := f.Pool.QueryRow(ctx, `INSERT INTO github_pull_request(workspace_id,installation_id,repo_owner,repo_name,pr_number,title,state,html_url,pr_created_at,pr_updated_at,snapshot_head_sha,checks_rollup_state)+ VALUES($1,1,'multica-ai','wakeup-test',(extract(epoch from clock_timestamp())*1000)::bigint % 100000,'PR','open','https://example.test/pr',now(),now(),'aaa','SUCCESS') RETURNING id`, f.WorkspaceID).Scan(&pr); err != nil {+ t.Fatal(err)+ }+ f.Cleanup(t, "DELETE FROM github_pull_request WHERE id=$1", pr)+ f.Cleanup(t, "DELETE FROM issue_pull_request WHERE pull_request_id=$1", pr)+ f.Exec(t, "INSERT INTO issue_pull_request(issue_id,pull_request_id) VALUES($1,$2)", issue, pr)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Instruction: "Look at CI",+ Condition: condition(t, map[string]any{"type": "pull_request", "event": "checks_finished"})})+ // Finished checks from before registration belong to an older push.+ wakeTick(t, f, s, w.ID)+ f.Exec(t, "UPDATE github_pull_request SET snapshot_head_sha='bbb',checks_rollup_state='PENDING' WHERE id=$1", pr)+ wakeTick(t, f, s, w.ID)+ if n := wakeRuns(t, f, w.ID); n != 0 {+ t.Fatalf("stale or pending checks started %d runs", n)+ }+ f.Exec(t, "UPDATE github_pull_request SET checks_rollup_state='FAILURE' WHERE id=$1", pr)+ got := wakeTick(t, f, s, w.ID)+ if n := wakeRuns(t, f, w.ID); n != 1 {+ t.Fatalf("finished checks started %d runs, want 1", n)+ }+ task, err := f.q.GetAgentTask(ctx, got.LastTaskID)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(task.HandoffNote.String, `"checks":"failure"`) || !strings.Contains(task.HandoffNote.String, `"head_sha":"bbb"`) {+ t.Fatalf("PR facts missing: %s", task.HandoffNote.String)+ }+}++func TestWakeupConditionValidation(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ ctx := context.Background()+ member := parseTestUUID(t, f.UserID)+ for name, in := range map[string]WakeupInput{+ "unknown status": {Condition: condition(t, map[string]any{"type": "issue_field", "field": "status", "value": "nope"})},+ "this issue": {Condition: condition(t, map[string]any{"type": "other_issue", "issue_id": util.UUIDToString(issue), "state": "done"})},+ "unknown field": {Condition: condition(t, map[string]any{"type": "issue_field", "field": "title", "value": "x"})},+ "extra key": {Condition: condition(t, map[string]any{"type": "children_done", "when": "soon"})},+ "with events": {EventTypes: []string{"comment.created"}, Condition: condition(t, map[string]any{"type": "children_done"})},+ "time kind": {Kind: "at", AfterSeconds: 60, Condition: condition(t, map[string]any{"type": "children_done"})},+ "cap on once": {MaxFires: 3, Condition: condition(t, map[string]any{"type": "children_done"})},+ "foreign assignee": {Condition: condition(t, map[string]any{"type": "issue_field", "field": "assignee", "assignee_type": "agent", "assignee_id": util.UUIDToString(parseTestUUID(t, "00000000-0000-0000-0000-000000000001"))})},+ "property archived": {Condition: condition(t, map[string]any{"type": "issue_field", "field": "property", "property_id": "00000000-0000-0000-0000-000000000002", "value": "x"})},+ } {+ in.AgentID, in.Instruction = agent, "x"+ if in.Kind == "" {+ in.Kind = "event"+ }+ if _, err := s.Create(ctx, issue, member, pgtype.UUID{}, in); !errors.Is(err, ErrWakeupInput) {+ t.Errorf("%s: err = %v, want ErrWakeupInput", name, err)+ }+ }+}diff --git a/server/internal/service/issue_wakeup_evidence.go b/server/internal/service/issue_wakeup_evidence.goindex b52455e7b7..c52d9b3520 100644--- a/server/internal/service/issue_wakeup_evidence.go+++ b/server/internal/service/issue_wakeup_evidence.go@@ -53,7 +53,7 @@ func mergeWakeupEvidence(w db.IssueWakeup, previous db.AgentTaskQueue, receiptsevidence = wakeupEvidence{Version: 1}}- header := "Wakeup " + util.UUIDToString(w.ID) + " triggered. Instruction:\n" + w.Instruction + "\nTrigger facts (read current state before deciding what to do):\n"+ header := wakeupNoteHeader(w)budget := wakeupNoteLimit - len(header) - len(wakeupOmittedEvidence) - len(wakeupLegacyHeading)budget = max(budget, 0)total := len(evidence.Legacy)@@ -107,7 +107,7 @@ func mergeWakeupEvidence(w db.IssueWakeup, previous db.AgentTaskQueue, receipts}func renderWakeupEvidence(w db.IssueWakeup, evidence wakeupEvidence) string {- header := "Wakeup " + util.UUIDToString(w.ID) + " triggered. Instruction:\n" + w.Instruction + "\nTrigger facts (read current state before deciding what to do):\n"+ header := wakeupNoteHeader(w)if evidence.Omitted {header += wakeupOmittedEvidence}@@ -133,3 +133,14 @@ func canonicalWakeupPayload(raw json.RawMessage) json.RawMessage {result, _ := json.Marshal(value)return result}++// wakeupNoteHeader opens the [WAKEUP] block. A scheduled check may end with a+// check-in instead of a comment when nothing needs a reply; say so, with the+// exact command, only for those rules.+func wakeupNoteHeader(w db.IssueWakeup) string {+ header := "Wakeup " + util.UUIDToString(w.ID) + " triggered. Instruction:\n" + w.Instruction + "\n"+ if w.Kind == "every" || w.Kind == "cron" {+ header += "This is a scheduled check. If it finds nothing that needs a reply, end with `multica issue wakeup checkin " + util.UUIDToString(w.IssueID) + " " + util.UUIDToString(w.ID) + " --note \"<what you checked and found>\"` instead of posting a comment; the note is shown on the rule. Post a comment when something changed, needs attention, or the check is done.\n"+ }+ return header + "Trigger facts (read current state before deciding what to do):\n"+}diff --git a/server/internal/service/issue_wakeup_expiry_test.go b/server/internal/service/issue_wakeup_expiry_test.gonew file mode 100644index 0000000000..abe335fa99--- /dev/null+++ b/server/internal/service/issue_wakeup_expiry_test.go@@ -0,0 +1,143 @@+package service++import (+ "context"+ "errors"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestIssueWakeupExpiryValidation(t *testing.T) {+ s := IssueWakeupService{}+ now := time.Now()+ past, far := now.Add(-time.Minute), now.Add(400*24*time.Hour)+ soon := now.Add(time.Hour)+ for name, in := range map[string]WakeupInput{+ "single time takes no deadline": {Kind: "at", ExpiresInSeconds: 3600},+ "both forms": {Kind: "event", ExpiresAt: &soon, ExpiresInSeconds: 3600},+ "timeout without deadline": {Kind: "event", OnTimeout: "wake"},+ "time rule cannot wake": {Kind: "every", ExpiresInSeconds: 3600, OnTimeout: "wake"},+ "unknown timeout": {Kind: "event", ExpiresInSeconds: 3600, OnTimeout: "retry"},+ "too short": {Kind: "event", ExpiresInSeconds: 30},+ "past deadline": {Kind: "cron", ExpiresAt: &past},+ "beyond a year": {Kind: "cron", ExpiresAt: &far},+ } {+ in := in+ if _, _, err := s.Expiry(&in, now); !errors.Is(err, ErrWakeupInput) {+ t.Errorf("%s: accepted %+v", name, in)+ }+ }+ in := WakeupInput{Kind: "event", ExpiresInSeconds: 3600}+ at, seconds, err := s.Expiry(&in, now)+ if err != nil || !at.Time.Equal(now.Add(time.Hour)) || seconds.Int64 != 3600 || in.OnTimeout != "end" {+ t.Fatalf("relative wait: %v %v %v %q", at, seconds, err, in.OnTimeout)+ }+ in = WakeupInput{Kind: "every"}+ if at, seconds, err = s.Expiry(&in, now); err != nil || at.Valid || seconds.Valid {+ t.Fatal("rules without a deadline stay open-ended for existing clients")+ }+}++// A deadline that passes without a subscribed event ends the rule. With+// on_timeout=wake the target runs once with the timeout as its trigger fact;+// the rule reads as timed out, not as turned off, so that run stays claimable.+func TestIssueWakeupTimeoutWakesOnceAndEnds(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "follow up", ExpiresInSeconds: 3600, OnTimeout: "wake"})+ if !w.ExpiresAt.Valid || w.ExpirySeconds.Int64 != 3600 || w.OnTimeout.String != "wake" {+ t.Fatalf("expiry not stored: %+v", w)+ }+ wakeDispatch(t, s, w)+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)); n != 0 {+ t.Fatal("dispatched before the deadline")+ }+ f.Exec(t, "UPDATE issue_wakeup SET expires_at=now()-interval '1 second' WHERE id=$1", w.ID)+ ready, err := f.q.ListReadyWakeups(ctx)+ if err != nil {+ t.Fatal(err)+ }+ found := false+ for _, r := range ready {+ found = found || r.ID == w.ID+ }+ if !found {+ t.Fatal("expired rule is not a scheduler candidate")+ }+ wakeDispatch(t, s, w)+ wakeDispatch(t, s, w)+ var note string+ if err = f.Pool.QueryRow(ctx, "SELECT handoff_note FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)).Scan(¬e); err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(note, "wakeup.timeout") {+ t.Fatalf("timeout fact missing from the prompt: %s", note)+ }+ got, _ := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if got.Enabled || !got.TimedOutAt.Valid || got.DisabledAt.Valid {+ t.Fatalf("timed-out rule state: %+v", got)+ }+ // Later events do not reach a timed-out rule.+ f.Exec(t, "INSERT INTO comment(issue_id,workspace_id,author_type,author_id,content,type) VALUES($1,$2,'member',$3,'late','comment')", issue, f.WorkspaceID, f.UserID)+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); n != 0 {+ t.Fatal("timed-out rule captured a later event")+ }++ // Enabling again restarts the relative wait from now.+ f.Exec(t, "UPDATE agent_task_queue SET status='completed',completed_at=now() WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID))+ again, err := s.Enable(ctx, issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: got.Revision, Rearm: true})+ if err != nil {+ t.Fatal(err)+ }+ if !again.Enabled || again.TimedOutAt.Valid || !again.ExpiresAt.Time.After(time.Now().Add(59*time.Minute)) {+ t.Fatalf("rearm kept the old deadline: %+v", again)+ }+}++func TestIssueWakeupTimeoutEndsQuietly(t *testing.T) {+ for _, kind := range []string{"event", "every"} {+ t.Run(kind, func(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ in := WakeupInput{AgentID: agent, Kind: kind, Instruction: "check", ExpiresInSeconds: 7200}+ if kind == "event" {+ in.EventTypes = []string{"comment.created"}+ } else {+ in.IntervalSeconds = 3600+ }+ w := wakeCreate(t, f, s, issue, in)+ f.Exec(t, "UPDATE issue_wakeup SET expires_at=now()-interval '1 second' WHERE id=$1", w.ID)+ wakeDispatch(t, s, w)+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)); n != 0 {+ t.Fatal("on_timeout=end must not start a run")+ }+ got, _ := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if got.Enabled || !got.TimedOutAt.Valid || got.NextFireAt.Valid {+ t.Fatalf("rule did not end: %+v", got)+ }+ })+ }+}++// An absolute deadline that has passed cannot be re-enabled; the rule must be+// replaced with a new end first.+func TestIssueWakeupPastAbsoluteDeadlineCannotBeEnabled(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ ctx := context.Background()+ end := time.Now().Add(48 * time.Hour)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "cron", CronExpression: "0 9 * * *", Timezone: "Asia/Shanghai", Instruction: "daily check", ExpiresAt: &end})+ if w.ExpirySeconds.Valid {+ t.Fatal("absolute deadline stored as a relative wait")+ }+ f.Exec(t, "UPDATE issue_wakeup SET expires_at=now()-interval '1 second' WHERE id=$1", w.ID)+ wakeDispatch(t, s, w)+ got, _ := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if _, err := s.Enable(ctx, issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: got.Revision}); !errors.Is(err, ErrWakeupInput) {+ t.Fatalf("re-enabled past its deadline: %v", err)+ }+}diff --git a/server/internal/service/issue_wakeup_join.go b/server/internal/service/issue_wakeup_join.gonew file mode 100644index 0000000000..eb11418701--- /dev/null+++ b/server/internal/service/issue_wakeup_join.go@@ -0,0 +1,475 @@+package service++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/attribution"+ "github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Runs are serialized per issue and agent, so a wakeup never runs alongside+// another run of its agent; it runs after it. Two cases would make that later+// run a repeat, and a firing that hits either one starts no run of its own:+//+// - acknowledged: every input came from the agent itself, so it already+// knows. An issue, comment, reaction or attachment event the agent+// produced never wakes it. A satisfied condition its own unfinished run on+// the issue brought about does not wake it either, when the rule is the+// platform's or the agent set it up itself; a person's condition rule+// carries an instruction the running agent does not have, so it still+// runs afterwards.+// - merged: a run of the agent that runs as the same person the rule's own+// run would is waiting to start on the issue. The rule keeps its inputs,+// and when a daemon that renders them claims that run it takes them along+// (JoinWaitingWakeups): the instruction and facts ride in its prompt. The+// inputs stay the rule's until that run starts; then the firing counts+// like one that started a run (takenReceipts). If the run ends without+// starting, or goes to an older daemon, the rule has its inputs back and+// starts its own run.+const (+ wakeupOutcomeMerged = "merged"+ wakeupOutcomeAcknowledged = "acknowledged"+ maxJoinedWakeupNote = 12000+)++// receiptActor reads who produced an event receipt. Coalesced receipts keep+// only the latest actor, so they never count as the agent's own.+func receiptActor(r db.IssueWakeupReceipt) (actorType, actorID string, single bool) {+ var p struct {+ ActorType string `json:"actor_type"`+ ActorID string `json:"actor_id"`+ AgentID string `json:"agent_id"`+ Count int64 `json:"coalesced_count"`+ }+ _ = json.Unmarshal(r.Payload, &p)+ if p.ActorType == "" && p.AgentID != "" {+ p.ActorType, p.ActorID = "agent", p.AgentID+ }+ return p.ActorType, p.ActorID, p.Count <= 1+}++// acknowledgedBySelf reports whether every input of this firing came from the+// target agent itself (see the rules above).+func acknowledgedBySelf(ctx context.Context, q *db.Queries, w db.IssueWakeup, agentID, issueID pgtype.UUID, receipts []db.IssueWakeupReceipt) (bool, error) {+ if len(receipts) == 0 {+ return false, nil+ }+ agent := util.UUIDToString(agentID)+ ownRule := w.SystemRule.Valid+ if !ownRule && w.SourceTaskID.Valid {+ source, err := q.GetAgentTask(ctx, w.SourceTaskID)+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return false, err+ }+ ownRule = err == nil && source.AgentID == agentID+ }+ seen := map[pgtype.UUID]bool{}+ var causes []pgtype.UUID+ for _, r := range receipts {+ switch {+ case r.EventType == wakeupConditionEventType:+ if !ownRule {+ return false, nil+ }+ var p struct {+ SourceTaskIDs []string `json:"source_task_ids"`+ }+ _ = json.Unmarshal(r.Payload, &p)+ if len(p.SourceTaskIDs) == 0 {+ return false, nil+ }+ for _, raw := range p.SourceTaskIDs {+ id, err := util.ParseUUID(raw)+ if err != nil {+ return false, nil+ }+ if !seen[id] {+ seen[id] = true+ causes = append(causes, id)+ }+ }+ case strings.HasPrefix(r.EventType, "task."), r.EventType == "time.due", r.EventType == wakeupManualEventType, r.EventType == wakeupTimeoutEventType:+ // A run ending, a time, a person's "wake now" and a deadline are+ // never the agent's own action.+ return false, nil+ default:+ // A rule that names the agent itself as the actor asked for this.+ if w.FilterActorType.String == "agent" && w.FilterActorID == agentID {+ return false, nil+ }+ actorType, actorID, single := receiptActor(r)+ if !single || actorType != "agent" || actorID != agent {+ return false, nil+ }+ }+ }+ if len(causes) == 0 {+ return true, nil+ }+ active, err := q.CountActiveIssueRunsOfAgent(ctx, db.CountActiveIssueRunsOfAgentParams{Ids: causes, AgentID: agentID, IssueID: issueID})+ if err != nil {+ return false, err+ }+ return int(active) == len(causes), nil+}++// hasWaitingRun reports whether a run of the agent that runs as this person+// is waiting to start on the issue. A firing then keeps its inputs for it.+func hasWaitingRun(ctx context.Context, q *db.Queries, issueID, agentID, runAs pgtype.UUID) (bool, error) {+ if !runAs.Valid {+ return false, nil+ }+ _, err := q.FindWaitingIssueRun(ctx, db.FindWaitingIssueRunParams{IssueID: issueID, AgentID: agentID, OriginatorUserID: runAs})+ if errors.Is(err, pgx.ErrNoRows) {+ return false, nil+ }+ return err == nil, err+}++// childDoneRunAs is who a child_done run for this agent runs as: whoever+// caused the parent to exist, as a run the parent's own assignment would+// start.+func (s *IssueWakeupService) childDoneRunAs(ctx context.Context, issue db.Issue, agent db.Agent) (attribution.Result, error) {+ attr := s.Tasks.attributionForIssueTask(ctx, issue, pgtype.UUID{}, attribution.SourceDelegation, pgtype.UUID{})+ return s.Tasks.applyAttributionFallback(ctx, attr, agent)+}++// joinedWakeupNote is what the run is told about a rule that joined it.+func joinedWakeupNote(w db.IssueWakeup, instruction string, receipts []db.IssueWakeupReceipt) string {+ var b strings.Builder+ fmt.Fprintf(&b, "Wakeup %s fired while this run was waiting to start, so it did not start a run of its own; handle it in this run. Instruction:\n%s\nTrigger facts (read current state before deciding what to do):\n", util.UUIDToString(w.ID), instruction)+ for _, r := range receipts {+ line := r.EventType + " " + string(canonicalWakeupPayload(r.Payload)) + "\n"+ if b.Len()+len(line) > maxJoinedWakeupNote {+ b.WriteString(wakeupOmittedEvidence)+ break+ }+ b.WriteString(line)+ }+ return b.String()+}++type joinedWakeup struct {+ WakeupID string `json:"wakeup_id"`+ Revision int64 `json:"wakeup_revision"`+ Note string `json:"note"`+}++// JoinWaitingWakeups hands a run being claimed the inputs of the wakeup rules+// that waited for it and returns the run's context as the claim should render+// it. Call it only for a daemon that renders wakeup_joined. The inputs are+// reserved for the run, not consumed (see takenReceipts). What an earlier+// claim of the same run reserved is checked again, so a rule turned off,+// changed or no longer allowed since then drops out and gets its inputs back.+// A rule another writer holds keeps what it had.+func (s *IssueWakeupService) JoinWaitingWakeups(ctx context.Context, task db.AgentTaskQueue) ([]byte, error) {+ if !task.IssueID.Valid || !task.OriginatorUserID.Valid || task.Status != "dispatched" {+ return task.Context, nil+ }+ var stored struct {+ Joined []joinedWakeup `json:"wakeup_joined"`+ Chain []string `json:"wakeup_chain"`+ }+ _ = json.Unmarshal(task.Context, &stored)+ candidates, err := s.Tasks.Queries.ListWaitingWakeups(ctx, db.ListWaitingWakeupsParams{IssueID: task.IssueID, AgentID: task.AgentID})+ if err != nil || (len(candidates) == 0 && len(stored.Joined) == 0) {+ return task.Context, err+ }+ previous := map[pgtype.UUID]joinedWakeup{}+ var rules []pgtype.UUID+ for _, entry := range stored.Joined {+ if id, err := util.ParseUUID(entry.WakeupID); err == nil {+ previous[id] = entry+ rules = append(rules, id)+ }+ }+ for _, id := range candidates {+ if _, ok := previous[id]; !ok {+ rules = append(rules, id)+ }+ }+ ctx, cancel := context.WithTimeout(ctx, 2*time.Second)+ defer cancel()+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return task.Context, err+ }+ defer tx.Rollback(ctx)+ if _, err = tx.Exec(ctx, "SET LOCAL lock_timeout = '50ms'"); err != nil {+ return task.Context, err+ }+ q := s.Tasks.Queries.WithTx(tx)+ issue, err := q.GetIssue(ctx, task.IssueID)+ if err != nil {+ return task.Context, err+ }+ active, err := wakeupIssueActive(ctx, q, issue)+ if err != nil {+ return task.Context, err+ }+ changed := len(previous) != len(stored.Joined)+ joined := make([]joinedWakeup, 0, len(rules))+ chain := stored.Chain+ for _, id := range rules {+ prev, had := previous[id]+ w, err := q.TryLockIssueWakeup(ctx, id)+ if errors.Is(err, pgx.ErrNoRows) {+ // Busy: keep what an earlier claim reserved. Deleted: nothing left.+ if _, err = q.LocklessWakeup(ctx, id); err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return task.Context, err+ }+ if had && err == nil {+ joined = append(joined, prev)+ } else if had {+ changed = true+ }+ continue+ }+ if err != nil {+ return task.Context, err+ }+ entry, ruleChain, err := s.reserveForRun(ctx, q, issue, active, task, w)+ if err != nil {+ return task.Context, err+ }+ if entry == nil {+ changed = changed || had+ continue+ }+ joined = append(joined, *entry)+ if !had || prev != *entry {+ changed = true+ chain = append(chain, ruleChain...)+ }+ }+ if !changed {+ return task.Context, nil+ }+ if len(chain) > wakeupChainLimit {+ chain = chain[len(chain)-wakeupChainLimit:]+ }+ values := map[string]json.RawMessage{}+ _ = json.Unmarshal(task.Context, &values)+ values["wakeup_joined"], _ = json.Marshal(joined)+ if len(chain) > 0 {+ values["wakeup_chain"], _ = json.Marshal(chain)+ }+ next, _ := json.Marshal(values)+ updated, err := q.SetClaimedTaskContext(ctx, db.SetClaimedTaskContextParams{Context: next, ID: task.ID, DispatchedAt: task.DispatchedAt})+ if errors.Is(err, pgx.ErrNoRows) {+ // A newer claim of this run answers instead.+ return task.Context, nil+ }+ if err != nil {+ return task.Context, err+ }+ if err = tx.Commit(ctx); err != nil {+ return task.Context, err+ }+ return updated.Context, nil+}++// reserveForRun reserves one locked rule's pending inputs for the run and+// returns its entry, or releases what the run held and returns nil when the+// rule must not reach this run (or, for its own dispatch to decide, the inputs+// are the agent's own or close a loop).+func (s *IssueWakeupService) reserveForRun(ctx context.Context, q *db.Queries, issue db.Issue, active bool, task db.AgentTaskQueue, w db.IssueWakeup) (*joinedWakeup, []string, error) {+ pending, err := q.ListPendingWakeupReceipts(ctx, db.ListPendingWakeupReceiptsParams{WakeupID: w.ID, Revision: w.Revision})+ if err != nil {+ return nil, nil, err+ }+ var receipts []db.IssueWakeupReceipt+ var held, free []pgtype.UUID+ for _, r := range pending {+ if len(w.Condition) > 0 && r.EventType != wakeupConditionEventType && r.EventType != wakeupTimeoutEventType && r.EventType != wakeupManualEventType {+ continue+ }+ switch r.TaskID {+ case task.ID:+ held = append(held, r.ID)+ case pgtype.UUID{}:+ free = append(free, r.ID)+ default:+ continue+ }+ receipts = append(receipts, r)+ }+ release := func() (*joinedWakeup, []string, error) {+ if len(held) == 0 {+ return nil, nil, nil+ }+ return nil, nil, q.ReleaseWakeupReceipts(ctx, held)+ }+ if len(receipts) == 0 || !active || w.DisabledAt.Valid || w.IssueID != task.IssueID {+ return release()+ }+ if _, err := q.FindPendingWakeupTask(ctx, util.UUIDToString(w.ID)); err == nil || !errors.Is(err, pgx.ErrNoRows) {+ // The rule's own run takes its inputs.+ if err != nil {+ return nil, nil, err+ }+ return release()+ }+ instruction, ok, err := s.mayJoin(ctx, q, issue, task, w)+ if err != nil {+ return nil, nil, err+ }+ if !ok {+ return release()+ }+ if self, err := acknowledgedBySelf(ctx, q, w, task.AgentID, issue.ID, receipts); err != nil || self {+ if err != nil {+ return nil, nil, err+ }+ return release()+ }+ chain, loop, err := wakeupChain(ctx, q, w, receipts)+ if err != nil {+ return nil, nil, err+ }+ if loop {+ return release()+ }+ if len(free) > 0 {+ if err = q.ReserveWakeupReceipts(ctx, db.ReserveWakeupReceiptsParams{TaskID: task.ID, Ids: free}); err != nil {+ return nil, nil, err+ }+ }+ return &joinedWakeup{WakeupID: util.UUIDToString(w.ID), Revision: w.Revision, Note: joinedWakeupNote(w, instruction, receipts)}, chain, nil+}++// mayJoin reports whether the run is one the rule's own run would be: the+// same agent, run as the same person, who may still use the agent. It returns+// the instruction the run gets.+func (s *IssueWakeupService) mayJoin(ctx context.Context, q *db.Queries, issue db.Issue, task db.AgentTaskQueue, w db.IssueWakeup) (string, bool, error) {+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: task.AgentID, WorkspaceID: w.WorkspaceID})+ if errors.Is(err, pgx.ErrNoRows) {+ return "", false, nil+ }+ if err != nil {+ return "", false, err+ }+ if !w.SystemRule.Valid {+ if w.AgentID != task.AgentID || w.CreatedBy != task.OriginatorUserID || (w.Mode == "once" && w.LastTaskID.Valid) {+ return "", false, nil+ }+ if err := s.authorize(ctx, q, w.WorkspaceID, w.CreatedBy, agent); err != nil {+ if errors.Is(err, ErrWakeupForbidden) {+ err = nil+ }+ return "", false, err+ }+ return w.Instruction, true, nil+ }+ if !w.Enabled || issuestatus.Effective(ctx, q, issue.WorkspaceID, issue.Status) == "backlog" {+ return "", false, nil+ }+ target, err := resolveWakeTarget(ctx, q, issue)+ if err != nil || target.Agent.ID != task.AgentID {+ return "", false, err+ }+ runAs, err := s.childDoneRunAs(ctx, issue, agent)+ if err != nil || runAs.UserID != task.OriginatorUserID {+ return "", false, err+ }+ var settings []byte+ if ws, err := q.GetWorkspace(ctx, issue.WorkspaceID); err == nil {+ settings = ws.Settings+ }+ return ChildDoneInstruction(w.Instruction, settings), true, nil+}++// takenRun is a run that took some of a rule's inputs along and has started.+type takenRun struct {+ task db.AgentTaskQueue+ receipts []db.IssueWakeupReceipt+}++// takenReceipts sorts a rule's pending inputs by the run a claim reserved them+// for. It returns the free ones (including those of a run that ended without+// starting, which go back to the rule), whether a run that has not started+// yet still holds some, and the runs that started with some, whose inputs+// the caller consumes as a merged firing.+func takenReceipts(ctx context.Context, q *db.Queries, receipts []db.IssueWakeupReceipt) ([]db.IssueWakeupReceipt, bool, []takenRun, error) {+ byRun := map[pgtype.UUID][]db.IssueWakeupReceipt{}+ var runs []pgtype.UUID+ for _, r := range receipts {+ if r.TaskID.Valid {+ if _, ok := byRun[r.TaskID]; !ok {+ runs = append(runs, r.TaskID)+ }+ byRun[r.TaskID] = append(byRun[r.TaskID], r)+ }+ }+ if len(runs) == 0 {+ return receipts, false, nil, nil+ }+ released := map[pgtype.UUID]bool{}+ holding := false+ var taken []takenRun+ for _, id := range runs {+ task, err := q.GetAgentTask(ctx, id)+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return nil, false, nil, err+ }+ switch {+ case err == nil && (task.StartedAt.Valid || task.Status == "running"):+ taken = append(taken, takenRun{task: task, receipts: byRun[id]})+ case err == nil && task.Status != "completed" && task.Status != "failed" && task.Status != "cancelled":+ holding = true+ default:+ ids := make([]pgtype.UUID, 0, len(byRun[id]))+ for _, r := range byRun[id] {+ ids = append(ids, r.ID)+ released[r.ID] = true+ }+ if err = q.ReleaseWakeupReceipts(ctx, ids); err != nil {+ return nil, false, nil, err+ }+ }+ }+ free := make([]db.IssueWakeupReceipt, 0, len(receipts))+ for _, r := range receipts {+ if released[r.ID] {+ r.TaskID = pgtype.UUID{}+ }+ if !r.TaskID.Valid {+ free = append(free, r)+ }+ }+ return free, holding, taken, nil+}++func receiptIDs(receipts []db.IssueWakeupReceipt) []pgtype.UUID {+ ids := make([]pgtype.UUID, 0, len(receipts))+ for _, r := range receipts {+ ids = append(ids, r.ID)+ }+ return ids+}++// JoinedWakeupNotes renders the wakeups that joined a run, for its prompt.+func JoinedWakeupNotes(context []byte) string {+ var stored struct {+ Joined []joinedWakeup `json:"wakeup_joined"`+ }+ if json.Unmarshal(context, &stored) != nil {+ return ""+ }+ notes := make([]string, 0, len(stored.Joined))+ for _, j := range stored.Joined {+ if strings.TrimSpace(j.Note) != "" {+ notes = append(notes, strings.TrimSpace(j.Note))+ }+ }+ return strings.Join(notes, "\n\n")+}diff --git a/server/internal/service/issue_wakeup_join_test.go b/server/internal/service/issue_wakeup_join_test.gonew file mode 100644index 0000000000..6b8729fb30--- /dev/null+++ b/server/internal/service/issue_wakeup_join_test.go@@ -0,0 +1,300 @@+package service++import (+ "context"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// wakeWaitingRun queues an ordinary run of the agent on the issue that runs+// as runAs, like an assignment or a comment would.+func wakeWaitingRun(t *testing.T, f principalFixture, issue pgtype.UUID, agent, runAs string) string {+ t.Helper()+ return f.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')"),+ "originator_user_id": runAs, "accountable_user_id": runAs})+}++// wakeClaim claims the run as a daemon that renders joined wakeups does and+// returns what its prompt gets.+func wakeClaim(t *testing.T, f principalFixture, s *IssueWakeupService, taskID string) string {+ t.Helper()+ f.Exec(t, "UPDATE agent_task_queue SET status='dispatched',dispatched_at=clock_timestamp() WHERE id=$1", taskID)+ task, err := f.q.GetAgentTask(context.Background(), parseTestUUID(t, taskID))+ if err != nil {+ t.Fatal(err)+ }+ joined, err := s.JoinWaitingWakeups(context.Background(), task)+ if err != nil {+ t.Fatal(err)+ }+ return JoinedWakeupNotes(joined)+}++// wakeStart marks the run started, as the daemon's start call does.+func wakeStart(t *testing.T, f principalFixture, taskID string) {+ t.Helper()+ f.Exec(t, "UPDATE agent_task_queue SET status='running',started_at=clock_timestamp() WHERE id=$1", taskID)+}++// wakeRequeue sends a claimed run back to the queue the way a claim that+// could not be finalized does.+func wakeRequeue(t *testing.T, f principalFixture, s *IssueWakeupService, taskID string) {+ t.Helper()+ task, err := f.q.GetAgentTask(context.Background(), parseTestUUID(t, taskID))+ if err != nil {+ t.Fatal(err)+ }+ next, err := s.Tasks.RequeueTaskAfterClaimFailure(context.Background(), task)+ if err != nil || next == nil || next.Status != "queued" {+ t.Fatalf("requeue: %+v %v", next, err)+ }+}++func invocableByWorkspace(t *testing.T, f principalFixture, agent string) {+ t.Helper()+ f.Exec(t, "UPDATE agent SET permission_mode='public_to',visibility='workspace' WHERE id=$1", agent)+ f.Insert(t, "agent_invocation_target", testutil.Cols{"agent_id": agent, "target_type": "workspace", "target_id": f.WorkspaceID})+}++// Joining a run counts toward the rule's cap like starting one.+func TestJoinedWakeupCountsTowardTheCap(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", MaxFires: 1, EventTypes: []string{"comment.created"}, Instruction: "Review"})+ waiting := wakeWaitingRun(t, f, issue, agent, f.UserID)+ f.Comment(t, util.UUIDToString(issue), "trigger")+ wakeTick(t, f, s, w.ID)+ if notes := wakeClaim(t, f, s, waiting); !strings.Contains(notes, "Review") {+ t.Fatalf("the claimed run lacks the rule: %q", notes)+ }+ wakeStart(t, f, waiting)+ wakeTick(t, f, s, w.ID)+ got, err := f.q.LocklessWakeup(context.Background(), w.ID)+ if err != nil {+ t.Fatal(err)+ }+ if got.Enabled || got.PausedReason.String != wakeupPausedMaxFires || got.FireCount != 1 {+ t.Fatalf("after joining once with max_fires=1: enabled=%t paused=%q fire_count=%d", got.Enabled, got.PausedReason.String, got.FireCount)+ }+}++// A rule turned off before the run is claimed hands it nothing, and one+// turned off after a claim that did not go through is dropped from the next.+func TestTurnedOffWakeupHandsNothingOver(t *testing.T) {+ ctx := context.Background()+ for _, tc := range []struct {+ name string+ afterClaim bool+ off func(*IssueWakeupService, pgtype.UUID, db.IssueWakeup, pgtype.UUID) error+ }{+ {"deleted before the claim", false, func(s *IssueWakeupService, issue pgtype.UUID, w db.IssueWakeup, member pgtype.UUID) error {+ return s.Delete(ctx, issue, w.ID, member)+ }},+ {"turned off before the claim", false, func(s *IssueWakeupService, issue pgtype.UUID, w db.IssueWakeup, member pgtype.UUID) error {+ _, err := s.Disable(ctx, issue, w.ID, member)+ return err+ }},+ {"turned off before a repeated claim", true, func(s *IssueWakeupService, issue pgtype.UUID, w db.IssueWakeup, member pgtype.UUID) error {+ _, err := s.Disable(ctx, issue, w.ID, member)+ return err+ }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "Do not run after it is off"})+ waiting := wakeWaitingRun(t, f, issue, agent, f.UserID)+ f.Comment(t, util.UUIDToString(issue), "trigger")+ wakeTick(t, f, s, w.ID)+ if tc.afterClaim {+ if notes := wakeClaim(t, f, s, waiting); notes == "" {+ t.Fatal("the first claim got nothing")+ }+ wakeRequeue(t, f, s, waiting)+ }+ if err := tc.off(s, issue, w, parseTestUUID(t, f.UserID)); err != nil {+ t.Fatal(err)+ }+ if notes := wakeClaim(t, f, s, waiting); notes != "" {+ t.Fatalf("the run still gets the rule: %q", notes)+ }+ })+ }+}++// The sub-issue rule turned off on the issue or for the workspace between a+// claim that did not go through and the next one no longer reaches the run.+func TestTurnedOffChildDoneRuleLeavesARequeuedRun(t *testing.T) {+ for _, scope := range []string{"issue", "workspace"} {+ t.Run(scope, func(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ ctx := context.Background()+ f.Exec(t, "UPDATE issue SET status='in_progress',assignee_type='agent',assignee_id=$2 WHERE id=$1", issue, agent)+ child := f.Issue(t, "child", testutil.Cols{"parent_issue_id": issue, "status": "in_progress"})+ f.Cleanup(t, "DELETE FROM issue_child_event WHERE parent_id=$1", issue)+ if err := s.ProcessChildEvents(ctx, issue); err != nil {+ t.Fatal(err)+ }+ waiting := wakeWaitingRun(t, f, issue, agent, f.UserID)+ f.Exec(t, "UPDATE issue SET status='done' WHERE id=$1", child)+ if err := s.ProcessChildEvents(ctx, issue); err != nil {+ t.Fatal(err)+ }+ if notes := wakeClaim(t, f, s, waiting); notes == "" {+ t.Fatal("the first claim got nothing")+ }+ wakeRequeue(t, f, s, waiting)+ off := false+ if scope == "issue" {+ if _, err := s.UpdateChildDoneRule(ctx, issue, SystemWakeupInput{Enabled: &off}); err != nil {+ t.Fatal(err)+ }+ } else if _, err := s.SetChildDoneDefault(ctx, parseTestUUID(t, f.WorkspaceID), &off, nil); err != nil {+ t.Fatal(err)+ }+ if notes := wakeClaim(t, f, s, waiting); notes != "" {+ t.Fatalf("the turned-off rule still reaches the run: %q", notes)+ }+ })+ }+}++// A run that runs as someone else is never joined: the rule starts its own+// run as its creator.+func TestWakeupJoinsOnlyRunsOfTheSamePerson(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ invocableByWorkspace(t, f, agent)+ other := f.member(t, "wake-other")+ w, err := s.Create(context.Background(), issue, parseTestUUID(t, other), pgtype.UUID{}, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Other member's instruction"})+ if err != nil {+ t.Fatal(err)+ }+ waiting := wakeWaitingRun(t, f, issue, agent, f.UserID)+ f.Comment(t, util.UUIDToString(issue), "trigger")+ wakeTick(t, f, s, w.ID)+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1 AND originator_user_id=$2", util.UUIDToString(w.ID), other); n != 1 {+ t.Fatalf("own runs as the rule's creator = %d, want 1", n)+ }+ if notes := wakeClaim(t, f, s, waiting); notes != "" {+ t.Fatalf("another person's run got the rule: %q", notes)+ }+}++// A creator who lost access by the time the run is claimed hands it nothing.+func TestJoinRechecksTheCreatorsAccess(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ invocableByWorkspace(t, f, agent)+ other := f.member(t, "wake-revoked")+ w, err := s.Create(context.Background(), issue, parseTestUUID(t, other), pgtype.UUID{}, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Check access"})+ if err != nil {+ t.Fatal(err)+ }+ waiting := wakeWaitingRun(t, f, issue, agent, other)+ f.Comment(t, util.UUIDToString(issue), "trigger")+ wakeTick(t, f, s, w.ID)+ if n := wakeRuns(t, f, w.ID); n != 0 {+ t.Fatalf("the rule queued %d runs while one of the same person waited", n)+ }+ f.Exec(t, "DELETE FROM member WHERE user_id=$1 AND workspace_id=$2", other, f.WorkspaceID)+ if notes := wakeClaim(t, f, s, waiting); notes != "" {+ t.Fatalf("the rule joined after its creator lost access: %q", notes)+ }+}++// A rule whose waiting run never takes its input, because the run was+// cancelled or went to a daemon that cannot render it, still has the input+// and starts its own run.+func TestWakeupKeepsItsInputWhenTheWaitingRunDoesNotTakeIt(t *testing.T) {+ ctx := context.Background()+ t.Run("run cancelled with the rule that queued it", func(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ member := parseTestUUID(t, f.UserID)+ host := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "every", IntervalSeconds: 3600, Instruction: "Scheduled check"})+ if err := s.Trigger(ctx, issue, host.ID, member); err != nil {+ t.Fatal(err)+ }+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Independent once-only work"})+ f.Comment(t, util.UUIDToString(issue), "trigger")+ wakeTick(t, f, s, w.ID)+ if n := wakeRuns(t, f, w.ID); n != 0 {+ t.Fatalf("the rule queued %d runs while the scheduled run waited", n)+ }+ if _, err := s.Disable(ctx, issue, host.ID, member); err != nil {+ t.Fatal(err)+ }+ wakeTick(t, f, s, w.ID)+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1 AND status='queued'", util.UUIDToString(w.ID)); n != 1 {+ t.Fatalf("queued runs of the rule = %d, want 1", n)+ }+ })+ t.Run("run claimed, sent back, then cancelled with its rule", func(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ member := parseTestUUID(t, f.UserID)+ host := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "every", IntervalSeconds: 3600, Instruction: "Scheduled check"})+ if err := s.Trigger(ctx, issue, host.ID, member); err != nil {+ t.Fatal(err)+ }+ var waiting string+ f.QueryRow(t, "SELECT id::text FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(host.ID)).Scan(&waiting)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Independent once-only work"})+ f.Comment(t, util.UUIDToString(issue), "trigger")+ wakeTick(t, f, s, w.ID)+ if notes := wakeClaim(t, f, s, waiting); !strings.Contains(notes, "Independent once-only work") {+ t.Fatalf("the claim lacks the rule: %q", notes)+ }+ wakeRequeue(t, f, s, waiting)+ if _, err := s.Disable(ctx, issue, host.ID, member); err != nil {+ t.Fatal(err)+ }+ got := wakeTick(t, f, s, w.ID)+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1 AND status='queued'", util.UUIDToString(w.ID)); n != 1 {+ t.Fatalf("queued runs of the rule = %d (enabled=%t fire_count=%d), want 1", n, got.Enabled, got.FireCount)+ }+ })+ t.Run("run claimed by an older daemon", func(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Review"})+ waiting := wakeWaitingRun(t, f, issue, agent, f.UserID)+ f.Comment(t, util.UUIDToString(issue), "trigger")+ wakeTick(t, f, s, w.ID)+ f.Exec(t, "UPDATE agent_task_queue SET status='dispatched',dispatched_at=clock_timestamp() WHERE id=$1", waiting)+ wakeTick(t, f, s, w.ID)+ if n := wakeRuns(t, f, w.ID); n != 1 {+ t.Fatalf("runs of the rule = %d, want 1", n)+ }+ })+}++// The one-time backfill can create a parent's rule while a sub-issue's+// closing is recorded but not processed; that closing still wakes the+// assignee.+func TestChildDoneBackfillKeepsAPendingClose(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ ctx := context.Background()+ f.Exec(t, "UPDATE issue SET status='in_progress',assignee_type='agent',assignee_id=$2 WHERE id=$1", issue, agent)+ child := f.Issue(t, "child", testutil.Cols{"parent_issue_id": issue, "status": "in_progress"})+ f.Cleanup(t, "DELETE FROM issue_child_event WHERE parent_id=$1", issue)+ // A sub-issue from before the rule existed: only its closing is recorded.+ f.Exec(t, "DELETE FROM issue_child_event WHERE parent_id=$1", issue)+ f.Exec(t, "UPDATE issue SET status='done' WHERE id=$1", child)+ parent, err := f.q.GetIssue(ctx, issue)+ if err != nil {+ t.Fatal(err)+ }+ if err = s.ensureRule(ctx, parent); err != nil {+ t.Fatal(err)+ }+ if err = s.ProcessChildEvents(ctx, issue); err != nil {+ t.Fatal(err)+ }+ w, err := f.q.GetSystemWakeup(ctx, db.GetSystemWakeupParams{IssueID: issue, SystemRule: systemRuleText(SystemRuleChildDone)})+ if err != nil {+ t.Fatal(err)+ }+ if n := wakeRuns(t, f, w.ID); n != 1 {+ t.Fatalf("pending closing lost after the backfill: runs=%d condition_state=%q", n, w.ConditionState)+ }+}diff --git a/server/internal/service/issue_wakeup_manage.go b/server/internal/service/issue_wakeup_manage.gonew file mode 100644index 0000000000..21f8de1a35--- /dev/null+++ b/server/internal/service/issue_wakeup_manage.go@@ -0,0 +1,202 @@+package service++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"+ "time"+ "unicode/utf8"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++const maxWakeupCheckinRunes = 500++// lockManagedWakeup takes Save's lock order (workspace, issue, rule) and+// checks that member may manage the rule: its creator or a workspace admin.+func lockManagedWakeup(ctx context.Context, tx pgx.Tx, q *db.Queries, issueID, id, member pgtype.UUID) (db.Issue, db.IssueWakeup, error) {+ var workspace pgtype.UUID+ if err := tx.QueryRow(ctx, "SELECT w.id FROM workspace w JOIN issue i ON i.workspace_id=w.id WHERE i.id=$1 FOR KEY SHARE OF w", issueID).Scan(&workspace); err != nil {+ return db.Issue{}, db.IssueWakeup{}, err+ }+ issue, err := q.LockWakeupIssue(ctx, issueID)+ if err != nil {+ return issue, db.IssueWakeup{}, err+ }+ membership, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: member, WorkspaceID: issue.WorkspaceID})+ if err != nil {+ return issue, db.IssueWakeup{}, ErrWakeupForbidden+ }+ w, err := q.LockIssueWakeup(ctx, id)+ if err != nil {+ return issue, w, err+ }+ if w.IssueID != issue.ID || w.WorkspaceID != issue.WorkspaceID {+ return issue, db.IssueWakeup{}, pgx.ErrNoRows+ }+ // System rules are changed on the issue's system rule, not as a person's rule.+ if w.SystemRule.Valid {+ return issue, db.IssueWakeup{}, ErrWakeupForbidden+ }+ if w.CreatedBy != member && membership.Role != "owner" && membership.Role != "admin" {+ return issue, db.IssueWakeup{}, ErrWakeupForbidden+ }+ return issue, w, nil+}++// Trigger ("wake now") queues one run of the rule immediately, as if its+// trigger had happened. It goes through ordinary dispatch, so it merges with+// a queued run and re-checks the creator's permission to invoke the agent. A+// rule someone turned off, or one the platform stopped for a loop or burst,+// must be turned on first.+func (s *IssueWakeupService) Trigger(ctx context.Context, issueID, id, member pgtype.UUID) error {+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)+ q := s.Tasks.Queries.WithTx(tx)+ issue, w, err := lockManagedWakeup(ctx, tx, q, issueID, id, member)+ if err != nil {+ return err+ }+ active, err := wakeupIssueActive(ctx, q, issue)+ if err != nil {+ return err+ }+ if !active {+ return fmt.Errorf("%w: issue is closed", ErrWakeupInput)+ }+ if w.DisabledAt.Valid {+ return fmt.Errorf("%w: turn the wakeup on first", ErrWakeupInput)+ }+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: w.AgentID, WorkspaceID: w.WorkspaceID})+ if err != nil {+ return ErrWakeupForbidden+ }+ if err = s.authorize(ctx, q, w.WorkspaceID, member, agent); err != nil {+ return err+ }+ var now time.Time+ if err = tx.QueryRow(ctx, "SELECT now()").Scan(&now); err != nil {+ return err+ }+ key := "manual:" + util.UUIDToString(dbid.NewV7())+ payload, _ := json.Marshal(map[string]any{"event_id": key, "requested_at": now.UTC().Format(time.RFC3339),+ "actor_type": "member", "actor_id": util.UUIDToString(member)})+ if _, err = q.RecordWakeupReceipt(ctx, db.RecordWakeupReceiptParams{ID: dbid.NewV7(), WakeupID: w.ID, Revision: w.Revision, EventKey: key, EventType: wakeupManualEventType, Payload: payload}); err != nil {+ return err+ }+ if err = tx.Commit(ctx); err != nil {+ return err+ }+ // Dispatch now rather than on the next tick; the scheduler retries if+ // this attempt loses a lock race.+ _ = s.dispatch(ctx, w)+ return nil+}++// Delete removes a rule and its pending inputs, and withdraws its runs that+// have not started. Started runs keep the ordinary Stop control, and their+// history stays in the run list.+func (s *IssueWakeupService) Delete(ctx context.Context, issueID, id, member pgtype.UUID) error {+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)+ q := s.Tasks.Queries.WithTx(tx)+ if _, _, err = lockManagedWakeup(ctx, tx, q, issueID, id, member); err != nil {+ return err+ }+ tasks, err := q.CancelUnstartedWakeupTasks(ctx, util.UUIDToString(id))+ if err != nil {+ return err+ }+ if err = q.DeleteIssueWakeupReceipts(ctx, id); err != nil {+ return err+ }+ if err = q.DeleteIssueWakeup(ctx, db.DeleteIssueWakeupParams{ID: id, IssueID: issueID}); err != nil {+ return err+ }+ if err = tx.Commit(ctx); err != nil {+ return err+ }+ for _, task := range tasks {+ s.Tasks.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)+ }+ return nil+}++// CheckIn lets a run of a scheduled check end without a comment when it found+// nothing new. The note is kept on the run and shown with the rule; the run+// completion then skips the synthesized fallback comment. This is the only+// exception to "every run leaves a comment": it needs a run the rule itself+// started, and only an every/cron rule.+func (s *IssueWakeupService) CheckIn(ctx context.Context, issueID, id, taskID pgtype.UUID, agentID string, note string) error {+ note = strings.TrimSpace(note)+ if note == "" || utf8.RuneCountInString(note) > maxWakeupCheckinRunes {+ return fmt.Errorf("%w: note must contain 1–%d characters", ErrWakeupInput, maxWakeupCheckinRunes)+ }+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)+ q := s.Tasks.Queries.WithTx(tx)+ var status, wakeupID string+ var taskIssue, taskAgent pgtype.UUID+ err = tx.QueryRow(ctx, "SELECT status,issue_id,agent_id,COALESCE(context->>'wakeup_id','') FROM agent_task_queue WHERE id=$1 FOR UPDATE", taskID).Scan(&status, &taskIssue, &taskAgent, &wakeupID)+ if err != nil {+ return ErrWakeupForbidden+ }+ if taskIssue != issueID || wakeupID != util.UUIDToString(id) || util.UUIDToString(taskAgent) != agentID {+ return ErrWakeupForbidden+ }+ if status != "running" {+ return fmt.Errorf("%w: only a running check can check in", ErrWakeupConflict)+ }+ w, err := q.LocklessWakeup(ctx, id)+ if err != nil {+ return err+ }+ if w.Kind != "every" && w.Kind != "cron" {+ return fmt.Errorf("%w: check-ins are for scheduled checks; post a comment instead", ErrWakeupInput)+ }+ var now time.Time+ if err = tx.QueryRow(ctx, "SELECT now()").Scan(&now); err != nil {+ return err+ }+ checkin, _ := json.Marshal(map[string]any{"note": note, "at": now.UTC().Format(time.RFC3339)})+ if _, err = tx.Exec(ctx, "UPDATE agent_task_queue SET context=COALESCE(context,'{}'::jsonb)||jsonb_build_object('wakeup_checkin',$2::jsonb) WHERE id=$1", taskID, checkin); err != nil {+ return err+ }+ activity, err := recordWakeupActivity(ctx, q, w, wakeupActivityCheckin, "agent", taskAgent, map[string]any{"note": note, "task_id": util.UUIDToString(taskID)})+ if err != nil {+ return err+ }+ if err = tx.Commit(ctx); err != nil {+ return err+ }+ s.publishWakeupActivities(activity)+ return nil+}++// HasWakeupCheckin reports whether a completed run ended with a check-in, in+// which case its completion posts no fallback comment.+func HasWakeupCheckin(task db.AgentTaskQueue) bool {+ var ctx struct {+ WakeupID string `json:"wakeup_id"`+ Checkin json.RawMessage `json:"wakeup_checkin"`+ }+ if json.Unmarshal(task.Context, &ctx) != nil {+ return false+ }+ return ctx.WakeupID != "" && len(ctx.Checkin) > 0 && string(ctx.Checkin) != "null"+}diff --git a/server/internal/service/issue_wakeup_safety_test.go b/server/internal/service/issue_wakeup_safety_test.gonew file mode 100644index 0000000000..3d195a1821--- /dev/null+++ b/server/internal/service/issue_wakeup_safety_test.go@@ -0,0 +1,231 @@+package service++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func finishWakeupRuns(t *testing.T, f principalFixture, id pgtype.UUID) {+ t.Helper()+ f.Exec(t, "UPDATE agent_task_queue SET status='completed',completed_at=now() WHERE context->>'wakeup_id'=$1 AND status IN ('queued','dispatched','running')", util.UUIDToString(id))+}++func TestWakeupMaxFiresPausesAfterTheCap(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", MaxFires: 2,+ EventTypes: []string{"comment.created"}, Instruction: "Answer new comments"})+ for i := range 3 {+ f.Comment(t, util.UUIDToString(issue), "question")+ w = wakeTick(t, f, s, w.ID)+ if i < 2 {+ finishWakeupRuns(t, f, w.ID)+ }+ }+ if n := wakeRuns(t, f, w.ID); n != 2 {+ t.Fatalf("capped rule started %d runs, want 2", n)+ }+ if w.Enabled || w.PausedReason.String != wakeupPausedMaxFires || w.DisabledAt.Valid {+ t.Fatalf("rule after cap: enabled=%t reason=%q disabled_at=%v", w.Enabled, w.PausedReason.String, w.DisabledAt)+ }+ if n := f.Count(t, "SELECT count(*) FROM activity_log WHERE issue_id=$1 AND action='wakeup_paused' AND details->>'reason'='max_fires'", issue); n != 1 {+ t.Fatalf("pause timeline entries = %d, want 1", n)+ }+ // Turning it back on starts a new count.+ w, err := s.Enable(context.Background(), issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: w.Revision})+ if err != nil {+ t.Fatal(err)+ }+ if !w.Enabled || w.FireCount != 0 || w.PausedReason.Valid {+ t.Fatalf("re-enabled rule = enabled %t count %d reason %v", w.Enabled, w.FireCount, w.PausedReason)+ }+}++func TestWakeupBurstPausesTheRule(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous",+ EventTypes: []string{"comment.created"}, Instruction: "Answer new comments"})+ for range wakeupHourlyRunLimit {+ f.Task(t, agent, testutil.Cols{"issue_id": issue, "status": "completed", "context": `{"wakeup_id":"` + util.UUIDToString(w.ID) + `"}`,+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ }+ f.Comment(t, util.UUIDToString(issue), "one more")+ got := wakeTick(t, f, s, w.ID)+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1 AND status='queued'", util.UUIDToString(w.ID)); n != 0 {+ t.Fatalf("burst still queued %d runs", n)+ }+ if got.Enabled || got.PausedReason.String != wakeupPausedRate || !got.DisabledAt.Valid {+ t.Fatalf("rule after burst: enabled=%t reason=%q disabled_at=%v", got.Enabled, got.PausedReason.String, got.DisabledAt)+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL", w.ID); n != 0 {+ t.Fatalf("paused rule kept %d pending inputs", n)+ }+ // "Wake now" is refused until someone turns the rule back on.+ if err := s.Trigger(context.Background(), issue, w.ID, parseTestUUID(t, f.UserID)); !errors.Is(err, ErrWakeupInput) {+ t.Fatalf("wake now on a paused rule: %v", err)+ }+}++func TestWakeupLoopBetweenRulesPausesTheRule(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ a := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous",+ EventTypes: []string{"comment.created"}, Instruction: "Reply to the other agent"})+ b := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous",+ EventTypes: []string{"task.completed"}, Instruction: "Unrelated rule"})+ chain := func(ids ...pgtype.UUID) string {+ out := make([]string, len(ids))+ for i, id := range ids {+ out[i] = util.UUIDToString(id)+ }+ raw, _ := json.Marshal(out)+ return string(raw)+ }+ // The other side of the review round is another agent: an agent's own+ // comments never wake it.+ var runtime string+ f.QueryRow(t, "SELECT runtime_id::text FROM agent WHERE id=$1", agent).Scan(&runtime)+ reviewer := f.Agent(t, "Reviewer", runtime)+ run := func(ctx string) string {+ return f.Task(t, reviewer, testutil.Cols{"issue_id": issue, "status": "running", "context": ctx, "runtime_id": runtime})+ }+ // Once through the loop is a normal review round: A's run wakes B's+ // agent, whose comment wakes A again.+ once := run(`{"wakeup_id":"` + util.UUIDToString(b.ID) + `","wakeup_chain":` + chain(a.ID, b.ID) + `}`)+ f.Comment(t, util.UUIDToString(issue), "round one", testutil.Cols{"author_type": "agent", "author_id": reviewer, "source_task_id": once})+ got := wakeTick(t, f, s, a.ID)+ if !got.Enabled || wakeRuns(t, f, a.ID) != 1 {+ t.Fatalf("first round was blocked: enabled=%t runs=%d", got.Enabled, wakeRuns(t, f, a.ID))+ }+ var stored struct {+ Chain []string `json:"wakeup_chain"`+ }+ task, err := f.q.GetAgentTask(context.Background(), got.LastTaskID)+ if err != nil {+ t.Fatal(err)+ }+ _ = json.Unmarshal(task.Context, &stored)+ if strings.Join(stored.Chain, ",") != strings.Join([]string{util.UUIDToString(a.ID), util.UUIDToString(b.ID), util.UUIDToString(a.ID)}, ",") {+ t.Fatalf("run chain = %v", stored.Chain)+ }+ finishWakeupRuns(t, f, a.ID)+ // The third pass through A without a person in between is a loop.+ again := run(`{"wakeup_id":"` + util.UUIDToString(b.ID) + `","wakeup_chain":` + chain(a.ID, b.ID, a.ID, b.ID) + `}`)+ f.Comment(t, util.UUIDToString(issue), "round two", testutil.Cols{"author_type": "agent", "author_id": reviewer, "source_task_id": again})+ got = wakeTick(t, f, s, a.ID)+ if got.Enabled || got.PausedReason.String != wakeupPausedLoop || wakeRuns(t, f, a.ID) != 1 {+ t.Fatalf("loop not stopped: enabled=%t reason=%q runs=%d", got.Enabled, got.PausedReason.String, wakeRuns(t, f, a.ID))+ }+ // A person's comment starts a fresh chain once the rule is back on.+ got, err = s.Enable(context.Background(), issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, a.ID, WakeupEnableInput{Revision: got.Revision})+ if err != nil {+ t.Fatal(err)+ }+ f.Comment(t, util.UUIDToString(issue), "from a person")+ if got = wakeTick(t, f, s, a.ID); !got.Enabled || wakeRuns(t, f, a.ID) != 2 {+ t.Fatalf("member comment after re-enable: enabled=%t runs=%d", got.Enabled, wakeRuns(t, f, a.ID))+ }+}++func TestWakeupTriggerDeleteAndCheckIn(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ ctx := context.Background()+ member := parseTestUUID(t, f.UserID)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "every", IntervalSeconds: 3600, Instruction: "Check the migration"})+ if err := s.Trigger(ctx, issue, w.ID, member); err != nil {+ t.Fatal(err)+ }+ if n := wakeRuns(t, f, w.ID); n != 1 {+ t.Fatalf("wake now started %d runs, want 1", n)+ }+ var taskID pgtype.UUID+ f.QueryRow(t, "SELECT id FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)).Scan(&taskID)+ // Only the running check itself can check in.+ if err := s.CheckIn(ctx, issue, w.ID, taskID, agent, "Nothing changed"); !errors.Is(err, ErrWakeupConflict) {+ t.Fatalf("queued run check-in: %v", err)+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='running',started_at=now() WHERE id=$1", taskID)+ if err := s.CheckIn(ctx, issue, w.ID, taskID, util.UUIDToString(member), "Nothing changed"); !errors.Is(err, ErrWakeupForbidden) {+ t.Fatalf("another actor's check-in: %v", err)+ }+ if err := s.CheckIn(ctx, issue, w.ID, taskID, agent, " Progress 38%, 0 failures "); err != nil {+ t.Fatal(err)+ }+ task, err := f.q.GetAgentTask(ctx, taskID)+ if err != nil {+ t.Fatal(err)+ }+ if !HasWakeupCheckin(task) {+ t.Fatalf("check-in not stored: %s", task.Context)+ }+ if n := f.Count(t, "SELECT count(*) FROM activity_log WHERE issue_id=$1 AND action='wakeup_checkin' AND details->>'note'='Progress 38%, 0 failures'", issue); n != 1 {+ t.Fatalf("check-in timeline entries = %d, want 1", n)+ }+ // Deleting withdraws queued runs and removes the rule.+ if err = s.Trigger(ctx, issue, w.ID, member); err != nil {+ t.Fatal(err)+ }+ if err = s.Delete(ctx, issue, w.ID, member); err != nil {+ t.Fatal(err)+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup WHERE id=$1", w.ID); n != 0 {+ t.Fatal("rule not deleted")+ }+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1 AND status='queued'", util.UUIDToString(w.ID)); n != 0 {+ t.Fatalf("delete left %d queued runs", n)+ }+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE id=$1 AND status='running'", taskID); n != 1 {+ t.Fatal("delete must not stop a started run")+ }+}++func TestWakeupCheckInIsOnlyForScheduledChecks(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Reply"})+ task := f.Task(t, agent, testutil.Cols{"issue_id": issue, "status": "running", "context": `{"wakeup_id":"` + util.UUIDToString(w.ID) + `"}`,+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ if err := s.CheckIn(context.Background(), issue, w.ID, parseTestUUID(t, task), agent, "no reply needed"); !errors.Is(err, ErrWakeupInput) {+ t.Fatalf("event rule check-in: %v", err)+ }+}++// The check-in exception is narrow: only a run that checked in completes+// without the synthesized fallback comment.+func TestCompleteTaskSkipsFallbackCommentOnlyAfterCheckIn(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ ctx := context.Background()+ f.Cleanup(t, "DELETE FROM comment WHERE issue_id=$1", issue)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "cron", CronExpression: "0 9 * * *", Instruction: "Daily check"})+ output, _ := json.Marshal(protocol.TaskCompletedPayload{Output: "Checked; nothing new."})+ complete := func(ctxJSON string, withComment bool) int {+ cols := testutil.Cols{"issue_id": issue, "status": "running", "started_at": testutil.Raw("now()"), "context": ctxJSON,+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")}+ if withComment {+ cols["trigger_comment_id"] = f.Comment(t, util.UUIDToString(issue), "please check")+ }+ id := parseTestUUID(t, f.Task(t, agent, cols))+ if _, err := s.Tasks.CompleteTask(ctx, id, output, "", "", "", false, "", ""); err != nil {+ t.Fatal(err)+ }+ return f.Count(t, "SELECT count(*) FROM comment WHERE issue_id=$1 AND author_type='agent' AND source_task_id=$2", issue, id)+ }+ wakeupCtx := `{"wakeup_id":"` + util.UUIDToString(w.ID) + `"`+ if n := complete(wakeupCtx+`,"wakeup_checkin":{"note":"nothing new"}}`, false); n != 0 {+ t.Fatalf("checked-in run posted %d fallback comments", n)+ }+ if n := complete(wakeupCtx+`}`, false); n != 1 {+ t.Fatalf("wakeup run without a check-in posted %d fallback comments, want 1", n)+ }+ if n := complete(`{}`, true); n != 1 {+ t.Fatalf("comment-triggered run posted %d fallback comments, want 1", n)+ }+ if n := complete(`{}`, false); n != 1 {+ t.Fatalf("assignment run posted %d fallback comments, want 1", n)+ }+}diff --git a/server/internal/service/issue_wakeup_system.go b/server/internal/service/issue_wakeup_system.gonew file mode 100644index 0000000000..6a4df182c6--- /dev/null+++ b/server/internal/service/issue_wakeup_system.go@@ -0,0 +1,811 @@+package service++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "strings"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// The child_done system rule wakes a parent's assignee when a stage of its+// sub-issues closes while a later stage waits, and once more when every+// sub-issue is closed. It is an ordinary issue_wakeup row with system_rule set:+// the shared condition, receipts, runaway protection, activity and run model+// apply. What differs is owned by the platform: it has no fixed agent or+// creator (the target is the parent's assignee when it fires, a squad's leader+// for a squad, an inbox notification for a member), it cannot be deleted or+// edited by agents, and it is evaluated when sub-issues change instead of on a+// polling schedule.+const (+ SystemRuleChildDone = "child_done"+ // MaxSystemWakeupInstruction bounds per-issue and workspace instructions.+ MaxSystemWakeupInstruction = 4000+ // WorkspaceSettingChildDone and WorkspaceSettingChildDoneInstruction hold+ // the rule's workspace default. Only an explicit false turns it off.+ WorkspaceSettingChildDone = "system_wakeup_child_done"+ WorkspaceSettingChildDoneInstruction = "system_wakeup_child_done_instruction"+ // childChangeHint prompts an evaluation after sub-issues changed. Like+ // other hints it never becomes a run input.+ childChangeHint = "children.changed"+)++var childDoneCondition = json.RawMessage(`{"type":"children_done","each_stage":true}`)++// ChildDoneDefaultInstruction is what the woken assignee is asked to do when+// neither the issue nor the workspace sets an instruction. The trigger facts+// say which stage closed, which one is next and how many were cancelled.+const ChildDoneDefaultInstruction = "Sub-issues of this issue have closed; the trigger facts list each stage and which one is next. " ++ "If a later stage is waiting, check that its dependencies are met, then move its sub-issues out of backlog so they start. " ++ "If a sub-issue in the closed stages was cancelled rather than finished, decide whether its work is still needed before advancing. " ++ "When every sub-issue is closed, bring their results together on this issue and move it forward, or mark it ready for review when nothing remains."++// SystemWakeupDefault is the rule's workspace default: whether it is on and+// the instruction set for the workspace ("" when none).+func SystemWakeupDefault(settings []byte) (bool, string) {+ var values map[string]json.RawMessage+ if json.Unmarshal(settings, &values) != nil {+ return true, ""+ }+ var instruction string+ _ = json.Unmarshal(values[WorkspaceSettingChildDoneInstruction], &instruction)+ return string(values[WorkspaceSettingChildDone]) != "false", strings.TrimSpace(instruction)+}++// ChildDoneInstruction is the instruction the rule's runs receive.+func ChildDoneInstruction(issueInstruction string, settings []byte) string {+ if s := strings.TrimSpace(issueInstruction); s != "" {+ return s+ }+ if _, s := SystemWakeupDefault(settings); s != "" {+ return s+ }+ return ChildDoneDefaultInstruction+}++func systemRuleText(rule string) pgtype.Text { return pgtype.Text{String: rule, Valid: true} }++// baselineChildDone records what already holds for a rule that was just+// turned on, so facts that became true while it was off do not wake anyone.+func baselineChildDone(ctx context.Context, tx pgx.Tx, q *db.Queries, rule db.IssueWakeup) error {+ children, err := loadSubIssues(ctx, tx, q, rule.IssueID, rule.WorkspaceID)+ if err != nil {+ return err+ }+ met, fingerprint, _ := stageProgress(children)+ if !met {+ fingerprint = ""+ }+ return q.SetWakeupConditionState(ctx, db.SetWakeupConditionStateParams{ID: rule.ID, ConditionState: fingerprint})+}++// EnsureChildDoneRule returns the parent's rule, creating it when missing.+// The new rule's baseline treats sub-issues whose closing is recorded but not+// yet processed as still open, so that change still wakes the assignee,+// whichever writer creates the rule first.+func EnsureChildDoneRule(ctx context.Context, tx pgx.Tx, q *db.Queries, parent db.Issue) (db.IssueWakeup, error) {+ rule, err := q.GetSystemWakeup(ctx, db.GetSystemWakeupParams{IssueID: parent.ID, SystemRule: systemRuleText(SystemRuleChildDone)})+ if !errors.Is(err, pgx.ErrNoRows) {+ return rule, err+ }+ ws, err := q.GetWorkspace(ctx, parent.WorkspaceID)+ if err != nil {+ return rule, err+ }+ enabled, _ := SystemWakeupDefault(ws.Settings)+ children, err := loadSubIssues(ctx, tx, q, parent.ID, parent.WorkspaceID)+ if err != nil {+ return rule, err+ }+ closing, err := q.ListUnprocessedClosedChildren(ctx, parent.ID)+ if err != nil {+ return rule, err+ }+ asOpen := make(map[pgtype.UUID]bool, len(closing))+ for _, id := range closing {+ asOpen[id] = true+ }+ for i := range children {+ if asOpen[children[i].ID] {+ children[i].Closed, children[i].Cancelled = false, false+ }+ }+ met, fingerprint, _ := stageProgress(children)+ if !met {+ fingerprint = ""+ }+ rule, err = q.CreateSystemWakeup(ctx, db.CreateSystemWakeupParams{+ ID: dbid.NewV7(), WorkspaceID: parent.WorkspaceID, IssueID: parent.ID,+ EventTypes: []string{"issue.status_changed"}, Condition: childDoneCondition, ConditionState: fingerprint,+ Enabled: enabled, SystemRule: systemRuleText(SystemRuleChildDone),+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return q.GetSystemWakeup(ctx, db.GetSystemWakeupParams{IssueID: parent.ID, SystemRule: systemRuleText(SystemRuleChildDone)})+ }+ return rule, err+}++// ProcessChildEvents handles the sub-issue changes recorded on these parents:+// it creates each parent's child_done rule when missing, hands every+// sub-issue rule a hint, and evaluates them right away. The hints are the+// durable handoff; a rule the immediate pass could not dispatch is picked up+// by the scheduler.+func (s *IssueWakeupService) ProcessChildEvents(ctx context.Context, parentIDs ...pgtype.UUID) error {+ var errs []error+ seen := map[pgtype.UUID]bool{}+ for _, parentID := range parentIDs {+ if !parentID.Valid || seen[parentID] {+ continue+ }+ seen[parentID] = true+ if err := s.processChildEvents(ctx, parentID); err != nil {+ slog.Warn("sub-issue wakeups: processing failed; will retry", "error", err, "parent_id", util.UUIDToString(parentID))+ errs = append(errs, err)+ }+ }+ return errors.Join(errs...)+}++func (s *IssueWakeupService) processChildEvents(ctx context.Context, parentID pgtype.UUID) error {+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)+ q := s.Tasks.Queries.WithTx(tx)+ events, err := q.ClaimChildEvents(ctx, parentID)+ if err != nil || len(events) == 0 {+ return err+ }+ ids := make([]pgtype.UUID, 0, len(events))+ kinds := map[string]bool{}+ // The agent runs that made the changes that can satisfy a sub-issue+ // condition (a sub-issue closing, leaving, or changing stage), when every+ // such change came from one. Adding or reopening a sub-issue satisfies+ // nothing, so it does not count.+ var sources []string+ allSourced := true+ for _, e := range events {+ ids = append(ids, e.ID)+ kinds[e.Kind] = true+ if e.Kind == "attached" || e.Kind == "reopened" {+ continue+ }+ if e.SourceTaskID.Valid {+ sources = append(sources, util.UUIDToString(e.SourceTaskID))+ } else {+ allSourced = false+ }+ }+ finish := func() error {+ if err := q.FinishChildEvents(ctx, ids); err != nil {+ return err+ }+ return tx.Commit(ctx)+ }+ parent, err := q.GetIssue(ctx, parentID)+ if errors.Is(err, pgx.ErrNoRows) {+ return finish()+ }+ if err != nil {+ return err+ }+ active, err := wakeupIssueActive(ctx, q, parent)+ if err != nil {+ return err+ }+ if !active {+ return finish()+ }+ if _, err = EnsureChildDoneRule(ctx, tx, q, parent); err != nil {+ return err+ }+ rules, err := q.ListChildConditionWakeups(ctx, parent.ID)+ if err != nil {+ return err+ }+ changes := make([]string, 0, len(kinds))+ for kind := range kinds {+ changes = append(changes, kind)+ }+ hint := map[string]any{"changes": changes}+ if allSourced && len(sources) > 0 {+ hint["source_task_ids"] = sources+ }+ payload, _ := json.Marshal(hint)+ key := "children:" + util.UUIDToString(events[len(events)-1].ID)+ for _, w := range rules {+ if _, err = q.RecordWakeupReceipt(ctx, db.RecordWakeupReceiptParams{ID: dbid.NewV7(), WakeupID: w.ID, Revision: w.Revision, EventKey: key, EventType: childChangeHint, Payload: payload}); err != nil {+ return err+ }+ }+ if err = finish(); err != nil {+ return err+ }+ // People's and agents' rules first, so the system rule sees their run and+ // waits to join it instead of starting a second one for the same fact.+ var errs []error+ for _, w := range rules {+ if w.SystemRule.Valid {+ err = s.dispatchSystem(ctx, w)+ } else {+ err = s.dispatch(ctx, w)+ }+ if err != nil {+ errs = append(errs, fmt.Errorf("wakeup %s: %w", util.UUIDToString(w.ID), err))+ }+ }+ if len(errs) > 0 {+ slog.Info("sub-issue wakeups: immediate dispatch deferred to the scheduler", "parent_id", util.UUIDToString(parent.ID), "error", errors.Join(errs...))+ }+ return nil+}++// SweepChildEvents processes changes that were recorded but not handled+// right after their write, and drops handled rows after a week.+func (s *IssueWakeupService) SweepChildEvents(ctx context.Context) error {+ parents, err := s.Tasks.Queries.ListStaleChildEventParents(ctx)+ if err != nil {+ return err+ }+ err = s.ProcessChildEvents(ctx, parents...)+ cleanupCtx, cancel := context.WithTimeout(ctx, 2*time.Second)+ defer cancel()+ if _, cleanupErr := s.Tasks.Queries.DeleteProcessedChildEvents(cleanupCtx, pgtype.Timestamptz{Time: time.Now().Add(-7 * 24 * time.Hour), Valid: true}); cleanupErr != nil {+ err = errors.Join(err, fmt.Errorf("expire sub-issue events: %w", cleanupErr))+ }+ return err+}++// BackfillChildDoneRules creates the rule on open parents that predate it,+// recording what already holds so nothing fires. It returns how many it+// created; zero means every open parent has its rule.+func (s *IssueWakeupService) BackfillChildDoneRules(ctx context.Context, limit int32) (int, error) {+ parents, err := s.Tasks.Queries.ListParentsWithoutSystemWakeup(ctx, db.ListParentsWithoutSystemWakeupParams{SystemRule: systemRuleText(SystemRuleChildDone), PageLimit: limit})+ if err != nil {+ return 0, err+ }+ created := 0+ for _, parent := range parents {+ if err := s.ensureRule(ctx, parent); err != nil {+ return created, err+ }+ created+++ }+ return created, nil+}++func (s *IssueWakeupService) ensureRule(ctx context.Context, parent db.Issue) error {+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)+ if _, err = EnsureChildDoneRule(ctx, tx, s.Tasks.Queries.WithTx(tx), parent); err != nil {+ return err+ }+ return tx.Commit(ctx)+}++// wakeTarget is who a system rule reaches: the parent's agent, its squad's+// leader, or its member assignee. Agent is set only when it can run.+type wakeTarget struct {+ Type string // agent | squad | member | none+ ID pgtype.UUID+ Agent db.Agent+ SquadID pgtype.UUID+}++func (t wakeTarget) key() string {+ return t.Type + ":" + util.UUIDToString(t.ID) + ":" + util.UUIDToString(t.Agent.ID) + ":" + util.UUIDToString(t.Agent.RuntimeID)+}++func resolveWakeTarget(ctx context.Context, q *db.Queries, issue db.Issue) (wakeTarget, error) {+ if !issue.AssigneeType.Valid || !issue.AssigneeID.Valid {+ return wakeTarget{Type: "none"}, nil+ }+ target := wakeTarget{Type: issue.AssigneeType.String, ID: issue.AssigneeID}+ usable := func(a db.Agent) bool { return a.RuntimeID.Valid && !a.ArchivedAt.Valid }+ switch target.Type {+ case "member":+ return target, nil+ case "agent":+ agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: issue.AssigneeID, WorkspaceID: issue.WorkspaceID})+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return target, err+ }+ if err == nil && usable(agent) {+ target.Agent = agent+ }+ return target, nil+ case "squad":+ squad, err := q.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: issue.AssigneeID, WorkspaceID: issue.WorkspaceID})+ if errors.Is(err, pgx.ErrNoRows) {+ return target, nil+ }+ if err != nil {+ return target, err+ }+ target.SquadID = squad.ID+ leader, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: squad.LeaderID, WorkspaceID: issue.WorkspaceID})+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return target, err+ }+ if err == nil && usable(leader) {+ target.Agent = leader+ }+ return target, nil+ }+ return wakeTarget{Type: "none"}, nil+}++// childDoneFacts summarizes the newest observation for the timeline entry and+// a member's notification: the closed stage (absent when every sub-issue+// closed) and how many sub-issues that covers.+func childDoneFacts(receipts []db.IssueWakeupReceipt) map[string]any {+ facts := map[string]any{"rule": SystemRuleChildDone}+ for i := len(receipts) - 1; i >= 0; i-- {+ if receipts[i].EventType != wakeupConditionEventType {+ continue+ }+ var payload struct {+ Observed struct {+ All bool `json:"all"`+ Stage *int32 `json:"stage"`+ Total int `json:"total"`+ Stages []stageCount `json:"stages"`+ } `json:"observed"`+ }+ _ = json.Unmarshal(receipts[i].Payload, &payload)+ facts["total"] = payload.Observed.Total+ if !payload.Observed.All && payload.Observed.Stage != nil {+ facts["stage"] = *payload.Observed.Stage+ for _, sc := range payload.Observed.Stages {+ if sc.Stage == *payload.Observed.Stage {+ facts["total"] = sc.Total+ }+ }+ }+ break+ }+ return facts+}++// dispatchSystem evaluates a system rule and wakes, notifies or records its+// outcome. It mirrors dispatch: the same lock order, receipts, runaway+// protection and timeline entries.+func (s *IssueWakeupService) dispatchSystem(ctx context.Context, prev db.IssueWakeup) error {+ ctx, cancel := context.WithTimeout(ctx, 2*time.Second)+ defer cancel()+ // Resolve the target and optional credentials before taking locks, then+ // confirm the target under them.+ snapshot, err := s.Tasks.Queries.GetIssue(ctx, prev.IssueID)+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return err+ }+ target, err := resolveWakeTarget(ctx, s.Tasks.Queries, snapshot)+ if err != nil {+ return err+ }+ headSHA := s.Tasks.ResolveIssueReviewSHAParam(ctx, prev.IssueID)+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)+ if _, err = tx.Exec(ctx, "SET LOCAL lock_timeout = '50ms'"); err != nil {+ return err+ }+ q := s.Tasks.Queries.WithTx(tx)+ if target.Agent.ID.Valid {+ var fenced bool+ if err = tx.QueryRow(ctx, "SELECT lock_task_owner_rows($1,$2,$3)", target.Agent.ID, prev.IssueID, target.Agent.RuntimeID).Scan(&fenced); err != nil {+ return err+ }+ if !fenced {+ return pgx.ErrNoRows+ }+ } else if _, err = q.LockWorkspaceForChatSessionCreate(ctx, prev.WorkspaceID); err != nil {+ return err+ }+ issue, err := q.LockWakeupIssue(ctx, prev.IssueID)+ if errors.Is(err, pgx.ErrNoRows) {+ return qCleanupMissingWakeup(ctx, tx, prev.ID)+ }+ if err != nil {+ return err+ }+ w, err := q.LockIssueWakeup(ctx, prev.ID)+ if err != nil {+ return err+ }+ if w.Revision != prev.Revision {+ return tx.Commit(ctx)+ }+ current, err := resolveWakeTarget(ctx, q, issue)+ if err != nil {+ return err+ }+ if current.key() != target.key() {+ // The assignee changed after the read above; the pending receipts+ // stay for the next pass.+ return tx.Commit(ctx)+ }+ if _, err = tx.Exec(ctx, "UPDATE issue_wakeup_receipt SET processed_at=now() WHERE wakeup_id=$1 AND revision<>$2 AND processed_at IS NULL", w.ID, w.Revision); err != nil {+ return err+ }+ active, err := wakeupIssueActive(ctx, q, issue)+ if err != nil {+ return err+ }+ // A closed parent or a rule that is off or paused keeps its state; a+ // system rule is never disabled by the platform for a closed issue.+ if !active || !w.Enabled {+ if err = q.DiscardWakeupReceipts(ctx, w.ID); err != nil {+ return err+ }+ return tx.Commit(ctx)+ }+ // A parked parent holds: nothing fires and nothing is marked as seen, so+ // a stage that closed meanwhile wakes the assignee once it leaves backlog.+ if issuestatus.Effective(ctx, q, issue.WorkspaceID, issue.Status) == "backlog" {+ if _, _, err = consumeConditionHints(ctx, tx, w.ID); err != nil {+ return err+ }+ return tx.Commit(ctx)+ }+ var now time.Time+ if err = tx.QueryRow(ctx, "SELECT now()").Scan(&now); err != nil {+ return err+ }+ _, causes, err := consumeConditionHints(ctx, tx, w.ID)+ if err != nil {+ return err+ }+ met, fingerprint, observed, err := evaluateCondition(ctx, tx, q, w)+ if err != nil {+ return err+ }+ state := w.ConditionState+ switch {+ case met && fingerprint != state:+ if err = recordConditionMet(ctx, q, w, observed, causes, now); err != nil {+ return err+ }+ state = fingerprint+ case !met:+ state = ""+ }+ if err = q.SetWakeupConditionState(ctx, db.SetWakeupConditionStateParams{ID: w.ID, ConditionState: state}); err != nil {+ return err+ }+ receipts, err := q.ListPendingWakeupReceipts(ctx, db.ListPendingWakeupReceiptsParams{WakeupID: w.ID, Revision: w.Revision})+ if err != nil {+ return err+ }+ var activities []wakeupActivity+ var inbox []db.InboxItem+ note := func(action string, details map[string]any) error {+ a, err := recordWakeupActivity(ctx, q, w, action, "system", pgtype.UUID{}, details)+ if err == nil {+ activities = append(activities, a)+ }+ return err+ }+ commit := func() error {+ if err := tx.Commit(ctx); err != nil {+ return err+ }+ s.publishWakeupActivities(activities...)+ for _, item := range inbox {+ s.publishSystemInbox(item, issue.Status)+ }+ return nil+ }+ // Facts a claimed run took along count once that run starts; until then+ // they wait with it, and they come back if it ends without starting.+ receipts, _, taken, err := takenReceipts(ctx, q, receipts)+ if err != nil {+ return err+ }+ for _, run := range taken {+ if err = q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: receiptIDs(run.receipts), TaskID: run.task.ID}); err != nil {+ return err+ }+ if err = q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: true, LastTaskID: run.task.ID}); err != nil {+ return err+ }+ if err = q.CountWakeupFires(ctx, w.ID); err != nil {+ return err+ }+ facts := childDoneFacts(run.receipts)+ facts["target_type"], facts["target_id"] = "agent", util.UUIDToString(run.task.AgentID)+ if current.Agent.ID == run.task.AgentID {+ facts["target_type"], facts["target_id"] = current.Type, util.UUIDToString(current.ID)+ }+ facts["outcome"], facts["task_id"] = wakeupOutcomeMerged, util.UUIDToString(run.task.ID)+ if err = note(wakeupActivityTriggered, facts); err != nil {+ return err+ }+ }+ if len(receipts) == 0 {+ return commit()+ }+ ids := receiptIDs(receipts)+ facts := childDoneFacts(receipts)+ if current.Type != "none" {+ facts["target_type"], facts["target_id"] = current.Type, util.UUIDToString(current.ID)+ }+ // Recorded without a run: nobody to wake, a member to notify, or an+ // assignee whose agent cannot run.+ if current.Type == "member" || !current.Agent.ID.Valid {+ facts["outcome"] = "none"+ if current.Type == "member" {+ facts["outcome"] = "notified"+ details, _ := json.Marshal(facts)+ item, err := q.CreateInboxItem(ctx, db.CreateInboxItemParams{+ ID: dbid.NewV7(), WorkspaceID: issue.WorkspaceID, RecipientType: "member", RecipientID: current.ID,+ Type: "children_done", Severity: "info", IssueID: issue.ID, Title: issue.Title,+ ActorType: pgtype.Text{String: "system", Valid: true}, Details: details,+ })+ if err != nil {+ return err+ }+ inbox = append(inbox, item)+ }+ if err = q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: ids}); err != nil {+ return err+ }+ if err = note(wakeupActivityTriggered, facts); err != nil {+ return err+ }+ return commit()+ }+ agent := current.Agent+ task, err := q.FindPendingWakeupTask(ctx, util.UUIDToString(w.ID))+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return err+ }+ taskExists := err == nil+ if taskExists && task.Status == "dispatched" {+ // A claimed prompt is immutable; the new facts wait for the next run.+ return tx.Commit(ctx)+ }+ instruction := w+ if ws, e := q.GetWorkspace(ctx, issue.WorkspaceID); e == nil {+ instruction.Instruction = ChildDoneInstruction(w.Instruction, ws.Settings)+ } else {+ instruction.Instruction = ChildDoneInstruction(w.Instruction, nil)+ }+ noteText, evidence := mergeWakeupEvidence(instruction, task, receipts)+ if taskExists {+ task, err = q.ReplaceWakeupEvidence(ctx, db.ReplaceWakeupEvidenceParams{ID: task.ID, HandoffNote: pgtype.Text{String: noteText, Valid: true}, WakeupEvidence: evidence})+ if err != nil {+ return err+ }+ if err = q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: ids, TaskID: task.ID}); err != nil {+ return err+ }+ return commit()+ }+ // The agent's own unfinished run on the parent closed the stage: no second+ // run. A run of the agent waiting to start there takes the facts along+ // when it is claimed (JoinWaitingWakeups).+ self, err := acknowledgedBySelf(ctx, q, w, agent.ID, issue.ID, receipts)+ if err != nil {+ return err+ }+ if self {+ facts["outcome"] = wakeupOutcomeAcknowledged+ if err = q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: ids}); err != nil {+ return err+ }+ if err = note(wakeupActivityTriggered, facts); err != nil {+ return err+ }+ return commit()+ }+ attr, err := s.childDoneRunAs(ctx, issue, agent)+ if err != nil {+ return err+ }+ waiting, err := hasWaitingRun(ctx, q, issue.ID, agent.ID, attr.UserID)+ if err != nil {+ return err+ }+ if waiting {+ return commit()+ }+ recent, err := q.CountRecentWakeupTasks(ctx, db.CountRecentWakeupTasksParams{WakeupID: util.UUIDToString(w.ID), IssueID: w.IssueID, Since: pgtype.Timestamptz{Time: now.Add(-time.Hour), Valid: true}})+ if err != nil {+ return err+ }+ if recent >= wakeupHourlyRunLimit {+ if err = q.PauseIssueWakeup(ctx, db.PauseIssueWakeupParams{ID: w.ID, PausedReason: pgtype.Text{String: wakeupPausedRate, Valid: true}, BlockRuns: true}); err != nil {+ return err+ }+ if err = q.DiscardWakeupReceipts(ctx, w.ID); err != nil {+ return err+ }+ if err = note(wakeupActivityPaused, map[string]any{"rule": SystemRuleChildDone, "reason": wakeupPausedRate, "limit": wakeupHourlyRunLimit}); err != nil {+ return err+ }+ return commit()+ }+ if err = guardIssueNotInTriage(ctx, q, issue.ID, OriginDerived); err != nil {+ return err+ }+ overlay := s.Tasks.buildRuntimeMCPOverlay(ctx, attr.UserID, agent)+ source, delegatedFrom, _, _ := attributionCreateParams(attr)+ contextJSON, _ := json.Marshal(map[string]any{"wakeup_id": util.UUIDToString(w.ID), "wakeup_revision": w.Revision, "wakeup_evidence": evidence, "wakeup_system": SystemRuleChildDone})+ task, err = q.CreateWakeupTask(ctx, db.CreateWakeupTaskParams{+ ID: dbid.NewV7(), AgentID: agent.ID, RuntimeID: agent.RuntimeID, IssueID: issue.ID, Priority: priorityToInt(issue.Priority),+ TriggerSummary: pgtype.Text{String: "Wakeup: sub-issues closed", Valid: true}, HandoffNote: pgtype.Text{String: noteText, Valid: true},+ IsLeaderTask: pgtype.Bool{Bool: current.Type == "squad", Valid: current.Type == "squad"}, SquadID: current.SquadID,+ OriginatorUserID: attr.UserID, AccountableUserID: attr.AccountableUserID, OriginatorSource: source, DelegatedFromTaskID: delegatedFrom,+ RuleVersionID: attr.RuleVersionID, TriggerEvidenceKind: pgtype.Text{String: "issue_wakeup", Valid: true}, TriggerEvidenceRefID: w.ID,+ HeadSha: headSHA, WakeupContext: contextJSON, RuntimeMcpOverlay: overlay.Overlay, RuntimeConnectedApps: overlay.ConnectedApps,+ })+ if err != nil {+ return err+ }+ if err = q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: ids, TaskID: task.ID}); err != nil {+ return err+ }+ if err = q.AdvanceIssueWakeup(ctx, db.AdvanceIssueWakeupParams{ID: w.ID, Enabled: true, LastTaskID: task.ID}); err != nil {+ return err+ }+ if err = q.CountWakeupFires(ctx, w.ID); err != nil {+ return err+ }+ facts["outcome"], facts["task_id"] = "woke", util.UUIDToString(task.ID)+ if err = note(wakeupActivityTriggered, facts); err != nil {+ return err+ }+ if err = commit(); err != nil {+ return err+ }+ s.Tasks.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)+ s.Tasks.NotifyTaskEnqueued(ctx, task)+ return nil+}++func (s *IssueWakeupService) publishSystemInbox(item db.InboxItem, issueStatus string) {+ if s.Tasks == nil || s.Tasks.Bus == nil {+ return+ }+ s.Tasks.Bus.Publish(events.Event{+ Type: protocol.EventInboxNew, WorkspaceID: util.UUIDToString(item.WorkspaceID), ActorType: "system",+ Payload: map[string]any{"item": map[string]any{+ "id": util.UUIDToString(item.ID), "workspace_id": util.UUIDToString(item.WorkspaceID),+ "recipient_type": item.RecipientType, "recipient_id": util.UUIDToString(item.RecipientID),+ "type": item.Type, "severity": item.Severity, "issue_id": util.UUIDToPtr(item.IssueID),+ "title": item.Title, "body": util.TextToPtr(item.Body), "read": item.Read, "archived": item.Archived,+ "created_at": util.TimestampToString(item.CreatedAt), "actor_type": util.TextToPtr(item.ActorType),+ "actor_id": util.UUIDToPtr(item.ActorID), "details": json.RawMessage(item.Details), "issue_status": issueStatus,+ }},+ })+}++// SystemWakeupInput is a person's change to a system rule on one issue.+// Omitted fields keep their value.+type SystemWakeupInput struct {+ Enabled *bool `json:"enabled"`+ Instruction *string `json:"instruction"`+}++// UpdateChildDoneRule applies a person's change on one issue. From then on+// the rule no longer follows the workspace default. Turning it off withdraws+// runs that have not started.+func (s *IssueWakeupService) UpdateChildDoneRule(ctx context.Context, issueID pgtype.UUID, in SystemWakeupInput) (db.IssueWakeup, error) {+ var out db.IssueWakeup+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return out, err+ }+ defer tx.Rollback(ctx)+ q := s.Tasks.Queries.WithTx(tx)+ issue, err := q.LockWakeupIssue(ctx, issueID)+ if err != nil {+ return out, err+ }+ rule, err := EnsureChildDoneRule(ctx, tx, q, issue)+ if err != nil {+ return out, err+ }+ if rule, err = q.LockIssueWakeup(ctx, rule.ID); err != nil {+ return out, err+ }+ enabled, instruction := rule.Enabled, rule.Instruction+ if in.Enabled != nil {+ enabled = *in.Enabled+ }+ if in.Instruction != nil {+ instruction = strings.TrimSpace(*in.Instruction)+ }+ if len(instruction) > MaxSystemWakeupInstruction {+ return out, fmt.Errorf("%w: instruction must be at most %d bytes", ErrWakeupInput, MaxSystemWakeupInstruction)+ }+ if out, err = q.CustomizeSystemWakeup(ctx, db.CustomizeSystemWakeupParams{ID: rule.ID, Enabled: enabled, Instruction: instruction}); err != nil {+ return out, err+ }+ if enabled && !rule.Enabled {+ if err = baselineChildDone(ctx, tx, q, out); err != nil {+ return out, err+ }+ }+ var cancelled []db.AgentTaskQueue+ if !enabled {+ if err = q.DiscardWakeupReceipts(ctx, rule.ID); err != nil {+ return out, err+ }+ if cancelled, err = q.CancelUnstartedWakeupTasks(ctx, util.UUIDToString(rule.ID)); err != nil {+ return out, err+ }+ }+ if err = tx.Commit(ctx); err != nil {+ return out, err+ }+ for _, task := range cancelled {+ s.Tasks.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)+ }+ return out, nil+}++// SetChildDoneDefault stores the rule's workspace default and applies it to+// every rule nobody customized. It returns how many rules changed.+func (s *IssueWakeupService) SetChildDoneDefault(ctx context.Context, workspaceID pgtype.UUID, enabled *bool, instruction *string) (int64, error) {+ patch := map[string]any{}+ if enabled != nil {+ patch[WorkspaceSettingChildDone] = *enabled+ }+ if instruction != nil {+ text := strings.TrimSpace(*instruction)+ if len(text) > MaxSystemWakeupInstruction {+ return 0, fmt.Errorf("%w: instruction must be at most %d bytes", ErrWakeupInput, MaxSystemWakeupInstruction)+ }+ patch[WorkspaceSettingChildDoneInstruction] = text+ }+ if len(patch) == 0 {+ return 0, nil+ }+ raw, _ := json.Marshal(patch)+ tx, err := s.Tasks.TxStarter.Begin(ctx)+ if err != nil {+ return 0, err+ }+ defer tx.Rollback(ctx)+ q := s.Tasks.Queries.WithTx(tx)+ if err = q.MergeWorkspaceSettings(ctx, db.MergeWorkspaceSettingsParams{ID: workspaceID, Patch: raw}); err != nil {+ return 0, err+ }+ var changed []db.IssueWakeup+ if enabled != nil {+ if changed, err = q.ApplySystemWakeupDefault(ctx, db.ApplySystemWakeupDefaultParams{WorkspaceID: workspaceID, SystemRule: systemRuleText(SystemRuleChildDone), Enabled: *enabled}); err != nil {+ return 0, err+ }+ for _, rule := range changed {+ if *enabled {+ if err = baselineChildDone(ctx, tx, q, rule); err != nil {+ return 0, err+ }+ continue+ }+ if err = q.DiscardWakeupReceipts(ctx, rule.ID); err != nil {+ return 0, err+ }+ }+ }+ return int64(len(changed)), tx.Commit(ctx)+}diff --git a/server/internal/service/issue_wakeup_system_test.go b/server/internal/service/issue_wakeup_system_test.gonew file mode 100644index 0000000000..2d4136104f--- /dev/null+++ b/server/internal/service/issue_wakeup_system_test.go@@ -0,0 +1,90 @@+package service++import (+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+)++func sub(stage int32, closed, cancelled bool) subIssue {+ s := subIssue{Closed: closed, Cancelled: cancelled}+ if stage > 0 {+ s.Stage = pgtype.Int4{Int32: stage, Valid: true}+ }+ return s+}++// The system rule's reading: a stage closing while a later one waits, then+// every sub-issue closing. People's children_done conditions keep theirs.+func TestStageProgress(t *testing.T) {+ cases := []struct {+ name string+ children []subIssue+ met bool+ fingerprint string+ next int32+ }{+ {"no sub-issues", nil, false, "", 0},+ {"unstaged, one open", []subIssue{sub(0, true, false), sub(0, false, false)}, false, "", 0},+ {"unstaged, all closed", []subIssue{sub(0, true, false), sub(0, true, true)}, true, "all", 0},+ {"stage 1 closed, stage 2 waits", []subIssue{sub(1, true, false), sub(1, true, true), sub(2, false, false)}, true, "stage:1", 2},+ {"two stages closed, stage 3 waits", []subIssue{sub(1, true, false), sub(2, true, false), sub(3, false, false)}, true, "stage:2", 3},+ {"a later stage closed first", []subIssue{sub(1, false, false), sub(2, true, false)}, false, "", 0},+ {"last stage closed, unstaged open", []subIssue{sub(1, true, false), sub(2, true, false), sub(0, false, false)}, false, "", 0},+ {"everything closed", []subIssue{sub(1, true, false), sub(2, true, true), sub(0, true, false)}, true, "all", 0},+ {"stage waits on unstaged-free set", []subIssue{sub(1, false, false), sub(0, true, false)}, false, "", 0},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ met, fingerprint, observed := stageProgress(tc.children)+ if met != tc.met || fingerprint != tc.fingerprint {+ t.Fatalf("stageProgress = %v %q, want %v %q (%v)", met, fingerprint, tc.met, tc.fingerprint, observed)+ }+ if tc.next != 0 && observed["next_stage"] != tc.next {+ t.Fatalf("next_stage = %v, want %d", observed["next_stage"], tc.next)+ }+ })+ }+}++func TestStageProgressCountsCancellations(t *testing.T) {+ _, _, observed := stageProgress([]subIssue{sub(1, true, true), sub(1, true, false), sub(2, false, false)})+ stages := observed["stages"].([]stageCount)+ if observed["cancelled"] != 1 || len(stages) != 2 || stages[0] != (stageCount{Stage: 1, Total: 2, Closed: 2, Cancelled: 1}) {+ t.Fatalf("observed = %+v", observed)+ }+}++func TestChildrenDoneStageCondition(t *testing.T) {+ stage := int32(1)+ children := []subIssue{sub(1, true, false), sub(2, false, false), sub(0, false, false)}+ if met, _, _ := childrenDone(WakeupCondition{Type: "children_done", Stage: &stage}, children); !met {+ t.Fatal("stage 1 closed but the stage condition did not hold")+ }+ if met, _, _ := childrenDone(WakeupCondition{Type: "children_done"}, children); met {+ t.Fatal("the all-children condition held while sub-issues were open")+ }+ missing := int32(3)+ if met, _, _ := childrenDone(WakeupCondition{Type: "children_done", Stage: &missing}, children); met {+ t.Fatal("a stage without sub-issues held")+ }+}++func TestChildDoneInstructionPrecedence(t *testing.T) {+ settings := []byte(`{"system_wakeup_child_done":false,"system_wakeup_child_done_instruction":" Workspace way "}`)+ if enabled, instruction := SystemWakeupDefault(settings); enabled || instruction != "Workspace way" {+ t.Fatalf("default = %v %q", enabled, instruction)+ }+ if got := ChildDoneInstruction(" Issue way ", settings); got != "Issue way" {+ t.Fatalf("issue instruction = %q", got)+ }+ if got := ChildDoneInstruction("", settings); got != "Workspace way" {+ t.Fatalf("workspace instruction = %q", got)+ }+ if got := ChildDoneInstruction("", []byte(`{}`)); got != ChildDoneDefaultInstruction {+ t.Fatalf("built-in instruction = %q", got)+ }+ if enabled, _ := SystemWakeupDefault([]byte(`not json`)); !enabled {+ t.Fatal("unreadable settings must keep the rule on")+ }+}diff --git a/server/internal/service/issue_wakeup_test.go b/server/internal/service/issue_wakeup_test.goindex 3216a6bf89..6d250c5687 100644--- a/server/internal/service/issue_wakeup_test.go+++ b/server/internal/service/issue_wakeup_test.go@@ -94,39 +94,61 @@ func TestIssueWakeupEventAtomicOnceAndIndependentInputs(t *testing.T) {t.Fatalf("rollback left %d receipts", n)}comment := f.Comment(t, util.UUIDToString(issue), "source")- // Existing assign task must coexist and must not absorb the wakeup.- ordinary := f.Task(t, agent, testutil.Cols{"issue_id": issue, "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ // The agent's assignment run, which runs as the rule's creator, is still+ // waiting to start: the wakeup keeps its input for it instead of queuing a+ // second run behind it, and hands it over when the run is claimed.+ ordinary := wakeWaitingRun(t, f, issue, agent, f.UserID)wakeDispatch(t, s, w)wakeDispatch(t, s, w)+ if n := wakeRuns(t, f, w.ID); n != 0 {+ t.Fatalf("the wakeup queued %d runs of its own", n)+ }got, e := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})if e != nil {t.Fatal(e)}- if got.Enabled || !got.LastTaskID.Valid {- t.Fatalf("not consumed: %+v", got)+ if !got.Enabled || got.LastTaskID.Valid {+ t.Fatalf("the once rule was used up before its input was handed over: %+v", got)+ }+ if notes := wakeClaim(t, f, s, ordinary); !strings.Contains(notes, comment) || !strings.Contains(notes, "Review latest changes") {+ t.Fatalf("the claimed run lacks the joined input: %q", notes)+ }+ // The input is the run's once it starts; until then the rule keeps it.+ wakeDispatch(t, s, w)+ if got, e = f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID}); e != nil || !got.Enabled || got.FireCount != 0 {+ t.Fatalf("before the run started: %+v %v", got, e)}- task, e := f.q.GetAgentTask(ctx, got.LastTaskID)+ wakeStart(t, f, ordinary)+ wakeDispatch(t, s, w)+ got, e = f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})if e != nil {t.Fatal(e)}- if !strings.Contains(task.HandoffNote.String, comment) || task.OriginatorUserID != parseTestUUID(t, f.UserID) {- t.Fatal("missing input or principal")+ if got.Enabled || util.UUIDToString(got.LastTaskID) != ordinary || got.FireCount != 1 {+ t.Fatalf("after the run started: enabled=%t last_task=%s fire_count=%d", got.Enabled, util.UUIDToString(got.LastTaskID), got.FireCount)}- if n := f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID)); n != 1 {- t.Fatalf("duplicate runs %d", n)+ if n := wakeRuns(t, f, w.ID); n != 0 {+ t.Fatalf("the wakeup also queued %d runs of its own", n)}- _, e = s.Disable(ctx, issue, w.ID, parseTestUUID(t, f.UserID))- if e != nil {- t.Fatal(e)+}++// Without a run waiting to start, the wakeup starts its own run under the+// rule creator's authority.+func TestIssueWakeupStartsItsOwnRunWhenNothingWaits(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Review latest changes"})+ comment := f.Comment(t, util.UUIDToString(issue), "source")+ wakeDispatch(t, s, w)+ got, err := f.q.GetIssueWakeup(context.Background(), db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})+ if err != nil {+ t.Fatal(err)}- var status string- f.QueryRow(t, "SELECT status FROM agent_task_queue WHERE id=$1", ordinary).Scan(&status)- if status != "queued" {- t.Fatal("disable changed assign task")+ task, err := f.q.GetAgentTask(context.Background(), got.LastTaskID)+ if err != nil {+ t.Fatal(err)}- f.QueryRow(t, "SELECT status FROM agent_task_queue WHERE id=$1", task.ID).Scan(&status)- if status != "cancelled" {- t.Fatal("wakeup not withdrawn")+ if !strings.Contains(task.HandoffNote.String, comment) || task.OriginatorUserID != parseTestUUID(t, f.UserID) {+ t.Fatal("missing input or principal")}}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 914e757ae5..3b3e0e9c85 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -525,9 +525,9 @@ func (s *TaskService) attributionForIssueTask(ctx context.Context, issue db.Issureturn attribution.Result{Source: attribution.SourceUnattributed}}// A member/agent trigger comment resolves the human (direct_human / delegation- // / comment_source). A SYSTEM-authored comment — today the Stage-completion- // child-done comment (issue_child_done.go), which wakes the parent assignee- // and threads no actor — carries no human and is not part of any delegation+ // / comment_source). A SYSTEM-authored comment — historically the+ // Stage-completion child-done comment, which woke the parent assignee+ // and threaded no actor — carries no human and is not part of any delegation// chain. Classifying it would degrade straight to owner_fallback (the agent's// own owner), which is wrong for a Stage cascade: the woken run should be// accountable to whoever caused the PARENT issue to exist. So for a system@@ -4507,7 +4507,9 @@ func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgtAuthorID: task.AgentID,Since: task.StartedAt,})- if !suppressNoActionComment && !agentCommented {+ // A scheduled wakeup check that found nothing new ends with a check-in+ // instead of a comment (see IssueWakeupService.CheckIn).+ if !suppressNoActionComment && !agentCommented && !HasWakeupCheckin(task) {var payload protocol.TaskCompletedPayloadif err := json.Unmarshal(result, &payload); err == nil {if payload.Output != "" {diff --git a/server/migrations/553_wakeup_expiry.down.sql b/server/migrations/553_wakeup_expiry.down.sqlnew file mode 100644index 0000000000..16cddd6221--- /dev/null+++ b/server/migrations/553_wakeup_expiry.down.sql@@ -0,0 +1,5 @@+ALTER TABLE issue_wakeup+ DROP COLUMN IF EXISTS timed_out_at,+ DROP COLUMN IF EXISTS on_timeout,+ DROP COLUMN IF EXISTS expiry_seconds,+ DROP COLUMN IF EXISTS expires_at;diff --git a/server/migrations/553_wakeup_expiry.up.sql b/server/migrations/553_wakeup_expiry.up.sqlnew file mode 100644index 0000000000..64b8358f37--- /dev/null+++ b/server/migrations/553_wakeup_expiry.up.sql@@ -0,0 +1,11 @@+-- Every wakeup can carry an end: an absolute deadline, or a relative wait that+-- restarts from "now" whenever the rule is (re)enabled. on_timeout decides+-- whether reaching the deadline wakes the target once to handle it or simply+-- ends the rule. timed_out_at records that the deadline, not a trigger or a+-- person, ended the rule. All columns are nullable: existing rules keep their+-- previous open-ended behavior.+ALTER TABLE issue_wakeup+ ADD COLUMN IF NOT EXISTS expires_at timestamptz,+ ADD COLUMN IF NOT EXISTS expiry_seconds bigint,+ ADD COLUMN IF NOT EXISTS on_timeout text CHECK (on_timeout IN ('wake','end')),+ ADD COLUMN IF NOT EXISTS timed_out_at timestamptz;diff --git a/server/migrations/554_wakeup_expiry_index.down.sql b/server/migrations/554_wakeup_expiry_index.down.sqlnew file mode 100644index 0000000000..eaed3817d6--- /dev/null+++ b/server/migrations/554_wakeup_expiry_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_expiry_idx;diff --git a/server/migrations/554_wakeup_expiry_index.up.sql b/server/migrations/554_wakeup_expiry_index.up.sqlnew file mode 100644index 0000000000..3c7ff00fe2--- /dev/null+++ b/server/migrations/554_wakeup_expiry_index.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS issue_wakeup_expiry_idx ON issue_wakeup(expires_at) WHERE enabled AND expires_at IS NOT NULL;diff --git a/server/migrations/555_wakeup_system_rule.down.sql b/server/migrations/555_wakeup_system_rule.down.sqlnew file mode 100644index 0000000000..d227022895--- /dev/null+++ b/server/migrations/555_wakeup_system_rule.down.sql@@ -0,0 +1,22 @@+DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE system_rule IS NOT NULL);+DELETE FROM issue_wakeup WHERE system_rule IS NOT NULL;++CREATE OR REPLACE FUNCTION guard_issue_wakeup_capacity() RETURNS trigger LANGUAGE plpgsql AS $$+BEGIN+ IF NOT NEW.enabled THEN RETURN NEW; END IF;+ IF TG_OP='UPDATE' AND OLD.enabled AND OLD.issue_id=NEW.issue_id AND OLD.workspace_id=NEW.workspace_id THEN RETURN NEW; END IF;+ PERFORM pg_advisory_xact_lock(hashtextextended('issue-wakeup-capacity:'||NEW.workspace_id::text,0));+ IF (SELECT count(*) FROM (SELECT 1 FROM issue_wakeup WHERE workspace_id=NEW.workspace_id AND issue_id=NEW.issue_id AND enabled AND id<>NEW.id LIMIT 32) slots)>=32 THEN+ RAISE EXCEPTION 'An issue can have at most 32 enabled wakeups' USING ERRCODE='23514',CONSTRAINT='issue_wakeup_active_limit';+ END IF;+ IF (SELECT count(*) FROM (SELECT 1 FROM issue_wakeup WHERE workspace_id=NEW.workspace_id AND enabled AND id<>NEW.id LIMIT 1000) slots)>=1000 THEN+ RAISE EXCEPTION 'A workspace can have at most 1000 enabled wakeups' USING ERRCODE='23514',CONSTRAINT='issue_wakeup_active_limit';+ END IF;+ RETURN NEW;+END $$;++ALTER TABLE issue_wakeup+ ALTER COLUMN created_by SET NOT NULL,+ ALTER COLUMN agent_id SET NOT NULL,+ DROP COLUMN IF EXISTS customized_at,+ DROP COLUMN IF EXISTS system_rule;diff --git a/server/migrations/555_wakeup_system_rule.up.sql b/server/migrations/555_wakeup_system_rule.up.sqlnew file mode 100644index 0000000000..6f84961594--- /dev/null+++ b/server/migrations/555_wakeup_system_rule.up.sql@@ -0,0 +1,28 @@+-- Platform-owned wakeup rules are ordinary issue_wakeup rows. system_rule names+-- the rule ('child_done': wake the issue's assignee when a stage of its+-- sub-issues finishes). Such a row has no fixed agent or creator: it targets+-- the issue's assignee at the moment it fires, so agent_id and created_by stay+-- NULL for it. customized_at records that a person changed the rule on this+-- issue; until then it follows the workspace default. All changes are+-- additive for existing rows.+ALTER TABLE issue_wakeup+ ADD COLUMN IF NOT EXISTS system_rule text CHECK (system_rule IN ('child_done')),+ ADD COLUMN IF NOT EXISTS customized_at timestamptz,+ ALTER COLUMN agent_id DROP NOT NULL,+ ALTER COLUMN created_by DROP NOT NULL;++-- System rules exist once per parent issue and do not use the per-issue or+-- per-workspace capacity people and agents share.+CREATE OR REPLACE FUNCTION guard_issue_wakeup_capacity() RETURNS trigger LANGUAGE plpgsql AS $$+BEGIN+ IF NOT NEW.enabled OR NEW.system_rule IS NOT NULL THEN RETURN NEW; END IF;+ IF TG_OP='UPDATE' AND OLD.enabled AND OLD.issue_id=NEW.issue_id AND OLD.workspace_id=NEW.workspace_id THEN RETURN NEW; END IF;+ PERFORM pg_advisory_xact_lock(hashtextextended('issue-wakeup-capacity:'||NEW.workspace_id::text,0));+ IF (SELECT count(*) FROM (SELECT 1 FROM issue_wakeup WHERE workspace_id=NEW.workspace_id AND issue_id=NEW.issue_id AND enabled AND system_rule IS NULL AND id<>NEW.id LIMIT 32) slots)>=32 THEN+ RAISE EXCEPTION 'An issue can have at most 32 enabled wakeups' USING ERRCODE='23514',CONSTRAINT='issue_wakeup_active_limit';+ END IF;+ IF (SELECT count(*) FROM (SELECT 1 FROM issue_wakeup WHERE workspace_id=NEW.workspace_id AND enabled AND system_rule IS NULL AND id<>NEW.id LIMIT 1000) slots)>=1000 THEN+ RAISE EXCEPTION 'A workspace can have at most 1000 enabled wakeups' USING ERRCODE='23514',CONSTRAINT='issue_wakeup_active_limit';+ END IF;+ RETURN NEW;+END $$;diff --git a/server/migrations/556_wakeup_system_rule_index.down.sql b/server/migrations/556_wakeup_system_rule_index.down.sqlnew file mode 100644index 0000000000..f2b279c236--- /dev/null+++ b/server/migrations/556_wakeup_system_rule_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_wakeup_system_rule_idx;diff --git a/server/migrations/556_wakeup_system_rule_index.up.sql b/server/migrations/556_wakeup_system_rule_index.up.sqlnew file mode 100644index 0000000000..7398257d99--- /dev/null+++ b/server/migrations/556_wakeup_system_rule_index.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS issue_wakeup_system_rule_idx ON issue_wakeup(issue_id,system_rule) WHERE system_rule IS NOT NULL;diff --git a/server/migrations/557_wakeup_conditions.down.sql b/server/migrations/557_wakeup_conditions.down.sqlnew file mode 100644index 0000000000..7e110e2f4b--- /dev/null+++ b/server/migrations/557_wakeup_conditions.down.sql@@ -0,0 +1,6 @@+ALTER TABLE issue_wakeup+ DROP COLUMN IF EXISTS paused_reason,+ DROP COLUMN IF EXISTS fire_count,+ DROP COLUMN IF EXISTS max_fires,+ DROP COLUMN IF EXISTS condition_state,+ DROP COLUMN IF EXISTS condition;diff --git a/server/migrations/557_wakeup_conditions.up.sql b/server/migrations/557_wakeup_conditions.up.sqlnew file mode 100644index 0000000000..4f1fbd0566--- /dev/null+++ b/server/migrations/557_wakeup_conditions.up.sql@@ -0,0 +1,18 @@+-- Platform-evaluated conditions and runaway protection for issue wakeups.+--+-- condition holds a structured predicate (a field value, sub-issues finishing,+-- a linked pull request, another issue's status). Such a rule stays+-- kind='event'; the scheduler evaluates it and only wakes the target when the+-- predicate becomes true. condition_state remembers the last satisfied+-- fingerprint so a rule fires on the change, not on every evaluation.+--+-- max_fires/fire_count cap repeating rules; paused_reason records why the+-- platform, not a person, stopped a rule (the cap, a detected loop, or a+-- burst of triggers). All columns are nullable or defaulted: existing rules+-- behave as before.+ALTER TABLE issue_wakeup+ ADD COLUMN IF NOT EXISTS condition jsonb,+ ADD COLUMN IF NOT EXISTS condition_state text NOT NULL DEFAULT '',+ ADD COLUMN IF NOT EXISTS max_fires integer CHECK (max_fires BETWEEN 1 AND 1000),+ ADD COLUMN IF NOT EXISTS fire_count integer NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS paused_reason text CHECK (paused_reason IN ('max_fires','loop','rate'));diff --git a/server/migrations/558_issue_child_event.down.sql b/server/migrations/558_issue_child_event.down.sqlnew file mode 100644index 0000000000..5b0b0eca46--- /dev/null+++ b/server/migrations/558_issue_child_event.down.sql@@ -0,0 +1,4 @@+DROP TRIGGER IF EXISTS issue_child_event_update ON issue;+DROP TRIGGER IF EXISTS issue_child_event_insert ON issue;+DROP FUNCTION IF EXISTS record_issue_child_event();+DROP TABLE IF EXISTS issue_child_event;diff --git a/server/migrations/558_issue_child_event.up.sql b/server/migrations/558_issue_child_event.up.sqlnew file mode 100644index 0000000000..7c84671ff7--- /dev/null+++ b/server/migrations/558_issue_child_event.up.sql@@ -0,0 +1,66 @@+-- Changes to a parent's set of sub-issues, recorded in the writing transaction+-- for every writer (HTTP, batch, PR automation, any future path). They drive+-- the parent's child_done system wakeup and sub-issue conditions: the server+-- processes the rows right after commit and a scheduler sweep retries rows+-- that were not processed. No foreign keys; issue and workspace deletion+-- remove these rows in the application deletion graph.+--+-- kind: closed | reopened (a sub-issue entered or left a closed status,+-- built-in or custom), attached | detached (it joined or left the parent),+-- restaged (its stage changed). source_task_id is the agent run that made the+-- change, when an agent made it, so a rule does not wake that run's agent for+-- what it just did.+CREATE TABLE IF NOT EXISTS issue_child_event (+ id uuid NOT NULL DEFAULT gen_random_uuid(),+ workspace_id uuid NOT NULL,+ parent_id uuid NOT NULL,+ child_id uuid NOT NULL,+ kind text NOT NULL CHECK (kind IN ('closed','reopened','attached','detached','restaged')),+ source_task_id uuid,+ created_at timestamptz NOT NULL DEFAULT clock_timestamp(),+ claimed_at timestamptz,+ processed_at timestamptz+);++CREATE OR REPLACE FUNCTION record_issue_child_event() RETURNS trigger LANGUAGE plpgsql AS $$+DECLARE old_closed boolean; new_closed boolean; source uuid;+BEGIN+ source := NULLIF(current_setting('multica.source_task_id',true),'')::uuid;+ IF TG_OP='INSERT' THEN+ INSERT INTO issue_child_event(workspace_id,parent_id,child_id,kind,source_task_id) VALUES(NEW.workspace_id,NEW.parent_issue_id,NEW.id,'attached',source);+ RETURN NULL;+ END IF;+ IF OLD.parent_issue_id IS DISTINCT FROM NEW.parent_issue_id THEN+ IF OLD.parent_issue_id IS NOT NULL THEN+ INSERT INTO issue_child_event(workspace_id,parent_id,child_id,kind,source_task_id) VALUES(OLD.workspace_id,OLD.parent_issue_id,OLD.id,'detached',source);+ END IF;+ IF NEW.parent_issue_id IS NOT NULL THEN+ INSERT INTO issue_child_event(workspace_id,parent_id,child_id,kind,source_task_id) VALUES(NEW.workspace_id,NEW.parent_issue_id,NEW.id,'attached',source);+ END IF;+ RETURN NULL;+ END IF;+ IF OLD.status IS DISTINCT FROM NEW.status THEN+ new_closed := NEW.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=NEW.workspace_id AND s.key=NEW.status AND s.category IN ('done','closed'));+ old_closed := OLD.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=OLD.workspace_id AND s.key=OLD.status AND s.category IN ('done','closed'));+ IF new_closed AND NOT old_closed THEN+ INSERT INTO issue_child_event(workspace_id,parent_id,child_id,kind,source_task_id) VALUES(NEW.workspace_id,NEW.parent_issue_id,NEW.id,'closed',source);+ ELSIF old_closed AND NOT new_closed THEN+ INSERT INTO issue_child_event(workspace_id,parent_id,child_id,kind,source_task_id) VALUES(NEW.workspace_id,NEW.parent_issue_id,NEW.id,'reopened',source);+ END IF;+ END IF;+ IF OLD.stage IS DISTINCT FROM NEW.stage THEN+ INSERT INTO issue_child_event(workspace_id,parent_id,child_id,kind,source_task_id) VALUES(NEW.workspace_id,NEW.parent_issue_id,NEW.id,'restaged',source);+ END IF;+ RETURN NULL;+END $$;++DROP TRIGGER IF EXISTS issue_child_event_insert ON issue;+CREATE TRIGGER issue_child_event_insert AFTER INSERT ON issue FOR EACH ROW+ WHEN (NEW.parent_issue_id IS NOT NULL)+ EXECUTE FUNCTION record_issue_child_event();++DROP TRIGGER IF EXISTS issue_child_event_update ON issue;+CREATE TRIGGER issue_child_event_update AFTER UPDATE OF status,parent_issue_id,stage ON issue FOR EACH ROW+ WHEN (OLD.parent_issue_id IS DISTINCT FROM NEW.parent_issue_id+ OR (NEW.parent_issue_id IS NOT NULL AND (OLD.status IS DISTINCT FROM NEW.status OR OLD.stage IS DISTINCT FROM NEW.stage)))+ EXECUTE FUNCTION record_issue_child_event();diff --git a/server/migrations/559_issue_child_event_id.down.sql b/server/migrations/559_issue_child_event_id.down.sqlnew file mode 100644index 0000000000..1975b992ff--- /dev/null+++ b/server/migrations/559_issue_child_event_id.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_child_event_id_idx;diff --git a/server/migrations/559_issue_child_event_id.up.sql b/server/migrations/559_issue_child_event_id.up.sqlnew file mode 100644index 0000000000..7031199e99--- /dev/null+++ b/server/migrations/559_issue_child_event_id.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS issue_child_event_id_idx ON issue_child_event(id);diff --git a/server/migrations/560_issue_child_event_pending.down.sql b/server/migrations/560_issue_child_event_pending.down.sqlnew file mode 100644index 0000000000..0859f85a69--- /dev/null+++ b/server/migrations/560_issue_child_event_pending.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_child_event_pending_idx;diff --git a/server/migrations/560_issue_child_event_pending.up.sql b/server/migrations/560_issue_child_event_pending.up.sqlnew file mode 100644index 0000000000..15f80885ed--- /dev/null+++ b/server/migrations/560_issue_child_event_pending.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS issue_child_event_pending_idx ON issue_child_event(parent_id,created_at) WHERE processed_at IS NULL;diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 0f62606346..aa355c849c 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -487,6 +487,9 @@ cleared_wakeup_receipts AS (cleared_wakeups AS (DELETE FROM issue_wakeup WHERE issue_id IN (SELECT target.id FROM target)),+cleared_child_events AS (+ DELETE FROM issue_child_event WHERE parent_id IN (SELECT target.id FROM target) OR child_id IN (SELECT target.id FROM target)+),cleared_task_supplements AS (DELETE FROM task_supplement WHERE issue_id IN (SELECT target.id FROM target)),diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 29f6808ce4..d8dd0c6fa6 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -5,6 +5,7 @@package dbimport (+ "encoding/json""net/netip""github.com/jackc/pgx/v5/pgtype"@@ -827,6 +828,18 @@ type Issue struct {DuplicateOfIssueID pgtype.UUID `json:"duplicate_of_issue_id"`}+type IssueChildEvent struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ParentID pgtype.UUID `json:"parent_id"`+ ChildID pgtype.UUID `json:"child_id"`+ Kind string `json:"kind"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ ClaimedAt pgtype.Timestamptz `json:"claimed_at"`+ ProcessedAt pgtype.Timestamptz `json:"processed_at"`+}+type IssueDependency struct {ID pgtype.UUID `json:"id"`IssueID pgtype.UUID `json:"issue_id"`@@ -1019,6 +1032,17 @@ type IssueWakeup struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`FilterActorType pgtype.Text `json:"filter_actor_type"`FilterActorID pgtype.UUID `json:"filter_actor_id"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+ ExpirySeconds pgtype.Int8 `json:"expiry_seconds"`+ OnTimeout pgtype.Text `json:"on_timeout"`+ TimedOutAt pgtype.Timestamptz `json:"timed_out_at"`+ SystemRule pgtype.Text `json:"system_rule"`+ CustomizedAt pgtype.Timestamptz `json:"customized_at"`+ Condition json.RawMessage `json:"condition"`+ ConditionState string `json:"condition_state"`+ MaxFires pgtype.Int4 `json:"max_fires"`+ FireCount int32 `json:"fire_count"`+ PausedReason pgtype.Text `json:"paused_reason"`}type IssueWakeupReceipt struct {diff --git a/server/pkg/db/generated/system_wakeup.sql.go b/server/pkg/db/generated/system_wakeup.sql.gonew file mode 100644index 0000000000..d069873014--- /dev/null+++ b/server/pkg/db/generated/system_wakeup.sql.go@@ -0,0 +1,556 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: system_wakeup.sql++package db++import (+ "context"+ "encoding/json"++ "github.com/jackc/pgx/v5/pgtype"+)++const applySystemWakeupDefault = `-- name: ApplySystemWakeupDefault :many+UPDATE issue_wakeup SET enabled= $1,updated_at=clock_timestamp()+WHERE workspace_id= $2 AND system_rule= $3 AND customized_at IS NULL+ AND paused_reason IS NULL AND enabled<> $1::bool+RETURNING id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id, expires_at, expiry_seconds, on_timeout, timed_out_at, system_rule, customized_at, condition, condition_state, max_fires, fire_count, paused_reason+`++type ApplySystemWakeupDefaultParams struct {+ Enabled bool `json:"enabled"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ SystemRule pgtype.Text `json:"system_rule"`+}++// The workspace default changed. Rules nobody customized and the platform did+// not pause follow it.+func (q *Queries) ApplySystemWakeupDefault(ctx context.Context, arg ApplySystemWakeupDefaultParams) ([]IssueWakeup, error) {+ rows, err := q.db.Query(ctx, applySystemWakeupDefault, arg.Enabled, arg.WorkspaceID, arg.SystemRule)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueWakeup{}+ for rows.Next() {+ var i IssueWakeup+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const claimChildEvents = `-- name: ClaimChildEvents :many+UPDATE issue_child_event SET claimed_at=clock_timestamp()+WHERE parent_id= $1 AND processed_at IS NULL+ AND (claimed_at IS NULL OR claimed_at < clock_timestamp()-interval '5 minutes')+RETURNING id, workspace_id, parent_id, child_id, kind, source_task_id, created_at, claimed_at, processed_at+`++// Claim a parent's recorded sub-issue changes. A claim that was not finished+// within five minutes (a crashed or failed attempt) can be claimed again.+func (q *Queries) ClaimChildEvents(ctx context.Context, parentID pgtype.UUID) ([]IssueChildEvent, error) {+ rows, err := q.db.Query(ctx, claimChildEvents, parentID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueChildEvent{}+ for rows.Next() {+ var i IssueChildEvent+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ParentID,+ &i.ChildID,+ &i.Kind,+ &i.SourceTaskID,+ &i.CreatedAt,+ &i.ClaimedAt,+ &i.ProcessedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const countCustomizedSystemWakeups = `-- name: CountCustomizedSystemWakeups :one+SELECT count(*) FROM issue_wakeup w JOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id+WHERE w.workspace_id= $1 AND w.system_rule= $2 AND w.customized_at IS NOT NULL+ AND i.status NOT IN ('done','cancelled')+ AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))+`++type CountCustomizedSystemWakeupsParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ SystemRule pgtype.Text `json:"system_rule"`+}++// Open issues whose rule a person changed, for the workspace settings page.+func (q *Queries) CountCustomizedSystemWakeups(ctx context.Context, arg CountCustomizedSystemWakeupsParams) (int64, error) {+ row := q.db.QueryRow(ctx, countCustomizedSystemWakeups, arg.WorkspaceID, arg.SystemRule)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const createSystemWakeup = `-- name: CreateSystemWakeup :one+INSERT INTO issue_wakeup(id,workspace_id,issue_id,instruction,kind,mode,event_types,timezone,condition,condition_state,enabled,system_rule)+VALUES($1,$2,$3,'','event','continuous',$4,'UTC',$5,$6,$7,$8)+ON CONFLICT (issue_id,system_rule) WHERE system_rule IS NOT NULL DO NOTHING+RETURNING id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id, expires_at, expiry_seconds, on_timeout, timed_out_at, system_rule, customized_at, condition, condition_state, max_fires, fire_count, paused_reason+`++type CreateSystemWakeupParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ EventTypes []string `json:"event_types"`+ Condition json.RawMessage `json:"condition"`+ ConditionState string `json:"condition_state"`+ Enabled bool `json:"enabled"`+ SystemRule pgtype.Text `json:"system_rule"`+}++// A platform rule on one issue. Two writers ensuring it at once keep the first+// row; the loser reads it back with GetSystemWakeup.+func (q *Queries) CreateSystemWakeup(ctx context.Context, arg CreateSystemWakeupParams) (IssueWakeup, error) {+ row := q.db.QueryRow(ctx, createSystemWakeup,+ arg.ID,+ arg.WorkspaceID,+ arg.IssueID,+ arg.EventTypes,+ arg.Condition,+ arg.ConditionState,+ arg.Enabled,+ arg.SystemRule,+ )+ var i IssueWakeup+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,+ )+ return i, err+}++const customizeSystemWakeup = `-- name: CustomizeSystemWakeup :one+UPDATE issue_wakeup SET enabled= $1,instruction= $2,customized_at=clock_timestamp(),+ paused_reason=CASE WHEN $1::bool THEN NULL ELSE paused_reason END,+ disabled_at=CASE WHEN $1::bool THEN NULL ELSE disabled_at END,+ updated_at=clock_timestamp()+WHERE id= $3 RETURNING id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id, expires_at, expiry_seconds, on_timeout, timed_out_at, system_rule, customized_at, condition, condition_state, max_fires, fire_count, paused_reason+`++type CustomizeSystemWakeupParams struct {+ Enabled bool `json:"enabled"`+ Instruction string `json:"instruction"`+ ID pgtype.UUID `json:"id"`+}++// A person changed the rule on this issue; it stops following the workspace+// default. Turning it on clears a platform pause.+func (q *Queries) CustomizeSystemWakeup(ctx context.Context, arg CustomizeSystemWakeupParams) (IssueWakeup, error) {+ row := q.db.QueryRow(ctx, customizeSystemWakeup, arg.Enabled, arg.Instruction, arg.ID)+ var i IssueWakeup+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,+ )+ return i, err+}++const deleteProcessedChildEvents = `-- name: DeleteProcessedChildEvents :execrows+WITH batch AS MATERIALIZED (+ SELECT e.id FROM issue_child_event e WHERE e.processed_at < $1+ ORDER BY e.processed_at LIMIT 1000 FOR UPDATE SKIP LOCKED+)+DELETE FROM issue_child_event d USING batch WHERE d.id=batch.id+`++func (q *Queries) DeleteProcessedChildEvents(ctx context.Context, cutoff pgtype.Timestamptz) (int64, error) {+ result, err := q.db.Exec(ctx, deleteProcessedChildEvents, cutoff)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const finishChildEvents = `-- name: FinishChildEvents :exec+UPDATE issue_child_event SET processed_at=clock_timestamp() WHERE id=ANY($1::uuid[])+`++func (q *Queries) FinishChildEvents(ctx context.Context, ids []pgtype.UUID) error {+ _, err := q.db.Exec(ctx, finishChildEvents, ids)+ return err+}++const getSystemWakeup = `-- name: GetSystemWakeup :one+SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id, expires_at, expiry_seconds, on_timeout, timed_out_at, system_rule, customized_at, condition, condition_state, max_fires, fire_count, paused_reason FROM issue_wakeup WHERE issue_id= $1 AND system_rule= $2+`++type GetSystemWakeupParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ SystemRule pgtype.Text `json:"system_rule"`+}++func (q *Queries) GetSystemWakeup(ctx context.Context, arg GetSystemWakeupParams) (IssueWakeup, error) {+ row := q.db.QueryRow(ctx, getSystemWakeup, arg.IssueID, arg.SystemRule)+ var i IssueWakeup+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,+ )+ return i, err+}++const listChildConditionWakeups = `-- name: ListChildConditionWakeups :many+SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id, expires_at, expiry_seconds, on_timeout, timed_out_at, system_rule, customized_at, condition, condition_state, max_fires, fire_count, paused_reason FROM issue_wakeup WHERE issue_id= $1 AND enabled AND condition->>'type'='children_done'+ORDER BY (system_rule IS NOT NULL),id+`++// Enabled rules on a parent whose condition reads its sub-issues.+func (q *Queries) ListChildConditionWakeups(ctx context.Context, issueID pgtype.UUID) ([]IssueWakeup, error) {+ rows, err := q.db.Query(ctx, listChildConditionWakeups, issueID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueWakeup{}+ for rows.Next() {+ var i IssueWakeup+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listParentsWithoutSystemWakeup = `-- name: ListParentsWithoutSystemWakeup :many+SELECT p.id, p.workspace_id, p.title, p.description, p.status, p.priority, p.assignee_type, p.assignee_id, p.creator_type, p.creator_id, p.parent_issue_id, p.acceptance_criteria, p.context_refs, p.position, p.due_date, p.created_at, p.updated_at, p.number, p.project_id, p.origin_type, p.origin_id, p.first_executed_at, p.start_date, p.metadata, p.stage, p.properties, p.revision, p.last_activity_at, p.triage_state, p.duplicate_of_issue_id FROM (SELECT DISTINCT c.parent_issue_id AS id FROM issue c WHERE c.parent_issue_id IS NOT NULL) parents+JOIN issue p ON p.id=parents.id+WHERE NOT EXISTS(SELECT 1 FROM issue_wakeup w WHERE w.issue_id=p.id AND w.system_rule= $1)+ AND p.status NOT IN ('done','cancelled')+ AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=p.workspace_id AND s.key=p.status AND s.category IN ('done','closed'))+LIMIT $2+`++type ListParentsWithoutSystemWakeupParams struct {+ SystemRule pgtype.Text `json:"system_rule"`+ PageLimit int32 `json:"page_limit"`+}++// Open parents that predate their rule, for the one-time backfill.+func (q *Queries) ListParentsWithoutSystemWakeup(ctx context.Context, arg ListParentsWithoutSystemWakeupParams) ([]Issue, error) {+ rows, err := q.db.Query(ctx, listParentsWithoutSystemWakeup, arg.SystemRule, arg.PageLimit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Issue{}+ for rows.Next() {+ var i Issue+ if err := rows.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,+ &i.Stage,+ &i.Properties,+ &i.Revision,+ &i.LastActivityAt,+ &i.TriageState,+ &i.DuplicateOfIssueID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listStaleChildEventParents = `-- name: ListStaleChildEventParents :many+SELECT DISTINCT parent_id FROM issue_child_event+WHERE processed_at IS NULL+ AND ((claimed_at IS NULL AND created_at < clock_timestamp()-interval '30 seconds') OR claimed_at < clock_timestamp()-interval '5 minutes')+LIMIT 50+`++// Parents whose changes were not processed right after their write.+func (q *Queries) ListStaleChildEventParents(ctx context.Context) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listStaleChildEventParents)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var parent_id pgtype.UUID+ if err := rows.Scan(&parent_id); err != nil {+ return nil, err+ }+ items = append(items, parent_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listUnprocessedClosedChildren = `-- name: ListUnprocessedClosedChildren :many+SELECT DISTINCT child_id FROM issue_child_event WHERE parent_id= $1 AND kind='closed' AND processed_at IS NULL+`++// Sub-issues whose closing is recorded but not processed yet.+func (q *Queries) ListUnprocessedClosedChildren(ctx context.Context, parentID pgtype.UUID) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listUnprocessedClosedChildren, parentID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var child_id pgtype.UUID+ if err := rows.Scan(&child_id); err != nil {+ return nil, err+ }+ items = append(items, child_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const mergeWorkspaceSettings = `-- name: MergeWorkspaceSettings :exec+UPDATE workspace SET settings=COALESCE(settings,'{}'::jsonb) || $1::jsonb,updated_at=now() WHERE id= $2+`++type MergeWorkspaceSettingsParams struct {+ Patch []byte `json:"patch"`+ ID pgtype.UUID `json:"id"`+}++func (q *Queries) MergeWorkspaceSettings(ctx context.Context, arg MergeWorkspaceSettingsParams) error {+ _, err := q.db.Exec(ctx, mergeWorkspaceSettings, arg.Patch, arg.ID)+ return err+}diff --git a/server/pkg/db/generated/wakeup.sql.go b/server/pkg/db/generated/wakeup.sql.goindex 6c27008ad4..d9b21632fa 100644--- a/server/pkg/db/generated/wakeup.sql.go+++ b/server/pkg/db/generated/wakeup.sql.go@@ -7,6 +7,7 @@ package dbimport ("context"+ "encoding/json""github.com/jackc/pgx/v5/pgtype")@@ -218,9 +219,55 @@ func (q *Queries) ConsumeWakeupReceipts(ctx context.Context, arg ConsumeWakeupRereturn err}+const countActiveIssueRunsOfAgent = `-- name: CountActiveIssueRunsOfAgent :one+SELECT count(*) FROM agent_task_queue WHERE id=ANY($1::uuid[]) AND agent_id= $2 AND issue_id= $3+ AND status IN ('dispatched','running','waiting_local_directory')+`++type CountActiveIssueRunsOfAgentParams struct {+ Ids []pgtype.UUID `json:"ids"`+ AgentID pgtype.UUID `json:"agent_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++// How many of these runs are the agent's own runs on this issue that have+// not finished: the run that made a change still knows about it.+func (q *Queries) CountActiveIssueRunsOfAgent(ctx context.Context, arg CountActiveIssueRunsOfAgentParams) (int64, error) {+ row := q.db.QueryRow(ctx, countActiveIssueRunsOfAgent, arg.Ids, arg.AgentID, arg.IssueID)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countRecentWakeupTasks = `-- name: CountRecentWakeupTasks :one+SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'= $1::text AND issue_id= $2 AND created_at> $3+`++type CountRecentWakeupTasksParams struct {+ WakeupID string `json:"wakeup_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ Since pgtype.Timestamptz `json:"since"`+}++func (q *Queries) CountRecentWakeupTasks(ctx context.Context, arg CountRecentWakeupTasksParams) (int64, error) {+ row := q.db.QueryRow(ctx, countRecentWakeupTasks, arg.WakeupID, arg.IssueID, arg.Since)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countWakeupFires = `-- name: CountWakeupFires :exec+UPDATE issue_wakeup SET fire_count=fire_count+1 WHERE id= $1+`++func (q *Queries) CountWakeupFires(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, countWakeupFires, id)+ return err+}+const createIssueWakeup = `-- name: CreateIssueWakeup :one-INSERT INTO issue_wakeup(id,workspace_id,issue_id,agent_id,created_by,source_task_id,parent_comment_id,instruction,kind,mode,event_types,filter_agent_id,filter_task_id,filter_actor_type,filter_actor_id,interval_seconds,cron_expression,timezone,next_fire_at)-VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19) RETURNING id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id+INSERT INTO issue_wakeup(id,workspace_id,issue_id,agent_id,created_by,source_task_id,parent_comment_id,instruction,kind,mode,event_types,filter_agent_id,filter_task_id,filter_actor_type,filter_actor_id,interval_seconds,cron_expression,timezone,next_fire_at,expires_at,expiry_seconds,on_timeout,condition,max_fires)+VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24) RETURNING id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id, expires_at, expiry_seconds, on_timeout, timed_out_at, system_rule, customized_at, condition, condition_state, max_fires, fire_count, paused_reason`type CreateIssueWakeupParams struct {@@ -243,6 +290,11 @@ type CreateIssueWakeupParams struct {CronExpression pgtype.Text `json:"cron_expression"`Timezone string `json:"timezone"`NextFireAt pgtype.Timestamptz `json:"next_fire_at"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+ ExpirySeconds pgtype.Int8 `json:"expiry_seconds"`+ OnTimeout pgtype.Text `json:"on_timeout"`+ Condition json.RawMessage `json:"condition"`+ MaxFires pgtype.Int4 `json:"max_fires"`}func (q *Queries) CreateIssueWakeup(ctx context.Context, arg CreateIssueWakeupParams) (IssueWakeup, error) {@@ -266,6 +318,11 @@ func (q *Queries) CreateIssueWakeup(ctx context.Context, arg CreateIssueWakeupPaarg.CronExpression,arg.Timezone,arg.NextFireAt,+ arg.ExpiresAt,+ arg.ExpirySeconds,+ arg.OnTimeout,+ arg.Condition,+ arg.MaxFires,)var i IssueWakeuperr := row.Scan(@@ -295,6 +352,17 @@ func (q *Queries) CreateIssueWakeup(ctx context.Context, arg CreateIssueWakeupPa&i.UpdatedAt,&i.FilterActorType,&i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,)return i, err}@@ -492,12 +560,36 @@ func (q *Queries) DeleteExpiredWakeupReceipts(ctx context.Context, cutoff pgtypereturn result.RowsAffected(), nil}+const deleteIssueWakeup = `-- name: DeleteIssueWakeup :exec+DELETE FROM issue_wakeup WHERE id= $1 AND issue_id= $2+`++type DeleteIssueWakeupParams struct {+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++func (q *Queries) DeleteIssueWakeup(ctx context.Context, arg DeleteIssueWakeupParams) error {+ _, err := q.db.Exec(ctx, deleteIssueWakeup, arg.ID, arg.IssueID)+ return err+}++const deleteIssueWakeupReceipts = `-- name: DeleteIssueWakeupReceipts :exec+DELETE FROM issue_wakeup_receipt WHERE wakeup_id= $1+`++func (q *Queries) DeleteIssueWakeupReceipts(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteIssueWakeupReceipts, id)+ return err+}+const disableIssueWakeups = `-- name: DisableIssueWakeups :execUPDATE issue_wakeup SET enabled=false,disabled_at=clock_timestamp(),updated_at=clock_timestamp()-WHERE issue_id= $1 AND disabled_at IS NULL+WHERE issue_id= $1 AND disabled_at IS NULL AND system_rule IS NULL`// Closing wins over every subscription on the issue; reopening does not rearm.+// A system rule only rests while its issue is closed and resumes on reopen.func (q *Queries) DisableIssueWakeups(ctx context.Context, issueID pgtype.UUID) error {_, err := q.db.Exec(ctx, disableIssueWakeups, issueID)return err@@ -583,8 +675,29 @@ func (q *Queries) FindPendingWakeupTask(ctx context.Context, wakeupID string) (Areturn i, err}+const findWaitingIssueRun = `-- name: FindWaitingIssueRun :one+SELECT id FROM agent_task_queue WHERE issue_id= $1 AND agent_id= $2 AND status='queued'+ AND originator_user_id= $3::uuid ORDER BY created_at,id LIMIT 1+`++type FindWaitingIssueRunParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+}++// A run of the agent on the issue that has not been claimed and runs as this+// person. A rule that fires meanwhile keeps its inputs for that run instead+// of queuing another.+func (q *Queries) FindWaitingIssueRun(ctx context.Context, arg FindWaitingIssueRunParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, findWaitingIssueRun, arg.IssueID, arg.AgentID, arg.OriginatorUserID)+ var id pgtype.UUID+ err := row.Scan(&id)+ return id, err+}+const getIssueWakeup = `-- name: GetIssueWakeup :one-SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id FROM issue_wakeup WHERE id= $1 AND workspace_id= $2+SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id, expires_at, expiry_seconds, on_timeout, timed_out_at, system_rule, customized_at, condition, condition_state, max_fires, fire_count, paused_reason FROM issue_wakeup WHERE id= $1 AND workspace_id= $2`type GetIssueWakeupParams struct {@@ -622,6 +735,17 @@ func (q *Queries) GetIssueWakeup(ctx context.Context, arg GetIssueWakeupParams)&i.UpdatedAt,&i.FilterActorType,&i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,)return i, err}@@ -635,8 +759,15 @@ SELECT w.id,w.workspace_id,w.issue_id,w.agent_id,w.created_by,w.source_task_id,w(CASE WHEN EXISTS(SELECT 1 FROM agent_task_queue ft JOIN agent fa ON fa.id=ft.agent_id AND fa.workspace_id=w.workspace_idWHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY($1::uuid[])) THEN w.filter_task_id END)::uuid AS filter_task_id,w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,w.enabled,w.disabled_at,w.revision,- w.last_task_id,w.last_error,w.created_at,w.updated_at,a.name AS agent_name,source.name AS filter_agent_name,t.status AS last_task_status+ w.last_task_id,w.last_error,w.created_at,w.updated_at,a.name AS agent_name,source.name AS filter_agent_name,t.status AS last_task_status,+ w.expires_at,w.expiry_seconds,w.on_timeout,w.timed_out_at,+ w.condition,w.max_fires,w.fire_count,w.paused_reason,+ (w.source_task_id IS NOT NULL)::bool AS created_by_agent,creator.name AS created_by_name,+ (CASE WHEN creator_agent.id IS NOT NULL THEN creator_agent.id END)::uuid AS source_agent_id,creator_agent.name AS source_agent_nameFROM issue_wakeup w JOIN agent a ON a.id=w.agent_id AND a.workspace_id=w.workspace_id+LEFT JOIN "user" creator ON creator.id=w.created_by+LEFT JOIN agent_task_queue creator_task ON creator_task.id=w.source_task_id+LEFT JOIN agent creator_agent ON creator_agent.id=creator_task.agent_id AND creator_agent.workspace_id=w.workspace_id AND creator_agent.id=ANY($1::uuid[])LEFT JOIN agent actor_agent ON w.filter_actor_type='agent' AND actor_agent.id=w.filter_actor_id AND actor_agent.workspace_id=w.workspace_id AND actor_agent.id=ANY($1::uuid[])LEFT JOIN member actor_member ON w.filter_actor_type='member' AND actor_member.user_id=w.filter_actor_id AND actor_member.workspace_id=w.workspace_idLEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id@@ -682,6 +813,18 @@ type ListIssueWakeupsRow struct {AgentName string `json:"agent_name"`FilterAgentName pgtype.Text `json:"filter_agent_name"`LastTaskStatus pgtype.Text `json:"last_task_status"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+ ExpirySeconds pgtype.Int8 `json:"expiry_seconds"`+ OnTimeout pgtype.Text `json:"on_timeout"`+ TimedOutAt pgtype.Timestamptz `json:"timed_out_at"`+ Condition json.RawMessage `json:"condition"`+ MaxFires pgtype.Int4 `json:"max_fires"`+ FireCount int32 `json:"fire_count"`+ PausedReason pgtype.Text `json:"paused_reason"`+ CreatedByAgent bool `json:"created_by_agent"`+ CreatedByName pgtype.Text `json:"created_by_name"`+ SourceAgentID pgtype.UUID `json:"source_agent_id"`+ SourceAgentName pgtype.Text `json:"source_agent_name"`}func (q *Queries) ListIssueWakeups(ctx context.Context, arg ListIssueWakeupsParams) ([]ListIssueWakeupsRow, error) {@@ -724,6 +867,61 @@ func (q *Queries) ListIssueWakeups(ctx context.Context, arg ListIssueWakeupsPara&i.AgentName,&i.FilterAgentName,&i.LastTaskStatus,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.Condition,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,+ &i.CreatedByAgent,+ &i.CreatedByName,+ &i.SourceAgentID,+ &i.SourceAgentName,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listPausedWakeupIssues = `-- name: ListPausedWakeupIssues :many+SELECT w.issue_id,w.id,w.agent_id,w.paused_reason+FROM issue_wakeup w JOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id+WHERE w.workspace_id= $1 AND NOT w.enabled AND w.paused_reason IN ('loop','rate','max_fires')+ AND i.status NOT IN ('done','cancelled')+ AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))+ORDER BY w.updated_at DESC LIMIT 200+`++type ListPausedWakeupIssuesRow struct {+ IssueID pgtype.UUID `json:"issue_id"`+ ID pgtype.UUID `json:"id"`+ AgentID pgtype.UUID `json:"agent_id"`+ PausedReason pgtype.Text `json:"paused_reason"`+}++// Rules the platform paused on open issues, for board cues and the+// workspace banner. Access follows shared issue visibility.+func (q *Queries) ListPausedWakeupIssues(ctx context.Context, workspaceID pgtype.UUID) ([]ListPausedWakeupIssuesRow, error) {+ rows, err := q.db.Query(ctx, listPausedWakeupIssues, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListPausedWakeupIssuesRow{}+ for rows.Next() {+ var i ListPausedWakeupIssuesRow+ if err := rows.Scan(+ &i.IssueID,+ &i.ID,+ &i.AgentID,+ &i.PausedReason,); err != nil {return nil, err}@@ -779,9 +977,13 @@ const listReadyWakeups = `-- name: ListReadyWakeups :manyWITH candidates AS (SELECT id FROM issue_wakeup WHERE enabled AND kind<>'event' AND next_fire_at<=now()UNION+ SELECT id FROM issue_wakeup WHERE enabled AND expires_at<=now()+ UNION+ SELECT id FROM issue_wakeup WHERE enabled AND condition IS NOT NULL AND next_fire_at<=now()+ UNIONSELECT wakeup_id FROM issue_wakeup_receipt WHERE processed_at IS NULL)-SELECT w.id, w.workspace_id, w.issue_id, w.agent_id, w.created_by, w.source_task_id, w.parent_comment_id, w.instruction, w.kind, w.mode, w.event_types, w.filter_agent_id, w.filter_task_id, w.interval_seconds, w.cron_expression, w.timezone, w.next_fire_at, w.enabled, w.disabled_at, w.revision, w.last_task_id, w.last_error, w.created_at, w.updated_at, w.filter_actor_type, w.filter_actor_id FROM candidates c JOIN issue_wakeup w ON w.id=c.id+SELECT w.id, w.workspace_id, w.issue_id, w.agent_id, w.created_by, w.source_task_id, w.parent_comment_id, w.instruction, w.kind, w.mode, w.event_types, w.filter_agent_id, w.filter_task_id, w.interval_seconds, w.cron_expression, w.timezone, w.next_fire_at, w.enabled, w.disabled_at, w.revision, w.last_task_id, w.last_error, w.created_at, w.updated_at, w.filter_actor_type, w.filter_actor_id, w.expires_at, w.expiry_seconds, w.on_timeout, w.timed_out_at, w.system_rule, w.customized_at, w.condition, w.condition_state, w.max_fires, w.fire_count, w.paused_reason FROM candidates c JOIN issue_wakeup w ON w.id=c.idORDER BY w.updated_at,w.id LIMIT 100`@@ -821,6 +1023,142 @@ func (q *Queries) ListReadyWakeups(ctx context.Context) ([]IssueWakeup, error) {&i.UpdatedAt,&i.FilterActorType,&i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWaitingWakeups = `-- name: ListWaitingWakeups :many+SELECT w.id FROM issue_wakeup w+WHERE w.issue_id= $1 AND (w.agent_id= $2 OR w.system_rule IS NOT NULL) AND w.disabled_at IS NULL+ AND EXISTS(SELECT 1 FROM issue_wakeup_receipt r WHERE r.wakeup_id=w.id AND r.revision=w.revision AND r.processed_at IS NULL+ AND (w.condition IS NULL OR r.event_type IN ('condition.met','wakeup.timeout','wakeup.manual')))+ORDER BY w.created_at,w.id+`++type ListWaitingWakeupsParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+}++// Rules on the issue with inputs a run of this agent can take along: the+// agent's own rules and the platform's. Read without locks; each one is+// locked and checked again before it joins.+func (q *Queries) ListWaitingWakeups(ctx context.Context, arg ListWaitingWakeupsParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listWaitingWakeups, arg.IssueID, arg.AgentID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWakeupChains = `-- name: ListWakeupChains :many+SELECT id,COALESCE(context->>'wakeup_id','')::text AS wakeup_id,COALESCE(context->'wakeup_chain','[]'::jsonb)::jsonb AS chain+FROM agent_task_queue WHERE id=ANY($1::uuid[])+`++type ListWakeupChainsRow struct {+ ID pgtype.UUID `json:"id"`+ WakeupID string `json:"wakeup_id"`+ Chain []byte `json:"chain"`+}++// Rules whose runs produced the source events, including rules further up+// each run's own trigger chain.+func (q *Queries) ListWakeupChains(ctx context.Context, ids []pgtype.UUID) ([]ListWakeupChainsRow, error) {+ rows, err := q.db.Query(ctx, listWakeupChains, ids)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListWakeupChainsRow{}+ for rows.Next() {+ var i ListWakeupChainsRow+ if err := rows.Scan(&i.ID, &i.WakeupID, &i.Chain); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWakeupRuns = `-- name: ListWakeupRuns :many+SELECT t.id,t.status,t.created_at,t.started_at,t.completed_at,+ COALESCE(t.context->'wakeup_checkin'->>'note','')::text AS checkin_note,+ COALESCE((SELECT array_agg(DISTINCT f->>'event_type') FROM jsonb_array_elements(CASE WHEN jsonb_typeof(t.context->'wakeup_evidence'->'facts')='array' THEN t.context->'wakeup_evidence'->'facts' ELSE '[]'::jsonb END) f),'{}')::text[] AS triggers,+ EXISTS(SELECT 1 FROM comment c WHERE c.issue_id=t.issue_id AND c.source_task_id=t.id)::bool AS commented+FROM agent_task_queue t WHERE t.context->>'wakeup_id'= $1::text AND t.issue_id= $2+ORDER BY t.created_at DESC,t.id DESC LIMIT 10+`++type ListWakeupRunsParams struct {+ WakeupID string `json:"wakeup_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++type ListWakeupRunsRow struct {+ ID pgtype.UUID `json:"id"`+ Status string `json:"status"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ StartedAt pgtype.Timestamptz `json:"started_at"`+ CompletedAt pgtype.Timestamptz `json:"completed_at"`+ CheckinNote string `json:"checkin_note"`+ Triggers []string `json:"triggers"`+ Commented bool `json:"commented"`+}++// The rule's latest runs with what triggered each one, a check-in note when+// the run ended silently, and whether it left a comment.+func (q *Queries) ListWakeupRuns(ctx context.Context, arg ListWakeupRunsParams) ([]ListWakeupRunsRow, error) {+ rows, err := q.db.Query(ctx, listWakeupRuns, arg.WakeupID, arg.IssueID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListWakeupRunsRow{}+ for rows.Next() {+ var i ListWakeupRunsRow+ if err := rows.Scan(+ &i.ID,+ &i.Status,+ &i.CreatedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.CheckinNote,+ &i.Triggers,+ &i.Commented,); err != nil {return nil, err}@@ -839,7 +1177,7 @@ WITH ranked AS (COALESCE(actor_agent.name,actor_user.name,'')::text AS filter_actor_name,(CASE WHEN EXISTS(SELECT 1 FROM agent_task_queue ft JOIN agent fa ON fa.id=ft.agent_id AND fa.workspace_id=w.workspace_idWHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY($1::uuid[])) THEN w.filter_task_id END)::uuid AS filter_task_id,- source.name AS filter_agent_name,w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,+ source.name AS filter_agent_name,w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,w.condition,count(*) OVER(PARTITION BY w.issue_id) AS active_count,count(*) FILTER(WHERE w.kind='event') OVER(PARTITION BY w.issue_id) AS event_count,row_number() OVER(PARTITION BY w.issue_id ORDER BY w.next_fire_at NULLS LAST,w.created_at,w.id) AS rank@@ -854,7 +1192,7 @@ LEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.AND i.status NOT IN ('done','cancelled')AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed')))-SELECT issue_id,id,agent_id,agent_name,kind,mode,event_types,filter_actor_type,filter_actor_id,filter_actor_name,filter_task_id,filter_agent_name,interval_seconds,cron_expression,timezone,next_fire_at,active_count,event_count+SELECT issue_id,id,agent_id,agent_name,kind,mode,event_types,filter_actor_type,filter_actor_id,filter_actor_name,filter_task_id,filter_agent_name,interval_seconds,cron_expression,timezone,next_fire_at,condition,active_count,event_countFROM ranked WHERE rank<=3 ORDER BY issue_id,rank`@@ -880,6 +1218,7 @@ type ListWorkspaceWakeupSummaryRowsRow struct {CronExpression pgtype.Text `json:"cron_expression"`Timezone string `json:"timezone"`NextFireAt pgtype.Timestamptz `json:"next_fire_at"`+ Condition []byte `json:"condition"`ActiveCount int64 `json:"active_count"`EventCount int64 `json:"event_count"`}@@ -911,6 +1250,7 @@ func (q *Queries) ListWorkspaceWakeupSummaryRows(ctx context.Context, arg ListWo&i.CronExpression,&i.Timezone,&i.NextFireAt,+ &i.Condition,&i.ActiveCount,&i.EventCount,); err != nil {@@ -925,7 +1265,7 @@ func (q *Queries) ListWorkspaceWakeupSummaryRows(ctx context.Context, arg ListWo}const lockIssueWakeup = `-- name: LockIssueWakeup :one-SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id FROM issue_wakeup WHERE id= $1 FOR UPDATE+SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id, expires_at, expiry_seconds, on_timeout, timed_out_at, system_rule, customized_at, condition, condition_state, max_fires, fire_count, paused_reason FROM issue_wakeup WHERE id= $1 FOR UPDATE`func (q *Queries) LockIssueWakeup(ctx context.Context, id pgtype.UUID) (IssueWakeup, error) {@@ -958,6 +1298,17 @@ func (q *Queries) LockIssueWakeup(ctx context.Context, id pgtype.UUID) (IssueWak&i.UpdatedAt,&i.FilterActorType,&i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,)return i, err}@@ -1081,7 +1432,7 @@ func (q *Queries) LockWakeupSourceTask(ctx context.Context, arg LockWakeupSource}const locklessWakeup = `-- name: LocklessWakeup :one-SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id FROM issue_wakeup WHERE id= $1+SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id, expires_at, expiry_seconds, on_timeout, timed_out_at, system_rule, customized_at, condition, condition_state, max_fires, fire_count, paused_reason FROM issue_wakeup WHERE id= $1`func (q *Queries) LocklessWakeup(ctx context.Context, id pgtype.UUID) (IssueWakeup, error) {@@ -1114,10 +1465,33 @@ func (q *Queries) LocklessWakeup(ctx context.Context, id pgtype.UUID) (IssueWake&i.UpdatedAt,&i.FilterActorType,&i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,)return i, err}+const markWakeupTimedOut = `-- name: MarkWakeupTimedOut :exec+UPDATE issue_wakeup SET enabled=false,next_fire_at=NULL,timed_out_at=clock_timestamp(),updated_at=clock_timestamp() WHERE id= $1+`++// The deadline ended the rule. disabled_at stays NULL: a timeout run created in+// the same transaction must remain claimable, and the rule reads as timed out,+// not as turned off by a person.+func (q *Queries) MarkWakeupTimedOut(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, markWakeupTimedOut, id)+ return err+}+const noteWakeupFailure = `-- name: NoteWakeupFailure :execUPDATE issue_wakeup SET last_error=$1,updated_at=clock_timestamp() WHERE id= $2`@@ -1132,6 +1506,26 @@ func (q *Queries) NoteWakeupFailure(ctx context.Context, arg NoteWakeupFailurePareturn err}+const pauseIssueWakeup = `-- name: PauseIssueWakeup :exec+UPDATE issue_wakeup SET enabled=false,next_fire_at=NULL,paused_reason= $1,+ disabled_at=CASE WHEN $2::bool THEN COALESCE(disabled_at,clock_timestamp()) ELSE disabled_at END,+ updated_at=clock_timestamp() WHERE id= $3+`++type PauseIssueWakeupParams struct {+ PausedReason pgtype.Text `json:"paused_reason"`+ BlockRuns bool `json:"block_runs"`+ ID pgtype.UUID `json:"id"`+}++// The platform stopped a rule. A detected loop or burst also sets disabled_at+// so queued runs of this rule can no longer be claimed; hitting the cap does+// not, because the run that reached it is legitimate.+func (q *Queries) PauseIssueWakeup(ctx context.Context, arg PauseIssueWakeupParams) error {+ _, err := q.db.Exec(ctx, pauseIssueWakeup, arg.PausedReason, arg.BlockRuns, arg.ID)+ return err+}+const recordWakeupReceipt = `-- name: RecordWakeupReceipt :oneINSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)VALUES($1,$2,$3,$4,$5,$6)@@ -1172,6 +1566,15 @@ func (q *Queries) RecordWakeupReceipt(ctx context.Context, arg RecordWakeupReceireturn i, err}+const releaseWakeupReceipts = `-- name: ReleaseWakeupReceipts :exec+UPDATE issue_wakeup_receipt SET task_id=NULL WHERE id=ANY($1::uuid[]) AND processed_at IS NULL+`++func (q *Queries) ReleaseWakeupReceipts(ctx context.Context, ids []pgtype.UUID) error {+ _, err := q.db.Exec(ctx, releaseWakeupReceipts, ids)+ return err+}+const replaceWakeupEvidence = `-- name: ReplaceWakeupEvidence :oneUPDATE agent_task_queue SET handoff_note=$1, context=COALESCE(context,'{}'::jsonb) || jsonb_build_object('wakeup_evidence', $2::jsonb) WHERE id= $3 AND status='queued' RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot`@@ -1249,6 +1652,116 @@ func (q *Queries) ReplaceWakeupEvidence(ctx context.Context, arg ReplaceWakeupEvreturn i, err}+const reserveWakeupReceipts = `-- name: ReserveWakeupReceipts :exec+UPDATE issue_wakeup_receipt SET task_id= $1 WHERE id=ANY($2::uuid[]) AND processed_at IS NULL+`++type ReserveWakeupReceiptsParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ Ids []pgtype.UUID `json:"ids"`+}++// A run being claimed takes these inputs along. They stay pending: they count+// as handled once that run starts, and go back to the rule if it never does.+func (q *Queries) ReserveWakeupReceipts(ctx context.Context, arg ReserveWakeupReceiptsParams) error {+ _, err := q.db.Exec(ctx, reserveWakeupReceipts, arg.TaskID, arg.Ids)+ return err+}++const setClaimedTaskContext = `-- name: SetClaimedTaskContext :one+UPDATE agent_task_queue SET context= $1::jsonb+WHERE id= $2 AND status='dispatched' AND dispatched_at= $3 RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot+`++type SetClaimedTaskContextParams struct {+ Context []byte `json:"context"`+ ID pgtype.UUID `json:"id"`+ DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`+}++// Only the claim being answered may change its task's context.+func (q *Queries) SetClaimedTaskContext(ctx context.Context, arg SetClaimedTaskContextParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, setClaimedTaskContext, arg.Context, arg.ID, arg.DispatchedAt)+ var i AgentTaskQueue+ err := row.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ )+ return i, err+}++const setWakeupConditionState = `-- name: SetWakeupConditionState :exec+UPDATE issue_wakeup SET condition_state= $1,next_fire_at=$2,updated_at=clock_timestamp() WHERE id= $3+`++type SetWakeupConditionStateParams struct {+ ConditionState string `json:"condition_state"`+ NextFireAt pgtype.Timestamptz `json:"next_fire_at"`+ ID pgtype.UUID `json:"id"`+}++func (q *Queries) SetWakeupConditionState(ctx context.Context, arg SetWakeupConditionStateParams) error {+ _, err := q.db.Exec(ctx, setWakeupConditionState, arg.ConditionState, arg.NextFireAt, arg.ID)+ return err+}+const touchWakeupDispatch = `-- name: TouchWakeupDispatch :execUPDATE issue_wakeup SET updated_at=clock_timestamp() WHERE id= $1`@@ -1259,3 +1772,53 @@ func (q *Queries) TouchWakeupDispatch(ctx context.Context, id pgtype.UUID) error_, err := q.db.Exec(ctx, touchWakeupDispatch, id)return err}++const tryLockIssueWakeup = `-- name: TryLockIssueWakeup :one+SELECT id, workspace_id, issue_id, agent_id, created_by, source_task_id, parent_comment_id, instruction, kind, mode, event_types, filter_agent_id, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, disabled_at, revision, last_task_id, last_error, created_at, updated_at, filter_actor_type, filter_actor_id, expires_at, expiry_seconds, on_timeout, timed_out_at, system_rule, customized_at, condition, condition_state, max_fires, fire_count, paused_reason FROM issue_wakeup WHERE id= $1 FOR UPDATE SKIP LOCKED+`++// A rule another writer holds is skipped; it keeps its inputs.+func (q *Queries) TryLockIssueWakeup(ctx context.Context, id pgtype.UUID) (IssueWakeup, error) {+ row := q.db.QueryRow(ctx, tryLockIssueWakeup, id)+ var i IssueWakeup+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,+ )+ return i, err+}diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex 6ed9cd8b2f..2d067d0f47 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -238,6 +238,9 @@ WITH deleted_wakeup_receipts AS (), deleted_wakeups AS (DELETE FROM issue_wakeup WHERE workspace_id=$1),+deleted_child_events AS (+ DELETE FROM issue_child_event WHERE workspace_id=$1+),deleted_issues AS (DELETE FROM issue WHERE issue.workspace_id = $1),diff --git a/server/pkg/db/generated/workspace_wakeup.sql.go b/server/pkg/db/generated/workspace_wakeup.sql.goindex fe968e07a8..707931e135 100644--- a/server/pkg/db/generated/workspace_wakeup.sql.go+++ b/server/pkg/db/generated/workspace_wakeup.sql.go@@ -23,9 +23,15 @@ WITH base AS MATERIALIZED (WHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY($1::uuid[])) THEN w.filter_task_id END AS filter_task_id,w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,w.enabled,w.revision,w.disabled_at,w.last_task_id,w.last_error,w.created_at,+ w.expires_at,w.expiry_seconds,w.on_timeout,w.timed_out_at,+ w.condition,w.max_fires,w.fire_count,w.paused_reason,+ (w.source_task_id IS NOT NULL) AS created_by_agent,creator.name AS created_by_name,+ CASE WHEN creator_agent.id IS NOT NULL THEN creator_agent.id END AS source_agent_id,creator_agent.name AS source_agent_name,(i.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))) AS issue_closed,COALESCE((w.created_by= $2::uuid OR $3::boolean),false) AS can_manage,- COALESCE(r.active_runs,0)::int AS active_runs+ COALESCE(r.active_runs,0)::int AS active_runs,+ (CASE WHEN w.source_task_id IS NOT NULL THEN 'agent' ELSE 'member' END)::text AS source,+ NULL::text AS rule,NULL::int AS system_stage,NULL::text AS target_type,NULL::int AS system_remainingFROM issue_wakeup wJOIN workspace ws ON ws.id=w.workspace_idJOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id@@ -34,25 +40,72 @@ WITH base AS MATERIALIZED (LEFT JOIN member actor_member ON w.filter_actor_type='member' AND actor_member.user_id=w.filter_actor_id AND actor_member.workspace_id=w.workspace_idLEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_idLEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.workspace_id AND source.id=ANY($1::uuid[])+ LEFT JOIN "user" creator ON creator.id=w.created_by+ LEFT JOIN agent_task_queue creator_task ON creator_task.id=w.source_task_id+ LEFT JOIN agent creator_agent ON creator_agent.id=creator_task.agent_id AND creator_agent.workspace_id=w.workspace_id AND creator_agent.id=ANY($1::uuid[])LEFT JOIN LATERAL (SELECT count(*) AS active_runs FROM agent_task_queue tWHERE t.context->>'wakeup_id'=w.id::text AND t.issue_id=w.issue_id AND t.agent_id=w.agent_idAND t.status IN ('queued','deferred','dispatched','running','waiting_local_directory')) r ON true- WHERE w.workspace_id= $4+ WHERE w.workspace_id= $4 AND w.system_rule IS NULL+ UNION ALL+ -- The child-done system rule of each open parent that still waits for a+ -- sub-issue: every child when unstaged, else its lowest unfinished stage.+ -- Its target is the parent's assignee (a squad's leader) at the moment.+ SELECT w.id,w.issue_id,p.title,ws.issue_prefix||'-'||p.number,+ COALESCE(ta.id,leader.id),COALESCE(ta.name,leader.name,''),w.kind,w.mode,w.event_types,NULL::text,+ NULL::uuid,''::text,NULL::uuid,NULL::text,NULL::uuid,+ NULL::bigint,NULL::text,w.timezone,+ NULL::timestamptz,w.enabled,w.revision,w.disabled_at,w.last_task_id,w.last_error,w.created_at,+ NULL::timestamptz,NULL::bigint,NULL::text,NULL::timestamptz,+ w.condition,w.max_fires,w.fire_count,w.paused_reason,+ false,NULL::text,+ NULL::uuid,NULL::text,+ false,true,COALESCE(sr.active_runs,0)::int,+ 'system',w.system_rule,ch.stage,p.assignee_type,ch.remaining+ FROM issue_wakeup w+ JOIN issue p ON p.id=w.issue_id AND p.workspace_id=w.workspace_id+ JOIN workspace ws ON ws.id=p.workspace_id+ LEFT JOIN agent ta ON p.assignee_type='agent' AND ta.id=p.assignee_id AND ta.workspace_id=p.workspace_id+ LEFT JOIN squad sq ON p.assignee_type='squad' AND sq.id=p.assignee_id AND sq.workspace_id=p.workspace_id+ LEFT JOIN agent leader ON leader.id=sq.leader_id AND leader.workspace_id=p.workspace_id+ CROSS JOIN LATERAL (+ SELECT bool_or(ci.stage IS NOT NULL) AS staged,+ min(ci.stage) FILTER(WHERE ci.stage IS NOT NULL AND NOT (ci.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status cs WHERE cs.workspace_id=ci.workspace_id AND cs.key=ci.status AND cs.category IN ('done','closed')))) AS stage,+ count(*) FILTER(WHERE NOT (ci.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status cs WHERE cs.workspace_id=ci.workspace_id AND cs.key=ci.status AND cs.category IN ('done','closed')))) AS open_count+ FROM issue ci WHERE ci.parent_issue_id=p.id AND ci.workspace_id=p.workspace_id+ ) agg+ CROSS JOIN LATERAL (+ SELECT (CASE WHEN agg.staged THEN agg.stage END)::int AS stage,+ (CASE WHEN agg.staged AND agg.stage IS NOT NULL THEN (SELECT count(*) FROM issue ci WHERE ci.parent_issue_id=p.id AND ci.workspace_id=p.workspace_id+ AND ci.stage=agg.stage AND NOT (ci.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status cs WHERE cs.workspace_id=ci.workspace_id AND cs.key=ci.status AND cs.category IN ('done','closed')))) ELSE agg.open_count END)::int AS remaining+ ) ch+ LEFT JOIN LATERAL (+ SELECT count(*) AS active_runs FROM agent_task_queue t+ WHERE t.context->>'wakeup_id'=w.id::text AND t.issue_id=w.issue_id+ AND t.status IN ('queued','deferred','dispatched','running','waiting_local_directory')+ ) sr ON true+ WHERE w.workspace_id= $4 AND w.system_rule IS NOT NULL AND agg.open_count>0+ AND p.status NOT IN ('done','cancelled')+ AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=p.workspace_id AND s.key=p.status AND s.category IN ('done','closed'))), classified AS (- SELECT id, issue_id, issue_title, issue_identifier, agent_id, agent_name, kind, mode, event_types, filter_actor_type, filter_actor_id, filter_actor_name, filter_agent_id, filter_agent_name, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, revision, disabled_at, last_task_id, last_error, created_at, issue_closed, can_manage, active_runs,CASE WHEN (enabled AND NOT issue_closed) OR active_runs>0 THEN 'active'- WHEN NOT issue_closed AND disabled_at IS NOT NULL THEN 'disabled' ELSE 'ended' END AS scope+ SELECT id, issue_id, issue_title, issue_identifier, agent_id, agent_name, kind, mode, event_types, filter_actor_type, filter_actor_id, filter_actor_name, filter_agent_id, filter_agent_name, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, revision, disabled_at, last_task_id, last_error, created_at, expires_at, expiry_seconds, on_timeout, timed_out_at, condition, max_fires, fire_count, paused_reason, created_by_agent, created_by_name, source_agent_id, source_agent_name, issue_closed, can_manage, active_runs, source, rule, system_stage, target_type, system_remaining,CASE WHEN (enabled AND NOT issue_closed) OR active_runs>0 THEN 'active'+ WHEN NOT issue_closed AND paused_reason IS NOT NULL THEN 'paused'+ WHEN NOT issue_closed AND (disabled_at IS NOT NULL OR source='system') THEN 'disabled' ELSE 'ended' END AS scopeFROM base), filtered AS (- SELECT id, issue_id, issue_title, issue_identifier, agent_id, agent_name, kind, mode, event_types, filter_actor_type, filter_actor_id, filter_actor_name, filter_agent_id, filter_agent_name, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, revision, disabled_at, last_task_id, last_error, created_at, issue_closed, can_manage, active_runs, scope FROM classified WHERE ($5::text='all' OR scope= $5)+ SELECT id, issue_id, issue_title, issue_identifier, agent_id, agent_name, kind, mode, event_types, filter_actor_type, filter_actor_id, filter_actor_name, filter_agent_id, filter_agent_name, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, revision, disabled_at, last_task_id, last_error, created_at, expires_at, expiry_seconds, on_timeout, timed_out_at, condition, max_fires, fire_count, paused_reason, created_by_agent, created_by_name, source_agent_id, source_agent_name, issue_closed, can_manage, active_runs, source, rule, system_stage, target_type, system_remaining, scope FROM classified WHERE ($5::text='all' OR scope= $5)AND ($6::text='all' OR ($6='event' AND kind='event') OR ($6='at' AND kind='at') OR ($6='recurring' AND kind IN ('every','cron')))- AND ($7::text='' OR agent_id::text= $7)- AND ($8::text='' OR strpos(lower(issue_title||' '||issue_identifier||' '||agent_name),lower($8))>0)+ AND ($7::text='' OR source= $7)+ AND ($8::text='' OR agent_id::text= $8)+ AND ($9::text='' OR strpos(lower(issue_title||' '||issue_identifier||' '||agent_name),lower($9))>0)), page AS (- SELECT id, issue_id, issue_title, issue_identifier, agent_id, agent_name, kind, mode, event_types, filter_actor_type, filter_actor_id, filter_actor_name, filter_agent_id, filter_agent_name, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, revision, disabled_at, last_task_id, last_error, created_at, issue_closed, can_manage, active_runs, scope FROM filtered ORDER BY created_at DESC,id DESC LIMIT $10::int OFFSET $9::int+ SELECT id, issue_id, issue_title, issue_identifier, agent_id, agent_name, kind, mode, event_types, filter_actor_type, filter_actor_id, filter_actor_name, filter_agent_id, filter_agent_name, filter_task_id, interval_seconds, cron_expression, timezone, next_fire_at, enabled, revision, disabled_at, last_task_id, last_error, created_at, expires_at, expiry_seconds, on_timeout, timed_out_at, condition, max_fires, fire_count, paused_reason, created_by_agent, created_by_name, source_agent_id, source_agent_name, issue_closed, can_manage, active_runs, source, rule, system_stage, target_type, system_remaining, scope FROM filtered ORDER BY created_at DESC,id DESC LIMIT $11::int OFFSET $10::int), details AS (- SELECT p.id, p.issue_id, p.issue_title, p.issue_identifier, p.agent_id, p.agent_name, p.kind, p.mode, p.event_types, p.filter_actor_type, p.filter_actor_id, p.filter_actor_name, p.filter_agent_id, p.filter_agent_name, p.filter_task_id, p.interval_seconds, p.cron_expression, p.timezone, p.next_fire_at, p.enabled, p.revision, p.disabled_at, p.last_task_id, p.last_error, p.created_at, p.issue_closed, p.can_manage, p.active_runs, p.scope,r.status AS last_task_status,+ SELECT p.id, p.issue_id, p.issue_title, p.issue_identifier, p.agent_id, p.agent_name, p.kind, p.mode, p.event_types, p.filter_actor_type, p.filter_actor_id, p.filter_actor_name, p.filter_agent_id, p.filter_agent_name, p.filter_task_id, p.interval_seconds, p.cron_expression, p.timezone, p.next_fire_at, p.enabled, p.revision, p.disabled_at, p.last_task_id, p.last_error, p.created_at, p.expires_at, p.expiry_seconds, p.on_timeout, p.timed_out_at, p.condition, p.max_fires, p.fire_count, p.paused_reason, p.created_by_agent, p.created_by_name, p.source_agent_id, p.source_agent_name, p.issue_closed, p.can_manage, p.active_runs, p.source, p.rule, p.system_stage, p.target_type, p.system_remaining, p.scope,r.status AS last_task_status,+ (SELECT count(*) FROM agent_task_queue t7 WHERE t7.context->>'wakeup_id'=p.id::text AND t7.issue_id=p.issue_id+ AND t7.created_at>now()-interval '7 days')::int AS runs_7d,CASE WHEN r.id IS NOT NULL THEN jsonb_build_object('id',r.id,'agent_id',r.agent_id,'runtime_id',r.runtime_id,'issue_id',r.issue_id,'wakeup_id',p.id,'status',r.status,'priority',r.priority,'created_at',r.created_at,'started_at',r.started_at,@@ -62,12 +115,12 @@ LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_idLEFT JOIN LATERAL (SELECT candidate.id, candidate.agent_id, candidate.runtime_id, candidate.issue_id, candidate.status, candidate.priority, candidate.created_at, candidate.started_at, candidate.dispatched_at, candidate.completed_at, candidate.active FROM ((SELECT t.id,t.agent_id,t.runtime_id,t.issue_id,t.status,t.priority,t.created_at,t.started_at,t.dispatched_at,t.completed_at,1 AS active- FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND t.agent_id=p.agent_id+ FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND (p.source='system' OR t.agent_id=p.agent_id)AND t.status IN ('queued','deferred','dispatched','running','waiting_local_directory')ORDER BY (t.status IN ('running','waiting_local_directory','dispatched')) DESC,t.created_at DESC,t.id DESC LIMIT 1)UNION ALL(SELECT t.id,t.agent_id,t.runtime_id,t.issue_id,t.status,t.priority,t.created_at,t.started_at,t.dispatched_at,t.completed_at,0 AS active- FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND t.agent_id=p.agent_id+ FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND (p.source='system' OR t.agent_id=p.agent_id)AND t.status NOT IN ('queued','deferred','dispatched','running','waiting_local_directory')ORDER BY t.created_at DESC,t.id DESC LIMIT 1)) candidate ORDER BY active DESC LIMIT 1@@ -77,8 +130,9 @@ SELECT jsonb_build_object('items',COALESCE((SELECT jsonb_agg(to_jsonb(details)-'created_at'-'scope' ORDER BY created_at DESC,id DESC) FROM details),'[]'::jsonb),'total',(SELECT count(*) FROM filtered),'counts',jsonb_build_object('all',(SELECT count(*) FROM classified),'active',(SELECT count(*) FROM classified WHERE scope='active'),+ 'paused',(SELECT count(*) FROM classified WHERE scope='paused'),'disabled',(SELECT count(*) FROM classified WHERE scope='disabled'),'ended',(SELECT count(*) FROM classified WHERE scope='ended')),- 'agents',COALESCE((SELECT jsonb_agg(x ORDER BY x.name,x.id) FROM (SELECT DISTINCT agent_id AS id,agent_name AS name FROM base) x),'[]'::jsonb)+ 'agents',COALESCE((SELECT jsonb_agg(x ORDER BY x.name,x.id) FROM (SELECT DISTINCT agent_id AS id,agent_name AS name FROM base WHERE agent_id IS NOT NULL) x),'[]'::jsonb)) AS result`@@ -89,6 +143,7 @@ type ListWorkspaceWakeupsParams struct {WorkspaceID pgtype.UUID `json:"workspace_id"`Scope string `json:"scope"`Kind string `json:"kind"`+ Source string `json:"source"`AgentID string `json:"agent_id"`Search string `json:"search"`PageOffset int32 `json:"page_offset"`@@ -104,6 +159,7 @@ func (q *Queries) ListWorkspaceWakeups(ctx context.Context, arg ListWorkspaceWakarg.WorkspaceID,arg.Scope,arg.Kind,+ arg.Source,arg.AgentID,arg.Search,arg.PageOffset,diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex a6d5d4bd4a..2eea06f260 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -484,6 +484,9 @@ cleared_wakeup_receipts AS (cleared_wakeups AS (DELETE FROM issue_wakeup WHERE issue_id IN (SELECT target.id FROM target)),+cleared_child_events AS (+ DELETE FROM issue_child_event WHERE parent_id IN (SELECT target.id FROM target) OR child_id IN (SELECT target.id FROM target)+),cleared_task_supplements AS (DELETE FROM task_supplement WHERE issue_id IN (SELECT target.id FROM target)),diff --git a/server/pkg/db/queries/system_wakeup.sql b/server/pkg/db/queries/system_wakeup.sqlnew file mode 100644index 0000000000..4b62003c28--- /dev/null+++ b/server/pkg/db/queries/system_wakeup.sql@@ -0,0 +1,80 @@+-- name: GetSystemWakeup :one+SELECT * FROM issue_wakeup WHERE issue_id= @issue_id AND system_rule= @system_rule;++-- name: CreateSystemWakeup :one+-- A platform rule on one issue. Two writers ensuring it at once keep the first+-- row; the loser reads it back with GetSystemWakeup.+INSERT INTO issue_wakeup(id,workspace_id,issue_id,instruction,kind,mode,event_types,timezone,condition,condition_state,enabled,system_rule)+VALUES(@id,@workspace_id,@issue_id,'','event','continuous',@event_types,'UTC',@condition,@condition_state,@enabled,@system_rule)+ON CONFLICT (issue_id,system_rule) WHERE system_rule IS NOT NULL DO NOTHING+RETURNING *;++-- name: CustomizeSystemWakeup :one+-- A person changed the rule on this issue; it stops following the workspace+-- default. Turning it on clears a platform pause.+UPDATE issue_wakeup SET enabled= @enabled,instruction= @instruction,customized_at=clock_timestamp(),+ paused_reason=CASE WHEN @enabled::bool THEN NULL ELSE paused_reason END,+ disabled_at=CASE WHEN @enabled::bool THEN NULL ELSE disabled_at END,+ updated_at=clock_timestamp()+WHERE id= @id RETURNING *;++-- name: ApplySystemWakeupDefault :many+-- The workspace default changed. Rules nobody customized and the platform did+-- not pause follow it.+UPDATE issue_wakeup SET enabled= @enabled,updated_at=clock_timestamp()+WHERE workspace_id= @workspace_id AND system_rule= @system_rule AND customized_at IS NULL+ AND paused_reason IS NULL AND enabled<> @enabled::bool+RETURNING *;++-- name: CountCustomizedSystemWakeups :one+-- Open issues whose rule a person changed, for the workspace settings page.+SELECT count(*) FROM issue_wakeup w JOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id+WHERE w.workspace_id= @workspace_id AND w.system_rule= @system_rule AND w.customized_at IS NOT NULL+ AND i.status NOT IN ('done','cancelled')+ AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'));++-- name: MergeWorkspaceSettings :exec+UPDATE workspace SET settings=COALESCE(settings,'{}'::jsonb) || @patch::jsonb,updated_at=now() WHERE id= @id;++-- name: ListParentsWithoutSystemWakeup :many+-- Open parents that predate their rule, for the one-time backfill.+SELECT p.* FROM (SELECT DISTINCT c.parent_issue_id AS id FROM issue c WHERE c.parent_issue_id IS NOT NULL) parents+JOIN issue p ON p.id=parents.id+WHERE NOT EXISTS(SELECT 1 FROM issue_wakeup w WHERE w.issue_id=p.id AND w.system_rule= @system_rule)+ AND p.status NOT IN ('done','cancelled')+ AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=p.workspace_id AND s.key=p.status AND s.category IN ('done','closed'))+LIMIT @page_limit;++-- name: ListChildConditionWakeups :many+-- Enabled rules on a parent whose condition reads its sub-issues.+SELECT * FROM issue_wakeup WHERE issue_id= @issue_id AND enabled AND condition->>'type'='children_done'+ORDER BY (system_rule IS NOT NULL),id;++-- name: ClaimChildEvents :many+-- Claim a parent's recorded sub-issue changes. A claim that was not finished+-- within five minutes (a crashed or failed attempt) can be claimed again.+UPDATE issue_child_event SET claimed_at=clock_timestamp()+WHERE parent_id= @parent_id AND processed_at IS NULL+ AND (claimed_at IS NULL OR claimed_at < clock_timestamp()-interval '5 minutes')+RETURNING *;++-- name: ListUnprocessedClosedChildren :many+-- Sub-issues whose closing is recorded but not processed yet.+SELECT DISTINCT child_id FROM issue_child_event WHERE parent_id= @parent_id AND kind='closed' AND processed_at IS NULL;++-- name: FinishChildEvents :exec+UPDATE issue_child_event SET processed_at=clock_timestamp() WHERE id=ANY(@ids::uuid[]);++-- name: ListStaleChildEventParents :many+-- Parents whose changes were not processed right after their write.+SELECT DISTINCT parent_id FROM issue_child_event+WHERE processed_at IS NULL+ AND ((claimed_at IS NULL AND created_at < clock_timestamp()-interval '30 seconds') OR claimed_at < clock_timestamp()-interval '5 minutes')+LIMIT 50;++-- name: DeleteProcessedChildEvents :execrows+WITH batch AS MATERIALIZED (+ SELECT e.id FROM issue_child_event e WHERE e.processed_at < @cutoff+ ORDER BY e.processed_at LIMIT 1000 FOR UPDATE SKIP LOCKED+)+DELETE FROM issue_child_event d USING batch WHERE d.id=batch.id;diff --git a/server/pkg/db/queries/wakeup.sql b/server/pkg/db/queries/wakeup.sqlindex cd58c23758..e14ae13772 100644--- a/server/pkg/db/queries/wakeup.sql+++ b/server/pkg/db/queries/wakeup.sql@@ -1,6 +1,6 @@-- name: CreateIssueWakeup :one-INSERT INTO issue_wakeup(id,workspace_id,issue_id,agent_id,created_by,source_task_id,parent_comment_id,instruction,kind,mode,event_types,filter_agent_id,filter_task_id,filter_actor_type,filter_actor_id,interval_seconds,cron_expression,timezone,next_fire_at)-VALUES(@id,@workspace_id,@issue_id,@agent_id,@created_by,sqlc.narg(source_task_id),sqlc.narg(parent_comment_id),@instruction,@kind,@mode,@event_types,sqlc.narg(filter_agent_id),sqlc.narg(filter_task_id),sqlc.narg(filter_actor_type),sqlc.narg(filter_actor_id),sqlc.narg(interval_seconds),sqlc.narg(cron_expression),@timezone,sqlc.narg(next_fire_at)) RETURNING *;+INSERT INTO issue_wakeup(id,workspace_id,issue_id,agent_id,created_by,source_task_id,parent_comment_id,instruction,kind,mode,event_types,filter_agent_id,filter_task_id,filter_actor_type,filter_actor_id,interval_seconds,cron_expression,timezone,next_fire_at,expires_at,expiry_seconds,on_timeout,condition,max_fires)+VALUES(@id,@workspace_id,@issue_id,@agent_id,@created_by,sqlc.narg(source_task_id),sqlc.narg(parent_comment_id),@instruction,@kind,@mode,@event_types,sqlc.narg(filter_agent_id),sqlc.narg(filter_task_id),sqlc.narg(filter_actor_type),sqlc.narg(filter_actor_id),sqlc.narg(interval_seconds),sqlc.narg(cron_expression),@timezone,sqlc.narg(next_fire_at),sqlc.narg(expires_at),sqlc.narg(expiry_seconds),sqlc.narg(on_timeout),sqlc.narg(condition),sqlc.narg(max_fires)) RETURNING *;-- name: ListIssueWakeups :manySELECT w.id,w.workspace_id,w.issue_id,w.agent_id,w.created_by,w.source_task_id,w.parent_comment_id,w.instruction,w.kind,w.mode,w.event_types,w.filter_actor_type,@@ -10,8 +10,15 @@ SELECT w.id,w.workspace_id,w.issue_id,w.agent_id,w.created_by,w.source_task_id,w(CASE WHEN EXISTS(SELECT 1 FROM agent_task_queue ft JOIN agent fa ON fa.id=ft.agent_id AND fa.workspace_id=w.workspace_idWHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY(@agent_ids::uuid[])) THEN w.filter_task_id END)::uuid AS filter_task_id,w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,w.enabled,w.disabled_at,w.revision,- w.last_task_id,w.last_error,w.created_at,w.updated_at,a.name AS agent_name,source.name AS filter_agent_name,t.status AS last_task_status+ w.last_task_id,w.last_error,w.created_at,w.updated_at,a.name AS agent_name,source.name AS filter_agent_name,t.status AS last_task_status,+ w.expires_at,w.expiry_seconds,w.on_timeout,w.timed_out_at,+ w.condition,w.max_fires,w.fire_count,w.paused_reason,+ (w.source_task_id IS NOT NULL)::bool AS created_by_agent,creator.name AS created_by_name,+ (CASE WHEN creator_agent.id IS NOT NULL THEN creator_agent.id END)::uuid AS source_agent_id,creator_agent.name AS source_agent_nameFROM issue_wakeup w JOIN agent a ON a.id=w.agent_id AND a.workspace_id=w.workspace_id+LEFT JOIN "user" creator ON creator.id=w.created_by+LEFT JOIN agent_task_queue creator_task ON creator_task.id=w.source_task_id+LEFT JOIN agent creator_agent ON creator_agent.id=creator_task.agent_id AND creator_agent.workspace_id=w.workspace_id AND creator_agent.id=ANY(@agent_ids::uuid[])LEFT JOIN agent actor_agent ON w.filter_actor_type='agent' AND actor_agent.id=w.filter_actor_id AND actor_agent.workspace_id=w.workspace_id AND actor_agent.id=ANY(@agent_ids::uuid[])LEFT JOIN member actor_member ON w.filter_actor_type='member' AND actor_member.user_id=w.filter_actor_id AND actor_member.workspace_id=w.workspace_idLEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id@@ -27,7 +34,7 @@ WITH ranked AS (COALESCE(actor_agent.name,actor_user.name,'')::text AS filter_actor_name,(CASE WHEN EXISTS(SELECT 1 FROM agent_task_queue ft JOIN agent fa ON fa.id=ft.agent_id AND fa.workspace_id=w.workspace_idWHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY(@agent_ids::uuid[])) THEN w.filter_task_id END)::uuid AS filter_task_id,- source.name AS filter_agent_name,w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,+ source.name AS filter_agent_name,w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,w.condition,count(*) OVER(PARTITION BY w.issue_id) AS active_count,count(*) FILTER(WHERE w.kind='event') OVER(PARTITION BY w.issue_id) AS event_count,row_number() OVER(PARTITION BY w.issue_id ORDER BY w.next_fire_at NULLS LAST,w.created_at,w.id) AS rank@@ -42,7 +49,7 @@ LEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.AND i.status NOT IN ('done','cancelled')AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed')))-SELECT issue_id,id,agent_id,agent_name,kind,mode,event_types,filter_actor_type,filter_actor_id,filter_actor_name,filter_task_id,filter_agent_name,interval_seconds,cron_expression,timezone,next_fire_at,active_count,event_count+SELECT issue_id,id,agent_id,agent_name,kind,mode,event_types,filter_actor_type,filter_actor_id,filter_actor_name,filter_task_id,filter_agent_name,interval_seconds,cron_expression,timezone,next_fire_at,condition,active_count,event_countFROM ranked WHERE rank<=3 ORDER BY issue_id,rank;-- name: GetIssueWakeup :oneSELECT * FROM issue_wakeup WHERE id= @id AND workspace_id= @workspace_id;@@ -57,8 +64,9 @@ UPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='WakeupWHERE context->>'wakeup_id'= @wakeup_id::text AND status IN ('queued','deferred') AND started_at IS NULL RETURNING *;-- name: DisableIssueWakeups :exec-- Closing wins over every subscription on the issue; reopening does not rearm.+-- A system rule only rests while its issue is closed and resumes on reopen.UPDATE issue_wakeup SET enabled=false,disabled_at=clock_timestamp(),updated_at=clock_timestamp()-WHERE issue_id= @issue_id AND disabled_at IS NULL;+WHERE issue_id= @issue_id AND disabled_at IS NULL AND system_rule IS NULL;-- name: CancelUnstartedIssueWakeupTasks :manyUPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Issue closed; wakeup disabled'WHERE issue_id= @issue_id AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL RETURNING *;@@ -66,6 +74,10 @@ WHERE issue_id= @issue_id AND context->>'wakeup_id' IS NOT NULL AND status IN ('WITH candidates AS (SELECT id FROM issue_wakeup WHERE enabled AND kind<>'event' AND next_fire_at<=now()UNION+ SELECT id FROM issue_wakeup WHERE enabled AND expires_at<=now()+ UNION+ SELECT id FROM issue_wakeup WHERE enabled AND condition IS NOT NULL AND next_fire_at<=now()+ UNIONSELECT wakeup_id FROM issue_wakeup_receipt WHERE processed_at IS NULL)SELECT w.* FROM candidates c JOIN issue_wakeup w ON w.id=c.id@@ -160,3 +172,98 @@ UPDATE issue_wakeup SET last_error=sqlc.narg(last_error),updated_at=clock_timest-- Move blocked configurations to the back of the scan so one noisy issue-- cannot monopolize the bounded batch.UPDATE issue_wakeup SET updated_at=clock_timestamp() WHERE id= @id;++-- name: MarkWakeupTimedOut :exec+-- The deadline ended the rule. disabled_at stays NULL: a timeout run created in+-- the same transaction must remain claimable, and the rule reads as timed out,+-- not as turned off by a person.+UPDATE issue_wakeup SET enabled=false,next_fire_at=NULL,timed_out_at=clock_timestamp(),updated_at=clock_timestamp() WHERE id= @id;++-- name: SetWakeupConditionState :exec+UPDATE issue_wakeup SET condition_state= @condition_state,next_fire_at=sqlc.narg(next_fire_at),updated_at=clock_timestamp() WHERE id= @id;++-- name: PauseIssueWakeup :exec+-- The platform stopped a rule. A detected loop or burst also sets disabled_at+-- so queued runs of this rule can no longer be claimed; hitting the cap does+-- not, because the run that reached it is legitimate.+UPDATE issue_wakeup SET enabled=false,next_fire_at=NULL,paused_reason= @paused_reason,+ disabled_at=CASE WHEN @block_runs::bool THEN COALESCE(disabled_at,clock_timestamp()) ELSE disabled_at END,+ updated_at=clock_timestamp() WHERE id= @id;++-- name: CountWakeupFires :exec+UPDATE issue_wakeup SET fire_count=fire_count+1 WHERE id= @id;++-- name: CountRecentWakeupTasks :one+SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'= @wakeup_id::text AND issue_id= @issue_id AND created_at> @since;++-- name: ListWakeupChains :many+-- Rules whose runs produced the source events, including rules further up+-- each run's own trigger chain.+SELECT id,COALESCE(context->>'wakeup_id','')::text AS wakeup_id,COALESCE(context->'wakeup_chain','[]'::jsonb)::jsonb AS chain+FROM agent_task_queue WHERE id=ANY(@ids::uuid[]);++-- name: ListWakeupRuns :many+-- The rule's latest runs with what triggered each one, a check-in note when+-- the run ended silently, and whether it left a comment.+SELECT t.id,t.status,t.created_at,t.started_at,t.completed_at,+ COALESCE(t.context->'wakeup_checkin'->>'note','')::text AS checkin_note,+ COALESCE((SELECT array_agg(DISTINCT f->>'event_type') FROM jsonb_array_elements(CASE WHEN jsonb_typeof(t.context->'wakeup_evidence'->'facts')='array' THEN t.context->'wakeup_evidence'->'facts' ELSE '[]'::jsonb END) f),'{}')::text[] AS triggers,+ EXISTS(SELECT 1 FROM comment c WHERE c.issue_id=t.issue_id AND c.source_task_id=t.id)::bool AS commented+FROM agent_task_queue t WHERE t.context->>'wakeup_id'= @wakeup_id::text AND t.issue_id= @issue_id+ORDER BY t.created_at DESC,t.id DESC LIMIT 10;++-- name: DeleteIssueWakeupReceipts :exec+DELETE FROM issue_wakeup_receipt WHERE wakeup_id= @id;++-- name: DeleteIssueWakeup :exec+DELETE FROM issue_wakeup WHERE id= @id AND issue_id= @issue_id;++-- name: ListPausedWakeupIssues :many+-- Rules the platform paused on open issues, for board cues and the+-- workspace banner. Access follows shared issue visibility.+SELECT w.issue_id,w.id,w.agent_id,w.paused_reason+FROM issue_wakeup w JOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id+WHERE w.workspace_id= @workspace_id AND NOT w.enabled AND w.paused_reason IN ('loop','rate','max_fires')+ AND i.status NOT IN ('done','cancelled')+ AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))+ORDER BY w.updated_at DESC LIMIT 200;++-- name: FindWaitingIssueRun :one+-- A run of the agent on the issue that has not been claimed and runs as this+-- person. A rule that fires meanwhile keeps its inputs for that run instead+-- of queuing another.+SELECT id FROM agent_task_queue WHERE issue_id= @issue_id AND agent_id= @agent_id AND status='queued'+ AND originator_user_id= @originator_user_id::uuid ORDER BY created_at,id LIMIT 1;++-- name: ListWaitingWakeups :many+-- Rules on the issue with inputs a run of this agent can take along: the+-- agent's own rules and the platform's. Read without locks; each one is+-- locked and checked again before it joins.+SELECT w.id FROM issue_wakeup w+WHERE w.issue_id= @issue_id AND (w.agent_id= @agent_id OR w.system_rule IS NOT NULL) AND w.disabled_at IS NULL+ AND EXISTS(SELECT 1 FROM issue_wakeup_receipt r WHERE r.wakeup_id=w.id AND r.revision=w.revision AND r.processed_at IS NULL+ AND (w.condition IS NULL OR r.event_type IN ('condition.met','wakeup.timeout','wakeup.manual')))+ORDER BY w.created_at,w.id;++-- name: TryLockIssueWakeup :one+-- A rule another writer holds is skipped; it keeps its inputs.+SELECT * FROM issue_wakeup WHERE id= @id FOR UPDATE SKIP LOCKED;++-- name: ReserveWakeupReceipts :exec+-- A run being claimed takes these inputs along. They stay pending: they count+-- as handled once that run starts, and go back to the rule if it never does.+UPDATE issue_wakeup_receipt SET task_id= @task_id WHERE id=ANY(@ids::uuid[]) AND processed_at IS NULL;++-- name: ReleaseWakeupReceipts :exec+UPDATE issue_wakeup_receipt SET task_id=NULL WHERE id=ANY(@ids::uuid[]) AND processed_at IS NULL;++-- name: SetClaimedTaskContext :one+-- Only the claim being answered may change its task's context.+UPDATE agent_task_queue SET context= @context::jsonb+WHERE id= @id AND status='dispatched' AND dispatched_at= @dispatched_at RETURNING *;++-- name: CountActiveIssueRunsOfAgent :one+-- How many of these runs are the agent's own runs on this issue that have+-- not finished: the run that made a change still knows about it.+SELECT count(*) FROM agent_task_queue WHERE id=ANY(@ids::uuid[]) AND agent_id= @agent_id AND issue_id= @issue_id+ AND status IN ('dispatched','running','waiting_local_directory');diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex c90d69c98e..9f6972cfb1 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -556,6 +556,9 @@ WITH deleted_wakeup_receipts AS (), deleted_wakeups AS (DELETE FROM issue_wakeup WHERE workspace_id=$1),+deleted_child_events AS (+ DELETE FROM issue_child_event WHERE workspace_id=$1+),deleted_issues AS (DELETE FROM issue WHERE issue.workspace_id = $1),diff --git a/server/pkg/db/queries/workspace_wakeup.sql b/server/pkg/db/queries/workspace_wakeup.sqlindex 0ba7e29efa..50e3e29862 100644--- a/server/pkg/db/queries/workspace_wakeup.sql+++ b/server/pkg/db/queries/workspace_wakeup.sql@@ -11,9 +11,15 @@ WITH base AS MATERIALIZED (WHERE ft.id=w.filter_task_id AND ft.issue_id=w.issue_id AND fa.id=ANY(@agent_ids::uuid[])) THEN w.filter_task_id END AS filter_task_id,w.interval_seconds,w.cron_expression,w.timezone,w.next_fire_at,w.enabled,w.revision,w.disabled_at,w.last_task_id,w.last_error,w.created_at,+ w.expires_at,w.expiry_seconds,w.on_timeout,w.timed_out_at,+ w.condition,w.max_fires,w.fire_count,w.paused_reason,+ (w.source_task_id IS NOT NULL) AS created_by_agent,creator.name AS created_by_name,+ CASE WHEN creator_agent.id IS NOT NULL THEN creator_agent.id END AS source_agent_id,creator_agent.name AS source_agent_name,(i.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))) AS issue_closed,COALESCE((w.created_by= @member_id::uuid OR @is_admin::boolean),false) AS can_manage,- COALESCE(r.active_runs,0)::int AS active_runs+ COALESCE(r.active_runs,0)::int AS active_runs,+ (CASE WHEN w.source_task_id IS NOT NULL THEN 'agent' ELSE 'member' END)::text AS source,+ NULL::text AS rule,NULL::int AS system_stage,NULL::text AS target_type,NULL::int AS system_remainingFROM issue_wakeup wJOIN workspace ws ON ws.id=w.workspace_idJOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id@@ -22,25 +28,72 @@ WITH base AS MATERIALIZED (LEFT JOIN member actor_member ON w.filter_actor_type='member' AND actor_member.user_id=w.filter_actor_id AND actor_member.workspace_id=w.workspace_idLEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_idLEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.workspace_id AND source.id=ANY(@agent_ids::uuid[])+ LEFT JOIN "user" creator ON creator.id=w.created_by+ LEFT JOIN agent_task_queue creator_task ON creator_task.id=w.source_task_id+ LEFT JOIN agent creator_agent ON creator_agent.id=creator_task.agent_id AND creator_agent.workspace_id=w.workspace_id AND creator_agent.id=ANY(@agent_ids::uuid[])LEFT JOIN LATERAL (SELECT count(*) AS active_runs FROM agent_task_queue tWHERE t.context->>'wakeup_id'=w.id::text AND t.issue_id=w.issue_id AND t.agent_id=w.agent_idAND t.status IN ('queued','deferred','dispatched','running','waiting_local_directory')) r ON true- WHERE w.workspace_id= @workspace_id+ WHERE w.workspace_id= @workspace_id AND w.system_rule IS NULL+ UNION ALL+ -- The child-done system rule of each open parent that still waits for a+ -- sub-issue: every child when unstaged, else its lowest unfinished stage.+ -- Its target is the parent's assignee (a squad's leader) at the moment.+ SELECT w.id,w.issue_id,p.title,ws.issue_prefix||'-'||p.number,+ COALESCE(ta.id,leader.id),COALESCE(ta.name,leader.name,''),w.kind,w.mode,w.event_types,NULL::text,+ NULL::uuid,''::text,NULL::uuid,NULL::text,NULL::uuid,+ NULL::bigint,NULL::text,w.timezone,+ NULL::timestamptz,w.enabled,w.revision,w.disabled_at,w.last_task_id,w.last_error,w.created_at,+ NULL::timestamptz,NULL::bigint,NULL::text,NULL::timestamptz,+ w.condition,w.max_fires,w.fire_count,w.paused_reason,+ false,NULL::text,+ NULL::uuid,NULL::text,+ false,true,COALESCE(sr.active_runs,0)::int,+ 'system',w.system_rule,ch.stage,p.assignee_type,ch.remaining+ FROM issue_wakeup w+ JOIN issue p ON p.id=w.issue_id AND p.workspace_id=w.workspace_id+ JOIN workspace ws ON ws.id=p.workspace_id+ LEFT JOIN agent ta ON p.assignee_type='agent' AND ta.id=p.assignee_id AND ta.workspace_id=p.workspace_id+ LEFT JOIN squad sq ON p.assignee_type='squad' AND sq.id=p.assignee_id AND sq.workspace_id=p.workspace_id+ LEFT JOIN agent leader ON leader.id=sq.leader_id AND leader.workspace_id=p.workspace_id+ CROSS JOIN LATERAL (+ SELECT bool_or(ci.stage IS NOT NULL) AS staged,+ min(ci.stage) FILTER(WHERE ci.stage IS NOT NULL AND NOT (ci.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status cs WHERE cs.workspace_id=ci.workspace_id AND cs.key=ci.status AND cs.category IN ('done','closed')))) AS stage,+ count(*) FILTER(WHERE NOT (ci.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status cs WHERE cs.workspace_id=ci.workspace_id AND cs.key=ci.status AND cs.category IN ('done','closed')))) AS open_count+ FROM issue ci WHERE ci.parent_issue_id=p.id AND ci.workspace_id=p.workspace_id+ ) agg+ CROSS JOIN LATERAL (+ SELECT (CASE WHEN agg.staged THEN agg.stage END)::int AS stage,+ (CASE WHEN agg.staged AND agg.stage IS NOT NULL THEN (SELECT count(*) FROM issue ci WHERE ci.parent_issue_id=p.id AND ci.workspace_id=p.workspace_id+ AND ci.stage=agg.stage AND NOT (ci.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status cs WHERE cs.workspace_id=ci.workspace_id AND cs.key=ci.status AND cs.category IN ('done','closed')))) ELSE agg.open_count END)::int AS remaining+ ) ch+ LEFT JOIN LATERAL (+ SELECT count(*) AS active_runs FROM agent_task_queue t+ WHERE t.context->>'wakeup_id'=w.id::text AND t.issue_id=w.issue_id+ AND t.status IN ('queued','deferred','dispatched','running','waiting_local_directory')+ ) sr ON true+ WHERE w.workspace_id= @workspace_id AND w.system_rule IS NOT NULL AND agg.open_count>0+ AND p.status NOT IN ('done','cancelled')+ AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=p.workspace_id AND s.key=p.status AND s.category IN ('done','closed'))), classified AS (SELECT *,CASE WHEN (enabled AND NOT issue_closed) OR active_runs>0 THEN 'active'- WHEN NOT issue_closed AND disabled_at IS NOT NULL THEN 'disabled' ELSE 'ended' END AS scope+ WHEN NOT issue_closed AND paused_reason IS NOT NULL THEN 'paused'+ WHEN NOT issue_closed AND (disabled_at IS NOT NULL OR source='system') THEN 'disabled' ELSE 'ended' END AS scopeFROM base), filtered AS (SELECT * FROM classified WHERE (@scope::text='all' OR scope= @scope)AND (@kind::text='all' OR (@kind='event' AND kind='event') OR (@kind='at' AND kind='at') OR (@kind='recurring' AND kind IN ('every','cron')))+ AND (@source::text='' OR source= @source)AND (@agent_id::text='' OR agent_id::text= @agent_id)AND (@search::text='' OR strpos(lower(issue_title||' '||issue_identifier||' '||agent_name),lower(@search))>0)), page AS (SELECT * FROM filtered ORDER BY created_at DESC,id DESC LIMIT @page_limit::int OFFSET @page_offset::int), details AS (SELECT p.*,r.status AS last_task_status,+ (SELECT count(*) FROM agent_task_queue t7 WHERE t7.context->>'wakeup_id'=p.id::text AND t7.issue_id=p.issue_id+ AND t7.created_at>now()-interval '7 days')::int AS runs_7d,CASE WHEN r.id IS NOT NULL THEN jsonb_build_object('id',r.id,'agent_id',r.agent_id,'runtime_id',r.runtime_id,'issue_id',r.issue_id,'wakeup_id',p.id,'status',r.status,'priority',r.priority,'created_at',r.created_at,'started_at',r.started_at,@@ -50,12 +103,12 @@ LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_idLEFT JOIN LATERAL (SELECT candidate.* FROM ((SELECT t.id,t.agent_id,t.runtime_id,t.issue_id,t.status,t.priority,t.created_at,t.started_at,t.dispatched_at,t.completed_at,1 AS active- FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND t.agent_id=p.agent_id+ FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND (p.source='system' OR t.agent_id=p.agent_id)AND t.status IN ('queued','deferred','dispatched','running','waiting_local_directory')ORDER BY (t.status IN ('running','waiting_local_directory','dispatched')) DESC,t.created_at DESC,t.id DESC LIMIT 1)UNION ALL(SELECT t.id,t.agent_id,t.runtime_id,t.issue_id,t.status,t.priority,t.created_at,t.started_at,t.dispatched_at,t.completed_at,0 AS active- FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND t.agent_id=p.agent_id+ FROM agent_task_queue t WHERE t.context->>'wakeup_id'=p.id::text AND t.issue_id=p.issue_id AND (p.source='system' OR t.agent_id=p.agent_id)AND t.status NOT IN ('queued','deferred','dispatched','running','waiting_local_directory')ORDER BY t.created_at DESC,t.id DESC LIMIT 1)) candidate ORDER BY active DESC LIMIT 1@@ -65,6 +118,7 @@ SELECT jsonb_build_object('items',COALESCE((SELECT jsonb_agg(to_jsonb(details)-'created_at'-'scope' ORDER BY created_at DESC,id DESC) FROM details),'[]'::jsonb),'total',(SELECT count(*) FROM filtered),'counts',jsonb_build_object('all',(SELECT count(*) FROM classified),'active',(SELECT count(*) FROM classified WHERE scope='active'),+ 'paused',(SELECT count(*) FROM classified WHERE scope='paused'),'disabled',(SELECT count(*) FROM classified WHERE scope='disabled'),'ended',(SELECT count(*) FROM classified WHERE scope='ended')),- 'agents',COALESCE((SELECT jsonb_agg(x ORDER BY x.name,x.id) FROM (SELECT DISTINCT agent_id AS id,agent_name AS name FROM base) x),'[]'::jsonb)+ 'agents',COALESCE((SELECT jsonb_agg(x ORDER BY x.name,x.id) FROM (SELECT DISTINCT agent_id AS id,agent_name AS name FROM base WHERE agent_id IS NOT NULL) x),'[]'::jsonb)) AS result;diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex d1acdb2dfb..30f25bb67a 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -61,6 +61,11 @@ const (// work, so such a daemon keeps getting a fresh directory and the parent's// stays untouched on disk.DaemonCapabilityCheckoutKeepsWorkV1 = "checkout-keeps-work-v1"+ // DaemonCapabilityJoinedWakeupsV1 advertises that the daemon renders the+ // claim's wakeup_joined field into the prompt. Only such a claim takes+ // along the inputs of wakeup rules that waited for this run; for any other+ // daemon those rules keep their inputs and start a run of their own.+ DaemonCapabilityJoinedWakeupsV1 = "joined-wakeups-v1"// DaemonCapabilityTaskSupplementV1 advertises that this provider run can accept// an additional text instruction without cancelling or starting a task.// It is persisted when this exact task enters running; absence always meansdiff --git a/server/sqlc.yaml b/server/sqlc.yamlindex f4dedb1b16..22e074281d 100644--- a/server/sqlc.yaml+++ b/server/sqlc.yaml@@ -10,3 +10,7 @@ sql:sql_package: "pgx/v5"emit_json_tags: trueemit_empty_slices: true+ overrides:+ - column: "issue_wakeup.condition"+ go_type: "encoding/json.RawMessage"+ nullable: true