Skip to content

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

Go

MUL-6986 refactor(skills): merge built-in skills into one platform skill and drop source maps (#7968)

Bohan Jiang0242f37154e9
diff --git a/CLAUDE.md b/CLAUDE.md
index 3d0953e6d5..2b0ffb94f7 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -127,7 +127,7 @@ These are hard requirements for every new or modified database design and produc
- If a flow or API is being replaced and the product is not live, prefer removing the old path instead of preserving both.
- New global pre-workspace routes must be a single word (`/login`, `/inbox`) or `/{noun}/{verb}` (`/workspaces/new`). Do not add hyphenated root routes like `/new-workspace`.
- Reserved slugs live in `server/internal/handler/reserved_slugs.json`. Edit it, run `pnpm generate:reserved-slugs`, and commit the generated `packages/core/paths/reserved-slugs.ts`.
-- When changing CLI commands/flags, API fields, or product behavior documented by built-in skills under `server/internal/service/builtin_skills/*`, update the relevant `SKILL.md` and `references/*-source-map.md` in the same PR.
+- When changing CLI commands/flags, API fields, or product behavior documented by built-in skills under `server/internal/service/builtin_skills/*`, update the relevant `references/<domain>.md` in the same PR.
## API Compatibility
diff --git a/server/cmd/multica/cmd_agent_mcp.go b/server/cmd/multica/cmd_agent_mcp.go
index b2a4623d29..615ed0016c 100644
--- a/server/cmd/multica/cmd_agent_mcp.go
+++ b/server/cmd/multica/cmd_agent_mcp.go
@@ -12,8 +12,6 @@ import (
)
// Assigning a workspace MCP server to an agent, mirroring `agent skills`.
-// Kept in its own file so cmd_agent.go's line references — which the
-// multica-creating-agents source map cites — stay stable.
var agentMcpCmd = &cobra.Command{
Use: "mcp",
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 3c82c389df..4881307254 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -209,6 +209,7 @@ func daemonCommonCapabilities() []string {
protocol.DaemonCapabilityLocalWorktreeV1,
protocol.DaemonCapabilitySourceContextQuickCreateV1,
protocol.DaemonCapabilityRPCV1,
+ protocol.DaemonCapabilityPlatformSkillV1,
}
}
diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.go
index a94fca52c3..a78607e10f 100644
--- a/server/internal/daemon/client_test.go
+++ b/server/internal/daemon/client_test.go
@@ -43,6 +43,14 @@ func TestClient_IdentityHeaders_PostJSON(t *testing.T) {
// is cancelled with an upgrade prompt (MUL-5707). Pin it here so
// dropping it from the list can never be a silent change.
protocol.DaemonCapabilityLocalWorktreeV1,
+ // Same shape, opposite default: this daemon's brief names the
+ // merged multica-platform skill, and advertising that is what
+ // stops the server shipping it a redirect stub under the old name
+ // (MUL-6986). Dropping it would silently hand every task on this
+ // machine a skill it does not need; the failure is extra payload
+ // and a stale signpost, neither of which any other test would
+ // notice.
+ protocol.DaemonCapabilityPlatformSkillV1,
} {
if !capabilities[want] {
t.Errorf("X-Client-Capabilities missing %q: %v", want, capabilities)
diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.go
index 3102b76256..f134bc0945 100644
--- a/server/internal/daemon/execenv/execenv_test.go
+++ b/server/internal/daemon/execenv/execenv_test.go
@@ -6112,16 +6112,18 @@ func TestInjectRuntimeConfigIssueMetadataSectionScope(t *testing.T) {
// MUL-5442: the brief keeps only what the interface cannot
// express — the read stance, the re-read bar, and the two
// write-time boundaries (secrets, length). The full ban list
- // and the key-naming conventions live in the
- // multica-working-on-issues skill, pinned by
- // TestWorkingOnIssuesSkillCoversIssueLoopContracts so this
- // pointer cannot dangle. The recommended-keys block was
+ // and the key-naming conventions live in the multica-platform
+ // skill, pinned by TestPlatformSkillCoversPlatformContracts.
+ // The pointer names whichever skill this task actually received
+ // and is omitted when neither is installed
+ // (TestBriefIssuePointerFollowsTheInstalledSkill), so it cannot
+ // dangle in either upgrade direction. The recommended-keys block was
// removed outright: metadata is deliberately free-form custom
// state (owner decision on MUL-5442), not a vocabulary the
// platform curates in every brief.
"never secrets or long content",
"multica issue metadata delete",
- "the `multica-working-on-issues` skill",
+ "`references/issues.md` in the `multica-platform` skill",
},
}
withoutSection := wantSection{
@@ -6160,6 +6162,7 @@ func TestInjectRuntimeConfigIssueMetadataSectionScope(t *testing.T) {
ctx: TaskContextForEnv{
IssueID: "issue-md-1",
TriggerCommentID: "comment-md-1",
+ AgentSkills: []SkillContextForEnv{platformSkillFixture()},
},
provider: "claude",
filename: "CLAUDE.md",
@@ -6190,8 +6193,11 @@ func TestInjectRuntimeConfigIssueMetadataSectionScope(t *testing.T) {
want: withSection,
},
{
- name: "assignment_triggered",
- ctx: TaskContextForEnv{IssueID: "issue-md-2"},
+ name: "assignment_triggered",
+ ctx: TaskContextForEnv{
+ IssueID: "issue-md-2",
+ AgentSkills: []SkillContextForEnv{platformSkillFixture()},
+ },
provider: "claude",
filename: "CLAUDE.md",
workflowStepPresent: []string{
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 7c8c384f4f..23094ec2d9 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -443,11 +443,15 @@ func writeProjectContext(b *strings.Builder, ctx TaskContextForEnv) {
// writeIssueMetadata emits the Issue Metadata discipline section
// (compressed). The dispatcher gates by kind.hasIssueContext(); this
// helper does not re-check.
-func writeIssueMetadata(b *strings.Builder) {
+func writeIssueMetadata(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("## Issue Metadata\n\n")
b.WriteString("`metadata` is a small per-issue KV bag — custom key-value state your workflow wants future runs on this issue to re-read. Most runs write nothing.\n\n")
b.WriteString("- **Read on entry.** Hints, not truth: latest comment / code wins on conflict. Empty `{}` is normal.\n")
- b.WriteString("- **Write on exit.** Only what a future run will actually re-read — short values, never secrets or long content. Overwrite or `multica issue metadata delete` stale keys. Full write discipline: the `multica-working-on-issues` skill.\n\n")
+ b.WriteString("- **Write on exit.** Only what a future run will actually re-read — short values, never secrets or long content. Overwrite or `multica issue metadata delete` stale keys.")
+ if where, ok := issueContractsSkill(modelVisibleSkills(ctx.AgentSkills)); ok {
+ b.WriteString(" Full write discipline: " + where + ".")
+ }
+ b.WriteString("\n\n")
}
// writeInstructionPrecedence emits the "Agent Identity wins over the issue
@@ -709,14 +713,63 @@ func writeWorkflowIssue(b *strings.Builder, ctx TaskContextForEnv) {
// writeSubIssueCreation emits the Sub-issue Creation section.
//
-// MUL-5442 demotes the full todo/backlog/stage playbook to the
-// multica-working-on-issues built-in skill: the semantics are only needed at
-// the moment an agent is about to create sub-issues, and that moment is
-// exactly what triggers the skill. The brief keeps the one-line map so the
-// flags remain discoverable without the skill.
-func writeSubIssueCreation(b *strings.Builder) {
+// MUL-5442 demotes the full todo/backlog/stage playbook to the multica-platform
+// built-in skill: the semantics are only needed at the moment an agent is about
+// to create sub-issues, and that moment is exactly what triggers the skill. The
+// brief keeps the one-line map so the flags remain discoverable without it.
+func writeSubIssueCreation(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("## Sub-issue Creation\n\n")
- b.WriteString("`--status todo` starts an agent-assigned child immediately; `--status backlog` parks it for later promotion; `--stage <N>` groups children into ordered stages. Before creating sub-issues, read the `multica-working-on-issues` skill — it covers serial chains, promotion, and stage wake semantics.\n\n")
+ b.WriteString("`--status todo` starts an agent-assigned child immediately; `--status backlog` parks it for later promotion; `--stage <N>` groups children into ordered stages.")
+ if where, ok := issueContractsSkill(modelVisibleSkills(ctx.AgentSkills)); ok {
+ b.WriteString(" Before creating sub-issues, read " + where + " — it covers serial chains, promotion, and stage wake semantics.")
+ }
+ b.WriteString("\n\n")
+}
+
+// platformSkillName is the built-in skill that holds Multica's platform
+// contracts. It mirrors service.PlatformSkillName, which the daemon must not
+// import; the brief's rendered-output tests pin the two together.
+const platformSkillName = "multica-platform"
+
+// legacyIssueSkillName is what that skill was called before the platform
+// merge (MUL-6986). A daemon can outlive the backend it talks to in either
+// direction — a backend deploy does not update installed apps, and an app
+// update does not wait for a deploy — so the brief resolves the name it points
+// at from the skills this task actually received instead of hardcoding one.
+const legacyIssueSkillName = "multica-working-on-issues"
+
+// issueContractsSkill returns how the brief should refer to the skill carrying
+// the issue contracts, and whether any such skill is installed at all.
+//
+// Naming a skill the agent does not have is worse than saying nothing: it sends
+// the agent hunting, and on a miss it may skip the contract entirely. So an
+// unrecognised skill set yields no pointer rather than a guess.
+func issueContractsSkill(skills []SkillContextForEnv) (string, bool) {
+ if slug, ok := builtinSlug(skills, platformSkillName); ok {
+ return "`references/issues.md` in the `" + slug + "` skill", true
+ }
+ if slug, ok := builtinSlug(skills, legacyIssueSkillName); ok {
+ return "the `" + slug + "` skill", true
+ }
+ return "", false
+}
+
+// builtinSlug finds a built-in by name.
+//
+// Stated assumption: `multica-` is the platform namespace, and no workspace
+// skill in the batch shares a built-in's name. If one ever did, it would be
+// listed first, take the bare slug, and this pointer would name it instead of
+// the platform skill. That is accepted rather than handled — it needs a user to
+// author a skill that sanitizes to exactly `multica-platform`, and the fix when
+// it happens is to reject the prefix at skill create/import, not to make every
+// pointer defensive.
+func builtinSlug(skills []SkillContextForEnv, name string) (string, bool) {
+ for _, skill := range skills {
+ if skill.Name == name {
+ return skill.Name, true
+ }
+ }
+ return "", false
}
// writeSkills emits the Skills section: an index of invocable skill names.
@@ -747,6 +800,17 @@ func writeSkills(b *strings.Builder, ctx TaskContextForEnv) {
fmt.Fprintf(b, "- **%s**\n", skill.Name)
}
b.WriteString("\n")
+ platformSlug, _ := builtinSlug(skills, platformSkillName)
+ // One recall hint for the platform skill, because it is the only listed
+ // skill whose trigger is "the platform itself" rather than a task the
+ // agent already knows it is doing. Its single description now covers eight
+ // domains that used to advertise one apiece, so an agent reaching for a
+ // Multica contract has one name to guess instead of eight — this line is
+ // what keeps that consolidation from costing recall, and it must therefore
+ // name the skill that actually holds those contracts.
+ if platformSlug != "" {
+ b.WriteString("For a Multica platform action this brief does not fully cover — issue and PR contracts, mentions, agents, squads, autopilots, projects, runtimes, skill import — load the `" + platformSlug + "` skill and open the reference(s) its routing table names for the domains your task touches.\n\n")
+ }
}
// writeMentions emits the @mention side-effects section (compressed).
@@ -925,7 +989,7 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {
writeProjectContext(&b, ctx)
if kind.hasIssueContext() {
- writeIssueMetadata(&b)
+ writeIssueMetadata(&b, ctx)
}
if kind == kindIssue {
@@ -945,7 +1009,7 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {
}
if kind.hasIssueContext() && ctx.IssueID != "" {
- writeSubIssueCreation(&b)
+ writeSubIssueCreation(&b, ctx)
}
// Every kind, quick-create included. Quick-create used to be skipped here
diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.go
index 8b611f51f9..12eb78cd4c 100644
--- a/server/internal/daemon/execenv/runtime_config_test.go
+++ b/server/internal/daemon/execenv/runtime_config_test.go
@@ -19,6 +19,16 @@ import (
// that remains is the `--status todo` vs `--status backlog` rule for
// creating sub-issues, which is unrelated to the notification path.
+// platformSkillFixture is the built-in every issue brief expects to be able to
+// point at. The pointer is resolved from the task's actual skills, so a brief
+// built without it deliberately carries no pointer at all.
+func platformSkillFixture() SkillContextForEnv {
+ return SkillContextForEnv{
+ Name: "multica-platform",
+ Content: "---\nname: multica-platform\n---\n\nbody",
+ }
+}
+
func TestSubIssueCreationSectionPresentForIssueRuns(t *testing.T) {
t.Parallel()
cases := []struct {
@@ -27,13 +37,17 @@ func TestSubIssueCreationSectionPresentForIssueRuns(t *testing.T) {
}{
{
name: "assignment-triggered",
- ctx: TaskContextForEnv{IssueID: "11111111-2222-3333-4444-555555555555"},
+ ctx: TaskContextForEnv{
+ IssueID: "11111111-2222-3333-4444-555555555555",
+ AgentSkills: []SkillContextForEnv{platformSkillFixture()},
+ },
},
{
name: "comment-triggered",
ctx: TaskContextForEnv{
IssueID: "22222222-3333-4444-5555-666666666666",
TriggerCommentID: "33333333-4444-5555-6666-777777777777",
+ AgentSkills: []SkillContextForEnv{platformSkillFixture()},
},
},
}
@@ -48,15 +62,14 @@ func TestSubIssueCreationSectionPresentForIssueRuns(t *testing.T) {
}
for _, want := range []string{
// MUL-5442 demotes the full todo/backlog/stage playbook to the
- // multica-working-on-issues skill. The brief keeps a one-line
- // map (all three flags stay discoverable, MUL-3508 follow-up)
- // plus the skill pointer; the skill side of the contract is
- // asserted in internal/service
- // (TestWorkingOnIssuesSkillCoversIssueLoopContracts).
+ // multica-platform skill. The brief keeps a one-line map (all
+ // three flags stay discoverable, MUL-3508 follow-up) plus the
+ // skill pointer; the skill side of the contract is asserted in
+ // internal/service (TestPlatformSkillCoversPlatformContracts).
"`--status todo` starts an agent-assigned child immediately",
"`--status backlog` parks it",
"`--stage <N>` groups children into ordered stages",
- "read the `multica-working-on-issues` skill",
+ "read `references/issues.md` in the `multica-platform` skill",
} {
if !strings.Contains(out, want) {
t.Errorf("[%s] section missing %q", tc.name, want)
@@ -2118,6 +2131,171 @@ func TestBriefSkillsListIsNamesOnly(t *testing.T) {
}
}
+// TestBriefIssuePointerFollowsTheInstalledSkill covers the compatibility
+// direction the server cannot reach (MUL-6986).
+//
+// The brief is assembled here, in the daemon, from a binary the user installs
+// on their own schedule. A backend deploy does not rewrite it, and an app
+// update does not wait for a deploy, so both skews happen:
+//
+// - old daemon, new backend — the server ships a redirect stub under the old
+// name, because this code is already frozen on that machine;
+// - new daemon, old backend — the server has no idea the merge happened, so
+// THIS code has to cope, which is why the pointer is resolved from the
+// skills the task actually received rather than hardcoded.
+//
+// The third case is the one that matters most: when neither skill is installed
+// the brief says nothing. Naming a skill the agent does not have is worse than
+// omitting the pointer — it sends the agent hunting, and on a miss it may skip
+// the contract altogether.
+func TestBriefIssuePointerFollowsTheInstalledSkill(t *testing.T) {
+ t.Parallel()
+
+ skill := func(name string) SkillContextForEnv {
+ return SkillContextForEnv{Name: name, Content: "---\nname: " + name + "\n---\n\nbody"}
+ }
+
+ cases := []struct {
+ name string
+ skills []SkillContextForEnv
+ want string // exact pointer text; "" = no pointer at all
+ }{
+ {
+ name: "current backend",
+ skills: []SkillContextForEnv{skill("multica-platform")},
+ want: "`references/issues.md` in the `multica-platform` skill",
+ },
+ {
+ // New daemon against a backend that has not been deployed yet.
+ name: "pre-merge backend",
+ skills: []SkillContextForEnv{skill("multica-working-on-issues")},
+ want: "the `multica-working-on-issues` skill",
+ },
+ {
+ // Mid-transition: the redirect stub rides along with the merged
+ // skill. The merged skill wins — the stub is only a signpost.
+ name: "merged skill wins over the redirect stub",
+ skills: []SkillContextForEnv{skill("multica-working-on-issues"), skill("multica-platform")},
+ want: "`references/issues.md` in the `multica-platform` skill",
+ },
+ {
+ name: "neither installed",
+ skills: []SkillContextForEnv{skill("pr-review")},
+ want: "",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ out := buildMetaSkillContent("claude", TaskContextForEnv{
+ IssueID: "issue-1",
+ AgentSkills: tc.skills,
+ })
+
+ // The flags themselves are unconditional: they stay discoverable
+ // with or without a skill to point at.
+ for _, always := range []string{
+ "`--status todo` starts an agent-assigned child immediately",
+ "`--stage <N>` groups children into ordered stages",
+ "never secrets or long content",
+ } {
+ if !strings.Contains(out, always) {
+ t.Errorf("brief lost unconditional content %q", always)
+ }
+ }
+
+ if tc.want == "" {
+ for _, banned := range []string{"Full write discipline:", "Before creating sub-issues, read"} {
+ if strings.Contains(out, banned) {
+ t.Errorf("brief points at a skill with none installed (%q):\n%s", banned, out)
+ }
+ }
+ return
+ }
+ if !strings.Contains(out, "Full write discipline: "+tc.want+".") {
+ t.Errorf("metadata pointer does not name %q:\n%s", tc.want, out)
+ }
+ if !strings.Contains(out, "Before creating sub-issues, read "+tc.want+" —") {
+ t.Errorf("sub-issue pointer does not name %q:\n%s", tc.want, out)
+ }
+ })
+ }
+}
+
+// TestBriefPointsAtThePlatformSkill pins the one recall hint the Skills section
+// carries (MUL-6986).
+//
+// Eight domain skills advertised eight descriptions in the always-loaded
+// listing; they are now one skill with one description, which is cheaper but
+// gives an agent one name to guess instead of eight. This line is what pays
+// that back, so it must appear whenever the skill does — an agent that cannot
+// find the platform contracts is strictly worse off than before the merge.
+//
+// Naming is by bare name, on the stated assumption that no workspace skill
+// shares a built-in's name (see builtinSlug).
+func TestBriefPointsAtThePlatformSkill(t *testing.T) {
+ t.Parallel()
+
+ skill := func(name string) SkillContextForEnv {
+ return SkillContextForEnv{Name: name, Content: "---\nname: " + name + "\n---\n\nbody"}
+ }
+
+ cases := []struct {
+ name string
+ skills []SkillContextForEnv
+ want string // the slug the pointer must name; "" = no pointer
+ }{
+ {
+ name: "platform skill present",
+ skills: []SkillContextForEnv{skill("multica-platform")},
+ want: "multica-platform",
+ },
+ {
+ name: "alongside workspace skills",
+ skills: []SkillContextForEnv{skill("pr-review"), skill("multica-platform")},
+ want: "multica-platform",
+ },
+ {
+ name: "platform skill absent",
+ skills: []SkillContextForEnv{skill("pr-review")},
+ want: "",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ out := buildMetaSkillContent("claude", TaskContextForEnv{
+ IssueID: "issue-1",
+ AgentName: "Eve",
+ AgentID: "eve-1",
+ AgentSkills: tc.skills,
+ })
+ if tc.want == "" {
+ if strings.Contains(out, "skill and open the reference") {
+ t.Errorf("brief emitted a platform pointer with no built-in platform skill present:\n%s", out)
+ }
+ return
+ }
+ want := "load the `" + tc.want + "` skill"
+ if !strings.Contains(out, want) {
+ t.Errorf("brief does not point at %q:\n%s", tc.want, out)
+ }
+ // Pinned as "the domains your task touches", never a count: a task
+ // that spans squads + issues + mentions needs all three, and
+ // wording that implies one would make the agent act on contracts
+ // it has not read.
+ if !strings.Contains(out, "for the domains your task touches") {
+ t.Errorf("pointer does not route by domain:\n%s", out)
+ }
+ if strings.Contains(out, "the one reference") {
+ t.Errorf("pointer narrows on-demand reading to a single reference:\n%s", out)
+ }
+ })
+ }
+}
+
// Every brief that teaches `--output json` also says not to merge stderr into
// it, because the two facts are only useful together. The CLI is right:
// confirmations go to stderr, JSON goes to stdout, and `--output json | jq` has
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 25101a2126..5b99a0f1e5 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2188,6 +2188,13 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
)
}
useSkillRefs := requestHasClientCapability(r, protocol.DaemonCapabilitySkillBundlesV1)
+ // A daemon older than the multica-platform merge assembles a brief that
+ // still names the built-ins this server stopped shipping. It cannot be
+ // fixed from here — the brief lives in the daemon binary — so the missing
+ // capability buys that daemon a redirect stub under the old name instead of
+ // a dangling pointer. Capability, not version: the version string is only
+ // ever shown to humans.
+ legacySkillRedirects := !requestHasClientCapability(r, protocol.DaemonCapabilityPlatformSkillV1)
var customEnv map[string]string
if agent.CustomEnv != nil {
if err := json.Unmarshal(agent.CustomEnv, &customEnv); err != nil {
@@ -2273,7 +2280,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
resp.Agent.Instructions = service.ComposeMikaInstructions(agent.Name, agent.Instructions)
}
if useSkillRefs {
- _, skillRefs, err := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)
+ _, skillRefs, err := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID, agent.SystemKey.String, legacySkillRedirects)
if err != nil {
return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, h.rejectClaimSkillLoad(task, err)
}
@@ -2285,7 +2292,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, h.rejectClaimSkillLoad(task, err)
}
agentSkillCount = len(skills)
- builtinSkills := h.TaskService.BuiltinSkills()
+ builtinSkills := h.TaskService.BuiltinSkills(agent.SystemKey.String, legacySkillRedirects)
builtinSkillCount = len(builtinSkills)
skills = append(skills, builtinSkills...)
resp.Agent.Skills = skills
diff --git a/server/internal/handler/daemon_legacy_skill_redirect_test.go b/server/internal/handler/daemon_legacy_skill_redirect_test.go
new file mode 100644
index 0000000000..f0511021f0
--- /dev/null
+++ b/server/internal/handler/daemon_legacy_skill_redirect_test.go
@@ -0,0 +1,115 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// TestClaimTaskByRuntime_LegacySkillRedirectFollowsTheCapability covers the
+// wiring the two end-to-end tests leave out (MUL-6986).
+//
+// The service test drives the decision by passing a bool straight in, and the
+// brief test hand-builds a skill set. Both ends were covered while the middle —
+// X-Client-Capabilities on the claim request, through the handler, into the
+// payload the daemon actually receives — was not. If that link ever breaks, the
+// other two tests stay green: an old daemon would silently lose its redirect
+// and its brief would point at a skill nobody shipped, or every current daemon
+// would start paying for a stub it does not need.
+//
+// Both claim branches are covered because they compute the built-in set
+// separately: the slim skill-refs claim and the older inline-skills claim.
+func TestClaimTaskByRuntime_LegacySkillRedirectFollowsTheCapability(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ const legacy = "multica-working-on-issues"
+
+ tests := []struct {
+ name string
+ fixture string
+ capabilities string
+ wantRedirect bool
+ }{
+ {
+ // A daemon released before the merge: its brief still names the old
+ // skill, so the server has to ship something under that name.
+ name: "inline claim without the capability",
+ fixture: "legacyredirinline",
+ capabilities: "",
+ wantRedirect: true,
+ },
+ {
+ name: "skill-refs claim without the capability",
+ fixture: "legacyredirrefs",
+ capabilities: protocol.DaemonCapabilitySkillBundlesV1,
+ wantRedirect: true,
+ },
+ {
+ // A current daemon names multica-platform itself and must not be
+ // charged for the stub.
+ name: "inline claim with the capability",
+ fixture: "legacyredirinlinenew",
+ capabilities: protocol.DaemonCapabilityPlatformSkillV1,
+ wantRedirect: false,
+ },
+ {
+ name: "skill-refs claim with the capability",
+ fixture: "legacyredirrefsnew",
+ capabilities: protocol.DaemonCapabilitySkillBundlesV1 + "," + protocol.DaemonCapabilityPlatformSkillV1,
+ wantRedirect: false,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx := context.Background()
+ runtimeID, _, _ := seedSkillLoadFixture(t, ctx, tc.fixture)
+
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, tc.fixture+"-daemon")
+ if tc.capabilities != "" {
+ req.Header.Set("X-Client-Capabilities", tc.capabilities)
+ }
+ req = withURLParam(req, "runtimeId", runtimeID)
+
+ var resp struct {
+ Task struct {
+ Agent *struct {
+ Skills []service.AgentSkillData `json:"skills"`
+ SkillRefs []service.AgentSkillRefData `json:"skill_refs"`
+ } `json:"agent"`
+ } `json:"task"`
+ }
+ testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK).JSON(&resp)
+ agent := resp.Task.Agent
+ if agent == nil {
+ t.Fatal("claim returned no agent payload")
+ }
+ if len(agent.Skills) == 0 && len(agent.SkillRefs) == 0 {
+ t.Fatal("claim delivered neither inline skills nor skill refs")
+ }
+
+ names := map[string]bool{}
+ for _, s := range agent.Skills {
+ names[s.Name] = true
+ }
+ for _, r := range agent.SkillRefs {
+ names[r.Name] = true
+ }
+
+ // Whichever branch ran must have delivered the merged skill; the
+ // redirect only ever adds to that, it never stands in for it.
+ if !names[service.PlatformSkillName] {
+ t.Errorf("claim payload is missing %q; names=%v", service.PlatformSkillName, names)
+ }
+ if got := names[legacy]; got != tc.wantRedirect {
+ t.Errorf("legacy redirect %q present = %v, want %v; names=%v", legacy, got, tc.wantRedirect, names)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/daemon_skill_resolve_scope_test.go b/server/internal/handler/daemon_skill_resolve_scope_test.go
index 8d169bc7bd..e1fb820df9 100644
--- a/server/internal/handler/daemon_skill_resolve_scope_test.go
+++ b/server/internal/handler/daemon_skill_resolve_scope_test.go
@@ -209,7 +209,8 @@ func TestResolveTaskSkillBundles_BuiltinRefTouchesNoWorkspaceQuery(t *testing.T)
spy := &skillQuerySpy{inner: testPool}
runtimeID, taskID, _ := resolveScopeFixture(t, ctx, "resolvebuiltin", "resolvebuiltin-alpha")
- builtins := testHandler.TaskService.BuiltinSkills()
+ // The unscoped set: resolution deliberately serves any built-in by id.
+ builtins := testHandler.TaskService.AllBuiltinSkills()
if len(builtins) == 0 {
t.Skip("no builtin skills embedded in this build")
}
diff --git a/server/internal/handler/handler_writejson_test.go b/server/internal/handler/handler_writejson_test.go
index 625384a5c8..9e042c4280 100644
--- a/server/internal/handler/handler_writejson_test.go
+++ b/server/internal/handler/handler_writejson_test.go
@@ -49,8 +49,8 @@ func TestWriteMeasuredJSONByteIdenticalToWriteJSON(t *testing.T) {
ID: "11111111-2222-3333-4444-555555555555",
Name: "agent <CC> & friends",
Skills: []skill{
- {Name: "multica-working-on-issues", Description: "do work <safely> & well", Files: map[string]string{"SKILL.md": "# Title\n<b>x</b> & y"}},
- {Name: "multica-mentioning", Description: "ping people", Files: map[string]string{"SKILL.md": "line1\nline2"}},
+ {Name: "multica-platform", Description: "do work <safely> & well", Files: map[string]string{"SKILL.md": "# Title\n<b>x</b> & y"}},
+ {Name: "team-conventions", Description: "ping people", Files: map[string]string{"SKILL.md": "line1\nline2"}},
},
Args: []string{"--flag", "a<b", "c&d"},
}}},
diff --git a/server/internal/service/builtin_skills.go b/server/internal/service/builtin_skills.go
index f7d9425c2d..e748c775ce 100644
--- a/server/internal/service/builtin_skills.go
+++ b/server/internal/service/builtin_skills.go
@@ -10,41 +10,116 @@ import (
//go:embed builtin_skills
var builtinSkillsFS embed.FS
-const builtinSkillsRoot = "builtin_skills"
+// Redirect stubs for built-ins this server no longer ships, keyed by the name
+// an older daemon's runtime brief still points at. See legacyRedirectSkills.
+//
+//go:embed builtin_skills_legacy
+var legacyBuiltinSkillsFS embed.FS
+
+const (
+ builtinSkillsRoot = "builtin_skills"
+ legacyBuiltinSkillsRoot = "builtin_skills_legacy"
+)
+
+// PlatformSkillName is the built-in skill carrying Multica's platform
+// contracts — issues, mentions, agents, squads, autopilots, projects, runtimes
+// and skill import — behind one routing SKILL.md. Every agent receives it.
+//
+// The daemon's runtime brief names the same skill from its own constant: the
+// daemon runs on the user's machine and must not import this package, so the
+// two are pinned by the brief's rendered-output tests instead of a shared
+// symbol.
+const PlatformSkillName = "multica-platform"
-// BuiltinSkills returns the platform's built-in skills, embedded at compile
-// time. Every agent receives these on top of its workspace-bound skills, so
-// they teach platform-wide "how to" workflows (e.g. mentioning) that the
-// runtime brief intentionally leaves to skills.
+// builtinSkillSystemKey restricts a built-in skill to one product-defined
+// agent, keyed by that agent's system key. A skill absent from this map is
+// universal and every agent receives it.
+//
+// The scoping exists because a built-in skill costs every agent that receives
+// it: its description sits in the always-loaded skill listing, and its files
+// are written into every task's workdir. Mika's onboarding walkthrough is one
+// agent's procedure, not a platform contract, so shipping it workspace-wide
+// spent that budget on nine agents out of ten that can never use it.
+var builtinSkillSystemKey = map[string]string{
+ "multica-onboarding": MikaSystemKey,
+}
+
+// BuiltinSkills returns the platform's built-in skills for an agent with the
+// given system key (empty for an ordinary workspace agent), embedded at compile
+// time. Every agent receives the universal ones on top of its workspace-bound
+// skills, so they teach platform-wide "how to" workflows that the runtime brief
+// intentionally leaves to skills.
//
// Layout: builtin_skills/<name>/SKILL.md plus optional supporting files. The
-// <name> directory carries a "multica-" prefix so its on-disk slug can never
-// collide with a workspace skill a user authored (see writeSkillFiles, which
-// derives the skill directory from AgentSkillData.Name).
-func (s *TaskService) BuiltinSkills() []AgentSkillData {
- return loadBuiltinSkills()
+// <name> directory carries a "multica-" prefix: that is the platform
+// namespace, and the brief names built-ins by their bare name on the
+// assumption that no workspace skill shares one. Nothing server-side reserves
+// the prefix today, so a user could author a skill that sanitizes to the same
+// slug and take the bare directory. That is accepted, not handled — when it
+// becomes real, the fix is to reject the prefix at skill create/import rather
+// than to make every pointer defensive.
+// legacyRedirects asks for redirect stubs under the names this server has
+// stopped shipping. The runtime brief is assembled by the daemon, not the
+// server, so a backend deploy cannot rewrite an installed daemon's copy of it:
+// a daemon older than the multica-platform merge still tells its agent to read
+// `multica-working-on-issues`. Passing true for such a daemon keeps that
+// pointer resolvable; the stub carries no contracts of its own, only the new
+// location. Callers decide by capability, never by version string.
+func (s *TaskService) BuiltinSkills(agentSystemKey string, legacyRedirects bool) []AgentSkillData {
+ skills := loadBuiltinSkills(agentSystemKey)
+ if legacyRedirects {
+ skills = append(skills, legacyRedirectSkills()...)
+ }
+ return skills
+}
+
+// legacyRedirectSkills loads the redirect stubs. They live outside
+// builtin_skills/ so that nothing ships them by default — a stub is only ever
+// correct for a daemon whose brief still names the skill it replaces.
+func legacyRedirectSkills() []AgentSkillData {
+ return loadSkillDirs(legacyBuiltinSkillsFS, legacyBuiltinSkillsRoot, func(string) bool { return true })
+}
+
+// AllBuiltinSkills returns every built-in skill regardless of agent scope. Only
+// the bundle-resolve path uses it: the claim already decided which built-ins an
+// agent was told about, and a daemon can only ask to resolve a ref it was
+// handed, so re-deriving the scope there would cost an agent read to re-answer
+// a question the claim answered.
+func (s *TaskService) AllBuiltinSkills() []AgentSkillData {
+ return append(loadBuiltinSkillDirs(func(string) bool { return true }), legacyRedirectSkills()...)
+}
+
+func loadBuiltinSkills(agentSystemKey string) []AgentSkillData {
+ return loadBuiltinSkillDirs(func(name string) bool {
+ want, scoped := builtinSkillSystemKey[name]
+ return !scoped || want == agentSystemKey
+ })
+}
+
+func loadBuiltinSkillDirs(include func(name string) bool) []AgentSkillData {
+ return loadSkillDirs(builtinSkillsFS, builtinSkillsRoot, include)
}
-func loadBuiltinSkills() []AgentSkillData {
- entries, err := fs.ReadDir(builtinSkillsFS, builtinSkillsRoot)
+func loadSkillDirs(fsys embed.FS, root string, include func(name string) bool) []AgentSkillData {
+ entries, err := fs.ReadDir(fsys, root)
if err != nil {
return nil
}
var skills []AgentSkillData
for _, entry := range entries {
- if !entry.IsDir() {
+ if !entry.IsDir() || !include(entry.Name()) {
continue
}
- if skill, ok := loadBuiltinSkill(entry.Name()); ok {
+ if skill, ok := loadBuiltinSkill(fsys, root, entry.Name()); ok {
skills = append(skills, skill)
}
}
return skills
}
-func loadBuiltinSkill(name string) (AgentSkillData, bool) {
- dir := path.Join(builtinSkillsRoot, name)
- content, err := fs.ReadFile(builtinSkillsFS, path.Join(dir, "SKILL.md"))
+func loadBuiltinSkill(fsys embed.FS, root, name string) (AgentSkillData, bool) {
+ dir := path.Join(root, name)
+ content, err := fs.ReadFile(fsys, path.Join(dir, "SKILL.md"))
if err != nil {
// A skill directory without a SKILL.md is malformed — skip it rather
// than ship an empty skill.
@@ -52,8 +127,8 @@ func loadBuiltinSkill(name string) (AgentSkillData, bool) {
}
skill := AgentSkillData{Name: name, Content: string(content)}
// Any other file in the directory becomes a supporting file, preserving
- // its relative path so subdirectories (e.g. rules/styling.md) survive.
- _ = fs.WalkDir(builtinSkillsFS, dir, func(p string, d fs.DirEntry, walkErr error) error {
+ // its relative path so subdirectories (e.g. references/issues.md) survive.
+ _ = fs.WalkDir(fsys, dir, func(p string, d fs.DirEntry, walkErr error) error {
if walkErr != nil || d.IsDir() {
return walkErr
}
@@ -61,7 +136,7 @@ func loadBuiltinSkill(name string) (AgentSkillData, bool) {
if rel == "SKILL.md" {
return nil
}
- data, readErr := fs.ReadFile(builtinSkillsFS, p)
+ data, readErr := fs.ReadFile(fsys, p)
if readErr != nil {
return nil
}
diff --git a/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md b/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md
deleted file mode 100644
index 4c20b58ed8..0000000000
--- a/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Autopilots source map
-
-- `server/cmd/multica/cmd_autopilot.go` registers `list`, `get`, `create`, `update`, `delete`, `trigger`, `runs`, `trigger-add`, `trigger-update`, `trigger-delete`, and `trigger-rotate-url`.
-- The CLI maps reads/writes to `/api/autopilots`, `/api/autopilots/{id}`, `/api/autopilots/{id}/trigger`, `/api/autopilots/{id}/runs`, and trigger subroutes. `autopilot get` nulls `webhook_token`, `webhook_path`, and `webhook_url` in normal JSON output and adds `has_webhook_token` plus `webhook_token_hint`; `--show-secrets` is an explicit JSON-only escape hatch that prints a credential-exposure warning to stderr.
-- `server/internal/service/autopilot.go` has `DispatchAutopilot`, synchronous delivery-idempotent `AdmitAutopilotWebhookDelivery`, and worker-side `DispatchAutopilotForWebhookDelivery`; it creates `autopilot_run` and switches on `execution_mode`.
-- `create_issue` calls `dispatchCreateIssue`; `run_only` calls `dispatchRunOnly`.
-- `resolveAutopilotLeader` resolves squad-assigned autopilots to the squad leader.
-- `AgentReadiness` blocks archived/runtime-unready agents before enqueue.
-- `server/cmd/server/router.go` exposes authenticated `/api/autopilots` routes and unauthenticated webhook ingress `/api/webhooks/autopilots/{token}`.
-- `server/internal/handler/autopilot_webhook.go` durably stores public webhook deliveries, synchronously admits an idempotent run for the compatible `200 accepted|skipped` + `run_id` response, and wakes the worker.
-- `server/internal/handler/webhook_delivery_worker.go` claims queued deliveries with expiring database leases, applies per-trigger dispatch pacing, and resumes admitted runs using `autopilot_run.webhook_delivery_id` so recovery cannot duplicate a run/task.
-- `GET /api/autopilots/cron-preview?expr=&tz=` (`server/internal/handler/autopilot_cron_preview.go`) returns `{next_runs}` — the next 3 occurrences as RFC3339 UTC — or 400 with the parser/timezone error. Compute-only (no autopilot is touched), gated by workspace membership; schedule editors use it instead of approximating the next run client-side.
-- Write/execute authorization lives in `autopilotWriteByOwnership` / `memberCanWriteAutopilot` / `requireAutopilotWrite` (`server/internal/handler/autopilot.go`): editing, deleting, triggering, replaying deliveries, and managing triggers/webhook secrets require the autopilot's creator, a workspace owner/admin, or an explicit collaborator. Reads (list/get/runs/deliveries) stay open to any workspace member, but `GetAutopilot` redacts `webhook_token`/`webhook_path`/`webhook_url` for callers who lack write access, since the token alone can trigger the autopilot. Creating a new autopilot is still open to any member (they become its creator). This is the autopilot-level View/Write layer; it is independent of, and ANDed with, the private-assignee-agent gate enforced at dispatch time in `shouldSkipDispatch`.
-- Explicit write grants ("collaborators") are stored in the `autopilot_collaborator` table (migration 128, members-only, no FK — deleted alongside the autopilot in the delete transaction). Endpoints: `POST /api/autopilots/{id}/collaborators` (body `{user_id}`) and `DELETE /api/autopilots/{id}/collaborators/{userId}`, both gated by the NARROWER `requireAutopilotAccessManagement` (creator or workspace owner/admin only — a granted collaborator keeps write/execute but cannot re-grant or revoke peers, preventing privilege escalation), both returning the updated `{collaborators}` list. `GetAutopilot` embeds the `collaborators` array and stamps two per-caller booleans: `can_write` (gates edit/run/trigger controls) and the narrower `can_manage_access` (gates the "Manage access" entry). The web/desktop "Manage access" UI lives in `packages/views/autopilots/components/manage-access-dialog.tsx`.
diff --git a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
deleted file mode 100644
index 95ac29c16c..0000000000
--- a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
+++ /dev/null
@@ -1,148 +0,0 @@
-# Creating agents — source map
-
-Evidence layer for `SKILL.md`. Every contract maps to `file:line` on the
-current tree, the runtime effect, and a safe read-only check. Line numbers were
-re-derived against this tree — re-derive again if the files move, the
-surrounding context (not the number) is the anchor.
-
-## Verification
-
-```bash
-# Conformance eval for this skill (and the shared template invariants):
-go test ./internal/service -run TestCreatingAgentsSkillCoversAgentCreationContracts
-go test ./internal/service -run TestBuiltinSkillsConformToTemplate
-```
-
-## CLI entry points — `server/cmd/multica/cmd_agent.go`
-
-| Contract | Line | Behavior | Safe check |
-|---|---|---|---|
-| Create flags: `name`, `description`, `instructions`, `runtime-id` | 160–163 | Registered create flags; `name`/`runtime-id` enforced in `runAgentCreate` | `multica agent create --help` |
-| `runtime-config`, `model`, `thinking-level`, `service-tier`, `custom-args` flags | 164–168 | `model` help: "Prefer this over passing --model in --custom-args"; Codex speed documents three states: empty = inherit local config, `default` = explicit Standard when the installed CLI capability is reported, catalog tier such as `priority` = explicit Fast | `multica agent create --help` |
-| Secret-safe env input: `custom-env`, `custom-env-stdin`, `custom-env-file` | 169–171 | `--custom-env` warns about shell history / `ps`; stdin and file modes keep secrets off the command line; mutually exclusive | `multica agent create --help` |
-| Secret-safe MCP input: `mcp-config`, `mcp-config-stdin`, `mcp-config-file` (create) | 172–174 | Same three-channel pattern as `custom-env`; `--mcp-config` warns about shell history / `ps`; value must be a JSON object or `null` | `multica agent create --help` |
-| MCP flags on `agent update` | 200–202 | Same three channels on update; `--mcp-config null` clears. Unlike `custom_env`, `mcp_config` IS settable via update | `multica agent update --help` |
-| `thinking-level` / `service-tier` flags on `agent update` | 189–190 | Thin pass-throughs; `service-tier` repeats the empty / `default` / catalog-tier contract, and an explicit empty string clears the saved override and restores the runtime/local Codex default | `multica agent update --help` |
-| `max-concurrent-tasks` flags + validation | `cmd_agent.go` 179, 208; `cmd_agent_validation.go` 5–20 | Shared CLI helper enforces 1–50; create/update call it before their HTTP mutation and omitted create flags stay absent | `multica agent create --help`; `multica agent update --help` |
-| `runAgentCreate` builds body + `POST /api/agents` | 533–628 | Only sets a body key when the flag `Changed`; validates `max_concurrent_tasks` at 605–611, then posts to `/api/agents` (617) | read 533–628 |
-| Body assembly: description/instructions/runtime-config/custom-args/custom-env/mcp-config/model/thinking-level/service-tier | 548–611 | `model`, `thinking_level`, and `service_tier` are `Changed`-gated pass-throughs; omitted flags are not sent | read the `runAgentCreate` body assembly |
-| `runAgentUpdate` sends `thinking_level` / `service_tier` / `mcp_config` | 630–725 | Each override key is added only when its flag is `Changed`; `max_concurrent_tasks` is range-checked at 693–699; `custom_env` is intentionally not a flag here | read the `runAgentUpdate` body assembly |
-| `parseMcpConfig` / `resolveMcpConfig` helpers | 1216, 1244 | Validator (object-or-`null`, content-free errors) + three-channel resolver, mirroring `parseCustomEnv`/`resolveCustomEnv` | read 1216–1301 |
-| `agent skills set` = replace-all | 922 | `PUT /api/agents/{id}/skills` (940); `--skill-ids ''` clears all (928–931) | `multica agent skills set --help` |
-| `agent skills add` = additive | 947 | `POST /api/agents/{id}/skills/add` (968); requires ≥1 id (953–958) | `multica agent skills add --help` |
-| `agent skills list` | 890 | reads bindings, no side effect | `multica agent skills list --help` |
-| `agent env get` | 1024 | `GET /api/agents/{id}/env` (1034) | `multica agent env get --help` |
-| `agent env set` | 1059 | `PUT /api/agents/{id}/env` with full `custom_env` map (1079) | `multica agent env set --help` |
-
-## Copy command — `server/cmd/multica/cmd_agent_copy.go`
-
-| Contract | Line | Behavior | Safe check |
-|---|---|---|---|
-| `agentCopyCmd` (`copy <source-agent-id>`) + flag registrar | 21, 47, 54 | Own file with its own `init()` so `cmd_agent.go` line refs stay stable; `registerAgentCopyFlags` is shared with the tests | `multica agent copy --help` |
-| Reads source via `GET /api/agents/<id>` | 95 | Composes over existing endpoints — no dedicated copy API | read `runAgentCopy` |
-| Conversation starters copied without an override flag | `runAgentCopy` conversation-starter body assembly | Copies `conversation_starters` when the source response contains an array; `registerAgentCopyFlags` intentionally exposes no conversation-starter override | `multica agent copy --help` |
-| Same-runtime vs cross-runtime rule | 114, 187 | `sameRuntime` copies `model`/`thinking_level`/`service_tier`; a different `--runtime-id` drops them and requires `--model` (empty allowed) | `multica agent copy --help` |
-| Concurrency copy compatibility | `runAgentCopy`, `copiedAgentMaxConcurrentTasks` | Explicit `--max-concurrent-tasks` is validated before any request; valid source values are copied, while historical values outside 1–50 are omitted so create defaults to 6 | read the concurrency body assembly |
-| Skills copied in the create transaction | 239 | Source skill ids sent as `skill_ids`, bound in the same `POST /api/agents` tx (267); `--no-skills` opts out | read `runAgentCopy` |
-| Secrets never copied | 240–266 | `custom_env`/`mcp_config`/`runtime_config` set only from explicit secret-safe flags, never read from the source | `multica agent copy --help` |
-
-## Create handler — `server/internal/handler/agent.go`
-
-| Contract | Line | Behavior |
-|---|---|---|
-| `maxAgentDescriptionLength = 255` | 31 | Cap is 255 **Unicode code points** (comment: counted via `utf8.RuneCountInString`, matches Postgres `char_length`) |
-| `AgentResponse` omits plaintext `custom_env` | 33–53 | Exposes only `has_custom_env` (52) and `custom_env_key_count` (53); comment cites MUL-2600 |
-| `CreateAgentRequest` fields | 930–970 | Includes `model`, `thinking_level`, and Codex `service_tier` alongside the profile/runtime/permission inputs |
-| Conversation-starter request and validation | `AgentConversationStarter`, `normaliseAgentConversationStarters`, create/update paths | `conversation_starters` is trimmed and validated as at most three complete label/prompt pairs before JSONB persistence; omission defaults to `[]`, update omission preserves, and `[]` clears |
-| `name` required | 623–625 | 400 "name is required" |
-| `description` ≤ 255 code points | 627–629 | `utf8.RuneCountInString(req.Description) > maxAgentDescriptionLength` → 400 |
-| `runtime_id` required | 631–633 | `if req.RuntimeID == ""` → 400 "runtime_id is required" |
-| `runtime_id` must resolve in workspace | 642–658 | parsed + `GetAgentRuntimeForWorkspace`; unknown → 400 "invalid runtime_id" |
-| `thinking_level` provider-level validation | `agent.go` create/update paths | `!agent.IsKnownThinkingValue(runtime.Provider, req.ThinkingLevel)` → 400; fixed-vocabulary providers use an enum (Pi: `off|minimal|low|medium|high|xhigh|max`), Codex/OpenCode use safe-token syntax, and per-model gaps are deferred to daemon (MUL-2339) |
-| `thinking_level` rejection copy | `agent.go` `thinkingLevelRejection` / `existingThinkingLevelRejection` | Splits "runtime has no reasoning control" from "unrecognised token" so a runtime-capability 400 does not read as a typo; both carry-over branches point at `thinking_level=""` (MUL-5770) |
-| `service_tier` provider-level validation | `agent.go` create/update paths | Non-empty values are Codex-only safe tokens; daemon owns the explicit-standard capability check and exact per-model catalog-tier validation |
-| Defaults: `{}` config/env, `[]` args | 688–701 | `RuntimeConfig`→`{}`, `CustomEnv`→`{}`, `CustomArgs`→`[]` when nil, before insert |
-| `visibility` default | 635–636 | `if req.Visibility == "" { req.Visibility = "private" }` — access-control field, not the runtime prompt |
-| `max_concurrent_tasks` create/default validation | `agent.go`; `agent_validation.go`; `internal/agentconfig/concurrency.go` | Shared 1–50 validator; a missing or explicit `null` field defaults to 6, while an explicitly supplied numeric 0/out-of-range value returns 400 |
-| `max_concurrent_tasks` update validation | 1660–1666 | Omission preserves the existing value; a supplied value outside 1–50 returns 400 before persistence |
-| `mcp_config` null-skip on create | 704–705 | raw JSON copied through unless the body value is the literal `null` |
-| `mcp_config` redacted on read | 54, 848–851 | `redactMcpConfig` sets `McpConfigRedacted=true`; a private agent read by a member also redacts (494, 509) |
-| Qwen Code managed-MCP injection | `pkg/agent/qwen.go` | Non-null `mcp_config` is written to a daemon-owned 0600 temporary JSON file and passed with `--mcp-config`; the file is removed after the process exits, while `null` preserves native inheritance. |
-| Assigned workspace MCP servers folded into the agent's | `internal/handler/workspace_mcp.go` `ResolveAgentMcpConfig`; applied in `internal/handler/daemon.go` `buildClaimedTaskResponse` | Only servers bound to this agent AND enabled are folded in; union by name with the agent's own winning; both containers normalized onto `mcpServers`; read on every claim, so an assignment or toggle lands on the agent's next task |
-| Workspace MCP library + assignment API | `internal/handler/workspace_mcp_api.go` | `GET /api/workspaces/{id}/mcp-servers` returns name / transport only, never the entry, for any role; `POST`/`PUT`/`DELETE` on the library are owner/admin; `GET`/`POST`/`PUT .../enabled`/`DELETE /api/agents/{id}/mcp-servers` manage one agent's assignments and admit the agent owner or a workspace owner/admin. Every write refuses agent actors. Deleting a library entry sweeps its bindings in the same transaction (no FK) |
-| Effective-set regression guard | `internal/daemon/runtime_mcp_workspace_test.go` | Runs resolve -> `mergeRuntimeAndAgentMcpConfig` for OpenCode; catches a resolver that emits a container the daemon merge would not read |
-| Random emoji avatar default | `agent_avatar.go` 11–32; `agent.go` 1127–1133 | Omitted, empty, or whitespace-only `avatar_url` becomes a cryptographically selected `emoji:<glyph>` sentinel; explicit values are preserved. |
-| `CreateAgent` insert params | `agent.go` create path | Persists avatar_url, runtime_config, instructions, conversation_starters, custom_env, custom_args, model, thinking_level, service_tier, mcp_config, visibility, max_concurrent_tasks |
-| `UpdateAgent` rejects `custom_env` | 910–913 | if `custom_env` present in body → 400 "use PUT /api/agents/{id}/env (or `multica agent env set`)" |
-| `UpdateAgent` persists / clears `mcp_config` | 944–948, 1060–1061 | Tri-state from the raw body: key omitted → no change; literal `null` → `ClearAgentMcpConfig`; object → replace. No 400 like `custom_env` — `mcp_config` IS updatable here |
-| `description` ≤ 255 on update too | 921–924 | same cap re-checked on update |
-
-## Runtime model/thinking discovery — `server/pkg/agent/{models,thinking}.go`
-
-| Contract | Line | Behavior |
-|---|---|---|
-| Codex model-list entry point | `models.go` 94–103 | `ListModels("codex")` uses cached daemon-local discovery instead of returning the fallback catalog unconditionally |
-| Codex fallback catalog | `models.go` 301–354 | Used for Codex <0.122.0 and failed/malformed discovery; includes current verified visible models plus legacy `gpt-5.3-codex`, with a separate `Thinking` catalog on every model |
-| Codex discovery version gate | `thinking.go` 280, 306–337 | `codex debug models --bundled` is used only for parseable versions ≥0.122.0; unsupported versions and command/parse/empty failures return the static model + thinking fallback |
-| Codex catalog projection | `thinking.go` `parseCodexModelCatalog` / `annotateCodexExplicitStandardServiceTier` | Hidden models are excluded; visible model, reasoning, and `service_tiers` metadata are preserved. Codex 0.133.0+ entries also carry `supports_explicit_standard_service_tier=true`; older daemon responses omit the additive field, which the UI treats as false |
-| Pi RPC model/thinking discovery | `models.go` `discoverPiModelsRPC` / `piThinkingFromRPCModel` | Starts an ephemeral `pi --mode rpc --no-session` process, requests `get_state` + `get_available_models`, preserves extension-registered providers, marks the current model as Default, and mirrors Pi's exact per-model `reasoning` / `thinkingLevelMap` rules. Older/forked Pi falls back to `--list-models` with no guessed thinking catalog. |
-| Pi invocation effort | `pi.go` `buildPiArgs` / `piBlockedArgs` | A non-empty persisted value becomes `--thinking <level>`; custom `--thinking` flags are filtered so the first-class field is the sole owner. |
-| Per-model thinking validation | `thinking.go` `ValidateThinkingLevel` | Accepts only values in the explicit model's `Thinking.SupportedLevels`; Pi empty-model validation resolves to the RPC current-model Default, while an empty Codex model fails closed because its effective `config.toml` model is unknown. |
-| Dynamic Codex token gate | `thinking.go` `IsKnownThinkingValue` | Server persistence accepts syntactically safe Codex/OpenCode/Kimi and ACP-catalog tokens so new catalog values do not require a Multica release; Pi instead uses its fixed seven-token CLI vocabulary. Exact support remains a daemon-local per-model check. |
-| Runtime reasoning capability | `thinking.go` `ThinkingControlSupported` | True for the fixed-enum providers (including Pi), the dynamic-catalog providers (Codex/OpenCode/Kimi), and the ACP-catalog providers in `acpCatalogThinkingProviders`. False for runtimes with no effort dial on the surface the daemon drives — Copilot discovers over ACP but executes through its own CLI, so no live ACP session exists to carry an effort. Provider granularity only: `hermes` reports true because jcode applies an effort, while Hermes Agent under the same provider advertises none and gets no picker — the per-session catalog settles it |
-| Generic ACP effort catalog | `acp_effort.go` `parseACPEffortOption` / `annotateACPThinkingForSessionModel` | One provider-neutral parser reads the effort selector out of any ACP `session/new` response (option id or category `effort` / `thought_level`), taking the advertised values verbatim. CodeBuddy keeps a flag whitelist on top because it applies the level via `--effort`, not over ACP |
-| ACP effort catalogs are per model, not per session | `acp_effort.go` `annotateACPThinkingForSessionModel` | Only the model marked `Default` (the advertised `currentModelId`) is annotated. ACP options may depend on each other, and reasonix v1.21.5 derives the catalog from the current model's provider entry — `deepseek-v4-flash` advertises `low`, `deepseek-v4-pro` does not, and some models expose no effort at all. Copying one catalog across models would offer levels the runtime then refuses. Other models keep `Thinking=nil` until per-model probing exists |
-| ACP effort application | `acp_effort.go` `applyACPEffortOption` | Sends `session/set_config_option` with the id the session advertised, then re-reads `currentValue`. The read-back proves only that the session reports the new value — not that the runtime threaded it into its provider request; it catches Kimi ≤0.28.1 confirming `on` after being set to `max`. Failures warn and let the prompt through rather than failing the task. `stateIsCurrent=false` after a model switch skips the local vocabulary check, because the advertised list then describes the previous model |
-| ACP capability is per runtime, not per provider | `agent.go` `acpThinkingDecision` / `ambiguousACPEffortProviders` | Three-state, consulted on create and both update branches. Catalog advertises an effort → allow; catalog advertises none → capability 400; **no catalog yet** → 400 for ambiguous providers only (`hermes`), because the cache is written solely by `ReportModelListResult`, so a CLI-only caller stays undiscovered indefinitely and "unknown" must not be read as "supported". `reasonix` is unambiguous and stays allowed while undiscovered |
-| ACP effort opt-in | `thinking.go` `acpCatalogThinkingProviders` | A runtime joins only when its `Execute` calls `applyACPEffortOption` AND someone has confirmed from source or a real run that it acts on the setting — currently `reasonix` and `hermes` (GitHub #6720). This list, not the read-back, is where that verification is recorded. `hermes` is the case that shows why the catalog rather than a version gate decides: jcode advertises `reasoning_effort` and threads it into the provider request (verified v0.71.1/v0.73.0), Hermes Agent advertises no configOptions at all (re-verified v0.20.0, 2026-08-11), and both run under the same provider type. Speaking ACP is not sufficient: Copilot discovers over ACP but executes through its own CLI, so a catalog there would render a picker with nothing behind it |
-| Service-tier validation | `thinking.go` `ValidateServiceTier` | Empty inherits local config. `default` requires the daemon-discovered explicit-standard capability and is model-independent; alternative tiers require the explicit Codex model to advertise the exact id, so an empty model fails closed because config.toml is unknown |
-| Daemon invalid-combination handling | `internal/daemon/daemon.go` 3860–3892 | Before execution, invalid `(provider, model, thinking_level)` combinations log a warning and omit the override rather than failing the task |
-
-## Env endpoint — `server/internal/handler/agent_env.go`
-
-| Contract | Line | Behavior |
-|---|---|---|
-| `authorizeAgentEnv` gate | 76 | loads agent, then applies the two checks below |
-| Agent actors denied | 90–94 | `if actorType == "agent"` → 403 "agents may not access env management endpoints" (MUL-2600 impersonation guard); runs FIRST, so an agent is denied even when its backing human owns the target agent |
-| Agent owner or ws owner/admin | 96–103 | `requireWorkspaceRole(..., "owner", "admin", "member")` then `canManageAgentEnv` → 403 otherwise (MUL-5438) |
-| `canManageAgentEnv` predicate | 120 | workspace owner/admin, or `agent.owner_id == member.user_id`; a NULL `owner_id` never matches |
-
-## Routes — `server/cmd/server/router.go`
-
-| Contract | Line | Behavior |
-|---|---|---|
-| `GET /env` | 603 | `h.GetAgentEnv` (plaintext read, gated) |
-| `PUT /env` | 604 | `h.UpdateAgentEnv` (full-map overwrite, gated) |
-
-## Claim-time injection — `server/internal/handler/daemon.go`
-
-| Contract | Line | Behavior |
-|---|---|---|
-| Fresh agent re-read on claim | 1109–1111 | `GetAgent(task.AgentID)` — claim uses persisted fields, not create output |
-| Workspace skills FIRST | 1115 | `skills := h.TaskService.LoadAgentSkills(...)` |
-| Built-ins appended | 1116 | `skills = append(skills, h.TaskService.BuiltinSkills()...)` |
-| Runtime payload | `daemon.go` `TaskAgentData` | Carries `Instructions`, `Skills`, `CustomEnv`, `CustomArgs`, `Model`, `ThinkingLevel`, `ServiceTier`, and `McpConfig`; metadata-only fields remain absent |
-| `custom_args` argv and safe launch log | `internal/daemon/daemon.go` `ExecOptions.CustomArgs`; `pkg/agent/launch.go` `Config.logAgentCommand` | Custom args normally reach the provider process argv. Launch logs preserve flag names but redact inline values and positional/value tokens; OS process-list exposure remains, so credentials belong in `custom_env`. |
-| ZeroClaw agent alias pseudo-args | `pkg/agent/zeroclaw.go` `takeZeroclawAgentAlias` / `zeroclawBlockedArgs` | `--agent` and `--agent-alias` (separate or `=value`) are consumed from `custom_args` and sent as `session/new.agentAlias`; neither token reaches argv because `zeroclaw acp` rejects those CLI flags. Omit the selector for sole-agent auto-selection; use it when multiple agents exist without `[acp].default_agent`. |
-
-## Skill loading — `server/internal/service/task.go`
-
-| Contract | Line | Behavior |
-|---|---|---|
-| `LoadAgentSkills` | 1685 | `ListAgentSkills` + per-skill `ListSkillFiles` → content + supporting files for execution |
-
-## Built-in skills — `server/internal/service/builtin_skills.go`
-
-| Contract | Line | Behavior |
-|---|---|---|
-| `go:embed builtin_skills` | 10–11 | skills embedded at compile time |
-| `loadBuiltinSkill` | 45 | reads `<name>/SKILL.md` (47) + walks sibling files into `Files` (56–68) |
-
-## Persisted columns — `server/pkg/db/generated/agent.sql.go`
-
-| Contract | Line | Behavior |
-|---|---|---|
-| `CreateAgent` INSERT | generated from `queries/agent.sql` | columns include `runtime_config, runtime_id, instructions, conversation_starters, custom_env, custom_args, mcp_config, model, thinking_level, service_tier` |
-| `CreateAgentParams` | generated from `queries/agent.sql` | typed params include nullable `Model`, `ThinkingLevel`, and `ServiceTier` |
-| `UpdateAgent` SET | generated from `queries/agent.sql` | COALESCE updates include model/thinking/service tier; dedicated clear queries restore each nullable override |
-| `UpdateAgentCustomEnv` (called by the `UpdateAgentEnv` handler) | 2652 | `SET custom_env = $2` — the only write path for env values |
diff --git a/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md b/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md
deleted file mode 100644
index ab51f2fe14..0000000000
--- a/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md
+++ /dev/null
@@ -1,146 +0,0 @@
-# Mentioning — source map
-
-Every claim in `SKILL.md` traces to a line below. Re-derive against the current
-tree before trusting any line number; the behavior is the contract, the line is
-a pointer.
-
-## The mention grammar (what parses)
-
-| Fact | Source |
-| --- | --- |
-| `MentionRe` — the only recognizer of a mention link | `server/internal/util/mention.go:16` |
-| Pattern: `` `\[@?(.+?)\]\(mention://(member\|agent\|squad\|issue\|all)/([0-9a-fA-F-]+\|all)\)` `` | `server/internal/util/mention.go:16` |
-| `<type>` group = `member \| agent \| squad \| issue \| all` | `server/internal/util/mention.go:16` |
-| `<id>` group = `[0-9a-fA-F-]+` (hex + dashes) **or** the literal `all` — so a typical name with non-hex letters never matches | `server/internal/util/mention.go:16` |
-| `ParseMentions` extracts and dedups `{Type, ID}` from `m[2]`/`m[3]` | `server/internal/util/mention.go:24-37` |
-| `Mention.Type` doc enum = "member", "agent", "issue", or "all" (squad added in regex) | `server/internal/util/mention.go:7` |
-| `HasMentionAll` reports whether any parsed mention is `all` | `server/internal/util/mention.go:40-47` |
-| **`project` is NOT in the type group** — `[Label](mention://project/<uuid>)` never parses, so it can enqueue nothing. It is a render-only link every client makes navigable — a chip on web/desktop (`RichLink` in `packages/views/rich-content/rich-content.tsx`), an ordinary enriched link whose tap is routed on mobile (`onLinkPress` in `apps/mobile/lib/markdown/markdown.tsx`, which renders no chip) | `server/internal/util/mention.go:16` |
-
-### Parser behavior tests (pin the example shapes the skill uses)
-
-| Case proven | Source |
-| --- | --- |
-| `mention://member/<real-uuid>` parses to `{member, uuid}` | `server/internal/util/mention_test.go:42-45` |
-| `mention://all/all` parses to `{all, all}` | `server/internal/util/mention_test.go:47-50` |
-| `mention://agent/<uuid>` parses; label may contain `[brackets]` | `server/internal/util/mention_test.go:13-35` |
-| plain text with no `mention://` parses to `nil` | `server/internal/util/mention_test.go:57-60` |
-| Skill eval: a name where a UUID belongs (`mention://member/Alice`) parses to `nil`; a bare `@name` parses to `nil`; a real UUID parses; `@all` → `{all, all}`; a **wrong** type with a real UUID still parses (points at the wrong entity) | `server/internal/service/builtin_skills_test.go:101-157` |
-
-## What each mention type enqueues
-
-| Fact | Source |
-| --- | --- |
-| `computeCommentAgentTriggers` is the shared comment trigger computation used by preview and enqueueing | `server/internal/handler/comment.go:1159-1195` |
-| `computeMentionedAgentCommentTriggers` builds the mention trigger set; `enqueueCommentAgentTriggers` is the shared enqueue helper | `server/internal/handler/comment.go:1381-1467,1124-1157` |
-| Comment creation runs `triggerTasksForComment`, which computes triggers, applies suppressions, then enqueues | `server/internal/handler/comment.go:1069,1092-1098` |
-| Comment edit re-triggering also runs `triggerTasksForComment` after cancelling old tasks for the edited comment | `server/internal/handler/comment.go:1577-1594` |
-| `squad` branch: resolve squad in workspace, read `LeaderID`, add the leader trigger | `server/internal/handler/comment.go:1397-1435` |
-| `squad` → shared enqueue helper calls `EnqueueTaskForSquadLeader` | `server/internal/handler/comment.go:1141-1147` |
-| Everything not `agent` after the squad branch is skipped: `if m.Type != "agent" { continue }` | `server/internal/handler/comment.go:1437-1439` |
-| `agent` branch: load agent in workspace, then add the agent trigger | `server/internal/handler/comment.go:1440-1464` |
-| `agent` → shared enqueue helper calls `EnqueueTaskForMention` (a run for that agent) | `server/internal/handler/comment.go:1148-1154` |
-| **`member` and `issue` mentions reach neither branch — they enqueue NOTHING.** A `member` mention fails the `!= "agent"` skip at lines 1437-1439 (the squad branch above it only matches `squad`); an `issue` mention does the same. | `server/internal/handler/comment.go:1397,1437-1439` |
-
-## Preview and suppression
-
-| Fact | Source |
-| --- | --- |
-| Preview route: `POST /api/issues/{id}/comments/trigger-preview` | `server/cmd/server/router.go:707` |
-| Preview handler loads the issue, expands issue identifiers, then calls `computeCommentAgentTriggers` | `server/internal/handler/comment.go:837-911` |
-| Preview request accepts `content`, optional `parent_id`, and optional `editing_comment_id` | `server/internal/handler/comment.go:778-782` |
-| Preview response returns agent `id`, `name`, optional `avatar_url`, `source`, and `reason` | `server/internal/handler/comment.go:784-793` |
-| `editing_comment_id` is parsed as UUID input, scoped to the same workspace and issue, and used as `ExcludeTriggerCommentID` | `server/internal/handler/comment.go:855-872` |
-| Preview validates or derives the parent context for an edit | `server/internal/handler/comment.go:874-897` |
-| `CreateCommentRequest` accepts optional `suppress_agent_ids` | `server/internal/handler/comment.go:770-776` |
-| `UpdateComment` accepts optional `suppress_agent_ids` | `server/internal/handler/comment.go:1509-1513` |
-| Create-comment `suppress_agent_ids` is parsed as request-boundary UUID input | `server/internal/handler/comment.go:957-964` |
-| Update-comment `suppress_agent_ids` is parsed as request-boundary UUID input | `server/internal/handler/comment.go:1523-1535` |
-| Create and edit trigger paths compute the full trigger set, then apply `filterSuppressedCommentAgentTriggers` before enqueueing | `server/internal/handler/comment.go:1092-1122,1594` |
-| Frontend API sends `editing_comment_id` for preview and `suppress_agent_ids` for update when present | `packages/core/api/client.ts:664-700` |
-| Edit UI calls preview with `editingCommentId`, renders trigger chips, tracks suppressed agents, and submits suppressions on save | `packages/views/issues/components/comment-card.tsx:269-274,300-315,359-367,578-582,858-862` |
-| Preview hook includes `editingCommentId` in its query key and sends it to the API | `packages/views/issues/hooks/use-comment-trigger-preview.ts:58-80` |
-| Timeline edit mutation passes suppressed agent IDs through to the API layer | `packages/views/issues/hooks/use-issue-timeline.ts:299-302` |
-
-## Plain replies and implicit routing
-
-| Fact | Source |
-| --- | --- |
-| A direct reply to an agent resolves through `routeReplyToParentAuthor` before any assignee fallback | `server/internal/handler/comment.go` (search `parentComment.AuthorType == "agent"` inside `computeCommentAgentTriggers`) |
-| A member-authored thread with an explicit or task-derived agent owner resolves through `routeThreadRootOwners` and returns before the final fallback | `server/internal/handler/comment.go` (search `routeThreadRootOwners` inside `computeCommentAgentTriggers`) |
-| If the direct parent is a member and no thread owner handled the reply, the reply returns no trigger instead of invoking `routeAssigneeFallback` | `server/internal/handler/comment.go` (search `A plain member-to-member reply`) |
-| Top-level member comments retain the final agent/squad assignee fallback because they have no parent | `server/internal/handler/comment.go` (the final `routeAssigneeFallback` call in `computeCommentAgentTriggers`) |
-| Regression coverage checks Agent and Squad assignees through both trigger preview and actual comment creation/enqueue | `server/internal/handler/comment_trigger_preview_test.go` (search `PlainReplyToUnownedMemberRootSkipsAssigneeFallback`) |
-
-## Edit-preview pending-task dedup
-
-| Fact | Source |
-| --- | --- |
-| Default dedup query skips any queued or dispatched task for the issue and agent | `server/pkg/db/queries/agent.sql:544-548` |
-| Edit-preview dedup query excludes only tasks whose `trigger_comment_id` equals the edited comment | `server/pkg/db/queries/agent.sql:550-558` |
-| `hasPendingTaskForIssueAndAgent` selects the comment-scoped exclusion only when `ExcludeTriggerCommentID` is valid | `server/internal/handler/comment.go:1232-1244` |
-| Agent-assignee on-comment dedup uses the shared helper | `server/internal/handler/issue.go:2576-2594` |
-| Assigned squad leader on-comment dedup uses the shared helper | `server/internal/handler/comment.go:1197-1229` |
-| Mentioned squad leader dedup uses the shared helper | `server/internal/handler/comment.go:1397-1435` |
-| Direct agent mention dedup uses the shared helper | `server/internal/handler/comment.go:1440-1464` |
-| Positive regression test covers all four edit-preview trigger sources | `server/internal/handler/comment_trigger_preview_test.go:179-265` |
-| Negative regression test proves another comment's pending task still dedupes the preview | `server/internal/handler/comment_trigger_preview_test.go:267-290` |
-| Edit-submit regression test proves `suppress_agent_ids` filters update-triggered tasks | `server/internal/handler/comment_trigger_preview_test.go:292-316` |
-
-## Guards and outcomes for a parsed mention
-
-A mention that parses is never silently dropped: every guard below either
-records a blocked outcome with a stable `reason_code`, or hands the trigger to
-enqueue, which resolves it to queued / coalesced / deferred. Only a mention
-that never parsed at all (a name where a UUID belongs) is a true silent no-op.
-
-| Guard | Outcome | Source |
-| --- | --- | --- |
-| mentioned agent is archived, or has no runtime bound | blocked `target_unavailable` / `runtime_offline` — evaluated in that order and AFTER the invoke gate, so a caller who may not invoke the target never learns its state | `server/internal/handler/comment.go` (search `resolveMentionedAgentCommentTriggers`, the agent-branch `ArchivedAt` / `RuntimeID` checks) |
-| mentioned squad's leader is archived, or has no runtime bound | blocked `target_unavailable` / `runtime_offline`, same ordering behind the leader invoke gate | `server/internal/handler/comment.go` (search `resolveMentionedAgentCommentTriggers`, the squad-branch `ArchivedAt` / `RuntimeID` checks) |
-| private agent the actor cannot INVOKE (`canInvokeAgent`, not `canAccessPrivateAgent` — MUL-3963 split see-vs-run) | blocked `invocation_not_allowed` | `server/internal/handler/comment.go` (search `resolveMentionedAgentCommentTriggers`, the agent-branch `canInvokeAgent` call) |
-| private squad leader the actor cannot INVOKE (`canInvokeAgent`) | blocked `invocation_not_allowed` | `server/internal/handler/comment.go` (search `resolveMentionedAgentCommentTriggers`, the squad-branch `canInvokeAgent` call) |
-| well-formed mention uuid that resolves to no agent in this workspace | blocked `invocation_not_allowed` — the SAME code as a private agent, so a blocked reason can never confirm existence | `server/internal/handler/comment.go` (search `Do not reveal whether the id exists`) |
-| mention id that is not a valid uuid at all (`mention://agent/-`) | blocked `target_unavailable` on BOTH the agent and squad branch: a non-uuid names no entity anywhere, so it hides nothing and must not be blamed on permission (MUL-5548) | `server/internal/handler/comment.go` (search `cannot name an entity in ANY workspace`) |
-| the mentioned agent already has a pending task on this issue | NOT a drop: the resolver flags `AlreadyPending` and enqueue folds the comment into that task — `coalesced` on a same-head merge, `deferred` on a different head, `blocked` if the merge fails closed | flag set in `server/internal/handler/comment.go` (search `AlreadyPending: hasPending`); resolved in `resolveCommentTriggerEnqueue` |
-| the mentioned squad's leader already has a pending task on this issue | same `AlreadyPending` fold as the agent row | `server/internal/handler/comment.go` (search `hasPendingTaskForIssueAndAgent` in the squad branch) |
-| `canAccessPrivateAgent` definition — the SEE gate, deliberately NOT used by the mention path | n/a (reference) | `server/internal/handler/agent_access.go` (search `func (h *Handler) canAccessPrivateAgent`) |
-| `canEnqueueSquadLeader` (loads leader, delegates to `canInvokeAgent`) — squad assignment/promote path, NOT the mention path | n/a (reference) | `server/internal/handler/agent_access.go` (search `func (h *Handler) canEnqueueSquadLeader`) |
-| autopilot-delegation invoke authority: an unattributed autopilot run delegating on the issue it created falls back to the autopilot creator as the effective invoking user for the gate, bound to verified speaking-task lineage (author == task agent, `task.issue_id` == this issue) so no cross-issue borrow (MUL-4857) | feeds the invoke gate | gate application via `opts.effectiveInvoker()` in `server/internal/handler/comment.go` (search `func (o commentTriggerComputeOptions) effectiveInvoker`); lineage-verifying helper in `server/internal/handler/agent_access.go` (search `func (h *Handler) autopilotDelegationAuthority`); resolved from the trusted X-Task-ID / `comment.source_task_id` via `autopilotDelegationAuthorityFromRequest` / `autopilotDelegationAuthorityFromComment` |
-| autopilot-delegation authority on the DEFERRED path: a delegation to a busy target replays at the target's completion reconcile, which restores the same authority from `comment.source_task_id` (MUL-4857) | feeds the invoke gate | `server/internal/handler/daemon.go` (search `reconcileCommentsOnCompletion`, the `autopilotDelegationAuthorityFromComment` call) |
-| authority lineage is persisted per-action: only an agent editing its OWN comment re-stamps `source_task_id` to the current editing task (like create, cross-issue included); any other editor — including a workspace owner/admin editing an agent's comment (manage rights, not invoke rights) — CLEARS it, so an admin edit makes every authority/originator read fail closed, including the deferred completion-reconcile — preview, save, and reconcile agree (MUL-4857) | fails closed | `server/internal/handler/comment.go` (search `commentSourceTaskID` and the `isAuthor` branch in `UpdateComment`) |
-| an agent's comment records the run that WROTE it on `source_task_id`, whichever issue it lands on, so the human originator chain survives an agent coordinating on another issue; the same-issue requirement lives only in the consumers that need it (`autopilotDelegationAuthority`, the reply-parent guard), never in the stamp (MUL-6490) | chain preserved, gate unchanged | `server/internal/handler/comment.go` (search `sourceTaskID captures the agent's currently-executing task`) |
-
-## @all broadcast and assignee-trigger suppression
-
-| Fact | Source |
-| --- | --- |
-| `HasMentionAll` reports whether any parsed mention is `all` | `server/internal/util/mention.go` (search `func HasMentionAll`) |
-| `@all` with no explicit `@agent`/`@squad` suppresses every implicit route (assignee / thread parent / conversation) → no run | `server/internal/handler/comment.go` (search `if util.HasMentionAll(mentions)` inside `computeCommentAgentTriggers`) |
-| `@all` does NOT suppress an EXPLICIT `@agent`/`@squad` in the same comment — the explicit branch is evaluated first (MUL-5411) | `server/internal/handler/comment.go` (the `hasAgentOrSquadMention` branch immediately above the `HasMentionAll` short-circuit) |
-| `@all` never enqueues a specific agent: it is neither `squad` nor `agent`, so it is skipped in the mention trigger computation | `server/internal/handler/comment.go` (search `if m.Type != "agent"` in `resolveMentionedAgentCommentTriggers`) |
-| Tests: `@all` alone → 0 agents; `@all` + `@agent` → the mentioned agent only; `@all` + `@squad` → the leader; `@all` + `@member` → 0 agents | `server/internal/handler/comment_trigger_preview_test.go` (search `AllPlusExplicitAgentMentionStillTriggers`) |
-| A mention id that matches `MentionRe` but is not a valid UUID (`mention://agent/-`) is parsed with the error-returning `util.ParseUUID` and reported as a blocked mention — never a panic / 500 | `server/internal/handler/comment.go` (search `util.ParseUUID(m.ID)` in `resolveMentionedAgentCommentTriggers`); test `server/internal/handler/comment_trigger_preview_test.go` (search `MalformedMentionIDDoesNotPanic`) |
-
-## CLI id sources (where the UUID comes from)
-
-| List command | Field used as mention id | Source |
-| --- | --- | --- |
-| `workspace member list` | `user_id` (NOT the membership-row id) | `server/cmd/multica/cmd_workspace.go:465` |
-| `agent list` | `id` | `server/cmd/multica/cmd_agent.go:365` |
-| `squad list` | `id` | `server/cmd/multica/cmd_squad.go:57` |
-| Member mention uses `user_id`, confirmed by the backend roster formatter: `formatMention(user.Name, "member", userID)` where `userID = UUIDToString(m.MemberID)` | `server/internal/handler/squad_briefing.go:189-190` |
-| `formatMention` emits `[@<name>](mention://<type>/<id>)` | `server/internal/handler/squad_briefing.go:216-218` |
-
-## Explicit non-claim: no member-notification path in the Go comment handler
-
-The skill deliberately does **not** assert that a `member` mention "sends a
-notification." `server/internal/handler/comment.go` has no notification
-delivery path for member (or issue) mentions: `computeMentionedAgentCommentTriggers`
-branches only on `squad` and `agent`
-(`server/internal/handler/comment.go:1397,1437-1439`), and a grep of the file for
-`notif` returns only an unrelated comment about avoiding "log spam" on
-unchanged threads — no member-notification call. The verified contract is
-narrow: a `member` or `issue` mention renders as a link and enqueues no agent
-run; only `agent` and `squad` mentions enqueue work. If a notification UX
-exists, it is not in this handler, so this skill makes no claim about it.
diff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.md
new file mode 100644
index 0000000000..557a61c977
--- /dev/null
+++ b/server/internal/service/builtin_skills/multica-platform/SKILL.md
@@ -0,0 +1,89 @@
+---
+name: multica-platform
+description: "Use for Multica platform actions the runtime brief does not fully cover: issue and PR contracts, mentions, agents, squads, autopilots, projects, runtimes, skill import. Not for the product code you are working on."
+user-invocable: false
+allowed-tools: Bash(multica *), Bash(git *), Bash(gh *)
+---
+
+# Operating Multica
+
+Your runtime brief owns the per-turn workflow: which issue you are on, when to
+comment, what status to write. This skill owns the platform contracts behind
+it — what a command actually does, what the server validates, and which writes
+have consequences you cannot take back.
+
+Read the invariants below, then open the reference(s) your task actually needs
+— usually one, sometimes a few. Do not read them all.
+
+## Routing
+
+| Open | When the task is about |
+|---|---|
+| `references/issues.md` | Issues: PR linking vs close intent, reading a linked PR's state, metadata, custom properties, status side effects, sub-issues and stages, who else is running |
+| `references/mentions.md` | Writing a `mention://` link: which types enqueue a run, which are inert, why one silently did nothing |
+| `references/agents.md` | Creating, copying or debugging an agent definition: fields, secrets, MCP config, skill binding |
+| `references/squads.md` | Squads: leader routing, roster, recording leader activity, why a squad did or did not run |
+| `references/autopilots.md` | Autopilots: schedule / webhook / manual triggers, `create_issue` vs `run_only`, why one did not fire |
+| `references/projects.md` | Projects and their durable resources (`github_repo`, `local_directory`, worktree mode) |
+| `references/runtimes.md` | Runtimes, daemons, `repo checkout`, and the task CLI boundary |
+| `references/skill-import.md` | Importing a skill into this workspace from a URL or a local archive |
+
+Open what the task needs. A single-domain task usually needs one; a task that
+crosses domains needs each domain it touches — creating a squad, assigning it an
+issue, then writing a mention needs `squads.md`, `issues.md` and `mentions.md`,
+and skipping one of those means acting on a contract you have not read.
+
+What is never right is reading all eight because you are not sure. Each
+reference states its own contracts in full and none depends on another, so
+pick by domain and skip the rest.
+
+## Invariants
+
+These hold across every reference and are not repeated there.
+
+**Read before you write.** Start with the read-only commands the reference you
+opened names — most domains have a `list` and a `get` that take `--output json`
+and have no side effects. Run those before any mutation. When a command's shape
+is unclear, `multica <command> --help` beats guessing at flags.
+
+**A name is not an id.** Mention links, assignment, and every `--*-id` flag take
+a real UUID from the matching `list --output json`. Never type a display name
+where an id belongs, and never invent a UUID: an id that is well-formed but
+belongs to nothing fails in ways that read like a permission error, which sends
+you debugging access when the real problem was the id.
+
+**`--output json` writes to stdout; warnings and confirmations go to stderr.**
+Do not merge them (`2>&1`) into anything that parses the output — that makes a
+write which SUCCEEDED look like it failed, and invites a duplicate retry.
+
+**Writes are real.** Creating, updating, deleting, assigning, commenting,
+mentioning, triggering and status changes mutate durable workspace state or
+start agent runs that cost real budget. Never run one to see what happens. When
+the user has not asked for a specific mutation, propose it instead of making it.
+
+**`--no-start` when you are only recording.** Assignment and status writes
+normally enqueue a run. When the work is already underway and the write merely
+records ownership or progress, pass `--no-start` on EVERY command in that flow —
+suppressing the assignment alone does not suppress a later status update.
+
+**Status is a category, not a literal.** A workspace may define custom statuses
+beyond the built-ins; each inherits its category's platform behavior in full,
+and the runtime brief lists this workspace's catalog. Read `status_category`
+rather than matching `status` against built-in names.
+
+**Comment reads stay bounded.** Scan the threads cheaply
+(`--roots-only --summary --compact`), then expand only what matters
+(`--thread <thread-id> --tail 30`). Never one unbounded pull — a wide read on a
+busy issue costs more than the answer is worth and still buries the reply
+bodies where triggers and instructions actually live.
+
+## When behavior looks wrong
+
+Classify before concluding: expected behavior, a configuration problem, a
+product limitation, or an actual bug. Explain what the platform currently does
+rather than defending it; when the behavior is technically correct but bad for
+the user, say so and propose a scoped change.
+
+Do not silently alter routing, briefing, or trigger behavior to make a complaint
+go away. Those are product contracts, and changing one without confirmation
+moves the surprise to somebody else.
diff --git a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md b/server/internal/service/builtin_skills/multica-platform/references/agents.md
similarity index 73%
rename from server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
rename to server/internal/service/builtin_skills/multica-platform/references/agents.md
index e73c77fdca..85231b0049 100644
--- a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/agents.md
@@ -1,17 +1,18 @@
----
-name: multica-creating-agents
-description: "Use when creating, inspecting, or debugging a Multica agent definition via the `multica agent` CLI or POST /api/agents. Not for assigning issues to agents that already exist, and not for runtime task prompts."
-user-invocable: false
-allowed-tools: Bash(multica *)
----
-
-# Creating Multica agents
-
-This is the contract for Multica's agent-creation path: what the create entry
-points accept, what the server validates and rejects, how each field is
-persisted, and which fields the daemon actually reads at claim time. It is
-not a parameter manual — it states source-traced facts, and every claim is
-backed by `file:line` in `references/creating-agents-source-map.md`.
+# Agents
+
+The contract for Multica's agent-creation path: what the create entry points
+accept, what the server validates and rejects, how each field is persisted, and
+which fields the daemon actually reads at claim time. This is not a
+parameter manual.
+
+- [Quick start (read-only inspection)](#quick-start-read-only-inspection)
+- [Core model](#core-model)
+- [CLI / API entry points](#cli--api-entry-points)
+- [Copying an agent](#copying-an-agent)
+- [Field contracts](#field-contracts)
+- [Env and secrets](#env-and-secrets)
+- [Skill binding](#skill-binding)
+- [Common wrong assumptions](#common-wrong-assumptions)
## Quick start (read-only inspection)
@@ -25,10 +26,10 @@ multica agent env get <agent-id> --output json # plaintext env (agent owner or
An agent can also be **unbound**: `runtime_id` is `NULL` (served as `""` with
`runtime_bound: false`) after its runtime was deleted, which unbinds instead of
-deleting its agents (MUL-5559). An unbound agent keeps everything it owns and
-stays editable, but no trigger path will run it — they all refuse with
-`agent_runtime_required` — until `agent update <id> --runtime-id <runtime-id>` binds
-it again. Unbound is orthogonal to archived.
+deleting its agents. An unbound agent keeps everything it owns and stays
+editable, but no trigger path will run it — they all refuse with
+`agent_runtime_required` — until `agent update <id> --runtime-id <runtime-id>`
+binds it again. Unbound is orthogonal to archived.
`agent get` returns the persisted agent including `runtime_id`, `model`,
`thinking_level`, `service_tier`, `custom_args`, `has_custom_env`,
@@ -36,10 +37,10 @@ it again. Unbound is orthogonal to archived.
## Core model
-An agent is a workspace-scoped row (table `agent`). Creation is a single
-`POST /api/agents` (`multica agent create`). At task claim time the daemon
-re-reads the agent row and assembles the runtime payload — so the persisted
-fields, not the create-time output, are what the agent runs on.
+An agent is a workspace-scoped record. Creation is a single `POST /api/agents`
+(`multica agent create`). At task claim time the daemon re-reads the agent and
+assembles the runtime payload — so the persisted fields, not the create-time
+output, are what the agent runs on.
Two distinct text fields, often confused:
@@ -62,18 +63,17 @@ multica agent create --name <name> --runtime-id <runtime-id> \
--output json
```
-`runAgentCreate` builds a JSON body and posts it to `/api/agents`. It only
-adds a key when its flag was provided — `description`/`instructions` on a
-non-empty value, the rest (`runtime-config`, `custom-args`, `model`,
-`thinking-level`, `service-tier`, `visibility`, …) on the flag being `Changed`
-— so omitted flags fall through to server defaults rather than sending empty
-strings. `--max-concurrent-tasks` is validated as 1–50 before the request is
-sent.
+The CLI builds a JSON body and posts it to `/api/agents`. It only adds a key
+when its flag was provided — `description`/`instructions` on a non-empty value,
+the rest (`runtime-config`, `custom-args`, `model`, `thinking-level`,
+`service-tier`, `visibility`, …) on the flag being explicitly set — so omitted
+flags fall through to server defaults rather than sending empty strings.
+`--max-concurrent-tasks` is validated as 1–50 before the request is sent.
-The HTTP body (`CreateAgentRequest`) accepts: `name`, `description`,
-`instructions`, `conversation_starters`, `avatar_url`, `runtime_id`, `runtime_config`, `custom_env`,
-`custom_args`, `model`, `thinking_level`, `service_tier`, `visibility`,
-`max_concurrent_tasks`, `mcp_config`, `skill_ids`.
+The HTTP body accepts: `name`, `description`, `instructions`,
+`conversation_starters`, `avatar_url`, `runtime_id`, `runtime_config`,
+`custom_env`, `custom_args`, `model`, `thinking_level`, `service_tier`,
+`visibility`, `max_concurrent_tasks`, `mcp_config`, `skill_ids`.
The body accepts more than the CLI exposes. `conversation_starters` has no
`agent create` / `agent update` flag — the CLI can only carry it across an
@@ -86,10 +86,10 @@ will find it.
`multica agent copy <source-agent-id>` forks an existing agent's portable
configuration into a brand-new agent, leaving the source untouched. It is the
CLI/headless equivalent of the web "Duplicate" action. No dedicated server API
-is involved: `runAgentCopy` reads the source with `GET /api/agents/<id>`, then
-POSTs a `CreateAgentRequest` — passing the source's skill ids in `skill_ids` so
-the bindings attach in the SAME create transaction (unlike `agent create`, which
-binds nothing). The mutation is therefore a single atomic create.
+is involved: the CLI reads the source with `GET /api/agents/<id>`, then POSTs a
+create request — passing the source's skill ids in `skill_ids` so the bindings
+attach in the SAME create transaction (unlike `agent create`, which binds
+nothing). The mutation is therefore a single atomic create.
```bash
multica agent copy <source-agent-id> --name "My Agent (copy)" # same runtime
@@ -118,31 +118,30 @@ multica agent copy <source-agent-id> --runtime-id <target> --model <model> # cr
## Field contracts
-| Field | Persisted as | Validated? | Consumed by |
+| Field | Stored as | Validated? | Consumed by |
|---|---|---|---|
-| `name` | `agent.name` | required, 400 if empty | listings, runtime payload |
-| `description` | `agent.description` | 400 if > 255 code points | catalog/listing only — NOT the runtime prompt |
-| `instructions` | `agent.instructions` | none | daemon → provider at claim time |
-| `conversation_starters` | `agent.conversation_starters` (JSON array) | at most 3 items; each requires a label (≤80 code points) and prompt (≤4000 code points) | human-facing Chat empty state only; selecting one prefills the composer and does not start a run |
-| `avatar_url` | `agent.avatar_url` | none; an explicit non-empty value is preserved, while omitted/empty creates a random `emoji:<glyph>` avatar | catalog/listing UI only — NOT the runtime prompt |
-| `runtime_id` | `agent.runtime_id` (nullable) | required at create (400) + must resolve to a runtime in this workspace | selects runtime/provider; `NULL` means unbound — see below |
-| `model` | `agent.model` (nullable) | none beyond runtime support | daemon reads; empty = runtime default |
-| `thinking_level` | `agent.thinking_level` (nullable) | provider-level enum/safe-token gate; unknown literal → 400. Pi accepts only `off|minimal|low|medium|high|xhigh|max`, then the daemon checks the selected model's RPC-discovered subset. ACP runtimes that advertise an effort selector in `session/new` (currently `reasonix` and `hermes`) take the safe-token path and are checked against the discovered catalog by the daemon; that catalog covers only the model the discovery session was on, so other models show no picker until per-model probing exists. `hermes` covers two binaries — jcode advertises and applies an effort, Hermes Agent advertises none and gets no picker — so the answer there comes from the runtime's discovered catalog, not the provider name. Because that catalog is only written once a client requests a model list, a `hermes` runtime that has never been discovered is refused with a distinct "has not reported a model catalog yet" 400 rather than being assumed capable; `reasonix`, whose provider name does determine the binary, is allowed in that state. A runtime with no reasoning control at all (e.g. `copilot`, which executes outside ACP) rejects EVERY non-empty value and says so — that 400 is a capability answer, not a bad token | daemon; empty = runtime default |
-| `service_tier` | `agent.service_tier` (nullable) | Codex-only safe token; other providers reject; daemon checks either the explicit-standard capability or the exact model/catalog-tier pair | daemon → Codex app-server; empty = local Codex config, `default` = explicit Standard, catalog tier such as `priority` = explicit Fast |
-| `custom_args` | `agent.custom_args` (JSON array) | JSON shape checked CLI-side; server stores as-is | daemon (extra CLI switches); defaults to `[]` |
-| `runtime_config` | `agent.runtime_config` (JSON) | JSON shape checked CLI-side; server stores as-is | runtime-specific config; defaults to `{}` |
-| `custom_env` | `agent.custom_env` (JSON object) | — | daemon (process env); see Env & secrets |
-| `mcp_config` | `agent.mcp_config` (raw JSON) | CLI checks it is a JSON object or `null`; server stores as-is. At create, literal `null` is dropped (no-op); at update, `null` clears the column | daemon → provider (provider-specific MCP handling); redacted on read |
-| `visibility` | `agent.visibility` | — | access control; defaults to `private`; gates who can read/route a private agent (e.g. a private squad leader) — NOT the runtime prompt |
-| `max_concurrent_tasks` | `agent.max_concurrent_tasks` | integer from 1 through 50; out-of-range values return 400 | scheduler task cap; defaults to `6` |
+| `name` | `name` | required, 400 if empty | listings, runtime payload |
+| `description` | `description` | 400 if > 255 code points | catalog/listing only — NOT the runtime prompt |
+| `instructions` | `instructions` | none | daemon → provider at claim time |
+| `conversation_starters` | `conversation_starters` (JSON array) | at most 3 items; each requires a label (≤80 code points) and prompt (≤4000 code points) | human-facing Chat empty state only; selecting one prefills the composer and does not start a run |
+| `avatar_url` | `avatar_url` | none; an explicit non-empty value is preserved, while omitted/empty creates a random `emoji:<glyph>` avatar | catalog/listing UI only — NOT the runtime prompt |
+| `runtime_id` | `runtime_id` (nullable) | required at create (400) + must resolve to a runtime in this workspace | selects runtime/provider; `NULL` means unbound — see above |
+| `model` | `model` (nullable) | none beyond runtime support | daemon reads; empty = runtime default |
+| `thinking_level` | `thinking_level` (nullable) | provider-level enum/safe-token gate; unknown literal → 400. Pi accepts only `off\|minimal\|low\|medium\|high\|xhigh\|max`, then the daemon checks the selected model's RPC-discovered subset. ACP runtimes that advertise an effort selector in `session/new` (currently `reasonix` and `hermes`) take the safe-token path and are checked against the discovered catalog by the daemon; that catalog covers only the model the discovery session was on, so other models show no picker until per-model probing exists. `hermes` covers two binaries — jcode advertises and applies an effort, Hermes Agent advertises none and gets no picker — so the answer there comes from the runtime's discovered catalog, not the provider name. Because that catalog is only written once a client requests a model list, a `hermes` runtime that has never been discovered is refused with a distinct "has not reported a model catalog yet" 400 rather than being assumed capable; `reasonix`, whose provider name does determine the binary, is allowed in that state. A runtime with no reasoning control at all (e.g. `copilot`, which executes outside ACP) rejects EVERY non-empty value and says so — that 400 is a capability answer, not a bad token | daemon; empty = runtime default |
+| `service_tier` | `service_tier` (nullable) | Codex-only safe token; other providers reject; daemon checks either the explicit-standard capability or the exact model/catalog-tier pair | daemon → Codex app-server; empty = local Codex config, `default` = explicit Standard, catalog tier such as `priority` = explicit Fast |
+| `custom_args` | `custom_args` (JSON array) | JSON shape checked CLI-side; server stores as-is | daemon (extra CLI switches); defaults to `[]` |
+| `runtime_config` | `runtime_config` (JSON) | JSON shape checked CLI-side; server stores as-is | runtime-specific config; defaults to `{}` |
+| `custom_env` | `custom_env` (JSON object) | — | daemon (process env); see Env and secrets |
+| `mcp_config` | `mcp_config` (raw JSON) | CLI checks it is a JSON object or `null`; server stores as-is. At create, literal `null` is dropped (no-op); at update, `null` clears the field | daemon → provider (provider-specific MCP handling); redacted on read |
+| `visibility` | `visibility` | — | access control; defaults to `private`; gates who can read/route a private agent (e.g. a private squad leader) — NOT the runtime prompt |
+| `max_concurrent_tasks` | `max_concurrent_tasks` | integer from 1 through 50; out-of-range values return 400 | scheduler task cap; defaults to `6` |
Defaults when omitted or explicitly `null`: `max_concurrent_tasks` → `6`.
Other defaults when omitted: `runtime_config` → `{}`, `custom_env` → `{}`,
`custom_args` → `[]`, `avatar_url` → a random `emoji:<glyph>`, `visibility` →
-`private`
-(all materialized server-side before the insert). `custom_args`/`runtime_config`
-are typed `[]string`/`any` and marshaled as-is — the JSON-shape rejection
-happens in the CLI, not the create handler.
+`private` (all materialized server-side before the insert).
+`custom_args`/`runtime_config` are stored as given — the JSON-shape rejection
+happens in the CLI, not on the server.
The 1–50 concurrency range applies consistently to create and update. On
create, an omitted field defaults to 6 while an explicitly supplied 0 is
@@ -211,7 +210,7 @@ configured still shows three built-in generic defaults in that empty state, so
`custom_args` are normally raw provider CLI args. The CLI help notes that some
providers (codex app-server, openclaw) reject `--model` inside `custom_args` —
but that is documented CLI guidance, not a server-enforced invariant; nothing
-in the create handler inspects `custom_args` for a model flag. Provider
+on the create path inspects `custom_args` for a model flag. Provider
backends may consume protocol selectors before launch:
- Pi filters `--thinking` because the first-class `thinking_level` field owns
@@ -228,7 +227,7 @@ in the provider process's argv and may be visible to other local processes
through `ps` or `/proc`. Put provider credentials in `custom_env` instead,
using its stdin or 0600 file input where possible.
-## Env & secrets
+## Env and secrets
`custom_env` is secret material. The CLI offers three input channels; two keep
secrets out of shell history and the process list:
@@ -254,7 +253,7 @@ Read-side facts (these are the wrong assumptions to avoid):
regardless of the backing member's role — a running agent cannot read another
agent's secrets, not even one its own human owns.
- Writing values after creation does NOT go through `agent update`. The generic
- update handler rejects any `custom_env` field with a 400 ("use PUT
+ update path rejects any `custom_env` field with a 400 ("use PUT
/api/agents/{id}/env"). Plaintext env writes are handled by
`PUT /api/agents/{id}/env` (`multica agent env set`), which carries the same
gate and writes an audit row.
@@ -337,11 +336,10 @@ multica agent skills list <agent-id> --output json
```
At claim time the daemon assembles the agent's skills as workspace-bound skills
-FIRST, then appends the platform built-in skills. `LoadAgentSkills` loads each
-bound skill's content plus its supporting files; built-in skills are embedded
-at compile time and loaded from `SKILL.md` + sibling files. Both reach the
-provider as skill content — which is why capability belongs in a bound skill,
-not pasted into `instructions`.
+FIRST, then appends the platform built-in skills. Each bound skill contributes
+its content plus its supporting files; built-in skills ship with the server and
+are loaded the same way. Both reach the provider as skill content — which is why
+capability belongs in a bound skill, not pasted into `instructions`.
## Side effects needing approval
@@ -349,9 +347,9 @@ Read-only (safe): `agent get`, `agent skills list`, `agent env get`.
State-changing (require an explicit instruction — do not run speculatively):
-- `multica agent create` — inserts a new agent row.
-- `multica agent copy` — inserts a new agent row (a fork of an existing agent);
- the source is left untouched.
+- `multica agent create` — creates a new agent.
+- `multica agent copy` — creates a new agent (a fork of an existing one); the
+ source is left untouched.
- `multica agent skills add` / `set` — mutate bindings (`set` is destructive:
it drops bindings not in the new list).
- `multica agent env set` — overwrites the full `custom_env` map and writes an
@@ -377,9 +375,3 @@ State-changing (require an explicit instruction — do not run speculatively):
unknown provider-level literal is — model-specific gaps fail at run time.
- "`set` and `add` are interchangeable for skills." `set` replaces all
bindings; using it when you meant `add` silently removes capabilities.
-
-## References
-
-`references/creating-agents-source-map.md` maps every contract above to its
-`file:line` on the current tree, the runtime effect, and a safe read-only
-verification command.
diff --git a/server/internal/service/builtin_skills/multica-autopilots/SKILL.md b/server/internal/service/builtin_skills/multica-platform/references/autopilots.md
similarity index 50%
rename from server/internal/service/builtin_skills/multica-autopilots/SKILL.md
rename to server/internal/service/builtin_skills/multica-platform/references/autopilots.md
index 526542175e..480dd40ac2 100644
--- a/server/internal/service/builtin_skills/multica-autopilots/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/autopilots.md
@@ -1,29 +1,18 @@
----
-name: multica-autopilots
-description: "Use when creating, updating, inspecting, triggering, or debugging a Multica autopilot (scheduled, webhook, or manual)."
-user-invocable: false
-allowed-tools: Bash(multica *)
----
+# Autopilots
-# Multica Autopilots
-
-## Quick start
-
-Autopilots are durable automations. Read before mutating:
-
-```bash
-multica autopilot list --output json
-multica autopilot get <autopilot-id> --output json
-multica autopilot runs <autopilot-id> --output json
-```
-
-Do not run `trigger`, `delete`, `trigger-delete`, or `trigger-rotate-url` to test. Those are real side effects.
+An autopilot is not an agent. It is a rule that dispatches work to an agent, or
+to a squad's leader agent.
## Core model
-An autopilot is not an agent. It is a rule that dispatches work to an agent, or to a squad's leader agent.
+The chain is: trigger fires (`schedule`, `webhook`, or `manual`) → an autopilot
+run is recorded → `execution_mode` decides the output → assignee readiness check
+→ issue/task execution → run status sync.
-The chain is: trigger fires (`schedule`, `webhook`, or `manual`) -> `autopilot_run` row -> `execution_mode` decides output -> assignee readiness check -> issue/task execution -> run status sync. Webhooks have a durable admission step in front: HTTP ingress stores a queued `webhook_delivery`, synchronously creates or reuses its idempotent run, and returns `200` with `status=accepted|skipped` plus `run_id`; a database-leased worker then resumes accepted runs and owns recoverable issue/task dispatch.
+Webhooks have a durable admission step in front: HTTP ingress stores a queued
+webhook delivery, synchronously creates or reuses its idempotent run, and
+returns `200` with `status=accepted|skipped` plus `run_id`; a leased worker then
+resumes accepted runs and owns recoverable issue/task dispatch.
Execution modes:
@@ -31,7 +20,8 @@ Execution modes:
- `run_only` creates an agent task directly. No issue is created; any durable
report location has to come from other task context or instructions.
-`issue-title-template` only supports `{{date}}`. Do not invent `{{trigger_id}}`, `{{branch}}`, or other variables.
+`issue-title-template` only supports `{{date}}`. Do not invent `{{trigger_id}}`,
+`{{branch}}`, or other variables.
## CLI
@@ -47,13 +37,22 @@ multica autopilot trigger <autopilot-id> --output json
multica autopilot trigger-rotate-url <autopilot-id> <trigger-id> --yes --output json
```
-Use `trigger` only when the user explicitly asks for a manual run. Use `trigger-rotate-url` only when rotating a webhook URL; the old URL stops being valid.
+Do not run `trigger`, `delete`, `trigger-delete`, or `trigger-rotate-url` to
+test — those are real side effects. Use `trigger` only when the user explicitly
+asks for a manual run, and `trigger-rotate-url` only when rotating a webhook
+URL; the old URL stops being valid immediately.
-`autopilot get` redacts `webhook_token`, `webhook_path`, and `webhook_url` by default while reporting whether a token exists and its non-sensitive hint. Only add `--show-secrets` when the user explicitly asks to retrieve the live webhook credential; the command warns on stderr. Do not paste webhook tokens or signing material into comments, logs, docs, or PRs.
+A schedule trigger without `--timezone` runs in **UTC**. Name the zone whenever
+a human confirmed a wall-clock time, or they will confirm a morning job and
+receive an afternoon one.
-## Debugging
+`autopilot get` redacts `webhook_token`, `webhook_path`, and `webhook_url` by
+default while reporting whether a token exists and its non-sensitive hint. Only
+add `--show-secrets` when the user explicitly asks to retrieve the live webhook
+credential; the command warns on stderr. Do not paste webhook tokens or signing
+material into comments, logs, docs, or PRs.
-For "why didn't it run":
+## Debugging "why didn't it run"
1. `multica autopilot get <id> --output json` — status, mode, assignee, triggers.
2. `multica autopilot runs <id> --output json` — run status and failure reason.
@@ -62,8 +61,22 @@ For "why didn't it run":
5. For webhooks, inspect delivery status: `queued` means the worker has not completed dispatch; `failed` carries the worker error. A provider retry with the same `X-GitHub-Delivery` / `Idempotency-Key` reuses the original delivery.
6. For `create_issue`, inspect the created issue if the run records one.
-## Side effects
+## Access
-These mutate durable state or start work: `create`, `update`, `delete`, trigger add/update/delete/rotate, `trigger`, and webhook calls to `/api/webhooks/autopilots/{token}`.
+Reads (list / get / runs / deliveries) are open to any workspace member, but
+`get` redacts the webhook token for callers without write access — the token
+alone can trigger the autopilot.
+
+Editing, deleting, triggering, replaying deliveries, and managing
+triggers/webhook secrets require the autopilot's creator, a workspace
+owner/admin, or an explicit collaborator. Granting or revoking a collaborator is
+narrower still: creator or workspace owner/admin only, so a granted collaborator
+keeps write/execute but cannot re-grant or revoke peers. `get` stamps two
+per-caller booleans — `can_write` and the narrower `can_manage_access` — read
+those rather than inferring from role.
+
+## Side effects
-More source-backed details: `references/autopilots-source-map.md`.
+These mutate durable state or start work: `create`, `update`, `delete`, trigger
+add/update/delete/rotate, `trigger`, and webhook calls to
+`/api/webhooks/autopilots/{token}`.
diff --git a/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md b/server/internal/service/builtin_skills/multica-platform/references/issues.md
similarity index 82%
rename from server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md
rename to server/internal/service/builtin_skills/multica-platform/references/issues.md
index 3a31619f12..4092d0cf63 100644
--- a/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md
@@ -1,20 +1,16 @@
----
-name: multica-working-on-issues
-description: "Use when acting on a Multica issue beyond what the brief covers: PR linking vs close intent, reading a linked PR's real state, metadata keys, status-change side effects, sub-issue todo vs backlog."
-user-invocable: false
-allowed-tools: Bash(multica *), Bash(git *), Bash(gh *)
----
+# Issues
-# Working on Multica issues
+Product contracts the runtime brief does not fully encode.
-Product contracts the runtime brief does not fully encode: PR linking vs close
-intent, reading linked-PR state, metadata keys, status side effects, and
-sub-issue enqueue behavior.
-
-For building mention links, load `multica-mentioning` instead — not this skill.
-
-Every contract below is traced to source in
-`references/working-on-issues-source-map.md`.
+- [PR linking and close intent are two distinct contracts](#pr-linking-and-close-intent-are-two-distinct-contracts)
+- [Reading a linked PR's real state](#reading-a-linked-prs-real-state)
+- [Metadata: durable custom state](#metadata-durable-custom-state)
+- [Custom properties: typed workflow state](#custom-properties-typed-workflow-state)
+- [Status changes have server side effects](#status-changes-have-server-side-effects)
+- [Claim ownership without duplicating a run](#claim-ownership-without-duplicating-a-run)
+- [Who else is running right now](#who-else-is-running-right-now)
+- [Sub-issues: todo starts work now, backlog parks it](#sub-issues-todo-starts-work-now-backlog-parks-it)
+- [Incorrect to correct](#incorrect-to-correct)
## PR linking and close intent are two distinct contracts
@@ -22,14 +18,14 @@ The GitHub webhook runs two separate scans over an incoming PR. They are not the
same gate and they read different fields.
**Linking** scans the PR **title, body, OR branch** for a routable issue key
-(`PREFIX-NUMBER`, e.g. `MUL-2759`). Each match writes an issue ↔ PR link row.
+(`PREFIX-NUMBER`, e.g. `MUL-123`). Each match writes an issue to PR link row.
This is the link that `multica issue pull-requests` reads back — but see the
reference-only rule below: a key that appears **only** as a bare mention in the
body is linked yet hidden from that list.
```text
-MUL-2759: add built-in issue working skill # title prefix → links, shown
-agent/matt/mul-2759-working-on-issues # branch ref → links, shown
+MUL-123: add the thing the issue asks for # title prefix → links, shown
+agent/dana/mul-123-add-the-thing # branch ref → links, shown
```
**Close intent** is stricter and is a separate scan over **title or body only —
@@ -39,10 +35,10 @@ adjacency is what sets the link row's close-intent flag, the gate that
auto-advances the issue to `done` when the PR merges.
```text
-Closes MUL-2759 # links AND records close intent
-Fixes MUL-2759
-Resolves MUL-2759
-Fix login MUL-2759 # links only — keyword not adjacent
+Closes MUL-123 # links AND records close intent
+Fixes MUL-123
+Resolves MUL-123
+Fix login MUL-123 # links only — keyword not adjacent
```
Consequence: a bare title prefix or a branch reference links the PR but does not
@@ -54,14 +50,14 @@ records close intent; on merge, that close intent can move the linked issue to
as a bare mention in the body — no closing keyword, and not in the title or
branch — still writes a link row, but the row is flagged `reference_only` and
**excluded from `multica issue pull-requests`** (and the issue's right-side PR
-list in the UI). This keeps passing mentions like `Related MUL-2759` or
-`Follow up in MUL-2759` from surfacing an unrelated PR as if it were working on
+list in the UI). This keeps passing mentions like `Related MUL-123` or
+`Follow up in MUL-123` from surfacing an unrelated PR as if it were working on
that issue. To make a PR show up for an issue, put the key in the title, the
branch, or after a closing keyword in the body — not as a loose body reference.
```text
-Closes MUL-2759 in the body # links and shown
-Related to MUL-2759 in the body (no title/branch) # links but reference_only → hidden
+Closes MUL-123 in the body # links and shown
+Related to MUL-123 in the body (no title/branch) # links but reference_only → hidden
```
### Default for code-changing issue work
@@ -78,8 +74,8 @@ the PR back to the issue. If the PR should close the issue on merge, put the key
immediately after a closing keyword in the title or body, for example:
```text
-MUL-2759: fix login redirect # links only
-Closes MUL-2759 # links and records close intent
+MUL-123: fix login redirect # links only
+Closes MUL-123 # links and records close intent
```
In the final issue comment, include the PR URL when a PR exists. If the task did
@@ -205,21 +201,18 @@ multica issue list --sort property:Impact --direction desc --output json
## Status changes have server side effects
A status change is not cosmetic — the server enqueues or skips agent work based
-on it. These are the contracts, not advice:
+on it. These are the contracts, not advice.
-A workspace may define custom statuses beyond the seven built-ins; when any
-exist, the runtime brief's Available Commands section lists this workspace's
-catalog. A custom status inherits its category's behavior in full, and each
-built-in key below is also the name of its category — so read these bullets as
-category rules. Two writes are literal-key exceptions, not category rules: the
-failed-task rollback below writes the literal `todo` key, and a merged PR with
-close intent writes the literal `done` key.
+Read them as category rules: a custom status inherits its category's behavior in
+full. Two writes are literal-key exceptions, not category rules — the failed-task
+rollback below writes the literal `todo` key, and a merged PR with close intent
+writes the literal `done` key.
- **`backlog`** parks an agent-assigned issue: the assignee is set but no task
fires. Moving `backlog → todo` (or any non-done/non-cancelled status) enqueues
the assigned agent then.
-- **`in_progress` / `in_review`** are agent-managed CLI mutations, not
- `StartTask` / `CompleteTask` side effects. The runtime brief asks agents to
+- **`in_progress` / `in_review`** are agent-managed CLI mutations, not automatic
+ side effects of a task starting or finishing. The runtime brief asks agents to
write the state the issue is in whenever their work changes it — not from
the trigger type or the run's lifecycle, and not gated on being the
assignee. Writes happen whenever the state changes, mid-turn included: a
@@ -244,8 +237,8 @@ close intent writes the literal `done` key.
itself on merge — you do not also need to flip it manually.
- **`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 in
- flight — a run in progress keeps going (MUL-4465). To stop a running task,
- cancel the task itself.
+ flight — a run in progress keeps going. To stop a running task, cancel the
+ task itself.
- **Failed issue-triggered tasks** may roll an issue from `in_progress` back to
`todo` when no active task / retry remains — that is the main server-owned
status write on the agent-run path.
@@ -254,8 +247,7 @@ close intent writes the literal `done` key.
Assigning an active issue to an agent normally starts a run. When the work is
already underway and the write only records ownership or progress, pass
-`--no-start` on every command in that flow — suppressing the assignment alone
-does not suppress a later status update:
+`--no-start` on every command in that flow:
```bash
multica issue assign <issue-id> --to-id <agent-id> --no-start
@@ -264,10 +256,10 @@ multica issue status <issue-id> in_progress --no-start
```
Before self-assigning, check the target issue's comment history for an existing
-claim. The server also suppresses a trusted self-assignment when the
-exact target `(issue, agent)` pair already has a non-terminal task, but it
-deliberately keeps same-agent handoffs to a fresh issue starting runs: cross-issue
-serial chains and triage batches rely on that.
+claim. The server also suppresses a trusted self-assignment when the exact
+target `(issue, agent)` pair already has a non-terminal task, but it
+deliberately keeps same-agent handoffs to a fresh issue starting runs:
+cross-issue serial chains and triage batches rely on that.
## Who else is running right now
@@ -301,7 +293,7 @@ a run you see may finish a second later, and one you don't see may start a
second later. Coordinate through the issue's comments — the reads tell you whom
to coordinate with.
-## Sub-issues: `todo` starts work now, `backlog` parks it
+## Sub-issues: todo starts work now, backlog parks it
On an agent-assigned issue, create status decides whether the assignee fires
immediately. A non-backlog status (e.g. `todo`) enqueues the agent at create
@@ -324,7 +316,7 @@ 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
+`--stage <N>` (N >= 1) groups sub-issues under the same parent into ordered
stages. The parent assignee is woken **once, when a whole stage finishes** —
i.e. every sub-issue in the lowest unfinished stage has reached a terminal
status (`done`/`cancelled`). A completion that does not close a stage is silent
@@ -352,23 +344,22 @@ multica issue children <parent-id> # sub-issues grouped by stage
multica issue status <stage-2-child-id> todo # promote when its deps are met
```
-`issue children --output json` reports per-stage `done` counts. A workspace may
-define custom statuses beyond the 7 built-ins; a custom status counts as done
-here when its category is `done` or `cancelled`, which is what `status_category`
-on each child carries. Read `status_category` rather than matching `status`
-against the built-in names.
+`issue children --output json` reports per-stage `done` counts. A custom status
+counts as done here when its category is `done` or `cancelled`, which is what
+`status_category` on each child carries. Read `status_category` rather than
+matching `status` against the built-in names.
Read each sub-issue's description before promoting and only promote items whose
stated dependencies are met; if a description conflicts with the parent's
breakdown, leave it `backlog` and comment to confirm first.
-## Incorrect → correct
+## Incorrect to correct
PR title (link the issue):
```text
Fix login redirect # incorrect — no issue key, won't link
-MUL-2759: fix login redirect # correct — links the PR
+MUL-123: fix login redirect # correct — links the PR
```
Serial / phased sub-issues (don't start the whole chain at once):
@@ -384,13 +375,3 @@ multica issue create --title "Step 1" --parent <issue-id> --assignee <agent> --s
multica issue create --title "Step 2" --parent <issue-id> --assignee <agent> --stage 2 --status backlog
multica issue create --title "Step 3" --parent <issue-id> --assignee <agent> --stage 3 --status backlog
```
-
-## References
-
-`references/working-on-issues-source-map.md` — accurate `file:line` for every
-contract above: the `pull-requests` CLI and route, the PR response field list,
-`derivePRState`, the two-path link (`extractIdentifiers`) vs close-intent
-(`extractClosingIdentifiers`) proof, the backlog enqueue lines, child-done
-notify, the stage column / `stageBarrierClosed` barrier and the `--stage` /
-`issue children` CLI, and the metadata CLI. Re-derive before depending on an
-exact line.
diff --git a/server/internal/service/builtin_skills/multica-mentioning/SKILL.md b/server/internal/service/builtin_skills/multica-platform/references/mentions.md
similarity index 62%
rename from server/internal/service/builtin_skills/multica-mentioning/SKILL.md
rename to server/internal/service/builtin_skills/multica-platform/references/mentions.md
index ec370dbea2..ca15af2362 100644
--- a/server/internal/service/builtin_skills/multica-mentioning/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/mentions.md
@@ -1,20 +1,17 @@
----
-name: multica-mentioning
-description: "Use when an issue comment needs to @mention someone — link to a person, trigger another agent, hand work to a squad, or broadcast with @all. Whether to mention at all is covered by the runtime brief, not here."
-user-invocable: false
-allowed-tools: Bash(multica *)
----
+# Mentions and delegation
-# Mentioning & Delegating
+What a mention link DOES. WHETHER to mention at all — loop avoidance, staying
+silent on acknowledgements — is in your runtime brief's Mentions section; follow
+that and do not re-derive it here.
-This skill states WHAT a mention link does in the Multica backend, traced to
-source. WHETHER to mention at all — loop avoidance, staying silent on
-acknowledgements — is in your runtime brief's Mentions section; follow that and
-do not repeat it here.
-
-Every claim below is pinned to source in
-`references/mentioning-source-map.md`. If behavior ever differs from this
-document, the source map is where to re-check it.
+- [A mention link is built from a real UUID](#a-mention-link-is-built-from-a-real-uuid)
+- [Step 1 — look up the UUID](#step-1--look-up-the-uuid)
+- [Step 2 — the four types and what each enqueues](#step-2--the-four-types-and-what-each-enqueues)
+- [Preview and per-comment suppression](#preview-and-per-comment-suppression)
+- [@all is the broadcast type](#all-is-the-broadcast-type)
+- [What does NOT happen](#what-does-not-happen)
+- [Who the invoke gate judges](#who-the-invoke-gate-judges)
+- [Incorrect to correct](#incorrect-to-correct)
## A mention link is built from a real UUID
@@ -22,9 +19,9 @@ The backend recognizes a mention only through this Markdown shape:
[@Label](mention://<type>/<id>)
-The parser (`util.MentionRe` in `server/internal/util/mention.go`) accepts
-exactly four `<type>` values plus the `all` sentinel, and the `<id>` group
-accepts only hex characters and dashes, OR the literal string `all`:
+The parser accepts exactly four `<type>` values plus the `all` sentinel, and the
+`<id>` group accepts only hex characters and dashes, OR the literal string
+`all`:
(member|agent|squad|issue|all)/([0-9a-fA-F-]+|all)
@@ -38,10 +35,10 @@ above, so the backend never parses it and it can enqueue nothing — it is a
render-only link every client makes navigable (a chip on web and desktop, an
ordinary link that opens the project on tap on mobile). That is the whole point:
a project reference should never be able to start a run. Use it freely to point
-at a project (see the multica-projects-and-resources skill); everything else in
-this document is about the four types (plus `all`) the parser does recognize.
+at a project; everything else in this document is about the four types (plus
+`all`) the parser does recognize.
-## Step 1 — look up the UUID with `--output json`
+## Step 1 — look up the UUID
A name is not a UUID. Look the UUID up first, from the matching list command:
@@ -54,38 +51,33 @@ backend's own roster formatter uses `user_id` for member mentions. Match by
display name. If the name is ambiguous or absent, do not guess — say so in your
comment instead of emitting a broken link.
-## Step 2 — the four types and exactly what each enqueues
+## Step 2 — the four types and what each enqueues
Format: `[@Name](mention://<type>/<uuid>)`. The `<type>` and the id source must
match, or the link resolves to the wrong entity (or to nothing).
| To… | type | uuid from | What the backend does |
| -------------------- | -------- | --------------- | -------------------------------------------------------- |
-| trigger an agent | `agent` | agent.id | enqueues a run for that agent (`EnqueueTaskForMention`) |
+| trigger an agent | `agent` | agent.id | enqueues a run for that agent |
| hand work to a squad | `squad` | squad.id | resolves the squad's `leader_id` and enqueues a run for the LEADER agent |
| link a person | `member` | member.user_id | renders a link; enqueues NOTHING — no agent run |
| reference an issue | `issue` | issue.id | renders a link; enqueues NOTHING — always safe |
-The mention trigger set is computed by `computeMentionedAgentCommentTriggers`
-(`server/internal/handler/comment.go`); the comment path folds that result into
-`computeCommentAgentTriggers` and enqueues it via `enqueueCommentAgentTriggers`.
-It acts on two types only: the `squad` branch resolves the squad and adds its
-leader to the trigger set; everything that is not `agent` after that is skipped
-(`if m.Type != "agent" { continue }`), then the `agent` branch adds that agent.
-A `member` or `issue` mention reaches neither branch, so it enqueues no task.
+The backend computes the trigger set from two types only: the `squad` branch
+resolves the squad and adds its leader to the set; everything that is not
+`agent` after that is skipped, then the `agent` branch adds that agent. A
+`member` or `issue` mention reaches neither branch, so it enqueues no task.
-A `member` mention therefore does NOT make a person "run", and this skill does
-NOT claim it delivers a notification through the Go comment handler — there is
-no such code path in that handler (see the source map). What is verified is the
-contract above: only `agent` and `squad` mentions enqueue work.
+A `member` mention therefore does NOT make a person "run", and no notification
+is delivered through the comment path. What IS guaranteed is the contract above:
+only `agent` and `squad` mentions enqueue work.
## Preview and per-comment suppression
Newer clients can call `POST /api/issues/{id}/comments/trigger-preview` before
-creating or editing a comment. The preview endpoint uses the same
-`computeCommentAgentTriggers` function as create and edit re-triggering, so the
-displayed agent chips come from backend rules, not from a client-side
-reimplementation.
+creating or editing a comment. The preview endpoint runs the same trigger
+computation as create and edit re-triggering, so the displayed agent chips come
+from backend rules, not from a client-side reimplementation.
When previewing an edit, clients may send `editing_comment_id`. The server
validates that the comment belongs to the same workspace and issue, derives or
@@ -113,14 +105,13 @@ conversation owner). Use `@all` to announce, not to request work from the
assignee.
`@all` only suppresses those IMPLICIT routes. An EXPLICIT `@agent` / `@squad`
-mention in the same comment still fires normally (MUL-5411): a comment reading
+mention in the same comment still fires normally: a comment reading
`[@all](mention://all/all) heads up — [@Preflight](mention://agent/<uuid>)
-please take this` enqueues Preflight and nobody else. Explicit mentions win over
-the broadcast; see `computeCommentAgentTriggers` in
-`server/internal/handler/comment.go`, where the explicit-mention branch is
-evaluated BEFORE the `@all` short-circuit.
+please take this` enqueues Preflight and nobody else. The explicit-mention
+branch is evaluated BEFORE the `@all` short-circuit, so explicit mentions win
+over the broadcast.
-## What does NOT happen (so the result doesn't surprise you)
+## What does NOT happen
None of these start a fresh run, and none produce an error response — but they
are three different things, and the response tells you which. A mention that
@@ -140,34 +131,34 @@ read. Read that array after posting — it is the only place any of this shows u
look identical on purpose**, because the id you typed could name a private
agent in another workspace and the reason must not confirm that it exists.
**So when you see `invocation_not_allowed`, check the UUID against the live
- roster BEFORE you touch any visibility or invocation setting** (MUL-5548);
+ roster BEFORE you touch any visibility or invocation setting**;
`multica squad member list <squad-id> --output json` returns the `member_id`
to build the mention from. An id that matches the pattern but is NOT a valid
UUID at all (`mention://agent/-`) is rejected by the id parser and blocked
with `target_unavailable` instead — a non-UUID names no entity anywhere, so
it conceals nothing. Neither case is ever an error response.
- **An already-pending task.** Even a correct `@agent`/`@squad` starts no second
- run when the target already has a pending task on this issue
- (`HasPendingTaskForIssueAndAgent`). This is a fold, not a drop: the comment
- merges into that task and the outcome is `coalesced` (same reviewed head) or
- `deferred` (different head) — do NOT re-post it as "the mention didn't work".
- Edit preview is the only exception: `editing_comment_id` ignores pending tasks
- from the same comment being edited, because save cancels those old tasks
- before it re-computes triggers. It is still comment-scoped, not an agent-wide
- bypass.
+ run when the target already has a pending task on this issue. This is a fold,
+ not a drop: the comment merges into that task and the outcome is `coalesced`
+ (same reviewed head) or `deferred` (different head) — do NOT re-post it as
+ "the mention didn't work". Edit preview is the only exception:
+ `editing_comment_id` ignores pending tasks from the same comment being edited,
+ because save cancels those old tasks before it re-computes triggers. It is
+ still comment-scoped, not an agent-wide bypass.
- **An archived agent, or one with no runtime bound** (likewise a squad whose
leader is): blocked with `target_unavailable` and `runtime_offline`
respectively. Both are checked only AFTER the invoke gate, so a caller who may
not invoke the target never learns its state.
-- **A private agent you cannot invoke:** blocked — the mention path gates on
- `canInvokeAgent` for both `@agent` and `@squad`. That is the *run* gate, not
- the *see* gate: since MUL-3963 a workspace admin who can open a private agent
- in the UI still may not trigger it, so being able to view the target says
- nothing about being able to mention it. (The `canEnqueueSquadLeader` wrapper
- is the squad assignment/promote path, not this one; the child-done wake is
- ungated — see the multica-squads skill.)
-
-A chain that crosses issues keeps its human (MUL-6490). The A2A gate judges the
+- **A private agent you cannot invoke:** blocked — the mention path applies the
+ invoke gate to both `@agent` and `@squad`. That is the *run* gate, not the
+ *see* gate: a workspace admin who can open a private agent in the UI still may
+ not trigger it, so being able to view the target says nothing about being able
+ to mention it. (The squad assignment/promote path has its own gate; the
+ child-done wake is ungated.)
+
+## Who the invoke gate judges
+
+A chain that crosses issues keeps its human. The agent-to-agent gate judges the
human at the top of your chain, and that human travels on the comment you write:
the comment records the run that authored it, so the run it wakes inherits your
originator. This holds when you comment on a DIFFERENT issue than the one you are
@@ -178,14 +169,15 @@ created. It does not go the other way: nothing ever substitutes a different huma
human at its top, member-scoped allow-lists stay closed no matter which issue you
move to.
-One nuance for automation (MUL-4857): when an UNATTRIBUTED autopilot run (a
-schedule/webhook dispatch has no human originator, so the A2A gate has no human
-to key on) delegates by `@mention` while working on the issue that autopilot
-created, the invoke gate falls back to the **autopilot creator** as the effective
-invoking user — the same principal that admitted the first dispatch. So a mid-run
-`@agent` / `@squad` delegation fires exactly when the autopilot creator could
-invoke that target (owner / `public_to` match), and stays skipped otherwise. It
-is authorization only — the enqueued run's originator/attribution is unchanged.
+One nuance for automation: when an UNATTRIBUTED autopilot run (a schedule/webhook
+dispatch has no human originator, so the gate has no human to key on) delegates
+by `@mention` while working on the issue that autopilot created, the invoke gate
+falls back to the **autopilot creator** as the effective invoking user — the same
+principal that admitted the first dispatch. So a mid-run `@agent` / `@squad`
+delegation fires exactly when the autopilot creator could invoke that target
+(owner / `public_to` match), and stays skipped otherwise. It is authorization
+only — the enqueued run's originator/attribution is unchanged.
+
This fallback is bound to verified task lineage: it applies only when the
delegating run's own task is the one working on that autopilot issue (author ==
task agent, `task.issue_id` == this issue), so a run doing work elsewhere can
@@ -194,6 +186,7 @@ The same authority carries the plain assigned-squad-leader wake (a worker's
result comment on the autopilot issue can still wake the leader), and it survives
a busy target: if the mentioned agent is already running, the delegation is
replayed at that run's completion under the same authority, so it is never lost.
+
An edit is treated as a fresh action — it re-derives the comment's lineage from
the editing action. Only the agent author editing its OWN comment re-stamps the
lineage to the editing task; any other editor — including a workspace owner/admin
@@ -202,7 +195,7 @@ an unrelated issue, or an admin editing an agent's comment (manage rights, not
invoke rights), fails closed at the deferred completion-reconcile instead of
reusing the original run's authority.
-## Incorrect → Correct
+## Incorrect to correct
Incorrect: `@alice please review`
→ plain text, no link, parses to nothing, nobody is reached.
@@ -219,15 +212,5 @@ Correct:
@all broadcast: `[@all](mention://all/all) heads up` — addresses everyone,
runs no specific agent, and suppresses the assignee auto-trigger.
-These exact shapes are pinned by a Go behavior test
-(`TestMentioningSkillTeachesTheParserContract`) that feeds them through
-`util.ParseMentions`: the name form parses to nothing, the real-UUID form
-parses, `@all` parses to `{all, all}`, and a wrong `type` with a real UUID
-still parses (which is why the type must match the id source).
-
-## References
-
-`references/mentioning-source-map.md` — file:line evidence for the regex, the
-enqueue branches, the @all suppression, and the CLI id-source mapping, plus the
-explicit note that no member-notification delivery path exists in the Go
-comment handler.
+Using the wrong `type` for a real UUID still parses — it just resolves to the
+wrong entity, or to nothing. That is why the type must match the id source.
diff --git a/server/internal/service/builtin_skills/multica-platform/references/projects.md b/server/internal/service/builtin_skills/multica-platform/references/projects.md
new file mode 100644
index 0000000000..5768249edd
--- /dev/null
+++ b/server/internal/service/builtin_skills/multica-platform/references/projects.md
@@ -0,0 +1,155 @@
+# Projects and resources
+
+A project groups work and carries durable resources. A resource is not just
+display metadata; it is context later injected into task briefs and
+`.multica/project/resources.json`.
+
+- [Core model](#core-model)
+- [CLI](#cli)
+- [local_directory execution modes](#local_directory-execution-modes)
+- [Referring to a project in a comment](#referring-to-a-project-in-a-comment)
+- [When to add a resource](#when-to-add-a-resource)
+- [Debugging wrong context](#debugging-wrong-context)
+- [Side effects](#side-effects)
+
+## Core model
+
+Projects are durable context containers. Resources attached to a project can
+affect future agent tasks.
+
+```bash
+multica project list --output json
+multica project get <project-id> --output json
+multica project resource list <project-id> --output json
+```
+
+Project resources are mutated through project resource commands/endpoints. Issue
+comments do not create durable project resources.
+
+A project's `description` is also durable context: when an issue (or a
+quick-create task) is bound to a project, the project description is injected
+into the agent's brief under `## Project Context` and written to
+`.multica/project/resources.json` as `project_description`. Use it for
+project-wide rules/context that should apply to every task in the project.
+
+Common resource types:
+
+- `github_repo` — durable GitHub repo context, with `resource_ref.url`, optional
+ checkout `ref`, and optional prompt-only `default_branch_hint`;
+- `local_directory` — daemon-local path context, with `resource_ref.local_path`,
+ `daemon_id`, optional label, and optional `execution_mode` (`in_place`, the
+ default, or `worktree`).
+
+## CLI
+
+```bash
+multica project list --output json
+multica project get <project-id> --output json
+multica project create --title "<title>" --repo <github-url> --output json
+multica project create --title "<title>" --start-date 2026-03-01 --due-date 2026-03-31 --output json
+multica project update <project-id> --title "<title>" --output json
+multica project update <project-id> --due-date 2026-04-15 --output json
+multica project update <project-id> --start-date "" --output json # clear the start date
+multica project status <project-id> in_progress --output json
+multica project resource list <project-id> --output json
+multica project resource add <project-id> --type github_repo --url <github-url> --output json
+multica project resource add <project-id> --type github_repo --url <github-url> --ref <branch-or-sha> --output json
+multica project resource add <project-id> --type local_directory --local-path <abs-path> --daemon-id <daemon-id> --output json
+multica project resource add <project-id> --type local_directory --local-path <abs-path> --daemon-id <daemon-id> --execution-mode worktree --output json
+multica project resource update <project-id> <resource-id> --execution-mode in_place --output json
+multica project resource update <project-id> <resource-id> --url <new-github-url> --output json
+multica project resource update <project-id> <resource-id> --ref <branch-or-sha> --output json
+multica project resource remove <project-id> <resource-id> --output json
+```
+
+For `github_repo`, non-JSON `--ref` sets `resource_ref.ref`, the default
+checkout branch/tag/SHA for future tasks in that project. JSON `--ref '<json>'`
+remains the escape hatch for full payloads or resource types not covered by
+shortcuts. `project resource update` merges shortcut edits with the existing
+`resource_ref`, so a partial edit does not clobber required fields.
+
+`--start-date` / `--due-date` are optional calendar days (`YYYY-MM-DD`, like
+issue dates). On `project update`, pass an empty string (`--start-date ""`) to
+clear a date; an unset flag leaves it untouched.
+
+## local_directory execution modes
+
+`--execution-mode` decides how tasks share a `local_directory`.
+
+`in_place` (default) runs the agent in the user's directory, one task at a time;
+a second task waits in `waiting_local_directory`.
+
+`worktree` gives each task its own git worktree of that repo, so tasks run
+concurrently and each delivers its work as a branch in the user's repo instead
+of editing the working copy. Every task of one conversation shares that branch —
+`agent/<agent>/<issue>` for an issue, `agent/<agent>/chat-<session>` for a chat
+— and each turn's worktree starts from the previous turn's work rather than from
+`HEAD`; a task with no conversation behind it gets `agent/<agent>/<task>`.
+
+Continuation is decided by an ownership record
+(`refs/multica/local-state/<branch>`, which holds the owning conversation, the
+snapshot of the user's directory the branch already carries, and the branch tip
+it was recorded at), never by the branch name. A same-named branch the user
+created — or one that no longer contains the recorded commit, i.e. deleted and
+recreated or force-moved — is left alone and the task falls back to
+`agent/<agent>/<issue>-<id>`.
+
+A turn replays only what the user changed since that snapshot; when those edits
+conflict with the branch's own work the worktree is handed to the agent
+mid-merge and the run delivers nothing until the agent resolves it.
+
+`worktree` requires the path to be a git repository with at least one commit;
+tasks fail with an explicit error otherwise. The gate is the `local-worktree-v1`
+capability the daemon advertises — not its version string — and it is checked
+twice: at save time, and again against the daemon that claims each task, so a
+machine whose runtime cannot do worktrees gets its tasks cancelled rather than
+run in place. Saving `worktree` is refused (HTTP 422, code
+`daemon_version_unsupported`) while the daemon on that machine does not
+advertise the capability — the fix is updating the Multica app there, then
+retrying. Pass an empty value to clear it back to the default.
+
+## Referring to a project in a comment
+
+A project has no `MUL-123`-style identifier, so writing its title as prose
+produces dead text — there is nothing for the reader's client to autolink. Use
+the mention-link form instead, with the project UUID from
+`multica project list --output json`:
+
+ [Roadmap](mention://project/<project-id>)
+
+Every client makes it navigable, with different presentation: web and desktop
+render a chip carrying the project's icon and current title, while mobile
+renders an ordinary link that opens the project on tap. Unlike `@agent` /
+`@squad`, it is a pure link: the mention parser does not recognize `project` at
+all, so it enqueues nothing and notifies nobody — the same no-side-effect
+contract as an `issue` mention.
+
+Prefer this form over pasting the project's URL. Web and desktop do unfurl a
+bare in-app project URL into that same chip, but mobile does not — there a
+pasted URL is handed to the system browser and takes the reader out of the app.
+
+## When to add a resource
+
+Add/update a project resource when the user asks for durable project context:
+"把这个 GitHub repo 绑到项目上", "以后都用这个 repo", "agent 总是拿不到这个项目的
+仓库", or "这个项目要在我的本地目录里跑".
+
+Project resources are durable and affect future tasks. `multica repo checkout`
+is task-local checkout state.
+
+## Debugging wrong context
+
+1. `multica project get <project-id> --output json`.
+2. `multica project resource list <project-id> --output json`.
+3. Check `github_repo.resource_ref.url`, optional `ref`, `default_branch_hint`,
+ and `local_directory.resource_ref.daemon_id`.
+4. Updating resources is a durable mutation. After an update, listing the
+ resource is the verification path.
+5. If resources match the expected task context, inspect runtime/repo checkout
+ path next.
+
+## Side effects
+
+Project create/update/delete/status and project resource add/update/remove
+mutate durable workspace state and affect future tasks. Ask before changing
+`local_directory` unless the user explicitly requested that exact local path.
diff --git a/server/internal/service/builtin_skills/multica-platform/references/runtimes.md b/server/internal/service/builtin_skills/multica-platform/references/runtimes.md
new file mode 100644
index 0000000000..b4c5da0506
--- /dev/null
+++ b/server/internal/service/builtin_skills/multica-platform/references/runtimes.md
@@ -0,0 +1,138 @@
+# Runtimes and repos
+
+A runtime is the execution target behind an agent. A daemon owns local runtime
+processes and claims queued tasks from the server.
+
+- [Core model](#core-model)
+- [CLI](#cli)
+- [Task CLI boundary](#task-cli-boundary)
+- [Debugging an agent that did not run](#debugging-an-agent-that-did-not-run)
+- [Repos](#repos)
+
+## Core model
+
+The chain is:
+
+1. a user action creates or updates a queued task;
+2. the task points at an agent and runtime;
+3. the server wakes the runtime over the daemon websocket when possible;
+4. the daemon polls and claims the task;
+5. the server returns task context, repos, project resources, prior
+ session/workdir hints, and a task token;
+6. the daemon prepares a workdir and launches the provider CLI;
+7. `multica repo checkout` talks to the local daemon, not directly to GitHub.
+
+## CLI
+
+```bash
+multica runtime list --output json
+multica runtime usage <runtime-id> --output json
+multica runtime activity <runtime-id> --output json
+multica runtime update <runtime-id> --target-version <version> --output json
+multica runtime delete <runtime-id>
+multica repo checkout <url>
+multica repo checkout <url> --ref <branch-or-sha>
+```
+
+Runtime and repo commands affect active agent execution. Do not restart daemons,
+update runtimes, or check out arbitrary repos just to test.
+
+`runtime update` and `runtime delete` are writes. Starting a runtime update is
+limited to its owner or a workspace owner/admin; the original initiator may keep
+polling that specific in-flight request if their admin role changes.
+
+`runtime delete` removes a runtime registration; if active agents are still
+bound, it refuses unless the user explicitly passes `--cascade`, which unbinds
+those agents and cancels their queued/running tasks before deleting the runtime.
+Unbinding keeps the agents and everything they own — instructions, skills,
+chats, labels, channel installations, autopilots and task history — and only
+clears the agent's runtime binding; an unbound agent cannot run until it is
+bound again (`multica agent update <id> --runtime-id <runtime-id>`), and every
+trigger path refuses it with `agent_runtime_required`.
+
+`repo checkout` creates a dedicated branch in the task working directory. Most
+runtimes use a linked worktree; Linux and Windows Codex use task-local Git
+metadata so a task can stage and commit without making the shared repository
+cache writable.
+
+`repo checkout` requires both `MULTICA_DAEMON_PORT` and the injected task-scoped
+`MULTICA_TOKEN`; it is intended to run inside the active daemon task and from
+that task's workdir (or a descendant). The local daemon authenticates the token
+against its active-task registry, derives workspace/task/agent identity itself,
+and rejects a caller-supplied workdir outside that task. If either variable is
+absent, you are not in the normal agent checkout path. When a project
+`github_repo` resource has `resource_ref.ref`, `repo checkout <url>` uses that
+ref by default for the current task; an explicit
+`repo checkout <url> --ref <branch-or-sha>` overrides it.
+
+## Task CLI boundary
+
+The daemon injects a task-scoped `mat_` credential for Multica API commands and
+a private task-local Multica configuration root. Inside that managed task
+context:
+
+- API commands such as `issue list`, `issue get`, and `issue runs` use the
+ injected task identity and never fall back to the daemon Owner's saved Multica
+ profile.
+- `config show` and `config set` operate only on task-local Multica state. A
+ missing task config root fails closed.
+- `auth status` may verify the task identity but omits all token material from
+ its output.
+- `daemon status` and `daemon disk-usage` report on the runtime hosting this
+ task: `status` probes the daemon-injected health port, and `disk-usage` scans
+ the daemon-injected workspaces root. Both refuse `--profile`, `disk-usage`
+ also refuses `--all-profiles` and `--workspaces-root`, and its STATUS column
+ stays blank because filling it would spend the Owner's credential.
+- Human/local profile and daemon commands — including `login`, `logout`,
+ `setup`, `workspace switch`, local runtime profile path mutation,
+ `daemon start` / `stop` / `restart`, `daemon logs`, and
+ `daemon probe-runtimes` — are unavailable. `daemon stop` in particular would
+ terminate the daemon running this task and every sibling task on it.
+
+`MULTICA_DAEMON_PORT` alone is a weak, defense-in-depth signal for task-safe API
+and profile resolution, not task identity for human/local command rejection.
+Genuine tasks also carry `MULTICA_AGENT_ID` / `MULTICA_TASK_ID`,
+`MULTICA_TASK_CONFIG_ROOT`, or a daemon-managed workdir marker. When the port is
+the only signal, `daemon status` uses the selected host profile's derived health
+port; ordinary API and profile-resolving commands still fail closed. Host
+operators should not export `MULTICA_DAEMON_PORT`; the daemon derives its host
+health port from the selected profile and injects the variable into tasks
+itself.
+
+The daemon still preserves the real `HOME` and XDG variables for provider tools
+such as `gh`, `aws`, `kubectl`, and npm. This is CLI resolution hardening, not
+hard filesystem confidentiality: a process under the same OS user can still open
+an explicitly known Owner path. Dedicated Unix users, containers, VMs, or an
+equivalent OS boundary are required for that stronger isolation.
+
+## Debugging an agent that did not run
+
+Check in this order:
+
+1. Was a task supposed to be created? Inspect issue/comment/autopilot context.
+2. Is the assignee an agent or squad? A squad routes to its leader.
+3. Is the agent archived or bound to a runtime the actor cannot use?
+4. Is the runtime online? `multica runtime list --output json`.
+5. Did the daemon heartbeat recently? Runtime `last_seen_at` is the visible clue.
+6. Did the task get claimed or is it stuck pending/running/waiting for local directory?
+7. If repo checkout failed, classify it after checking whether repo context was
+ present in the task/project context.
+
+## Repos
+
+The runtime brief lists repos available to this task. Treat that list as the
+authority for agent checkout unless the user explicitly asks to bind a new
+project resource.
+
+Workspace repos and project resources are not the same thing:
+
+- workspace repo metadata can appear in workspace context;
+- `github_repo` project resources are durable project context and can affect
+ future tasks; optional `resource_ref.ref` pins the default checkout ref for
+ tasks in that project;
+- `local_directory` resources point at a path owned by a daemon and carry
+ local-machine assumptions.
+
+Do not add a project resource just because `repo checkout` failed. First
+determine whether the user asked for durable project context or just a task
+checkout.
diff --git a/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md b/server/internal/service/builtin_skills/multica-platform/references/skill-import.md
similarity index 81%
rename from server/internal/service/builtin_skills/multica-skill-importing/SKILL.md
rename to server/internal/service/builtin_skills/multica-platform/references/skill-import.md
index 7938d8ddc3..de16f2c32f 100644
--- a/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/skill-import.md
@@ -1,22 +1,21 @@
----
-name: multica-skill-importing
-description: "Use when asked to import or install a specific skill into this Multica workspace from a URL or slug. Not for choosing which skill the user needs; never treat a local installer such as `npx skills add` as the final install."
-user-invocable: false
-allowed-tools: Bash(multica *)
----
-
-# Importing skills into Multica
-
-Use this skill when the user already provided a skill URL, slug, or a clear intent
-to import a specific skill into the current Multica workspace.
-
-Do not use this skill to decide which skill the user needs. If the user only
-describes a capability and no URL is known, external search may produce candidate
-URLs, but this import skill starts only once a URL or concrete import target is
-known.
-
-Every claim below is traced to source in
-`references/skill-importing-source-map.md`. When in doubt, read that file.
+# Importing skills
+
+Use this when the user already provided a skill URL, slug, or a clear intent to
+import a specific skill into the current Multica workspace. It does not help you
+decide WHICH skill the user needs — if they only described a capability and no
+URL is known, external search may produce candidates, but importing starts only
+once a URL or concrete target exists.
+
+- [The invariant](#the-invariant)
+- [Supported URL source families](#supported-url-source-families)
+- [Local archive import](#local-archive-import)
+- [Direct URL flow](#direct-url-flow)
+- [Additive add vs replace-all set](#additive-add-vs-replace-all-set)
+- [Reserved SKILL.md supporting file](#reserved-skillmd-supporting-file)
+- [Same-name conflicts: --on-conflict](#same-name-conflicts---on-conflict)
+- [Updating an already-imported skill](#updating-an-already-imported-skill)
+- [Reading a skill back](#reading-a-skill-back)
+- [Incorrect to correct](#incorrect-to-correct)
## The invariant
@@ -47,7 +46,7 @@ environment, not the Multica workspace DB, so Multica cannot manage or bind it.
## Supported URL source families
-`detectImportSource` accepts these hosts (and `www.` variants). Pass any of these
+The import endpoint accepts these hosts (and `www.` variants). Pass any of these
forms to `multica skill import --url <url> --output json`:
```bash
@@ -64,7 +63,7 @@ multica skill import --url github.com/owner/repo/blob/main/path/to/SKILL.md --ou
- A bare ClawHub slug (no host) is accepted and routed to ClawHub.
- Any other host is rejected with a 400 naming the supported sources.
-## Local archive import (`.skill` / `.zip`)
+## Local archive import
`multica skill import --file <path> --output json` imports a skill from a local
archive instead of a hosted URL. A `.skill` file is a standard zip — the format
@@ -103,14 +102,13 @@ structured import result envelope:
{
"status": "created|updated|conflict|skipped|failed",
"reason": "...",
- "skill": { "...": "SkillWithFilesResponse when created/updated" },
+ "skill": { "...": "the workspace skill, with its files, when created/updated" },
"existing_skill": { "id": "...", "name": "...", "can_overwrite": true }
}
```
-For `created` / `updated`, `skill` is a workspace `SkillWithFilesResponse`: it
-embeds the standard `SkillResponse` and adds the supporting `files` array. Report
-the relevant fields:
+For `created` / `updated`, `skill` is the workspace skill record plus a `files`
+array of its supporting files. Report the relevant fields:
- `status` and `reason` when present.
- `skill.id` / `skill.name` / `skill.description`.
@@ -137,21 +135,21 @@ target skill id is present before claiming the skill is available to that agent.
## Additive add vs replace-all set
-`multica agent skills add` is additive: the server inserts the assignments without
-clearing existing ones (`AddAgentSkills`).
+`multica agent skills add` is additive: the server inserts the assignments
+without clearing existing ones.
`multica agent skills set` is replace-all: the server clears every current
-assignment, then re-adds exactly the ids you pass (`SetAgentSkills`).
-`set` is the replacement path. Passing only one id to `set` leaves the agent with
-only that one skill and drops every previous assignment.
+assignment, then re-adds exactly the ids you pass. `set` is the replacement
+path. Passing only one id to `set` leaves the agent with only that one skill and
+drops every previous assignment.
## Reserved SKILL.md supporting file
-A skill's primary content is its `SKILL.md`. That filename is reserved: the daemon
-writes the primary content to `SKILL.md` itself when preparing the execution
-environment, so a *supporting* file may not also be named `SKILL.md`
-(`IsReservedContentPath`; the check cleans the path and is case-insensitive, so
-`./SKILL.md` and `sub/../SKILL.md` are caught too).
+A skill's primary content is its `SKILL.md`. That filename is reserved: the
+daemon writes the primary content to `SKILL.md` itself when preparing the
+execution environment, so a *supporting* file may not also be named `SKILL.md`.
+The check cleans the path and is case-insensitive, so `./SKILL.md` and
+`sub/../SKILL.md` are caught too.
Practical effect when importing or creating a skill: if the manifest lists a
supporting file named `SKILL.md`, the server silently drops it — the import still
@@ -161,7 +159,7 @@ rename it to a non-reserved path. (The hard `400` rejection — "SKILL.md is res
for the primary skill content" — only fires on the dedicated single-file endpoint
`PUT /api/skills/{id}/files`, not on import.)
-## Same-name conflicts: `--on-conflict`
+## Same-name conflicts: --on-conflict
Default behavior is safe: `multica skill import --url <url>` is equivalent to
`--on-conflict fail`. If the imported skill name already exists, the command
@@ -234,7 +232,7 @@ Then report that the skill already exists and include its `id` / `name`. Do not
retry in a loop, and do not create a second skill under a different name just to
dodge the conflict.
-## Updating an already-imported skill: `multica skill refresh`
+## Updating an already-imported skill
When the goal is to pull the latest version of a skill that is already in the
workspace, prefer `refresh` over re-typing the import URL:
@@ -255,9 +253,9 @@ skill in place:
- Permission: the skill's creator or a workspace `owner`/`admin` — broader than
`import --on-conflict overwrite`, which stays creator-only.
-The success response is the plain `SkillWithFilesResponse` (same shape as
-`multica skill get --with-content`), not the import result envelope. Failure modes to report
-instead of retrying in a loop:
+The success response is the plain skill-with-files shape (same as
+`multica skill get --with-content`), not the import result envelope. Failure
+modes to report instead of retrying in a loop:
- `422`: the skill has no refreshable provenance (created manually, imported
from a local archive, or copied from a local runtime). Re-import instead.
@@ -267,13 +265,13 @@ instead of retrying in a loop:
- `502` / `503` / `504` / `413`: upstream fetch failed (gone, unavailable,
timed out, or now exceeds import caps); the skill is left untouched.
-## Reading a skill back: metadata by default
+## Reading a skill back
`multica skill get` and `multica skill files list` return **metadata only** —
path, byte size and content hash per file, plus the size and hash of the
SKILL.md body. That is what the conflict and verification steps above need, and
it is what keeps a large skill inspectable at all: inlining every body made a
-~600KB skill impossible to fetch over a slow link (GH #7498).
+~600KB skill impossible to fetch over a slow link.
```bash
multica skill get <skill-id> --output json # metadata
@@ -285,7 +283,7 @@ Reach for `--with-content` only when you are going to read the content. To find
out why a skill is large, the default output already answers it: the `size`
column names the file.
-## Incorrect → correct
+## Incorrect to correct
Incorrect (bypasses Multica):
@@ -296,9 +294,8 @@ npx skills add https://skills.sh/owner/repo/skill
The skill may exist locally, but Multica cannot manage it as a workspace skill.
Incorrect agent binding for a normal add (replaces every existing assignment):
-
-Using `set` with only the new skill id wipes the agent's other skills. For an add,
-use `add`.
+using `set` with only the new skill id wipes the agent's other skills. For an
+add, use `add`.
Correct import:
@@ -313,8 +310,3 @@ agent's skill assignments:
multica agent skills add <agent-id> --skill-ids <skill-id> --output json
multica agent skills list <agent-id> --output json
```
-
-## References
-
-- `references/skill-importing-source-map.md` — every behavior above mapped to
- `file:line` in `server/`, plus the verification command to re-derive the lines.
diff --git a/server/internal/service/builtin_skills/multica-squads/SKILL.md b/server/internal/service/builtin_skills/multica-platform/references/squads.md
similarity index 73%
rename from server/internal/service/builtin_skills/multica-squads/SKILL.md
rename to server/internal/service/builtin_skills/multica-platform/references/squads.md
index f608639bd0..dacf887663 100644
--- a/server/internal/service/builtin_skills/multica-squads/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/squads.md
@@ -1,15 +1,22 @@
----
-name: multica-squads
-description: "Use when creating, inspecting, updating, assigning to, or debugging a Multica squad, including how leader routing picks who runs."
-user-invocable: false
-allowed-tools: Bash(multica *)
----
+# Squads
-# Multica Squads
+A squad is a workspace routing and coordination object. It is not an agent and
+it does not run work by itself.
-## Quick start
+- [Debugging a squad that did or did not run](#debugging-a-squad-that-did-or-did-not-run)
+- [Core model](#core-model)
+- [CLI](#cli)
+- [Squad fields](#squad-fields)
+- [Creation and leader membership](#creation-and-leader-membership)
+- [Leader briefing](#leader-briefing)
+- [Issue assignment behavior](#issue-assignment-behavior)
+- [Comment and mention behavior](#comment-and-mention-behavior)
+- [Autopilot behavior](#autopilot-behavior)
+- [Common wrong assumptions](#common-wrong-assumptions)
-If debugging why a squad did or did not run, inspect first:
+## Debugging a squad that did or did not run
+
+Inspect first:
```bash
multica issue get <issue-id> --output json
@@ -19,28 +26,13 @@ multica issue comment list <issue-id> --roots-only --summary --output json
multica issue comment list <issue-id> --thread <thread-id> --tail 30 --output json
```
-The two comment reads are a sequence: scan the roots first, then open the threads that look relevant — mention triggers, failure reasons, and user instructions usually live in the replies, which the roots scan never returns.
-
-If the command shape is unclear, check help instead of guessing:
-
-```bash
-multica squad --help
-multica squad member --help
-multica issue update --help
-multica issue comment add --help
-```
-
-Do not assign, comment, mention, update, delete, or record squad activity just
-to test. These can mutate workspace state or trigger agent runs.
+The two comment reads are a sequence: scan the roots first, then open the
+threads that look relevant — mention triggers, failure reasons, and user
+instructions usually live in the replies, which the roots scan never returns.
## Core model
-A Multica squad is a workspace routing and coordination object.
-
-A squad is not an agent. It does not run work by itself. Current behavior:
-squad-routed work runs through the squad's `leader_id` agent.
-
-Important consequences:
+Squad-routed work runs through the squad's `leader_id` agent. Consequences:
- assigning an issue to a squad routes to the leader;
- mentioning a squad routes to the leader;
@@ -81,11 +73,11 @@ Use it only when acting as the squad leader after evaluating a trigger.
Which issue it accepts: **the issue your current turn is running on**. The
target issue does NOT need to be assigned to your squad — a `@squad` mention on
an issue owned by an individual agent, or a leader task bound to a child issue,
-all record fine. What the server checks is your task row (`is_leader_task` plus
-a stamped `squad_id`), not the issue's assignee. A leader woken by a stage
-barrier runs on the PARENT issue, so record against the parent, not the child
-you just read; passing an unrelated issue id is rejected and the error names the
-issue you should have used.
+all record fine. What the server checks is your task's leader flag and stamped
+squad id, not the issue's assignee. A leader woken by a stage barrier runs on
+the PARENT issue, so record against the parent, not the child you just read;
+passing an unrelated issue id is rejected and the error names the issue you
+should have used.
If the call fails, do not exit silently — the comment prohibition on `no_action`
only applies once the recording succeeded. Post one short comment with the
@@ -101,10 +93,8 @@ multica issue comment list <issue-id> --roots-only --summary --output json
multica issue comment add <issue-id> --help
```
-Comment reads stay bounded — the scan-then-expand sequence from the quick
-start above — never one unbounded `issue comment list` pull.
-
-Prefer `--output json` for reads. Use `--help` before writes.
+Comment reads stay bounded — the scan-then-expand sequence above, never one
+unbounded pull.
## Squad fields
@@ -112,7 +102,7 @@ Prefer `--output json` for reads. Use `--help` before writes.
- `workspace_id` — workspace the squad belongs to.
- `name` — display name; unique per workspace.
- `description` — human-facing metadata/display text. Do not assume runtime
- prompt impact unless source proves a consumer.
+ prompt impact.
- `instructions` — squad-level instructions added to the squad leader briefing.
They are not directly injected into every squad member.
- `avatar_url` — optional squad avatar URL.
@@ -132,9 +122,8 @@ write it as if every member automatically receives it.
- `member_type` — `agent` or `member`.
- `member_id` — ID of the agent or workspace member.
-- `role` — roster role label. Current behavior: non-empty `role` appears in the
- leader briefing roster. Do not assume it creates scheduling, permissions, or
- routing behavior.
+- `role` — roster role label. A non-empty `role` appears in the leader briefing
+ roster. It does not create scheduling, permissions, or routing behavior.
## Creation and leader membership
@@ -161,7 +150,7 @@ Roster entries include member name, member type, mention markdown, and non-empty
role. For agent members the roster also lists their assigned skills
(`skills: a, b`, or `no skills assigned` when the agent has none) so the leader
can delegate by capability instead of guessing from the role label; human
-members carry no skills segment. Builtin `multica-*` skills are not listed —
+members carry no skills segment. Built-in `multica-*` skills are not listed —
only the workspace skills explicitly attached to the agent. Archived agent
members are skipped from the briefing roster.
@@ -186,7 +175,7 @@ Current behavior:
the leader's first assignment turn should move the parent to `in_progress`
and keep it there while members work; the leader moves the parent to
`in_review` only when a later re-trigger confirms the overall goal is met.
- Completing a leader `task` (including the first dispatch) does not itself
+ Completing a leader task (including the first dispatch) does not itself
change issue status;
- that status authority is granted only when the issue's `assignee_type` /
`assignee_id` point at THIS squad. The leader briefing is injected on every
@@ -194,9 +183,8 @@ Current behavior:
— on those paths the protocol instead carries an explicit "do not change this
issue's status".
-The status names above are category rules: a workspace may define custom
-statuses beyond the built-ins, and each one inherits its category's behavior in
-full (the runtime brief lists the workspace catalog when any exist).
+The status names above are category rules: a custom status inherits its
+category's behavior in full.
Assignment validation rejects a missing type/id pair, non-existent squad,
archived squad, archived leader, and private leader when the actor cannot access
@@ -231,24 +219,6 @@ and `assignee_id = <squad-id>`, while the actual executing agent is the resolved
leader. For `run_only` autopilots, no issue is created; the task is created
directly for the resolved leader agent.
-## Handling complaints or product gaps
-
-When the user says squad behavior is wrong, confusing, or disappointing, do not
-immediately assume code is broken and do not defend current behavior just because
-it exists. Classify first:
-
-- expected current behavior;
-- configuration issue;
-- product limitation;
-- actual bug.
-
-Explain the current source-backed behavior. If the behavior is technically
-correct but product-wise bad, say so and propose a scoped product/code change.
-
-Do not silently change squad routing, member fan-out, leader briefing, autopilot
-behavior, or comment-trigger behavior without confirmation. These are product
-contract changes with side effects.
-
## Side effects
These actions can trigger agent work or mutate durable state:
@@ -264,10 +234,7 @@ These actions can trigger agent work or mutate durable state:
- mentioning a squad;
- creating or triggering squad-assigned autopilots;
- recording squad activity with `multica squad activity`;
-- deleting/archive squad.
-
-Do not perform side-effecting actions as tests unless the user explicitly
-authorizes them.
+- deleting/archiving a squad.
## Common wrong assumptions
@@ -277,7 +244,7 @@ authorizes them.
- Squad assignment routes to the leader, not every member.
- Squad autopilot resolves to the leader as executable agent.
- `instructions` are leader briefing content, not automatic member prompts.
-- `description` is not proven runtime prompt content.
+- `description` has no proven runtime prompt effect.
- `role` is roster context, not automatic scheduling.
- Backlog assignment does not immediately start work.
- First leader dispatch is not parent completion — parent stays `in_progress`
@@ -287,11 +254,3 @@ authorizes them.
- Getting the leader briefing does NOT imply status authority. A squad
`@`-mentioned into an issue assigned to someone else is a guest: roster and
delegation rules yes, `multica issue status` no.
-
-## References
-
-For source paths, tests, edge cases, and exact routing details, see:
-
-```text
-references/squad-source-map.md
-```
diff --git a/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md b/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md
deleted file mode 100644
index 376be48124..0000000000
--- a/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md
+++ /dev/null
@@ -1,121 +0,0 @@
----
-name: multica-projects-and-resources
-description: "Use when creating, inspecting, updating, or debugging Multica projects and their resources (github_repo, local_directory)."
-user-invocable: false
-allowed-tools: Bash(multica *)
----
-
-# Multica Projects and Resources
-
-## Quick start
-
-Projects are durable context containers. Resources attached to a project can affect future agent tasks.
-
-```bash
-multica project list --output json
-multica project get <project-id> --output json
-multica project resource list <project-id> --output json
-```
-
-Project resources are mutated through project resource commands/endpoints. Issue
-comments do not create durable project resources.
-
-## Core model
-
-A project groups work and carries durable resources. A resource is not just display metadata; it is context later injected into task briefs and `.multica/project/resources.json`.
-
-A project's `description` is also durable context: when an issue (or a quick-create task) is bound to a project, the project description is injected into the agent's brief under `## Project Context` and written to `.multica/project/resources.json` as `project_description`. Use it for project-wide rules/context that should apply to every task in the project.
-
-Common resource types:
-
-- `github_repo` — durable GitHub repo context, with `resource_ref.url`, optional checkout `ref`, and optional prompt-only `default_branch_hint`;
-- `local_directory` — daemon-local path context, with `resource_ref.local_path`, `daemon_id`, optional label, and
- optional `execution_mode` (`in_place`, the default, or `worktree`).
-
-## CLI
-
-```bash
-multica project list --output json
-multica project get <project-id> --output json
-multica project create --title "<title>" --repo <github-url> --output json
-multica project create --title "<title>" --start-date 2026-03-01 --due-date 2026-03-31 --output json
-multica project update <project-id> --title "<title>" --output json
-multica project update <project-id> --due-date 2026-04-15 --output json
-multica project update <project-id> --start-date "" --output json # clear the start date
-multica project status <project-id> in_progress --output json
-multica project resource list <project-id> --output json
-multica project resource add <project-id> --type github_repo --url <github-url> --output json
-multica project resource add <project-id> --type github_repo --url <github-url> --ref <branch-or-sha> --output json
-multica project resource add <project-id> --type local_directory --local-path <abs-path> --daemon-id <daemon-id> --output json
-multica project resource add <project-id> --type local_directory --local-path <abs-path> --daemon-id <daemon-id> --execution-mode worktree --output json
-multica project resource update <project-id> <resource-id> --execution-mode in_place --output json
-multica project resource update <project-id> <resource-id> --url <new-github-url> --output json
-multica project resource update <project-id> <resource-id> --ref <branch-or-sha> --output json
-multica project resource remove <project-id> <resource-id> --output json
-```
-
-`--execution-mode` decides how tasks share a `local_directory`. `in_place` (default) runs the agent in the user's
-directory, one task at a time; a second task waits in `waiting_local_directory`. `worktree` gives each task its own
-git worktree of that repo, so tasks run concurrently and each delivers its work as a branch in the user's repo
-instead of editing the working copy. Every task of one conversation shares that branch — `agent/<agent>/<issue>` for
-an issue, `agent/<agent>/chat-<session>` for a chat — and each turn's worktree starts from the previous turn's work
-rather than from `HEAD`; a task with no conversation behind it gets `agent/<agent>/<task>`. Continuation is decided by
-an ownership record (`refs/multica/local-state/<branch>`, which holds the owning conversation, the snapshot of the
-user's directory the branch already carries, and the branch tip it was recorded at), never by the branch name. A
-same-named branch the user created — or one that no longer contains the recorded commit, i.e. deleted and recreated or
-force-moved — is left alone and the task falls back to `agent/<agent>/<issue>-<id>`. A turn replays only what the user changed since that snapshot; when those
-edits conflict with the branch's own work the worktree is handed to the agent mid-merge and the run delivers nothing
-until the agent resolves it. `worktree` requires the path to be a git repository with at
-least one commit; tasks fail with an explicit error otherwise. The gate is the `local-worktree-v1` capability the
-daemon advertises — not its version string — and it is checked twice: at save time, and again against the daemon that
-claims each task, so a machine whose runtime cannot do worktrees gets its tasks cancelled rather than run in place.
-Saving `worktree` is also refused (HTTP 422, code `daemon_version_unsupported`) while the daemon on that machine does
-not advertise the capability — the fix is updating the Multica app there, then retrying. Pass an empty value to clear
-it back to the default.
-
-For `github_repo`, non-JSON `--ref` sets `resource_ref.ref`, the default checkout branch/tag/SHA for future tasks in that project. JSON `--ref '<json>'` remains the escape hatch for full payloads or resource types not covered by shortcuts.
-
-`--start-date` / `--due-date` are optional calendar days (`YYYY-MM-DD`, like issue dates). On `project update`, pass an empty string (`--start-date ""`) to clear a date; an unset flag leaves it untouched.
-
-## Referring to a project in a comment
-
-A project has no `MUL-123`-style identifier, so writing its title as prose
-produces dead text — there is nothing for the reader's client to autolink. Use
-the mention-link form instead, with the project UUID from
-`multica project list --output json`:
-
- [Roadmap](mention://project/<project-id>)
-
-Every client makes it navigable, with different presentation: web and desktop
-render a chip carrying the project's icon and current title, while mobile
-renders an ordinary link that opens the project on tap. Unlike `@agent` /
-`@squad`, it is a pure link: `util.MentionRe` does not even include `project`,
-so it enqueues nothing and notifies nobody — the same no-side-effect contract
-as an `issue` mention.
-
-Prefer this form over pasting the project's URL. Web and desktop do unfurl a
-bare in-app project URL into that same chip, but mobile does not — there a
-pasted URL is handed to the system browser and takes the reader out of the app.
-
-## When to add a resource
-
-Add/update a project resource when the user asks for durable project context: "把这个 GitHub repo 绑到项目上", "以后都用这个 repo", "agent 总是拿不到这个项目的仓库", or "这个项目要在我的本地目录里跑".
-
-Project resources are durable and affect future tasks. `multica repo checkout`
-is task-local checkout state.
-
-## Debugging wrong context
-
-1. `multica project get <project-id> --output json`.
-2. `multica project resource list <project-id> --output json`.
-3. Check `github_repo.resource_ref.url`, optional `ref`, `default_branch_hint`, and `local_directory.resource_ref.daemon_id`.
-4. Updating resources is a durable mutation. After an update, listing the
- resource is the verification path.
-5. If resources match the expected task context, inspect runtime/repo checkout
- path next.
-
-## Side effects
-
-Project create/update/delete/status and project resource add/update/remove mutate durable workspace state and affect future tasks. Ask before changing `local_directory` unless the user explicitly requested that exact local path.
-
-More source-backed details: `references/projects-and-resources-source-map.md`.
diff --git a/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.md b/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.md
deleted file mode 100644
index 9a89150045..0000000000
--- a/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# Projects and resources source map
-
-- `server/cmd/multica/cmd_project.go` registers project `list`, `get`, `create`, `update`, `delete`, and `status`.
-- The same file registers `project resource list/add/update/remove`.
-- `project create --repo` attaches `github_repo` resources during project creation.
-- `project create` / `project update` accept `--start-date` / `--due-date` (calendar days, `YYYY-MM-DD`), mapping to the project `start_date` / `due_date` columns (migration `166_project_dates`); an empty `--start-date ""`/`--due-date ""` on update clears the date, mirroring the issue date flags in `cmd_issue.go`.
-- `project resource add` supports shortcuts for `github_repo` (`--url`, non-JSON `--ref` for checkout ref, `--default-branch-hint`) and `local_directory` (`--local-path`, `--daemon-id`, `--ref-label`, `--execution-mode`), or generic JSON `--ref '<json>'`.
-- `local_directory.execution_mode` is validated in `server/internal/handler/project_resource.go` (`validateLocalDirectoryRef`); the daemon reads it in `server/internal/daemon/local_directory.go` (`localDirectoryAssignment.UsesWorktree`) and builds the per-task worktree in `server/internal/daemon/execenv/local_worktree.go`.
-- The branch a worktree task delivers on is chosen by `resolveTaskBranch` in `server/internal/daemon/execenv/local_worktree.go`: one branch per conversation (issue, else chat session — `localWorktreeConversation`), task-scoped only when there is no conversation or when a sibling task already holds the conversation's branch. Continuing one requires proving ownership (`branchOwnedBy`): the branch record must carry this workspace/agent/conversation AND its checkpoint (the record commit's second parent) must still be an ancestor of the branch tip, so a same-named branch that was deleted and recreated or force-moved is refused. An unowned branch pushes the task onto `<branch>-<fingerprint>`. The checkpoint is always a commit the branch could not sit at without this conversation's work: every branch this mode creates gets a baseline commit of its own (`commitBaseline`, empty when the user's tree was clean), and every later turn that replays user edits commits its own baseline too. `Finalize.verifyDeliveryPoint` requires the delivered tip to be its own branch's and to still contain `LocalWorktree.BaseCommit` — the commit THAT turn started from, which is later than any earlier checkpoint once the user has committed on the branch themselves. A turn whose replay conflicted has no baseline until the agent resolves, so it only advances the recorded snapshot when the branch moved past where that turn found it. `Finalize` records the tip it delivered before removing the worktree, and fails the task — keeping the worktree — when the delivery cannot be verified or the record cannot be written.
-- The user's directory is captured as one commit including untracked files (`captureUserSnapshot`, built in a private index under the task env root) and recorded at `refs/multica/local-state/<branch>` once the branch carries it. A follow-up turn replays only the difference (`replayUserState`); an unmergeable difference is left in the worktree for the agent, announced by `buildWorktreeReplayConflictBlock` in `server/internal/daemon/prompt.go`, and `Finalize` refuses to commit while any path is still unmerged. Orphaned refs are dropped by `pruneOrphanedStateRefs` on the next prepare in that repo.
-- Saving `execution_mode=worktree` is gated on the daemon having advertised the `local-worktree-v1` capability (`protocol.DaemonCapabilityLocalWorktreeV1`), checked by `requireWorktreeCapableDaemon` in `server/internal/handler/project_resource.go` against the daemon's most recently seen runtime row; not capable → HTTP 422 `daemon_version_unsupported`. The authoritative gate is at claim time (`worktreeClaimBlockReason` in `server/internal/handler/daemon.go`), which reads the capability off the claim request itself and cancels the task with a reason. `MinLocalWorktreeCLIVersion` is only the number shown to the user; nothing gates on it.
-- `project resource update` merges shortcut edits with existing `resource_ref` so a partial edit does not clobber required fields; non-JSON `--ref` updates `github_repo.resource_ref.ref`.
-- `server/cmd/server/router.go` exposes `/api/projects` plus `/api/projects/{projectId}/resources` routes.
-- `server/pkg/db/queries/project_resource.sql` is the CRUD query surface for `project_resource` rows.
-- Project resources are written into `.multica/project/resources.json` for agent workdirs.
-- `github_repo.resource_ref.ref` is lifted into daemon `RepoData.Ref` by `server/internal/handler/daemon.go`; `server/internal/daemon/daemon.go` stores it per task, and `server/internal/daemon/health.go` uses it as the default `/repo/checkout` ref when the checkout request does not explicitly pass one.
-- Referring to a project in a comment: `[Label](mention://project/<uuid>)` is a render-only link. `util.MentionRe` (`server/internal/util/mention.go`) does NOT include `project` in its type group, so the backend never parses it and it can enqueue nothing — deliberately weaker than `agent` / `squad`. Presentation differs by client and the skill says so: web and desktop render a chip in `RichLink` (`packages/views/rich-content/rich-content.tsx`) and the editor's `MentionView` (`packages/views/editor/extensions/mention-view.tsx`), while mobile has no chip — `apps/mobile/lib/markdown/markdown.tsx` leaves the default enriched-link styling and only routes the tap (`onLinkPress`). Unfurling a bare in-app project/issue URL is web/desktop only, via `parseWorkspaceEntityLink` (`packages/views/editor/utils/link-handler.ts`), which requires same origin (resolved through `URL`, not a prefix test), no query/fragment, the current workspace slug, and an id that addresses one entity — a UUID, or an issue identifier (`MUL-123`), which is the form `copyLink` produces and which falls back to the plain link when it resolves to nothing (MUL-5499). On mobile a bare URL still goes to `Linking.openURL`. The agent-facing line lives in the runtime brief's Mentions section (`writeMentions`, `server/internal/daemon/execenv/runtime_config_sections.go`).
-- A project's `description` is injected as durable context for every task in the project. The claim handler (`server/internal/handler/daemon.go`) reads `proj.Description` onto the claim response (`ProjectDescription`, `server/internal/handler/agent.go`); the daemon carries it through `Task` (`server/internal/daemon/types.go`) and `TaskContextForEnv` (`server/internal/daemon/execenv/execenv.go`) into the brief's `## Project Context` section (`server/internal/daemon/execenv/runtime_config.go`) and into `.multica/project/resources.json` as `project_description` (`server/internal/daemon/execenv/context.go`).
diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
deleted file mode 100644
index fbcddab48f..0000000000
--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
+++ /dev/null
@@ -1,91 +0,0 @@
----
-name: multica-runtimes-and-repos
-description: "Use when a Multica runtime or daemon misbehaves: agent not running, task not claimed, runtime offline, workdir or session reuse, repository checkout."
-user-invocable: false
-allowed-tools: Bash(multica *)
----
-
-# Multica Runtimes and Repos
-
-## Quick start
-
-For "agent did not run" or "repo checkout failed", read the chain before changing anything:
-
-```bash
-multica agent get <agent-id> --output json
-multica runtime list --output json
-multica repo checkout <repo-url>
-```
-
-Runtime and repo commands affect active agent execution. Do not restart daemons, update runtimes, or check out arbitrary repos just to test.
-
-## Core model
-
-A runtime is the execution target behind an agent. A daemon owns local runtime processes and claims queued tasks from the server.
-
-The chain is:
-
-1. user action creates or updates an `agent_task_queue` row;
-2. the task points at an agent and runtime;
-3. server wakes the runtime over daemon websocket when possible;
-4. daemon polls/claims the task;
-5. server returns task context, repos, project resources, prior session/workdir hints, and task token;
-6. daemon prepares a workdir and launches the provider CLI;
-7. `multica repo checkout` talks to the local daemon, not directly to GitHub.
-
-## CLI
-
-```bash
-multica runtime list --output json
-multica runtime usage <runtime-id> --output json
-multica runtime activity <runtime-id> --output json
-multica runtime update <runtime-id> --target-version <version> --output json
-multica runtime delete <runtime-id>
-multica repo checkout <url>
-multica repo checkout <url> --ref <branch-or-sha>
-```
-
-`runtime update` and `runtime delete` are writes. Starting a runtime update is limited to its owner or a workspace owner/admin; the original initiator may keep polling that specific in-flight request if their admin role changes. `runtime delete` removes a runtime registration; if active agents are still bound, it refuses unless the user explicitly passes `--cascade`, which unbinds those agents and cancels their queued/running tasks before deleting the runtime. Unbinding keeps the agents and everything they own — instructions, skills, chats, labels, channel installations, autopilots and task history — and only clears `agent.runtime_id`; an unbound agent cannot run until it is bound to a runtime again (`multica agent update <id> --runtime-id <runtime-id>`), and every trigger path refuses it with `agent_runtime_required`. `repo checkout` creates a dedicated branch in the task working directory. Most runtimes use a linked worktree; Linux and Windows Codex use task-local Git metadata so a task can stage and commit without making the shared `.repos` cache writable.
-
-`repo checkout` requires both `MULTICA_DAEMON_PORT` and the injected task-scoped `MULTICA_TOKEN`; it is intended to run inside the active daemon task and from that task's workdir (or a descendant). The local daemon authenticates the token against its active-task registry, derives workspace/task/agent identity itself, and rejects a caller-supplied workdir outside that task. If either variable is absent, you are not in the normal agent checkout path. When a project `github_repo` resource has `resource_ref.ref`, `repo checkout <url>` uses that ref by default for the current task; an explicit `repo checkout <url> --ref <branch-or-sha>` overrides it.
-
-## Task CLI boundary
-
-The daemon injects a task-scoped `mat_` credential for Multica API commands and a private task-local Multica configuration root. Inside that managed task context:
-
-- API commands such as `issue list`, `issue get`, and `issue runs` use the injected task identity and never fall back to the daemon Owner's saved Multica profile.
-- `config show` and `config set` operate only on task-local Multica state. A missing task config root fails closed.
-- `auth status` may verify the task identity but omits all token material from its output.
-- `daemon status` and `daemon disk-usage` report on the runtime hosting this task: `status` probes the daemon-injected health port, and `disk-usage` scans the daemon-injected workspaces root. Both refuse `--profile`, `disk-usage` also refuses `--all-profiles` and `--workspaces-root`, and its STATUS column stays blank because filling it would spend the Owner's credential.
-- Human/local profile and daemon commands — including `login`, `logout`, `setup`, `workspace switch`, local runtime profile path mutation, `daemon start` / `stop` / `restart`, `daemon logs`, and `daemon probe-runtimes` — are unavailable. `daemon stop` in particular would terminate the daemon running this task and every sibling task on it.
-
-`MULTICA_DAEMON_PORT` alone is a weak, defense-in-depth signal for task-safe API and profile resolution, not task identity for human/local command rejection. Genuine tasks also carry `MULTICA_AGENT_ID` / `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, or a daemon-managed workdir marker. When the port is the only signal, `daemon status` uses the selected host profile's derived health port; ordinary API and profile-resolving commands still fail closed. Host operators should not export `MULTICA_DAEMON_PORT`; the daemon derives its host health port from the selected profile and injects the variable into tasks itself.
-
-The daemon still preserves the real `HOME` and XDG variables for provider tools such as `gh`, `aws`, `kubectl`, and npm. This is CLI resolution hardening, not hard filesystem confidentiality: a process under the same OS user can still open an explicitly known Owner path. Dedicated Unix users, containers, VMs, or an equivalent OS boundary are required for that stronger isolation.
-
-## Debugging an agent that did not run
-
-Check in this order:
-
-1. Was a task supposed to be created? Inspect issue/comment/autopilot context.
-2. Is the assignee an agent or squad? A squad routes to its leader.
-3. Is the agent archived or bound to a runtime the actor cannot use?
-4. Is the runtime online? `multica runtime list --output json`.
-5. Did the daemon heartbeat recently? Runtime `last_seen_at` is the visible clue.
-6. Did the task get claimed or is it stuck pending/running/waiting for local directory?
-7. If repo checkout failed, classify it after checking whether repo context was
- present in the task/project context.
-
-## Repos
-
-The runtime brief lists repos available to this task. Treat that list as the authority for agent checkout unless the user explicitly asks to bind a new project resource.
-
-Workspace repos and project resources are not the same thing:
-
-- workspace repo metadata can appear in workspace context;
-- `github_repo` project resources are durable project context and can affect future tasks; optional `resource_ref.ref` pins the default checkout ref for tasks in that project;
-- `local_directory` resources point at a path owned by a daemon and carry local-machine assumptions.
-
-Do not add a project resource just because `repo checkout` failed. First determine whether the user asked for durable project context or just a task checkout.
-
-More source-backed details: `references/runtimes-and-repos-source-map.md`.
diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
deleted file mode 100644
index 9f79283345..0000000000
--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# Runtimes and repos source map
-
-- `server/cmd/multica/cmd_runtime.go` registers `runtime list`, `usage`, `activity`, `update`, and `delete`.
-- `runtime list` reads `/api/runtimes` and prints `id`, `name`, `runtime_mode`, `provider`, `status`, and `last_seen_at`.
-- `runtime update` posts to `/api/runtimes/{runtime-id}/update`; with `--wait` it polls update status. Initiation enforces runtime-owner or workspace-owner/admin access through `canEditRuntime`; status polling additionally permits that request's immutable initiator so an in-flight poll survives an admin-role change (`server/internal/handler/runtime_update.go` and `runtime.go`).
-- `runtime delete` deletes `/api/runtimes/{runtime-id}`; with `--cascade`, it first reads the `runtime_has_active_agents` conflict payload and posts those ids to `/api/runtimes/{runtime-id}/unbind-agents-and-delete` (the older `/archive-agents-and-delete` path still routes to the same handler for installed clients). Both delete paths run `service.TeardownRuntime` in `server/internal/service/runtime_teardown.go`: user agents are unbound (`runtime_id = NULL`, MUL-5559), their task history is detached so deleting the runtime cannot cascade it away, active tasks are cancelled for user-confirmed deletion, and only `kind='system'` agents are hard-deleted.
-- `server/cmd/multica/cmd_repo.go` registers `repo checkout <url> [--ref]`.
-- `repo checkout` requires `MULTICA_DAEMON_PORT` plus the injected task-scoped `MULTICA_TOKEN`. It sends the token as a localhost bearer credential along with `workspace_id`, `workdir`, `ref`, `agent_name`, `task_id`, and the daemon-managed optional `checkout_mode`, then prints the checked-out path.
-- `server/internal/daemon/daemon.go` registers each provider execution in an in-memory checkout registry keyed by its task token and removes it when execution ends. `server/internal/daemon/health.go` authenticates `/repo/checkout` against that registry, requires the requested workspace/task and canonical workdir to belong to the active task, and derives the branch's agent name from the registry instead of trusting the request. It then resolves the checkout ref: request `ref` wins; otherwise it asks `daemon.go` for the current task's project repo default ref, and forwards the validated isolated-checkout mode into `repocache.WorktreeParams`.
-- `server/internal/daemon/daemon.go` injects `MULTICA_REPO_CHECKOUT_MODE=isolated` for Linux and Windows Codex tasks. Linux keeps the isolated checkout it already had; Windows Codex now uses the same layout to cover its native sandbox, where a linked worktree's external gitdir stays read-only and `git add` / `git commit` fail from inside the checkout (multica-ai/multica#6449). That failure only bites a Windows user who opted into `windows.sandbox` — `server/internal/daemon/execenv/codex_sandbox.go` defaults both Linux and Windows Codex to `danger-full-access` — but the checkout layout is chosen per platform, not per sandbox policy, so it does not depend on a task's resolved policy. `server/internal/daemon/repocache/cache.go` implements the mode as a local clone with task-local Git metadata and the real repository as `origin`; on Windows it clones with `--no-hardlinks` so the checkout's objects are private copies rather than NTFS links that share one file and security descriptor with the cache. Other runtimes keep the linked-worktree path.
-- When the bare cache is a partial clone, that isolated checkout must have `remote.origin.promisor` / `partialclonefilter` restored before its first `checkout`: `git clone --local` neither inherits them nor errors on the missing objects it leaves behind, so the checkout would otherwise succeed with an empty working tree. The linked-worktree path shares the cache's own config and needs no such repair.
-- `server/cmd/server/router.go` registers daemon APIs under `/api/daemon`, including workspace repos and task claim.
-- `server/internal/daemon/daemon.go` claims tasks, prepares workdirs, launches provider CLIs, and reports completion. It validates the task-scoped `mat_` credential, exports `MULTICA_TASK_CONFIG_ROOT`, and keeps that daemon-owned variable ahead of custom environment assembly so agents cannot override it.
-- `server/internal/daemon/execenv/execenv.go` creates and restores the private per-task `multica-config` directory with mode `0700`; it does not copy the daemon Owner's Multica profile into the directory.
-- `server/internal/cli/config.go` resolves Multica CLI profiles below `MULTICA_TASK_CONFIG_ROOT` when present while leaving ordinary `HOME`-based resolution unchanged outside tasks.
-- `server/cmd/multica/cmd_agent.go`, `cmd_config.go`, `cmd_auth.go`, `cmd_login.go`, `cmd_setup.go`, `cmd_workspace.go`, `cmd_runtime_profile.go`, and `cmd_daemon.go` enforce the task boundary: API calls require task authentication, task-local config commands fail closed without their root, auth status hides credential material, and human/local profile or daemon commands reject strong managed-task identity (`MULTICA_AGENT_ID` / `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, or the workdir marker). `MULTICA_DAEMON_PORT` remains a weak fail-closed signal for general API/profile resolution but is not sufficient by itself to reject human/local commands, because older host/container setups may leave it in the startup environment; guarded login paths explicitly resolve and update the human profile.
-- `cmd_daemon.go` scopes the two read-only diagnostics instead of rejecting them: with strong task identity, `daemonStatusHealthPort` takes the injected `MULTICA_DAEMON_PORT` (never the `--profile` hash, which would report an unrelated daemon); when that port is the only signal in a host environment, it uses the selected profile's derived port. `resolveDiskUsageRoot` takes `daemon.TaskWorkspacesRootEnv` (never the `$HOME`-derived default), `checkTaskDiskUsageScope` rejects the flags that widen the scan past this daemon, and the STATUS column plus the other-roots hint are skipped because both reach for Owner profile state.
-- `server/internal/daemon/execenv/runtime_config.go` injects task/project/repo context into agent workdirs.
diff --git a/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md b/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md
deleted file mode 100644
index f95351e508..0000000000
--- a/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md
+++ /dev/null
@@ -1,172 +0,0 @@
-# Skill-importing source map
-
-Evidence layer for `multica-skill-importing`. Every behavioral claim in `SKILL.md`
-maps to a real code path below with `file:line`. Paths are relative to the repo
-root (`multica/`).
-
-Re-derive before trusting: line numbers drift. To re-verify a single anchor,
-`grep` the symbol and read its surroundings, e.g.:
-
-```bash
-grep -n "func (h \*Handler) ImportSkill" server/internal/handler/skill.go
-grep -n "func runSkillImport" server/cmd/multica/cmd_skill.go
-grep -n "func IsReservedContentPath" server/internal/skill/reserved.go
-```
-
-## Import endpoint and route
-
-| Behavior | File:line |
-|---|---|
-| `ImportSkill` handler (`POST /api/skills/import`) | `server/internal/handler/skill.go:1882` |
-| Decodes `ImportSkillRequest` (`{ "url": ..., "on_conflict": ... }`) | `server/internal/handler/skill.go:1895-1899`, struct at `:553` |
-| Validates `on_conflict` (`fail`, `overwrite`, `rename`, `skip`) | `server/internal/handler/skill.go:1900-1908`, helper `validImportOnConflict` at `:566` |
-| Detects source family + normalizes URL | `server/internal/handler/skill.go:1910` (calls `detectImportSource`) |
-| Persists provenance into `config.origin` | `server/internal/handler/skill.go:1944-1948` — set only when `imported.origin != nil`; otherwise `config` stays `{}` and `origin` is absent |
-| Structured conflict dispatcher | `server/internal/handler/skill.go:1813-1878` |
-| Builds skill + files via `createSkillWithFiles` (def `server/internal/handler/skill_create.go:77`, tx body `:29`) | wrapped by `createImportedSkillWithName` at `server/internal/handler/skill.go:1774` |
-| Structured success: `201 Created` with `{status:"created", skill}` when `on_conflict` was sent | `server/internal/handler/skill.go:1985-1988` |
-| Legacy success: `201 Created` with bare `SkillWithFilesResponse` when `on_conflict` was omitted | `server/internal/handler/skill.go:1990` |
-| Route registration `r.Post("/import", h.ImportSkill)` | `server/cmd/server/router.go:874` |
-
-Note: `ImportSkill` now branches on content type. A multipart body routes to the
-archive path (below); a JSON body keeps the URL flow. Both converge on the shared
-`finishSkillImport` tail. Line numbers in this table predate that split — re-grep
-`func (h *Handler) ImportSkill` / `finishSkillImport` to re-derive.
-
-## Local archive import (`.skill` / `.zip`)
-
-| Behavior | File:line |
-|---|---|
-| `ImportSkill` branches to the archive path on multipart bodies | `server/internal/handler/skill.go:1924` (`if isMultipartForm(r)`) |
-| Shared create + conflict tail `finishSkillImport` (URL and archive) | `server/internal/handler/skill.go:1974` |
-| `isMultipartForm` content-type check | `server/internal/handler/skill_import_archive.go:26` |
-| `importSkillFromArchive` (multipart parse + `MaxBytesReader` + `on_conflict` + `file`) | `server/internal/handler/skill_import_archive.go:36` |
-| Upload cap `maxImportArchiveUploadSize` (16 MiB compressed) | `server/internal/handler/skill_import_archive.go:22` |
-| `parseSkillArchive` (zip decode, shallowest-`SKILL.md` root, frontmatter name, zip-slip + reserved + ignore filters) | `server/internal/handler/skill_import_archive.go:95` |
-| Reuses per-file / per-bundle / count caps via `importedSkill.addFile` | `server/internal/handler/skill.go:618` (`maxImportFileSize`/`maxImportTotalSize`/`maxImportFileCount` at `:579-583`) |
-| Name fallback (wrapper dir, then filename) | `server/internal/handler/skill_import_archive.go:201` |
-| Ignore filter (dotfiles, `__MACOSX`, license) | `server/internal/handler/skill_import_archive.go:218` |
-| Per-entry size-capped read | `server/internal/handler/skill_import_archive.go:234` |
-| Tests (parser units + handler multipart create/skip/reject) | `server/internal/handler/skill_import_archive_test.go` |
-
-## CLI: `multica skill import --url` / `--file`
-
-| Behavior | File:line |
-|---|---|
-| `skill import` command def | `server/cmd/multica/cmd_skill.go:59-63` |
-| `--url` flag | `server/cmd/multica/cmd_skill.go:143` |
-| `--file` flag (local `.skill` / `.zip`; mutually exclusive with `--url`) | `server/cmd/multica/cmd_skill.go:144` |
-| `--on-conflict` flag (default `fail`) | `server/cmd/multica/cmd_skill.go:145` |
-| `--output` flag (default `json`) | `server/cmd/multica/cmd_skill.go:146` |
-| `runSkillImport` | `server/cmd/multica/cmd_skill.go:412` |
-| Requires exactly one of `--url` / `--file` | `server/cmd/multica/cmd_skill.go:420-427` |
-| `--file` reads the archive and posts multipart via `ImportSkillFile` | `server/cmd/multica/cmd_skill.go:436-447`, client method `server/internal/cli/client.go:535` |
-| `POST /api/skills/import` (URL, JSON body) | `server/cmd/multica/cmd_skill.go:455` |
-| Structured HTTP error body handling | `server/cmd/multica/cmd_skill.go:437-440`, `handleSkillImportError` at `:454` |
-| Prints structured result (`json` or table) | `server/cmd/multica/cmd_skill.go:443`, helper at `:497` |
-
-## Same-name conflict handling
-
-| Behavior | File:line |
-|---|---|
-| `SkillImportResult` (`status`, `reason`, `skill`, `existing_skill`) | `server/internal/handler/skill.go:104-109` |
-| `ExistingSkillIdentity` (`id`, `name`, `created_by`, `can_overwrite`) | `server/internal/handler/skill.go:112-117` |
-| Pre-create lookup for structured conflict flow | `server/internal/handler/skill.go:1951-1962` |
-| Race-safe unique-violation fallback into structured conflict flow | `server/internal/handler/skill.go:1966-1971` |
-| Default `fail`: `status:"conflict"` and HTTP 409 | `server/internal/handler/skill.go:1872-1877` |
-| `overwrite`: creator-only update, preserves skill identity/bindings via `overwriteSkillWithFiles` | `server/internal/handler/skill.go:1823-1852`, tx helper at `server/internal/handler/skill_create.go:133` |
-| `rename`: creates suffixed name with bounded attempts | `server/internal/handler/skill.go:1854-1870`, helper at `:1786` |
-| `skip`: returns `status:"skipped"` and leaves existing skill untouched | `server/internal/handler/skill.go:1816-1821` |
-| Legacy duplicate branch when `on_conflict` was omitted | `server/internal/handler/skill.go:1973-1978` |
-| Legacy duplicate response `{error, existing_skill}` | `server/internal/handler/skill.go:118-123` |
-| CLI normalizes legacy `{existing_skill}` body into `status:"conflict"` | `server/cmd/multica/cmd_skill.go:454-482`, helper at `:484` |
-
-## Response shape: `SkillWithFilesResponse`
-
-| Behavior | File:line |
-|---|---|
-| `SkillWithFilesResponse` = embedded `SkillResponse` + `Files []SkillFileResponse` | `server/internal/handler/skill.go:99-102` |
-| `SkillResponse` fields (`id, workspace_id, name, description, content, config, created_by, created_at, updated_at`) | `server/internal/handler/skill.go:41-51` |
-| `SkillFileResponse` fields | `server/internal/handler/skill.go:80-87` |
-| `createSkillWithFilesInTx` returns `SkillWithFilesResponse{SkillResponse, Files}` | `server/internal/handler/skill_create.go:66-69` |
-| `config.origin` set on import | `server/internal/handler/skill.go:1947` |
-
-For current CLI imports, `SkillWithFilesResponse` appears under
-`SkillImportResult.skill` when status is `created` or `updated`. Legacy clients
-that omit `on_conflict` still receive a bare `SkillWithFilesResponse`.
-
-## URL source families (`detectImportSource`)
-
-| Behavior | File:line |
-|---|---|
-| `detectImportSource` | `server/internal/handler/skill.go:773-804` |
-| `skills.sh` / `www.skills.sh` | `server/internal/handler/skill.go:791-792` |
-| `clawhub.ai` / `www.clawhub.ai` | `server/internal/handler/skill.go:793-794` |
-| `github.com` / `www.github.com` | `server/internal/handler/skill.go:795-796` |
-| Bare slug (no host) defaults to ClawHub | `server/internal/handler/skill.go:798-800` |
-| `parseGitHubURL` handles `/tree/{ref}/...` and `/blob/{ref}/.../SKILL.md` | `server/internal/handler/skill.go:1450-1503` (tree/blob check `:1463-1480`) |
-
-## Additive add vs replace-all set
-
-| Behavior | File:line |
-|---|---|
-| `AddAgentSkills` (additive: AddAgentSkill loop, no RemoveAll) | `server/internal/handler/skill.go:2161`; loop `:2192-2200` |
-| Route `POST /api/agents/{id}/skills/add` | `server/cmd/server/router.go:851` |
-| `SetAgentSkills` (replace-all: RemoveAllAgentSkills then re-add) | `server/internal/handler/skill.go:2106`; `RemoveAllAgentSkills` `:2138`; re-add `:2143-2151` |
-| Route `PUT /api/agents/{id}/skills` | `server/cmd/server/router.go:850` |
-| CLI `agent skills add` def ("without replacing existing assignments") | `server/cmd/multica/cmd_agent.go:125-130` |
-| `runAgentSkillsAdd` → `POST .../skills/add` | `server/cmd/multica/cmd_agent.go:797`; POST `:818` |
-| CLI `agent skills set` def ("replaces all current assignments") | `server/cmd/multica/cmd_agent.go:118-123` |
-| `runAgentSkillsSet` → `PUT .../skills` | `server/cmd/multica/cmd_agent.go:772`; PUT `:790` |
-| CLI `agent skills list` | `server/cmd/multica/cmd_agent.go:740`; GET `:750` |
-
-## Updating an imported skill (`POST /api/skills/{id}/refresh`)
-
-| Behavior | File:line |
-|---|---|
-| `RefreshSkill` handler | `server/internal/handler/skill_refresh.go:120` |
-| Route `r.Post("/refresh", h.RefreshSkill)` | `server/cmd/server/router.go:1594` |
-| Reads stored provenance `config.origin.{type,source_url}` | `parseSkillOrigin`, `server/internal/handler/skill_refresh.go:32` |
-| Refreshable origins are `github` / `skills_sh` / `clawhub` only | `refreshableOriginSource`, `server/internal/handler/skill_refresh.go:57` |
-| Re-runs the matching import fetcher from the stored `source_url` | `fetchImportedSkillFromOrigin`, `server/internal/handler/skill_refresh.go:75` |
-| Non-refreshable origin → 422 | `errSkillNotRefreshable`, `server/internal/handler/skill_refresh.go:22` |
-| Permission: creator or workspace owner/admin, checked before the fetch | `server/internal/handler/skill_refresh.go:120` (body) — broader than import-overwrite's creator-only rule |
-| Merges only `config.origin`, preserving other config keys | `mergeSkillConfigOrigin`, `server/internal/handler/skill_refresh.go:99` |
-| In-place overwrite preserving id/creator/bindings, adopting upstream rename | `overwriteSkillWithFiles` with `NewName` + `AllowOverwrite`, `server/internal/handler/skill_create.go:119-122`, tx helper `:133` |
-| Upstream rename colliding with another skill → 409 | `errSkillOverwriteNameConflict`, `server/internal/handler/skill_create.go:104` |
-| Fetch failures map like import (413/502/503/504) | `importFetchErrorResponse` (grep in `server/internal/handler/skill.go`) |
-| CLI `skill refresh <id>` def / runner | `server/cmd/multica/cmd_skill.go:66`, `runSkillRefresh` at `:425` |
-| Handler tests | `server/internal/handler/skill_refresh_test.go` |
-
-## Reserved primary-content filename (`SKILL.md`)
-
-| Behavior | File:line |
-|---|---|
-| `ContentFilename = "SKILL.md"` | `server/internal/skill/reserved.go:12` |
-| `IsReservedContentPath` (cleans path, case-insensitive compare) | `server/internal/skill/reserved.go:25-27` |
-| Import/create path: reserved supporting file is **silently skipped** (`continue`) | `server/internal/handler/skill_create.go:50-54` |
-| `UpdateSkill` (PUT `/api/skills/{id}`) replace-files path: also silently skips | `server/internal/handler/skill.go:490-494` |
-| `UpsertSkillFile` (PUT `/api/skills/{id}/files`): **rejects 400** "SKILL.md is reserved for the primary skill content" | `server/internal/handler/skill.go:2014`; reserved check `:2034-2036` |
-
-Reason `SKILL.md` is reserved: the daemon writes the skill's `Content` to that path
-itself when preparing the execution environment, so a supporting file may not also
-claim it (`server/internal/skill/reserved.go:8-24`).
-
-Behavior is path-shape-dependent. On **import or create** a manifest's `SKILL.md`
-supporting file is dropped (it will not appear in the returned `files`), so the
-import still succeeds — it does not 400. The hard 400 rejection fires only on the
-dedicated single-file endpoint `PUT /api/skills/{id}/files`.
-
-## Reading a skill back (`?include=`)
-
-| Behavior | File:line |
-|---|---|
-| `resolveSkillInclude` parses `?include=content\|metadata`, 400 on anything else | `server/internal/handler/skill.go`, grep `func resolveSkillInclude` |
-| Both endpoints default to `content` when `?include=` is absent — installed desktop builds and older CLIs cannot be asked to send it | `resolveSkillInclude`, `server/internal/handler/skill.go` |
-| Compatibility test for that default | `TestSkillEndpointsWithoutIncludeStillReturnContent`, `server/internal/handler/skill_metadata_test.go` |
-| Metadata shapes (`size`, `content_hash`, `content_size`) | `SkillFileMetadataResponse` / `SkillWithFileMetadataResponse` in `server/internal/handler/skill.go` |
-| Size + hash of file bodies computed in Postgres, so those bodies never leave it | `ListSkillFileMetadata`, `server/pkg/db/queries/skill.sql` |
-| Hash is over raw UTF-8 (`convert_to`, never `content::bytea` — the cast reads backslash escapes and rejects a bare `\`) | `server/pkg/db/queries/skill.sql`, test `TestSkillFileHashCoversRawUTF8Bytes` |
-| CLI sends `include=metadata` unless `--with-content` | `skillIncludeQuery`, `server/cmd/multica/cmd_skill.go` |
-| Handler tests | `server/internal/handler/skill_metadata_test.go` |
-| CLI tests | `server/cmd/multica/cmd_skill_test.go`, grep `AsksForMetadataUnlessContentRequested` |
diff --git a/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.md b/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.md
deleted file mode 100644
index 03e23e536c..0000000000
--- a/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.md
+++ /dev/null
@@ -1,346 +0,0 @@
-# Squad Source Map
-
-This file records source evidence for `multica-squads/SKILL.md`.
-
-Use this when the task requires exact source paths, edge-case behavior, tests, or contract verification.
-
-## Object Model
-
-### DB shape
-
-Source:
-
-```text
-server/migrations/084_squad.up.sql # base table: name, description, leader_id, creator_id
-server/migrations/085_squad_archive.up.sql # archived_at, archived_by columns
-server/migrations/088_squad_instructions.up.sql # instructions column
-server/pkg/db/queries/squad.sql
-packages/core/types/squad.ts
-```
-
-Key facts:
-
-- `squad` stores `name`, `description`, `leader_id`, `creator_id` (084), archive
- metadata `archived_at`/`archived_by` (085), and `instructions` (088).
-- `squad_member` stores `member_type`, `member_id`, and `role`.
-- `member_type` is constrained to `agent` or `member`.
-- issue `assignee_type` supports `squad`.
-
-## CLI
-
-Source:
-
-```text
-server/cmd/multica/cmd_squad.go
-```
-
-Commands:
-
-```bash
-multica squad list
-multica squad get <squad-id>
-multica squad create
-multica squad update <squad-id>
-multica squad delete <squad-id>
-multica squad activity <issue-id> <outcome>
-
-multica squad member list <squad-id>
-multica squad member add <squad-id>
-multica squad member remove <squad-id>
-multica squad member set-role <squad-id>
-```
-
-Use `--help` for exact flags before writes.
-
-## Create / Update
-
-Source:
-
-```text
-server/internal/handler/squad.go # CreateSquad ~200-272, UpdateSquad ~287-364
-server/pkg/db/queries/agent.sql # GetAgentInWorkspace ~15-17
-server/pkg/db/generated/agent.sql.go # getAgentInWorkspace ~1261
-```
-
-Contracts:
-
-- create requires `leader_id` (squad.go:215-218);
-- leader must be a workspace agent — both create (squad.go:230-237) and update
- (squad.go:333-338) validate via `GetAgentInWorkspace`;
-- archived leader is NOT rejected at create/update: `GetAgentInWorkspace` is
- `WHERE id = $1 AND workspace_id = $2` (agent.sql:15-17) with no archived
- filter, so an archived agent can be set as leader here. Archived-leader fails
- closed later, at routing/dispatch — see the readiness gate (squad.go:945,
- isSquadLeaderReady → service.AgentReadiness at squad.go:1017), assignment
- validation (issue.go:2625-2627), and autopilot admission (autopilot.go:885-891);
-- leader is auto-added as member with role `leader` (squad.go:258-263);
-- updating `leader_id` auto-adds new leader as member if missing (squad.go:340-347).
-
-## Leader Briefing
-
-Source:
-
-```text
-server/internal/handler/squad_briefing.go # buildSquadLeaderBriefing ~104, buildSquadRoster ~121, renderMemberRow ~169, agentSkillsRosterSegment, formatRosterRow
-server/internal/handler/daemon.go # briefing injection ~1187, ~1530
-```
-
-Contracts:
-
-- squad leader tasks append briefing to leader agent instructions
- (daemon.go:1187, 1530);
-- briefing includes operating protocol, roster, and optional instructions
- (squad_briefing.go:104-117);
-- `buildSquadLeaderBriefing` takes an `ownsIssueStatus` argument selecting
- responsibility 6 via `squadOperatingProtocolFor`: the status grant
- (`squadParentStatusOwned`) only when `issue.assignee_type == "squad"` and
- `issue.assignee_id == squad.id`, otherwise an explicit prohibition
- (`squadParentStatusNotOwned`). Quick-create passes `false` — no issue exists
- yet. Injection is broader than authority on purpose: it is keyed off
- `is_leader_task`, which also fires for `@squad` mentions on issues owned by
- someone else (MUL-3724);
-- when the claim's defensive gate withholds the briefing (NULL `squad_id`,
- squad hard-deleted, leader swapped after enqueue), the handler also clears
- `is_leader_task` on the claim response, so the wire flag means "briefing
- injected" and the run degrades to an ordinary agent turn. The daemon derives
- the leader role from that flag (plus `squad_id` for quick-create), never from
- the briefing text (MUL-5811);
-- every claim response carries `leader_role_resolved: true`, the capability
- that tells the daemon those fields are authoritative. Servers predating it
- omit it, and a daemon seeing it absent falls back to the legacy
- "`## Squad Operating Protocol` appears in instructions" inference. That is
- the only correct read of either older shape: before #4951 no `is_leader_task`
- was sent at all, and after it the flag was sent without any guarantee that a
- briefing came with it. The field is claim-only and never rendered into a
- prompt;
-- `instructions` section appears only when non-empty (squad_briefing.go:110-112);
-- archived agent members are skipped from roster (squad_briefing.go:178-179);
-- agent member roster rows list assigned workspace skills via
- `loadSquadMemberSkillNames` (ListAgentSkillNamesByAgentIDs) and
- `agentSkillsRosterSegment` — "skills: a, b" or
- "no skills assigned"; builtin multica-* skills are excluded and human
- members carry no skills segment (squad_briefing.go renderMemberRow);
-- no traced behavior injects `instructions` into every squad member.
-
-## Leader Evaluation Recording
-
-Source:
-
-```text
-server/internal/handler/squad.go # RecordSquadLeaderEvaluation ~949
-server/cmd/multica/cmd_squad.go # runSquadActivity ~459
-server/internal/service/squad_no_action.go # HasSquadLeaderNoActionEvaluationForTask
-server/internal/handler/comment.go # no_action comment rejection ~1851
-```
-
-Contracts:
-
-- authority is the TASK row from `X-Task-ID`, not the issue's assignee:
- `task.issue_id == issue.id`, `task.is_leader_task`, `task.squad_id` valid.
- The squad is loaded from `task.squad_id`; the target issue may be assigned to
- anyone (MUL-6622 / GH #7487). The pre-fix `issue.assignee_type == "squad"`
- gate diverged from the claim-side `is_leader_task` gate and made the call
- unsatisfiable on `@squad`-on-agent-issue and leader-task-on-child paths;
-- the task is loaded with `GetAgentTaskInWorkspace`, not `GetAgentTask`: the
- latter is a global lookup by id, and the rejection path quotes the task's
- issue id. Check order is load-bearing — tenant scope, then "caller owns this
- task", and only then any message naming a task-derived id;
-- two authorization gates: `task.agent_id == caller`, then
- `squad.leader_id == caller`. The second is required because
- `is_leader_task` on the row is enqueue-time INTENT: when the leader was
- swapped before the claim, `handler/daemon.go` clears `resp.IsLeaderTask` and
- runs the task as an ordinary agent turn while the row keeps
- `is_leader_task = true`. Without the live check, such a downgraded run could
- write a leader verdict and suppress its own comment. Removing this gate
- requires persisting the role the claim actually delivered;
-- `activity_log.actor_id` is `task.agent_id`, not `squad.leader_id`: the
- `no_action` comment suppression lookup matches on `task.agent_id`, so the
- live leader id there would silently break suppression;
-- a leader agent running a NON-leader task is rejected — it is not running as
- the leader, and the runtime only mandates the call for `is_leader_task`;
-- the `no_action` comment prohibition is conditional on this write succeeding
- (comment.go:1851 checks the activity exists), so the injected instructions
- tell leaders to fall back to a comment when the call errors — capped at one
- comment, and only when the turn has not already commented. That rule is
- stated in exactly one place: responsibility 5 of the Squad Operating Protocol
- (`squadOperatingProtocolFor`, `server/internal/handler/squad_briefing.go`),
- which the server appends to a leader's Instructions. The runtime brief
- (workflow step 4 and `## Output` in
- `server/internal/daemon/execenv/runtime_config_sections.go`) and the per-turn
- reply imperative (`BuildCommentReplyInstructions` /
- `BuildMultiThreadCommentReplyInstructions`,
- `server/internal/daemon/execenv/reply_instructions.go`) carry only the
- `no_action` EXCEPTION to their own imperative and point back at the protocol.
- They used to restate the rule; the four copies had already drifted on the
- failure fallback when they were collapsed (MUL-6984).
-
-## Issue Assignment
-
-Source:
-
-```text
-server/internal/handler/issue.go # assignee validation ~2614-2632
-server/internal/handler/squad.go # shouldEnqueueSquadLeaderOnAssign ~990, enqueueSquadLeaderTask ~1027
-server/internal/service/task.go
-```
-
-Contracts:
-
-- `assignee_type="squad"` routes to `squad.leader_id` (squad.go:1028-1050);
-- backlog assignment does not immediately enqueue (squad.go:991-993);
-- moving out of backlog can enqueue leader (squad.go:990-994 → isSquadLeaderReady);
-- assignee change cancels existing issue tasks first;
-- private leader access is checked at assign-time (issue.go:2629-2632) and at
- enqueue-time via `canEnqueueSquadLeader` (squad.go:1037);
-- archived squad / archived leader rejected at assign-time (issue.go:2622-2627);
-- pending task dedup is applied (squad.go:1042-1048);
-- parent status is agent-managed: since MUL-6417 the brief's status rule is a
- fact judgment written when the work changes it (`writeWorkflowIssue`), and the
- leader variant adds one bullet — dispatching members is not delivery, so a dispatch
- turn leaves the parent `in_progress` and `in_review` waits for the re-trigger
- that confirms the overall goal is met. Squad Operating Protocol
- (`squad_briefing.go`) still states the ongoing `in_progress` → later
- `in_review` responsibility for owning leaders. `StartTask` / `CompleteTask`
- do not write issue status. There is no assignee gate anymore: a guest leader
- writes nothing not because it lacks a grant but because a turn that did not
- move the issue's state has nothing to record.
-- status names are category rules: custom statuses inherit their category's
- behavior in full (MUL-6243, `server/internal/issuestatus/issuestatus.go`
- `Effective`/`Resolve`); the brief lists the workspace catalog when any custom
- statuses exist (MUL-6460, `writeIssueStatusCommand` in
- `server/internal/daemon/execenv/runtime_config_sections.go`).
-
-## Comment / Mention
-
-Source:
-
-```text
-server/internal/handler/comment.go # comment triggers ~1057-1199, squad mention branch ~1352
-server/internal/handler/squad.go # enqueueSquadLeaderTask ~986 (assign/backlog paths), lastTaskWasLeader ~915
-server/internal/service/task.go # EnqueueTaskForSquadLeader
-```
-
-Contracts:
-
-- commenting on a squad-assigned issue can wake the leader — the comment path
- computes triggers via `computeCommentAgentTriggers` (comment.go:1124), whose
- assigned-squad branch is `computeAssignedSquadLeaderCommentTrigger`
- (comment.go:1162-1199); the same computation backs the trigger-preview
- endpoint;
-- explicit `mention://squad/<id>` resolves squad and adds the leader trigger
- (comment.go:1352-1391);
-- squad mention does not fan out to members — enqueue targets `squad.LeaderID`
- only (comment.go:1104-1112, and squad.go:1007 on the assign/backlog paths);
-- leader task uses `is_leader_task=true` (via `EnqueueTaskForSquadLeader`);
-- leader self-trigger loops are guarded — same-leader / last-task-was-leader
- guards (comment.go:1173-1176, lastTaskWasLeader at squad.go:915) and member
- explicit-mention skip (comment.go:1177-1179).
-
-## Autopilot
-
-Source:
-
-```text
-server/internal/service/autopilot.go # resolveAutopilotLeader ~617-655, dispatch ~88-111
-server/internal/handler/autopilot.go # save-time validateAutopilotAssignee ~845-893
-```
-
-Contracts:
-
-- squad autopilot resolves executable agent from `squad.leader_id` —
- `resolveAutopilotLeader` squad branch (autopilot.go:639-651);
-- readiness/admission checks target the leader: save-time validation rejects an
- archived squad/leader (handler/autopilot.go:881-891), and dispatch re-runs
- `resolveAutopilotLeader` + `AgentReadiness`;
-- archived squad fails closed / skips dispatch — `errSquadArchived`
- (autopilot.go:644-645);
-- `create_issue` keeps the issue assigned to the squad (autopilot.go:88-97);
-- `run_only` creates task directly for leader (autopilot.go:99-106, dispatch via
- `resolveAutopilotLeader` at autopilot.go:284).
-
-## Child-done Parent Trigger
-
-Source:
-
-```text
-server/internal/handler/issue_child_done.go # dispatchParentAssigneeTrigger ~246, triggerChildDoneSquad ~304
-```
-
-Contracts:
-
-- when a child issue closes a stage barrier and the parent is assigned to a
- squad, the parent squad leader is triggered (triggerChildDoneSquad in
- issue_child_done.go);
-- routing is leader-only — one `EnqueueTaskForSquadLeader` on the leader, no
- member fan-out (triggerChildDoneSquad / dispatchParentAssigneeTrigger);
-- no self-trigger guard: a same-squad or shared-leader child still wakes the
- parent squad leader — the wake is a serial handoff onto the PARENT and is the
- only carrier of the stage-barrier "advance / wrap up" instruction (MUL-3969,
- mirrors the agent path from MUL-2808). Re-triggering is bounded only by
- `HasPendingTaskForIssueAndAgent` (idempotent per parent issue + agent).
-- no leader-invocation gate: child-done does NOT re-check whether the child's
- completer can invoke the leader. The parent was already permission-checked at
- squad-assign time (`validateAssigneePair`), so waking its own leader is a
- coordination handoff, not a fresh invocation. Re-checking it here failed
- closed for the DEFAULT private leader (the child's completer is an
- agent/system actor with no resolvable human originator), stranding every
- process-squad pipeline after stage 1 while direct-to-leader-agent parents
- advanced fine (MUL-4063 / GH #4928). Agent and squad child-done now share one
- ungated path; any future invocation gate must be added to BOTH together.
-- parent status is not auto-advanced by the barrier: the system comment asks the
- leader to continue or — when the overall goal is met — run
- `multica issue status <parent-id> in_review`. The Squad Operating Protocol's
- standing "Own the parent issue status" responsibility (present exactly when
- the issue is assigned to this squad) states the same expectation; the system
- comment marks the wrap-up moment. Since MUL-6417 the write itself needs no
- grant — the brief's fact judgment covers it — but `done` remains
- human / integration owned.
-
-## Private Leader Access
-
-Source:
-
-```text
-server/internal/handler/agent_access.go # canInvokeAgent ~48-108, canEnqueueSquadLeader ~261-267
-server/internal/handler/squad.go # enqueueSquadLeaderTask gate ~955-974
-```
-
-Contracts (invocation gate, MUL-3963 — this is the *trigger* gate, distinct from
-the view gate `canAccessPrivateAgent`):
-
-- `canEnqueueSquadLeader` loads the leader and delegates to `canInvokeAgent`
- (agent_access.go:261-267);
-- `canInvokeAgent` judges by the *effective invoking user*: a member actor is
- itself; an agent/system actor is the top-of-chain human originator
- (`originatorUserID`), which is `""` when none resolved (agent_access.go:48-54);
-- the agent owner may always invoke their own agent (agent_access.go:57-59);
-- `permission_mode != "public_to"` (i.e. private) is deny-by-default — no admin
- bypass, no A2A bypass; only the owner branch passes (agent_access.go:61-65);
-- `public_to` consults the invocation-target allow-list: a `workspace` target
- admits any workspace member AND workspace-internal agent/system principals even
- with no resolved human (`workspaceBroad`); `member` targets require the
- resolved human to match; `team` targets are inert in V1 (agent_access.go:82-106);
-- wired into `enqueueSquadLeaderTask` (squad.go:955-974): the squad
- assign/promote path denies the enqueue when the actor cannot invoke the leader
- (member authors are their own originator; agent-authored triggers pass `""`).
-- NOTE: the child-done wake does NOT use this gate anymore — see "Child-done
- Parent Trigger" above (MUL-4063).
-
-## Tests
-
-Relevant test groups:
-
-```text
-server/internal/handler/squad_assign_trigger_test.go
-server/internal/handler/squad_comment_trigger_test.go
-server/internal/handler/squad_briefing_test.go
-server/internal/handler/squad_private_leader_test.go
-server/internal/handler/autopilot_private_leader_test.go
-server/internal/handler/squad_no_action_test.go
-```
-
-Verification command:
-
-```bash
-go test ./internal/handler -run 'Test.*Squad|Test.*squad|Test.*Autopilot.*Squad|Test.*ChildDone.*Squad'
-```
diff --git a/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md b/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md
deleted file mode 100644
index 45ca0e9fc6..0000000000
--- a/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md
+++ /dev/null
@@ -1,231 +0,0 @@
-# working-on-issues source map
-
-Evidence layer for `SKILL.md`. Every contract the skill states is traced to a
-current `file:line` here. Lines were re-derived against `feat/builtin-skills`
-after the latest `main` merge; the prior skill cited pre-merge lines that have
-since moved (see the "drifted" column). Re-confirm with the verification command
-at the bottom before relying on an exact line.
-
-## `multica issue pull-requests` — read PR links from Multica
-
-| Behavior | File:line | Drifted from |
-|---|---|---|
-| CLI command `pull-requests <id>` (alias `prs`) | `server/cmd/multica/cmd_issue.go:105` | `:104` |
-| `runIssuePullRequests` handler | `server/cmd/multica/cmd_issue.go:507` | new citation |
-| Calls `GET /api/issues/<id>/pull-requests` | `server/cmd/multica/cmd_issue.go:522` | `:522` (unchanged) |
-| API route registration | `server/cmd/server/router.go:480` | `:480` (unchanged) |
-| Handler `ListPullRequestsForIssue` → `Queries.ListPullRequestsByIssue` | `server/internal/handler/github.go:687,692` | `:466` |
-| Row → response mapper `issuePullRequestRowToResponse` | `server/internal/handler/github.go:205` | `:149` |
-
-The CLI resolves the issue ref, GETs the endpoint, and (for `--output json`)
-prints the raw `{"pull_requests": [...]}` body. Only `--output` is accepted; the
-default `table` shows `NUMBER STATE TITLE URL`.
-
-## PR response shape
-
-`GitHubPullRequestResponse` struct: `server/internal/handler/github.go:58`. JSON
-fields the agent can read off each element of `pull_requests`:
-
-- `provider` (`json:"provider"`, line 63)
-- `number` (`json:"number"`, line 67)
-- `html_url` (`json:"html_url"`, line 70)
-- `title` (`json:"title"`, line 68)
-- `state` (`json:"state"`, line 69) — the folded lifecycle enum (see below)
-- `merged_at` (`json:"merged_at"`, line 74), `closed_at` (line 75)
-- `mergeable_state` (`json:"mergeable_state"`, line 80) — mirrors GitHub; UI only
- surfaces `clean`/`dirty`, other values round-trip as unknown
-- `snapshot_available` (`json:"snapshot_available"`, line 100) — for GitHub,
- true only when the App snapshot feature is enabled and the snapshot head
- matches the current PR head (`currentGitHubSnapshotAvailable`, lines 258-265)
-- `mergeable` / `merge_state_status` (lines 90, 94) — conflict-only verdict vs
- the complete merge gate; "ready" requires `merge_state_status == "clean"`
-- `checks_rollup` (`json:"checks_rollup"`, line 105) and run-level
- `checks_total` / `checks_passed` / `checks_failed` / `checks_running`
- (lines 111-114), plus `failed_check_names` (line 118)
-- `checks_conclusion` (`json:"checks_conclusion"`, line 108) — coarse
- `"passed"`/`"failed"`/`"pending"` or `null`; GitHub derives it only from an
- available current-head snapshot (mapper lines 242-254), while self-hosted VCS
- providers use `aggregateChecksConclusion` (line 275)
-
-There is **no** standalone `draft` or `merged` boolean in the response. The
-PR lifecycle is encoded in the single `state` string by `derivePRState`
-(`server/internal/handler/github.go:1317`):
-
-```
-merged → if PullRequest.Merged
-closed → else if PullRequest.State == "closed"
-draft → else if PullRequest.Draft
-open → otherwise
-```
-
-`derivePRState` is called when the webhook upserts the row
-(`server/internal/handler/github.go:1115`), so `state` is what the list endpoint
-returns. "Is it merged?" = `state == "merged"` (or `merged_at != null`); "is it a
-draft?" = `state == "draft"`. Combine with `checks_conclusion` for CI status.
-
-## Two distinct webhook paths: link vs close-intent
-
-Both run inside the `pull_request` webhook handler, gated by the workspace
-auto-link flag (`workspaceAutoLinkPRsEnabled`, `github.go:1074`).
-
-### Path 1 — link (title OR body OR branch)
-
-- `extractIdentifiers` regex helper: `server/internal/handler/github.go:1028`
-- driving regex `identifierRe` (`\b([a-z][a-z0-9]{1,9})-(\d+)\b`, case-insensitive):
- `server/internal/handler/github.go:490`
-- call site: `server/internal/handler/github.go:727` —
- `extractIdentifiers(p.PullRequest.Title, p.PullRequest.Body, p.PullRequest.Head.Ref)`
-
-Every `PREFIX-NUMBER` mention in **title, body, or branch** resolves to an issue
-in the workspace and writes a link row (`LinkIssueToPullRequest`, ~`github.go:762`).
-This is what `multica issue pull-requests` later reads back.
-
-**Reference-only flag (MUL-3739).** The link row carries a `reference_only`
-boolean (`migrations/127_issue_pull_request_reference_only.up.sql`). The handler
-computes a `qualifyingIdents` set = identifiers in **title or branch** (any
-`extractIdentifiers` match) ∪ **body closing keywords** (`closingIdents`). A
-linked identifier NOT in that set was matched only by a bare body mention, so its
-row is written with `reference_only = true`. Both `ListPullRequestsByIssue` and
-`GetIssuePullRequestCloseAggregate` filter `AND NOT reference_only`, so
-reference-only links are hidden from the CLI / UI PR list **and** excluded from
-the auto-advance gate (an open body-only mention must not silently block the
-issue from reaching `done` while invisible in the list). The row still exists for
-edit-time close-intent tracking. `reference_only` follows the same
-`preserve_close_intent` terminal gate as `close_intent`.
-
-Drifted from the prior skill's `github.go:727` citation, which pointed at the old
-call-site location for the link logic.
-
-### Path 2 — close intent (title OR body only, keyword-adjacent)
-
-- `extractClosingIdentifiers` regex helper: `server/internal/handler/github.go:1051`
-- driving regex `closingIdentifierRe`
- (`\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)[:\s]+([a-z][a-z0-9]{1,9})-(\d+)\b`):
- `server/internal/handler/github.go:501`
-- call site: `server/internal/handler/github.go:736` —
- `extractClosingIdentifiers(p.PullRequest.Title, p.PullRequest.Body)` (no branch arg)
-
-Only a `PREFIX-NUMBER` immediately after a closing keyword
-(`Closes`/`Fixes`/`Resolves`, optional `:` then whitespace) sets the link row's
-`close_intent` flag — the gate that auto-advances the issue to `done` on merge.
-`Fix MUL-1` closes; `Fix login MUL-1` does not (adjacency). Branch names are
-deliberately excluded (function doc, `github.go:1044-1050`): a branch like
-`mul-1/fix-login` links but must never declare close intent.
-
-Drifted from the prior skill's `github.go:736` citation.
-
-Net: a bare title prefix (`MUL-2759: ...`) or a branch ref links only (shown in
-the PR list); `Closes MUL-2759` links **and** records close intent; a bare body
-mention with no title/branch ref and no closing keyword links as `reference_only`
-and is hidden from the PR list.
-
-## Status side effects (enqueue contracts)
-
-| Behavior | File:line | Drifted from |
-|---|---|---|
-| Create-time: agent-assigned, non-backlog issue enqueues immediately | `server/internal/handler/issue.go:2263-2264` | new citation |
-| `shouldEnqueueAgentTask` returns false for `backlog` (parking lot) | `server/internal/handler/issue.go:2644-2648` | new citation |
-| Backlog → non-backlog (not done/cancelled) enqueues on update | `server/internal/handler/issue.go:2537-2540` | `:2523` |
-| Same contract in batch update | `server/internal/handler/issue.go:3021-3024` | new citation |
-| Child → `done` notifies + wakes the parent, gated by the stage barrier | `server/internal/handler/issue_child_done.go:66` (`notifyParentOfChildDone`; doc comment at `:15`; barrier gate at `:115`) | func def `:51` |
-| Status change (incl. → `cancelled`) does NOT cancel in-flight tasks; only issue deletion does (MUL-4465) | no-cancel note in `server/internal/handler/issue.go:2652-2658` (`UpdateIssue`) and `:3170-3171` (`BatchUpdateIssues`); deletion still cancels at `:2863` (`DeleteIssue`) / `:3239` (`BatchDeleteIssues`) via `CancelTasksForIssue` (`server/internal/service/task.go:1229`) | new citation |
-| `StartTask` / `CompleteTask` do not write issue status (agent CLI owns progress) | `server/internal/service/task.go` (`StartTask` / `CompleteTask` comments) | new citation |
-| Runtime brief: status written whenever the work changes it, mid-turn included — starting the issue's own ask → `in_progress` immediately (workflow step 3); delivery → `in_review`, continuing → `in_progress`, stuck → `blocked`; a turn producing none of the issue's own deliverable → no write at any point; the activity kind never decides (research/design/planning/review count as work when they are the ask); no assignee gate; squad leader dispatch is not delivery (MUL-6417) | `server/internal/daemon/execenv/runtime_config_sections.go` (`writeWorkflowIssue`) | new citation |
-| Failed task may roll `in_progress` → `todo` when no active task remains | `server/internal/service/task.go` (`HandleFailedTasks`) | new citation |
-| Custom statuses inherit their category's behavior in full; enqueue/park contracts resolve the effective category via `issuestatus.Effective` / `Resolve` (MUL-6243) | `server/internal/issuestatus/issuestatus.go` (`Effective`, `Resolve`) | new citation |
-| Runtime brief lists the workspace's active custom statuses grouped by category; catalog rides the claim payload (MUL-6460) | `server/internal/daemon/execenv/runtime_config_sections.go` (`writeIssueStatusCommand`); claim injection in `server/internal/handler/daemon.go` (`buildClaimedTaskResponse`, status catalog block) | new citation |
-| Literal-key exceptions to category rules: failed-task rollback writes the `todo` key; merged close-intent PR writes the `done` key | `server/internal/service/task.go` (`HandleFailedTasks`); `server/internal/handler/github.go` (merge close-intent path) | new citation |
-
-Creation with `--status todo` (or any non-backlog status) on an agent-assigned
-issue fires the agent immediately; `--status backlog` parks it with the assignee
-set but no trigger. Promoting `backlog → todo` later fires it then (update path,
-line 2537).
-
-Moving an issue to `cancelled` used to call `CancelTasksForIssue` and stop every
-active task on it (the old #940 behavior). MUL-4465 removed that from both
-`UpdateIssue` and `BatchUpdateIssues`: a status flip — `cancelled` included —
-never cancels tasks now. `CancelTasksForIssue` fires only from the issue-deletion
-paths (`DeleteIssue` / `BatchDeleteIssues`), where the owning issue row is going
-away, so no task is left orphaned.
-
-## Ownership-only assignment and duplicate-run awareness
-
-| Behavior | Source |
-|---|---|
-| `issue assign --no-start`, `issue update --no-start`, and `issue status --no-start` send `suppress_run=true` | `server/cmd/multica/cmd_issue.go` (`runIssueAssign`, `runIssueUpdate`, `runIssueStatus`) |
-| Update and batch-update apply ownership while skipping dispatch when `suppress_run` is true | `server/internal/handler/issue.go` (`UpdateIssue`, `BatchUpdateIssues`) |
-| Trusted direct self-assignment suppresses enqueue only when the target `(issue, agent)` already has a non-terminal task | `server/internal/service/issue_trigger.go` (`WillEnqueueRun`), `server/internal/handler/issue_trigger.go` (`shouldSuppressActiveSelfAssignment`) |
-| `issue runs --active` / `--siblings` send `active=true` / `scope=family` to the task-runs endpoint | `server/cmd/multica/cmd_issue.go` (`runIssueRuns`) |
-| `scope=family` roots at the issue's parent, or the issue itself when it has none, and returns in-flight runs on that root plus all of its children | `server/internal/handler/daemon.go` (`ListTasksByIssue`), `server/pkg/db/queries/agent.sql` (`ListActiveTasksByIssueFamily`) |
-| Invalid `active` / `scope` values are rejected rather than silently answering with the full history | `server/internal/handler/daemon.go` (`ListTasksByIssue`) |
-| The family cap fetches one row past `familyActiveRunCap` and reports truncation on `X-Active-Runs-Truncated`, which the CLI surfaces on stderr | `server/internal/handler/daemon.go` (`familyActiveRunCap`, `HeaderActiveRunsTruncated`), `server/cmd/multica/cmd_issue.go` (`runIssueRuns`) |
-| The active path skips usage hydration, which is keyed by issue and spans the full history | `server/internal/handler/daemon.go` (`ListTasksByIssue`), `server/pkg/db/queries/task_usage.sql` (`ListIssueTaskUsage`) |
-| The family read returns its own compact row rather than the execution-log record, and skips usage and attribution hydration | `server/internal/handler/daemon.go` (`ActiveRunSummary`), `server/pkg/db/queries/agent.sql` (`ListActiveTasksByIssueFamily`) |
-
-The self-assignment guard is intentionally pair-scoped. It does not treat
-"this agent is busy on some other issue" as a reason to suppress a fresh
-cross-issue handoff, because serial sub-issue promotion and triage batches rely
-on those assignments creating their normal queued runs.
-
-## Sub-issue stages (barrier wake)
-
-| Behavior | File:line |
-|---|---|
-| `issue.stage` column (nullable, `>= 1`) | `server/migrations/123_issue_stage.up.sql` |
-| Stage barrier: notify+wake fire only when the lowest unfinished stage is all-terminal; unstaged set = one implicit stage | `server/internal/handler/issue_child_done.go:231` (`stageBarrierClosed`) |
-| Per-stage summary + next stage for the wake comment | `server/internal/handler/issue_child_done.go:254` (`stageProgressSummary`) |
-| `--stage` on `issue create` / `issue update` | `server/cmd/multica/cmd_issue.go:328,350` |
-| `multica issue children <id>` (sub-issues grouped by stage) | `server/cmd/multica/cmd_issue.go:114,678`; stage `done` counting via `isTerminalChildIssue` (reads `status_category`, MUL-6243); route `GET /api/issues/{id}/children` → `ListChildIssues` |
-
-Advancement is agent-driven: the server only detects the closed barrier and
-wakes the parent assignee. Promoting the next stage's `backlog` sub-issues to
-`todo` is the woken agent's decision, not a server side effect. When the woken
-assignee (often a squad leader) decides the parent is complete, the system
-comment explicitly asks for `multica issue status <parent-id> in_review`. Any
-turn may move the status on its own too, judged from what the work changes
-about the issue — there is no assignee gate (MUL-6417).
-
-## Metadata CLI
-
-| Behavior | File:line |
-|---|---|
-| `multica issue metadata set <issue-id> --key --value [--type]` | `server/cmd/multica/cmd_issue_metadata.go:80,109-111` |
-| `multica issue metadata delete <issue-id> --key` | `server/cmd/multica/cmd_issue_metadata.go:93,113` |
-| API routes (PUT/DELETE `/metadata/{key}`) | `server/cmd/server/router.go:478-479` |
-
-`--value` is JSON-parsed by default (bool/number sniff); `--type` forces
-`string`/`number`/`bool`.
-
-## Custom properties CLI
-
-| Behavior | File:line |
-|---|---|
-| `multica property list/get/create/update/archive/unarchive` | `server/cmd/multica/cmd_property.go` |
-| `multica issue property list/set/unset` (name→id translation) | `server/cmd/multica/cmd_property.go` (`encodeIssuePropertyValue`) |
-| `issue list --property "Name=Value"` filter (OR within a definition, AND across; `__none__` unset sentinel; scalar values sent in their stored spelling) | `server/cmd/multica/cmd_property.go` (`buildPropertiesFilterQueryParam`, `resolvePropertyFilterValue`, `propertyNoValueSentinel`) |
-| `issue list --sort property:<name-or-id>` (archived + orderless types rejected up front) | `server/cmd/multica/cmd_property.go` (`resolveSortableProperty`, `issueSortablePropertyTypes`); `server/cmd/multica/cmd_issue.go` (`runIssueList`) |
-| Server `properties=` filter contract the CLI forwards to | `server/internal/handler/property.go` (`parsePropertiesFilterParam`, `noPropertyValue`) |
-| Select sort follows option order (ordinal scales sort by meaning) | `server/internal/handler/property.go` (`propertySortExpr`, `selectPropertySortExpr`) |
-| Definition CRUD, admin gate, agent-actor rejection | `server/internal/handler/property.go` (`requirePropertyAdmin`) |
-| Optional catalog icon field and allowlist validation | `server/internal/handler/property.go` (`PropertyResponse`, `validatePropertyIcon`) |
-| Per-type value validation (self-correcting errors) | `server/internal/handler/property.go` (`validatePropertyValue`) |
-| `actor` / `multi_actor` reference parsing, `member` as the only kind, 20-value cap | `server/internal/handler/property.go` (`actorPropertyKinds`, `parseActorRef`, `parseActorRefList`, `maxPropertyActorValues`) |
-| Actor references are checked for workspace membership only | `server/internal/handler/property.go` (`resolveActorRefs`) |
-| `--value` name / email / id → `member:<uuid>` resolution (same member lookup as `--assignee`) | `server/cmd/multica/cmd_property.go` (`resolveActorPropertyRef`, `memberOnlyKinds`) |
-| Shared actor-reference types and helpers | `packages/core/types/property.ts` (`parseActorRef`, `actorRefsFromValue`, `MAX_ISSUE_PROPERTY_ACTOR_VALUES`) |
-| API routes (`/api/properties`, PUT/DELETE `/api/issues/{id}/properties/{propertyId}`) | `server/cmd/server/router.go` |
-
-## Verification command
-
-Re-derive any line above before depending on it:
-
-```bash
-cd server
-grep -n 'pull-requests <id>' cmd/multica/cmd_issue.go
-grep -n 'ListPullRequestsForIssue' cmd/server/router.go internal/handler/github.go
-grep -n 'func issuePullRequestRowToResponse\|type GitHubPullRequestResponse struct\|func derivePRState\|func extractIdentifiers\|func extractClosingIdentifiers\|closingIdentifierRe' internal/handler/github.go
-grep -n 'extractIdentifiers(\|extractClosingIdentifiers(\|derivePRState(' internal/handler/github.go
-grep -n 'qualifyingIdents\|reference_only\|ReferenceOnly' internal/handler/github.go pkg/db/queries/github.sql
-grep -n 'prevIssue.Status == "backlog"\|func (h \*Handler) shouldEnqueueAgentTask' internal/handler/issue.go
-grep -n 'func notifyParentOfChildDone' internal/handler/issue_child_done.go
-```
diff --git a/server/internal/service/builtin_skills_legacy/multica-working-on-issues/SKILL.md b/server/internal/service/builtin_skills_legacy/multica-working-on-issues/SKILL.md
new file mode 100644
index 0000000000..2a55872d84
--- /dev/null
+++ b/server/internal/service/builtin_skills_legacy/multica-working-on-issues/SKILL.md
@@ -0,0 +1,27 @@
+---
+name: multica-working-on-issues
+description: "Superseded by the multica-platform skill — load that instead. This file only records where the Multica issue contracts moved to."
+user-invocable: false
+allowed-tools: Bash(multica *)
+---
+
+# Moved into `multica-platform`
+
+Multica's platform contracts are now one skill. Everything this skill used to
+carry — PR linking vs close intent, reading a linked PR's real state, metadata
+write discipline, custom properties, status side effects, sub-issues and stages,
+and finding who else is running — lives in:
+
+```text
+multica-platform → references/issues.md
+```
+
+Load the `multica-platform` skill and open that file. Its routing table also
+names the reference for every other platform domain: mentions, agents, squads,
+autopilots, projects, runtimes, and skill import.
+
+Nothing was dropped in the move — the contracts were reorganized, not shortened.
+
+You are seeing this redirect because the Multica app on this machine is older
+than the server it is talking to, so its task brief still refers to the previous
+skill name. Updating the app removes this extra hop.
diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.go
index baa49572b3..639ea0b23d 100644
--- a/server/internal/service/builtin_skills_test.go
+++ b/server/internal/service/builtin_skills_test.go
@@ -1,6 +1,7 @@
package service
import (
+ "regexp"
"strings"
"testing"
@@ -17,20 +18,36 @@ import (
// The evals live in a _test.go file on purpose: anything *inside* a skill
// directory is walked into AgentSkillData.Files and shipped to agent machines
// (see loadBuiltinSkill). Tests must stay out of that payload.
+//
+// The same reasoning is what TestBuiltinSkillPayloadCarriesNoSourceReferences
+// enforces for the payload's CONTENT (MUL-6986). A shipped skill is read on a
+// machine that has no copy of this repository, so a file:line citation, a Go
+// identifier, or a `go test` command in it is not merely useless — it sends the
+// reader grepping for paths that do not exist. Evidence about how the server
+// implements a contract belongs here, next to the assertion that pins it.
const (
// maxSkillBodyLines is Anthropic's L2 budget for a SKILL.md body
// (~5k tokens). Past this, content belongs in one-level-deep supporting
// files, not the always-loaded body.
maxSkillBodyLines = 500
+ // maxRoutingBodyLines applies to a skill that HAS supporting references.
+ // Its body is then a router — positioning, shared invariants, and a table
+ // naming the reference to open — and every line it spends restating a
+ // reference is a line every activation pays for. The whole point of
+ // splitting into references is that the body stays cheap.
+ maxRoutingBodyLines = 150
// maxDescriptionChars is the frontmatter description cap — it is the only
// thing an agent sees when deciding whether to load the skill, and every
// runtime CLI pays for it in the always-loaded skill listing. A description
// earns its characters two ways only: trigger wording that matches how the
// task actually arrives, and reverse boundaries that prevent mis-routing.
- // A "Covers A, B, C..." content inventory does neither — the agent reads the
- // body once it opens the skill. The cap is deliberately tight (the longest
- // built-in sits at 222) so that inventory prose cannot creep back in.
+ //
+ // Naming several domains is not the "content inventory" this rules out. The
+ // ban is on restating the BODY's section headings, which the agent reads for
+ // free once it opens the skill. Nouns like "squad" or "autopilot" are how
+ // the task arrives — they are trigger wording, and after MUL-6986 one
+ // description has to do the recall work eight used to.
maxDescriptionChars = 300
)
@@ -38,15 +55,18 @@ const (
// on every built-in skill, current and future. A new skill that violates the
// shape fails here without anyone having to remember the rules.
func TestBuiltinSkillsConformToTemplate(t *testing.T) {
- skills := loadBuiltinSkills()
+ skills := allBuiltinSkillsForTest()
if len(skills) == 0 {
t.Fatal("no built-in skills loaded; embed or layout is broken")
}
for _, skill := range skills {
t.Run(skill.Name, func(t *testing.T) {
- // The multica- prefix keeps the on-disk slug from colliding with a
- // user-authored workspace skill.
+ // The multica- prefix is the platform namespace. Pointers name
+ // built-ins by their bare name on the assumption that no
+ // workspace skill shares one; nothing reserves the prefix
+ // server-side yet, and that gap is accepted rather than handled
+ // (see builtinSlug).
if !strings.HasPrefix(skill.Name, "multica-") {
t.Errorf("skill name %q must carry the multica- prefix", skill.Name)
}
@@ -65,8 +85,40 @@ func TestBuiltinSkillsConformToTemplate(t *testing.T) {
if len(desc) > maxDescriptionChars {
t.Errorf("description is %d chars, over the %d cap", len(desc), maxDescriptionChars)
}
- if n := strings.Count(body, "\n") + 1; n > maxSkillBodyLines {
- t.Errorf("SKILL.md body is %d lines, over the %d-line L2 budget; move detail into one-level-deep supporting files", n, maxSkillBodyLines)
+ budget := maxSkillBodyLines
+ if len(skill.Files) > 0 {
+ // A skill with references has already paid for the split; its
+ // body must stay a router.
+ budget = maxRoutingBodyLines
+ }
+ if n := strings.Count(body, "\n") + 1; n > budget {
+ t.Errorf("SKILL.md body is %d lines, over the %d-line budget; move detail into one-level-deep supporting files", n, budget)
+ }
+
+ // Every built-in is a platform-contract skill: it triggers from
+ // context rather than a slash command, and it is fenced to the CLI
+ // it teaches.
+ if got := strings.TrimSpace(fm["user-invocable"]); got != "false" {
+ t.Errorf("user-invocable = %q, want false (a platform-contract skill triggers from context, not a slash command)", got)
+ }
+ // allowed-tools is the union across everything the skill now covers.
+ // Merging eight skills merged their tool declarations too, so the
+ // router declares Bash(git *) / Bash(gh *) — which only issues.md
+ // needs — while an agent is reading, say, autopilots.md. The
+ // alternative is dropping them and regressing the issue workflow
+ // that legitimately runs `gh pr`. Recorded rather than silently
+ // widened: allowed-tools is a pre-approval list, and today the
+ // daemon's global permission mode means this grants no privilege
+ // the agent did not already have. Revisit if per-reference
+ // declarations ever exist.
+ if got := strings.TrimSpace(fm["allowed-tools"]); !strings.Contains(got, "Bash(multica *)") {
+ t.Errorf("allowed-tools = %q, want access to the Multica CLI", got)
+ }
+
+ for _, f := range skill.Files {
+ if n := strings.Count(f.Content, "\n") + 1; n > maxSkillBodyLines {
+ t.Errorf("supporting file %q is %d lines, over the %d-line budget; split it", f.Path, n, maxSkillBodyLines)
+ }
}
// Evals must never ride along to agent machines as supporting files.
@@ -92,7 +144,7 @@ func TestBuiltinSkillsConformToTemplate(t *testing.T) {
// on the broken files. Only a real yaml.Unmarshal reproduces what Codex does,
// which is exactly what is needed to catch this class of bug before it ships.
func TestBuiltinSkillsFrontmatterIsStrictYAML(t *testing.T) {
- skills := loadBuiltinSkills()
+ skills := allBuiltinSkillsForTest()
if len(skills) == 0 {
t.Fatal("no built-in skills loaded; embed or layout is broken")
}
@@ -125,32 +177,508 @@ func TestBuiltinSkillsFrontmatterIsStrictYAML(t *testing.T) {
}
}
-// TestMentioningSkillFollowsContractFrontmatter locks the reference template:
-// the mentioning skill is a context-triggered platform-contract skill, so it
-// must declare user-invocable:false and fence itself to the multica CLI. New
-// contract skills should copy this shape.
-func TestMentioningSkillFollowsContractFrontmatter(t *testing.T) {
- skill, ok := findSkill(t, "multica-mentioning")
+// TestBuiltinSkillPayloadCarriesNoSourceReferences is the regression guard for
+// MUL-6986: the shipped payload must not reference this repository's source.
+//
+// Every file in a skill directory is written into the workdir of every task
+// that receives the skill — on the user's own machine, which has no checkout of
+// this repo. A `file:line` citation there resolves to nothing, and a `go test`
+// or `grep -n ... internal/handler/x.go` "verification command" actively sends
+// the reading agent after paths that cannot exist. Before this test, roughly
+// half the built-in payload by bytes was exactly that.
+//
+// Maintainer-facing evidence for a contract belongs in this file, beside the
+// assertion that pins it, where it stays with the code it describes.
+func TestBuiltinSkillPayloadCarriesNoSourceReferences(t *testing.T) {
+ banned := []struct {
+ what string
+ re *regexp.Regexp
+ }{
+ {"a path into this repository", regexp.MustCompile(`(?:server|packages|apps|e2e)/[A-Za-z0-9_-]+/`)},
+ {"a source file name", regexp.MustCompile(`[A-Za-z0-9_./-]*\.(?:go|ts|tsx|sql)\b`)},
+ {"a command that only runs in this repository", regexp.MustCompile(`\bgo (?:test|build|vet|run)\b`)},
+ {"a migration ordinal", regexp.MustCompile(`\bmigrations?/[0-9]`)},
+ {"a Go package-qualified identifier", regexp.MustCompile(`\b(?:util|service|handler|db|protocol|skillpkg|repocache|execenv|daemon)\.[A-Z][A-Za-z0-9]*`)},
+ {"a Go test name", regexp.MustCompile(`\bTest[A-Z][A-Za-z0-9]{3,}\b`)},
+ {"a development branch name", regexp.MustCompile(`\b(?:feat|fix|refactor|chore)/[a-z0-9][a-z0-9-]*`)},
+ }
+
+ for _, skill := range allBuiltinSkillsForTest() {
+ t.Run(skill.Name, func(t *testing.T) {
+ files := map[string]string{"SKILL.md": skill.Content}
+ for _, f := range skill.Files {
+ files[f.Path] = f.Content
+ }
+ for path, content := range files {
+ for _, b := range banned {
+ if m := b.re.FindString(content); m != "" {
+ t.Errorf("%s leaks %s (%q); the reader's machine has no copy of this repository — "+
+ "state the user-observable behavior instead, and keep the evidence in builtin_skills_test.go", path, b.what, m)
+ }
+ }
+ }
+ })
+ }
+}
+
+// TestPlatformSkillRoutingTableMatchesItsReferences keeps the router honest in
+// both directions. A reference the table does not name is unreachable — the
+// body is the only thing loaded on activation, so nothing else can point at it
+// — and a table row naming a file that does not exist sends the agent to open
+// a path that is not there.
+func TestPlatformSkillRoutingTableMatchesItsReferences(t *testing.T) {
+ skill, ok := findSkill(t, PlatformSkillName)
+ if !ok {
+ return
+ }
+ _, body, _ := splitFrontmatter(skill.Content)
+
+ shipped := make(map[string]bool, len(skill.Files))
+ for _, f := range skill.Files {
+ shipped[f.Path] = true
+ if !strings.HasPrefix(f.Path, "references/") {
+ t.Errorf("supporting file %q is not under references/; the routing table only addresses that directory", f.Path)
+ }
+ if !strings.Contains(body, f.Path) {
+ t.Errorf("SKILL.md routing table never names %q, so nothing can reach it", f.Path)
+ }
+ }
+
+ for _, cited := range regexp.MustCompile("references/[a-z-]+\\.md").FindAllString(body, -1) {
+ if !shipped[cited] {
+ t.Errorf("SKILL.md points at %q, which the skill does not ship", cited)
+ }
+ }
+
+ if len(skill.Files) == 0 {
+ t.Fatal("platform skill ships no references; the routing body has nothing to route to")
+ }
+}
+
+// TestLegacyRedirectsFollowTheDaemonsBrief pins the compatibility contract for
+// the merge (MUL-6986).
+//
+// The runtime brief is assembled by the DAEMON, so deploying a backend does not
+// rewrite an installed daemon's copy of it. A daemon released before the merge
+// still tells its agent to "read the `multica-working-on-issues` skill" — a
+// name this server no longer ships — and backend upgrades do not force a daemon
+// upgrade, so that window is open-ended. Such a daemon gets a redirect stub;
+// a current one gets nothing extra, which is what lets the stub retire itself.
+//
+// The stub must stay a signpost: if it ever grows contracts of its own they
+// will rot against references/issues.md, silently, on exactly the installs that
+// cannot be updated from here.
+func TestLegacyRedirectsFollowTheDaemonsBrief(t *testing.T) {
+ const legacy = "multica-working-on-issues"
+ svc := &TaskService{}
+
+ current := svc.BuiltinSkills("", false)
+ if named(current, legacy) {
+ t.Errorf("a current daemon still receives %q; the stub only exists for briefs that name it", legacy)
+ }
+ if !named(current, PlatformSkillName) {
+ t.Fatalf("a current daemon does not receive %q", PlatformSkillName)
+ }
+
+ old := svc.BuiltinSkills("", true)
+ if !named(old, legacy) {
+ t.Errorf("a pre-merge daemon does not receive %q, so its brief points at a skill that is not installed", legacy)
+ }
+ if !named(old, PlatformSkillName) {
+ t.Errorf("a pre-merge daemon lost %q; the redirect adds to the set, it does not replace it", PlatformSkillName)
+ }
+
+ // Mika's scoping is orthogonal to the redirect: both dimensions compose.
+ if !named(svc.BuiltinSkills(MikaSystemKey, true), "multica-onboarding") {
+ t.Errorf("Mika on a pre-merge daemon lost multica-onboarding")
+ }
+ if named(svc.BuiltinSkills("", true), "multica-onboarding") {
+ t.Errorf("the redirect path leaked multica-onboarding to an ordinary agent")
+ }
+
+ var stub AgentSkillData
+ for _, s := range old {
+ if s.Name == legacy {
+ stub = s
+ }
+ }
+ if len(stub.Files) != 0 {
+ t.Errorf("redirect stub ships %d supporting files; it should carry nothing but the new location", len(stub.Files))
+ }
+ _, body, ok := splitFrontmatter(stub.Content)
+ if !ok {
+ t.Fatal("redirect stub has no frontmatter")
+ }
+ if !strings.Contains(body, PlatformSkillName) || !strings.Contains(body, "references/issues.md") {
+ t.Errorf("redirect stub does not name where the contracts went:\n%s", body)
+ }
+ if n := strings.Count(body, "\n") + 1; n > 40 {
+ t.Errorf("redirect stub is %d lines; a signpost that grows contracts will rot against the real reference", n)
+ }
+
+ // Bundle resolution must still serve it: the stub reaches the daemon as a
+ // ref like any other built-in, and the resolve path is name-blind.
+ if !named(svc.AllBuiltinSkills(), legacy) {
+ t.Errorf("the unscoped set is missing %q; bundle resolution would 404 for a pre-merge daemon", legacy)
+ }
+}
+
+// TestPlatformSkillDescriptionNamesEveryDomain is the recall guard for the
+// nine-into-one merge (MUL-6986).
+//
+// Before the merge, each domain advertised its own description in the
+// always-loaded listing, so an agent looking for "how does squad routing work"
+// matched on the word "squad". Collapsing to one skill removes seven of those
+// eight surfaces, and the remaining description is the only thing an agent sees
+// before deciding to open the skill. If a domain's trigger word is not in it,
+// that domain became strictly harder to find than it was before — which is the
+// one regression this merge is not allowed to cause.
+//
+// The map must also stay exhaustive: adding a reference without adding its
+// trigger word ships contracts that nothing advertises.
+func TestPlatformSkillDescriptionNamesEveryDomain(t *testing.T) {
+ // reference file -> the word an agent would use when the task arrives.
+ // These are task nouns, not section headings: a task arrives as "set up an
+ // autopilot", never as "Core model".
+ triggerWords := map[string]string{
+ "references/issues.md": "issue",
+ "references/mentions.md": "mention",
+ "references/agents.md": "agent",
+ "references/squads.md": "squad",
+ "references/autopilots.md": "autopilot",
+ "references/projects.md": "project",
+ "references/runtimes.md": "runtime",
+ "references/skill-import.md": "skill import",
+ }
+
+ skill, ok := findSkill(t, PlatformSkillName)
if !ok {
return
}
fm, _, _ := splitFrontmatter(skill.Content)
+ desc := strings.ToLower(fm["description"])
+
+ for _, f := range skill.Files {
+ word, mapped := triggerWords[f.Path]
+ if !mapped {
+ t.Errorf("reference %q has no trigger word; add one here and to the description, "+
+ "or an agent has no way to learn this skill covers it", f.Path)
+ continue
+ }
+ if !strings.Contains(desc, word) {
+ t.Errorf("description never says %q, so %s is unreachable from the skill listing", word, f.Path)
+ }
+ }
+
+ shipped := make(map[string]bool, len(skill.Files))
+ for _, f := range skill.Files {
+ shipped[f.Path] = true
+ }
+ for path := range triggerWords {
+ if !shipped[path] {
+ t.Errorf("trigger word mapped for %q, which the skill no longer ships", path)
+ }
+ }
+}
+
+// TestPlatformSkillCoversPlatformContracts re-homes the per-domain contract
+// anchors that each merged skill used to assert on its own body. They are
+// anchors, not prose review: if a contract leaves the payload, the brief
+// pointers and the product decisions behind them go stale silently.
+func TestPlatformSkillCoversPlatformContracts(t *testing.T) {
+ skill, ok := findSkill(t, PlatformSkillName)
+ if !ok {
+ return
+ }
+ files := make(map[string]string, len(skill.Files)+1)
+ files["SKILL.md"] = skill.Content
+ for _, f := range skill.Files {
+ files[f.Path] = f.Content
+ }
- if got := strings.TrimSpace(fm["user-invocable"]); got != "false" {
- t.Errorf("user-invocable = %q, want false (a platform-contract skill triggers from context, not a slash command)", got)
+ cases := []struct {
+ file string
+ want []string
+ notWant []string
+ }{
+ {
+ file: "SKILL.md",
+ want: []string{
+ // Must-fix from review: "load on demand" is not "load exactly
+ // one". A task that creates a squad, assigns it an issue and
+ // writes a mention needs three references, and wording that
+ // implies one would have the agent act on contracts it never
+ // read — the recall loss the merge is not allowed to cause.
+ "open the reference(s) your task actually needs",
+ "crosses domains needs each domain it touches",
+ "Do not read them all",
+ // The router's whole job: name every domain and its file.
+ "references/issues.md",
+ "references/mentions.md",
+ "references/agents.md",
+ "references/squads.md",
+ "references/autopilots.md",
+ "references/projects.md",
+ "references/runtimes.md",
+ "references/skill-import.md",
+ // Invariants deduplicated out of the eight merged bodies. Each
+ // was repeated in most of them; the router is now their only
+ // home, so losing one here loses it everywhere.
+ "A name is not an id",
+ "`--output json` writes to stdout",
+ "`--no-start` when you are only recording",
+ "Status is a category, not a literal",
+ "Comment reads stay bounded",
+ "--roots-only --summary --compact",
+ "--thread <thread-id> --tail 30",
+ },
+ notWant: []string{
+ // The singular forms this replaced.
+ "open the ONE reference",
+ "there is never a reason to read all eight",
+ },
+ },
+ {
+ file: "references/issues.md",
+ want: []string{
+ "multica issue pull-requests <issue-id> --output json",
+ "Default for code-changing issue work",
+ "open or update a PR before posting the final Multica issue comment",
+ "This is a default, not",
+ "Use a routable issue key in the PR title, body, or branch",
+ "include the PR URL when a PR exists",
+ "Closes MUL-123",
+ "--status backlog",
+ // The only sanctioned pr_url reference is the negative
+ // compatibility warning about pre-existing data — not a write
+ // recommendation (MUL-5442 owner ruling: no curated key
+ // vocabulary).
+ "`pr_url` metadata (which can be",
+ // MUL-5442: the brief's Sub-issue Creation section is a
+ // one-line map pointing here. These anchors are the demoted
+ // playbook — if they leave, the brief pointer dangles.
+ "todo starts work now, backlog parks it",
+ "`--stage <N>`",
+ "when a whole stage finishes",
+ "multica issue status <child-id> todo",
+ // MUL-5442: the brief's Issue Metadata section defers the full
+ // write discipline here. Every relocated ban is anchored
+ // individually — both defining categories AND each example —
+ // so no single item or category boundary can be dropped while
+ // the brief still points here.
+ "Never store secrets, tokens, or API keys",
+ "Not metadata: logs or summaries",
+ "bookkeeping such as timestamps",
+ "attempt counts, or agent IDs",
+ "other single-run details",
+ "files touched and investigation notes",
+ "belong in the result comment",
+ "the platform curates no vocabulary",
+ // #7768: nothing about concurrent runs is pushed into the
+ // prompt any more (MUL-6984), so the skill has to carry the
+ // pull path itself. All three anchors are load-bearing — the
+ // command is the remedy, the cap disclosure stops a truncated
+ // answer from reading as an empty one, and the advisory line
+ // is a negative safety boundary: an agent that reads these as
+ // a lock will skip the coordination they exist to prompt.
+ "multica issue runs <issue-id> --siblings --output json",
+ "capped at 20",
+ "Nothing here reserves an issue or serialises anything",
+ },
+ notWant: []string{
+ // A curated key list is the "recommended fields" concept the
+ // owner ruled out on MUL-5442.
+ "High-signal keys",
+ "reuse these names so queries stay consistent",
+ "scratchpad for run state",
+ "(`pr_url`, `waiting_on`",
+ // Per-turn workflow the runtime brief owns; duplicating it here
+ // is how the two drift apart.
+ "Start from the trigger, not from memory",
+ "multica issue comment list <issue-id> --thread <trigger-comment-id>",
+ "multica issue comment add <issue-id> --parent <trigger-comment-id>",
+ },
+ },
+ {
+ file: "references/mentions.md",
+ want: []string{
+ "(member|agent|squad|issue|all)/([0-9a-fA-F-]+|all)",
+ "multica workspace member list --output json",
+ "enqueues a run for that agent",
+ "enqueues NOTHING",
+ "[@all](mention://all/all)",
+ "invocation_not_allowed",
+ "target_unavailable",
+ "runtime_offline",
+ "coalesced",
+ "deferred",
+ // The autopilot-creator fallback is authorization only; an
+ // agent reading it as attribution would mis-report who ran.
+ "It is authorization only",
+ },
+ },
+ {
+ file: "references/agents.md",
+ want: []string{
+ "not a parameter manual",
+ "`description` is a catalog summary",
+ "`instructions` is the runtime behavior contract",
+ "`conversation_starters`",
+ "`avatar_url` → a random `emoji:<glyph>`",
+ "multica agent create --name <name> --runtime-id <runtime-id>",
+ "`model` is a first-class persisted column",
+ "custom_env",
+ "Never put credentials or other secrets in `custom_args`",
+ "--custom-env-stdin",
+ "--custom-env-file",
+ "multica agent skills add <agent-id> --skill-ids <skill-id> --output json",
+ "multica agent skills list <agent-id> --output json",
+ "multica agent get <agent-id> --output json",
+ "255",
+ },
+ notWant: []string{
+ "--from-template",
+ "/api/agent-templates",
+ "template_slug",
+ "curated template",
+ // De-coaching: this states contracts, it does not teach a
+ // generic how-to methodology.
+ "Define the job first",
+ "Run a low-risk task",
+ "Decision flow",
+ },
+ },
+ {
+ file: "references/squads.md",
+ want: []string{
+ "A squad is not an agent",
+ "squad's `leader_id` agent",
+ "squad members are not automatically fanned out",
+ "multica squad member set-role",
+ "mention://squad/<squad-id>",
+ "recording squad activity",
+ // The debugging entry point must stay a bounded two-step read
+ // (MUL-5442): a roots-only scan alone never returns reply
+ // bodies, where mention triggers and failure reasons live.
+ "--roots-only --summary",
+ "--thread <thread-id> --tail 30",
+ "scan the roots first, then open the threads",
+ },
+ notWant: []string{
+ // MUL-5696: no unbounded comment pull. Both shapes contradict
+ // the brief's "two bounded reads, never one bulk pull".
+ "multica issue comment list <issue-id> --output json",
+ "--recent 10",
+ },
+ },
+ {
+ file: "references/autopilots.md",
+ want: []string{
+ "An autopilot is not an agent",
+ "create_issue",
+ "run_only",
+ "multica autopilot trigger-add <autopilot-id> --kind schedule",
+ "multica autopilot trigger <autopilot-id> --output json",
+ "Do not run `trigger`",
+ "webhook tokens",
+ "{{date}}",
+ "squad's leader agent",
+ // A schedule with no --timezone silently runs in UTC, which is
+ // the one wrong assumption here that recurs daily.
+ "runs in **UTC**",
+ },
+ },
+ {
+ file: "references/runtimes.md",
+ want: []string{
+ "the daemon polls and claims the task",
+ "multica runtime list --output json",
+ "multica repo checkout <url>",
+ "MULTICA_DAEMON_PORT",
+ "resource_ref.ref",
+ "github_repo",
+ "local_directory",
+ "Runtime and repo commands affect active agent execution",
+ // An agent reads this to know whether its checkout can be
+ // committed to. Codex on Linux and Windows gets task-local Git
+ // metadata; every other runtime gets a linked worktree.
+ "Linux and Windows Codex",
+ "task-local Git metadata",
+ },
+ },
+ {
+ file: "references/projects.md",
+ want: []string{
+ "Projects are durable context containers",
+ ".multica/project/resources.json",
+ "multica project resource list <project-id> --output json",
+ "multica project resource add <project-id> --type github_repo --url <github-url> --output json",
+ "multica project resource add <project-id> --type github_repo --url <github-url> --ref <branch-or-sha> --output json",
+ "multica project resource add <project-id> --type local_directory",
+ "Project resources are durable and affect future tasks",
+ "github_repo.resource_ref.url",
+ "resource_ref.ref",
+ },
+ },
+ {
+ file: "references/skill-import.md",
+ want: []string{
+ "multica skill import --url <url> --output json",
+ "/api/skills/import",
+ "clawhub.ai",
+ "skills.sh",
+ "github.com",
+ "config.origin",
+ "--on-conflict fail",
+ "--on-conflict overwrite",
+ "--on-conflict rename",
+ "--on-conflict skip",
+ "conflict",
+ "skipped",
+ "409",
+ "existing_skill",
+ "legacy",
+ "multica skill list --output json",
+ "npx skills add",
+ "multica agent skills add <agent-id> --skill-ids <skill-id> --output json",
+ "multica agent skills list <agent-id> --output json",
+ "replace-all",
+ "`set` is the replacement path",
+ },
+ notWant: []string{
+ "multica agent skills set <agent-id> --skill-ids <skill-id>",
+ "merge the new skill id with the existing ids",
+ },
+ },
}
- if got := strings.TrimSpace(fm["allowed-tools"]); got != "Bash(multica *)" {
- t.Errorf("allowed-tools = %q, want Bash(multica *) (fence the skill to the CLI it teaches)", got)
+
+ for _, tc := range cases {
+ t.Run(tc.file, func(t *testing.T) {
+ content, ok := files[tc.file]
+ if !ok {
+ t.Fatalf("platform skill does not ship %q", tc.file)
+ }
+ for _, want := range tc.want {
+ if !containsUnwrapped(content, want) {
+ t.Errorf("%s missing %q", tc.file, want)
+ }
+ }
+ for _, forbidden := range tc.notWant {
+ if containsUnwrapped(content, forbidden) {
+ t.Errorf("%s carries banned content %q", tc.file, forbidden)
+ }
+ }
+ })
}
}
-// TestMentioningSkillTeachesTheParserContract is the eval that gives the skill
-// its value: it proves the skill teaches exactly what util.ParseMentions
-// enforces. The skill's "Incorrect" examples must parse to nothing (the
-// @gpt-boy class of bug: a name where a UUID belongs fails silently), and its
-// "Correct" example must parse. If mention.go:16 drifts, this breaks and the
-// skill's claims must be re-checked.
-func TestMentioningSkillTeachesTheParserContract(t *testing.T) {
+// TestPlatformSkillTeachesTheParserContract is the eval that gives the mentions
+// reference its value: it proves the skill teaches exactly what
+// util.ParseMentions enforces. The skill's "Incorrect" examples must parse to
+// nothing (the @gpt-boy class of bug: a name where a UUID belongs fails
+// silently), and its "Correct" example must parse. If the mention regex drifts,
+// this breaks and the skill's claims must be re-checked.
+func TestPlatformSkillTeachesTheParserContract(t *testing.T) {
const uuid = "7f3a1b2c-0000-4000-8000-000000000abc"
cases := []struct {
@@ -184,13 +712,20 @@ func TestMentioningSkillTeachesTheParserContract(t *testing.T) {
want: []util.Mention{{Type: "all", ID: "all"}},
},
{
- // Skill: "Using the wrong type for an id points at the wrong
- // entity." The link still parses — it just resolves wrong — which
- // is exactly why the skill stresses matching type to id source.
+ // Skill: "Using the wrong type for a real UUID still parses — it
+ // just resolves to the wrong entity." Which is exactly why the
+ // skill stresses matching type to id source.
name: "wrong type still parses (points at wrong entity)",
content: "[@Bot](mention://member/" + uuid + ")",
want: []util.Mention{{Type: "member", ID: uuid}},
},
+ {
+ // Skill: `project` is deliberately outside the type group, so a
+ // project reference can never start a run.
+ name: "project is not a parseable mention type",
+ content: "[Roadmap](mention://project/" + uuid + ")",
+ want: nil,
+ },
}
for _, tc := range cases {
@@ -208,394 +743,71 @@ func TestMentioningSkillTeachesTheParserContract(t *testing.T) {
}
}
-func TestWorkingOnIssuesSkillCoversIssueLoopContracts(t *testing.T) {
- skill, ok := findSkill(t, "multica-working-on-issues")
- if !ok {
- return
- }
- fm, body, _ := splitFrontmatter(skill.Content)
-
- if got := strings.TrimSpace(fm["user-invocable"]); got != "false" {
- t.Errorf("user-invocable = %q, want false (issue workflow guidance triggers from context)", got)
- }
- if got := strings.TrimSpace(fm["allowed-tools"]); !strings.Contains(got, "Bash(multica *)") {
- t.Errorf("allowed-tools = %q, want access to the Multica CLI", got)
- }
-
- // Contract anchors only — exact file:line citations live in the skill's
- // references/source-map.md, not here, so a downstream main merge that
- // shifts a line cannot rot this test into pinning a stale lie.
- mustContain := []string{
- "multica issue pull-requests <issue-id> --output json",
- "Default for code-changing issue work",
- "open or update a PR before posting the final Multica issue comment",
- "This is a default, not",
- "Use a routable issue key in the PR title, body, or branch",
- "include the PR URL when a PR exists",
- "Closes MUL-2759",
- "--status backlog",
- // The only sanctioned pr_url reference is the negative compatibility
- // warning about pre-existing data — not a write recommendation
- // (MUL-5442 owner ruling: no curated key vocabulary).
- "`pr_url` metadata (which can be",
- "references/working-on-issues-source-map.md",
- // MUL-5442: the brief's Sub-issue Creation section is now a one-line
- // map pointing here. These anchors are the demoted playbook — if they
- // leave the skill, the brief pointer dangles.
- "`todo` starts work now, `backlog` parks it",
- "`--stage <N>`",
- "when a whole stage finishes",
- "multica issue status <child-id> todo",
- // MUL-5442: the brief's Issue Metadata section defers the full
- // write discipline here. Every relocated ban is anchored
- // individually — both defining categories AND each example —
- // so no single item or category boundary can be dropped while
- // the brief still points at this skill (round-3 review).
- "Never store secrets, tokens, or API keys",
- "Not metadata: logs or summaries",
- "bookkeeping such as timestamps",
- "attempt counts, or agent IDs",
- "other single-run details",
- "files touched and investigation notes",
- "belong in the result comment",
- // Owner ruling: metadata is deliberately free-form custom state;
- // the platform curates no key vocabulary.
- "the platform curates no vocabulary",
- // #7768: nothing about concurrent runs is pushed into the prompt any
- // more (MUL-6984), so the skill has to carry the pull path itself.
- // All three anchors are load-bearing — the command is the remedy, the
- // cap disclosure is what stops a truncated answer from reading as an
- // empty one, and the advisory line is a negative safety boundary: an
- // agent that reads these as a lock will skip the coordination they
- // exist to prompt.
- "multica issue runs <issue-id> --siblings --output json",
- "capped at 20",
- "Nothing here reserves an issue or serialises anything",
- }
- for _, want := range mustContain {
- if !strings.Contains(body, want) {
- t.Errorf("working-on-issues skill missing %q", want)
- }
- }
-
- mustNotContain := []string{
- // A curated key list is the "recommended fields" concept the owner
- // ruled out on MUL-5442 — it must not creep back into the skill
- // that loads exactly when an agent is about to write metadata.
- "High-signal keys",
- "reuse these names so queries stay consistent",
- "scratchpad for run state",
- "(`pr_url`, `waiting_on`",
- "Start from the trigger, not from memory",
- "multica issue get <issue-id> --output json",
- "multica issue metadata list <issue-id> --output json",
- "multica issue comment list <issue-id> --thread <trigger-comment-id>",
- "multica issue comment add <issue-id> --parent <trigger-comment-id>",
- }
- for _, forbidden := range mustNotContain {
- if strings.Contains(body, forbidden) {
- t.Errorf("working-on-issues skill duplicates runtime prompt contract %q", forbidden)
- }
- }
-
- if !skillHasFile(skill, "references/working-on-issues-source-map.md") {
- t.Errorf("working-on-issues skill missing supporting file references/working-on-issues-source-map.md")
- }
-}
+// TestOnboardingSkillIsScopedToMika pins the agent-scoping rule (MUL-6986).
+//
+// The onboarding walkthrough is one agent's procedure, not a platform contract.
+// Shipping it to every agent put its description in every agent's always-loaded
+// skill listing and its body in every task workdir, to be usable by one.
+func TestOnboardingSkillIsScopedToMika(t *testing.T) {
+ const onboarding = "multica-onboarding"
-func TestSkillImportingSkillCoversWorkspaceImportContracts(t *testing.T) {
- skill, ok := findSkill(t, "multica-skill-importing")
- if !ok {
- return
+ ordinary := loadBuiltinSkills("")
+ if named(ordinary, onboarding) {
+ t.Errorf("an ordinary agent still receives %q", onboarding)
}
- fm, body, _ := splitFrontmatter(skill.Content)
-
- if got := strings.TrimSpace(fm["user-invocable"]); got != "false" {
- t.Errorf("user-invocable = %q, want false (skill import guidance triggers from context)", got)
- }
- if got := strings.TrimSpace(fm["allowed-tools"]); !strings.Contains(got, "Bash(multica *)") {
- t.Errorf("allowed-tools = %q, want access to the Multica CLI", got)
- }
-
- mustContain := []string{
- "multica skill import --url <url> --output json",
- "/api/skills/import",
- "clawhub.ai",
- "skills.sh",
- "github.com",
- "config.origin",
- "--on-conflict fail",
- "--on-conflict overwrite",
- "--on-conflict rename",
- "--on-conflict skip",
- "status",
- "conflict",
- "skipped",
- "409",
- "existing_skill",
- "id",
- "name",
- "legacy",
- "multica skill list --output json",
- "npx skills add",
- "multica agent skills add <agent-id> --skill-ids <skill-id> --output json",
- "multica agent skills list <agent-id> --output json",
- "replace-all",
- "`set` is the replacement path",
- "references/skill-importing-source-map.md",
- }
- for _, want := range mustContain {
- if !strings.Contains(body, want) {
- t.Errorf("skill-importing skill missing %q", want)
- }
+ if !named(ordinary, PlatformSkillName) {
+ t.Errorf("an ordinary agent does not receive %q, which every agent needs", PlatformSkillName)
}
- mustNotContain := []string{
- "multica agent skills set <agent-id> --skill-ids <skill-id>",
- "merge the new skill id with the existing ids",
+ mika := loadBuiltinSkills(MikaSystemKey)
+ if !named(mika, onboarding) {
+ t.Errorf("Mika does not receive %q, which only Mika can use", onboarding)
}
- for _, forbidden := range mustNotContain {
- if strings.Contains(body, forbidden) {
- t.Errorf("skill-importing skill should not teach stale or destructive binding command %q", forbidden)
- }
+ if !named(mika, PlatformSkillName) {
+ t.Errorf("Mika lost %q; scoping must add to the universal set, not replace it", PlatformSkillName)
}
- if !skillHasFile(skill, "references/skill-importing-source-map.md") {
- t.Errorf("skill-importing skill missing supporting file references/skill-importing-source-map.md")
+ // The resolve path deliberately serves any built-in by id — the claim is
+ // the gate, and re-deriving the scope there would cost an agent read to
+ // re-answer a question the claim already answered.
+ if !named(allBuiltinSkillsForTest(), onboarding) {
+ t.Errorf("the unscoped set is missing %q; bundle resolution would 404 for Mika's daemon", onboarding)
}
}
-func TestCreatingAgentsSkillCoversAgentCreationContracts(t *testing.T) {
- skill, ok := findSkill(t, "multica-creating-agents")
- if !ok {
- return
- }
- fm, body, _ := splitFrontmatter(skill.Content)
-
- if got := strings.TrimSpace(fm["user-invocable"]); got != "false" {
- t.Errorf("user-invocable = %q, want false (agent creation guidance triggers from context)", got)
- }
- if got := strings.TrimSpace(fm["allowed-tools"]); !strings.Contains(got, "Bash(multica *)") {
- t.Errorf("allowed-tools = %q, want access to the Multica CLI", got)
- }
-
- mustContain := []string{
- "not a parameter manual",
- "`description` is a catalog summary",
- "`instructions` is the runtime behavior contract",
- "`conversation_starters`",
- "`avatar_url` → a random `emoji:<glyph>`",
- "multica agent create --name <name> --runtime-id <runtime-id>",
- "`model` is a first-class persisted column",
- "custom_env",
- "Never put credentials or other secrets in `custom_args`",
- "--custom-env-stdin",
- "--custom-env-file",
- "multica agent skills add <agent-id> --skill-ids <skill-id> --output json",
- "multica agent skills list <agent-id> --output json",
- "multica agent get <agent-id> --output json",
- "255",
- "references/creating-agents-source-map.md",
- }
- for _, want := range mustContain {
- if !strings.Contains(body, want) {
- t.Errorf("creating-agents skill missing %q", want)
- }
- }
-
- mustNotContain := []string{
- "--from-template",
- "/api/agent-templates",
- "template_slug",
- "curated template",
- "copy this parameter list",
- // De-coaching: this skill states source-backed contracts, it does not
- // teach a generic how-to methodology.
- "Define the job first",
- "Run a low-risk task",
- "Decision flow",
- }
- for _, forbidden := range mustNotContain {
- if strings.Contains(body, forbidden) {
- t.Errorf("creating-agents skill should not teach immature template content or generic how-to coaching %q", forbidden)
- }
- }
-
- if !skillHasFile(skill, "references/creating-agents-source-map.md") {
- t.Errorf("creating-agents skill missing supporting file references/creating-agents-source-map.md")
- }
+// containsUnwrapped matches an anchor against prose that Markdown has hard
+// wrapped. These anchors pin a claim, not a line layout — matching raw bytes
+// made every reflow of a paragraph look like a deleted contract, which trains
+// authors to fix the test instead of the text.
+func containsUnwrapped(content, want string) bool {
+ return strings.Contains(collapseSpace(content), collapseSpace(want))
}
-func TestSquadsSkillCoversLeaderRoutingContract(t *testing.T) {
- skill, ok := findSkill(t, "multica-squads")
- if !ok {
- return
- }
- fm, body, _ := splitFrontmatter(skill.Content)
-
- if got := strings.TrimSpace(fm["user-invocable"]); got != "false" {
- t.Errorf("user-invocable = %q, want false (squad guidance triggers from context)", got)
- }
- if got := strings.TrimSpace(fm["allowed-tools"]); !strings.Contains(got, "Bash(multica *)") {
- t.Errorf("allowed-tools = %q, want access to the Multica CLI", got)
- }
-
- mustContain := []string{
- "A squad is not an agent",
- "squad's `leader_id` agent",
- "squad members are not automatically fanned out",
- "multica squad member set-role",
- "mention://squad/<squad-id>",
- "recording squad activity",
- "references/squad-source-map.md",
- // The debugging quick-start must stay a bounded two-step read
- // (MUL-5442): a roots-only scan alone never returns reply bodies,
- // where mention triggers and failure reasons usually live — and it
- // must not regress to a --recent bulk pull either.
- "--roots-only --summary",
- "--thread <thread-id> --tail 30",
- "scan the roots first, then open the threads",
- }
- for _, want := range mustContain {
- if !strings.Contains(body, want) {
- t.Errorf("squads skill missing %q", want)
- }
- }
-
- // MUL-5696: no unbounded comment pull anywhere in the skill. #6347 fixed
- // the quick start's `--recent 10` but missed a second unbounded
- // `issue comment list` in the CLI section; both shapes contradict the
- // brief's "two bounded reads, never one bulk pull" doctrine.
- for _, banned := range []string{
- "multica issue comment list <issue-id> --output json",
- "--recent 10",
- } {
- if strings.Contains(body, banned) {
- t.Errorf("squads skill carries the unbounded comment read %q (MUL-5696)", banned)
- }
- }
+var whitespaceRun = regexp.MustCompile(`\s+`)
- if !skillHasFile(skill, "references/squad-source-map.md") {
- t.Errorf("squads skill missing supporting file references/squad-source-map.md")
- }
+func collapseSpace(s string) string {
+ return strings.TrimSpace(whitespaceRun.ReplaceAllString(s, " "))
}
-func TestAutopilotsSkillCoversDispatchAndSideEffects(t *testing.T) {
- skill, ok := findSkill(t, "multica-autopilots")
- if !ok {
- return
- }
- fm, body, _ := splitFrontmatter(skill.Content)
-
- if got := strings.TrimSpace(fm["user-invocable"]); got != "false" {
- t.Errorf("user-invocable = %q, want false", got)
- }
- if got := strings.TrimSpace(fm["allowed-tools"]); !strings.Contains(got, "Bash(multica *)") {
- t.Errorf("allowed-tools = %q, want access to the Multica CLI", got)
- }
-
- mustContain := []string{
- "An autopilot is not an agent",
- "create_issue",
- "run_only",
- "multica autopilot trigger-add <autopilot-id> --kind schedule",
- "multica autopilot trigger <autopilot-id> --output json",
- "Do not run `trigger`",
- "webhook tokens",
- "{{date}}",
- "squad's leader agent",
- "references/autopilots-source-map.md",
- }
- for _, want := range mustContain {
- if !strings.Contains(body, want) {
- t.Errorf("autopilots skill missing %q", want)
- }
- }
- if !skillHasFile(skill, "references/autopilots-source-map.md") {
- t.Errorf("autopilots skill missing supporting file references/autopilots-source-map.md")
- }
-}
-
-func TestRuntimesAndReposSkillCoversClaimAndCheckoutChain(t *testing.T) {
- skill, ok := findSkill(t, "multica-runtimes-and-repos")
- if !ok {
- return
- }
- fm, body, _ := splitFrontmatter(skill.Content)
-
- if got := strings.TrimSpace(fm["user-invocable"]); got != "false" {
- t.Errorf("user-invocable = %q, want false", got)
- }
- if got := strings.TrimSpace(fm["allowed-tools"]); !strings.Contains(got, "Bash(multica *)") {
- t.Errorf("allowed-tools = %q, want access to the Multica CLI", got)
- }
-
- mustContain := []string{
- "agent_task_queue",
- "daemon polls/claims the task",
- "multica runtime list --output json",
- "multica repo checkout <url>",
- "MULTICA_DAEMON_PORT",
- "resource_ref.ref",
- "github_repo",
- "local_directory",
- "Runtime and repo commands affect active agent execution",
- "references/runtimes-and-repos-source-map.md",
- // An agent reads this to know whether its checkout can be committed to.
- // Codex on Linux and Windows gets task-local Git metadata; every other
- // runtime gets a linked worktree (multica-ai/multica#2925, #6449).
- "Linux and Windows Codex",
- "task-local Git metadata",
- }
- for _, want := range mustContain {
- if !strings.Contains(body, want) {
- t.Errorf("runtimes-and-repos skill missing %q", want)
+func named(skills []AgentSkillData, name string) bool {
+ for _, s := range skills {
+ if s.Name == name {
+ return true
}
}
- if !skillHasFile(skill, "references/runtimes-and-repos-source-map.md") {
- t.Errorf("runtimes-and-repos skill missing supporting file references/runtimes-and-repos-source-map.md")
- }
+ return false
}
-func TestProjectsAndResourcesSkillCoversDurableContext(t *testing.T) {
- skill, ok := findSkill(t, "multica-projects-and-resources")
- if !ok {
- return
- }
- fm, body, _ := splitFrontmatter(skill.Content)
-
- if got := strings.TrimSpace(fm["user-invocable"]); got != "false" {
- t.Errorf("user-invocable = %q, want false", got)
- }
- if got := strings.TrimSpace(fm["allowed-tools"]); !strings.Contains(got, "Bash(multica *)") {
- t.Errorf("allowed-tools = %q, want access to the Multica CLI", got)
- }
-
- mustContain := []string{
- "Projects are durable context containers",
- ".multica/project/resources.json",
- "multica project resource list <project-id> --output json",
- "multica project resource add <project-id> --type github_repo --url <github-url> --output json",
- "multica project resource add <project-id> --type github_repo --url <github-url> --ref <branch-or-sha> --output json",
- "multica project resource add <project-id> --type local_directory",
- "Project resources are durable and affect future tasks",
- "github_repo.resource_ref.url",
- "resource_ref.ref",
- "references/projects-and-resources-source-map.md",
- }
- for _, want := range mustContain {
- if !strings.Contains(body, want) {
- t.Errorf("projects-and-resources skill missing %q", want)
- }
- }
- if !skillHasFile(skill, "references/projects-and-resources-source-map.md") {
- t.Errorf("projects-and-resources skill missing supporting file references/projects-and-resources-source-map.md")
- }
+// allBuiltinSkillsForTest includes the legacy redirect stubs. They are shipped
+// payload like any other built-in, so the template, frontmatter and
+// source-leak suites must hold for them as well.
+func allBuiltinSkillsForTest() []AgentSkillData {
+ return append(loadBuiltinSkillDirs(func(string) bool { return true }), legacyRedirectSkills()...)
}
func findSkill(t *testing.T, name string) (AgentSkillData, bool) {
t.Helper()
- for _, s := range loadBuiltinSkills() {
+ for _, s := range allBuiltinSkillsForTest() {
if s.Name == name {
return s, true
}
@@ -604,15 +816,6 @@ func findSkill(t *testing.T, name string) (AgentSkillData, bool) {
return AgentSkillData{}, false
}
-func skillHasFile(skill AgentSkillData, path string) bool {
- for _, f := range skill.Files {
- if f.Path == path {
- return true
- }
- }
- return false
-}
-
// splitFrontmatter returns the top-level scalar keys of a leading YAML
// frontmatter block, the body after it, and whether a block was found. It only
// understands flat `key: value` lines — enough for the template's frontmatter.
@@ -636,11 +839,13 @@ func splitFrontmatter(content string) (map[string]string, string, bool) {
if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
continue // nested value; the template uses only flat scalars
}
- key, val, found := strings.Cut(line, ":")
- if !found {
+ key, value, ok := strings.Cut(line, ":")
+ if !ok {
continue
}
- fm[strings.TrimSpace(key)] = strings.Trim(strings.TrimSpace(val), `"'`)
+ value = strings.TrimSpace(value)
+ value = strings.Trim(value, `"`)
+ fm[strings.TrimSpace(key)] = value
}
return fm, body, true
}
diff --git a/server/internal/service/skill_bundle_test.go b/server/internal/service/skill_bundle_test.go
index ea9be58b29..cbb01f19c4 100644
--- a/server/internal/service/skill_bundle_test.go
+++ b/server/internal/service/skill_bundle_test.go
@@ -28,11 +28,11 @@ func TestBuildAgentSkillBundlesProducesRefsAndFullBundles(t *testing.T) {
}
func TestBuildAgentSkillBundlesAssignsBuiltinID(t *testing.T) {
- _, refs := BuildAgentSkillBundles([]AgentSkillData{{Name: "multica-working-on-issues", Content: "body"}})
+ _, refs := BuildAgentSkillBundles([]AgentSkillData{{Name: "multica-platform", Content: "body"}})
if len(refs) != 1 {
t.Fatalf("refs = %d, want 1", len(refs))
}
- if refs[0].ID != "builtin:multica-working-on-issues" || refs[0].Source != "builtin" {
+ if refs[0].ID != "builtin:multica-platform" || refs[0].Source != "builtin" {
t.Fatalf("builtin ref = %+v", refs[0])
}
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 75eb2651e5..c9bef30c39 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -6662,12 +6662,12 @@ func (s *TaskService) skillsWithFiles(ctx context.Context, skills []db.Skill) ([
// It fails closed on a workspace-skill read error for the reason in
// LoadAgentSkills: a bundle set built from a partial read is indistinguishable
// from a correct one.
-func (s *TaskService) LoadAgentSkillBundles(ctx context.Context, agentID pgtype.UUID) ([]AgentSkillData, []AgentSkillRefData, error) {
+func (s *TaskService) LoadAgentSkillBundles(ctx context.Context, agentID pgtype.UUID, agentSystemKey string, legacyRedirects bool) ([]AgentSkillData, []AgentSkillRefData, error) {
skills, err := s.LoadAgentSkills(ctx, agentID)
if err != nil {
return nil, nil, err
}
- skills = append(skills, s.BuiltinSkills()...)
+ skills = append(skills, s.BuiltinSkills(agentSystemKey, legacyRedirects)...)
bundles, refs := BuildAgentSkillBundles(skills)
return bundles, refs, nil
}
@@ -6748,7 +6748,8 @@ func (s *TaskService) LoadRequestedAgentSkillBundles(ctx context.Context, agentI
}
}
if len(wantBuiltin) > 0 {
- for _, builtin := range s.BuiltinSkills() {
+ // Every built-in, not the agent-scoped subset — see AllBuiltinSkills.
+ for _, builtin := range s.AllBuiltinSkills() {
if _, ok := wantBuiltin[BuiltinSkillID(builtin.Name)]; ok {
requested = append(requested, builtin)
}
diff --git a/server/internal/service/task_agent_skills_test.go b/server/internal/service/task_agent_skills_test.go
index 30ac3f94a4..e410001f75 100644
--- a/server/internal/service/task_agent_skills_test.go
+++ b/server/internal/service/task_agent_skills_test.go
@@ -229,7 +229,7 @@ func TestLoadAgentSkillBundles_FailsClosedOnReadFailure(t *testing.T) {
}
svc := &TaskService{Queries: db.New(fake)}
- bundles, refs, err := svc.LoadAgentSkillBundles(context.Background(), testUUID(9))
+ bundles, refs, err := svc.LoadAgentSkillBundles(context.Background(), testUUID(9), "", false)
if err == nil {
t.Fatalf("LoadAgentSkillBundles returned nil error with %d bundles / %d refs", len(bundles), len(refs))
}
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index efeb977b2a..e2947f0495 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -36,6 +36,19 @@ const (
// server's missing fields make a newer daemon retain its short fallback.
DaemonCapabilityClaimPollHintsV1 = "claim-poll-hints-v1"
+ // DaemonCapabilityPlatformSkillV1 advertises that the daemon's runtime
+ // brief names the merged `multica-platform` skill instead of the
+ // per-domain built-ins it replaced (MUL-6986).
+ //
+ // The brief is assembled by the daemon, so a backend upgrade does not
+ // rewrite it: a daemon released before that merge still tells the agent to
+ // "read the `multica-working-on-issues` skill", a name this server no
+ // longer ships. Without this gate the pointer dangles and the agent is left
+ // hunting for a skill that is not installed. When it is absent the server
+ // ships a redirect stub under the old name; when it is present it ships
+ // nothing extra, so the stub retires itself as daemons update.
+ DaemonCapabilityPlatformSkillV1 = "platform-skill-v1"
+
// AppCapabilityChatDraftRestoreV1 is advertised (X-Client-Capabilities) by
// app clients that understand the durable draft-restore recovery path:
// chat:cancel_finalized as an invalidation hint plus the draft-restores