# Managed Skill

> Canonical path: `specs/skill/skill.md`
> Status: living product and architecture spec
> Scope: MeshX managed Skill resources, repository-backed Skill detail, repository scanning, and permission boundaries.

## 1. Purpose

Managed Skill is a MeshX workspace resource backed by an AGS repository. It is
the product surface for storing, browsing, importing, and maintaining reusable
agent skill instructions.

Managed Skill repositories are separate from portable role assets and agent-local runtime
state. Role materialization may consume skill assets, but the managed Skill
resource owns its metadata, grants, repository mapping, and repository-backed
detail surface.

## 2. Repository Model

Each managed Skill has one canonical repository. Product visibility and backing
repository storage are separate concerns. New user-facing Skill creation
defaults to personal repository storage unless the caller explicitly requests a
workspace storage scope.

```text
default personal storage:    <user_id>/<skill_slug>.sk
explicit workspace storage:  <workspace_id>/<skill_slug>.sk
```

The repository owner segment is always the owning user or workspace identity
itself. It must not carry a Skill-specific suffix such as `.sk`; the Skill
suffix belongs only to the repository name.

The product identity for a Skill slug is scoped by workspace, visibility scope,
and visibility owner. The backing repository full name is scoped by storage
owner and repository name. Product identities may differ while still requiring a
unique backing repository full name under the selected storage owner:

```text
alice private abc:        alice/abc.sk
bob private abc:          bob/abc.sk
workspace visible abc:    alice/abc.sk by default when Alice creates it
workspace-owned abc:      <workspace_id>/abc.sk only with explicit workspace storage
```

Within the same visibility owner, a slug remains unique. A single user cannot
create two private Skills with the same slug in one workspace, and a workspace
cannot have two workspace-visible Skills with the same slug. Within the same
storage owner, the canonical AGS repository full name must also remain unique.

Creation rules:

1. MeshX validates create permission.
2. MeshX resolves product visibility. Private visibility records the initiating
   user as visibility owner; workspace visibility records the workspace as
   visibility owner and creates a sparse workspace `view` grant.
3. MeshX resolves repository storage independently. If no storage scope is
   explicitly provided, the repository is stored under the initiating user's AGS
   owner. Explicit workspace storage stores it under the workspace AGS owner and
   is reserved for workspace-owned or system-created resources.
4. MeshX ensures the canonical repository under that storage owner.
5. MeshX initializes the repository with the Skill collection scaffold.
6. MeshX records the mapping in `resource_repositories`.
7. MeshX creates Skill metadata and the initiating user's owner grant. For
   workspace-visible Skills, MeshX also creates one workspace subject grant with
   `view` role. Any human AGS execution-plane access must be recorded as
   durable access intent and reconciled explicitly.

The Skill repository mapping must exist for a newly created Skill to be usable.
Repository identity lives in `resource_repositories`, not in ad hoc Skill fields
or inferred route names.

Repository lifecycle rules:

- MeshX mutates AGS repositories only through AGS APIs. It must not read or
  write AGS database tables directly for Skill repository lifecycle.
- Metadata updates do not rename, move, or infer repository identity.
  Repository identity remains the `resource_repositories` row until an explicit
  repository lifecycle operation changes it.
- Delete first deletes the managed AGS repository through the AGS repository API
  and only then removes Skill bindings, grants, repository mappings, and Skill
  metadata.
- If AGS deletion fails, MeshX must keep the Skill metadata and repository
  mapping so the operation can be retried.
- If AGS was changed but MeshX cannot persist cleanup, MeshX records the
  failure in `resource_repository_lifecycle_events` for compensation and
  operator repair.

## 3. Repository Layout

New managed Skill repositories are initialized as a collection scaffold. The
repository contains repository-level guidance and a `skills/` directory, but it
does not create a default skill from the repository name.

Canonical skill entries live under:

```text
skills/<skill-name>/SKILL.md
```

A skill entry may contain additional files and directories under the same skill
root. `SKILL.md` is the default landing document for that skill.

The scaffold is a writing scaffold only. Users may add, delete, rename, or
import skill entries after creation; repository content remains the source of
truth for Browse.

Importing skill content appends to the collection. Existing skill roots under
`skills/` remain in place unless the import contains the same skill name, in
which case the imported skill replaces that `skills/<skill-name>/` root. The
repository skill index and stored skill count must reflect the full valid skill
set after the append.

## 3.1 Built-in Official Skill Libraries

AgentTeam maintains an ordered catalog of workspace-owned, public-browseable
official Skill libraries. Each library has a reserved `(slug, created_by)`
identity, its own canonical repository, localized preset metadata and content,
an explicit expected Skill set, source metadata, a source fingerprint, and an
explicit `auto_agent_access` policy. A slug alone does not identify an official
library.

The catalog includes the AgentTeam-owned Workflow Plan authoring library plus pinned
third-party official libraries from Superpowers and Addy Osmani. The Workflow Plan authoring Skill is
distributed from `agentteam-workflow-plan-author-skills` and its workspace-owned
canonical repository. Third-party skills are bundled only when their source
and license permit redistribution.

Official materialization reserves the workspace-visible slug in the same scope
as the database uniqueness constraint before creating repository resources. A
private user-owned Skill may reuse the slug without becoming official; with
normal personal storage it does not block materialization. Repository-name
collisions from workspace storage still follow the existing repository
conflict checks. A workspace-visible slug collision is rejected before
official-library repository side effects.

Official libraries are materialized lazily when a Skill list, Skill-agent
binding list, or Skill agent-access batch request first needs them. The request
may include a template locale. MeshX normalizes that locale to the preset
locales (`en`, `zh-CN`, or `ja`) and uses it independently for each library's
first materialization:

- metadata such as name and description comes from that library's localized
  preset;
- imported `SKILL.md` and reference content comes from the matching localized
  preset files;
- unsupported, blank, or missing locales fall back to English.

Only one instance of each registered official library exists per workspace. If
a later request uses a different locale after a library has already been fully
materialized, MeshX must not rewrite that library's existing metadata or
content merely to match the later viewer. If a library exists but its detected
Skill count or source fingerprint no longer matches the registered catalog,
self-healing import may use the locale from the request that triggered repair.

Repository visibility repair, canonical mapping recovery, unreachable or empty
repository rebuild, and content re-import are performed independently for each
official library. A repair for one library must use that library's own
repository identity, archive, expected Skill set, and preserved locale.

Official libraries with `auto_agent_access=true` are included automatically in
the managed Skill access batch for every Agent owned by the caller. Official
libraries with `auto_agent_access=false` are visible in the Skill library UI
but are not exposed to an Agent runtime until the user explicitly binds that
library to the Agent. Manual binding and unbinding of read-only official
libraries is allowed for the caller's own Agents; editing, deleting, importing
content into, or changing grants for official libraries still requires manage
access and remains unavailable to ordinary workspace users. Ownership must be
verified before lazy materialization so an unauthorized request cannot trigger
official-library side effects.

Removing a library from the official registry is an authoritative retirement,
not a visibility change. On the next official list or Agent access refresh,
MeshX matches the retired resource by its exact reserved `(slug, created_by)`
identity, revokes bindings and grants, removes repository mappings, and
repository branch pins, then permanently deletes the Skill row. A user-created
Skill that reuses the old slug under another creator must remain untouched. AGS
repository deletion is best-effort and its failure is recorded, but it must
not block access revocation or the authoritative access response. An upgraded
daemon uses that response to remove the orphaned managed checkout and
manifest-owned runtime copies from Agent roots and persisted sessions.

## 4. Repository Scan

MeshX scans the Skill repository for `SKILL.md` files. Scan results include the
skill name, description, path, layout, status, issue code, and scan truncation
metadata. Scan and Browse contracts do not expose a skill version field; Skill
cards display the name and description only.

Valid scanned skills require frontmatter with a valid `name` and
`description`. The scanner rejects unsafe or ambiguous candidates such as
oversized `SKILL.md` files, symlinks, path traversal, invalid frontmatter,
missing name/description, and duplicate skill names.

The scan endpoint is Skill-specific. Memory Browse must not use Skill scanning.

Authorized consumers that materialize multiple managed Skill entries must read
them as one atomic batch from the canonical repository snapshot returned by the
Skill scan. The read request must include that scan's full commit SHA. MeshX
must verify the canonical repository still resolves to the expected commit,
perform one valid Skill scan, and return content only for paths accepted by
that scan. The response preserves the de-duplicated request order and identifies
the same commit.

The batch is fail-closed: an empty or oversized request, a missing or invalid
path, a symlink or traversal path, or a truncated scan rejects the entire read
without returning partial content. A changed commit returns a stable conflict
that requires the consumer to refresh the Skill scan; it must not return content
from the newer revision. Repository content reads remain behind the managed
Skill `view` grant, so a caller without product visibility receives the same
not-found result as other Skill reads before any repository access occurs.

## 5. Permissions And Agent Binding

Managed Skill access is fail-closed.

Human roles exposed by the product:

| Role     | View | Maintain content | Manage grants | Delete |
| -------- | ---- | ---------------- | ------------- | ------ |
| `owner`  | Yes  | Yes              | Yes           | Yes    |
| `manage` | Yes  | Yes              | Yes           | Yes    |
| `view`   | Yes  | No               | No            | No     |
| `none`   | No   | No               | No            | No     |

Skill is not a workspace catalog by default. New Skills default to private
visibility: workspace members inherit `none` / not-visible unless a Skill owner
or manager grants access. Workspace visibility is explicit creation-time product
visibility, represented by a sparse workspace subject grant with `view` role.
It must not be implemented by materializing grants for every workspace member.
`edit` is a legacy compatibility value and must not be shown in new UI or
created by new grants.
Human grants control Skill product visibility, product content maintenance, and
manage access only; direct human AGS repository access requires explicit durable
access intent. Agent access is not modeled as a generic
`skill_grants(subject_type=agent)` grant; it is modeled as explicit
Skill-agent bindings.

Human role precedence is:

1. creator / user owner role;
2. explicit user grant (`owner`, `manage`, or `view`);
3. workspace subject grant (`view`);
4. no access.

Skill Settings is visible only to `owner`, `manage`, or `canManage=true`
viewers. `view` users must not see a Settings tab or a disabled Settings page;
direct Settings URLs must replace to Browse.

Skill-agent binding rules:

- a single agent may be assigned multiple Skills;
- the same Skill-agent pair upserts idempotently when the branch is unchanged;
- only a Skill `owner` or `manage` actor can bind or unbind the actor's own agent;
- the binding stores an explicit branch, falling back to the canonical
  repository default branch and then `main` only when the caller omits one;
- a canonical Skill repository may be active on only one branch at a time within
  the workspace; binding the same repository on another branch must fail until
  the existing branch pin is removed.

AGS repository access is required for repository operations but does not replace
MeshX Skill grants or Skill-agent bindings. Skill AGS repositories are not
workspace-directory resources by default and are not listed as a generic
workspace catalog.

Self-demotion protection is required for browser-facing Skill permission writes.
When a workspace member changes their own Skill grant from a higher role to a
lower role, including `manage` to `view` and `view` to `none`, the UI must block
the write until the member explicitly confirms the downgrade. The confirmation
must explain that the member may lose Skill visibility, skill content
maintenance, grant management, role/materialization availability that depends on
the Skill, and any Skill-owned AGS repository materialization tied to durable
access intent; an owner or another manager may need to restore access later. The
API request must carry an explicit confirmation flag for the confirmed
submission, and the server must reject unconfirmed self-demotion attempts
defensively so the rule is identical to KB and Memory permission changes.

## 6. Skill Detail Surface

Managed Skill detail is a repository-backed product surface.

The product tabs are:

- **Browse / 浏览**: repository browser for skill content.
- **Settings / 设置**: manager-only Skill metadata, agent usage, member access,
  storage identity, and destructive actions.

Issue, merge request, and label management are not Skill product tabs. Opening a
Skill defaults to Browse.

Skill repository backup and restore is a manager-only detail action. Opening
the backup menu may list repository backups for that one Skill repository only;
the list must be paginated and must not enumerate backups for other workspace
Skills. Creating a backup records the current canonical repository branch as a
repository tag/release. Restoring a backup resets the canonical branch to that
backup's commit, then MeshX rescans the same repository to refresh Skill
metadata such as the detected Skill count.

Skill Settings keeps ordinary editing separate from read-only storage facts.
The General section edits only enabled state, display name, and description.
Agent usage shows owned-agent bindings; branch/version selection is only exposed
when more than one version is available or an existing binding is pinned to a
non-default version. Permissions controls member access. Storage and identity is
read-only and contains only product-level identifiers a user can reason about:
the user-facing URL slug and product visibility scope. Canonical repository path
and default branch are implementation details surfaced through explicit
repository actions such as Browse, clone, backup, and restore rather than the
ordinary settings form.

## 7. Browse Modes

Browse offers two left-column display modes:

- a skill-card view, which is the friendly default and renders one card per
  valid scanned skill;
- a raw directory tree, which preserves the underlying repository directory and
  filename view.

Each skill card displays the skill name and description. Clicking a skill card
opens that skill's `SKILL.md`. If the skill root contains only `SKILL.md`, the
card does not expand a child file list. If additional files or directories exist,
the card expands an inline subtree for that skill root.

When rendering `SKILL.md` through Browse, YAML frontmatter is hidden from the
Markdown preview. The selected skill name should be emphasized in the card row.
The raw directory tree remains available for users who need to inspect the exact
repository structure.

Browser routes are product-surface routes. The data layer may call AGS
repository APIs such as tree, commits, releases, and contents plus the
Skill-specific scan endpoint. This path/API decoupling is part of the product
contract.

## 8. Navigation

Skill routes:

```text
/skills
/skills/:skillId
/skills/:skillId/browse
/skills/:skillId/settings
```

Skills are a top-level workspace rail category positioned immediately above
Knowledge. Skill list and detail routes are workspace-scoped product surfaces
under the `/skills` route family.
The Skills sidebar exposes a `My skills` section with the current user's skill
libraries and an add action, followed by links for all, official templates,
and shared in workspace. The full Skills page still supports the
created-by-me filter for deep links and list views.
二级 Sidebar 的集合入口与“我的技能”条目必须互斥选中：当前详情对应“我的技能”
中的条目时，只高亮该技能；当前技能不在该列表中时，保留来源集合高亮。

Legacy `history` and `releases` route segments redirect to Browse.

When the user opens a Skill from another workspace surface:

- if a Skill has an active selection, the detail opens that Skill;
- otherwise the Skill landing surface opens the recent activity or list
  experience;
- the right-side content must not remain on an unrelated repository or previous
  resource detail.

Switching between Skills should preserve the detail shell and update content
with stable loading states instead of blanking the whole right-side surface.
技能详情 Header 复用 Workspace 的 Context Header：在同一行展示
`技能 / <技能名称> · <技能描述>`，过长的描述必须截断；管理操作使用紧凑的
图标按钮，并提供无障碍名称和悬停 Tooltip。
技能与智能体的绑定只在 Settings Tab 中管理，详情 Header 不提供重复入口。
Settings Tab 按“通用、权限、智能体使用、危险操作”的顺序展示；“智能体使用”
直接列出当前用户拥有的全部智能体，勾选即绑定技能，取消勾选即解除绑定，不提供
额外的“选择智能体并添加”流程。

## 9. Clean Boundary

Do not mix managed Skill with:

- agent-local runtime state;
- managed Memory Browse or Memory document-map behavior;
- role asset materialization as repository ownership;
- repository name inference as authority;
- generic repository issue, merge request, or label tabs as Skill product tabs.

The clean model is: reusable skill instructions live in MeshX Skill metadata,
Skill grants, Skill-agent bindings, `resource_repositories`, and AGS repository
content. Memory and Role may consume or reference Skills through explicit
product contracts, but they do not own Skill repository scanning or Skill detail
behavior.
