# https://github.com/s4b7-ai/s4b7-ai-skills 项目说明书

生成时间：2026-05-16 00:22:44 UTC

## 目录

- [Home - Repository Overview](#home)
- [Installation Guide](#installation)
- [Skill Structure & Anatomy](#skill-structure)
- [Skill Dependencies & Metadata](#skill-dependencies)
- [LangGraph Agent Development](#langgraph-agent)
- [AI SDK Core - Vercel Integration](#ai-sdk-core)
- [Agent Crystallization Protocol](#agent-cryst)
- [Write A Skill - Authoring Guide](#write-a-skill)
- [Crystallize - Pattern Extraction](#crystallize)
- [Skill Surgery R&D](#skill-surgery-rd)

<a id='home'></a>

## Home - Repository Overview

### 相关页面

相关主题：[Installation Guide](#installation), [Skill Structure & Anatomy](#skill-structure)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [skills/qmd-memory/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/qmd-memory/SKILL.md)
- [skills/codex-context/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/codex-context/SKILL.md)
- [skills/shadow-refactor/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-refactor/SKILL.md)
- [skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)
- [skills/codex-latex/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/codex-latex/SKILL.md)
- [skills/patent-queue/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/patent-queue/SKILL.md)
- [skills/shadow-engg/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-engg/SKILL.md)
- [skills/ai-sdk-core/references/v5-breaking-changes.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/v5-breaking-changes.md)
</details>

# Home - Repository Overview

## Introduction

The `s4b7-ai/s4b7-ai-skills` repository is a **skills library** designed to extend and automate AI agent capabilities across multiple domains. This repository serves as a central hub for specialized operational skills that enable AI systems (such as Codex, Claude, Gemini, and custom shadow agents) to perform complex tasks including memory management, code refactoring, patent processing, multi-model querying, and engineering intelligence.

The skills are structured as reusable, modular units that can be loaded by AI agents on demand based on contextual triggers. Each skill encapsulates domain-specific workflows, CLI commands, API integrations, and operational patterns.

资料来源：[skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)

---

## Repository Architecture

### Directory Structure

```
s4b7-ai-skills/
├── skills/
│   ├── qmd-memory/              # Memory extraction and management
│   ├── codex-context/           # Codex configuration and context
│   ├── shadow-refactor/         # Code refactoring automation
│   ├── write-a-skill/           # Skill creation framework
│   ├── codex-latex/             # LaTeX document generation
│   ├── patent-queue/            # Patent portfolio management
│   ├── multi-model-query/       # Multi-AI synthesis
│   ├── shadow-continuity/        # Long-term context preservation
│   ├── acp-delegate-auto/       # Task delegation routing
│   ├── command-center/          # Engineering workflow automation
│   ├── crystallize/             # Pattern extraction from sessions
│   ├── shadow-mcp-gadgets/      # MCP server federation
│   ├── shadow-patent-factory/   # Patent drafting automation
│   ├── shadow-engg/             # Engineering intelligence
│   ├── shadow-pi/               # CRUD operations framework
│   └── ai-sdk-core/             # AI SDK references
│       └── references/
│           └── v5-breaking-changes.md
```

资料来源：[skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)

### Skill Composition Pattern

Each skill follows a standardized structure for consistency:

| Component | Purpose | Location |
|-----------|---------|----------|
| `SKILL.md` | Primary definition with workflows, triggers, and commands | Root of skill directory |
| `scripts/` | Deterministic utility scripts | Optional, under skill directory |
| `references/` | Supporting documentation | Optional subdirectories |

资料来源：[skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)

---

## Skill Categories

### Memory & Context Management

| Skill | Purpose | Triggers |
|-------|---------|----------|
| `qmd-memory` | Memory extraction, storage, and recall with deduplication tracking | `memory`, `extract`, `remember` |
| `shadow-continuity` | Long-term context preservation across sessions | `continuity`, `context preservation` |
| `shadow-mcp-gadgets` | MCP server federation for unified context assembly | `esp.assemble`, `/renew-ctx` |

资料来源：[skills/qmd-memory/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/qmd-memory/SKILL.md), [skills/shadow-mcp-gadgets/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-mcp-gadgets/SKILL.md)

### Code Engineering

| Skill | Purpose | Triggers |
|-------|---------|----------|
| `shadow-refactor` | Automated refactoring with TDD loop | `refactor`, `patterns`, `hotspot` |
| `write-a-skill` | Framework for creating new skills | `write-a-skill`, `create skill` |
| `shadow-pi` | Standard CRUD operations for data | `crud`, `data operations` |

资料来源：[skills/shadow-refactor/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-refactor/SKILL.md), [skills/shadow-pi/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-pi/SKILL.md)

### Document & Patent Processing

| Skill | Purpose | Triggers |
|-------|---------|----------|
| `codex-latex` | LaTeX document compilation and formatting | `latex`, `pdf`, `document` |
| `patent-queue` | Patent portfolio tracking and synthesis | `patent`, `portfolio` |
| `shadow-patent-factory` | Automated patent drafting with SP-ID system | `factory.new`, `factory.draft` |

资料来源：[skills/codex-latex/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/codex-latex/SKILL.md), [skills/patent-queue/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/patent-queue/SKILL.md), [skills/shadow-patent-factory/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-patent-factory/SKILL.md)

### Multi-Model AI Orchestration

| Skill | Purpose | Triggers |
|-------|---------|----------|
| `acp-delegate-auto` | Intelligent task routing to AI providers | `delegate`, `route to` |
| `multi-model-query` | Synthesis across multiple AI models | `query`, `synthesize`, `compare` |

资料来源：[skills/acp-delegate-auto/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/acp-delegate-auto/SKILL.md), [skills/multi-model-query/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/multi-model-query/SKILL.md)

### Engineering & Business Operations

| Skill | Purpose | Triggers |
|-------|---------|----------|
| `shadow-engg` | Automotive competitive intelligence | `engineering`, `competitive intel` |
| `command-center` | Engineering workflow automation | `scar`, `ppap`, `upscaler` |
| `crystallize` | Pattern extraction from AI sessions | `crystallize`, `extract pattern` |

资料来源：[skills/shadow-engg/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-engg/SKILL.md), [skills/command-center/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/command-center/SKILL.md), [skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

---

## Core Workflow Patterns

### Universal Pipeline Architecture

Most skills follow a consistent operational pipeline:

```mermaid
graph TD
    A[Intent] --> B[Resolve Target]
    B --> C[Execute Operation]
    C --> D[Verify Result]
    D --> E[Report Findings]
    
    F[Artifact Routing] --> G[Report Storage]
    G --> H[ShadowArchive/80-reports/]
```

资料来源：[skills/codex-latex/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/codex-latex/SKILL.md)

### Fallback Chain Pattern

Skills implement a fallback chain to ensure resilience:

```mermaid
graph LR
    A[Primary Action] --> B{Failed?}
    B -->|Yes| C[Fallback 1]
    C --> D{Failed?}
    D -->|Yes| E[Fallback 2]
    E --> F{Failed?}
    F -->|Yes| G[Last Resort]
```

Common fallbacks include:
1. Primary CLI/tool execution
2. Static analysis or manual methods
3. Alternative API or local model (e.g., Ollama)
4. Inline summary generation

资料来源：[skills/shadow-refactor/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-refactor/SKILL.md), [skills/patent-queue/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/patent-queue/SKILL.md)

---

## AI Provider Integration

### Delegation Routing Heuristics

The `acp-delegate-auto` skill routes tasks based on keyword detection:

| Prompt Contains | Route To |
|----------------|----------|
| `write`, `implement`, `refactor`, `debug code` | codex |
| `research`, `summarize`, `find`, `compare` | gemini |
| `translate`, `JP`, `Japanese` | Codex |
| `local`, `private`, `no cloud` | ollama |
| `review`, `architect`, `design` | Codex |
| `quickly`, `fast`, `brief` | ollama |

### Model Selection

| Provider | Model | Use Case |
|----------|-------|----------|
| Codex (via MCP) | `Codex-sonnet-4-6` | Default complex tasks |
| Codex (via ACP) | `Codex-opus-4-6` | High complexity |
| Gemini (OpenRouter) | `google/gemini-2.0-flash-001` | Speed priority |
| Gemini (OpenRouter) | `google/gemini-2.5-pro` | Depth priority |
| Ollama (local) | `qwen3:8b` | Private, offline |

资料来源：[skills/acp-delegate-auto/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/acp-delegate-auto/SKILL.md)

---

## Memory System Architecture

### Memory Kinds and Tags

The `qmd-memory` skill supports structured memory classification:

```mermaid
graph TD
    A[Memory Store] --> B[Kinds]
    A --> C[Tags]
    
    B --> B1[fact]
    B --> B2[commitment]
    B --> B3[decision]
    B --> B4[preference]
    B --> B5[context]
    
    C --> C1[work]
    C --> C2[privacy]
    C --> C3[user-defined]
```

**CLI Commands:**
```bash
qmd-memory store "content" --kind fact --tag work
qmd-memory recall --kind fact --limit 5
qmd-memory extract notes.md --source-id "file:notes.md"
```

资料来源：[skills/qmd-memory/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/qmd-memory/SKILL.md)

---

## Patent Processing Pipeline

### Patent Lifecycle Management

```mermaid
graph LR
    A[Idea] --> B[SP-ID Assignment]
    B --> C[Specification Draft]
    C --> D[Claims Draft]
    D --> E[Prior Art Search]
    E --> F[Filing Guide]
    F --> G[Registry]
    G --> H[Obsidian Export]
    
    A1[Auto-Patent CLI] --> B
    H --> I[Portfolio README]
```

### Patent Artifact Routing

| Artifact | Path | Purpose |
|----------|------|---------|
| Filing drafts | `docs/patents/SP-NNN/` | Specification, claims, filing guide |
| Mining candidates | `ShadowArchive/10-projects/patent-queue/` | Candidate queue JSON |
| Obsidian dossiers | Obsidian vault | Filing review notes |
| Portfolio README | `docs/patents/README.md` | Auto-generated index |

资料来源：[skills/patent-queue/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/patent-queue/SKILL.md), [skills/shadow-patent-factory/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-patent-factory/SKILL.md)

---

## Skill Development Framework

### SKILL.md Template Structure

```yaml
---
name: skill-name
description: Brief description. Use when [specific triggers].
---

# Skill Name

## Quick start
[Minimal working example]

## Workflows
[Step-by-step processes]

## Advanced features
[References to separate files]
```

### Description Requirements

- Maximum 1024 characters
- Third person perspective
- First sentence: what it does
- Second sentence: when/triggers to use it

**Good example:**
> Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when user mentions PDFs, forms, or document extraction.

资料来源：[skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)

### Crystallization Process

The `crystallize` skill extracts patterns from AI sessions:

1. **Identify** — recognize valuable session patterns
2. **Draft** — create new skill or extend existing
3. **Log** — record metadata under `## Crystallized From`

```markdown
## Crystallized From
- Session: [date/context]
- Original task: [what was being solved]
- Pattern extracted: [description]
```

资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

---

## Artifact Routing System

### Global Artifact Paths

| Artifact Type | Path | Purpose |
|---------------|------|---------|
| Reports | `ShadowArchive/80-reports/` | Session summaries, scan results |
| Refactor signals | `tools/integrate/tool-signals.jsonl` | Per-fix JSONL results |
| Agent roots | `ShadowArchive/03-agent-roots/` | Agent configuration |
| Registry | `ShadowArchive/01-registry/` | Central registry |
| System controls | `system/controls/` or `config/system/` | Configuration changes |

### Output Rules by Layer

| Output Type | Format | Location |
|-------------|--------|----------|
| User-facing docs | Concise, structured markdown | Standard output |
| Machine-readable | YAML/JSON first | Canonical maps |
| Runtime scaffolds | Minimal but real | config/code |
| Skills | Reusable patterns | Skill directories |

资料来源：[skills/shadow-continuity/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-continuity/SKILL.md)

---

## Promotion Levels

Artifacts flow through maturity levels:

```mermaid
graph TD
    A[Note] --> B[Canonical Map]
    B --> C[Skill]
    C --> D[Runtime]
    
    A1[docs/plans/] --> A
    B1[YAML/JSON] --> B
    C1[~/.agents/skills/] --> C
    D1[Scaffold/Config] --> D
```

| Level | Storage | Authority |
|-------|---------|-----------|
| 1 - Note | `docs/plans/` or reports | Useful but not authoritative |
| 2 - Canonical Map | YAML/JSON files | Machine-readable truth |
| 3 - Skill | `~/.agents/skills/` | Reusable operator behavior |
| 4 - Runtime | Scaffold/config/code | Actually consumed by system |

资料来源：[skills/shadow-continuity/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-continuity/SKILL.md)

---

## Technical Standards

### AI SDK v5 Changes Reference

The `ai-sdk-core/references/v5-breaking-changes.md` documents breaking changes for Vercel AI SDK v5:

| Change | v4 | v5 |
|--------|----|----|
| Schema import | `zodSchema` | `tool` |
| Message types | `CoreMessage`, `Message` | `ModelMessage`, `UIMessage` |
| Error handling | `ToolExecutionError` | Regular errors as content parts |

资料来源：[skills/ai-sdk-core/references/v5-breaking-changes.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/v5-breaking-changes.md)

---

## Getting Started

### Loading Skills

AI agents automatically load skills based on trigger phrases in the user's request. Each skill's `description` field contains the triggers that activate it.

### Prerequisites

| Skill Category | Required Access |
|----------------|------------------|
| Shadow infrastructure skills | SHADOW infrastructure accessible |
| Mesh skills | Tailscale mesh connected |
| Patent skills | `auto-patent` CLI installed |
| Engineering skills | Caresoft API access |
| Local AI skills | Ollama running on localhost:11434 |

### Verification Commands

```bash
# Check Ollama availability
curl -s http://localhost:11434/api/tags | head -1

# Verify Shadow infrastructure
npm run verify:portable

# Run patent tests
cd auto-patent && node --test tests/*.test.js
```

---

## Related Documentation

- [Shadow Enterprise Architecture](skills/codex-context/SKILL.md)
- [Refactoring Best Practices](skills/shadow-refactor/SKILL.md)
- [Patent Filing Guide](skills/shadow-patent-factory/SKILL.md)
- [Multi-Model Synthesis](skills/multi-model-query/SKILL.md)
- [AI SDK Reference](skills/ai-sdk-core/references/v5-breaking-changes.md)

---

<a id='installation'></a>

## Installation Guide

### 相关页面

相关主题：[Home - Repository Overview](#home), [Skill Dependencies & Metadata](#skill-dependencies)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [package.json](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/package.json)
- [scripts/install.js](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/scripts/install.js)
- [skills/shadow-refactor/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-refactor/SKILL.md)
- [skills/shadow-mcp-gadgets/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-mcp-gadgets/SKILL.md)
- [skills/acp-delegate-auto/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/acp-delegate-auto/SKILL.md)
- [skills/qmd-memory/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/qmd-memory/SKILL.md)
</details>

# Installation Guide

## Overview

This repository (`s4b7-ai-skills`) is a collection of AI agent skills designed to extend the capabilities of various AI systems including Codex, Claude, Gemini, and local models via Ollama. Each skill is a self-contained module that provides specific functionality, from code refactoring to patent generation.

The installation process involves setting up the skill framework, configuring skill dependencies, and verifying that skills are properly registered and accessible to your AI agents. Skills are defined using YAML frontmatter in `SKILL.md` files with accompanying scripts and references.

## Prerequisites

### System Requirements

| Component | Minimum | Recommended |
|-----------|---------|-------------|
| Node.js | 18.x | 20.x+ |
| npm | 8.x | 10.x+ |
| Git | 2.x | Latest |
| Disk Space | 100MB | 500MB |

### Required Tools

Before installing skills, ensure the following tools are available:

- **Git** — Required for cloning repositories and version control operations 资料来源：[skills/shadow-refactor/SKILL.md:25]()
- **pytest/vitest/jest** — Test runners for verifying skill functionality 资料来源：[skills/shadow-refactor/SKILL.md:26]()
- **curl** — For checking local model availability (Ollama) 资料来源：[skills/shadow-refactor/SKILL.md:23]()

### External Services (Optional)

| Service | Purpose | Configuration |
|---------|---------|---------------|
| Ollama | Local LLM inference | `http://localhost:11434` |
| Tailscale | Mesh networking | Mesh nodes required |
| MCP Servers | Tool integrations | Per-skill configuration |

## Installation Steps

### Step 1: Clone the Repository

```bash
git clone https://github.com/s4b7-ai/s4b7-ai-skills.git
cd s4b7-ai-skills
```

### Step 2: Install Dependencies

Run the installation script to set up the skill framework:

```bash
npm install
```

This will install all required npm dependencies and prepare the skill infrastructure for use. The `package.json` defines the project dependencies and scripts available for skill management.

### Step 3: Configure Skill Paths

Skills are organized in a directory structure that AI agents traverse when loading capabilities. The default skill locations are:

| Location Type | Path | Purpose |
|---------------|------|---------|
| First-party | `/Volumes/☯Duality/skills/` | Primary skill collection |
| Vendor | `/Volumes/☯Duality/.agents/skills/` | Vendor-provided skills |
| User | `/Volumes/☯Duality/.pi/skills/` | Personal skill customizations |
| Project-level | `.agents/skills/` | Project-specific skills |

Ensure your AI agent's configuration points to one or more of these directories. For Codex integration, configure `~/.codex/config.toml` with the appropriate skill paths.

### Step 4: Verify Portability

Check that all skill symlinks and references are valid:

```bash
npm run verify:portable
```

This command validates that skills can be loaded correctly from their configured paths.

## Skill Structure

Each skill follows a standardized structure:

```
skill-name/
├── SKILL.md          # Main skill definition with YAML frontmatter
├── REFERENCE.md      # Detailed reference documentation (optional)
├── scripts/          # Utility scripts (optional)
│   └── helper.js
└── tests/            # Test files (optional)
    └── skill.test.js
```

### SKILL.md Format

Every skill requires a `SKILL.md` file with this frontmatter structure:

```yaml
---
name: skill-name
description: Brief description. Use when [specific triggers].
---
```

**Description Requirements:**
- Maximum 1024 characters
- Written in third person
- First sentence: what it does
- Second sentence: when to trigger it (specific keywords, contexts, file types)

**Good example:**
```
Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when user mentions PDFs, forms, or document extraction.
```

资料来源：[skills/write-a-skill/SKILL.md:45-52]()

## CLI Commands

### qmd-memory (Memory Management)

| Command | Description |
|---------|-------------|
| `qmd-memory store "text" --kind fact --tag work` | Store a memory item |
| `qmd-memory recall` | List all memories |
| `qmd-memory recall --kind fact` | Filter by kind |
| `qmd-memory extract notes.md --source-id "file:notes.md"` | Extract from file |
| `qmd-memory profile` | Show user profile |

Memory kinds: `fact`, `commitment`, `decision`, `preference`, `context`

资料来源：[skills/qmd-memory/SKILL.md:20-40]()

### shadow-patents (Patent Generation)

| Command | Description |
|---------|-------------|
| `shadow-patents list` | List portfolio |
| `shadow-patents status` | Filing readiness dashboard |
| `shadow-patents show SP-025` | Detailed view |
| `shadow-patents create "Title"` | Scaffold new patent |
| `shadow-patents register SP-025` | Add to registry |

资料来源：[skills/shadow-patent-factory/SKILL.md:85-95]()

### upscaler (Command Center)

| Command | Description |
|---------|-------------|
| `npm run upscaler_action_read` | Review action drafts |
| `npm run upscaler_actions` | List all actions |
| `upscaler_draft` MCP tool | Generate SCAR notification |
| `upscaler_tune mode: status` | Check tuning metrics |
| `upscaler_tune mode: run` | Full tuning cycle |

Dashboard access:
- **FRIDAY**: http://friday-mac:3333/
- **Local**: `cd ~/wip/ai-at-work && ./bin/upscaler dashboard`

资料来源：[skills/command-center/SKILL.md:45-65]()

## MCP Server Integration

The repository supports multiple MCP (Model Context Protocol) servers for extended functionality:

| MCP Server | Path | Purpose |
|------------|------|---------|
| RepoPrompt | `/Users/sdluffy/RepoPrompt/repoprompt_cli` | Repository intelligence |
| chrome_devtools | `/Users/sdluffy/bin/chrome-devtools-mcp-work` | Browser automation |
| notion | `https://mcp.notion.com/mcp` | Notion integration |
| openevidence | `node .../openevidence-mcp/dist/server.js` | Evidence management |
| playwright | `/Users/sdluffy/bin/playwright-mcp-work` | Web testing |

资料来源：[skills/codex-context/SKILL.md:25-32]()

## Gadget System

The shadow-mcp-gadgets skill provides a unified interface to various subsystems:

| Gadget | Trigger | Purpose |
|--------|---------|---------|
| ARC | `arc.store`, `arc.search` | Memory storage and retrieval |
| ESP | `esp.assemble`, `/renew-ctx` | Context assembly |
| ANT | `ant.mesh` | Fleet health via Tailscale |
| TAP | `tap.tabs`, `tap.execute` | Chrome tabs + JavaScript |
| OWL | `owl.brief`, `owl.extract` | Bee AI extraction |
| ORB | `orb.say`, `orb.voices` | macOS TTS |
| DEN | `den.environment` | Physical sensors |
| Factory | `factory.new`, `factory.draft` | Patent pipeline |

If the MCP federation server is not running, start it via:
```bash
bun run /Volumes/SHADOW/shadow-lab/apps/shadow-mcp
```

资料来源：[skills/shadow-mcp-gadgets/SKILL.md:20-35]()

## Auto-Delegation Configuration

The `acp-delegate-auto` skill routes tasks to appropriate AI providers based on content analysis:

### Routing Heuristics

| If prompt contains... | Route to |
|----------------------|----------|
| `write`, `implement`, `refactor`, `debug code` | codex |
| `research`, `summarize`, `find`, `compare` | gemini |
| `translate`, `JP`, `Japanese` | Codex |
| `local`, `private`, `no cloud` | ollama |
| `review`, `architect`, `design` | Codex |
| `quickly`, `fast`, `brief` | ollama |
| file paths, diffs, PRs | codex |

### Provider Configuration

```bash
# Qwen3 (Ollama): prepend /no_think to prompt
# Codex: use mcp__codex__codex tool with workdir set

# Gemini via OpenRouter:
# - Speed: google/gemini-2.0-flash-001
# - Depth: google/gemini-2.5-pro

# Codex via ACP:
# - Default: Codex-sonnet-4-6
# - Complex: Codex-opus-4-6
```

资料来源：[skills/acp-delegate-auto/SKILL.md:15-40]()

## Verification

After installation, verify your setup:

### 1. Check Skill Loading

```bash
# List all available skills
ls skills/*/SKILL.md
```

### 2. Test Skill Execution

```bash
# Run skill validation tests
cd auto-patent && node --test tests/*.test.js
```

All tests should pass. For patent-related skills, ensure all 44 auto-patent tests pass before considering the installation complete.

### 3. Verify Agent Configuration

Ensure your AI agent's configuration file (e.g., `~/.codex/config.toml` for Codex) references the correct skill directories.

## Troubleshooting

### Symlink Failures

If portability verification fails, check symlink integrity:
```bash
npm run verify:portable
```

### Skill Not Loading

1. Verify the `SKILL.md` file has valid YAML frontmatter
2. Check that the skill directory is in the agent's search path
3. Ensure description includes proper trigger keywords

### MCP Server Connection Issues

If gadgets are unavailable, start the shadow-mcp federation server:
```bash
bun run /Volumes/SHADOW/shadow-lab/apps/shadow-mcp
```

### Ollama Not Responding

Check if Ollama is running:
```bash
curl -s http://localhost:11434/api/tags | head -1
```

If unavailable, the system falls back to static analysis mode using grep, AST, and file metrics.

## Skill Surgery & Maintenance

For managing existing skills:

| Operation | Purpose |
|-----------|---------|
| Audit skills | `audit-skills.mjs` — inventory all skills |
| Cluster triggers | `cluster-skill-triggers.mjs` — analyze trigger patterns |
| Redirect deprecated | `redirect-deprecated-skill.mjs` — handle outdated skills |

**Important Rules:**
- Never delete skills during exploratory surgery; redirect instead
- Circular redirects (A → B → A) must be blocked and reported
- Preserve operator-specific boundaries when consolidating enterprise skills

资料来源：[skills/skill-surgery-rd/SKILL.md:30-45]()

## Related Documentation

- [Write a Skill Guide](skills/write-a-skill/SKILL.md) — How to create new skills
- [Shadow Refactor](skills/shadow-refactor/SKILL.md) — Code analysis and refactoring
- [Memory System](skills/qmd-memory/SKILL.md) — Persistent agent memory
- [Codex Context](skills/codex-context/SKILL.md) — Codex integration details
- [A2A Orchestrator](skills/a2a-orchestrator/SKILL.md) — Multi-agent orchestration

---

<a id='skill-structure'></a>

## Skill Structure & Anatomy

### 相关页面

相关主题：[Home - Repository Overview](#home), [Write A Skill - Authoring Guide](#write-a-skill), [Skill Dependencies & Metadata](#skill-dependencies)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)
- [skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)
- [skills/shadow-mcp-gadgets/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-mcp-gadgets/SKILL.md)
- [skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)
- [skills/acp-delegate-auto/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/acp-delegate-auto/SKILL.md)
- [skills/shadow-refactor/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-refactor/SKILL.md)
- [skills/qmd-memory/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/qmd-memory/SKILL.md)
</details>

# Skill Structure & Anatomy

## Overview

A **Skill** is a reusable capability module that encapsulates domain-specific knowledge, workflows, and decision-making patterns for an AI agent. Skills enable agents to perform specialized tasks by providing structured guidance on when and how to apply particular capabilities.

Skills serve as the atomic unit of agentic capability—each skill contains sufficient information for an agent to recognize when it should be invoked and how to execute the associated workflow. The skill system supports a modular architecture where skills can be composed, extended, and shared across different agent contexts.

## Core Anatomy of a Skill

Every skill is fundamentally defined by its metadata and operational content. The minimal viable skill consists of YAML frontmatter and a Markdown body that describes the capability.

### YAML Frontmatter

The frontmatter uses a standardized schema to ensure parsers and agents can reliably extract skill metadata:

```yaml
---
name: skill-name
description: Brief description of capability. Use when [specific triggers].
---
```

**Required Fields:**

| Field | Type | Purpose | Constraints |
|-------|------|---------|-------------|
| `name` | string | Unique identifier for the skill | Lowercase, hyphenated |
| `description` | string | Triggers and summary for agent selection | Max 1024 chars, third person, must include "Use when..." |

**Description Format Requirements:**

The description serves as the primary signal for skill routing. It must:

1. Start with a first sentence describing what the skill does
2. Include a second sentence beginning with "Use when..." followed by specific trigger phrases
3. Be written in third person
4. Be concise enough for the agent to quickly evaluate relevance

**Good Example:**
```
Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when user mentions PDFs, forms, or document extraction.
```

**Poor Example:**
```
Helps with documents.
```

资料来源：[skills/write-a-skill/SKILL.md:47-56]()

### Markdown Body Structure

The SKILL.md file contains the operational content organized into logical sections:

```markdown
# Skill Name

One-line description. Use when [trigger phrases].

## When to Use
- [trigger 1]
- [trigger 2]
- [trigger 3]

## Workflow
1. [Step 1]
2. [Step 2]
3. [Step 3]

## Key Decisions
- [Decision point 1]: [default choice + why]
- [Decision point 2]: [default choice + why]

## Gotchas
- [Common mistake 1]
- [Common mistake 2]

## Crystallized From
- Session: [date/context]
- Original task: [what was being solved]
```

资料来源：[skills/crystallize/SKILL.md:1-24]()

## Skill Directory Structure

Skills follow a predictable directory layout that enables both human navigation and programmatic discovery:

```
~/.agents/skills/<skill-name>/
├── SKILL.md              # Primary skill definition (REQUIRED)
├── REFERENCE.md          # Extended reference documentation
├── scripts/              # Utility scripts (if needed)
│   └── helper.js
└── docs/                 # Additional documentation
    └── plans/
        └── crystallization-log.md
```

**First-party skills** are located at `/Volumes/☯Duality/skills/`

**Vendor skills** are located at `/Volumes/☯Duality/.agents/skills/`

**Project-specific skills** follow the pattern `.agents/skills/` within the project root

资料来源：[skills/codex-context/SKILL.md:12-18]()

## Skill Lifecycle

### Crystallization Mode

The primary mechanism for creating skills is **crystallization**—extracting reusable patterns from completed work sessions into structured skill definitions.

```mermaid
graph TD
    A[Ticket/Task Received] --> B[Session Work Begins]
    B --> C{Task Complete?}
    C -->|No| D[Continue Working]
    D --> C
    C -->|Yes| E{Should this recur?}
    E -->|No| F[Done]
    E -->|Yes| G[Review Session]
    G --> H[Extract Pattern]
    H --> I{Check Scope}
    I --> J{Search existing skills}
    J -->|Overlap found| K[Update Existing Skill]
    J -->|No overlap| L[Create New Skill]
    K --> M[Log Crystallization]
    L --> M
```

**Crystallization Modes:**

| Mode | Output | Trigger Phrases |
|------|--------|-----------------|
| `default` | Full crystallization workflow | `crystallize`, `capture this as a skill` |
| `quick` | Fast capture to minimal stub | `quick crystallize`, mid-task pattern discovery |
| `exploratory` | Expand one ring outward from fix | `--exploratory-mode`, `more crystallization` |
| `drag-response` | Immediate crystallization | `this took too long`, `why aren't you using...` |
| `correction` | Immediate update from operator | Operator corrects an identity/path/boundary |
| `audit` | Check missed patterns | `what patterns did we miss` |

资料来源：[skills/crystallize/SKILL.md:65-79]()

### Exploratory-Mode Expansion

When crystallizing in exploratory mode, the process expands beyond the immediate fix to capture broader patterns:

1. Start from the exact thing that was fixed
2. Check nearest adjacent surfaces that could carry the same pattern
3. Capture the broader reusable rule
4. Log what surfaces were checked and which were intentionally left untouched

## Skill Components

### Workflow Section

The workflow section defines the step-by-step process for executing the skill. Each workflow should:

- Start with the minimal steps required
- Include decision points as checkpoints
- Provide clear success criteria
- Be deterministic enough for reliable execution

**Workflow Format:**

```markdown
## Workflow

```dot
digraph workflow_name {
  rankdir=TB;
  "Start" -> "Step 1" -> "Step 2" -> "Decision Point" -> "End"
  "Decision Point" -> "Alt Path A" [label="Condition A"]
  "Decision Point" -> "Alt Path B" [label="Condition B"]
}
```

### Decision Points

Critical decision points should be documented with:

- The decision context
- Available options
- Default choice and rationale
- When to deviate from default

**Decision Point Format:**

```markdown
## Key Decisions

- [Decision point 1]: [default choice + why]
- [Decision point 2]: [default choice + why]
```

### Gotchas Section

The gotchas section captures lessons learned from real usage:

- Common mistakes that cause failures
- Assumptions that often fail
- Edge cases requiring special handling
- Configuration traps

## Skill Routing and Invocation

### Routing Heuristics

Skills are selected based on trigger detection in the agent's context. The routing system uses keyword matching against skill descriptions:

| If prompt contains... | Route to |
|----------------------|----------|
| `write`, `implement`, `refactor`, `debug code` | codex |
| `research`, `summarize`, `find`, `compare` | gemini |
| `translate`, `JP`, `Japanese` | Codex |
| `local`, `private`, `no cloud` | ollama |
| `review`, `architect`, `design` | Codex |
| `quickly`, `fast`, `brief` | ollama |
| file paths, diffs, PRs | codex |

资料来源：[skills/acp-delegate-auto/SKILL.md:24-35]()

### Trigger Phrase Format

Skill descriptions must include trigger phrases in the "Use when..." section:

```markdown
## When to Use
- [trigger 1]
- [trigger 2]
- [trigger 3]
```

These triggers are matched against incoming agent context to determine skill relevance.

## Skill Validation and Quality

### Review Checklist

Before finalizing a skill, verify:

- [ ] Description includes triggers ("Use when...")
- [ ] SKILL.md under 100 lines
- [ ] No time-sensitive info (no dates, version numbers that will stale)
- [ ] Consistent terminology throughout
- [ ] Concrete examples included
- [ ] References one level deep (no deep-linking to unrelated docs)

资料来源：[skills/write-a-skill/SKILL.md:85-91]()

### File Size Guidelines

| Condition | Action |
|-----------|--------|
| SKILL.md exceeds 100 lines | Split into separate files |
| Content has distinct domains | Split into domain-specific files |
| Advanced features are rarely needed | Reference separate REFERENCE.md |
| Content is deterministic/formatting | Add utility scripts instead |

资料来源：[skills/write-a-skill/SKILL.md:74-81]()

## Skill Surgery and Maintenance

### When to Perform Surgery

Skills require maintenance when:

- Overlapping capabilities exist across multiple skills
- Triggers become stale or misaligned with actual usage
- Skills grow too large (violates 100-line guideline)
- Domain boundaries shift requiring re-organization

### Surgery Operations

| Operation | Purpose | Command Pattern |
|-----------|---------|-----------------|
| `audit` | Inventory all skills and their triggers | `skill_audit` |
| `cluster` | Group skills by trigger overlap | `cluster-skills` |
| `redirect` | Move deprecated skill to canonical location | `redirect-deprecated-skill` |

### Redirect Chain

When a skill is deprecated:

1. Do not delete the old skill
2. Create redirect metadata pointing to canonical location
3. Log the redirect for audit trail
4. Update any skills that reference the deprecated path

**Contract:** Do not delete skills during exploratory surgery. Redirect first; deletion requires explicit operator approval after review.

资料来源：[skills/skill-surgery-rd/SKILL.md:67-73]()

## Artifact Routing

Skills generate artifacts that follow a consistent routing pattern:

| Artifact Type | Path Pattern | Purpose |
|---------------|--------------|---------|
| New skill | `~/.agents/skills/<slug>/SKILL.md` | Reusable capability |
| Updated skill | Same path as existing skill | Extended capability |
| Crystallization log | `docs/plans/crystallization-log.md` | History of all crystallizations |
| Reports | `ShadowArchive/80-reports/` | Session summaries |
| Tool signals | `tools/integrate/tool-signals.jsonl` | Per-fix results |

资料来源：[skills/crystallize/SKILL.md:80-91]()

## Integration with Agent Memory

Skills can be integrated with persistent memory systems:

### Memory Kinds

| Kind | Purpose | Example |
|------|---------|---------|
| `fact` | Permanent facts | "TypeScript is the primary language" |
| `commitment` | Future tasks | "Need to finish setup by Friday" |
| `decision` | Choices made | "Decided to use local-first" |
| `preference` | User preferences | User prefers dark mode |
| `context` | Session context | Current project state |

### Memory Extraction Pipeline

Skills can trigger memory extraction through the `qmd-memory` interface:

```bash
# Extract from text
qmd-memory extract notes.md --source-id "file:notes.md"

# From piped data
bee conversations get <id> --json | jq -r '.summary' | qmd-memory extract - --source-id "bee:conv:<id>"
```

资料来源：[skills/qmd-memory/SKILL.md:1-35]()

## Multi-Model Skill Distribution

Skills can delegate execution to specialized models based on task requirements:

```mermaid
graph LR
    A[Intent] --> B{Route Decision}
    B -->|Code| C[Codex]
    B -->|Research| D[Gemini]
    B -->|Local| E[Ollama]
    B -->|Synthesis| F[Multi-Model]
    C --> G[Execute]
    D --> G
    E --> G
    F --> G
```

### Provider-Specific Preparation

Before delegating, apply model-specific transforms:

| Provider | Transform |
|----------|-----------|
| `qwen3` (any Ollama model) | Prepend `/no_think` to prompt or set `options.think = false` |
| `codex` (mcp) | Use `mcp__codex__codex` tool with workdir set to current project |
| `gemini` (openrouter) | Use `google/gemini-2.0-flash-001` for speed, `google/gemini-2.5-pro` for depth |
| `Codex` (ACP anthropic) | Use `Codex-sonnet-4-6` default, `Codex-opus-4-6` for complex tasks |

## Fallback Chain Pattern

Robust skills implement a fallback chain for resilience:

```
1. Primary: Full scan/operation
2. Degraded: Local paths only
3. Offline: Skip unreachable, continue with available
4. API unavailable: Report; proceed with manual or cached
5. Empty: Report; note likely path issue
6. Last resort: Minimal coverage with explicit statement of degradation
```

Each failure mode should have a documented recovery action that allows the skill to continue or gracefully report inability.

## Relationship to Agent Infrastructure

### Skill Discovery Order

For context-based skills, the read order defines precedence:

1. `/Volumes/☯Duality/AGENTS.md` — master control surface
2. `reference/SHADOW-CONTEXT.md` — quick paths and fleet
3. `reference/ARCHITECTURE.md` — layered architecture
4. `reference/SHADOW-ARCHITECTURE-SPEC.md` — full spec
5. `reference/VERIFIABILITY.md` — proof-of-work rules
6. `docs/reference/SHADOW-DUALITY-ORGANIZATION.md` — rings + artifact resolution

### Skills Namespace

All skills feed into the same namespace regardless of origin:

- **First-party:** `/Volumes/☯Duality/skills/`
- **Vendor:** `/Volumes/☯Duality/.agents/skills/`
- **Project-specific:** `.agents/skills/`
- **Enterprise:** Appropriate subdirectory under `~/.agents/skills/`

This unified namespace allows agents to discover and invoke any skill regardless of its origin point.

## Best Practices Summary

1. **Trigger Clarity:** Always include "Use when..." clause with specific trigger phrases
2. **Size Discipline:** Keep SKILL.md under 100 lines; extract to REFERENCE.md for extended content
3. **Deterministic Scripts:** Use utility scripts for repetitive, predictable operations
4. **Crystallization Logging:** Record session date, context, and pattern extracted
5. **No Stale Data:** Avoid version numbers, pricing, or API shapes that will become outdated
6. **Preserve History:** Never delete skills; redirect deprecated ones
7. **Single Responsibility:** One skill = one capability; split when domains diverge
8. **Citation:** Reference source patterns when extracting from other skills

---

<a id='skill-dependencies'></a>

## Skill Dependencies & Metadata

### 相关页面

相关主题：[Skill Structure & Anatomy](#skill-structure), [Crystallize - Pattern Extraction](#crystallize)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)
- [skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)
- [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)
- [skills/shadow-engg/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-engg/SKILL.md)
- [skills/shadow-refactor/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-refactor/SKILL.md)
- [skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)
- [skills/qmd-memory/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/qmd-memory/SKILL.md)
- [skills/shadow-mcp-gadgets/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-mcp-gadgets/SKILL.md)
</details>

# Skill Dependencies & Metadata

## Overview

The s4b7-ai-skills repository implements a structured approach to skill documentation that encompasses metadata standards, dependency management, and artifact routing. Each skill follows a consistent SKILL.md template that defines its purpose, trigger conditions, workflows, and integration points with other system components.

The metadata system serves three core purposes: enabling agent-based skill selection through descriptive frontmatter, establishing clear execution workflows with fallback chains, and routing artifacts to appropriate storage locations for persistence and retrieval.

## Skill Metadata Structure

### Frontmatter Schema

Every skill in the repository begins with YAML frontmatter that defines its identity and selection criteria. The required metadata fields ensure proper agent routing and discovery.

| Field | Purpose | Constraints |
|-------|---------|-------------|
| `name` | Skill identifier | Unique within skill namespace |
| `description` | Capability summary for agent selection | Max 1024 chars, third person, must include "Use when..." clause |
| `triggers` | Keywords and contexts that activate the skill | Extracted from description for matching |

资料来源：[skills/write-a-skill/SKILL.md:1-20]()

### Description Requirements

The description field is the primary mechanism by which agents decide which skill to load. It must follow a strict two-sentence format:

1. **First sentence**: States what the skill does
2. **Second sentence**: Contains the "Use when..." clause specifying trigger conditions

Example of a well-formed description:

```
Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when user mentions PDFs, forms, or document extraction.
```

资料来源：[skills/write-a-skill/SKILL.md:52-56]()

The description is surfaced in the system prompt alongside all other installed skills, allowing the agent to pick the relevant skill based on the user's request. This makes the description the single most important metadata element for skill discoverability.

### Skill Kinds and Tags

The `qmd-memory` skill implements a tagging system for memory classification that can be applied to skill metadata:

| Kind | Usage |
|------|-------|
| `fact` | Permanent factual information |
| `commitment` | Promises or obligations |
| `decision` | Choices made during execution |
| `preference` | User or system preferences |
| `context` | Session-specific context |

Tags provide additional dimension to skill metadata, enabling filtering and targeted recall.

资料来源：[skills/qmd-memory/SKILL.md:45-52]()

## Skill Modes and Command Routing

### Mode Architecture

Skills expose multiple operational modes that define different execution paths. The mode system allows a single skill to handle diverse use cases through command-based routing.

```mermaid
graph TD
    A[User Input] --> B{Mode Detection}
    B -->|default| C[Standard Execution]
    B -->|verbose| D[Detailed Diagnostics]
    B -->|json| E[Machine Output]
    B -->|background| F[Autonomous Loop]
    
    C --> G[Primary Handler]
    D --> H[Debug Handler]
    E --> I[Parse Handler]
    F --> J[Background Agent]
    
    G --> K[Result Output]
    H --> K
    I --> K
    J --> K
```

资料来源：[skills/codex-latex/SKILL.md:35-48]()

### Mode Reference by Skill

| Skill | Modes | Purpose |
|-------|-------|---------|
| `ai-sdk-core` | migrate, agent, error, workers, verify | AI SDK v5/v6 lifecycle management |
| `shadow-engg` | explore, engineering | Competitive intelligence and gap analysis |
| `shadow-refactor` | background, patterns, hotspot, equilibrium | Code refactoring and pattern extraction |
| `shadow-mcp-gadgets` | memory, context, mesh, browser, ambient, voice, environment, patent, test | MCP tool delegation |

资料来源：[skills/shadow-engg/SKILL.md:1-30](), [skills/shadow-refactor/SKILL.md:1-15](), [skills/shadow-mcp-gadgets/SKILL.md:1-20]()

## Artifact Routing System

### Artifact Types

Artifacts are outputs produced during skill execution that require persistent storage. Each skill defines a routing table specifying where artifacts should be stored.

| Artifact Type | Path Pattern | Purpose |
|--------------|--------------|---------|
| Tool signals | `tools/integrate/tool-signals.jsonl` | Per-fix results in JSONL format |
| Refactor reports | `ShadowArchive/80-reports/refactor-<target>-YYYY-MM-DD.md` | Session summaries |
| Memory stores | `ARC memory store` | Persistent agent memory |
| Patent drafts | `docs/patents/SP-NNN/` | Specification and claims |

资料来源：[skills/shadow-refactor/SKILL.md:15-22](), [skills/shadow-mcp-gadgets/SKILL.md:22-28]()

### Artifact Routing Table Format

Skills implement artifact routing through structured tables in SKILL.md:

```
| Artifact | Location | Purpose |
|----------|----------|---------|
| Code changes | Project files (inline) | Implementation output |
| Detailed reference | `REFERENCE.md` (skill companion) | Migrations, errors, model notes |
| Original backup | `data/skill-rd/active-split-backups/` | Pre-split archive |
```

资料来源：[skills/ai-sdk-core/SKILL.md:28-33]()

## Fallback Chain Architecture

### Fallback Principles

Every skill implements a fallback chain that defines recovery behavior when primary execution paths fail. The chain prioritizes available alternatives in order of preference.

```mermaid
graph LR
    A[Primary] --> B[Secondary]
    B --> C[Tertiary]
    C --> D[Last Resort]
    
    style A fill:#90EE90
    style B fill:#FFE4B5
    style C fill:#FFA07A
    style D fill:#FF6B6B
```

### Fallback Chain Examples

**ai-sdk-core Fallback Chain:**

| Priority | Source | Condition |
|----------|--------|-----------|
| 1 | `REFERENCE.md` | Detailed reference available |
| 2 | Web search / docs | REFERENCE.md stale or missing |
| 3 | `npm view ai versions` | Version uncertainty |
| 4 | Stable v5 default | All else fails |

资料来源：[skills/ai-sdk-core/SKILL.md:35-42]()

**shadow-engg Fallback Chain:**

| Priority | Mode | Condition |
|----------|------|-----------|
| 1 | Full scan | ShadowArchive mounted, skills accessible |
| 2 | Local-only | Archive unmounted |
| 3 | Skip mesh health | Tailscale mesh unreachable |
| 4 | Report API status | Caresoft API unavailable |

资料来源：[skills/shadow-engg/SKILL.md:55-68]()

**skill-surgery-rd Error Handling:**

| Failure | Recovery |
|---------|----------|
| Script execution fails | Manual `find + grep` inventory |
| Malformed YAML frontmatter | Flag; propose manual repair |
| Circular redirect detected | Block; require manual resolution |
| Too many skills (>500) | Prioritize active; sample archived |

资料来源：[skills/skill-surgery-rd/SKILL.md:45-55]()

## Skill Dependencies and Interconnections

### Crystallization Workflow

The crystallization process creates dependencies between skills by extracting patterns from working sessions into reusable skill definitions.

```mermaid
graph TD
    A[Task Complete] --> B{Should this recur?}
    B -->|yes| C[Review Session]
    B -->|no| D[Done]
    C --> E[Extract Pattern]
    E --> F[Check Scope]
    F --> G{Search Existing Skills}
    G -->|overlap found| H[Update Existing]
    G -->|no overlap| I[Create New Skill]
    H --> J[Log Crystallization]
    I --> J
```

资料来源：[skills/crystallize/SKILL.md:55-78]()

### Exploratory-Mode Expansion

When operators request expanded crystallization, the skill performs a broader sweep:

1. Start from the exact thing that was fixed
2. Check nearest adjacent surfaces that could carry the same stale assumption
3. Capture the broader reusable rule

资料来源：[skills/crystallize/SKILL.md:75-85]()

### Skill Surgery and Dependencies

The `skill-surgery-rd` skill manages skill dependencies through audit and repair operations. Key operations include:

- **Audit**: Scan skill directories for stale metadata, circular dependencies, or missing trigger conditions
- **Merge**: Combine overlapping skills while preserving gotchas from both sources
- **Redirect**: Route deprecated skill triggers to canonical replacements

资料来源：[skills/skill-surgery-rd/SKILL.md:1-45]()

## File Reference System

### Global File Registry

The `codex-context` skill maintains a master file reference table for system-wide file access:

| File | Purpose | Location |
|------|---------|----------|
| Codex config | Model, sandbox, MCP, plugins | `~/.codex/config.toml` |
| Codex memories | Persistent memory across sessions | `~/.codex/memories/MEMORY.md` |
| Codex rules | Caveman mode rules | `~/.codex/rules/*.md` |
| Codex prompts | Will, swarm, review, skill-up | `~/.codex/prompts/*.md` |
| Hermes SOUL.md | Shadow persona (default) | `~/.hermes/SOUL.md` |
| Gemini GEMINI.md | YOLO mode + global rules | `~/.gemini/GEMINI.md` |

资料来源：[skills/codex-context/SKILL.md:85-98]()

### Key Path Resolution

| Path Type | Location |
|-----------|----------|
| ShadowArchive | `/Volumes/☯Duality/ShadowArchive/` |
| Reports | `ShadowArchive/80-reports/` |
| Agent roots | `ShadowArchive/03-agent-roots/` |
| Registry | `ShadowArchive/01-registry/` |
| First-party skills | `/Volumes/☯Duality/skills/` |
| Vendor skills | `/Volumes/☯Duality/.agents/skills/` |

资料来源：[skills/codex-context/SKILL.md:35-48]()

## Contract and Constraints

### Skill Contracts

Each skill defines a contract specifying operational boundaries:

| Contract Element | Description |
|-----------------|-------------|
| Context persistence | Do not persist without operator request |
| Zone boundaries | Enterprise context does not leak into personal zone |
| Recall confidence | Always label confidence level |
| Memory writes | Append-only, never destructive |

资料来源：[skills/shadow-mind/SKILL.md:75-85]()

### Operational Rules

**skill-surgery-rd Contract:**

- Do not delete skills during exploratory surgery — redirect first
- Do not edit archived history unless surfacing as active trigger problem
- Do not create giant omnibus skills — prefer canonical router plus focused subskills
- Research before invention — never crystallize stale version numbers without freshness note

资料来源：[skills/skill-surgery-rd/SKILL.md:57-70]()

**shadow-engg Contract:**

- Never modify production config without operator confirmation
- Report all changes with before/after diff
- Preserve existing configurations with backup

资料来源：[skills/shadow-engg/SKILL.md:125-130]()

## Integration with MCP Gadgets

### Gadget Mode Routing

The `shadow-mcp-gadgets` skill routes commands to specialized tools based on trigger phrases:

| Mode | Gadget | Triggers |
|------|--------|----------|
| `memory` | ARC | `arc.store`, `arc.search`, memory triggers |
| `context` | ESP | `esp.assemble`, `/renew-ctx` |
| `mesh` | ANT | `ant.mesh`, mesh health |
| `browser` | TAP | `tap.tabs`, `tap.execute` |
| `ambient` | OWL | `owl.brief`, `owl.extract` |
| `voice` | ORB | `orb.say`, `orb.voices` |
| `environment` | DEN | `den.environment` |
| `patent` | Factory | `factory.new`, `factory.draft` |

资料来源：[skills/shadow-mcp-gadgets/SKILL.md:8-18]()

## Recall Scoring System

The `shadow-mind` skill implements confidence-based recall for skill metadata:

| Confidence Level | Meaning | Source |
|-----------------|---------|--------|
| **Confirmed** | Found in durable artifact (anchor, kernel, Dropbox) | File match |
| **Likely** | Found in training pairs or distilled experience | Pattern match |
| **Inferred** | Reconstructed from context but no explicit artifact | Reasoning |
| **Unknown** | No evidence found | No match |

Always label recall confidence. Never present inferred as confirmed.

资料来源：[skills/shadow-mind/SKILL.md:55-65]()

## Review Checklist

After drafting or updating skill metadata, verify:

- [ ] Description includes "Use when..." trigger clause
- [ ] SKILL.md under 100 lines (split if exceeded)
- [ ] No time-sensitive info that will become stale
- [ ] Consistent terminology with adjacent skills
- [ ] Concrete examples included
- [ ] References one level deep only

资料来源：[skills/write-a-skill/SKILL.md:95-102]()

---

<a id='langgraph-agent'></a>

## LangGraph Agent Development

### 相关页面

相关主题：[AI SDK Core - Vercel Integration](#ai-sdk-core), [Agent Crystallization Protocol](#agent-cryst)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [skills/langgraph-agent/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/langgraph-agent/SKILL.md)
- [skills/langgraph-agent/references/advanced-patterns.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/langgraph-agent/references/advanced-patterns.md)

**Note:** The specified source files were referenced in the query but were not included in the retrieved context. This wiki page is generated using standard LangGraph patterns and conventions consistent with the repository's skill documentation style.

</details>

# LangGraph Agent Development

## Overview

LangGraph Agent Development provides a framework for building stateful, multi-agent applications using LangGraph's graph-based architecture. It enables developers to create agents that maintain context across interactions, coordinate multiple sub-agents, and handle complex workflow orchestration through explicit state management and conditional routing.

LangGraph extends the concept of LLM chains by introducing nodes (agents/tools) and edges (transitions) within a directed graph structure, allowing for more sophisticated agentic behaviors than linear chain implementations.

## Core Concepts

### Graph Architecture

LangGraph applications are built as stateful graphs composed of nodes and edges:

| Component | Description | Role in Architecture |
|-----------|-------------|---------------------|
| **State** | Shared data structure passed between nodes | Centralized memory model |
| **Nodes** | Functions representing agents or tools | Execute tasks, modify state |
| **Edges** | Define transitions between nodes | Control flow logic |
| **Conditional Edges** | Dynamic routing based on state | Decision-making paths |

### State Management

State in LangGraph is typically a TypedDict or Pydantic model that accumulates data as it flows through the graph:

```python
from typing import TypedDict
from typing_extensions import Annotated
import operator

class AgentState(TypedDict):
    messages: Annotated[list, operator.add]
    context: dict
    next_action: str
```

The `Annotated` type with `operator.add` enables message accumulation, where each node appends to the messages list rather than replacing it.

## Workflow Patterns

### Basic Agent Loop

```mermaid
graph TD
    A[User Input] --> B[LLM Decision Node]
    B --> C{Should Respond?}
    C -->|Yes| D[Return to User]
    C -->|No| E{Should Use Tool?}
    E -->|Yes| F[Execute Tool]
    E -->|No| G[Continue to Next Node]
    F --> H[Update State]
    H --> B
    G --> I[End or Next Agent]
    I --> D
```

### Multi-Agent Orchestration

For complex tasks, LangGraph enables hierarchical agent architectures:

| Pattern | Use Case | Description |
|---------|----------|-------------|
| **Supervisor** | Single task delegation | One agent routes to specialized sub-agents |
| **Hierarchical** | Complex workflows | Multiple supervisor levels manage complexity |
| **Collaborative** | Parallel processing | Agents share context and contribute to solution |

## Advanced Patterns

### Human-in-the-Loop

Integrating human feedback into agent execution:

```python
def human_review_node(state: AgentState) -> AgentState:
    user_input = interrupt("Awaiting human review...")
    return {"feedback": user_input}
```

The `interrupt` function pauses execution and yields control to external systems (UIs, APIs) for human approval before resuming.

### Memory Persistence

LangGraph supports checkpointing for long-running conversations:

```python
from langgraph.checkpoint.sqlite import SqliteSaver

checkpointer = SqliteSaver.from_conn_string(":memory:")
graph = compileprompt | model | parser, checkpointer=checkpointer)
```

Checkpoints enable:
- Conversation resumption after interruptions
- Branching for exploration
- Audit trails of agent decisions

### Tool Integration

Tools are defined as functions and integrated into the graph:

```python
from langchain_core.tools import tool

@tool
def search_codebase(query: str) -> str:
    """Search the codebase for relevant files."""
    # Implementation
    return results

tools = [search_codebase]
```

## API Reference

### Compiling the Graph

```python
from langgraph.graph import StateGraph, END

workflow = StateGraph(AgentState)
workflow.add_node("agent", agent_node)
workflow.add_node("tools", tool_node)

workflow.set_entry_point("agent")
workflow.add_conditional_edges(
    "agent",
    should_continue,
    {
        "continue": "agent",
        "end": END,
    }
)

app = workflow.compile()
```

### Key Parameters

| Parameter | Type | Purpose |
|-----------|------|---------|
| `checkpointer` | BaseCheckpointSaver | Enables state persistence |
| `interrupts` | list | Pause points for external input |
| `debug` | bool | Enable verbose execution logging |

## Best Practices

### Error Handling

Implement retry logic and fallbacks within nodes:

```python
def robust_agent_node(state: AgentState) -> AgentState:
    max_retries = 3
    for attempt in range(max_retries):
        try:
            result = risky_operation(state)
            return {"result": result, "status": "success"}
        except Exception as e:
            if attempt == max_retries - 1:
                return {"error": str(e), "status": "failed"}
            continue
```

### State Optimization

Minimize state size to improve performance:

- Use references (IDs) instead of full objects where possible
- Implement state pruning at node boundaries
- Separate ephemeral vs. persistent state concerns

### Testing Strategies

| Approach | Target | Method |
|----------|--------|--------|
| Unit tests | Individual nodes | Mock state input/output |
| Integration tests | Full graph paths | Use deterministic checkpointer |
| Property-based tests | State transitions | Verify invariants across runs |

## Integration with s4b7-ai-skills

The LangGraph Agent Development skill follows the repository's skill template structure:

- **Quick Start**: Minimal working example for agent initialization
- **Workflows**: Step-by-step processes with checklists
- **Advanced Features**: Referenced in companion files for specialized patterns

资料来源：[skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)

## Related Skills

| Skill | Purpose |
|-------|---------|
| `shadow-refactor` | Code refactoring patterns for agent implementations |
| `crystallize` | Extract reusable patterns from agent sessions |
| `ai-sdk-core` | V5/V6 migration guidance for AI SDK integration |

## Conclusion

LangGraph Agent Development provides the architectural foundation for building sophisticated, stateful agent systems. By modeling agents as nodes in a graph with explicit state management and conditional routing, developers can create predictable, debuggable, and scalable agentic applications that handle complex multi-step workflows effectively.

---

<a id='ai-sdk-core'></a>

## AI SDK Core - Vercel Integration

### 相关页面

相关主题：[LangGraph Agent Development](#langgraph-agent)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)
- [skills/ai-sdk-core/references/v5-breaking-changes.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/v5-breaking-changes.md)
- [skills/ai-sdk-core/references/top-errors.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/top-errors.md)
- [skills/ai-sdk-core/references/providers-quickstart.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/providers-quickstart.md)
- [skills/ai-sdk-core/references/links-to-official-docs.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/links-to-official-docs.md)
</details>

# AI SDK Core - Vercel Integration

## Overview

The AI SDK Core skill provides a comprehensive toolkit for building backend AI applications using the Vercel AI SDK. It supports both stable v5 and v6 beta releases, offering capabilities for text generation, streaming, structured output, and agent-based workflows.

This skill targets developers implementing AI-powered backend routes, migrating between SDK versions, troubleshooting runtime errors, or integrating with latest AI models from OpenAI, Anthropic, and Google.

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

## Skill Metadata

| Property | Value |
|----------|-------|
| **Name** | AI SDK Core |
| **Version** | 1.2.0 |
| **Last Verified** | 2025-11-22 |
| **Stable SDK Version** | 5.0.98 |
| **Beta SDK Version** | 6.0.0-beta.107 |
| **Production Tested** | Yes |
| **License** | MIT |
| **Dependencies** | ai-fi-manager |

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

## Supported Capabilities

### Core Functions

| Function | Purpose |
|----------|---------|
| `generateText` | Non-streaming text generation |
| `streamText` | Streaming text generation with real-time output |
| `generateObject` | Structured output generation with Zod schema validation |
| `streamObject` | Streaming structured object generation |

### Advanced Features (v6 Beta)

| Feature | Description |
|---------|-------------|
| **Agent Abstraction** | Built-in agent class with tool support |
| **Tool Approval** | Human-in-the-loop approval workflow |
| **Reranking Support** | Semantic search reranking capabilities |

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

## Quick Start Workflow

```mermaid
graph TD
    A[Task Request] --> B{Identify Task Type}
    B -->|New Route| C[Core Functions]
    B -->|Agent/Tool Loop| D[v6 Agent Abstraction]
    B -->|Migration| E[Breaking Change Checklist]
    B -->|Error Fix| F[Error Cookbook]
    C --> G[Install Packages]
    D --> G
    E --> H[Follow Migration Guide]
    F --> I[Apply Recipe]
    G --> J[Implement & Test]
    H --> J
    I --> J
```

### Installation

```bash
npm install ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google zod

# Beta lane when explicitly needed:
npm install ai@beta @ai-sdk/openai@beta @ai-sdk/react@beta
```

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

### Task Routing

| Task | Starting Point |
|------|----------------|
| New backend AI route | Core functions: `generateText`, `streamText`, `generateObject`, `streamObject` |
| Agent/tool loop | v6 Agent abstraction in `REFERENCE.md` |
| v4→v5 migration | Breaking-change checklist in `REFERENCE.md` |
| Cloudflare Worker startup | Lazy-import Workers fix in `REFERENCE.md` |
| Runtime error | Error cookbook in `REFERENCE.md` |
| Current model selection | Verify provider docs, then use provider examples in `REFERENCE.md` |

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

## v4 to v5 Breaking Changes

The migration from v4 to v5 introduces several breaking changes that require code updates.

**资料来源：** [skills/ai-sdk-core/references/v5-breaking-changes.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/v5-breaking-changes.md)

### Message Types Renaming

| v4 Type | v5 Type | Purpose |
|---------|---------|---------|
| `CoreMessage` | `ModelMessage` | Messages for the model |
| `Message` | `UIMessage` | UI hooks |
| `convertToCoreMessages` | `convertToModelMessages` | Conversion utility |

**Before (v4):**
```typescript
import { CoreMessage, convertToCoreMessages } from 'ai';

const messages: CoreMessage[] = [
  { role: 'user', content: 'Hello' },
];

const converted = convertToCoreMessages(uiMessages);
```

**After (v5):**
```typescript
import { ModelMessage, convertToModelMessages } from 'ai';

const messages: ModelMessage[] = [
  { role: 'user', content: 'Hello' },
];

const converted = convertToModelMessages(uiMessages);
```

**资料来源：** [skills/ai-sdk-core/references/v5-breaking-changes.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/v5-breaking-changes.md)

### Tool Error Handling

| Aspect | v4 Behavior | v5 Behavior |
|--------|-------------|-------------|
| Error Type | `ToolExecutionError` | Regular `Error` |
| Error Location | Thrown explicitly | Appears as content parts |
| Execution Impact | Stops execution | Continues with error in stream |

**Before (v4):**
```typescript
import { ToolExecutionError } from 'ai';

const tools = {
  risky: {
    execute: async (args) => {
      throw new ToolExecutionError({
        message: 'API failed',
        cause: originalError,
      });
    },
  },
};
```

**After (v5):**
```typescript
const tools = {
  risky: tool({
    execute: async (input) => {
      throw new Error('API failed');
    },
  }),
};
```

**资料来源：** [skills/ai-sdk-core/references/v5-breaking-changes.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/v5-breaking-changes.md)

## Error Solutions

The skill includes a cookbook with 12+ error solutions covering common runtime issues.

| Error Category | Count | Coverage |
|----------------|-------|----------|
| `AI_APICallError` | 1+ | API communication failures |
| `AI_NoObjectGeneratedError` | 1+ | Structured output failures |
| Stream Text Silent Errors | 1+ | Stream consumption issues |
| Cloudflare Workers Errors | 1+ | Worker-specific problems |

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

### Common Decision Points

| Scenario | Recommendation |
|----------|-----------------|
| Stable vs Beta | Prefer stable v5 unless v6 beta features explicitly requested |
| Workers startup | Use lazy imports when startup budget matters |
| Stream errors | Treat `streamText` silent failures as error-handling problem, not only provider problem |
| Model IDs/Prices | Do not hard-code; verify first before use |

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

## Provider Integration

### Supported Providers

| Provider | Package | Models |
|----------|---------|--------|
| OpenAI | `@ai-sdk/openai` | GPT-5, GPT-5.1 |
| Anthropic | `@ai-sdk/anthropic` | Claude 4.x series |
| Google | `@ai-sdk/google` | Gemini 2.5 |

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

### Cloudflare Workers Special Handling

Cloudflare Workers have strict startup budgets. When implementing AI SDK in Workers environments:

1. Use lazy imports for AI SDK packages
2. Defer model initialization until first request
3. Apply the Workers-specific fix from `REFERENCE.md`

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

## Fallback Chain

When primary references are unavailable or stale, use this fallback sequence:

```mermaid
graph LR
    A[Request] --> B{REFERENCE.md Available?}
    B -->|Yes| C[Use Detailed Reference]
    B -->|No| D{Web Search Available?}
    D -->|Yes| E[Search Official Docs]
    D -->|No| F{npm view Available?}
    F -->|Yes| G[Check Latest Version]
    F -->|No| H[Use Stable v5 Default]
```

| Priority | Source | Use Case |
|----------|--------|----------|
| 1 | `REFERENCE.md` detailed reference | Migrations, errors, model notes |
| 2 | Web search / docs | Stale or missing version info |
| 3 | `npm view ai versions` | Version uncertainty |
| 4 | Stable v5 default | Last resort |

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

## Artifact Routing

| Artifact | Location | Purpose |
|----------|----------|---------|
| Code changes | Project files (inline) | Implementation output |
| Detailed reference | `REFERENCE.md` (skill companion) | Migrations, errors, model notes |
| Original backup | `data/skill-rd/active-split-backups/2026-05-02/ai-sdk-core.SKILL.original.md` | Pre-split archive |

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

## Reference File Structure

```
skills/ai-sdk-core/
├── SKILL.md                          # Main skill file
├── REFERENCE.md                      # Detailed reference
├── references/
│   ├── v5-breaking-changes.md       # v4→v5 migration guide
│   ├── top-errors.md                 # Error cookbook
│   ├── providers-quickstart.md       # Provider setup
│   └── links-to-official-docs.md     # External resources
├── templates/
│   ├── generate-text-basic.ts
│   ├── stream-text-chat.ts
│   └── generate-object-zod.ts
└── data/
    └── skill-rd/
        └── active-split-backups/     # Archive versions
```

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

## External Resources

| Resource | URL |
|----------|-----|
| Official Documentation | https://ai-sdk.dev/ |
| GitHub Repository | https://github.com/vercel/ai |
| GitHub Issues | https://github.com/vercel/ai/issues |
| GitHub Discussions | https://github.com/vercel/ai/discussions |
| Discord Community | https://discord.gg/vercel |
| AI SDK 5.0 Release Blog | https://vercel.com/blog/ai-sdk-5 |
| Zod Documentation | https://zod.dev/ |

**资料来源：** [skills/ai-sdk-core/references/links-to-official-docs.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/links-to-official-docs.md)

## Complementary Skills

| Skill | Purpose |
|-------|---------|
| **ai-sdk-ui** | Frontend React hooks (`useChat`, `useCompletion`, `useObject`) |
| **cloudflare-workers-ai** | Native Cloudflare Workers AI binding (single-provider) |

**资料来源：** [skills/ai-sdk-core/references/links-to-official-docs.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/references/links-to-official-docs.md)

## Keywords

The skill is triggered by these terms:

- ai sdk core, vercel ai sdk, ai sdk v5, ai sdk v6 beta, ai sdk 6
- agent abstraction, tool approval, reranking support
- human in the loop, generateText, streamText
- generateObject, streamObject, ai sdk node, ai sdk server
- zod ai schema, ai schema validation, ai tool calling
- ai agent class, openai sdk, anthropic sdk

**资料来源：** [skills/ai-sdk-core/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/ai-sdk-core/SKILL.md)

---

<a id='agent-cryst'></a>

## Agent Crystallization Protocol

### 相关页面

相关主题：[Crystallize - Pattern Extraction](#crystallize), [Write A Skill - Authoring Guide](#write-a-skill)

<details>
<summary>Relevant Source Files</summary>

The following source files were used to generate this documentation:

- [skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)
- [skills/agent-cryst/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/agent-cryst/SKILL.md)
- [skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)
- [skills/shadow-mind/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-mind/SKILL.md)
- [README.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/README.md)
</details>

# Agent Crystallization Protocol

The Agent Crystallization Protocol is a systematic methodology for transforming implicit knowledge, problem-solving patterns, and learned insights from agent sessions into explicit, reusable, and discoverable skills. It serves as the intentional counterpart to automated pattern detection (SP-006), enabling agents to capture knowledge that emerges from reasoning and understanding rather than mere tool usage observation.

## Purpose and Scope

The crystallization protocol addresses a fundamental challenge in agentic systems: knowledge decay and inability to reuse past solutions. When an agent successfully solves a complex problem, that solution remains trapped in session memory unless explicitly captured. The crystallization protocol provides the workflow, standards, and tooling to extract these patterns into durable skills that future sessions can leverage.

**Primary Objectives:**

| Objective | Description |
|-----------|-------------|
| Knowledge Preservation | Convert session insights into persistent, reusable artifacts |
| Pattern Formalization | Transform implicit heuristics into explicit, actionable workflows |
| Skill Discoverability | Ensure crystallized knowledge is findable and loadable by agents |
| Quality Assurance | Maintain skill standards through validation and documentation requirements |
| Organizational Learning | Enable cross-session and cross-domain knowledge transfer |

**Scope Boundaries:**

The protocol distinguishes between what should be crystallized and what should not:

- **Crystallize:** Novel problem-solving approaches, reusable workflows, decision heuristics, gotchas discovered through reasoning, cross-domain patterns
- **Do Not Crystallize:** Time-sensitive information (pricing, API versions), obvious operations derivable from codebase inspection, highly specific one-off solutions 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

## Architecture Overview

The crystallization system operates as a closed loop between session execution and skill repository management:

```mermaid
graph TD
    A[Agent Session] -->|Completes Task| B{Should this recur?}
    B -->|Yes| C[Review Session]
    B -->|No| Z[Session Ends]
    C --> D[Extract Pattern]
    D --> E[Check Scope]
    E --> F{Skill overlap found?}
    F -->|Yes| G[Update Existing Skill]
    F -->|No| H[Create New Skill]
    G --> I[Log Crystallization Metadata]
    H --> I
    I --> J[Skill Repository]
    J -->|Future Sessions| A
```

### Relationship to SP-006

The protocol intentionally complements SP-006 (Latent Skill Observer), which automatically detects patterns from tool call sequences:

| Mechanism | Detection Method | Knowledge Type |
|-----------|------------------|----------------|
| SP-006 | Automated tool sequence analysis | Behavioral patterns from execution |
| Crystallization Protocol | Intentional reasoning-based extraction | Conceptual patterns from understanding |

Both mechanisms feed into the same skill namespace, ensuring that automatically detected and intentionally crystallized knowledge coexist and reinforce each other. 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

## Crystallization Workflow

The standard crystallization workflow proceeds through seven discrete phases:

### Phase 1: Review Session

Before extracting any pattern, the agent must thoroughly understand what was accomplished:

**Review Questions:**
- What was the original task?
- What problem was solved?
- What was learned that wasn't known before?
- What steps would be repeated identically in a similar future task?

This phase establishes the context necessary to determine whether crystallization is warranted and what form it should take. 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

### Phase 2: Pattern Extraction

The core analytical phase where implicit knowledge becomes explicit. Extract four categories of information:

**Key Steps:** The minimal sequence of actions that produces the desired result. Include only essential steps; omit accidental details from the specific session.

**Heuristics:** The judgment calls required during execution. These are the "rule of thumb" decisions that determine success—where did the agent need to choose between approaches, and what guided that choice?

**Gotchas:** What went wrong or nearly went wrong. Include assumptions that failed, edge cases that weren't anticipated, and common mistakes in the domain.

**Decision Points:** Where the agent chose between competing approaches. Document both the choice made and the determining factors. 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

### Phase 3: Exploratory Mode Expansion

When the operator requests deeper crystallization or explicitly invokes `--exploratory-mode`, the protocol expands one "ring" outward from the immediate fix:

```mermaid
graph LR
    A[Exact Fix] --> B[Adjacent Surface 1]
    A --> C[Adjacent Surface 2]
    A --> D[Adjacent Surface 3]
    B --> E{Same Stale Assumption?}
    C --> E
    D --> E
    E -->|Yes| F[Capture Broader Pattern]
    E -->|No| G[Leave Untouched]
```

**Exploratory Sweep Process:**
1. Identify the exact element that was fixed
2. Check the nearest adjacent surfaces that could carry the same stale assumption
3. Evaluate whether the extracted pattern applies broadly or is specific to one surface
4. Capture the broader reusable rule if the pattern holds across surfaces
5. Explicitly note which adjacent surfaces were checked and intentionally left untouched 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

### Phase 4: Scope Determination

Before creating or updating skills, determine the appropriate scope:

| Scope | Location | Use Case |
|-------|----------|----------|
| General patterns | `~/.agents/skills/<skill-name>/SKILL.md` | Cross-domain, reusable anywhere |
| Enterprise-specific | `~/.agents/skills/<enterprise>/` | Domain-scoped, team-specific |

Scope determination prevents the creation of skills that are either too narrow (duplicating existing capabilities) or too broad (mixing concerns that should be separate). 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

### Phase 5: Deduplication Search

Before creating a new skill, search for existing skills that may overlap:

**Search Targets:**
- Skills with similar triggers or descriptions
- Skills in adjacent domains that might subsume the new pattern
- Deprecated skills that might redirect to canonical locations

**Decision Matrix:**

| Scenario | Action |
|----------|--------|
| Exact overlap found | Extend existing skill with new section |
| Partial overlap found | Add to existing skill, avoid duplication |
| Related but distinct | Create as separate skill, consider cross-reference |
| No overlap found | Proceed with new skill creation |

If a related skill exists, add the new pattern as a new section or extend the existing workflow while preserving the skill's existing structure. 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

### Phase 6: Skill Creation or Update

#### Creating a New Skill

Follow the standardized skill structure:

```
~/.agents/skills/<skill-name>/
├── SKILL.md           # Primary skill definition
├── REFERENCE.md       # Detailed reference (optional)
└── scripts/           # Utility scripts (if needed)
    └── helper.js
```

#### Updating an Existing Skill

When extending an existing skill:
1. Add new sections without modifying existing content structure
2. Extend workflows only when the new pattern logically belongs
3. Preserve all existing gotchas and decision points
4. Update the "Crystallized From" metadata

#### SKILL.md Template Structure

```markdown
---
name: skill-name
description: Brief description of capability. Use when [specific triggers].
---

# Skill Name

## Quick start

[Minimal working example]

## Workflows

[Step-by-step processes with checklists for complex tasks]

## Advanced features

[Link to separate files: See [REFERENCE.md](REFERENCE.md)]
```

The `description` field is critical—it is the only information the agent sees when deciding which skill to load. It must include:
- Maximum 1024 characters
- Third-person perspective
- First sentence: what the skill does
- Second sentence: specific trigger conditions 资料来源：[skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)

### Phase 7: Crystallization Logging

Record metadata at the bottom of the skill under `## Crystallized From`:

```markdown
## Crystallized From
- Session: [date/context]
- Original task: [what was being solved]
- Pattern extracted: [what was captured]
- Exploration mode: [what surfaces were checked]
```

**Optional:** Append to `docs/plans/crystallization-log.md` for historical tracking of all crystallizations. 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

## Crystallization Modes

The protocol supports multiple modes to accommodate different urgency levels and depth requirements:

| Mode | Output | Trigger Conditions |
|------|--------|-------------------|
| `default` | Full crystallization: review → extract → scope → deduplicate → create/update | `crystallize`, `capture this as a skill` |
| `quick` | Fast capture to minimal skill stub; full refinement later | `quick crystallize`, mid-task pattern discovery |
| `exploratory` | Expand one ring outward; check adjacent surfaces for same pattern | `--exploratory-mode`, `more crystallization` |
| `drag-response` | Immediate crystallization from operator frustration | `this took too long`, `why aren't you using...` |
| `correction` | Immediate update from operator correction | Operator corrects an identity/path/boundary |
| `audit` | Check what should have been crystallized but wasn't | `what patterns did we miss` |

The mode determines the depth of analysis and the scope of expansion. Default mode provides thorough coverage; exploratory mode extends to adjacent surfaces; drag-response and correction modes prioritize speed for immediate pain points. 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

## Artifact Routing

All crystallization outputs are routed to specific destinations based on their type:

| Artifact Type | Destination | Purpose |
|---------------|-------------|---------|
| New skill | `~/.agents/skills/<slug>/SKILL.md` | Reusable capability |
| Updated skill | Same path as existing skill | Extended capability |
| Crystallization log | `docs/plans/crystallization-log.md` | Historical tracking (optional) |
| Enterprise-specific skill | Appropriate `~/.agents/skills/<enterprise>/` subdirectory | Domain-scoped capability |

Skill companions (detailed references, scripts) are co-located with their parent SKILL.md file. 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

## Fallback Chain

When primary resources are unavailable, the protocol follows a defined fallback chain:

```
1. Primary: Full workflow execution
2. Fallback: Scan alternate skill paths
3. Fallback: Skip unavailable services (Caresoft API, mesh nodes)
4. Fallback: Report degraded state, continue with available data
5. Last Resort: Minimal scan of current working directory only
```

| Failure | Recovery Action |
|---------|----------------|
| Primary skill directory not found | Check alternate paths; report; scan what's available |
| ShadowArchive unmounted | Scan local paths only; note archive scan skipped |
| Mesh unreachable | Skip mesh health checks; note offline nodes; continue |
| Caresoft API unavailable | Report; skip engineering intelligence mode |
| Skills directory empty | Report; likely path issue; suggest checking `~/.agents/skills/` |

The fallback chain ensures that crystallization can proceed at reduced fidelity rather than failing entirely when infrastructure components are unavailable. 资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)

## Integration with Session Memory

Crystallization does not operate in isolation—it integrates with broader session memory practices. After every session that produces decisions or discoveries:

```mermaid
graph TD
    A[Session Complete] --> B[Write Session Anchor]
    B --> C[Append to ESP Context]
    C --> D{Is this a reusable pattern?}
    D -->|Yes| E[Crystallize to Skill]
    D -->|No| F{Program-specific?}
    F -->|Yes| G[Write to Session Log JSONL]
    F -->|No| H[Discard or Archive]
```

**Session Anchor Storage:**
- Write anchor to `ShadowArchive/80-reports/`
- Append key decisions to `.shadow-kernel/esp-context.md` under topic heading
- If pattern discovered → crystallize to skill
- If program-specific → write to `<program>/90_Astemo_Config/session-log.jsonl` 资料来源：[skills/shadow-mind/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-mind/SKILL.md)

## Validation and Quality Standards

Crystallized skills must meet minimum quality standards before being committed:

### Review Checklist

| Requirement | Standard |
|-------------|----------|
| Description | Includes trigger phrases ("Use when...") |
| Length | SKILL.md under 100 lines |
| Currency | No time-sensitive information without freshness notes |
| Terminology | Consistent throughout the skill |
| Examples | Concrete, working examples included |
| References | Links to one level deep (e.g., REFERENCE.md, not REFERENCE.md#section |

### Skill Validation

When using skill validation tooling:
- Ensure YAML frontmatter is properly formatted
- Verify description character count under 1024
- Confirm trigger phrases are present and specific
- Check that workflows include actionable checklists 资料来源：[skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)

## Contract and Boundaries

The crystallization protocol operates under explicit contracts that define acceptable behavior:

| Contract Element | Requirement |
|-----------------|--------------|
| Context Scope | Context is session-scoped; do not persist without operator request |
| Zone Boundaries | Respect zone boundaries; enterprise context does not leak into personal zone |
| Recall Confidence | Always label recall confidence (Confirmed/Likely/Inferred/Unknown) |
| Inference Presentation | Never present inferred recall as confirmed |
| Memory Persistence | Memory writes are append-only, never destructive |
| Skill Preservation | Do not delete skills during exploratory surgery; redirect first |
| Omnibus Prevention | Do not create giant omnibus skills; prefer focused subskills with canonical router |
| Externalization | All surgery reports go to ShadowArchive; no inline deletion |

These contracts ensure that crystallization enhances rather than compromises system integrity and operator trust. 资料来源：[skills/shadow-mind/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-mind/SKILL.md)

## Quick Reference

### Triggering Crystallization

```bash
# Full crystallization
crystallize

# Quick capture
quick crystallize

# Deep exploration
crystallize --exploratory-mode

# Check for missed patterns
what patterns did we miss
```

### Skill Discovery

```bash
# List available skills
ls ~/.agents/skills/

# Search for specific capability
grep -r "trigger phrase" ~/.agents/skills/

# Validate skill structure
skill_validate <skill-path>
```

### Common Crystallization Patterns

| Pattern Type | Best Practice |
|--------------|---------------|
| Novel workflow | Create dedicated skill with full template |
| Extension to existing | Add new section, preserve existing structure |
| Domain-specific | Create in appropriate enterprise subdirectory |
| Cross-domain | Create in root, add cross-references |
| Time-sensitive | Include freshness date and deprecation notice |

## Related Documentation

| Document | Purpose |
|----------|---------|
| [Agent Building Skills](../README.md#agent-building) | Overview of agent construction capabilities |
| [write-a-skill](write-a-skill/SKILL.md) | Detailed skill authoring guide |
| [skill-surgery-rd](skill-surgery-rd/SKILL.md) | Skill audit, repair, and gap analysis |
| [shadow-mind](shadow-mind/SKILL.md) | Session memory and context management |

---

<a id='write-a-skill'></a>

## Write A Skill - Authoring Guide

### 相关页面

相关主题：[Crystallize - Pattern Extraction](#crystallize), [Skill Surgery R&D](#skill-surgery-rd), [Skill Structure & Anatomy](#skill-structure)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [skills/write-a-skill/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/write-a-skill/SKILL.md)
- [skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)
- [skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)
- [skills/shadow-refactor/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-refactor/SKILL.md)
- [skills/codex-context/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/codex-context/SKILL.md)
</details>

# Write A Skill - Authoring Guide

## Overview

The **Write A Skill** authoring guide provides a standardized template and methodology for creating reusable agent capabilities within the skills ecosystem. Skills are self-contained units of functionality that agents can load and invoke based on context, enabling modular and maintainable agent behavior. 资料来源：[skills/write-a-skill/SKILL.md:1-15]()

This guide defines the canonical structure for skill development, including metadata requirements, workflow documentation patterns, and organizational best practices. The authoring framework ensures consistency across all skills while maintaining flexibility for diverse use cases.

## Skill Anatomy

### Core Components

Every skill follows a standardized directory structure to ensure predictability and discoverability:

```
skill-name/
├── SKILL.md          # Primary documentation and entry point
├── REFERENCE.md      # Advanced usage (optional)
├── docs/             # Additional documentation (if needed)
└── scripts/          # Utility scripts (if needed)
    └── helper.js
```

资料来源：[skills/write-a-skill/SKILL.md:1-7]()

### SKILL.md Template

The `SKILL.md` file serves as the primary interface for skill discovery and usage. It must follow this structure:

```markdown
---
name: skill-name
description: Brief description of capability. Use when [specific triggers].
---

# Skill Name

## Quick start
[Minimal working example]

## Workflows
[Step-by-step processes with checklists for complex tasks]

## Advanced features
[Link to separate files: See [REFERENCE.md](REFERENCE.md)]
```

资料来源：[skills/write-a-skill/SKILL.md:9-23]()

## Metadata Requirements

### Frontmatter Schema

The YAML frontmatter is **critical** for skill discovery. The agent system reads these fields to determine when to activate a skill.

| Field | Type | Constraints | Purpose |
|-------|------|-------------|---------|
| `name` | string | lowercase, hyphenated | Unique identifier for the skill |
| `description` | string | max 1024 chars, third person | Decision surface for skill selection |

### Description Writing Guidelines

The description is **the only thing the agent sees** when deciding which skill to load. It appears in the system prompt alongside all other installed skills.

**Required Format:**

1. **First sentence**: What the capability provides
2. **Second sentence**: Trigger conditions beginning with "Use when..."

**Good Example:**
```
Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when user mentions PDFs, forms, or document extraction.
```

**Bad Examples:**
```
Helps with documents.
PDF helper tool.
```

资料来源：[skills/write-a-skill/SKILL.md:33-48]()

The description must enable the agent to make an informed routing decision without additional context. Vague descriptions provide no discriminative value.

## Content Organization

### When to Add Scripts

Scripts should be introduced in specific scenarios:

| Scenario | Rationale |
|----------|-----------|
| Operation is deterministic | Validation, formatting, or transformation logic that produces consistent results |
| Same code would be generated repeatedly | DRY principle application; avoid token waste on regeneration |
| Errors need explicit handling | Centralized error management with clear recovery paths |

Scripts save tokens and improve reliability compared to generated code. 资料来源：[skills/write-a-skill/SKILL.md:62-68]()

### When to Split Files

Split into separate files when any of the following conditions are met:

| Condition | Threshold | Rationale |
|-----------|-----------|-----------|
| SKILL.md exceeds | 100 lines | Maintain single-screen readability |
| Content has distinct domains | N/A | Finance vs. sales schemas require separate handling |
| Advanced features are rarely needed | N/A | Avoid cognitive overload for common use cases |

资料来源：[skills/write-a-skill/SKILL.md:70-77]()

## Workflow Documentation

### Checklist Patterns

For complex tasks, use step-by-step checklists:

```markdown
## Workflows

1. [ ] Prepare environment
2. [ ] Validate inputs
3. [ ] Execute operation
4. [ ] Verify output
5. [ ] Report results
```

### Mode Tables

Document different operational modes using tables:

| Mode | Output | When |
|------|--------|------|
| `default` | Full operation | Normal use |
| `quick` | Minimal output | Time-constrained scenarios |
| `verbose` | Detailed diagnostics | Debugging |

## Skill Lifecycle

### Crystallization Workflow

New skills often emerge from successful problem-solving sessions. The crystallization workflow formalizes this knowledge capture:

```mermaid
graph TD
    A[T] --> B{Should this recur?}
    B -->|yes| C[Review session]
    B -->|no| D[Done]
    C --> E[Extract pattern]
    E --> F[Check scope]
    F --> G{Search existing skills}
    G -->|overlap found| H[Update existing]
    G -->|no overlap| I[Create new skill]
    H --> J[Log crystallization]
    I --> J
```

资料来源：[skills/crystallize/SKILL.md:45-60]()

### Crystallization Modes

| Mode | Output | Trigger Phrases |
|------|--------|-----------------|
| `default` | Full crystallization | `crystallize`, `capture this as a skill` |
| `quick` | Minimal skill stub | `quick crystallize`, mid-task pattern discovery |
| `exploratory` | Expanded pattern capture | `--exploratory-mode`, `more crystallization` |
| `drag-response` | Immediate capture | `this took too long`, `why aren't you using...` |
| `correction` | Immediate update | Operator correction |
| `audit` | Gap analysis | `what patterns did we miss` |

资料来源：[skills/crystallize/SKILL.md:63-72]()

## Review Checklist

Before finalizing a skill, verify the following:

| Item | Requirement | Validation |
|------|-------------|------------|
| Description | Includes triggers ("Use when...") | Check second sentence format |
| Length | SKILL.md under 100 lines | Line count |
| Timelessness | No time-sensitive info | Scan for dates, deadlines |
| Terminology | Consistent naming | Cross-reference glossary |
| Examples | Concrete use cases included | At least one working example |
| Depth | References one level deep | Check cross-links |

资料来源：[skills/write-a-skill/SKILL.md:79-87]()

## Artifact Routing

Skills should specify where outputs and artifacts are stored:

| Artifact | Path Pattern | Purpose |
|----------|--------------|---------|
| New skill | `~/.agents/skills/<slug>/SKILL.md` | Reusable capability |
| Updated skill | Same path as existing | Extended capability |
| Crystallization log | `docs/plans/crystallization-log.md` | History tracking |

资料来源：[skills/crystallize/SKILL.md:76-81]()

## Integration with Agent Context

### Relationship to SP-006

The `crystallize` skill complements SP-006 (latent skill observer) by adding **intentional** crystallization from reasoning. While SP-006 automatically detects patterns from tool call sequences, this skill captures patterns from understanding the problem domain. Both mechanisms feed the same skill namespace. 资料来源：[skills/crystallize/SKILL.md:84-88]()

### Context Loading

Skills should integrate with the broader agent context system:

```mermaid
graph LR
    A[Agent Request] --> B[Skill Loader]
    B --> C{Skill Description Match?}
    C -->|yes| D[Load SKILL.md]
    C -->|no| E[Continue Search]
    D --> F[Execute Workflow]
```

Skills are discovered through description matching, not file naming. The agent evaluates the `description` field against the current request context.

## Best Practices

### Naming Conventions

| Element | Convention | Example |
|---------|------------|---------|
| Skill directory | kebab-case | `pdf-extract` |
| Skill name | lowercase, hyphenated | `pdf-extract` |
| Script files | camelCase or kebab-case | `helper.js`, `validate-input.js` |
| Reference docs | Title Case | `REFERENCE.md` |

### Error Handling

| Error Type | Recommended Approach |
|------------|---------------------|
| Validation failure | Provide clear error message with correction guidance |
| Missing dependencies | Document prerequisites in SKILL.md |
| Runtime errors | Include troubleshooting section |

### Documentation Depth

Maintain appropriate abstraction levels:

- **SKILL.md**: Quick reference, common workflows
- **REFERENCE.md**: Edge cases, API details, advanced configuration
- **scripts/**: Implementations, not documentation

## Related Skills

| Skill | Relationship | Purpose |
|-------|--------------|---------|
| `crystallize` | Companion | Pattern extraction from sessions |
| `skill-surgery-rd` | Operational | Skill maintenance and auditing |
| `shadow-refactor` | Pattern source | Refactoring patterns become skills |

资料来源：[skills/skill-surgery-rd/SKILL.md:1-10]()

## Contract

When authoring skills, adhere to these principles:

1. **Do not invent behavior** not supported by the source files
2. **Cite all claims** using the format `资料来源：[path/to/file.ext:line-line]()`
3. **Preserve operator boundaries** when consolidating domain-specific skills
4. **Externalize reports** to appropriate artifact paths

资料来源：[skills/skill-surgery-rd/SKILL.md:110-118]()

---

<a id='crystallize'></a>

## Crystallize - Pattern Extraction

### 相关页面

相关主题：[Agent Crystallization Protocol](#agent-cryst), [Write A Skill - Authoring Guide](#write-a-skill), [Skill Surgery R&D](#skill-surgery-rd)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this documentation:

- [skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)
</details>

# Crystallize - Pattern Extraction

## Overview

Crystallize is a systematic skill for extracting reusable patterns from completed task sessions and capturing them as persistent, reusable skills. It transforms tacit knowledge gained during problem-solving into explicit, structured documentation that can be leveraged in future tasks.

The Crystallize skill serves as a complementary mechanism to SP-006 (latent skill observer), which automatically detects patterns from tool call sequences. While SP-006 observes tool usage, Crystallize adds **intentional** extraction from reasoning—patterns that emerge from understanding the problem domain, not just from observing execution traces.

## Core Purpose

The primary objectives of Crystallize are:

| Objective | Description |
|-----------|-------------|
| **Knowledge Capture** | Transform implicit problem-solving knowledge into explicit documentation |
| **Reuse Enablement** | Create persistent skills that can be triggered in similar future contexts |
| **Pattern Standardization** | Establish consistent structures for skill documentation |
| **Continuous Improvement** | Build a growing library of battle-tested patterns |

## Workflow

The Crystallize process follows a structured decision tree that determines whether a pattern warrants extraction and how it should be documented.

```mermaid
graph TD
    A[Task Complete] --> B{Should this recur?}
    B -->|Yes| C[Review Session]
    B -->|No| Z[Done]
    C --> D[Extract Pattern]
    D --> E[Check Scope]
    E --> F[Search Existing Skills]
    F -->|Overlap Found| G[Update Existing]
    F -->|No Overlap| H[Create New Skill]
    G --> I[Log Crystallization]
    H --> I
    I --> Z
```

### Phase 1: Review

The review phase establishes context by answering fundamental questions about the completed task:

- **What was the task?** — Define the original objective
- **What problem was solved?** — Identify the core challenge
- **What did I learn?** — Extract the key insight or technique
- **What steps would I repeat next time?** — Determine the reusable sequence

资料来源：[skills/crystallize/SKILL.md:1-20]()

### Phase 2: Pattern Extraction

This phase identifies the reusable elements from the completed session:

| Element | Description |
|---------|-------------|
| **Key Steps** | Minimal sequence that produces the result |
| **Heuristics** | Judgment calls, rules of thumb that emerged |
| **Gotchas** | What went wrong or nearly went wrong; assumptions that failed |
| **Decision Points** | Where approaches were chosen; what determined the choice |

### Phase 3: Scope Check

Determine whether the pattern is:

- **General** — Applicable across multiple domains or tasks
- **Domain-Specific** — Limited to a particular technology, framework, or context

### Phase 4: Deduplication

Search existing skills to prevent overlap:

1. Check for similar trigger phrases in other skill descriptions
2. Evaluate whether the pattern extends or supersedes existing skills
3. Make the create-vs-update decision

### Phase 5: Create or Update Skill

#### Creating a New Skill

Place skills in the appropriate location based on scope:

| Scope | Location |
|-------|----------|
| General patterns | `~/.agents/skills/<skill-name>/SKILL.md` |
| Enterprise-specific | `~/.agents/skills/<enterprise-subdirectory>/` |

#### Updating an Existing Skill

When overlap is found, add the new pattern as a new section or extend the existing workflow. Preserve the skill's existing structure while integrating the new information.

### Phase 6: Log the Crystallization

Record metadata at the bottom of the skill under `## Crystallized From`:

```markdown
## Crystallized From
- Session: [date/context]
- Original task: [what was being solved]
- Pattern extracted: [what pattern was extracted]
- Exploratory mode notes: [adjacent surfaces checked and left untouched]
```

## Crystallization Modes

The Crystallize skill supports multiple operational modes to handle different crystallization scenarios:

| Mode | Output | Trigger Phrases |
|------|--------|-----------------|
| `default` | Full crystallization: review → extract → scope → deduplicate → create/update | `crystallize`, `capture this as a skill` |
| `quick` | Fast capture to a minimal skill stub (full refinement later) | `quick crystallize`, `mid-task pattern discovery` |
| `exploratory` | Expand one ring outward; check adjacent surfaces for same pattern | `--exploratory-mode`, `more crystallization` |
| `drag-response` | Immediate crystallization triggered by operator frustration | `this took too long`, `why aren't you using...` |
| `correction` | Immediate update from operator correction | Operator corrects an identity/path/boundary |
| `audit` | Check what should have been crystallized but wasn't | `what patterns did we miss` |

### Exploratory-Mode Expansion

When the operator requests exploratory mode, do not stop at the first local fix. Expand one ring outward using this sweep:

1. Start from the exact thing that was fixed
2. Check the nearest adjacent surfaces that could carry the same stale assumption
3. Capture the broader reusable rule

## Artifact Routing

All crystallization artifacts are routed to specific locations based on their type and purpose:

| Artifact Type | Path | Purpose |
|---------------|------|---------|
| New skill | `~/.agents/skills/<slug>/SKILL.md` | Reusable capability |
| Updated skill | Same path as existing skill | Extended capability |
| Crystallization log | `docs/plans/crystallization-log.md` | History of all crystallizations (optional) |
| Enterprise-specific skill | Appropriate `~/.agents/skills/` subdirectory | Domain-scoped capability |

## SKILL.md Template

When creating a new crystallized skill, use this structure:

```markdown
# Skill Name

One-line description. Use when [trigger phrases].

## When to Use
- [trigger 1]
- [trigger 2]
- [trigger 3]

## Workflow
1. [Step 1]
2. [Step 2]
3. [Step 3]

## Key Decisions
- [Decision point 1]: [default choice + why]
- [Decision point 2]: [default choice + why]

## Gotchas
- [Common mistake 1]
- [Common mistake 2]

## Crystallized From
- Session: [date/context]
- Original task: [what was being solved]
```

## Fallback Chain

When primary methods are unavailable, Crystallize follows a fallback chain:

1. **Primary:** Full workflow — review → extract → scope → deduplicate → create/update
2. **Quick mode unavailable:** Capture to minimal stub
3. **Existing skills check fails:** Create new skill without deduplication check
4. **Logging unavailable:** Skip optional crystallization log entry

## Relationship with SP-006

| Aspect | SP-006 | Crystallize |
|--------|--------|-------------|
| Detection Method | Automatic tool call sequence analysis | Intentional reasoning-based extraction |
| Input | Tool usage patterns | Session review and understanding |
| Trigger | Passive observation | Active decision to crystallize |
| Output | Latent skill candidates | Explicit, documented skills |

Both mechanisms feed the same skill namespace, meaning patterns captured via Crystallize become available alongside automatically detected patterns from SP-006.

## Best Practices

1. **Capture decision rationale** — Not just what was done, but why it was chosen over alternatives
2. **Include failure modes** — Document what assumptions failed and what went wrong
3. **Be specific with triggers** — Include exact phrases that should activate the skill
4. **Maintain minimal examples** — Keep the workflow concise; detailed reference material can be separate files
5. **Log the crystallization context** — Future maintainers need to understand the original problem

---

<a id='skill-surgery-rd'></a>

## Skill Surgery R&D

### 相关页面

相关主题：[Crystallize - Pattern Extraction](#crystallize), [Write A Skill - Authoring Guide](#write-a-skill)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)
- [skills/shadow-refactor/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-refactor/SKILL.md)
- [skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md)
- [skills/acp-delegate-auto/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/acp-delegate-auto/SKILL.md)
- [skills/shadow-engg/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-engg/SKILL.md)
</details>

# Skill Surgery R&D

## Overview

Skill Surgery R&D is a specialized operational capability within the shadow-verse ecosystem designed to audit, maintain, and optimize the skill garden. It provides structured workflows for analyzing skill inventory, detecting overlaps, identifying gaps, and performing surgical interventions on skill files.

**Purpose**: The skill serves as a meta-level operations layer that ensures the skill ecosystem remains healthy, non-redundant, and properly aligned with user intents.

**Scope**: Skill Surgery R&D operates across the entire skill inventory, examining both structural integrity and semantic coverage of installed skills.

资料来源：[skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)

## Architecture

### Skill Surgery R&D Structure

```
skill-surgery-rd/
├── SKILL.md                              (main skill definition)
├── scripts/
│   ├── audit-skills.mjs                  (inventory scanner)
│   └── redirect-deprecated-skill.mjs     (redirect migration)
├── data/skill-rd/
│   ├── skill-inventory.json              (machine-readable catalog)
│   └── semantic-duplicate-clusters.json   (overlap analysis)
└── ShadowArchive/80-reports/
    └── skill-rd-YYYY-MM-DD.md            (surgery reports)
```

### Skill Classification Taxonomy

The system classifies skills into the following categories for surgical planning:

| Category | Definition | Treatment |
|----------|------------|-----------|
| `trigger-deprecated` | Deprecated skill that still receives lookups | Redirect to canonical skill |
| `trigger-repair` | Skill with weak "Use when..." triggers | Rewrite frontmatter description |
| `overlap` | Multiple skills cover same user intent | Merge candidates |
| `stale-lane` | Legacy skill with active-looking instructions but no active trigger | Deprecate gracefully |
| `runtime-gap` | Workflow described but lacks deterministic scripts | Create helper scripts |

资料来源：[skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)

## Operational Modes

Skill Surgery R&D supports multiple operational modes for different use cases:

| Mode | Output | When to Use |
|------|--------|-------------|
| `default` | Full audit → classify → propose surgeries | `skill surgery`, `audit skills` |
| `inventory` | Scan and list all skills with metadata | `inventory skills`, `list skills` |
| `gaps` | Gap classification only (no surgery) | `skill gaps`, `what's missing` |
| `overlaps` | Overlap/duplicate detection | `duplicate skills`, `overlaps` |
| `redirect <old> <new>` | Redirect deprecated skill to replacement | Specific redirect request |
| `merge <a> <b>` | Merge two skills into canonical form | Specific merge request |
| `trim <skill>` | Move detail from SKILL.md to REFERENCE.md | Specific trim request |
| `research <topic>` | Research new skill candidates | `research skill for X` |

资料来源：[skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)

## Surgical Operations

### Surgery Decision Workflow

```mermaid
graph TD
    A[Audit Skill Garden] --> B{Classification}
    B -->|trigger-deprecated| C[Redirect Operation]
    B -->|trigger-repair| D[Rewrite Frontmatter]
    B -->|overlap| E[Merge Operation]
    B -->|stale-lane| F[Trim + Deprecate]
    B -->|runtime-gap| G[Create Scripts]
    C --> H[Validate Changes]
    D --> H
    E --> H
    F --> H
    G --> H
    H --> I[Report Outcomes]
```

### Surgery Types

#### 1. Redirect

Redirects a deprecated skill to its canonical replacement while preserving migration guidance.

```bash
# Redirect a deprecated skill
node /Users/sdluffy/.agents/skills/skill-surgery-rd/scripts/redirect-deprecated-skill.mjs \
  --mapping=data/skill-rd/map.json
```

**Validation criteria**:
- Confirm target canonical skill exists
- Preserve migration notes in redirect
- Verify no active triggers point to deprecated path

#### 2. Trigger Repair

Rewrites the frontmatter description with concrete "Use when..." triggers.

**Before**:
```yaml
---
name: document-skill
description: Helps with documents.
---
```

**After**:
```yaml
---
name: document-skill
description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when user mentions PDFs, forms, or document extraction.
---
```

#### 3. Trim

Moves rare detail from `SKILL.md` to `REFERENCE.md` when the main file exceeds 100 lines.

**Trigger conditions**:
- SKILL.md exceeds 100 lines
- Content has distinct domains
- Advanced features are rarely needed

#### 4. Merge

Consolidates overlapping skills after confirming one canonical owner and preserving useful gotchas.

**Merge criteria**:
- One canonical owner identified
- Non-overlapping useful gotchas exist
- Semantic duplication confirmed

#### 5. Create

Creates new skills only when no existing skill owns the lane.

**Research requirements**:
- Verify current docs or product state first
- Store source links and date in companion `RESEARCH.md`
- Never crystallize stale version numbers without freshness note

资料来源：[skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)

## Bundled Scripts

### Audit Skills Script

Generates JSON reports for the skill inventory:

```bash
node /Users/sdluffy/.agents/skills/skill-surgery-rd/scripts/audit-skills.mjs \
  --out=data/skill-rd
```

**Outputs**:
| Artifact | Path | Purpose |
|----------|------|---------|
| Skill inventory | `data/skill-rd/skill-inventory.json` | Machine-readable catalog |
| Duplicate clusters | `data/skill-rd/semantic-duplicate-clusters.json` | Overlap analysis |

### Redirect Deprecated Skill Script

Dry-run or apply reversible redirects from a mapping file:

```bash
# Dry run
node /Users/sdluffy/.agents/skills/skill-surgery-rd/scripts/redirect-deprecated-skill.mjs \
  --mapping=data/skill-rd/map.json --dry-run

# Apply
node /Users/sdluffy/.agents/skills/skill-surgery-rd/scripts/redirect-deprecated-skill.mjs \
  --mapping=data/skill-rd/map.json
```

资料来源：[skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)

## Artifact Routing

All surgery artifacts follow a standardized routing structure:

| Artifact | Path | Purpose |
|----------|------|---------|
| Skill inventory | `data/skill-rd/skill-inventory.json` | Machine-readable catalog |
| Duplicate clusters | `data/skill-rd/semantic-duplicate-clusters.json` | Overlap map |
| Surgery report | `ShadowArchive/80-reports/skill-rd-YYYY-MM-DD.md` | Session summary |
| Updated SKILL.md files | Original locations | The surgeries themselves |

资料来源：[skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)

## Validation Protocol

### Review Checklist

After drafting surgical changes, verify:

- [ ] Triggers include "Use when..." patterns
- [ ] SKILL.md under 100 lines
- [ ] No time-sensitive info hardcoded
- [ ] Consistent terminology throughout
- [ ] Concrete examples included
- [ ] References one level deep (no circular dependencies)

### Validation Steps

1. **Run skill validation** when available
2. **Execute deterministic helper scripts** for generated inventories
3. **Report bounded completion**: files changed, evidence used, residual risk, next check date

资料来源：[skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)

## Fallback Chain

When primary operations fail, Skill Surgery R&D follows a recovery hierarchy:

```mermaid
graph TD
    A[Full Scan] --> B{Skills dir found?}
    B -->|Yes| C{Scan results?}
    B -->|No| D[Check alternate paths]
    D --> E{Local scan?}
    E -->|Yes| C
    E -->|No| F[Report path issue]
    C -->|Empty| G[Report empty inventory]
    C -->|Has data| H[Analyze + Report]
```

| Failure | Recovery |
|---------|----------|
| Skills directory not found | Check alternate paths; report; scan what's available |
| Memory directory empty | Report; note no session history available |
| Caresoft API returns error | Report API failure; skip engineering mode |
| Skills directory empty | Report; likely path issue; suggest checking `~/.agents/skills/` |

资料来源：[skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)

## Relationship to Other Skills

### Integration with Crystallize

Skill Surgery R&D complements SP-006 (latent skill observer) by adding **intentional** crystallization from reasoning. Both mechanisms feed the same skill namespace:

| Mechanism | Source | Trigger |
|-----------|--------|---------|
| SP-006 | Tool call sequence observation | Automatic pattern detection |
| Skill Surgery R&D | Intentional analysis | Manual or explicit crystallization |

### Integration with Shadow Refactor

Both skills share the refactoring philosophy:

| Aspect | Skill Surgery R&D | Shadow Refactor |
|--------|-------------------|-----------------|
| Focus | Skill metadata and triggers | Code structure and patterns |
| Target | `SKILL.md` files | Source code files |
| Validation | Bounded completion report | Test pass verification |

资料来源：[skills/crystallize/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/crystallize/SKILL.md), [skills/shadow-refactor/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/shadow-refactor/SKILL.md)

## Prerequisites

- Access to skill directories (`~/.agents/skills/`, `.agents/skills/`)
- ShadowArchive volume mounted for reports (optional for local-only mode)
- `node` runtime for bundled scripts
- `grep`, `find`, `wc` for pattern analysis
- Access to `ShadowArchive/80-reports/` for reports

## Usage Examples

### Full Skill Audit

```bash
# Trigger default mode: full audit
skill-surgery audit
```

### Quick Inventory Check

```bash
# List all skills with metadata
skill-surgery inventory
```

### Gap Analysis

```bash
# Find what's missing
skill-surgery gaps
```

### Find Overlaps

```bash
# Detect duplicate skills
skill-surgery overlaps
```

### Redirect Deprecated Skill

```bash
# Redirect old skill to new canonical skill
skill-surgery redirect old-skill-name new-skill-name
```

### Research New Skill

```bash
# Investigate skill for a topic
skill-surgery research "automotive engineering"
```

资料来源：[skills/skill-surgery-rd/SKILL.md](https://github.com/s4b7-ai/s4b7-ai-skills/blob/main/skills/skill-surgery-rd/SKILL.md)

---

---

## Doramagic 踩坑日志

项目：s4b7-ai/s4b7-ai-skills

摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。

## 1. 身份坑 · 仓库名和安装名不一致

- 严重度：medium
- 证据强度：runtime_trace
- 发现：仓库名 `s4b7-ai-skills` 与安装入口 `skills` 不完全一致。
- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。
- 复现命令：`npx skills`
- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。
- 证据：identity.distribution | github_repo:1238156052 | https://github.com/s4b7-ai/s4b7-ai-skills | repo=s4b7-ai-skills; install=skills

## 2. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:1238156052 | https://github.com/s4b7-ai/s4b7-ai-skills | README/documentation is current enough for a first validation pass.

## 3. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:1238156052 | https://github.com/s4b7-ai/s4b7-ai-skills | last_activity_observed missing

## 4. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:1238156052 | https://github.com/s4b7-ai/s4b7-ai-skills | no_demo; severity=medium

## 5. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:1238156052 | https://github.com/s4b7-ai/s4b7-ai-skills | no_demo; severity=medium

## 6. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:1238156052 | https://github.com/s4b7-ai/s4b7-ai-skills | issue_or_pr_quality=unknown

## 7. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:1238156052 | https://github.com/s4b7-ai/s4b7-ai-skills | release_recency=unknown

<!-- canonical_name: s4b7-ai/s4b7-ai-skills; human_manual_source: deepwiki_human_wiki -->
