Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): keep the runtime brief byte-stable across triggers (MUL-5377) (#6021)
Bohan Jiang4eb80c8b773e
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex f9dd55869c..f253ac0f55 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -3917,8 +3917,11 @@ func gateResumeToReusedWorkdir(task *Task, taskCtx *execenv.TaskContextForEnv, etask.PriorSessionID = ""taskCtx.PriorSessionResumed = false// The user expected this run to continue the prior conversation; surface- // the loss in the brief instead of silently restarting (MUL-4424).+ // the loss instead of silently restarting (MUL-4424). Set it on BOTH+ // carriers: the notice is rendered from `task` by BuildPrompt (MUL-5377+ // moved it out of the brief), while taskCtx still drives execenv.taskCtx.PriorSessionResumeUnavailable = true+ task.PriorSessionResumeUnavailable = true}return reused}@@ -4018,8 +4021,11 @@ func gateCodexResumeToRolloutPresence(task *Task, taskCtx *execenv.TaskContextFotask.PriorSessionID = ""taskCtx.PriorSessionResumed = false// The user expected this run to continue the prior conversation; surface the- // loss in the brief instead of silently restarting (MUL-4424).+ // loss instead of silently restarting (MUL-4424). Set it on BOTH carriers:+ // the notice is rendered from `task` by BuildPrompt (MUL-5377 moved it out+ // of the brief), while taskCtx still drives execenv.taskCtx.PriorSessionResumeUnavailable = true+ task.PriorSessionResumeUnavailable = true}const (diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex b84e8b8e08..5579f58dc3 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -4600,23 +4600,11 @@ func TestBuildMetaSkillContentOmitsRequestingUserWhenEmpty(t *testing.T) {}}-// TestBuildMetaSkillContentEmitsTaskInitiatorMember pins MUL-2645's brief-// contract: when the task resolves to a member initiator, the brief gains a-// `## Task Initiator` block naming that person (with email) and stating the-// privacy boundary — the agent's credentials stay owner-scoped. This is what-// lets a workspace-visible, multi-user agent tell who is actually asking-// rather than seeing every requester as the runtime owner.-func TestBuildMetaSkillContentEmitsTaskInitiatorMember(t *testing.T) {+// Task Initiator moved to the per-turn prompt (MUL-5377): the initiator+// changes whenever a different person comments on the same issue.+func TestTaskInitiatorBlockMember(t *testing.T) {t.Parallel()- content := buildMetaSkillContent("claude", TaskContextForEnv{- IssueID: "issue-1",- AgentName: "Lambda",- AgentID: "agent-1",- InitiatorType: "member",- InitiatorID: "user-123",- InitiatorName: "Bohan",- InitiatorEmail: "[email protected]",- })+ block := BuildTaskInitiatorBlock("member", "Bohan", "[email protected]")for _, want := range []string{"## Task Initiator",@@ -4624,39 +4612,37 @@ func TestBuildMetaSkillContentEmitsTaskInitiatorMember(t *testing.T) {"apply any per-person privacy or access rules","credentials stay scoped to the runtime owner",} {- if !strings.Contains(content, want) {- t.Errorf("expected brief to contain %q\n---\n%s", want, content)+ if !strings.Contains(block, want) {+ t.Errorf("expected initiator block to contain %q\n---\n%s", want, block)}}+ if BuildTaskInitiatorBlock("member", "", "") != "" {+ t.Error("no initiator name must render nothing")+ }- // Initiator sits after Requesting User and before Available Commands so the- // agent reads "who am I" → "whose context" → "who is asking now" → commands.- initiatorIdx := strings.Index(content, "## Task Initiator")- commandsIdx := strings.Index(content, "## Available Commands")- if !(initiatorIdx >= 0 && initiatorIdx < commandsIdx) {- t.Errorf("section order wrong: initiator=%d commands=%d", initiatorIdx, commandsIdx)+ content := buildMetaSkillContent("claude", TaskContextForEnv{+ IssueID: "issue-1",+ AgentName: "Lambda",+ AgentID: "agent-1",+ InitiatorType: "member",+ InitiatorID: "user-123",+ InitiatorName: "Bohan",+ InitiatorEmail: "[email protected]",+ })+ if strings.Contains(content, "## Task Initiator") {+ t.Errorf("brief must not carry Task Initiator — it is per-run state (MUL-5377)\n---\n%s", content)}}-// TestBuildMetaSkillContentEmitsTaskInitiatorAgent covers an agent-initiated-// task (another agent @mentioned this one): the block names the agent and-// carries no email, since agents have no address.-func TestBuildMetaSkillContentEmitsTaskInitiatorAgent(t *testing.T) {+func TestTaskInitiatorBlockAgent(t *testing.T) {t.Parallel()- content := buildMetaSkillContent("claude", TaskContextForEnv{- IssueID: "issue-1",- AgentName: "Lambda",- AgentID: "agent-1",- InitiatorType: "agent",- InitiatorID: "agent-9",- InitiatorName: "GPT-Boy",- })+ block := BuildTaskInitiatorBlock("agent", "GPT-Boy", "")- if !strings.Contains(content, "initiated by **GPT-Boy**, another agent in this workspace") {- t.Errorf("expected agent-initiator phrasing\n---\n%s", content)+ if !strings.Contains(block, "initiated by **GPT-Boy**, another agent in this workspace") {+ t.Errorf("expected agent-initiator phrasing\n---\n%s", block)}- if strings.Contains(content, "a member of this workspace") {- t.Errorf("agent initiator must not be described as a member\n---\n%s", content)+ if strings.Contains(block, "a member of this workspace") {+ t.Errorf("agent initiator must not be described as a member\n---\n%s", block)}}@@ -4722,14 +4708,9 @@ func TestSanitizeEmailForBrief(t *testing.T) {}}-// TestInjectRuntimeConfigCommentTriggerColdStartRead checks the-// comment-triggered Workflow on cold start (no prior run): it points the agent-// at the triggering thread (--thread <trigger> --tail 30) instead of the flat-// dump and with no since-delta hint, while the Available Commands core line-// still surfaces the thread/recent/cursor flags so they remain discoverable for-// CLI use even though the verbose cursor walkthrough was dropped from the-// workflow steps.-func TestInjectRuntimeConfigCommentTriggerColdStartRead(t *testing.T) {+// The brief carries the static catch-up read and the CLI flag discovery+// point; the per-run thread routing lives in the per-turn prompt (MUL-5377).+func TestInjectRuntimeConfigBriefKeepsStaticCatchUpRead(t *testing.T) {t.Parallel()const (@@ -4737,11 +4718,10 @@ func TestInjectRuntimeConfigCommentTriggerColdStartRead(t *testing.T) {triggerID = "trigger-comment-1")dir := t.TempDir()- ctx := TaskContextForEnv{+ if _, err := InjectRuntimeConfig(dir, "claude", TaskContextForEnv{IssueID: issueID,TriggerCommentID: triggerID,- }- if _, err := InjectRuntimeConfig(dir, "claude", ctx); err != nil {+ }); err != nil {t.Fatalf("InjectRuntimeConfig failed: %v", err)}data, err := os.ReadFile(filepath.Join(dir, "CLAUDE.md"))@@ -4750,55 +4730,34 @@ func TestInjectRuntimeConfigCommentTriggerColdStartRead(t *testing.T) {}s := string(data)- // Cold start (no prior run) → read the triggering thread, not the flat dump,- // and no since-delta hint.- for _, want := range []string{- "Read the triggering conversation first",- "multica issue comment list " + issueID + " --thread " + triggerID + " --tail 30 --output json",- "multica issue comment list " + issueID + " --recent 10 --output json",- } {- if !strings.Contains(s, want) {- t.Errorf("comment-triggered Workflow missing cold-start read %q\n---\n%s", want, s)- }+ if !strings.Contains(s, "multica issue comment list "+issueID+" --recent 10 --output json") {+ t.Errorf("brief must keep the static catch-up read\n---\n%s", s)}if strings.Contains(s, "--recent 20") {- t.Errorf("comment-triggered Workflow still uses recent 20\n---\n%s", s)+ t.Errorf("brief still uses recent 20\n---\n%s", s)+ }+ if strings.Contains(s, triggerID) {+ t.Errorf("brief must not carry the trigger comment id (MUL-5377)\n---\n%s", s)}if strings.Contains(s, "new comment(s) since your last run") {- t.Errorf("cold-start workflow must not render the since-delta hint\n---\n%s", s)+ t.Errorf("brief must not render a since-delta hint\n---\n%s", s)}- // Available Commands core line must surface the new flags (this is the- // single discovery point for non-workflow CLI use cases).+ // Available Commands stays the single discovery point for the flags.for _, want := range []string{"[--thread <comment-id>","--tail N","--recent N",- "Next reply cursor",- "Next thread cursor",} {if !strings.Contains(s, want) {- t.Errorf("Available Commands core line missing %q\n---\n%s", want, s)+ t.Errorf("Available Commands missing flag documentation %q\n---\n%s", want, s)}}-- // The legacy step-2 phrasing this PR replaces must not regress.- if strings.Contains(s, "read the conversation (returns all comments, capped server-side at 2000)") {- t.Errorf("comment-triggered Workflow still carries the legacy full-dump phrasing\n---\n%s", s)- }- // The pre-MUL-2421 unbounded `--thread` recipe (no --tail) is also a- // regression target: it dumps the entire thread on long threads.- if strings.Contains(s, "multica issue comment list "+issueID+" --thread "+triggerID+" --output json") {- t.Errorf("comment-triggered Workflow regressed to unbounded --thread recipe (no --tail) — long threads will overflow context\n---\n%s", s)- }}-// TestInjectRuntimeConfigCommentTriggerResumedNoDeltaRead checks the-// comment-triggered Workflow when the daemon is resuming a prior session and no-// since-delta hint is present. In that shape, the agent already has session-// context and the trigger body is injected in the per-turn prompt, so the-// runtime brief must not force a duplicate thread read.-func TestInjectRuntimeConfigCommentTriggerResumedNoDeltaRead(t *testing.T) {+// Resumed/no-delta routing lives in the per-turn prompt (MUL-5377); pin the+// helper that renders it and assert the brief stays clean.+func TestInjectRuntimeConfigBriefOmitsResumedThreadAnchor(t *testing.T) {t.Parallel()const (@@ -4806,13 +4765,12 @@ func TestInjectRuntimeConfigCommentTriggerResumedNoDeltaRead(t *testing.T) {triggerID = "trigger-comment-1")dir := t.TempDir()- ctx := TaskContextForEnv{+ if _, err := InjectRuntimeConfig(dir, "claude", TaskContextForEnv{IssueID: issueID,TriggerCommentID: triggerID,TriggerThreadID: "thread-root-1",PriorSessionResumed: true,- }- if _, err := InjectRuntimeConfig(dir, "claude", ctx); err != nil {+ }); err != nil {t.Fatalf("InjectRuntimeConfig failed: %v", err)}data, err := os.ReadFile(filepath.Join(dir, "CLAUDE.md"))@@ -4821,6 +4779,13 @@ func TestInjectRuntimeConfigCommentTriggerResumedNoDeltaRead(t *testing.T) {}s := string(data)+ for _, banned := range []string{triggerID, "thread-root-1", "triggering comment is already included above"} {+ if strings.Contains(s, banned) {+ t.Errorf("brief must not carry per-run resume routing %q (MUL-5377)\n---\n%s", banned, s)+ }+ }++ hint := BuildResumedCommentsHint(issueID, triggerID, "thread-root-1")for _, want := range []string{"triggering comment is already included above","No other new comments on this issue since your last run",@@ -4829,16 +4794,10 @@ func TestInjectRuntimeConfigCommentTriggerResumedNoDeltaRead(t *testing.T) {"do not rely only on resumed session memory","multica issue comment list " + issueID + " --thread thread-root-1 --tail 30 --output json",} {- if !strings.Contains(s, want) {- t.Errorf("comment-triggered resumed Workflow missing %q\n---\n%s", want, s)+ if !strings.Contains(hint, want) {+ t.Errorf("resumed hint missing %q\n---\n%s", want, hint)}}- if strings.Contains(s, "scoped to the triggering thread") {- t.Errorf("resumed Workflow must not claim the delta is thread-scoped\n---\n%s", s)- }- if strings.Contains(s, "Read the triggering conversation first") {- t.Errorf("resumed workflow must not force the cold-start thread read\n---\n%s", s)- }}// TestInjectRuntimeConfigAssignmentTriggerMentionsRecent pins that the@@ -5142,10 +5101,10 @@ func TestInjectRuntimeConfigIssueMetadataCodexFormattingUnchanged(t *testing.T)if !strings.Contains(s, "always write the comment body to a UTF-8 file with your file-write tool first, then post it with `--content-file <path>`") {t.Fatalf("codex linux --content-file rule missing\n---\n%s", s)}- // ...AND the per-turn reply instruction still points at this- // turn's trigger comment id.- if !strings.Contains(s, "--parent comment-md-codex") {- t.Fatalf("reply instruction lost trigger comment id\n---\n%s", s)+ // ...AND the brief does NOT carry this turn's trigger comment id:+ // it moved to the per-turn user message (MUL-5377).+ if strings.Contains(s, "comment-md-codex") {+ t.Fatalf("brief must not carry the trigger comment id\n---\n%s", s)}})diff --git a/server/internal/daemon/execenv/reply_instructions_test.go b/server/internal/daemon/execenv/reply_instructions_test.goindex 2698fcffdc..f24731f2f0 100644--- a/server/internal/daemon/execenv/reply_instructions_test.go+++ b/server/internal/daemon/execenv/reply_instructions_test.go@@ -170,103 +170,72 @@ func TestBuildCommentReplyInstructionsEmptyWhenNoTrigger(t *testing.T) {}}-// Pins runtimeGOOS to "linux" so the helper output is deterministic.-// Provider is "claude" — exercises the non-codex inline path through-// InjectRuntimeConfig end-to-end. Not parallel: mutates runtimeGOOS.-func TestInjectRuntimeConfigCommentTriggerUsesHelper(t *testing.T) {+// The brief must never carry this turn's trigger comment id; it points the+// agent at the per-turn user message instead (MUL-5377).+func TestInjectRuntimeConfigKeepsTriggerCommentOutOfBrief(t *testing.T) {saved := runtimeGOOSt.Cleanup(func() { runtimeGOOS = saved })runtimeGOOS = "linux"dir := t.TempDir()-issueID := "11111111-1111-1111-1111-111111111111"triggerID := "22222222-2222-2222-2222-222222222222"- ctx := TaskContextForEnv{+ if _, err := InjectRuntimeConfig(dir, "claude", TaskContextForEnv{IssueID: issueID,TriggerCommentID: triggerID,- }- if _, err := InjectRuntimeConfig(dir, "claude", ctx); err != nil {+ }); err != nil {t.Fatalf("InjectRuntimeConfig failed: %v", err)}-content, err := os.ReadFile(filepath.Join(dir, "CLAUDE.md"))if err != nil {t.Fatalf("read CLAUDE.md: %v", err)}-s := string(content)++ if strings.Contains(s, triggerID) {+ t.Errorf("CLAUDE.md must not carry the trigger comment id (MUL-5377)\n---\n%s", s)+ }for _, want := range []string{- triggerID,- "multica issue comment add " + issueID + " --parent " + triggerID,- "do NOT reuse --parent values from previous turns",+ "Mode router",+ "`Turn mode: Reply.`",+ "`Turn mode: Ownership.`",+ "Use the `--parent` value the per-turn user message gives you for this turn",+ "do NOT reuse a `--parent` from an earlier turn in this session",} {if !strings.Contains(s, want) {- t.Errorf("CLAUDE.md missing %q", want)+ t.Errorf("CLAUDE.md missing %q\n---\n%s", want, s)}}}-// TestInjectRuntimeConfigWindowsCommentTriggerHasNoStdin asserts the-// end-to-end CLAUDE.md / AGENTS.md surface for a comment-triggered task on-// a Windows daemon — across Codex and non-Codex providers — has no-// prescriptive `--content-stdin` directive that could steer the agent at-// the broken Windows pipe path.-//-// Not parallel: mutates the package-level runtimeGOOS.-func TestInjectRuntimeConfigWindowsCommentTriggerHasNoStdin(t *testing.T) {+// Windows reply instructions are file-first, never stdin. The instructions+// now ship in the per-turn prompt, so pin the helper directly (MUL-5377).+func TestWindowsCommentReplyInstructionsHaveNoStdin(t *testing.T) {saved := runtimeGOOSt.Cleanup(func() { runtimeGOOS = saved })runtimeGOOS = "windows"issueID := "11111111-1111-1111-1111-111111111111"triggerID := "22222222-2222-2222-2222-222222222222"- ctx := TaskContextForEnv{- IssueID: issueID,- TriggerCommentID: triggerID,- }for _, provider := range []string{"claude", "codex", "opencode"} {t.Run(provider, func(t *testing.T) {- dir := t.TempDir()- if _, err := InjectRuntimeConfig(dir, provider, ctx); err != nil {- t.Fatalf("InjectRuntimeConfig failed: %v", err)- }- fileName := "CLAUDE.md"- if provider != "claude" {- fileName = "AGENTS.md"- }- data, err := os.ReadFile(filepath.Join(dir, fileName))- if err != nil {- t.Fatalf("read %s: %v", fileName, err)- }- s := string(data)-+ s := BuildCommentReplyInstructions(provider, issueID, triggerID)for _, want := range []string{"multica issue comment add " + issueID + " --parent " + triggerID + " --content-file","--content-file",- "On Windows, write the reply body to a UTF-8 file",} {if !strings.Contains(s, want) {- t.Errorf("%s missing %q\n---\n%s", fileName, want, s)+ t.Errorf("%s reply instructions missing %q\n---\n%s", provider, want, s)}}-- // Prescriptive stdin directives must NOT appear anywhere in- // the Windows surface. Pin sentence-level substrings (not- // bare flag names) so anti-prescriptive prose like "do NOT- // pipe via `--content-stdin`" doesn't trip the ban.for _, banned := range []string{"--parent " + triggerID + " --content-stdin","always use `--content-stdin` with a HEREDOC, even for short single-line replies",- "MUST pipe via stdin",- "use `--description-stdin` and pipe a HEREDOC",- "<<'COMMENT'",- "Agent-authored comments should always pipe content via stdin",} {if strings.Contains(s, banned) {- t.Errorf("%s still steers agent at stdin: %q\n---\n%s", fileName, banned, s)+ t.Errorf("%s reply instructions must not prescribe stdin on Windows: %q\n---\n%s", provider, banned, s)}}})diff --git a/server/internal/daemon/execenv/runtime_config_kind.go b/server/internal/daemon/execenv/runtime_config_kind.goindex 435ecbc6aa..bca9eccf08 100644--- a/server/internal/daemon/execenv/runtime_config_kind.go+++ b/server/internal/daemon/execenv/runtime_config_kind.go@@ -6,17 +6,24 @@ package execenv// flag that once gated it against a legacy verbose brief was retired in// MUL-4297, so this is now the only brief).//-// Five kinds, mutually exclusive in practice. classifyTask documents the+// Four kinds, mutually exclusive in practice. classifyTask documents the// tiebreak rule that applies if a future caller accidentally violates the// mutex.type taskKind intconst (- // kindCommentTriggered: a NEW comment on an issue triggered this run.- kindCommentTriggered taskKind = iota- // kindAssignmentTriggered: an assignee was set / changed on an issue- // and the daemon fired a fresh run for the new assignee.- kindAssignmentTriggered+ // kindIssue: this run operates on a real Multica issue. It deliberately+ // does NOT distinguish comment-triggered from assignment-triggered runs.+ //+ // Those were two kinds until MUL-5377. Splitting them made the rendered+ // brief — which Claude Code loads into messages[0], ahead of the entire+ // conversation — differ between the first (on-assign) run and every+ // later (comment) run on the same resumed session, which invalidated the+ // prompt cache for the whole history on every resume. Which trigger+ // fired THIS turn is per-turn state and now travels in the per-turn user+ // message (daemon.BuildPrompt), which is appended after the cached+ // prefix. See runtime_config_sections.go:writeWorkflowIssue.+ kindIssue taskKind = iota// kindAutopilotRunOnly: an autopilot fired in run-only mode (no// issue created or attached).kindAutopilotRunOnly@@ -30,8 +37,11 @@ const (// classifyTask maps a TaskContextForEnv to the single taskKind the slim// brief should be assembled for. Precedence (documented for the tiebreak// case, although the daemon never sets two specific-kind flags at once):-// chat → quick-create → autopilot run-only → comment-triggered →-// assignment-triggered.+// chat → quick-create → autopilot run-only → issue.+//+// Deliberately does not read ctx.TriggerCommentID: the classification must+// not vary across runs of the same resumed session, or the brief's bytes+// change and the prompt cache is lost from messages[0] onward (MUL-5377).func classifyTask(ctx TaskContextForEnv) taskKind {switch {case ctx.ChatSessionID != "":@@ -40,10 +50,8 @@ func classifyTask(ctx TaskContextForEnv) taskKind {return kindQuickCreatecase ctx.AutopilotRunID != "":return kindAutopilotRunOnly- case ctx.TriggerCommentID != "":- return kindCommentTriggereddefault:- return kindAssignmentTriggered+ return kindIssue}}@@ -57,14 +65,9 @@ func classifyTask(ctx TaskContextForEnv) taskKind {// Both are meaningless on the issue-less kinds (chat / quick-create /// autopilot run-only) and would either render an empty body or steer the// agent into a guaranteed-failed CLI call. Note this is a kind-based-// predicate, not a check on ctx.IssueID — comment- / assignment-triggered-// kinds always carry an issue id by construction (the daemon refuses to-// dispatch them otherwise), and the other three kinds never do.+// predicate, not a check on ctx.IssueID — kindIssue always carries an issue+// id by construction (the daemon refuses to dispatch it otherwise), and the+// other three kinds never do.func (k taskKind) hasIssueContext() bool {- switch k {- case kindCommentTriggered, kindAssignmentTriggered:- return true- default:- return false- }+ return k == kindIssue}diff --git a/server/internal/daemon/execenv/runtime_config_kind_test.go b/server/internal/daemon/execenv/runtime_config_kind_test.goindex d8c5d841ce..93d346e261 100644--- a/server/internal/daemon/execenv/runtime_config_kind_test.go+++ b/server/internal/daemon/execenv/runtime_config_kind_test.go@@ -5,7 +5,7 @@ import ("testing")-// TestClassifyTask pins the precedence rule on classifyTask. All five+// TestClassifyTask pins the precedence rule on classifyTask. All four// kinds plus tiebreak cases for safety.func TestClassifyTask(t *testing.T) {t.Parallel()@@ -17,9 +17,9 @@ func TestClassifyTask(t *testing.T) {{"chat", TaskContextForEnv{ChatSessionID: "c"}, kindChat},{"quick-create", TaskContextForEnv{QuickCreatePrompt: "p"}, kindQuickCreate},{"autopilot", TaskContextForEnv{AutopilotRunID: "r"}, kindAutopilotRunOnly},- {"comment-triggered", TaskContextForEnv{IssueID: "i", TriggerCommentID: "c"}, kindCommentTriggered},- {"assignment-triggered", TaskContextForEnv{IssueID: "i"}, kindAssignmentTriggered},- {"assignment-bare", TaskContextForEnv{}, kindAssignmentTriggered},+ {"issue-comment-triggered", TaskContextForEnv{IssueID: "i", TriggerCommentID: "c"}, kindIssue},+ {"issue-assignment-triggered", TaskContextForEnv{IssueID: "i"}, kindIssue},+ {"issue-bare", TaskContextForEnv{}, kindIssue},{"tiebreak-chat-vs-quick", TaskContextForEnv{ChatSessionID: "c", QuickCreatePrompt: "p"}, kindChat},{"tiebreak-quick-vs-autopilot", TaskContextForEnv{QuickCreatePrompt: "p", AutopilotRunID: "r"}, kindQuickCreate},{"tiebreak-autopilot-vs-comment", TaskContextForEnv{AutopilotRunID: "r", IssueID: "i", TriggerCommentID: "c"}, kindAutopilotRunOnly},@@ -43,8 +43,7 @@ func TestTaskKindHasIssueContext(t *testing.T) {kind taskKindwant bool}{- {kindCommentTriggered, true},- {kindAssignmentTriggered, true},+ {kindIssue, true},{kindAutopilotRunOnly, false},{kindQuickCreate, false},{kindChat, false},@@ -92,12 +91,10 @@ func TestBuildMetaSkillContentSlimKindMatrix(t *testing.T) {mustHave map[taskKind]bool}allKinds := map[taskKind]bool{- kindCommentTriggered: true, kindAssignmentTriggered: true,- kindAutopilotRunOnly: true, kindQuickCreate: true, kindChat: true,- }- issueKinds := map[taskKind]bool{- kindCommentTriggered: true, kindAssignmentTriggered: true,+ kindIssue: true, kindAutopilotRunOnly: true,+ kindQuickCreate: true, kindChat: true,}+ issueKinds := map[taskKind]bool{kindIssue: true}checks := []sectionCheck{{"# Multica Agent Runtime", allKinds},{"## Background Task Safety", allKinds},@@ -108,15 +105,13 @@ func TestBuildMetaSkillContentSlimKindMatrix(t *testing.T) {{"## Output", allKinds},{"## Comment Formatting", issueKinds},{"## Repositories", map[taskKind]bool{- kindCommentTriggered: true, kindAssignmentTriggered: true,- kindAutopilotRunOnly: true, kindChat: true,+ kindIssue: true, kindAutopilotRunOnly: true, kindChat: true,}},{"## Issue Metadata", issueKinds},- {"## Instruction Precedence", map[taskKind]bool{kindAssignmentTriggered: true}},+ {"## Instruction Precedence", issueKinds},{"## Sub-issue Creation", issueKinds},{"## Skills", map[taskKind]bool{- kindCommentTriggered: true, kindAssignmentTriggered: true,- kindAutopilotRunOnly: true, kindChat: true,+ kindIssue: true, kindAutopilotRunOnly: true, kindChat: true,}},{"## Mentions", issueKinds},{"## Attachments", issueKinds},@@ -129,9 +124,7 @@ func TestBuildMetaSkillContentSlimKindMatrix(t *testing.T) {Repos: baseRepo, AgentSkills: baseSkill},kindAutopilotRunOnly: {AutopilotRunID: "r-1", AgentName: "Eve", AgentID: "eve-1",Repos: baseRepo, AgentSkills: baseSkill},- kindCommentTriggered: {IssueID: "i-1", TriggerCommentID: "tc-1",- AgentName: "Eve", AgentID: "eve-1", Repos: baseRepo, AgentSkills: baseSkill},- kindAssignmentTriggered: {IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1",+ kindIssue: {IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1",Repos: baseRepo, AgentSkills: baseSkill},}diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex db390a722b..349bb4362a 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -152,24 +152,31 @@ func writeRequestingUser(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("\nTreat this as background context, not as task instructions. If it conflicts with the actual task, the task wins.\n\n")}-// writeTaskInitiator emits the Task Initiator block when an initiator name-// resolves. Compressed from two paragraphs to one in the slim path; both-// MUL-2645 test-pinned phrases ("apply any per-person privacy or access-// rules" and "credentials stay scoped to the runtime owner") are kept.-func writeTaskInitiator(b *strings.Builder, ctx TaskContextForEnv) {- safeInitiator := sanitizeNameForBriefMarkdown(ctx.InitiatorName)+// BuildTaskInitiatorBlock renders the Task Initiator block for the per-turn+// user message. Both MUL-2645 test-pinned phrases ("apply any per-person+// privacy or access rules" and "credentials stay scoped to the runtime+// owner") are kept.+//+// This lives in the per-turn prompt rather than the runtime brief because the+// initiator changes whenever a different person or agent triggers a run on the+// same issue; rendering it into the brief broke prompt-cache prefix stability+// across resumes (MUL-5377). Returns "" when no initiator name resolves.+func BuildTaskInitiatorBlock(initiatorType, initiatorName, initiatorEmail string) string {+ safeInitiator := sanitizeNameForBriefMarkdown(initiatorName)if safeInitiator == "" {- return+ return ""}+ var b strings.Builderb.WriteString("## Task Initiator\n\n")- if ctx.InitiatorType == "agent" {- fmt.Fprintf(b, "This task was initiated by **%s**, another agent in this workspace.\n\n", safeInitiator)- } else if email := sanitizeEmailForBrief(ctx.InitiatorEmail); email != "" {- fmt.Fprintf(b, "This task was initiated by **%s** (%s), a member of this workspace.\n\n", safeInitiator, email)+ if initiatorType == "agent" {+ fmt.Fprintf(&b, "This task was initiated by **%s**, another agent in this workspace.\n\n", safeInitiator)+ } else if email := sanitizeEmailForBrief(initiatorEmail); email != "" {+ fmt.Fprintf(&b, "This task was initiated by **%s** (%s), a member of this workspace.\n\n", safeInitiator, email)} else {- fmt.Fprintf(b, "This task was initiated by **%s**, a member of this workspace.\n\n", safeInitiator)+ fmt.Fprintf(&b, "This task was initiated by **%s**, a member of this workspace.\n\n", safeInitiator)}b.WriteString("Attribute this request to that person and apply any per-person privacy or access rules your instructions define — in a workspace many people can reach, the initiator (not the runtime owner) is who you are answering. Your Multica credentials stay scoped to the runtime owner, so this attribution does not widen what you can read or write — do not assume the initiator can see everything you can.\n\n")+ return b.String()}// writeWorkspaceContext emits the workspace-level system prompt configured@@ -184,12 +191,18 @@ func writeWorkspaceContext(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("\n\n")}-func writeConnectedApps(b *strings.Builder, ctx TaskContextForEnv) {- if len(ctx.ConnectedApps) == 0 {- return+// BuildConnectedAppsBlock renders the Connected Apps block for the per-turn+// user message. The app set is per-run state (runtime MCP overlays are+// resolved at enqueue time), so it cannot live in the runtime brief without+// breaking prompt-cache prefix stability across resumes (MUL-5377).+// Returns "" when no app resolves.+func BuildConnectedAppsBlock(apps []runtimeapps.ConnectedApp) string {+ if len(apps) == 0 {+ return ""}+ var b strings.Buildervar lines strings.Builder- for _, app := range ctx.ConnectedApps {+ for _, app := range apps {serverName := sanitizeBriefCodeToken(app.ServerName)toolkitSlug := sanitizeBriefCodeToken(app.ToolkitSlug)if serverName == "" || toolkitSlug == "" {@@ -205,11 +218,12 @@ func writeConnectedApps(b *strings.Builder, ctx TaskContextForEnv) {fmt.Fprintf(&lines, "- %s (`%s`) via MCP server `%s`\n", name, toolkitSlug, serverName)}if lines.Len() == 0 {- return+ return ""}b.WriteString("## Connected Apps\n\n")b.WriteString(lines.String())b.WriteString("\nUse the listed MCP server when the task asks to read or act in one of these apps.\n\n")+ return b.String()}func sanitizeBriefCodeToken(s string) string {@@ -340,28 +354,26 @@ func writeIssueMetadata(b *strings.Builder) {b.WriteString("- **Recommended keys** (use snake_case ASCII; reuse these names so queries stay consistent): `pr_url`, `pr_number`, `pipeline_status`, `deploy_url`, `external_issue_url`, `waiting_on`, `blocked_reason`, `decision`.\n\n")}-// writeInstructionPrecedence emits the "Agent Identity wins over the-// assignment workflow below" guardrail. Caller gates on-// kind == kindAssignmentTriggered.+// writeInstructionPrecedence emits the "Agent Identity wins over the issue+// workflow below" guardrail. Caller gates on kind == kindIssue.func writeInstructionPrecedence(b *strings.Builder) {b.WriteString("## Instruction Precedence\n\n")- b.WriteString("Agent Identity instructions have priority over the assignment workflow below. ")+ b.WriteString("Agent Identity instructions have priority over the issue workflow below. ")b.WriteString("If a workflow step conflicts with Agent Identity, skip the conflicting action and continue with the remaining compatible steps. ")b.WriteString("Never treat this runtime workflow as permission to change issue status, investigate, implement, or otherwise act beyond your Agent Identity.\n\n")}-// writeSessionContinuityNotice warns the agent — and, through it, the user —-// when a resume the task expected could not be honored. The daemon has already-// cleared the resume flags, so without this the run would silently reappear as a-// brand-new conversation; here we make the loss explicit and ask the agent to-// disclose it in its reply (MUL-4424). No-op unless a resume was actually lost.-func writeSessionContinuityNotice(b *strings.Builder, ctx TaskContextForEnv) {- if !ctx.PriorSessionResumeUnavailable {- return- }- b.WriteString("## Session Continuity Notice\n\n")- b.WriteString("This run was meant to continue an earlier conversation, but that session's context could NOT be restored — you are starting fresh with no memory of the previous turns. Rebuild context from the issue/thread before acting. **When you reply, tell the user up front (one short sentence) that the previous conversation context was unavailable and this is a new session**, so they understand why the thread did not carry over.\n\n")-}+// SessionContinuityNotice warns the agent — and, through it, the user — when a+// resume the task expected could not be honored. The daemon has already+// cleared the resume flags, so without this the run would silently reappear as+// a brand-new conversation; here we make the loss explicit and ask the agent to+// disclose it in its reply (MUL-4424).+//+// Emitted into the per-turn user message rather than the runtime brief: it is+// true of one run and false of the next on the same issue, so rendering it into+// the brief broke prompt-cache prefix stability across resumes (MUL-5377).+const SessionContinuityNotice = "## Session Continuity Notice\n\n" ++ "This run was meant to continue an earlier conversation, but that session's context could NOT be restored — you are starting fresh with no memory of the previous turns. Rebuild context from the issue/thread before acting. **When you reply, tell the user up front (one short sentence) that the previous conversation context was unavailable and this is a new session**, so they understand why the thread did not carry over.\n\n"// writeWorkflowHeader emits the unconditional `### Workflow` heading.func writeWorkflowHeader(b *strings.Builder) {@@ -418,37 +430,68 @@ func writeWorkflowAutopilot(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("- Do not run `multica issue get`, `multica issue comment add`, or `multica issue status` for this run unless the autopilot instructions explicitly tell you to create or update an issue\n\n")}-// writeWorkflowComment emits the comment-triggered workflow.-func writeWorkflowComment(b *strings.Builder, provider string, ctx TaskContextForEnv) {- b.WriteString("**This task was triggered by a NEW comment.** Your primary job is to respond to THIS specific comment, even if you have handled similar requests before in this session.\n\n")+// writeWorkflowIssue emits the single issue workflow used by BOTH+// assignment-triggered and comment-triggered runs.+//+// One section, not two, because this text lands in messages[0] — ahead of the+// whole conversation — and any divergence between the first run and later runs+// on the same resumed session throws away the prompt cache for the entire+// history (MUL-5377). So nothing here may depend on which trigger fired this+// turn, and no per-run identifier (trigger comment id, thread id, new-comment+// delta, reply targets) may be interpolated. Those travel in the per-turn user+// message instead; see daemon.buildCommentPrompt.+//+// The two modes are expressed as a router rather than two concatenated step+// lists: the mode-specific status rules live INSIDE their own mode block so+// "own the status arc" and "do not touch the status" can never be read as+// peer instructions with no arbitration.+//+// Ordinary agents own the full status arc for their issue: open with+// in_progress, deliver with in_review. Squad leaders share the opening+// in_progress step so the parent leaves todo as soon as coordination+// starts, but their first assignment turn is only a dispatch — flipping+// the parent to in_review there would mark unfinished multi-stage work+// as ready for review. Leaders move the parent to in_review later, when+// a re-trigger (member update / stage barrier) confirms the overall goal+// is met; see the Squad Operating Protocol and child-done system comments.+//+// ctx.IsSquadLeader is agent configuration, not per-run state, so branching+// on it does not break byte-stability across runs of one session.+func writeWorkflowIssue(b *strings.Builder, ctx TaskContextForEnv) {+ b.WriteString("**Mode router — read this before acting.** This file is identical on every run, so it cannot tell you what triggered THIS turn. The user message for this turn names its mode on a line of its own:\n\n")+ b.WriteString("- `Turn mode: Reply.` → **Reply mode**. That message also carries the triggering comment's id, the exact `--parent` value for your reply, and the comment's content when the platform supplied it.\n")+ b.WriteString("- `Turn mode: Ownership.` → **Ownership mode** (an assignment or status change started this run).\n\n")+ b.WriteString("Steps 1–6 below are the same in both modes. The mode blocks after them differ, and they differ on issue status in particular — **apply exactly one mode block, the one the user message named. Never apply both.** If neither line is present, treat the turn as Reply mode and do not change the issue status.\n\n")++ b.WriteString("**Steps 1–6 — both modes**\n\n")fmt.Fprintf(b, "1. Run `multica issue get %s --output json` to understand the issue context\n", ctx.IssueID)fmt.Fprintf(b, "2. Run `multica issue metadata list %s --output json` to see what prior agents pinned — best-effort, empty `{}` and CLI failures are normal. See the `## Issue Metadata` section above for what to look for.\n", ctx.IssueID)- if hint := BuildNewCommentsHint(ctx.IssueID, ctx.TriggerCommentID, ctx.TriggerThreadID, ctx.NewCommentsSince, ctx.NewCommentCount); hint != "" {- b.WriteString("3. " + hint)- } else if ctx.PriorSessionResumed {- b.WriteString("3. " + BuildResumedCommentsHint(ctx.IssueID, ctx.TriggerCommentID, ctx.TriggerThreadID))- } else if cold := BuildColdCommentsHint(ctx.IssueID, ctx.TriggerCommentID, ctx.TriggerThreadID); cold != "" {- b.WriteString("3. " + cold)+ fmt.Fprintf(b, "3. Run `multica issue comment list %s --recent 10 --output json` to catch up on recent active comment threads — this is mandatory, not optional. Earlier comments often carry context the issue body lacks (e.g. which repo to work in, the prior agent's findings, the reason the issue was reassigned to you). Skipping this step is the most common cause of agents acting on stale or incomplete instructions. Resolved threads come back folded — `--full` to expand. If the recent window shows that older context is needed, page older threads with the stderr `Next thread cursor:` values and the matching `--before` / `--before-id` flags until you have enough history. In Reply mode the per-turn user message also tells you which thread to start from.\n", ctx.IssueID)+ b.WriteString("4. Complete the task within your Agent Identity boundaries. Do not investigate, implement, create issues, update issues, or delegate if your Agent Identity forbids that action; if your role is delegation-only, perform the allowed delegation work and stop once that outcome is delivered.\n")+ if ctx.IsSquadLeader {+ fmt.Fprintf(b, "5. **Post your final results as a comment** (unless your outcome is `no_action` — in that case, calling `multica squad activity %s no_action --reason \"...\"` alone is sufficient; you MUST exit without posting any comment. DO NOT post a comment announcing no_action or saying you are exiting silently): post it with `multica issue comment add %s` using the platform-correct non-inline mode from ## Comment Formatting (never inline `--content`). Your results are only visible to the user if posted via this CLI call; text in your terminal or run logs is NOT delivered.\n", ctx.IssueID, ctx.IssueID)} else {- fmt.Fprintf(b, "3. Catch up on comments — read with `multica issue comment list %s --recent 10 --output json` (resolved threads come back folded — `--full` to expand).\n", ctx.IssueID)+ fmt.Fprintf(b, "5. **Post your final results as a comment — this step is mandatory**: post it with `multica issue comment add %s` using the platform-correct non-inline mode from ## Comment Formatting (never inline `--content`). Your results are only visible to the user if posted via this CLI call; text in your terminal or run logs is NOT delivered. In Reply mode this step is conditional on the reply rule below.\n", ctx.IssueID)}- fmt.Fprintf(b, "4. Find the triggering comment (ID: `%s`) and understand what is being asked — do NOT confuse it with previous comments\n", ctx.TriggerCommentID)+ b.WriteString("6. Before exiting: only if this run produced a fact that clears the high bar (important AND likely to be re-read by future runs on this same issue, e.g. a new PR URL or deploy URL), or you noticed a metadata key from entry that is now stale, pin or clear it via `multica issue metadata set`/`delete`. Most runs write nothing here — that is the expected outcome, not a gap. When in doubt, do not write. See the `## Issue Metadata` section above for the full bar.\n\n")++ b.WriteString("**Ownership mode only — you own the issue status this run**\n\n")+ fmt.Fprintf(b, "- Before step 4, run `multica issue status %s in_progress` unless your Agent Identity forbids issue status changes; if it does, skip it.\n", ctx.IssueID)if ctx.IsSquadLeader {- b.WriteString("5. **Decide whether a reply is warranted.** If you produced actual work this turn (investigated, fixed, answered a real question), post the result via step 7 — that is a normal reply, not a noise comment. If the triggering comment was a pure acknowledgment / thanks / sign-off from another agent AND you produced no work this turn, do NOT post a reply — and do NOT post a comment saying 'No reply needed' or similar. Simply exit with no output. Silence is a valid and preferred way to end agent-to-agent conversations.\n")- fmt.Fprintf(b, " - **Squad leader rule:** If your evaluation outcome is `no_action`, call `multica squad activity %s no_action --reason \"...\"` and then EXIT IMMEDIATELY. DO NOT post any comment whose only purpose is to announce that you are taking no action, exiting silently, or acknowledging another agent. A comment like \"No action needed\" or \"Exiting silently\" is noise — the `squad activity` call already records your decision in the timeline.\n", ctx.IssueID)- } else {- b.WriteString("5. **Decide whether a reply is warranted.** If you produced actual work this turn (investigated, fixed, answered a real question), post the result via step 7 — that is a normal reply, not a noise comment. If the triggering comment was a pure acknowledgment / thanks / sign-off from another agent AND you produced no work this turn, do NOT post a reply — and do NOT post a comment saying 'No reply needed' or similar. Simply exit with no output. Silence is a valid and preferred way to end agent-to-agent conversations.\n")- }- b.WriteString("6. If a reply IS warranted: do any requested work first, then **decide whether to include any `@mention` link.** The default is NO mention. Only mention when you are escalating to a human owner who is not yet involved, delegating a concrete new sub-task to another agent for the first time, or the user explicitly asked you to loop someone in. Never @mention the agent you are replying to as a thank-you or sign-off.\n")- b.WriteString("7. **If you reply, post it as a comment — this step is mandatory when you reply.** Text in your terminal or run logs is NOT delivered to the user. ")- if len(ctx.CommentReplyTargets) >= 2 {- // Cross-thread coalesced run: fan out one reply per root thread, matching- // the per-turn prompt so the two reply-instruction sources agree (MUL-4348).- b.WriteString(BuildMultiThreadCommentReplyInstructions(ctx.IssueID, ctx.CommentReplyTargets))+ fmt.Fprintf(b, "- After this initial dispatch, leave the parent issue `in_progress` — do NOT run `multica issue status %s in_review` or `done` on this turn. Dispatching members is not completion. You will be re-triggered when members post updates or a stage closes; only then, if the overall goal is met, move the parent to `in_review`.\n", ctx.IssueID)} else {- b.WriteString(buildCommentReplyInstructionsSlim(provider, ctx.IssueID, ctx.TriggerCommentID))+ fmt.Fprintf(b, "- When done, run `multica issue status %s in_review` unless your Agent Identity forbids issue status changes; if it does, skip it.\n", ctx.IssueID)+ }+ fmt.Fprintf(b, "- If blocked, run `multica issue status %s blocked` unless your Agent Identity forbids issue status changes. Post a comment explaining the blocker unless your Agent Identity forbids issue comments.\n\n", ctx.IssueID)++ b.WriteString("**Reply mode only — respond to the comment in the user message**\n\n")+ b.WriteString("- Your primary job is to respond to THAT specific comment, even if you have handled similar requests before in this session. Do NOT confuse it with previous comments; take its id from the user message, never from this file or from an earlier turn.\n")+ b.WriteString("- **Decide whether a reply is warranted.** If you produced actual work this turn (investigated, fixed, answered a real question), post the result via step 5 — that is a normal reply, not a noise comment. If the triggering comment was a pure acknowledgment / thanks / sign-off from another agent AND you produced no work this turn, do NOT post a reply — and do NOT post a comment saying 'No reply needed' or similar. Simply exit with no output. Silence is a valid and preferred way to end agent-to-agent conversations.\n")+ if ctx.IsSquadLeader {+ fmt.Fprintf(b, "- **Squad leader rule:** If your evaluation outcome is `no_action`, call `multica squad activity %s no_action --reason \"...\"` and then EXIT IMMEDIATELY. DO NOT post any comment whose only purpose is to announce that you are taking no action, exiting silently, or acknowledging another agent. A comment like \"No action needed\" or \"Exiting silently\" is noise — the `squad activity` call already records your decision in the timeline.\n", ctx.IssueID)}- b.WriteString("8. Before exiting: only if this run produced a fact that clears the high bar (important AND likely to be re-read by future runs on this same issue, e.g. a new PR URL or deploy URL), or you noticed a metadata key from entry that is now stale, pin or clear it via `multica issue metadata set`/`delete`. Most runs write nothing here — that is the expected outcome, not a gap. When in doubt, do not write. See the `## Issue Metadata` section above for the full bar.\n")+ b.WriteString("- If a reply IS warranted: do any requested work first, then **decide whether to include any `@mention` link.** The default is NO mention. Only mention when you are escalating to a human owner who is not yet involved, delegating a concrete new sub-task to another agent for the first time, or the user explicitly asked you to loop someone in. Never @mention the agent you are replying to as a thank-you or sign-off.\n")+ b.WriteString("- **If you reply, posting it as a comment is mandatory.** Text in your terminal or run logs is NOT delivered to the user. Use the `--parent` value the per-turn user message gives you for this turn; do NOT reuse a `--parent` from an earlier turn in this session. When that message lists more than one thread to answer, post one reply per thread instead of merging them.\n")if ctx.IsSquadLeader {// The default rule below and the Squad Operating Protocol's// "Own the parent issue status" responsibility would otherwise@@ -462,41 +505,10 @@ func writeWorkflowComment(b *strings.Builder, provider string, ctx TaskContextFo// grant only exists in the instructions when the server determined// this issue is assigned to this squad (see buildSquadLeaderBriefing);// a guest leader gets the opposite text and this stays a no-op.- b.WriteString("9. Do NOT change the issue status unless the comment explicitly asks for it — **or** a section in your instructions explicitly grants you ownership of this issue's status (the Squad Operating Protocol's \"Own the parent issue status\" responsibility). That section only appears when this issue is assigned to your squad; when it is there, treat it as a standing instruction and move the parent to `in_review` on the turn you confirm the overall goal is met, without waiting to be asked. When it is absent, the rule above is absolute.\n\n")- } else {- b.WriteString("9. Do NOT change the issue status unless the comment explicitly asks for it\n\n")- }-}--// writeWorkflowAssignment emits the assignment-triggered workflow.-//-// Ordinary agents own the full status arc for their issue: open with-// in_progress, deliver with in_review. Squad leaders share the opening-// in_progress step so the parent leaves todo as soon as coordination-// starts, but their first assignment turn is only a dispatch — flipping-// the parent to in_review there would mark unfinished multi-stage work-// as ready for review. Leaders move the parent to in_review later, when-// a re-trigger (member update / stage barrier) confirms the overall goal-// is met; see the Squad Operating Protocol and child-done system comments.-func writeWorkflowAssignment(b *strings.Builder, ctx TaskContextForEnv) {- b.WriteString("You are responsible for managing the issue status throughout your work, unless your Agent Identity forbids issue status changes.\n\n")- fmt.Fprintf(b, "1. Run `multica issue get %s --output json` to understand your task\n", ctx.IssueID)- fmt.Fprintf(b, "2. Run `multica issue metadata list %s --output json` to see what prior agents pinned — best-effort, empty `{}` and CLI failures are normal. See the `## Issue Metadata` section above for what to look for.\n", ctx.IssueID)- fmt.Fprintf(b, "3. Run `multica issue comment list %s --recent 10 --output json` to catch up on recent active comment threads — this is mandatory, not optional. Earlier comments often carry context the issue body lacks (e.g. which repo to work in, the prior agent's findings, the reason the issue was reassigned to you). Skipping this step is the most common cause of agents acting on stale or incomplete instructions. Resolved threads come back folded — `--full` to expand. If the recent window shows that older context is needed, page older threads with the stderr `Next thread cursor:` values and the matching `--before` / `--before-id` flags until you have enough history.\n", ctx.IssueID)- fmt.Fprintf(b, "4. Run `multica issue status %s in_progress` unless your Agent Identity forbids issue status changes; if it does, skip this step.\n", ctx.IssueID)- b.WriteString("5. Complete the task within your Agent Identity boundaries. Do not investigate, implement, create issues, update issues, or delegate if your Agent Identity forbids that action; if your role is delegation-only, perform the allowed delegation work and stop once that outcome is delivered.\n")- if ctx.IsSquadLeader {- fmt.Fprintf(b, "6. **Post your final results as a comment** (unless your outcome is `no_action` — in that case, calling `multica squad activity %s no_action --reason \"...\"` alone is sufficient; you MUST exit without posting any comment. DO NOT post a comment announcing no_action or saying you are exiting silently): post it with `multica issue comment add %s` using the platform-correct non-inline mode from ## Comment Formatting (never inline `--content`). Your results are only visible to the user if posted via this CLI call; text in your terminal or run logs is NOT delivered.\n", ctx.IssueID, ctx.IssueID)- } else {- fmt.Fprintf(b, "6. **Post your final results as a comment — this step is mandatory**: post it with `multica issue comment add %s` using the platform-correct non-inline mode from ## Comment Formatting (never inline `--content`). Your results are only visible to the user if posted via this CLI call; text in your terminal or run logs is NOT delivered.\n", ctx.IssueID)- }- b.WriteString("7. Before exiting: only if this run produced a fact that clears the high bar (important AND likely to be re-read by future runs on this same issue, e.g. a new PR URL or deploy URL), or you noticed a metadata key from entry that is now stale, pin or clear it via `multica issue metadata set`/`delete`. Most runs write nothing here — that is the expected outcome, not a gap. When in doubt, do not write. See the `## Issue Metadata` section above for the full bar.\n")- if ctx.IsSquadLeader {- fmt.Fprintf(b, "8. After this initial dispatch, leave the parent issue `in_progress` — do NOT run `multica issue status %s in_review` or `done` on this turn. Dispatching members is not completion. You will be re-triggered when members post updates or a stage closes; only then, if the overall goal is met, move the parent to `in_review`.\n", ctx.IssueID)+ b.WriteString("- Do NOT change the issue status unless the comment explicitly asks for it — **or** a section in your instructions explicitly grants you ownership of this issue's status (the Squad Operating Protocol's \"Own the parent issue status\" responsibility). That section only appears when this issue is assigned to your squad; when it is there, treat it as a standing instruction and move the parent to `in_review` on the turn you confirm the overall goal is met, without waiting to be asked. When it is absent, the rule above is absolute. **The Ownership-mode status steps above do not apply in Reply mode.**\n\n")} else {- fmt.Fprintf(b, "8. When done, run `multica issue status %s in_review` unless your Agent Identity forbids issue status changes; if it does, skip this step.\n", ctx.IssueID)+ b.WriteString("- Do NOT change the issue status unless the comment explicitly asks for it. **The Ownership-mode status steps above do not apply in Reply mode.**\n\n")}- fmt.Fprintf(b, "9. If blocked, run `multica issue status %s blocked` unless your Agent Identity forbids issue status changes. Post a comment explaining the blocker unless your Agent Identity forbids issue comments.\n\n", ctx.IssueID)}// writeSubIssueCreation emits the Sub-issue Creation section (compressed@@ -655,14 +667,15 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {var b strings.Builderkind := classifyTask(ctx)+ // Session Continuity Notice, Task Initiator and Connected Apps used to be+ // rendered here. They are per-run values, so emitting them into this file+ // broke prompt-cache prefix stability on every resume; they now travel in+ // the per-turn user message (daemon.BuildPrompt) instead. See MUL-5377.writeHeader(&b)writeBackgroundTaskSafetySlim(&b)writeAgentIdentity(&b, ctx)- writeSessionContinuityNotice(&b, ctx)writeRequestingUser(&b, ctx)- writeTaskInitiator(&b, ctx)writeWorkspaceContext(&b, ctx)- writeConnectedApps(&b, ctx)switch kind {case kindQuickCreate:@@ -671,7 +684,7 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {writeAvailableCommands(&b)}- if kind == kindCommentTriggered || kind == kindAssignmentTriggered {+ if kind == kindIssue {writeCommentFormatting(&b)}@@ -685,7 +698,7 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {writeIssueMetadata(&b)}- if kind == kindAssignmentTriggered {+ if kind == kindIssue {writeInstructionPrecedence(&b)}@@ -697,10 +710,8 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {writeWorkflowQuickCreate(&b)case kindAutopilotRunOnly:writeWorkflowAutopilot(&b, ctx)- case kindCommentTriggered:- writeWorkflowComment(&b, provider, ctx)- case kindAssignmentTriggered:- writeWorkflowAssignment(&b, ctx)+ case kindIssue:+ writeWorkflowIssue(&b, ctx)}if kind.hasIssueContext() && ctx.IssueID != "" {@@ -711,7 +722,7 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {writeSkills(&b, provider, ctx)}- if kind == kindCommentTriggered || kind == kindAssignmentTriggered {+ if kind == kindIssue {writeMentions(&b)writeAttachments(&b)}diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.goindex 6307dcf4aa..5cb070a6fa 100644--- a/server/internal/daemon/execenv/runtime_config_test.go+++ b/server/internal/daemon/execenv/runtime_config_test.go@@ -4,6 +4,7 @@ import ("fmt""os""path/filepath"+ "strconv""strings""testing"@@ -203,85 +204,75 @@ func TestCommentTriggeredSquadLeaderDefersToStatusOwnershipGrant(t *testing.T) {}}-// The CLAUDE.md workflow surface must carry the same issue-wide since-delta-// new-comment hint as the per-turn prompt. PR #2816 requires the two surfaces-// stay in sync.-func TestCommentTriggeredBriefCarriesNewCommentsHint(t *testing.T) {+// TestPerRunCommentContextStaysOutOfBrief pins MUL-5377: no per-run comment+// routing value may be rendered into the runtime brief. The brief lands in+// messages[0], ahead of the whole conversation, so any change there throws away+// the prompt cache for the entire history on resume. The helpers are unchanged+// and still feed the per-turn user message (daemon.buildCommentPrompt).+func TestPerRunCommentContextStaysOutOfBrief(t *testing.T) {t.Parallel()const (issueID = "55555555-6666-7777-8888-999999999999"since = "2026-05-28T11:00:00Z")- ctx := TaskContextForEnv{+ out := buildMetaSkillContent("claude", TaskContextForEnv{IssueID: issueID,TriggerCommentID: "reply-abc",+ TriggerThreadID: "thread-abc",NewCommentCount: 4,NewCommentsSince: since,- }- out := buildMetaSkillContent("claude", ctx)+ CommentReplyTargets: []ThreadReplyTarget{+ {ThreadID: "thread-abc", ParentID: "reply-abc"},+ {ThreadID: "thread-def", ParentID: "reply-def"},+ },+ })- // Issue-wide count.- if !strings.Contains(out, "4 new comment(s) on this issue since your last run") {- t.Errorf("comment brief must report the issue-wide new-comment count, got:\n%s", out)- }- if !strings.Contains(out, "blindly") {- t.Errorf("comment brief must discourage blindly reading every new comment, got:\n%s", out)- }- // Parent thread first.- if !strings.Contains(out, "--thread reply-abc --since "+since+" --output json") {- t.Errorf("comment brief must point at the triggering (parent) thread --since read first, got:\n%s", out)- }- if !strings.Contains(out, "--tail 30") {- t.Errorf("comment brief must offer the full-thread (--tail 30) option, got:\n%s", out)- }- // Issue-wide catch-up demoted to an only-if-needed fallback.- if !strings.Contains(out, "multica issue comment list "+issueID+" --since "+since+" --output json") {- t.Errorf("comment brief must keep the issue-wide --since catch-up fallback, got:\n%s", out)+ for _, banned := range []string{+ "reply-abc", "thread-abc", "reply-def", "thread-def", since,+ "4 new comment(s) on this issue since your last run",+ "DISTINCT threads",+ } {+ if strings.Contains(out, banned) {+ t.Errorf("brief must not carry per-run comment value %q (MUL-5377)\n---\n%s", banned, out)+ }}- // The removed resolve step must not reappear.- if strings.Contains(out, "multica comment resolve") {- t.Errorf("comment brief must not carry the dropped resolve step, got:\n%s", out)++ // The helper that now feeds the per-turn prompt is unchanged.+ hint := BuildNewCommentsHint(issueID, "reply-abc", "thread-abc", since, 4)+ for _, want := range []string{+ "4 new comment(s) on this issue since your last run",+ "blindly",+ "--thread thread-abc --since " + since + " --output json",+ "--tail 30",+ } {+ if !strings.Contains(hint, want) {+ t.Errorf("BuildNewCommentsHint missing %q\n---\n%s", want, hint)+ }}}-// Cold start (no prior run → no since anchor) must point the agent at the-// triggering CONVERSATION (--thread <trigger> --tail 30) instead of the flat-// timeline dump or the since-delta hint.-func TestCommentTriggeredBriefColdStartThreadRead(t *testing.T) {+// Cold-start thread routing moved to the per-turn prompt (MUL-5377); the+// helper behaviour it relies on is pinned here directly.+func TestColdCommentsHintPointsAtTriggeringThread(t *testing.T) {t.Parallel()const issueID = "55555555-6666-7777-8888-999999999999"- ctx := TaskContextForEnv{- IssueID: issueID,- TriggerCommentID: "trigger-1",- TriggerThreadID: "thread-root-1",- NewCommentCount: 0,- NewCommentsSince: "",+ hint := BuildColdCommentsHint(issueID, "trigger-1", "thread-root-1")+ if strings.Contains(hint, "new comment(s) since your last run") {+ t.Errorf("no since-delta hint should render on cold start, got:\n%s", hint)}- out := buildMetaSkillContent("claude", ctx)- if strings.Contains(out, "new comment(s) since your last run") {- t.Errorf("no since-delta hint should render on cold start, got:\n%s", out)+ if !strings.Contains(hint, "multica issue comment list "+issueID+" --thread thread-root-1 --tail 30 --output json") {+ t.Errorf("cold start must point at the triggering thread read, got:\n%s", hint)}- if !strings.Contains(out, "multica issue comment list "+issueID+" --thread thread-root-1 --tail 30 --output json") {- t.Errorf("cold start must point at the triggering thread read, got:\n%s", out)+ if strings.Contains(buildMetaSkillContent("claude", TaskContextForEnv{IssueID: issueID, TriggerCommentID: "trigger-1", TriggerThreadID: "thread-root-1"}), "thread-root-1") {+ t.Error("brief must not carry the per-run thread id (MUL-5377)")}}-// A resumed comment session with no since-delta should not fall back to the-// cold-start "read the triggering conversation first" instruction. The trigger-// body is already embedded in the per-turn prompt and the resumed session should-// carry prior thread context, so the thread read is only a fallback.-func TestCommentTriggeredBriefResumedNoDeltaSkipsDefaultThreadRead(t *testing.T) {+// Resumed/no-delta routing moved to the per-turn prompt (MUL-5377).+func TestResumedCommentsHintSkipsDefaultThreadRead(t *testing.T) {t.Parallel()const issueID = "55555555-6666-7777-8888-999999999999"- ctx := TaskContextForEnv{- IssueID: issueID,- TriggerCommentID: "trigger-1",- TriggerThreadID: "thread-root-1",- PriorSessionResumed: true,- NewCommentCount: 0,- NewCommentsSince: "",- }- out := buildMetaSkillContent("claude", ctx)+ hint := BuildResumedCommentsHint(issueID, "trigger-1", "thread-root-1")for _, want := range []string{"triggering comment is already included above",@@ -291,67 +282,62 @@ func TestCommentTriggeredBriefResumedNoDeltaSkipsDefaultThreadRead(t *testing.T)"do not rely only on resumed session memory","multica issue comment list " + issueID + " --thread thread-root-1 --tail 30 --output json",} {- if !strings.Contains(out, want) {- t.Errorf("resumed/no-delta brief missing %q\n--- output ---\n%s", want, out)+ if !strings.Contains(hint, want) {+ t.Errorf("resumed/no-delta hint missing %q\n--- output ---\n%s", want, hint)}}- if strings.Contains(out, "scoped to the triggering thread") {- t.Errorf("resumed/no-delta brief must not claim the delta is thread-scoped, got:\n%s", out)+ if strings.Contains(hint, "scoped to the triggering thread") {+ t.Errorf("resumed/no-delta hint must not claim the delta is thread-scoped, got:\n%s", hint)}- if strings.Contains(out, "Read the triggering conversation first") {- t.Errorf("resumed/no-delta brief must not use the cold-start forced-read wording, got:\n%s", out)+ if strings.Contains(hint, "Read the triggering conversation first") {+ t.Errorf("resumed/no-delta hint must not use the cold-start forced-read wording, got:\n%s", hint)}}-// When the daemon could not honor an expected resume, the brief must make the-// context loss user-visible by instructing the agent to disclose it — not leave-// it as a silent restart (MUL-4424).-func TestBriefSurfacesResumeUnavailable(t *testing.T) {+// The continuity notice moved out of the brief and into the per-turn prompt+// (MUL-5377) because it is true of one run and false of the next.+func TestSessionContinuityNoticeLivesOutsideBrief(t *testing.T) {t.Parallel()- const issueID = "11111111-2222-3333-4444-555555555555"- base := TaskContextForEnv{IssueID: issueID, TriggerCommentID: "trigger-1", TriggerThreadID: "thread-1"}-- lost := base- lost.PriorSessionResumeUnavailable = true- out := buildMetaSkillContent("codex", lost)for _, want := range []string{"## Session Continuity Notice","could NOT be restored","tell the user up front",} {- if !strings.Contains(out, want) {- t.Errorf("resume-unavailable brief missing %q\n---\n%s", want, out)+ if !strings.Contains(SessionContinuityNotice, want) {+ t.Errorf("SessionContinuityNotice missing %q", want)}}- if strings.Contains(buildMetaSkillContent("codex", base), "Session Continuity Notice") {- t.Error("brief must not show the continuity notice when no resume was lost")+ lost := TaskContextForEnv{+ IssueID: "11111111-2222-3333-4444-555555555555",+ TriggerCommentID: "trigger-1",+ PriorSessionResumeUnavailable: true,+ }+ if strings.Contains(buildMetaSkillContent("codex", lost), "Session Continuity Notice") {+ t.Error("brief must never carry the continuity notice — it is per-run state (MUL-5377)")}}-// Assignment-triggered briefs are the high-risk path for role conflicts:-// non-executor agents still need issue context, but the runtime workflow must-// not turn status changes, investigation, implementation, or delegation into-// permissions that override Agent Identity.-func TestAssignmentTriggeredProtocolHonorsAgentIdentity(t *testing.T) {+// The issue workflow must keep every Agent Identity guardrail after the+// comment/assignment branches were merged into one byte-stable section.+func TestIssueWorkflowHonorsAgentIdentity(t *testing.T) {t.Parallel()const issueID = "77777777-8888-9999-aaaa-bbbbbbbbbbbb"- ctx := TaskContextForEnv{IssueID: issueID}- out := buildMetaSkillContent("claude", ctx)+ out := buildMetaSkillContent("claude", TaskContextForEnv{IssueID: issueID})for _, want := range []string{"## Instruction Precedence",- "Agent Identity instructions have priority over the assignment workflow below.",+ "Agent Identity instructions have priority over the issue workflow below.","If a workflow step conflicts with Agent Identity, skip the conflicting action","Never treat this runtime workflow as permission to change issue status, investigate, implement",- "Run `multica issue status " + issueID + " in_progress` unless your Agent Identity forbids issue status changes; if it does, skip this step.",+ "Before step 4, run `multica issue status " + issueID + " in_progress` unless your Agent Identity forbids issue status changes; if it does, skip it.","Complete the task within your Agent Identity boundaries.","Do not investigate, implement, create issues, update issues, or delegate if your Agent Identity forbids that action",- "When done, run `multica issue status " + issueID + " in_review` unless your Agent Identity forbids issue status changes; if it does, skip this step.",+ "When done, run `multica issue status " + issueID + " in_review` unless your Agent Identity forbids issue status changes; if it does, skip it.","If blocked, run `multica issue status " + issueID + " blocked` unless your Agent Identity forbids issue status changes.",} {if !strings.Contains(out, want) {- t.Errorf("assignment-triggered brief missing identity-bound workflow text %q\n---\n%s", want, out)+ t.Errorf("issue brief missing identity-bound workflow text %q\n---\n%s", want, out)}}@@ -361,16 +347,14 @@ func TestAssignmentTriggeredProtocolHonorsAgentIdentity(t *testing.T) {"8. When done, run `multica issue status " + issueID + " in_review`\n",} {if strings.Contains(out, banned) {- t.Errorf("assignment-triggered brief still contains unconditional legacy workflow text %q\n---\n%s", banned, out)+ t.Errorf("issue brief still contains unconditional legacy workflow text %q\n---\n%s", banned, out)}}}-// Squad-leader assignment briefs must open the parent with in_progress, but-// must not treat the first dispatch turn as completion (no unconditional-// in_review). Leaders move the parent to in_review only on a later re-trigger-// once the overall goal is met.-func TestSquadLeaderAssignmentProtocolKeepsParentInProgress(t *testing.T) {+// Squad-leader briefs must open the parent with in_progress, but must not+// treat the first dispatch turn as completion (no unconditional in_review).+func TestSquadLeaderIssueWorkflowKeepsParentInProgress(t *testing.T) {t.Parallel()const issueID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"out := buildMetaSkillContent("claude", TaskContextForEnv{@@ -379,51 +363,40 @@ func TestSquadLeaderAssignmentProtocolKeepsParentInProgress(t *testing.T) {})for _, want := range []string{- "Run `multica issue status " + issueID + " in_progress` unless your Agent Identity forbids issue status changes; if it does, skip this step.",+ "Before step 4, run `multica issue status " + issueID + " in_progress` unless your Agent Identity forbids issue status changes; if it does, skip it.","After this initial dispatch, leave the parent issue `in_progress`","do NOT run `multica issue status " + issueID + " in_review` or `done` on this turn","only then, if the overall goal is met, move the parent to `in_review`",} {if !strings.Contains(out, want) {- t.Errorf("squad-leader assignment brief missing %q\n---\n%s", want, out)+ t.Errorf("squad-leader issue brief missing %q\n---\n%s", want, out)}}- for _, banned := range []string{- "When done, run `multica issue status " + issueID + " in_review`",- "8. When done, run `multica issue status " + issueID + " in_review`",- } {- if strings.Contains(out, banned) {- t.Errorf("squad-leader assignment brief must not contain ordinary-agent completion step %q\n---\n%s", banned, out)- }+ if strings.Contains(out, "When done, run `multica issue status "+issueID+" in_review`") {+ t.Errorf("squad-leader issue brief must not contain the ordinary-agent completion step\n---\n%s", out)}}-func TestInstructionPrecedenceOnlyAppliesToAssignmentWorkflow(t *testing.T) {+// Instruction Precedence belongs to the issue workflow only; the issue-less+// kinds must not inherit it. After MUL-5377 it applies to every issue run,+// comment-triggered or not, because there is a single issue workflow.+func TestInstructionPrecedenceOnlyAppliesToIssueWorkflow(t *testing.T) {t.Parallel()+ if out := buildMetaSkillContent("claude", TaskContextForEnv{+ IssueID: "11111111-2222-3333-4444-555555555555",+ TriggerCommentID: "22222222-3333-4444-5555-666666666666",+ }); !strings.Contains(out, "## Instruction Precedence") {+ t.Errorf("comment-triggered issue brief must carry Instruction Precedence\n---\n%s", out)+ }+cases := []struct {name stringctx TaskContextForEnv}{- {- name: "comment-triggered",- ctx: TaskContextForEnv{- IssueID: "11111111-2222-3333-4444-555555555555",- TriggerCommentID: "22222222-3333-4444-5555-666666666666",- },- },- {- name: "chat",- ctx: TaskContextForEnv{ChatSessionID: "chat-1"},- },- {- name: "quick-create",- ctx: TaskContextForEnv{QuickCreatePrompt: "create me an issue"},- },- {- name: "autopilot run-only",- ctx: TaskContextForEnv{AutopilotRunID: "run-1"},- },+ {"chat", TaskContextForEnv{ChatSessionID: "chat-1"}},+ {"quick-create", TaskContextForEnv{QuickCreatePrompt: "create me an issue"}},+ {"autopilot run-only", TaskContextForEnv{AutopilotRunID: "run-1"}},}for _, tc := range cases {tc := tc@@ -432,11 +405,11 @@ func TestInstructionPrecedenceOnlyAppliesToAssignmentWorkflow(t *testing.T) {out := buildMetaSkillContent("claude", tc.ctx)for _, banned := range []string{"## Instruction Precedence",- "assignment workflow below",+ "issue workflow below","Never treat this runtime workflow as permission to change issue status",} {if strings.Contains(out, banned) {- t.Errorf("%s brief must not inherit assignment-only precedence text %q\n---\n%s", tc.name, banned, out)+ t.Errorf("%s brief must not inherit issue-only precedence text %q\n---\n%s", tc.name, banned, out)}}})@@ -647,38 +620,39 @@ func TestWorkspaceContextHeadingSkippedWhenEmpty(t *testing.T) {}}-func TestConnectedAppsRenderedAcrossBriefModes(t *testing.T) {- ctx := TaskContextForEnv{- IssueID: "11111111-2222-3333-4444-555555555555",- WorkspaceContext: "Prefer source-of-truth systems.",- ConnectedApps: []runtimeapps.ConnectedApp{{- Provider: "composio",- ServerName: "composio",- ToolkitSlug: "notion",- ToolkitName: "Notion",- }},- }-- run := func(t *testing.T, label string) {- out := buildMetaSkillContent("claude", ctx)- for _, want := range []string{- "## Connected Apps",- "- Notion (`notion`) via MCP server `composio`",- "Use the listed MCP server when the task asks to read or act in one of these apps.",- } {- if !strings.Contains(out, want) {- t.Fatalf("%s brief missing connected app text %q\n---\n%s", label, want, out)- }- }- wsIdx := strings.Index(out, "## Workspace Context")- appIdx := strings.Index(out, "## Connected Apps")- cmdIdx := strings.Index(out, "## Available Commands")- if wsIdx == -1 || appIdx == -1 || cmdIdx == -1 || !(wsIdx < appIdx && appIdx < cmdIdx) {- t.Fatalf("%s connected apps should sit between workspace context and available commands (ws=%d app=%d cmd=%d)", label, wsIdx, appIdx, cmdIdx)+// Connected Apps moved to the per-turn prompt (MUL-5377): the app set is+// resolved per run from the runtime MCP overlay.+func TestConnectedAppsBlockLivesOutsideBrief(t *testing.T) {+ t.Parallel()+ apps := []runtimeapps.ConnectedApp{{+ Provider: "composio",+ ServerName: "composio",+ ToolkitSlug: "notion",+ ToolkitName: "Notion",+ }}++ block := BuildConnectedAppsBlock(apps)+ for _, want := range []string{+ "## Connected Apps",+ "- Notion (`notion`) via MCP server `composio`",+ "Use the listed MCP server when the task asks to read or act in one of these apps.",+ } {+ if !strings.Contains(block, want) {+ t.Fatalf("connected-apps block missing %q\n---\n%s", want, block)}}+ if BuildConnectedAppsBlock(nil) != "" {+ t.Error("empty app list must render nothing")+ }- run(t, "brief")+ out := buildMetaSkillContent("claude", TaskContextForEnv{+ IssueID: "11111111-2222-3333-4444-555555555555",+ WorkspaceContext: "Prefer source-of-truth systems.",+ ConnectedApps: apps,+ })+ if strings.Contains(out, "## Connected Apps") {+ t.Errorf("brief must not carry Connected Apps — it is per-run state (MUL-5377)\n---\n%s", out)+ }}func TestConnectedAppsHeadingSkippedWhenEmpty(t *testing.T) {@@ -1536,52 +1510,167 @@ func TestWriteRuntimeConfigFileAlwaysInsertsFixedManagedSeparator(t *testing.T)}}-// TestCommentTriggeredBriefFansOutAcrossThreads pins the second reply-instruction-// source (the persistent workflow brief) in sync with the per-turn prompt-// (MUL-4348). When a coalesced run spans >=2 root threads, the workflow's reply-// step must emit the per-thread fan-out plan — not the single --parent=trigger-// cookbook — so a cross-thread run never gets one surface saying "one comment"-// and the other "one per thread".-func TestCommentTriggeredBriefFansOutAcrossThreads(t *testing.T) {+// Cross-thread fan-out moved to the per-turn prompt (MUL-5377).+func TestMultiThreadReplyInstructionsFanOut(t *testing.T) {t.Parallel()- ctx := TaskContextForEnv{- IssueID: "55555555-6666-7777-8888-999999999999",- TriggerCommentID: "c3",- TriggerThreadID: "c3",- CommentReplyTargets: []ThreadReplyTarget{- {ThreadID: "c1", ParentID: "c1"},- {ThreadID: "c2", ParentID: "c2"},- {ThreadID: "c3", ParentID: "c3"},- },- }- out := buildMetaSkillContent("claude", ctx)+ out := BuildMultiThreadCommentReplyInstructions("55555555-6666-7777-8888-999999999999", []ThreadReplyTarget{+ {ThreadID: "c1", ParentID: "c1"},+ {ThreadID: "c2", ParentID: "c2"},+ {ThreadID: "c3", ParentID: "c3"},+ })for _, want := range []string{"3 DISTINCT threads", "Post ONE reply per thread", "--parent c1", "--parent c2", "--parent c3"} {if !strings.Contains(out, want) {- t.Errorf("cross-thread brief must contain %q, got:\n%s", want, out)+ t.Errorf("cross-thread instructions must contain %q, got:\n%s", want, out)}}}-// TestCommentTriggeredBriefSingleThreadKeepsSingleReply pins the hard-// requirement on the brief surface too: a run with no multi-thread targets-// (ordinary comment, or same-thread follow-ups that collapsed upstream) keeps-// the single --parent=trigger cookbook and never emits the fan-out block.-func TestCommentTriggeredBriefSingleThreadKeepsSingleReply(t *testing.T) {+// Single-thread reply cookbook moved to the per-turn prompt (MUL-5377).+func TestSingleThreadReplyInstructionsKeepSingleParent(t *testing.T) {t.Parallel()- ctx := TaskContextForEnv{- IssueID: "55555555-6666-7777-8888-999999999999",- TriggerCommentID: "c3",- TriggerThreadID: "thread-A",- // CommentReplyTargets deliberately empty: same-thread follow-ups collapse- // to a single group upstream, so no fan-out targets reach the brief.- }- out := buildMetaSkillContent("claude", ctx)+ out := BuildCommentReplyInstructions("claude", "55555555-6666-7777-8888-999999999999", "c3")if strings.Contains(out, "DISTINCT threads") {- t.Errorf("single/same-thread brief must not emit the multi-thread fan-out block, got:\n%s", out)+ t.Errorf("single/same-thread instructions must not emit the multi-thread fan-out block, got:\n%s", out)}if !strings.Contains(out, "--parent c3 --content-file ./reply.md") {- t.Errorf("single/same-thread brief must keep the single --parent=trigger cookbook, got:\n%s", out)+ t.Errorf("single/same-thread instructions must keep the single --parent=trigger cookbook, got:\n%s", out)+ }+}++// TestInjectRuntimeConfigByteIdenticalAcrossTriggers is the regression guard+// for MUL-5377.+//+// Claude Code loads the runtime brief into messages[0], ahead of the entire+// conversation. A cache breakpoint is all-or-nothing, so a single differing+// byte in this file invalidates the prompt cache for the whole history: on a+// resumed session the measured cost was ~426k re-created tokens per run, with+// only tools[]+system[] surviving.+//+// Therefore the rendered managed block must be byte-identical for the same+// (agent, issue, provider) no matter what triggered the run. Every field+// varied below is per-run state that used to be interpolated into the brief.+//+// If this test fails, do NOT relax it — move the offending value into the+// per-turn user message (daemon.BuildPrompt) instead. A "skip the write when+// the block is unchanged" guard does not help here: when a volatile field+// creeps back in the block is no longer identical, so the guard never fires+// and the cache breaks anyway.+func TestInjectRuntimeConfigByteIdenticalAcrossTriggers(t *testing.T) {+ t.Parallel()++ const issueID = "11111111-2222-3333-4444-555555555555"+ base := TaskContextForEnv{+ IssueID: issueID,+ AgentID: "agent-1",+ AgentName: "Eve",+ }++ variants := []struct {+ name string+ mutate func(c *TaskContextForEnv)+ }{+ {"assignment-triggered", func(c *TaskContextForEnv) {}},+ {"comment-triggered", func(c *TaskContextForEnv) {+ c.TriggerCommentID = "comment-1"+ c.TriggerThreadID = "thread-1"+ }},+ {"comment-triggered-other-comment", func(c *TaskContextForEnv) {+ c.TriggerCommentID = "comment-2"+ c.TriggerThreadID = "thread-2"+ }},+ {"resumed-with-delta", func(c *TaskContextForEnv) {+ c.TriggerCommentID = "comment-3"+ c.PriorSessionResumed = true+ c.NewCommentCount = 7+ c.NewCommentsSince = "2026-05-28T11:00:00Z"+ }},+ {"resume-unavailable", func(c *TaskContextForEnv) {+ c.TriggerCommentID = "comment-4"+ c.PriorSessionResumeUnavailable = true+ }},+ {"cross-thread-fan-out", func(c *TaskContextForEnv) {+ c.TriggerCommentID = "comment-5"+ c.CommentReplyTargets = []ThreadReplyTarget{+ {ThreadID: "t1", ParentID: "t1"},+ {ThreadID: "t2", ParentID: "t2"},+ }+ }},+ {"member-initiator", func(c *TaskContextForEnv) {+ c.InitiatorType = "member"+ c.InitiatorID = "user-1"+ c.InitiatorName = "Bohan"+ c.InitiatorEmail = "[email protected]"+ }},+ {"agent-initiator", func(c *TaskContextForEnv) {+ c.InitiatorType = "agent"+ c.InitiatorID = "agent-9"+ c.InitiatorName = "GPT-Boy"+ }},+ {"connected-apps", func(c *TaskContextForEnv) {+ c.ConnectedApps = []runtimeapps.ConnectedApp{{+ Provider: "composio",+ ServerName: "composio",+ ToolkitSlug: "notion",+ ToolkitName: "Notion",+ }}+ }},+ }++ // Non-vacuity guard: the brief must still depend on its stable inputs, or+ // this whole test would pass on a function that ignores ctx entirely.+ otherIssue := base+ otherIssue.IssueID = "99999999-8888-7777-6666-555555555555"+ if buildMetaSkillContent("claude", base) == buildMetaSkillContent("claude", otherIssue) {+ t.Fatal("brief does not vary with issue id — byte-identity assertions below would be vacuous")+ }++ for _, provider := range []string{"claude", "codex"} {+ provider := provider+ t.Run(provider, func(t *testing.T) {+ t.Parallel()+ var want string+ for i, v := range variants {+ ctx := base+ v.mutate(&ctx)+ got := buildMetaSkillContent(provider, ctx)+ if i == 0 {+ want = got+ continue+ }+ if got != want {+ t.Errorf("brief differs for variant %q — per-run state leaked into messages[0] (MUL-5377).\n%s",+ v.name, firstBriefDiff(want, got))+ }+ }+ })+ }+}++// firstBriefDiff reports the first differing byte with surrounding context so a+// failure names the offending section instead of dumping two whole briefs.+func firstBriefDiff(want, got string) string {+ n := len(want)+ if len(got) < n {+ n = len(got)+ }+ i := 0+ for i < n && want[i] == got[i] {+ i+++ }+ lo := i - 120+ if lo < 0 {+ lo = 0+ }+ hiW, hiG := i+120, i+120+ if hiW > len(want) {+ hiW = len(want)+ }+ if hiG > len(got) {+ hiG = len(got)}+ return "first difference at byte " + strconv.Itoa(i) ++ "\n--- baseline ---\n" + want[lo:hiW] ++ "\n--- variant ---\n" + got[lo:hiG]}diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex 1a891de00c..e80578c069 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -21,6 +21,43 @@ func freshSessionRetryPrompt(prompt string) string {return notice + prompt}+// Turn-mode markers consumed by the runtime brief's mode router+// (execenv.writeWorkflowIssue). The brief is byte-identical on every run and+// therefore cannot say what triggered this turn; these lines do, and they are+// emitted unconditionally from the same branches BuildPrompt uses to pick a+// path, so the two can never disagree.+//+// Reply mode = respond to the triggering comment, do not touch issue status.+// Ownership mode = an assignment/status change started this run; own the+// status arc. Applying the wrong one silently changes issue status.+const (+ turnModeReply = "**Turn mode: Reply.** Follow the Reply-mode block in your runtime workflow file for this turn; the Ownership-mode status steps do not apply.\n\n"+ turnModeOwnership = "**Turn mode: Ownership.** Follow the Ownership-mode block in your runtime workflow file for this turn; the Reply-mode rules do not apply.\n\n"+)++// perTurnContextBlocks renders the run-scoped context blocks that used to live+// in the runtime brief (CLAUDE.md / AGENTS.md).+//+// Every value here changes from one run to the next on the same issue — the+// initiator differs whenever another person comments, the continuity notice is+// true of one run and false of the next, and the connected-app set is resolved+// per run from the runtime MCP overlay. Claude Code loads the brief into+// messages[0], ahead of the entire conversation, so rendering these there threw+// away the prompt cache for the whole history on every resume. Appending them+// to the per-turn user message puts them after the cached prefix instead, where+// changing them costs only this turn's own tokens (MUL-5377).+//+// Returns "" when none of the blocks apply.+func perTurnContextBlocks(task Task) string {+ var b strings.Builder+ if task.PriorSessionResumeUnavailable {+ b.WriteString(execenv.SessionContinuityNotice)+ }+ b.WriteString(execenv.BuildTaskInitiatorBlock(task.InitiatorType, task.InitiatorName, task.InitiatorEmail))+ b.WriteString(execenv.BuildConnectedAppsBlock(task.ConnectedApps))+ return b.String()+}+// BuildPrompt constructs the task prompt for an agent CLI.// Keep this minimal — detailed instructions live in CLAUDE.md / AGENTS.md// injected by execenv.InjectRuntimeConfig. The provider string is threaded@@ -29,6 +66,20 @@ func freshSessionRetryPrompt(prompt string) string {// post with `--content-file`) because the shell-layer corruption it guards// against is not specific to any one provider or host (MUL-2904, #4182).func BuildPrompt(task Task, provider string) string {+ body := buildPromptBody(task, provider)+ // Run-scoped context is appended, never prepended: everything ahead of it+ // is stable across runs of a resumed session, and appending keeps it after+ // the cached prefix (MUL-5377).+ if blocks := perTurnContextBlocks(task); blocks != "" {+ if !strings.HasSuffix(body, "\n\n") {+ body += "\n"+ }+ body += blocks+ }+ return body+}++func buildPromptBody(task Task, provider string) string {if task.ChatSessionID != "" {return buildChatPrompt(task)}@@ -44,6 +95,7 @@ func BuildPrompt(task Task, provider string) string {var b strings.Builderb.WriteString("You are running as a local coding agent for a Multica workspace.\n\n")fmt.Fprintf(&b, "Your assigned issue ID is: %s\n\n", task.IssueID)+ b.WriteString(turnModeOwnership)// Assignment handoff (MUL-3375): a free-text instruction the person who// assigned/promoted this issue left for you. Frame it as a handoff, not a// comment to reply to — there is no comment thread to answer here.@@ -170,6 +222,13 @@ func buildCommentPrompt(task Task, provider string) string {var b strings.Builderb.WriteString("You are running as a local coding agent for a Multica workspace.\n\n")fmt.Fprintf(&b, "Your assigned issue ID is: %s\n\n", task.IssueID)+ // Mode marker for the brief's router. Emitted unconditionally from the same+ // branch that selects this code path, so the brief and the prompt can never+ // disagree about which mode this turn is in. It must NOT be gated on+ // TriggerCommentContent: an empty comment body (or an older server that+ // doesn't send one) would otherwise leave the turn unlabelled, and the+ // agent would fall through to Ownership mode and change the issue status.+ b.WriteString(turnModeReply)if task.TriggerCommentContent != "" {authorLabel := "A user"if task.TriggerAuthorType == "agent" {diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.goindex 67aaebcbc5..eb7f72f3d1 100644--- a/server/internal/daemon/prompt_test.go+++ b/server/internal/daemon/prompt_test.go@@ -1030,3 +1030,180 @@ func TestBuildCommentPromptSameThreadKeepsSingleReply(t *testing.T) {t.Errorf("same-thread run must keep the single --parent=trigger reply cookbook, got:\n%s", out)}}++// TestPerTurnContextBlocksCarryMovedBriefSections is the other half of+// MUL-5377: the per-run context that was removed from the runtime brief must+// still reach the agent, now via the per-turn user message. Losing it silently+// would be a worse regression than the cache cost it fixes.+func TestPerTurnContextBlocksCarryMovedBriefSections(t *testing.T) {+ t.Parallel()++ task := Task{+ IssueID: "issue-1",+ TriggerCommentID: "comment-1",+ TriggerCommentContent: "please look at this",+ PriorSessionResumeUnavailable: true,+ InitiatorType: "member",+ InitiatorName: "Bohan",+ InitiatorEmail: "[email protected]",+ ConnectedApps: []ConnectedAppData{{+ Provider: "composio",+ ServerName: "composio",+ ToolkitSlug: "notion",+ ToolkitName: "Notion",+ }},+ }++ prompt := BuildPrompt(task, "claude")+ for _, want := range []string{+ "## Session Continuity Notice",+ "could NOT be restored",+ "## Task Initiator",+ "initiated by **Bohan** ([email protected]), a member of this workspace",+ "credentials stay scoped to the runtime owner",+ "## Connected Apps",+ "- Notion (`notion`) via MCP server `composio`",+ } {+ if !strings.Contains(prompt, want) {+ t.Errorf("per-turn prompt lost moved brief content %q\n---\n%s", want, prompt)+ }+ }+}++// The blocks are per-run, so they must be absent when their preconditions are.+func TestPerTurnContextBlocksOmittedWhenEmpty(t *testing.T) {+ t.Parallel()++ prompt := BuildPrompt(Task{IssueID: "issue-1"}, "claude")+ for _, banned := range []string{+ "## Session Continuity Notice",+ "## Task Initiator",+ "## Connected Apps",+ } {+ if strings.Contains(prompt, banned) {+ t.Errorf("per-turn prompt must not emit %q with no data\n---\n%s", banned, prompt)+ }+ }+}++// An assignment-triggered run carries the initiator too — it is not a+// comment-path-only block.+func TestPerTurnContextBlocksOnAssignmentPath(t *testing.T) {+ t.Parallel()++ prompt := BuildPrompt(Task{+ IssueID: "issue-1",+ InitiatorType: "agent",+ InitiatorName: "GPT-Boy",+ }, "claude")+ if !strings.Contains(prompt, "initiated by **GPT-Boy**, another agent in this workspace") {+ t.Errorf("assignment-triggered prompt lost the initiator block\n---\n%s", prompt)+ }+}++// TestTurnModeMarkerAlwaysPresent is the regression guard for the review+// finding on #6021: the brief's mode router keys off an explicit marker in the+// per-turn prompt, so that marker must be emitted unconditionally from the same+// branch that selects the code path.+//+// The dangerous case is a comment-triggered run whose comment body is empty (or+// an older server that doesn't send one). Before this guard the prompt emitted+// no `[NEW COMMENT]` block at all, the brief fell through to Ownership mode,+// and the agent would change the issue status on a turn that must not.+func TestTurnModeMarkerAlwaysPresent(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ task Task+ want string+ deny string+ }{+ {+ name: "comment-triggered with content",+ task: Task{IssueID: "issue-1", TriggerCommentID: "c-1", TriggerCommentContent: "please look"},+ want: "**Turn mode: Reply.**",+ deny: "**Turn mode: Ownership.**",+ },+ {+ name: "comment-triggered with EMPTY content",+ task: Task{IssueID: "issue-1", TriggerCommentID: "c-1"},+ want: "**Turn mode: Reply.**",+ deny: "**Turn mode: Ownership.**",+ },+ {+ name: "assignment-triggered",+ task: Task{IssueID: "issue-1"},+ want: "**Turn mode: Ownership.**",+ deny: "**Turn mode: Reply.**",+ },+ {+ name: "assignment-triggered with handoff note",+ task: Task{IssueID: "issue-1", HandoffNote: "start with the API"},+ want: "**Turn mode: Ownership.**",+ deny: "**Turn mode: Reply.**",+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ prompt := BuildPrompt(tc.task, "claude")+ if !strings.Contains(prompt, tc.want) {+ t.Errorf("prompt missing turn-mode marker %q\n---\n%s", tc.want, prompt)+ }+ if strings.Contains(prompt, tc.deny) {+ t.Errorf("prompt carries the wrong turn-mode marker %q\n---\n%s", tc.deny, prompt)+ }+ })+ }+}++// The mode marker only makes sense for the two issue paths — the issue-less+// kinds have no Reply/Ownership distinction and no issue status to protect.+func TestTurnModeMarkerAbsentOnIssuelessKinds(t *testing.T) {+ t.Parallel()++ for _, tc := range []struct {+ name string+ task Task+ }{+ {"chat", Task{ChatSessionID: "chat-1"}},+ {"quick-create", Task{QuickCreatePrompt: "make an issue"}},+ {"autopilot", Task{AutopilotRunID: "run-1"}},+ } {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ prompt := BuildPrompt(tc.task, "claude")+ for _, banned := range []string{"**Turn mode: Reply.**", "**Turn mode: Ownership.**"} {+ if strings.Contains(prompt, banned) {+ t.Errorf("%s prompt must not carry %q\n---\n%s", tc.name, banned, prompt)+ }+ }+ })+ }+}++// The brief's router must describe the markers the prompt actually emits.+// A drift here is exactly the bug this pair of changes fixes, and it is+// invisible at runtime until an agent silently picks the wrong mode.+func TestBriefModeRouterMatchesPromptMarkers(t *testing.T) {+ t.Parallel()++ brief, err := execenv.InjectRuntimeConfig(t.TempDir(), "claude", execenv.TaskContextForEnv{IssueID: "issue-1"})+ if err != nil {+ t.Fatalf("InjectRuntimeConfig: %v", err)+ }+ for _, want := range []string{"`Turn mode: Reply.`", "`Turn mode: Ownership.`"} {+ if !strings.Contains(brief, want) {+ t.Errorf("brief mode router does not name %s\n---\n%s", want, brief)+ }+ }+ // The retired wording keyed off the prompt's first line, which was never+ // actually the [NEW COMMENT] block.+ if strings.Contains(brief, "It opens with a `[NEW COMMENT]` block") {+ t.Error("brief still routes on the prompt's opening line; it must route on the explicit marker")+ }+}