---
name: quinn
description: "Proves the system works by writing and executing comprehensive test suites."
risk: safe
source: community
date_added: "2026-06-11"
role: QA Tester
phase: 6 — Testing
squad: agent-squad
reports-to: agent-squad
depends-on: rex, alex, mason, luna
---

# Quinn — The QA Tester

Quinn proves the system works. She writes tests that verify the implementation matches the requirements — not tests that pass by accident or tests that only cover the happy path. She works from Rex's acceptance criteria, Alex's Definitions of Done, and Mason's code. Luna's findings inform where she focuses extra coverage.

Quinn does not find style issues. She finds real functional gaps, unhandled edge cases, and broken contracts. Her test suite is the proof that the system can be trusted.

---

## When to Use
- Use this skill when the task matches this description: Proves the system works by writing and executing comprehensive test suites.

## Responsibilities

### 1. Test Strategy Design
- Map every **User Story + Acceptance Criterion** from the Rex Report to at least one test.
- Map every **Definition of Done** from Alex's checklist to a verifiable test.
- Identify which test type covers each scenario:
  - **Unit**: pure functions, business logic, data transformations.
  - **Integration**: DB interactions, service-to-service, API endpoints with real DB.
  - **E2E**: full user flows through the UI or API surface.
  - **Contract**: API shape validation (response structure, status codes).
- Identify **what must be mocked** vs. what should use real implementations.

### 2. Unit Tests
- Test every **pure function** for: happy path, empty input, boundary values, invalid types.
- Test **business logic rules** that come from Rex's requirements — not implementation details.
- Use **AAA structure**: Arrange → Act → Assert. One assert per test concept.
- Test names must describe **behavior, not implementation**: `"returns 400 when email is missing"` not `"test validateInput"`.
- Parameterize tests for **multiple input variants** rather than duplicating test bodies.
- Cover **negative cases explicitly**: what the function should NOT do is as important as what it should.

### 3. Integration Tests
- Test each **API endpoint** with real request/response cycles.
- Test **database operations**: create, read, update, delete — verify data persists and queries return correct shapes.
- Test **auth flows**: valid token passes, expired token fails, missing token fails, wrong-scope token fails.
- Test **error responses**: verify the error envelope shape matches Aria's contract on all 4xx/5xx paths.
- Test **cascade behaviors**: what happens when a parent record is deleted?
- Test **concurrent operations** if race conditions were flagged by Luna.

### 4. Edge Case Coverage
- Every **edge case flagged in the Rex Report** must have a test.
- Test **empty collections, zero-values, null optionals, and max-length strings**.
- Test **special characters** in string inputs (quotes, angle brackets, unicode, null bytes).
- Test **pagination boundaries**: page 0, page beyond last, limit=0, limit=max+1.
- Test **file uploads** (if applicable): empty file, oversized file, wrong MIME type.
- Test **rate limiting** behavior if implemented.

### 5. Test Coverage Report
- Report **line coverage and branch coverage** percentage per module.
- Flag any module below **80% line coverage** — not as a hard failure, but as a risk area.
- Identify **untestable code** (tightly coupled, no dependency injection) and flag it for Mason to refactor.
- List **tests that are failing** with the exact assertion that fails and the actual vs. expected values.

---

## Output Format (Structured Report to Main Agent)

```
QUINN TEST REPORT — v1.0
Project: [name]
Input: Rex Report v[x], Alex Plan v[x], Mason M[n], Luna Review v[x]

## Test Summary
Total tests: X
  Passing: X
  Failing: X
  Skipped: X

Coverage:
  Lines: X%
  Branches: X%
  Modules below 80%: [list]

## Test Results by Layer

### Unit Tests
  [PASS] [test name]
  [FAIL] [test name] — Expected: [x] Actual: [y]

### Integration Tests
  [PASS] [test name]
  [FAIL] [test name] — [reason]

### E2E Tests (if applicable)
  [PASS] [test name]
  [FAIL] [test name]

## Acceptance Criteria Coverage
  [✓] US-001 AC-1: [description]
  [✗] US-002 AC-2: [description] — No test exists / test failing

## DoD Verification
  [✓] Task 1.1 — DoD confirmed by test [test name]
  [✗] Task 2.3 — DoD not verified — [gap description]

## Findings Requiring Code Changes
### [HIGH/MED] — [Short title]
  Issue: [what the test revealed]
  Failing test: [test name]
  Recommended fix: [for Mason]

## Notes for Dep (Deployment)
- [anything relevant for CI/CD test pipeline setup]
```

---

## Handoff Protocol

When tests **fail due to code bugs**:
- Route findings back to **Mason** with the failing test name, assertion, actual vs expected.
- Quinn re-runs only the affected tests after Mason's fix — not the full suite.

When tests **fail due to missing requirements**:
- Route back to **Rex** to clarify the acceptance criteria.

When all tests pass (or only LOW-risk gaps remain):
- Forward test report to **Dep (Deployment)** with "Notes for Dep."
- Flag modules below 80% coverage for **Max (Refactoring)** if a cleanup pass is requested.

---

## Interaction Style

- Evidence-first. Every finding comes with a failing test, not an opinion.
- Does not re-implement business logic to "make tests pass" — tests verify code, not replace it.
- Does not gold-plate the test suite with tests that don't map to requirements — coverage theater wastes everyone's time.
- Flags genuinely untestable code as a design problem, not a testing problem.
- When Luna flagged security findings, Quinn writes **regression tests** for those specific patches.

## Limitations
- AI agents may occasionally hallucinate or provide incorrect guidance. Always verify generated code and architectural designs before pushing to production.
- Context window constraints mean large project histories must be compressed by the Orchestrator.


---
name: quit-sponsor
description: "Helps an AI agent provide non-judgmental, evidence-informed quit-smoking support with user-consented tracking, craving check-ins, and escalation to human or clinical help. Not medical care."
category: personal-development
risk: safe
source: community
source_repo: metrox-eth/quit-sponsor
source_type: community
date_added: "2026-07-12"
author: metrox-eth
tags: [quit-smoking, smoking-cessation, health, habits, addiction-recovery, wellbeing, coaching]
tools: [claude]
license: "MIT"
license_source: "https://github.com/metrox-eth/quit-sponsor/blob/main/LICENSE"
---

# Quit-sponsor

## Overview

Quit-sponsor helps an AI agent act as a consistent, non-judgmental companion while an adult works toward stopping smoking. It can help the person make a plan, prepare for cravings, learn from slips, and keep a private log when they explicitly want one. It does not diagnose, prescribe, or replace a clinician, trained quit coach, crisis service, or emergency service.

This is a condensed adaptation of [metrox-eth/quit-sponsor](https://github.com/metrox-eth/quit-sponsor). Apply the safety rules in this file even if upstream wording differs. The evidence boundary is current public-health guidance: [CDC quitting guidance](https://www.cdc.gov/tobacco/about/how-to-quit.html), the [WHO tobacco cessation guideline](https://www.who.int/publications/i/item/9789240096431), and [NICE NG209](https://www.nice.org.uk/guidance/ng209/chapter/treating-tobacco-dependence). These sources support behavioural help, quit planning, and appropriate pharmacological support; they do not support one universal method for every person.

## When to Use This Skill

- Use when a person asks for help quitting smoking (cigarettes or other smoked tobacco)
- Use when a person announces they are quitting, or asks the agent to witness and track a quit
- Use when a person reports a craving, a slip, or a relapse during an ongoing quit
- Use the optional cannabis module only when joints or cannabis co-use are part of the picture
- For minors, provide supportive language and direct them to age-appropriate local health services rather than running an adult protocol

## How It Works

### Step 1: Take the sponsor role, only on acceptance

Offer the role once, plainly. Ask separately before creating or retaining a logbook. If accepted, record only what the person wants retained and offer a three-clause agreement: (1) check in during a craving when possible; (2) treat slips as information rather than a moral failure; (3) respond with evidence and empathy, not sermons. Ask whether the person wants to stop now, choose a quit date, or work toward stopping through reduction. Help remove smoking materials only if they choose that step.

### Step 2: Run the evidence layer

Use current guidance rather than categorical rules. Help the person build a quit plan, which may include a quit date. Abrupt cessation can work well, but a structured reduction or harm-reduction path toward stopping is also valid when the person is not ready to stop in one step. Explain that withdrawal timing and intensity vary. Offer practical coping options such as delaying, changing context, drinking water, eating if hungry, breathing exercises, movement, and contacting a real supporter. Explain that counselling plus an evidence-based cessation medication often improves success, then direct medication selection, dosing, contraindications, pregnancy questions, and interactions to a clinician or pharmacist.

### Step 3: Run the sponsor decision tree

On a declared craving: acknowledge the check-in, ask whether smoking material is immediately reachable, offer a short coping action the person prefers, and connect them to human support when useful. On a slip: normalize without minimizing, move attribution away from "I am weak" toward the situation and plan, ask what the person wants to do next, and update one coping plan. Offer a clinician, pharmacist, or local quitline early; repeated slips strengthen that recommendation. Schedule follow-ups only when the platform actually supports reminders and the person has opted in—never pretend the agent can initiate contact when it cannot.

### Step 4: Personalize

Across the first days: explore the person's own reasons for change, review prior attempts without blame, write a small set of specific if-then plans, and use language that feels natural to them. Preserve continuity with data minimization: store only what the person explicitly consents to retain, make the storage location clear, and support review or deletion at any time.

## Examples

### Example 1: A craving at 1 a.m.

```
User: "I want one. Right now."
Agent: acknowledges the check-in, asks about reachable material, offers
the person's preferred short coping action (for example water, delay,
breathing, or a brief walk), suggests human support if needed, and logs
the outcome only if the person opted in.
```

### Example 2: The morning after a slip

```
User: "I smoked two at the party last night. I've ruined everything."
Agent: normalizes without minimizing ("the banked days stay banked"),
steers attribution to the situation and the missing plan rather than
character, agrees on re-establishing abstinence today, runs a blame-free
debrief, updates one if-then plan, and checks the slip log for repetition.
```

## Best Practices

- ✅ Ask permission before logging and keep the record local, minimal, reviewable, and deletable
- ✅ Offer a real quitline, clinician, pharmacist, or trusted person early—not only after failure
- ✅ Present multiple evidence-based paths and let the person choose with appropriate clinical support
- ❌ Do not prescribe medication, recommend doses, diagnose symptoms, or promise a fixed withdrawal timeline
- ❌ Do not present abrupt quitting, a quit date, or gradual reduction as universally correct or incorrect
- ❌ Do not moralize about a slip or claim to provide human monitoring the platform cannot perform

## Limitations

- This skill does not replace medical care, therapy, or crisis support; it is orchestration of published evidence, not treatment.
- It assumes persistent memory across sessions; without it the skill degrades to keeping a logbook file the person owns.
- It cannot be a peer group and must never fake one; it pushes toward at least one real human recovery space.
- Local treatment options, medication availability, vaping law, quitlines, and emergency numbers vary by country and can change; verify them before presenting them as current.
- Stop and ask for clarification if required inputs, permissions, or safety boundaries are missing.

## Security & Safety Notes

- For chest pain, severe or sudden difficulty breathing, coughing blood, fainting, signs of stroke, or another possible emergency, stop the coaching flow and tell the person to contact local emergency services now. Do not interpret the symptom or wait for a follow-up check-in.
- For imminent self-harm, suicide risk, acute psychological crisis, or danger from another person, stop the quit protocol and connect the person to local emergency or crisis support and a trusted human now.
- Escalate promptly to a clinician for medication questions, pregnancy or breastfeeding, significant medical or mental-health conditions, escalating alcohol or sedative use, or symptoms that concern the person.
- Do not recommend vaping without verifying current local clinical guidance and law. Do not call any medication a universally safe default; suitability depends on the person.
- The logbook is private health data: keep it local, never exfiltrate or quote it publicly, and delete it when the person requests deletion.


---
name: radare2
description: "Drive the radare2 CLI for binary reconnaissance, disassembly, analysis, function locating, export, and lightweight patching (r2/rabin2/rasm2/radiff2) without a GUI."
risk: safe
source: "https://github.com/zhaoxuya520/reverse-skill"
source_repo: "zhaoxuya520/reverse-skill"
source_type: community
date_added: "2026-08-25"
license: "MIT"
license_source: "https://github.com/zhaoxuya520/reverse-skill/blob/main/LICENSE"
---
# radare2
## When to Use

- Quick terminal-based analysis of a binary without a heavy IDE.
- Scriptable disassembly, diffing, or small binary patches.

面向 `radare2` CLI 的二进制分析技能。重点是直接用命令行完成侦察、分析、定位、导出和轻量修改，不依赖 GUI。

## 适用范围

当用户有这些意图时应优先使用本 skill：

- 要用 `r2` / `radare2` 分析 `exe`、`dll`、`so`、`elf`、`apk`、`dex`、`wasm` 等文件
- 询问 `rabin2`、`rasm2`、`radiff2`、`rahash2`、`rax2` 怎么用
- 需要命令行反汇编、看函数、看字符串、看导入导出、查交叉引用、做 patch
- 需要写 `radare2` 批处理命令、`-c` 自动化命令、或 `r2pipe` 脚本

如果用户明确要 GUI 逆向、Hex-Rays 风格伪代码、或 IDA 工作流，优先考虑 `ida-reverse`。如果是网页 JS 逆向，优先考虑 `reverse-engineering`。

## 先做环境确认

先不要假设 `r2` 可用。先检查：

```powershell
r2 -v
rabin2 -v
```

如果未安装，再检查常见安装位置或提示安装。

Windows 常见可执行文件：

- `radare2.exe`
- `rabin2.exe`
- `rasm2.exe`
- `radiff2.exe`
- `rahash2.exe`
- `rax2.exe`
- `r2pm.exe`

## 内置资源

这个 skill 自带两个资源，优先复用，不要每次临时组织一套重复命令。

### `scripts/recon.ps1`

标准侦察脚本，适合先做第一轮概况分析。会输出：

- 基本信息
- 节区
- 导入
- 导出
- 字符串
- 可选的 `r2 -A` 自动分析摘要

调用方式：

```powershell
powershell -File "<skill-root>\radare2\scripts\recon.ps1" -TargetPath "C:\path\to\sample.exe"
```

如果需要附带 `r2` 自动分析：

```powershell
powershell -File "<skill-root>\radare2\scripts\recon.ps1" -TargetPath "C:\path\to\sample.exe" -RunAnalysis
```

### `references/cheatsheet.md`

当需要更多命令细节、常见场景模板、或要快速回忆语法时，读取这个速查表，而不是凭记忆硬猜。

## 已知现象

### Windows 下偶发 `.sdb` 缺失告警

某些 PE 文件在 `rabin2` 侦察时，可能出现类似下面的告警：

```text
ERROR: Cannot find ...\share\format\dll\*.sdb
```

如果主体输出仍然正常返回，通常不影响基础侦察结论，先继续分析即可。不要因为这类附带告警就直接判定分析失败。

## 基本原则

### 1. 先侦察，后深挖

不要一上来就全量自动分析。先用轻量命令确认文件类型、架构、入口点、字符串、导入表，再决定是否做 `aaa`、`aaaa` 或定向分析。

### 2. 优先最小足够命令

`radare2` 命令非常多，用户通常只需要最短路径：

- 看文件信息：`rabin2 -I`
- 看字符串：`rabin2 -z`
- 看导入导出：`rabin2 -i` / `rabin2 -E`
- 交互分析：`r2 <file>` 后再执行局部命令

### 3. 修改前保持谨慎

如果用户要 patch 二进制：

- 默认先只读打开：`r2 <file>`
- 只有在明确需要修改时再用写模式：`r2 -w <file>` 或会话中 `oo+`
- 修改前先告知风险，避免无意覆盖原文件

## 常用工作流

## 工作流 1：快速侦察

适合刚拿到一个二进制文件时。

### 硬门禁（MUST — 未满足禁止进入工作流 2 及后续）

对 PE/ELF/Mach-O 等含导入表的二进制，**MUST** 先完成导入表检查并落成 Evidence，再进入函数级分析或动态步骤：

1. 执行 `rabin2 -i <sample>`（或 `recon.ps1` 输出中的 imports 段）；DLL/SYS 另 MUST `rabin2 -E` 并记 `E-exports`
2. 将完整/分类后的导入表结果写入 Evidence（建议 id：`E-imports` 或 `E-triage-imports`），至少包含：
   - 复现命令（`repro_command`）
   - 关键导入分类摘要：网络 / 文件 / 加密 / 进程注入 / 注册表 / 其他可疑 API
   - 若导入表为空、解析失败或工具报错：仍 MUST 记录失败现象与原始输出为 Evidence，**不得静默跳过**
   - 导入表「过干净」（仅基础 DLL）：MUST 注明动态加载嫌疑，SHOULD 转入动态抓 API
3. .NET 等无传统 IAT：MUST 走等价锚点（dnSpy/IL/元数据摘要）写入同一 Evidence 语义槽，禁止空过
4. 加壳样本 IAT 修复：x86 用 ImportREC（或等价）、x64 用 Scylla（或等价）。修复失败 MUST 记 `E-iat-repair-fail` 后转动态 API 断点；**禁止**在静态 IAT 上无限死磕（见 `reverse-engineering/references/re-agent-workflow.md` §1.2）
5. 用户明确要求「重做导入表检查 / 重新检查导入表 / 重做 IAT」时：MUST 重做被点名步骤本身（阻塞时先走可行性门闩：说明前提+请确认；强制则标 quality=unreadable），**禁止改换为无关步骤冒充完成**

未记录导入表（或合法等价锚点 / IAT 失败旁路）Evidence 前：MUST NOT 声称「基础侦察完成」，MUST NOT 进入工作流 2+ 的深挖结论。

优先直接运行内置脚本：

```powershell
powershell -File "<skill-root>\radare2\scripts\recon.ps1" -TargetPath "sample.exe"
```

如果只需要手动最小命令，则使用：

```powershell
rabin2 -I sample.exe
rabin2 -z sample.exe
rabin2 -i sample.exe
rabin2 -E sample.exe
```

关注点：

- 文件格式、位数、架构、平台
- 入口点地址
- 可疑字符串：URL、路径、报错、注册表、命令行参数
- 导入函数：网络、文件、加密、进程注入、注册表操作（**MUST 落 Evidence，见上方硬门禁**）

## 工作流 2：交互式分析函数

```powershell
r2 sample.exe
```

进入后常用：

```text
aaa          # 常规自动分析
afl          # 列出函数
iz           # 列出字符串
iS           # 列节区
is           # 列符号
s entry0     # 跳到入口点
pdf          # 反汇编当前函数
VV           # 进入可视化模式（如果终端适合）
q            # 退出
```

说明：

- 默认优先 `aaa`，不要一开始就用更重的 `aaaa`
- 如果样本很大或分析很慢，可以只分析入口附近，再手动扩展

## 工作流 3：定位 main / 关键逻辑

```text
afl~main
afl~sym.
iz~http
iz~error
axt <addr>
```

思路：

- 先从 `main`、入口点、字符串引用入手
- 用 `axt` 查谁引用了某个字符串或地址
- 找到引用点后再 `s <addr>`、`pdf`

## 工作流 4：十六进制与内存查看

```text
px 64        # 当前地址起 64 字节十六进制
pd 20        # 反汇编 20 条指令
psz          # 读取当前地址字符串
pxa          # 更友好的十六进制视图
```

## 工作流 5：二进制 patch

仅当用户明确要求修改文件时使用：

```powershell
r2 -w sample.exe
```

进入后例如：

```text
s 0x401000
wa nop
wa jmp 0x401050
wq
```

常见写操作：

- `wa <asm>`：写汇编
- `wx <hex>`：写原始字节
- `wq`：写入并退出

修改前最好先备份原文件。如果用户没提备份，至少提醒一次。

## 工作流 6：非交互自动化

适合一次性输出结果：

```powershell
r2 -A -q -c "afl;iz;ii;q" sample.exe
```

常用参数：

- `-A`：启动时自动分析
- `-q`：安静模式
- `-c`：执行命令串

如果命令很多，优先整理成易读顺序，不要塞入难以维护的超长串。

更推荐先用内置侦察脚本打底，再决定要不要补定制命令。

## 常用子工具

### `rabin2`

适合静态信息提取：

```powershell
rabin2 -I sample.exe   # 基本信息
rabin2 -S sample.exe   # 节区
rabin2 -s sample.exe   # 符号
rabin2 -i sample.exe   # 导入
rabin2 -E sample.exe   # 导出
rabin2 -z sample.exe   # 字符串
rabin2 -zz sample.exe  # 更详细字符串
```

### `rasm2`

适合快速汇编/反汇编：

```powershell
rasm2 -d "9090"
rasm2 -a x86 -b 64 "xor eax, eax"
```

### `radiff2`

适合对比两个二进制：

```powershell
radiff2 old.exe new.exe
radiff2 -C old.exe new.exe
```

### `rahash2`

适合算哈希：

```powershell
rahash2 -a md5 sample.exe
rahash2 -a sha256 sample.exe
```

### `rax2`

适合进制和编码转换：

```powershell
rax2 0x401000
rax2 4198400
rax2 -s hello
```

## 推荐分析顺序

遇到未知样本时，按这个顺序做：

1. `rabin2 -I` 看格式、架构、入口点
2. `rabin2 -z` 看字符串
3. `rabin2 -i` 看导入函数 — **MUST + Evidence（硬门，见工作流 1）**
4. 如需交互分析，再进 `r2`（仅当步骤 3 的 Evidence 已落盘）
5. 先 `aaa`，再 `afl` / `iz` / `pdf`
6. 通过字符串引用、导入调用、入口流程逐步定位关键函数

这个顺序的好处是噪音低，能尽快建立方向感。步骤 3 不是可选优化，是进入深挖前的硬门。

## Windows 注意事项

- 路径里有空格时，命令必须正确加引号
- 如果当前终端找不到 `r2`，可能是 `PATH` 刚更新，开一个新终端再试
- 有些样本需要管理员权限读取，但默认不要主动提升权限，除非用户明确需要
- 对可疑样本做动态调试前，要先确认用户意图，避免误操作

## 输出风格

当用户不是只要命令，而是要你实际分析文件时：

- 先给出侦察结果摘要
- 再列出关键证据：字符串、导入、函数、地址
- 最后给出下一步建议或继续深入分析

不要只罗列命令而不解释为什么这么做。

## 典型请求示例

### 示例 1：分析一个 exe

用户：`帮我看看这个 exe 干了什么，用 radare2 就行`

处理方式：

1. 先用 `rabin2 -I/-z/-i`
2. 判断是否需要进入 `r2`
3. 用 `aaa`、`afl`、`pdf` 深挖入口和关键字符串引用

### 示例 2：找字符串在哪被调用

用户：`这个报错字符串在哪个函数里触发的`

处理方式：

1. 用 `iz~关键字` 找字符串地址
2. 用 `axt <addr>` 找引用
3. 跳到引用点 `s <addr>` 后 `pdf`

### 示例 3：改掉跳转

用户：`把这个 jne 改成 je`

处理方式：

1. 先确认目标地址
2. 明确告知要进入写模式
3. 用 `wa je <target>` 或直接 `wx`
4. 修改后再次反汇编验证

## 避免的做法

- 不要把 `radare2` 当成只有 `aaa` 一个命令的工具
- 不要在未说明风险时直接写模式打开用户文件
- 不要在还没做基础侦察前就下结论
- **禁止跳过导入表检查**（`rabin2 -i` / recon imports）：未写入 Evidence 不得进入下一步；用户要求重做导入表时禁止改做其他步骤
- **禁止 IAT 修复失败后静态死磕**：记 `E-iat-repair-fail` 后转动态；禁止 64 位样本只用 ImportREC
- 不要把网页 JS 逆向误导到这个 skill；那是 `reverse-engineering` 的范围

## 参考资料

- 命令速查：`references/cheatsheet.md`
- 标准侦察脚本：`scripts/recon.ps1`

## radare2-skills 生态

radare2-skills 项目（radareorg/radare2-skills）提供了更完整的生态工具和工作流：

- **r2xsql**：SQL 查询二进制导入表 / 字符串 / 函数
- **r2mcp / r2http**：MCP 工具与 HTTP 状态化命令通道
- **radius2**：符号执行、符号动态分析
- **r2pm**：插件管理、扩展
- **decompiler plugins**：radare2 插件机制

**使用策略**：
- 当用户提到 `r2xsql`、`r2mcp`、`r2http`、`radius2`、`r2pm`、`rabin2`、`rasm2`、`radiff2`、`rahash2`、`rax2` 时，优先路由到本 skill（radare2/SKILL.md）
- 这些工具只是生态加速器，**不能绕过**：授权门禁、`tool-index` 校验、Evidence 导入、写模式确认
- 给出最小可复现命令示例：
  - `r2xsql -s <file> -q "SELECT ..."`
  - `curl.exe -sS --data-binary 'aaa' http://127.0.0.1:9393/cmd`
  - `radius2 -p <binary> ...`
  - `r2pm -ci <plugin>`

本 skill 保持原有硬门禁和证据链完整性，不允许跳过任何授权或 Evidence 步骤。

---

## 路由上下文

**上游入口**: `skills/SKILL.md`（总控）、`routing.md`
**上游备选**: `ida-reverse/`（需要反编译/伪代码时升级到 IDA）
**下游出口**:
- 需动态分析 → `reverse-engineering/tools-dynamic.md`（Frida/GDB）
- 需深度反编译 → `ida-reverse/`
- PAT 发现有趣字符串后需交叉引用 → `ida-reverse/`（IDA 的 xref 更强大）

**同级关联模块**: `ida-reverse/`（互补：r2 侦察快，IDA 反编译深）

## 按需自举（On-Demand Bootstrap）

本 skill 的入口脚本已接入统一自举系统。缺少 radare2 时不会直接报错，而是自动尝试安装。

### 自动化能力边界

| 工具 | 可自动安装 | 安装方式 | 说明 |
|------|-----------|---------|------|
| r2 | ✓ | GitHub Release ZIP (w64) | 自动下载解压到 `%USERPROFILE%\Tools\radare2\` |
| rabin2 | ✓ | 同上（包含在 radare2 发行包中） | — |
| rasm2 | ✓ | 同上 | — |
| radiff2 | ✓ | 同上 | — |
| rahash2 | ✓ | 同上 | — |
| rax2 | ✓ | 同上 | — |

### 自举触发点

- `scripts/recon.ps1`：缺 `rabin2` 或 `r2` 时自动调用 `bootstrap-reverse.ps1`

### 自举失败时

如果自动安装失败（网络不通、GitHub API 限流等），脚本会抛出明确错误并附带手动安装链接。

手动安装：从 https://github.com/radareorg/radare2/releases 下载 `radare2-*-w64.zip`，解压到 `%USERPROFILE%\Tools\radare2\` 并确保 `bin\` 目录在 PATH 中。

## 任务完成自检（声称完成前 MUST 通过）

- [ ] 我是否执行了工作流中的每一步（而不是只阅读）？
- [ ] 导入表检查是否已执行且写入 Evidence（E-imports / E-triage-imports 或 .NET 等价）？DLL/SYS 是否含 E-exports？
- [ ] IAT 修复失败是否记录 E-iat-repair-fail 并转动态？重做请求是否回到同一步？
- [ ] 我是否基于 `tool-index` 使用了真实工具路径？
- [ ] 我是否产出了可复现证据（命令/脚本/截图/报告）？
- [ ] 我是否完成并回写了 RULES 要求的 Checklist 项？

## Limitations

- Steep learning curve; terse commands reward experienced users.
- High-level decompilation needs r2ghidra/pdc plugins for readability.

> Adapted from [zhaoxuya520/reverse-skill](https://github.com/zhaoxuya520/reverse-skill) (MIT).


---
name: radio-sdr
description: "Authorized RF/SDR security research: signal identification, replay-feasibility study in shielded labs, and wireless protocol analysis outside regulated bands."
risk: offensive
source: "https://github.com/zhaoxuya520/reverse-skill"
source_repo: "zhaoxuya520/reverse-skill"
source_type: community
date_added: "2026-08-25"
license: "MIT"
license_source: "https://github.com/zhaoxuya520/reverse-skill/blob/main/LICENSE"
---
> **⚠ AUTHORIZED USE ONLY**
> This skill is for educational purposes or authorized security assessments only.
> You must have explicit, written permission from the system owner before using this tool.
> Misuse of this tool is illegal and strictly prohibited.

> **Mandatory confirmation gate**
> Before running any command that probes, exploits, changes, persists on, extracts data from, or attempts credential access against a target:
> 1. Ask the user to state the exact target URL, IP, account, or resource.
> 2. Ask the user to confirm written authorization and the permitted scope.
> 3. Show the exact command(s) and explain their expected effect.
> 4. Wait for explicit confirmation in the current conversation.
>
> Without that confirmation, remain read-only and provide defensive guidance only. Prefer a sandbox, disposable VM, or controlled lab.

# RF / SDR Security Research
## When to Use

- Lab study of wireless protocols with your own devices.
- Feasibility checks for replay attacks in RF-isolated environments.

## 适用场景

- 无线遥控/传感器等非 Wi-Fi RF（授权）
- ADS-B/遥控等协议研究（合法接收）
- 与 wifi-wireless 分工：本 skill 偏 **SDR 通用 RF**；Wi-Fi 攻防走 R29

## 工作流

```text
□ 法规与许可确认
□ 只收：识别中心频率与调制
□ GNU Radio / URH 分析
□ 重放仅屏蔽室且书面允许
□ 结论侧重：是否可未授权控制 / 加固建议
```

## 工具链

| 工具 | 用途 |
|------|------|
| RTL-SDR / HackRF（合规） | 收发硬件 |
| URH / GNU Radio | 分析 |
| Inspectrum | 信号 |

## 参考

- `references/sdr-lab-rules.md`
- `../wifi-wireless/` `../ot-ics/` `../hardware-security/`

## 路由上下文

**上游**: MASTER R38
**MUST NOT**: 干扰公共通信、未授权发射

## 任务完成自检

- [ ] 是否默认只收并记录法规边界？
- [ ] Checklist？

## Limitations

- Transmitting on licensed frequencies is illegal without permits; shield and stay low-power.
- Protocol analysis quality depends on SDR bandwidth and sampling.

> Adapted from [zhaoxuya520/reverse-skill](https://github.com/zhaoxuya520/reverse-skill) (MIT).


---
name: radix-ui-design-system
description: "Build accessible design systems with Radix UI primitives. Headless component customization, theming strategies, and compound component patterns for production-grade UI libraries."
risk: safe
source: self
date_added: "2026-02-27"
---

# Radix UI Design System

Build production-ready, accessible design systems using Radix UI primitives with full customization control and zero style opinions.

## Overview

Radix UI provides unstyled, accessible components (primitives) that you can customize to match any design system. This skill guides you through building scalable component libraries with Radix UI, focusing on accessibility-first design, theming architecture, and composable patterns.

**Key Strengths:**
- **Headless by design**: Full styling control without fighting defaults
- **Accessibility built-in**: WAI-ARIA compliant, keyboard navigation, screen reader support
- **Composable primitives**: Build complex components from simple building blocks
- **Framework agnostic**: Works with React, but styles work anywhere

## When to Use This Skill

- Creating a custom design system from scratch
- Building accessible UI component libraries
- Implementing complex interactive components (Dialog, Dropdown, Tabs, etc.)
- Migrating from styled component libraries to unstyled primitives
- Setting up theming systems with CSS variables or Tailwind
- Need full control over component behavior and styling
- Building applications requiring WCAG 2.1 AA/AAA compliance

## Do not use this skill when

- You need pre-styled components out of the box (use shadcn/ui, Mantine, etc.)
- Building simple static pages without interactivity
- The project doesn't use React 16.8+ (Radix requires hooks)
- You need components for frameworks other than React

---

## Core Principles

### 1. Accessibility First

Every Radix primitive is built with accessibility as the foundation:

- **Keyboard Navigation**: Full keyboard support (Tab, Arrow keys, Enter, Escape)
- **Screen Readers**: Proper ARIA attributes and live regions
- **Focus Management**: Automatic focus trapping and restoration
- **Disabled States**: Proper handling of disabled and aria-disabled

**Rule**: Never override accessibility features. Enhance, don't replace.

### 2. Headless Architecture

Radix provides **behavior**, you provide **appearance**:

```tsx
// ❌ Don't fight pre-styled components
<Button className="override-everything" />

// ✅ Radix gives you behavior, you add styling
<Dialog.Root>
  <Dialog.Trigger className="your-button-styles" />
  <Dialog.Content className="your-modal-styles" />
</Dialog.Root>
```

### 3. Composition Over Configuration

Build complex components from simple primitives:

```tsx
// Primitive components compose naturally
<Tabs.Root>
  <Tabs.List>
    <Tabs.Trigger value="tab1">Tab 1</Tabs.Trigger>
    <Tabs.Trigger value="tab2">Tab 2</Tabs.Trigger>
  </Tabs.List>
  <Tabs.Content value="tab1">Content 1</Tabs.Content>
  <Tabs.Content value="tab2">Content 2</Tabs.Content>
</Tabs.Root>
```

---

## Getting Started

### Installation

```bash
# Install individual primitives (recommended)
npm install @radix-ui/react-dialog @radix-ui/react-dropdown-menu

# Or install multiple at once
npm install @radix-ui/react-{dialog,dropdown-menu,tabs,tooltip}

# For styling (optional but common)
npm install clsx tailwind-merge class-variance-authority
```

### Basic Component Pattern

Every Radix component follows this pattern:

```tsx
import * as Dialog from '@radix-ui/react-dialog';

export function MyDialog() {
  return (
    <Dialog.Root>
      {/* Trigger the dialog */}
      <Dialog.Trigger asChild>
        <button className="trigger-styles">Open</button>
      </Dialog.Trigger>

      {/* Portal renders outside DOM hierarchy */}
      <Dialog.Portal>
        {/* Overlay (backdrop) */}
        <Dialog.Overlay className="overlay-styles" />

        {/* Content (modal) */}
        <Dialog.Content className="content-styles">
          <Dialog.Title>Title</Dialog.Title>
          <Dialog.Description>Description</Dialog.Description>

          {/* Your content here */}

          <Dialog.Close asChild>
            <button>Close</button>
          </Dialog.Close>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}
```

---

## Theming Strategies

### Strategy 1: CSS Variables (Framework-Agnostic)

**Best for**: Maximum portability, SSR-friendly

```css
/* globals.css */
:root {
  --color-primary: 220 90% 56%;
  --color-surface: 0 0% 100%;
  --radius-base: 0.5rem;
  --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1);
}

[data-theme="dark"] {
  --color-primary: 220 90% 66%;
  --color-surface: 222 47% 11%;
}
```

```tsx
// Component.tsx
<Dialog.Content
  className="
    bg-[hsl(var(--color-surface))]
    rounded-[var(--radius-base)]
    shadow-[var(--shadow-lg)]
  "
/>
```

### Strategy 2: Tailwind + CVA (Class Variance Authority)

**Best for**: Tailwind projects, variant-heavy components

```tsx
// button.tsx
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';

const buttonVariants = cva(
  // Base styles
  "inline-flex items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground hover:bg-primary/90",
        destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
        outline: "border border-input bg-background hover:bg-accent",
        ghost: "hover:bg-accent hover:text-accent-foreground",
      },
      size: {
        default: "h-10 px-4 py-2",
        sm: "h-9 rounded-md px-3",
        lg: "h-11 rounded-md px-8",
        icon: "h-10 w-10",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
);

interface ButtonProps extends VariantProps<typeof buttonVariants> {
  children: React.ReactNode;
}

export function Button({ variant, size, children }: ButtonProps) {
  return (
    <button className={cn(buttonVariants({ variant, size }))}>
      {children}
    </button>
  );
}
```

### Strategy 3: Stitches (CSS-in-JS)

**Best for**: Runtime theming, scoped styles

```tsx
import { styled } from '@stitches/react';
import * as Dialog from '@radix-ui/react-dialog';

const StyledContent = styled(Dialog.Content, {
  backgroundColor: '$surface',
  borderRadius: '$md',
  padding: '$6',

  variants: {
    size: {
      small: { width: '300px' },
      medium: { width: '500px' },
      large: { width: '700px' },
    },
  },

  defaultVariants: {
    size: 'medium',
  },
});
```

---

## Component Patterns

### Pattern 1: Compound Components with Context

**Use case**: Share state between primitive parts

```tsx
// Select.tsx
import * as Select from '@radix-ui/react-select';
import { CheckIcon, ChevronDownIcon } from '@radix-ui/react-icons';

export function CustomSelect({ items, placeholder, onValueChange }) {
  return (
    <Select.Root onValueChange={onValueChange}>
      <Select.Trigger className="select-trigger">
        <Select.Value placeholder={placeholder} />
        <Select.Icon>
          <ChevronDownIcon />
        </Select.Icon>
      </Select.Trigger>

      <Select.Portal>
        <Select.Content className="select-content">
          <Select.Viewport>
            {items.map((item) => (
              <Select.Item
                key={item.value}
                value={item.value}
                className="select-item"
              >
                <Select.ItemText>{item.label}</Select.ItemText>
                <Select.ItemIndicator>
                  <CheckIcon />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Viewport>
        </Select.Content>
      </Select.Portal>
    </Select.Root>
  );
}
```

### Pattern 2: Polymorphic Components with `asChild`

**Use case**: Render as different elements without losing behavior

```tsx
// ✅ Render as Next.js Link but keep Radix behavior
<Dialog.Trigger asChild>
  <Link href="/settings">Open Settings</Link>
</Dialog.Trigger>

// ✅ Render as custom component
<DropdownMenu.Item asChild>
  <YourCustomButton icon={<Icon />}>Action</YourCustomButton>
</DropdownMenu.Item>
```

**Why `asChild` matters**: Prevents nested button/link issues in accessibility tree.

### Pattern 3: Controlled vs Uncontrolled

```tsx
// Uncontrolled (Radix manages state)
<Tabs.Root defaultValue="tab1">
  <Tabs.Trigger value="tab1">Tab 1</Tabs.Trigger>
</Tabs.Root>

// Controlled (You manage state)
const [activeTab, setActiveTab] = useState('tab1');

<Tabs.Root value={activeTab} onValueChange={setActiveTab}>
  <Tabs.Trigger value="tab1">Tab 1</Tabs.Trigger>
</Tabs.Root>
```

**Rule**: Use controlled when you need to sync with external state (URL, Redux, etc.).

### Pattern 4: Animation with Framer Motion

```tsx
import * as Dialog from '@radix-ui/react-dialog';
import { motion, AnimatePresence } from 'framer-motion';

export function AnimatedDialog({ open, onOpenChange }) {
  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <Dialog.Portal forceMount>
        <AnimatePresence>
          {open && (
            <>
              <Dialog.Overlay asChild>
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  className="dialog-overlay"
                />
              </Dialog.Overlay>

              <Dialog.Content asChild>
                <motion.div
                  initial={{ opacity: 0, scale: 0.95 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.95 }}
                  className="dialog-content"
                >
                  {/* Content */}
                </motion.div>
              </Dialog.Content>
            </>
          )}
        </AnimatePresence>
      </Dialog.Portal>
    </Dialog.Root>
  );
}
```

---

## Common Primitives Reference

### Dialog (Modal)

```tsx
<Dialog.Root> {/* State container */}
  <Dialog.Trigger /> {/* Opens dialog */}
  <Dialog.Portal> {/* Renders in portal */}
    <Dialog.Overlay /> {/* Backdrop */}
    <Dialog.Content> {/* Modal content */}
      <Dialog.Title /> {/* Required for a11y */}
      <Dialog.Description /> {/* Required for a11y */}
      <Dialog.Close /> {/* Closes dialog */}
    </Dialog.Content>
  </Dialog.Portal>
</Dialog.Root>
```

### Dropdown Menu

```tsx
<DropdownMenu.Root>
  <DropdownMenu.Trigger />
  <DropdownMenu.Portal>
    <DropdownMenu.Content>
      <DropdownMenu.Item />
      <DropdownMenu.Separator />
      <DropdownMenu.CheckboxItem />
      <DropdownMenu.RadioGroup>
        <DropdownMenu.RadioItem />
      </DropdownMenu.RadioGroup>
      <DropdownMenu.Sub> {/* Nested menus */}
        <DropdownMenu.SubTrigger />
        <DropdownMenu.SubContent />
      </DropdownMenu.Sub>
    </DropdownMenu.Content>
  </DropdownMenu.Portal>
</DropdownMenu.Root>
```

### Tabs

```tsx
<Tabs.Root defaultValue="tab1">
  <Tabs.List>
    <Tabs.Trigger value="tab1" />
    <Tabs.Trigger value="tab2" />
  </Tabs.List>
  <Tabs.Content value="tab1" />
  <Tabs.Content value="tab2" />
</Tabs.Root>
```

### Tooltip

```tsx
<Tooltip.Provider delayDuration={200}>
  <Tooltip.Root>
    <Tooltip.Trigger />
    <Tooltip.Portal>
      <Tooltip.Content side="top" align="center">
        Tooltip text
        <Tooltip.Arrow />
      </Tooltip.Content>
    </Tooltip.Portal>
  </Tooltip.Root>
</Tooltip.Provider>
```

### Popover

```tsx
<Popover.Root>
  <Popover.Trigger />
  <Popover.Portal>
    <Popover.Content side="bottom" align="start">
      Content
      <Popover.Arrow />
      <Popover.Close />
    </Popover.Content>
  </Popover.Portal>
</Popover.Root>
```

---

## Accessibility Checklist

### Every Component Must Have:

- [ ] **Focus Management**: Visible focus indicators on all interactive elements
- [ ] **Keyboard Navigation**: Full keyboard support (Tab, Arrows, Enter, Esc)
- [ ] **ARIA Labels**: Meaningful labels for screen readers
- [ ] **Color Contrast**: WCAG AA minimum (4.5:1 for text, 3:1 for UI)
- [ ] **Error States**: Clear error messages with `aria-invalid` and `aria-describedby`
- [ ] **Loading States**: Proper `aria-busy` during async operations

### Dialog-Specific:
- [ ] `Dialog.Title` is present (required for screen readers)
- [ ] `Dialog.Description` provides context
- [ ] Focus trapped inside modal when open
- [ ] Escape key closes dialog
- [ ] Focus returns to trigger on close

### Dropdown-Specific:
- [ ] Arrow keys navigate items
- [ ] Type-ahead search works
- [ ] First/last item wrapping behavior
- [ ] Selected state indicated visually and with ARIA

---

## Best Practices

### ✅ Do This

1. **Always use `asChild` to avoid wrapper divs**
   ```tsx
   <Dialog.Trigger asChild>
     <button>Open</button>
   </Dialog.Trigger>
   ```

2. **Provide semantic HTML**
   ```tsx
   <Dialog.Content asChild>
     <article role="dialog" aria-labelledby="title">
       {/* content */}
     </article>
   </Dialog.Content>
   ```

3. **Use CSS variables for theming**
   ```css
   .dialog-content {
     background: hsl(var(--surface));
     color: hsl(var(--on-surface));
   }
   ```

4. **Compose primitives for complex components**
   ```tsx
   function CommandPalette() {
     return (
       <Dialog.Root>
         <Dialog.Content>
           <Combobox /> {/* Radix Combobox inside Dialog */}
         </Dialog.Content>
       </Dialog.Root>
     );
   }
   ```

### ❌ Don't Do This

1. **Don't skip accessibility parts**
   ```tsx
   // ❌ Missing Title and Description
   <Dialog.Content>
     <div>Content</div>
   </Dialog.Content>
   ```

2. **Don't fight the primitives**
   ```tsx
   // ❌ Overriding internal behavior
   <Dialog.Content onClick={(e) => e.stopPropagation()}>
   ```

3. **Don't mix controlled and uncontrolled**
   ```tsx
   // ❌ Inconsistent state management
   <Tabs.Root defaultValue="tab1" value={activeTab}>
   ```

4. **Don't ignore keyboard navigation**
   ```tsx
   // ❌ Disabling keyboard behavior
   <DropdownMenu.Item onKeyDown={(e) => e.preventDefault()}>
   ```

---

## Real-World Examples

### Example 1: Command Palette (Combo Dialog)

```tsx
import * as Dialog from '@radix-ui/react-dialog';
import { Command } from 'cmdk';

export function CommandPalette() {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const down = (e: KeyboardEvent) => {
      if (e.key === 'k' && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        setOpen((open) => !open);
      }
    };
    document.addEventListener('keydown', down);
    return () => document.removeEventListener('keydown', down);
  }, []);

  return (
    <Dialog.Root open={open} onOpenChange={setOpen}>
      <Dialog.Portal>
        <Dialog.Overlay className="fixed inset-0 bg-black/50" />
        <Dialog.Content className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
          <Command>
            <Command.Input placeholder="Type a command..." />
            <Command.List>
              <Command.Empty>No results found.</Command.Empty>
              <Command.Group heading="Suggestions">
                <Command.Item>Calendar</Command.Item>
                <Command.Item>Search Emoji</Command.Item>
              </Command.Group>
            </Command.List>
          </Command>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}
```

### Example 2: Dropdown Menu with Icons

```tsx
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import { DotsHorizontalIcon } from '@radix-ui/react-icons';

export function ActionsMenu() {
  return (
    <DropdownMenu.Root>
      <DropdownMenu.Trigger asChild>
        <button className="icon-button" aria-label="Actions">
          <DotsHorizontalIcon />
        </button>
      </DropdownMenu.Trigger>

      <DropdownMenu.Portal>
        <DropdownMenu.Content className="dropdown-content" align="end">
          <DropdownMenu.Item className="dropdown-item">
            Edit
          </DropdownMenu.Item>
          <DropdownMenu.Item className="dropdown-item">
            Duplicate
          </DropdownMenu.Item>
          <DropdownMenu.Separator className="dropdown-separator" />
          <DropdownMenu.Item className="dropdown-item text-red-500">
            Delete
          </DropdownMenu.Item>
        </DropdownMenu.Content>
      </DropdownMenu.Portal>
    </DropdownMenu.Root>
  );
}
```

### Example 3: Form with Radix Select + React Hook Form

```tsx
import * as Select from '@radix-ui/react-select';
import { useForm, Controller } from 'react-hook-form';

interface FormData {
  country: string;
}

export function CountryForm() {
  const { control, handleSubmit } = useForm<FormData>();

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
      <Controller
        name="country"
        control={control}
        render={({ field }) => (
          <Select.Root onValueChange={field.onChange} value={field.value}>
            <Select.Trigger className="select-trigger">
              <Select.Value placeholder="Select a country" />
              <Select.Icon />
            </Select.Trigger>

            <Select.Portal>
              <Select.Content className="select-content">
                <Select.Viewport>
                  <Select.Item value="us">United States</Select.Item>
                  <Select.Item value="ca">Canada</Select.Item>
                  <Select.Item value="uk">United Kingdom</Select.Item>
                </Select.Viewport>
              </Select.Content>
            </Select.Portal>
          </Select.Root>
        )}
      />
      <button type="submit">Submit</button>
    </form>
  );
}
```

---

## Troubleshooting

### Problem: Dialog doesn't close on Escape key

**Cause**: `onEscapeKeyDown` event prevented or `open` state not synced

**Solution**:
```tsx
<Dialog.Root open={open} onOpenChange={setOpen}>
  {/* Don't prevent default on escape */}
</Dialog.Root>
```

### Problem: Dropdown menu positioning is off

**Cause**: Parent container has `overflow: hidden` or transform

**Solution**:
```tsx
// Use Portal to render outside overflow container
<DropdownMenu.Portal>
  <DropdownMenu.Content />
</DropdownMenu.Portal>
```

### Problem: Animations don't work

**Cause**: Portal content unmounts immediately

**Solution**:
```tsx
// Use forceMount + AnimatePresence
<Dialog.Portal forceMount>
  <AnimatePresence>
    {open && <Dialog.Content />}
  </AnimatePresence>
</Dialog.Portal>
```

### Problem: TypeScript errors with `asChild`

**Cause**: Type inference issues with polymorphic components

**Solution**:
```tsx
// Explicitly type your component
<Dialog.Trigger asChild>
  <button type="button">Open</button>
</Dialog.Trigger>
```

---

## Performance Optimization

### 1. Code Splitting

```tsx
// Lazy load heavy primitives
const Dialog = lazy(() => import('@radix-ui/react-dialog'));
const DropdownMenu = lazy(() => import('@radix-ui/react-dropdown-menu'));
```

### 2. Portal Container Reuse

```tsx
// Create portal container once
<Tooltip.Provider>
  {/* All tooltips share portal container */}
  <Tooltip.Root>...</Tooltip.Root>
  <Tooltip.Root>...</Tooltip.Root>
</Tooltip.Provider>
```

### 3. Memoization

```tsx
// Memoize expensive render functions
const SelectItems = memo(({ items }) => (
  items.map((item) => <Select.Item key={item.value} value={item.value} />)
));
```

---

## Integration with Popular Tools

### shadcn/ui (Built on Radix)

shadcn/ui is a collection of copy-paste components built with Radix + Tailwind.

```bash
npx shadcn@latest init
npx shadcn@latest add dialog
```

**When to use shadcn vs raw Radix**:
- Use shadcn: Quick prototyping, standard designs
- Use raw Radix: Full customization, unique designs

### Radix Themes (Official Styled System)

```tsx
import { Theme, Button, Dialog } from '@radix-ui/themes';

function App() {
  return (
    <Theme accentColor="crimson" grayColor="sand">
      <Button>Click me</Button>
    </Theme>
  );
}
```

---

## Related Skills

- `@tailwind-design-system` - Tailwind + Radix integration patterns
- `@react-patterns` - React composition patterns
- `@frontend-design` - Overall frontend architecture
- `@accessibility-compliance` - WCAG compliance testing

---

## Resources

### Official Documentation
- [Radix UI Docs](https://www.radix-ui.com/primitives)
- [Radix Colors](https://www.radix-ui.com/colors) - Accessible color system
- [Radix Icons](https://www.radix-ui.com/icons) - Icon library

### Community Resources
- [shadcn/ui](https://ui.shadcn.com) - Component collection
- [Radix UI Discord](https://discord.com/invite/7Xb99uG) - Community support
- [CVA Documentation](https://cva.style/docs) - Variant management

### Examples
- [Radix Playground](https://www.radix-ui.com/primitives/docs/overview/introduction#try-it-out)
- [shadcn/ui Source](https://github.com/shadcn-ui/ui) - Production examples

---

## Quick Reference

### Installation
```bash
npm install @radix-ui/react-{primitive-name}
```

### Basic Pattern
```tsx
<Primitive.Root>
  <Primitive.Trigger />
  <Primitive.Portal>
    <Primitive.Content />
  </Primitive.Portal>
</Primitive.Root>
```

### Key Props
- `asChild` - Render as child element
- `defaultValue` - Uncontrolled default
- `value` / `onValueChange` - Controlled state
- `open` / `onOpenChange` - Open state
- `side` / `align` - Positioning

---

**Remember**: Radix gives you **behavior**, you give it **beauty**. Accessibility is built-in, customization is unlimited.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: rag-engineer
description: Expert in building Retrieval-Augmented Generation systems. Masters
  embedding models, vector databases, chunking strategies, and retrieval
  optimization for LLM applications.
risk: critical
source: vibeship-spawner-skills (Apache 2.0)
date_added: 2026-02-27
---

# RAG Engineer

Expert in building Retrieval-Augmented Generation systems. Masters embedding models,
vector databases, chunking strategies, and retrieval optimization for LLM applications.

**Role**: RAG Systems Architect

I bridge the gap between raw documents and LLM understanding. I know that
retrieval quality determines generation quality - garbage in, garbage out.
I obsess over chunking boundaries, embedding dimensions, and similarity
metrics because they make the difference between helpful and hallucinating.

### Expertise

- Embedding model selection and fine-tuning
- Vector database architecture and scaling
- Chunking strategies for different content types
- Retrieval quality optimization
- Hybrid search implementation
- Re-ranking and filtering strategies
- Context window management
- Evaluation metrics for retrieval

### Principles

- Retrieval quality > Generation quality - fix retrieval first
- Chunk size depends on content type and query patterns
- Embeddings are not magic - they have blind spots
- Always evaluate retrieval separately from generation
- Hybrid search beats pure semantic in most cases

## Capabilities

- Vector embeddings and similarity search
- Document chunking and preprocessing
- Retrieval pipeline design
- Semantic search implementation
- Context window optimization
- Hybrid search (keyword + semantic)

## Prerequisites

- Required skills: LLM fundamentals, Understanding of embeddings, Basic NLP concepts

## Patterns

### Semantic Chunking

Chunk by meaning, not arbitrary token counts

**When to use**: Processing documents with natural sections

- Use sentence boundaries, not token limits
- Detect topic shifts with embedding similarity
- Preserve document structure (headers, paragraphs)
- Include overlap for context continuity
- Add metadata for filtering

### Hierarchical Retrieval

Multi-level retrieval for better precision

**When to use**: Large document collections with varied granularity

- Index at multiple chunk sizes (paragraph, section, document)
- First pass: coarse retrieval for candidates
- Second pass: fine-grained retrieval for precision
- Use parent-child relationships for context

### Hybrid Search

Combine semantic and keyword search

**When to use**: Queries may be keyword-heavy or semantic

- BM25/TF-IDF for keyword matching
- Vector similarity for semantic matching
- Reciprocal Rank Fusion for combining scores
- Weight tuning based on query type

### Query Expansion

Expand queries to improve recall

**When to use**: User queries are short or ambiguous

- Use LLM to generate query variations
- Add synonyms and related terms
- Hypothetical Document Embedding (HyDE)
- Multi-query retrieval with deduplication

### Contextual Compression

Compress retrieved context to fit window

**When to use**: Retrieved chunks exceed context limits

- Extract relevant sentences only
- Use LLM to summarize chunks
- Remove redundant information
- Prioritize by relevance score

### Metadata Filtering

Pre-filter by metadata before semantic search

**When to use**: Documents have structured metadata

- Filter by date, source, category first
- Reduce search space before vector similarity
- Combine metadata filters with semantic scores
- Index metadata for fast filtering

## Sharp Edges

### Fixed-size chunking breaks sentences and context

Severity: HIGH

Situation: Using fixed token/character limits for chunking

Symptoms:
- Retrieved chunks feel incomplete or cut off
- Answer quality varies wildly
- High recall but low precision

Why this breaks:
Fixed-size chunks split mid-sentence, mid-paragraph, or mid-idea.
The resulting embeddings represent incomplete thoughts, leading to
poor retrieval quality. Users search for concepts but get fragments.

Recommended fix:

Use semantic chunking that respects document structure:
- Split on sentence/paragraph boundaries
- Use embedding similarity to detect topic shifts
- Include overlap for context continuity
- Preserve headers and document structure as metadata

### Pure semantic search without metadata pre-filtering

Severity: MEDIUM

Situation: Only using vector similarity, ignoring metadata

Symptoms:
- Returns outdated information
- Mixes content from wrong sources
- Users can't scope their searches

Why this breaks:
Semantic search finds semantically similar content, but not necessarily
relevant content. Without metadata filtering, you return old docs when
user wants recent, wrong categories, or inapplicable content.

Recommended fix:

Implement hybrid filtering:
- Pre-filter by metadata (date, source, category) before vector search
- Post-filter results by relevance criteria
- Include metadata in the retrieval API
- Allow users to specify filters

### Using same embedding model for different content types

Severity: MEDIUM

Situation: One embedding model for code, docs, and structured data

Symptoms:
- Code search returns irrelevant results
- Domain terms not matched properly
- Similar concepts not clustered

Why this breaks:
Embedding models are trained on specific content types. Using a text
embedding model for code, or a general model for domain-specific
content, produces poor similarity matches.

Recommended fix:

Evaluate embeddings per content type:
- Use code-specific embeddings for code (e.g., CodeBERT)
- Consider domain-specific or fine-tuned embeddings
- Benchmark retrieval quality before choosing
- Separate indices for different content types if needed

### Using first-stage retrieval results directly

Severity: MEDIUM

Situation: Taking top-K from vector search without reranking

Symptoms:
- Clearly relevant docs not in top results
- Results order seems arbitrary
- Adding more results helps quality

Why this breaks:
First-stage retrieval (vector search) optimizes for recall, not precision.
The top results by embedding similarity may not be the most relevant
for the specific query. Cross-encoder reranking dramatically improves
precision for the final results.

Recommended fix:

Add reranking step:
- Retrieve larger candidate set (e.g., top 20-50)
- Rerank with cross-encoder (query-document pairs)
- Return reranked top-K (e.g., top 5)
- Cache reranker for performance

### Cramming maximum context into LLM prompt

Severity: MEDIUM

Situation: Using all retrieved context regardless of relevance

Symptoms:
- Answers drift with more context
- LLM ignores key information
- High token costs

Why this breaks:
More context isn't always better. Irrelevant context confuses the LLM,
increases latency and cost, and can cause the model to ignore the
most relevant information. Models have attention limits.

Recommended fix:

Use relevance thresholds:
- Set minimum similarity score cutoff
- Limit context to truly relevant chunks
- Summarize or compress if needed
- Order context by relevance

### Not measuring retrieval quality separately from generation

Severity: HIGH

Situation: Only evaluating end-to-end RAG quality

Symptoms:
- Can't diagnose poor RAG performance
- Prompt changes don't help
- Random quality variations

Why this breaks:
If answers are wrong, you can't tell if retrieval failed or generation
failed. This makes debugging impossible and leads to wrong fixes
(tuning prompts when retrieval is the problem).

Recommended fix:

Separate retrieval evaluation:
- Create retrieval test set with relevant docs labeled
- Measure MRR, NDCG, Recall@K for retrieval
- Evaluate generation only on correct retrievals
- Track metrics over time

### Not updating embeddings when source documents change

Severity: MEDIUM

Situation: Embeddings generated once, never refreshed

Symptoms:
- Returns outdated information
- References deleted content
- Inconsistent with source

Why this breaks:
Documents change but embeddings don't. Users retrieve outdated content
or, worse, content that no longer exists. This erodes trust in the
system.

Recommended fix:

Implement embedding refresh:
- Track document versions/hashes
- Re-embed on document change
- Handle deleted documents
- Consider TTL for embeddings

### Same retrieval strategy for all query types

Severity: MEDIUM

Situation: Using pure semantic search for keyword-heavy queries

Symptoms:
- Exact term searches miss results
- Concept searches too literal
- Users frustrated with both

Why this breaks:
Some queries are keyword-oriented (looking for specific terms) while
others are semantic (looking for concepts). Pure semantic search fails
on exact matches; pure keyword search fails on paraphrases.

Recommended fix:

Implement hybrid search:
- BM25/TF-IDF for keyword matching
- Vector similarity for semantic matching
- Reciprocal Rank Fusion to combine
- Tune weights based on query patterns

## Related Skills

Works well with: `ai-agents-architect`, `prompt-engineer`, `database-architect`, `backend`

## When to Use
- User mentions or implies: building RAG
- User mentions or implies: vector search
- User mentions or implies: embeddings
- User mentions or implies: semantic search
- User mentions or implies: document retrieval
- User mentions or implies: context retrieval
- User mentions or implies: knowledge base
- User mentions or implies: LLM with documents
- User mentions or implies: chunking strategy
- User mentions or implies: pinecone
- User mentions or implies: weaviate
- User mentions or implies: chromadb
- User mentions or implies: pgvector

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: rag-implementation
description: "RAG (Retrieval-Augmented Generation) implementation workflow covering embedding selection, vector database setup, chunking strategies, and retrieval optimization."
category: granular-workflow-bundle
risk: safe
source: personal
date_added: "2026-02-27"
---

# RAG Implementation Workflow

## Overview

Specialized workflow for implementing RAG (Retrieval-Augmented Generation) systems including embedding model selection, vector database setup, chunking strategies, retrieval optimization, and evaluation.

## When to Use This Workflow

Use this workflow when:
- Building RAG-powered applications
- Implementing semantic search
- Creating knowledge-grounded AI
- Setting up document Q&A systems
- Optimizing retrieval quality

## Workflow Phases

### Phase 1: Requirements Analysis

#### Skills to Invoke
- `ai-product` - AI product design
- `rag-engineer` - RAG engineering

#### Actions
1. Define use case
2. Identify data sources
3. Set accuracy requirements
4. Determine latency targets
5. Plan evaluation metrics

#### Copy-Paste Prompts
```
Use @ai-product to define RAG application requirements
```

### Phase 2: Embedding Selection

#### Skills to Invoke
- `embedding-strategies` - Embedding selection
- `rag-engineer` - RAG patterns

#### Actions
1. Evaluate embedding models
2. Test domain relevance
3. Measure embedding quality
4. Consider cost/latency
5. Select model

#### Copy-Paste Prompts
```
Use @embedding-strategies to select optimal embedding model
```

### Phase 3: Vector Database Setup

#### Skills to Invoke
- `vector-database-engineer` - Vector DB
- `similarity-search-patterns` - Similarity search

#### Actions
1. Choose vector database
2. Design schema
3. Configure indexes
4. Set up connection
5. Test queries

#### Copy-Paste Prompts
```
Use @vector-database-engineer to set up vector database
```

### Phase 4: Chunking Strategy

#### Skills to Invoke
- `rag-engineer` - Chunking strategies
- `rag-implementation` - RAG implementation

#### Actions
1. Choose chunk size
2. Implement chunking
3. Add overlap handling
4. Create metadata
5. Test retrieval quality

#### Copy-Paste Prompts
```
Use @rag-engineer to implement chunking strategy
```

### Phase 5: Retrieval Implementation

#### Skills to Invoke
- `similarity-search-patterns` - Similarity search
- `hybrid-search-implementation` - Hybrid search

#### Actions
1. Implement vector search
2. Add keyword search
3. Configure hybrid search
4. Set up reranking
5. Optimize latency

#### Copy-Paste Prompts
```
Use @similarity-search-patterns to implement retrieval
```

```
Use @hybrid-search-implementation to add hybrid search
```

### Phase 6: LLM Integration

#### Skills to Invoke
- `llm-application-dev-ai-assistant` - LLM integration
- `llm-application-dev-prompt-optimize` - Prompt optimization

#### Actions
1. Select LLM provider
2. Design prompt template
3. Implement context injection
4. Add citation handling
5. Test generation quality

#### Copy-Paste Prompts
```
Use @llm-application-dev-ai-assistant to integrate LLM
```

### Phase 7: Caching

#### Skills to Invoke
- `prompt-caching` - Prompt caching
- `rag-engineer` - RAG optimization

#### Actions
1. Implement response caching
2. Set up embedding cache
3. Configure TTL
4. Add cache invalidation
5. Monitor hit rates

#### Copy-Paste Prompts
```
Use @prompt-caching to implement RAG caching
```

### Phase 8: Evaluation

#### Skills to Invoke
- `llm-evaluation` - LLM evaluation
- `evaluation` - AI evaluation

#### Actions
1. Define evaluation metrics
2. Create test dataset
3. Measure retrieval accuracy
4. Evaluate generation quality
5. Iterate on improvements

#### Copy-Paste Prompts
```
Use @llm-evaluation to evaluate RAG system
```

## RAG Architecture

```
User Query -> Embedding -> Vector Search -> Retrieved Docs -> LLM -> Response
                |              |              |              |
            Model         Vector DB     Chunk Store    Prompt + Context
```

## Quality Gates

- [ ] Embedding model selected
- [ ] Vector DB configured
- [ ] Chunking implemented
- [ ] Retrieval working
- [ ] LLM integrated
- [ ] Evaluation passing

## Related Workflow Bundles

- `ai-ml` - AI/ML development
- `ai-agent-development` - AI agents
- `database` - Vector databases

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: rayden-code
description: Generate React code with Rayden UI components using correct props, tokens, and premium layout patterns
category: development
risk: safe
source: https://github.com/playbookTV/rayden-ui-design-skill
source_type: community
date_added: 2026-04-10
author: Leslie Williams
tags: react, tailwind, design-system, ui, components, vibe-coding, rayden, rayna-ui, code-generation
tools: Read, Write, Edit, Bash, Glob, Grep
---

# Rayden Code Skill

## Overview

Generate production-quality React + Tailwind CSS code using the Rayden UI component library (34 components). The skill loads a complete API reference with every component, every prop, design tokens, layout patterns, and an explicit anti-pattern ban list — preventing hallucinated components and generic AI output. Built on the Rayna UI design system.

## When to Use This Skill

- You're building a new page or feature using Rayden UI components
- You want to scaffold a dashboard, landing page, auth screen, settings page, or data table
- You need to generate React code that follows a specific design system precisely
- You want to prototype UI quickly with correct component usage and premium aesthetics
- You're vibe coding and want design-system-compliant output

## How It Works

1. **Parses the request** — Identifies page type, required components, and data model
2. **Loads RAYDEN_RULES.md** — Complete reference: 34 components with full props, design philosophy, token classes, layout patterns, anti-patterns, and accessibility rules
3. **Plans the layout** — Decides page structure, component selection, spacing, color, and elevation strategy
4. **Generates code** — Writes React + Tailwind CSS using only documented components and token classes
5. **Self-validates** — Runs a 16-point checklist covering correctness (valid components/props, token usage, nesting) and design quality (whitespace, hierarchy, restraint, responsiveness)

## Examples

### Vibe code a SaaS dashboard

```
/rayden-code a dashboard with KPI cards, a recent orders table, and an activity feed
```

**Use case:** You're building an internal analytics tool and need a full dashboard page with MetricsCard grid, sortable Table, and ActivityFeed sidebar — all with correct Rayden imports and token classes.

### Scaffold a login page

```
/rayden-code login page with email and password
```

**Use case:** You need a centered auth form with Input components, a primary Button, and proper visual hierarchy — following Rayden's "Auth / Focused Form" pattern.

### Build an admin settings page

```
/rayden-code settings page with profile section, notification toggles, and danger zone
```

**Use case:** You're adding a settings area to your app and need form sections with Toggle components, a destructive action zone, and a single-column constrained layout.

### Create a pricing page

```
/rayden-code pricing page with 3 tiers and a feature comparison table
```

**Use case:** You need a marketing pricing section with Card components for each tier, Badge for the recommended plan, and a Table for feature comparison.

### Build an e-commerce product grid

```
/rayden-code product catalog with filters, search, and a card grid
```

**Use case:** You're building a storefront and need a responsive product grid with Chip filters, Input search, Pagination, and Cards with images — all using Rayden's layout and spacing rules.

## Best Practices

- Describe what you want in plain language — the skill maps your request to the right components
- Install `@raydenui/ui` in your project first (`npm install @raydenui/ui`)
- Import `@raydenui/ui/styles.css` in your app entry point for design tokens to work
- Review generated code for business logic — the skill handles UI, not data fetching
- Use alongside `/rayden-use` if you also want the same design built in Figma

## Security & Safety Notes

- This skill only reads its bundled rules file and writes code to your project
- No external network requests
- No secrets or credentials involved
- Generated code uses standard React patterns with no eval or dynamic code execution

## Common Pitfalls

| Problem | Solution |
|---------|----------|
| Components not rendering correctly | Ensure `@raydenui/ui/styles.css` is imported in your app entry |
| "Component doesn't exist" error | The skill only uses documented components — check if you're asking for something Rayden doesn't have |
| Colors look wrong | Use token classes (`bg-primary-500`) not hex values. Ensure the Rayden CSS is loaded |
| Layout not responsive | The skill generates responsive code by default — check that your viewport meta tag is set |

## Related Skills

- `rayden-use` — Build Rayden UI components and screens in Figma via MCP (included in the same package)

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: rayden-use
description: Build and maintain Rayden UI components and screens in Figma via Figma MCP with full design token enforcement
category: design
risk: safe
source: https://github.com/playbookTV/rayden-ui-design-skill
source_type: community
date_added: 2026-04-10
author: Leslie Williams
tags: figma, design-system, ui, components, mcp, rayden, rayna-ui
tools: mcp__claude_ai_Figma__use_figma, mcp__claude_ai_Figma__get_screenshot, mcp__claude_ai_Figma__whoami, Read
---

# Rayden UI Design Skill

## Overview

Build and maintain Rayden UI components and screens directly in Figma using the Figma MCP. The skill enforces the Rayna UI design system — resolved design tokens, craft rules, anti-pattern detection, and visual validation — so every output is mechanically correct and visually premium. Supports three style modes (conservative, balanced, expressive) and includes a dedicated subagent for full-page screen composition.

## When to Use This Skill

- You need to build a new Rayden UI component with all its variants in Figma
- You're composing a full screen (dashboard, landing page, auth form, settings, data table) from Rayden patterns
- You want to audit an existing Figma file for design system compliance
- You need to add new variants to an existing Figma component
- You're syncing React component updates back to Figma

## How It Works

1. **Verifies environment** — Checks Figma MCP connection and write access via `whoami`
2. **Loads component data** — Reads Rayden component specs, anatomy, and tokens from the `@raydenui/ai` MCP server or installed package
3. **Loads craft rules** — Reads supporting files: resolved token values, craft rules, anti-patterns, and screen layout patterns
4. **Identifies task type** — Determines if building a single component, composing a screen, auditing, or adding variants
5. **Applies style mode** — Adjusts spacing, shadow, typography, and visual weight based on conservative/balanced/expressive mode
6. **Builds with helpers** — Generates Figma Plugin API code using mandatory helper functions (hexToRgb, loadFonts, applyShadow, applyBorder) with auto layout on every frame
7. **Visual validation** — Takes screenshots after each build stage and validates against 8 acceptance criteria (alignment, spacing, color accuracy, hierarchy, radius, shadow, primary action count)

## Examples

### Build a component with all variants

```
/rayden-use Button https://figma.com/file/abc123
```

**Use case:** You're starting a new design system file and need the Button component with all variants (primary, secondary, grey, destructive) in solid and outlined appearances across SM and LG sizes.

### Design a SaaS dashboard

```
/rayden-use dashboard-screen balanced https://figma.com/file/abc123
```

**Use case:** You're designing an analytics dashboard and need a sidebar layout with KPI cards, a data table, and an activity feed — all using consistent Rayden tokens and spacing.

### Build a marketing landing page

```
/rayden-compose landing expressive https://figma.com/file/abc123
```

**Use case:** You need a high-impact landing page with bolder typography, stronger shadows, and asymmetric layouts that avoid the generic "AI-generated" look.

### Audit an existing design for compliance

```
/rayden-use audit https://figma.com/file/abc123
```

**Use case:** You have an existing Figma file and want to check that all colors match Rayden tokens, spacing is on the 4px grid, and radius is concentric.

### Add variants to an existing component

```
/rayden-use add-variants Input https://figma.com/file/abc123
```

**Use case:** The Input component exists in your Figma file but is missing error and success states — the skill reads the existing structure and extends it.

## Best Practices

- Always provide a Figma file URL as the last argument
- Use `balanced` mode (default) for most use cases; `conservative` for dense admin UIs, `expressive` for marketing pages
- Let the skill take screenshots between build stages — this is how it validates output quality
- Install `@raydenui/ai` as an MCP server for the richest component data access
- Review the generated output in Figma after completion — the skill validates mechanically but human judgment on aesthetics is still valuable

## Security & Safety Notes

- This skill only reads local supporting files and calls the Figma MCP — no external network requests beyond Figma's API
- Requires Figma Dev or Full seat with write access to the target file
- Does not modify files outside of the target Figma document
- All design tokens are bundled in the skill's supporting files — no secrets or credentials involved

## Common Pitfalls

| Problem | Solution |
|---------|----------|
| "Font not found" error | The skill falls back to Roboto if Inter is unavailable — ensure Inter is loaded in your Figma file for best results |
| Components don't combine as variants | All components must share the same parent frame before calling `combineAsVariants` |
| Colors look wrong | Verify you're using resolved token hex values from tokens.md, not approximations |
| Figma permission denied | Check that your Figma seat is Dev or Full (not Viewer) and the file isn't view-only |

## Related Skills

- `rayden-code` — Generate React code with Rayden UI components (included in the same package)
- `rayden-compose` — Dedicated subagent for composing full-page Figma screens (included in this skill package)

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: rclone-cli
description: Rclone command-line cloud storage manager reference and usage guide. Use this skill whenever the user mentions rclone, or any task involving terminal-based cloud file operations such as upload, download, sync, copy, move, mount, or remote management. Triggers on S3-compatible storage,...
risk: critical
source: https://github.com/chaunsin/agent-skills/tree/master/skills/rclone-cli
source_repo: chaunsin/agent-skills
source_type: community
date_added: 2026-07-01
license: Apache-2.0
license_source: https://github.com/chaunsin/agent-skills/blob/master/LICENSE
---

# rclone — The Swiss Army Knife of Cloud Storage
## When to Use

Use this skill when you need rclone command-line cloud storage manager reference and usage guide. Use this skill whenever the user mentions rclone, or any task involving terminal-based cloud file operations such as upload, download, sync, copy, move, mount, or remote management. Triggers on S3-compatible storage,...

Rclone is a command-line program to manage files on cloud storage. It is a feature-rich alternative to cloud vendors' web storage interfaces. Over 70 cloud storage products support rclone including S3 object stores, business & consumer file storage services, and standard transfer protocols.

Rclone has powerful cloud equivalents to the unix commands rsync, cp, mv, mount, ls, ncdu, tree, rm, and cat. It preserves timestamps and verifies checksums at all times. Transfers can be restarted from the last good file.

**Official resources:** [rclone.org](https://rclone.org/) | [Docs](https://rclone.org/docs/) | [Commands](https://rclone.org/commands/) | [Install](https://rclone.org/install/) | [Forum](https://forum.rclone.org/) | [GitHub](https://github.com/rclone/rclone)

## Prerequisites

Before using rclone, verify it is installed:

```bash
# Check if rclone is installed
rclone --version

# If not found, run the install script:
# See scripts/install.sh in this skill's directory
sudo -v ; curl https://rclone.org/install.sh | sudo bash

# Or for beta version:
sudo -v ; curl https://rclone.org/install.sh | sudo bash -s beta
```

For offline/manual installation, use the bundled script at `scripts/install.sh`.

## Security Warnings

> **IMPORTANT**: Rclone is extremely powerful and can irreversibly modify or delete data on cloud storage.
> Pay close attention to the following safety guidelines:

- **Always use `--dry-run` first** when running `sync`, `move`, `delete`, or `purge` commands. This shows what would happen without actually doing it.
- **Use `--interactive` / `-i` flag** while learning rclone to avoid accidental data loss. It asks for confirmation before each destructive operation.
- **Never expose credentials in plain text** on the command line. Use `rclone config` to store credentials securely, or use environment variables.
- **Private keys and tokens** (S3 secret keys, service account JSON, OAuth tokens) must never be committed to version control or logged. The config file `~/.config/rclone/rclone.conf` contains sensitive data — protect it with `chmod 600`.
- **`rclone purge` ignores all filters** — it deletes everything under the specified path. Use with extreme caution.
- **`rclone sync` makes dest identical to source** — files in dest that are not in source will be DELETED. Always verify with `--dry-run` first.
- **Remote control API** (`--rc`) should bind to localhost only by default. Exposing it without authentication (`--rc-htpasswd`) allows anyone to control your rclone instance.
- **Mount operations** can cause data loss if the mount is interrupted during writes. Use `--vfs-cache-mode full` for safer writes.

## Quick Reference

### Configuration

```bash
# Interactive configuration (recommended)
rclone config

# Show current config (redacts secrets by default)
rclone config show

# Show full config including secrets (DANGEROUS — do not share output)
rclone config show --redacted=false

# List configured remotes
rclone listremotes

# Create a remote non-interactively
rclone config create myremote s3 provider=AWS env_auth=true region=us-east-1

# Update existing remote
rclone config update myremote region=us-west-2
```

### Basic Syntax

```
rclone subcommand [options] source:path dest:path
```

Source and destination paths use `remote:path` syntax. For local paths, just use `/path/to/dir`.

### Core Commands

```bash
# List files
rclone ls remote:path                    # list all objects with size
rclone lsd remote:path                   # list directories
rclone lsl remote:path                   # list with size, modtime, path
rclone lsf remote:path                   # list in flexible format
rclone size remote:path                  # total size and object count
rclone tree remote:path                  # tree view

# Copy (does not delete files at destination)
rclone copy /local/path remote:path      # local to remote
rclone copy remote:path /local/path      # remote to local
rclone copy remote1:path remote2:path    # remote to remote (server-side if possible)

# Sync (makes destination identical to source — DELETES extra files at dest)
rclone sync --dry-run /local/path remote:path    # ALWAYS dry-run first!
rclone sync -i /local/path remote:path           # interactive mode

# Move (copies then deletes source)
rclone move /local/path remote:path

# Delete operations
rclone delete remote:path                # delete contents of path
rclone purge remote:path                 # delete path AND all contents (ignores filters!)

# Check integrity
rclone check /local/path remote:path     # compare source and dest
rclone checksum remote:path              # verify checksums
rclone cryptcheck crypt:path             # verify encrypted remote

# Directory operations
rclone mkdir remote:path                 # create directory
rclone rmdir remote:path                 # remove empty directory
rclone rmdirs remote:path                # remove empty directories recursively

# Other useful commands
rclone cat remote:path/file.txt          # output file to stdout
rclone dedupe remote:path                # interactively find/delete duplicates
rclone about remote:                     # get quota information
rclone version                           # show version
```

### Filtering

Filter rules determine which files rclone processes. Always test with `--dry-run` and `-vv`.

```bash
# Include only specific patterns
rclone copy /src /dst --include "*.jpg"
rclone copy /src /dst --include-from filter-file.txt

# Exclude specific patterns
rclone copy /src /dst --exclude "*.tmp"
rclone copy /src /dst --exclude-from exclude-file.txt

# Use filter rules (preferred when mixing include/exclude)
rclone sync /src /dst --filter "+ *.jpg" --filter "- *"
rclone sync /src /dst --filter-from rules.txt

# Size-based filtering
rclone copy /src /dst --min-size 1M --max-size 10G

# Age-based filtering
rclone copy /src /dst --min-age 7d --max-age 30d

# IMPORTANT: Do NOT mix --include, --exclude, and --filter flags.
# Use --filter exclusively when combining rules.
```

Filter pattern syntax:
- `*` matches any sequence of non-separator characters
- `**` matches any sequence including separators
- `?` matches any single non-separator character
- `{a,b}` matches pattern alternatives
- `{{regexp}}` matches using Go regexp

### Global Flags (Most Common)

```bash
# Verbosity
-v                                        # info level
-vv                                       # debug level (shows filter matches)
--log-level LEVEL                         # DEBUG|INFO|NOTICE|ERROR

# Safety
--dry-run                                 # preview without doing anything
-i, --interactive                         # ask before each operation
--ignore-existing                         # skip files that exist at dest
-I, --ignore-times                        # transfer all, ignore modtime/size

# Transfer control
--transfers N                             # parallel transfers (default 4)
--checkers N                              # parallel checks (default 8)
--bwlimit RATE                            # bandwidth limit (e.g. 10M)
--max-transfer SIZE                       # stop after transferring this much
-c, --checksum                            # use checksum instead of modtime
--size-only                               # compare by size only

# Performance
--multi-thread-streams N                  # multi-thread downloads (default 4)
-P, --progress                            # show real-time progress

# Config
--config STRING                           # config file path
-C, --no-check-dest                       # skip dest check on copy
```

### Mount

```bash
# Basic mount
rclone mount remote:path /mnt/remote

# Recommended mount with caching
rclone mount remote:path /mnt/remote \
  --vfs-cache-mode full \
  --vfs-cache-max-size 10G \
  --vfs-read-chunk-size 128M

# Unmount
fusermount -u /mnt/remote                # Linux
umount /mnt/remote                        # macOS
```

### Serve

```bash
rclone serve http remote:path             # HTTP file server
rclone serve webdav remote:path           # WebDAV server
rclone serve sftp remote:path             # SFTP server
rclone serve ftp remote:path              # FTP server
rclone serve s3 remote:path               # S3-compatible server
rclone serve dlna remote:path             # DLNA media server
rclone serve restic remote:path           # Restic backup backend
rclone serve docker remote:path           # Docker registry
```

### Encryption (Crypt Remote)

```bash
# Configure encrypted remote wrapping another remote
rclone config
# Choose "crypt" type, point to an existing remote (e.g., "drive:private")

# Use crypt remote — files are encrypted/decrypted transparently
rclone copy /local/files crypt:path
rclone ls crypt:path

# Check integrity of encrypted files
rclone cryptcheck crypt:path
```

## Detailed Reference Files

For in-depth information, consult these reference files:

These files are converted from the official Hugo-based rclone documentation under
`testdata/rclone/docs/`. Treat any remaining Hugo shortcode or template syntax
as a conversion bug: replace it with normal Markdown, a static table, or an
official URL before relying on it in an answer.

| File | Content | When to read | Official link |
|------|---------|-------------|---------------|
| `references/usage.md` | Full usage guide: syntax, config, remote paths, options | Understanding advanced rclone behavior | [Docs](https://rclone.org/docs/) |
| `references/flags.md` | Complete global flags reference | Looking up specific flag options | [Flags](https://rclone.org/flags/) |
| `references/filtering.md` | Filtering, includes/excludes, patterns | Building complex filter rules | [Filtering](https://rclone.org/filtering/) |
| `references/rc.md` | Remote control / HTTP API | Using rclone's API for programmatic control | [RC API](https://rclone.org/rc/) |
| `references/bisync.md` | Bidirectional sync between two paths | Setting up two-way sync | [Bisync](https://rclone.org/bisync/) |
| `references/crypt.md` | Encrypted remote configuration | Setting up encrypted cloud storage | [Crypt](https://rclone.org/crypt/) |
| `references/cache.md` | Cache backend and directory caching | Optimizing performance with caching | [Cache](https://rclone.org/cache/) |
| `references/chunker.md` | Transparent file chunking | Handling large files on limited remotes | [Chunker](https://rclone.org/chunker/) |
| `references/union.md` | Union backend (merge multiple remotes) | Combining multiple storage backends | [Union](https://rclone.org/union/) |
| `references/combine.md` | Combine backend (unified namespace) | Unified view of multiple remotes | [Combine](https://rclone.org/combine/) |
| `references/hasher.md` | Hasher backend for checksum handling | Adding hash support to remotes | [Hasher](https://rclone.org/hasher/) |
| `references/overview.md` | Cloud storage system feature comparison | Comparing provider capabilities | [Overview](https://rclone.org/overview/) |
| `references/install.md` | Detailed installation instructions | Troubleshooting installation | [Install](https://rclone.org/install/) |
| `references/docker.md` | Docker usage guide | Running rclone in Docker | [Docker](https://rclone.org/docker/) |
| `references/faq.md` | Frequently asked questions | Troubleshooting common issues | [FAQ](https://rclone.org/faq/) |
| `references/commands/` | Individual command documentation | Detailed command usage | [Commands](https://rclone.org/commands/) |

### Popular Provider References

For configuring specific cloud storage providers, read the corresponding file in
`references/providers/` when present. Some virtual/backing providers, such as
`crypt`, `cache`, `chunker`, `union`, `combine`, and `hasher`, live as top-level
files in `references/` because they are cross-provider backends rather than
single cloud services.
- `s3.md` — Amazon S3 / compatible ([Official](https://rclone.org/s3/))
- `drive.md` — Google Drive ([Official](https://rclone.org/drive/))
- `dropbox.md` — Dropbox ([Official](https://rclone.org/dropbox/))
- `onedrive.md` — Microsoft OneDrive ([Official](https://rclone.org/onedrive/))
- `azureblob.md` — Azure Blob Storage ([Official](https://rclone.org/azureblob/))
- `b2.md` — Backblaze B2 ([Official](https://rclone.org/b2/))
- `googlecloudstorage.md` — Google Cloud Storage ([Official](https://rclone.org/googlecloudstorage/))
- `sftp.md` — SFTP ([Official](https://rclone.org/sftp/))
- `webdav.md` — WebDAV ([Official](https://rclone.org/webdav/))
- `swift.md` — OpenStack Swift ([Official](https://rclone.org/swift/))
- `ftp.md` — FTP ([Official](https://rclone.org/ftp/))
- And 60+ more providers — each has a page at `https://rclone.org/<name>/`

### Command References

For detailed command documentation, read the corresponding file in `references/commands/`:
- `rclone_copy.md`, `rclone_sync.md`, `rclone_move.md` — transfer commands
- `rclone_mount.md` — FUSE mount
- `rclone_serve_*.md` — various serve modes
- `rclone_config*.md` — configuration management
- `rclone_bisync.md` — bidirectional sync
- And 80+ more commands — each has a page at `https://rclone.org/commands/<command>/`

## Common Workflows

### Initial Setup
```bash
rclone config          # interactive setup wizard
rclone lsd remote:     # verify connection works
```

### Backup Local to Cloud
```bash
rclone sync --dry-run -P /home/user/documents remote:backup/documents
# Review dry-run output carefully, then:
rclone sync -P /home/user/documents remote:backup/documents
```

### Cloud-to-Cloud Migration
```bash
rclone copy --dry-run -P source_remote:path dest_remote:path
rclone copy -P --transfers 8 source_remote:path dest_remote:path
```

### Restore from Cloud
```bash
rclone copy --dry-run remote:backup/documents /home/user/restored
rclone copy -P remote:backup/documents /home/user/restored
```

### Bandwidth-Limited Transfer
```bash
rclone copy --bwlimit 10M -P /data remote:backup
```

### Encrypted Backup
```bash
# First configure a crypt remote wrapping your storage remote
rclone config
# Then use the crypt remote for all operations
rclone sync -P /sensitive-data crypt:backup
```

### Scheduled Backup (cron)
```bash
# Add to crontab (daily at 2am):
0 2 * * * rclone sync -P /data remote:backup >> /var/log/rclone.log 2>&1
```

## Limitations

- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.


---
name: re-create
description: "Completely delete and rewrite a file or module from scratch when structural rot makes patching impossible."
risk: critical
source: community
date_added: "2026-06-27"
---

# re-create — Controlled Erasure & Rebuild Protocol

## Overview

> Hollow Purple is Gojo's most destructive technique — blue and red combined into total erasure of the target. But Gojo doesn't use it carelessly. He knows exactly what he's erasing and why. Same here: this skill is the nuclear option, invoked only when patching is the wrong call, executed with full control over what gets erased and what must survive.

Rewrites are dangerous not because rebuilding is hard, but because it is easy to silently erase behavior that was working and expected. This skill enforces a complete inventory of what must survive before a single line is deleted, and a full verification that everything survived after the rebuild.

---

## When to Use This Skill

- Use when a file, module, or component needs to be completely deleted and rewritten from scratch
- Use when structural rot is so deep that individual fixes would only make it worse
- Use when accumulated technical debt makes the code unmaintainable
- Use when the target is fundamentally broken and beyond saving
- **DO NOT** use for partial refactors, single-function fixes, or targeted edits

---

## How It Works

### PHASE 1 — Justify the Erasure

The AI must prove that a full rewrite is necessary. It must answer all of the following:

1. **What specifically is broken or unsalvageable?**
   - Not "it's messy" — specific structural problems that make targeted fixes impossible or counterproductive
2. **Why would targeted edits make things worse, not better?**
   - Patching on top of rot, compounding complexity, architectural mismatch
3. **What is the concrete cost of keeping the current implementation?**
   - Maintenance burden, bug surface, performance, developer velocity

If the AI cannot clearly answer all three, it must fall back to targeted edits instead of a rewrite. A rewrite is not a reward for messy code — it is a last resort.

> **The bar is high.** "This code is ugly" does not justify hollow purple. "The architecture assumes X but the system now requires Y and every patch makes the mismatch worse" does.

---

### PHASE 2 — Read the Target Completely

Before proposing deletion, the AI must read the entire target (file, module, or component) in full.

The AI must identify and catalog:

1. **Public interfaces** — functions, classes, types, or exports that other parts of the codebase call
2. **Implicit contracts** — behaviors that other files depend on even if not formally typed
3. **Working behaviors** — things the current implementation does correctly that must continue to work
4. **Non-obvious logic** — edge cases, guards, or special handling that looks incidental but is intentional
5. **Blast radius** — every file in the codebase that imports from or depends on the target

> **The AI cannot skip this phase even if it has read the file before.** The purpose is not familiarity — it is building the Preservation List.

---

### PHASE 3 — Erasure Declaration (User Must Confirm)

The AI outputs a complete erasure plan and **waits for user confirmation before deleting or writing anything.**

```
HOLLOW PURPLE — ERASURE PLAN
─────────────────────────────────────────
TARGET FOR ERASURE:
  [file path or module name]

WHY TARGETED FIXES ARE WRONG:
  [specific justification — architectural rot, fundamental mismatch, etc.]

PRESERVATION LIST (must survive the rewrite):
  - [public interface / export 1] → [what it does, who depends on it]
  - [public interface / export 2] → [what it does, who depends on it]
  - [working behavior 1]          → [what it does, why it must be kept]
  - [non-obvious logic 1]         → [what it guards against]

BLAST RADIUS (files that depend on the target):
  - [file path] → depends on [what specifically]
  - [file path] → depends on [what specifically]

NEW IMPLEMENTATION PLAN:
  [Description of what the rebuild will look like — structure, approach, key decisions]

WHAT WILL NOT BE PRESERVED:
  [Anything intentionally dropped and why — dead code, deprecated behavior, etc.]
─────────────────────────────────────────
Confirm to proceed with erasure and rebuild.
```

> **Nothing is deleted until the user explicitly confirms.** A reply of "yes", "confirmed", "do it", or equivalent counts. Silence does not.

---

### PHASE 4 — Controlled Erasure

User confirms → the target is deleted. Rules for this phase:

- **Delete cleanly.** Not commented out, not renamed to `_old`, not archived in place — deleted.
- **Delete only the declared target.** Nothing outside the declared scope is touched during erasure.
- **Pause if scope expands.** If deletion reveals unexpected dependencies not in the blast radius list, the AI stops and reports before continuing.

---

### PHASE 5 — Rebuild Against the Preservation List

The AI writes the new implementation. Rules:

1. **Every item on the Preservation List is an obligation.** The rebuild is not complete until every preserved interface, behavior, and edge case is implemented and checked off.
2. **Match the blast radius expectations.** Files that depended on the old implementation must be able to use the new one without changes — unless changes to dependent files were declared in Phase 3.
3. **No bonus features.** The rebuild implements what was declared. New improvements, extra functionality, and cleanup of adjacent things are a separate task.
4. **Follow existing codebase conventions.** The new implementation must use the same patterns, naming conventions, and style as the surrounding codebase — not whatever the AI prefers.

The AI tracks preservation progress explicitly:

```
REBUILD PROGRESS
─────────────────────────────────────────
Preservation List:
  ✓ [interface 1]         → implemented
  ✓ [working behavior 1]  → implemented
  ✗ [non-obvious logic 1] → pending
─────────────────────────────────────────
```

---

### PHASE 6 — Blast Radius Verification

After the rebuild is complete, the AI checks every file in the blast radius:

1. **Re-read each dependent file** and confirm it can still use the new implementation
2. **Verify each dependency** — the function signatures, exports, and behaviors it relied on are present in the rebuild
3. **Flag any breakage** — if a dependent file now has a mismatch, report it and propose a fix before declaring done

Final verification report:

```
HOLLOW PURPLE — VERIFICATION
─────────────────────────────────────────
Preservation List:          ALL ITEMS ✓
Blast radius files checked:
  - [file] → ✓ compatible with new implementation
  - [file] → ✓ compatible with new implementation
New issues introduced:      NONE / [describe if found]
─────────────────────────────────────────
Status: CLEAN ✓  /  NEEDS FOLLOW-UP ⚠
```

---

## Self-Ask Before Erasure

The AI must answer all four before Phase 4 begins:

| # | Question | Required |
|---|---|---|
| 1 | Have I read the entire target and built a complete Preservation List? | Yes — or read more |
| 2 | Have I identified the full blast radius? | Yes — or search more |
| 3 | Has the user confirmed the erasure plan? | Yes — or wait |
| 4 | Is the erasure scoped exactly to what was declared? | Yes — or re-declare |

---

## Hard Rules (Never Violated)

- **No deletion before user confirmation.** Ever.
- **No deletion before the Preservation List is complete.** You cannot protect what you haven't inventoried.
- **No "clean up while I'm at it" during rebuild.** The rebuild scope is exactly what was declared.
- **No undeclared blast radius expansion.** If a dependent file wasn't in the list, stop and report it.
- **No skipping Phase 6.** The rebuild is not done until blast radius files are verified.
- **No rewrites disguised as refactors.** If more than 80% of a file is being changed, this protocol applies.

---

## What This Skill Prevents

- Rewrites that silently drop working edge-case logic that wasn't documented
- Rebuilds that break dependent files because their interfaces changed
- Rewrites done for the wrong reason (style preference, boredom) when a targeted fix would have been better
- Partial rebuilds that leave the codebase in a broken half-old-half-new state
- Blast radius files breaking silently with no one noticing until runtime

---

## Quick Reference

| Phase | Action | Deletes/Writes Code? |
|---|---|---|
| 1 — Justify | Prove erasure is necessary | ❌ No |
| 2 — Read | Read target fully, build Preservation List | ❌ No |
| 3 — Declare | Output erasure plan, wait for confirmation | ❌ No |
| 4 — Erase | Delete the declared target | 🗑 Deletes only |
| 5 — Rebuild | Write new implementation against Preservation List | ✅ Writes |
| 6 — Verify | Check Preservation List + blast radius | ❌ No |

---

## Security & Safety Notes

- **Authorized Use Only:** This skill involves destructive capabilities (deleting files). Always ensure you have appropriate authorization and backups before triggering a full rebuild.
- **Explicit Confirmation Required:** No code should ever be deleted without explicit user confirmation of the Erasure Plan.

---

## Examples

### Example 1: Triggering a full module rewrite
```text
User: "The authentication module is beyond saving. Rewrite this from scratch."

AI: [Outputs HOLLOW PURPLE — ERASURE PLAN]
"Confirm to proceed with erasure and rebuild."

User: "Confirmed."

AI: [Executes Phase 4 and 5: Controlled Erasure and Rebuild against the Preservation List]
```

### Example 2: Erasure correctly rejected in Phase 1
```text
User: "This data formatting script is a mess, rewrite it from scratch."

AI: [Evaluates Phase 1 criteria]
"I cannot justify a full rewrite. While the code is messy, the structural rot is not deep enough to make patching impossible. The blast radius is limited, and targeted edits will improve it without the risk of erasing undocumented behaviors. I will proceed with surgical refactoring instead."
```

---

## Trigger Phrases

- "rewrite this from scratch"
- "delete this and redo it"
- "this is beyond saving / beyond repair"
- "the whole module / component / file is broken"
- "start over on this"
- Any situation where patching would compound the problem rather than solve it

---

## Limitations

- The AI must explicitly justify the rewrite and receive user confirmation before deleting anything.
- The rebuild scope must exactly match what was declared (no bonus features or extra cleanup).
- Does not apply to partial refactoring, single-function fixes, or targeted bug fixes.
- It requires identifying the full blast radius upfront to avoid silently breaking dependencies.