chore: add shared skills catalog (19 skills), installers, manifest, validator

This commit is contained in:
2026-08-26 22:08:40 +07:00
parent 62f31484ea
commit a1050f5502
38 changed files with 1850 additions and 2 deletions

View File

@@ -0,0 +1,34 @@
---
name: code-review-and-quality
description: Use when conducting comprehensive code reviews on pull requests, diffs, or newly implemented features to ensure architectural cleanliness, maintainability, performance, and best engineering practices.
---
# Code Review & Software Quality Assurance
## Purpose
Deliver senior-level code reviews that identify architectural debt, hidden regressions, performance bottlenecks, maintainability issues, and missing test coverage before merging.
## Review Dimensions
### 1. Architectural Alignment & Design
- Does the change fit into the existing system architecture, or introduce conflicting abstractions?
- Is there duplicate functionality that can be eliminated by reusing maintained libraries or existing codebase helpers?
- Are boundaries and contracts between modules explicit and clean?
### 2. Correctness & Edge Cases
- Are asynchronous operations, cancellations, and promise chains handled defensively (no unhandled rejections, race conditions, or leaking timers)?
- How are empty inputs, `null`/`undefined`, zero-length collections, and large datasets handled?
- Are error states surfaced with structured diagnostics instead of swallowed silently?
### 3. Maintainability & Code Hygiene
- Are functions small, focused on a single responsibility, and easy to test?
- Are types strict (no unwarranted `any`, `@ts-ignore`, or loose type assertions)?
- Are names descriptive and self-documenting?
### 4. Performance & Efficiency
- Are database queries, network calls, or expensive computations avoided inside loops (N+1 queries)?
- Is memory allocated efficiently (no memory leaks from long-lived event listeners or unbounded caches)?
## Feedback Guidelines
- Classify comments by importance: `[BLOCKER]`, `[IMPORTANT]`, `[NITPICK]`, `[QUESTION]`, or `[PRAISE]`.
- Always provide actionable suggestions or code snippets showing the recommended improvement.

View File

@@ -0,0 +1,52 @@
---
name: conventional-commits-and-pr
description: Use when generating commit messages, structuring pull request descriptions, or maintaining changelogs following the Conventional Commits specification.
---
# Conventional Commits & Pull Request Documentation
## Purpose
Format commit messages and PR descriptions consistently according to the Conventional Commits 1.0.0 specification for automated versioning and transparent project history.
## Commit Message Format
```
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
```
### Types
- **`feat`**: A new feature (correlates with `MINOR` in Semantic Versioning).
- **`fix`**: A bug fix (correlates with `PATCH` in Semantic Versioning).
- **`docs`**: Documentation only changes.
- **`style`**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc).
- **`refactor`**: A code change that neither fixes a bug nor adds a feature.
- **`perf`**: A code change that improves performance.
- **`test`**: Adding missing tests or correcting existing tests.
- **`build`**: Changes that affect the build system or external dependencies.
- **`ci`**: Changes to CI configuration files and scripts.
- **`chore`**: Other changes that don't modify src or test files.
### Breaking Changes
Indicated by an exclamation mark `!` after the type/scope or `BREAKING CHANGE:` in the footer (correlates with `MAJOR` in SemVer):
```
feat(api)!: drop legacy v1 authentication endpoints
```
## Pull Request Template Structure
```markdown
## Summary
Concise 2-3 sentence overview of what this PR accomplishes and why.
## Key Changes
- **Area 1:** Bullet point explaining concrete change.
- **Area 2:** Bullet point explaining concrete change.
## Verification & Testing
- [x] Unit tests passing (`pnpm test`)
- [x] Tested locally with [scenario description]
```

View File

@@ -0,0 +1,34 @@
---
name: db-migration-safety
description: Use when designing database schemas, writing schema migrations, optimizing slow SQL queries, or planning zero-downtime database changes.
---
# Safe Database Migrations & SQL Optimization
## Purpose
Ensure all database schema changes execute safely in production without blocking table locks, downtime, or data corruption, while optimizing query execution plans.
## Safe Migration Rules (Zero-Downtime Pattern)
### 1. Adding Columns
- **Safe:** Adding nullable columns or columns with default values (PostgreSQL >= 11 handles constant defaults instantly without table rewrites).
- **Unsafe:** Adding `NOT NULL` without a default on large tables (locks table). Use a 3-step migration: add nullable column $\to$ backfill data in batches $\to$ add `NOT NULL` constraint with `NOT VALID` then `VALIDATE CONSTRAINT`.
### 2. Renaming & Dropping Columns
- **Never rename/drop in one step:** Old application instances running during deployment will crash when the column disappears.
- **Expand/Contract Pattern:**
1. Add new column.
2. Write to both old and new columns in application code.
3. Backfill existing rows.
4. Switch reads to new column.
5. Stop writing to old column.
6. Drop old column.
### 3. Adding Indexes Safely
- In PostgreSQL: Always use `CREATE INDEX CONCURRENTLY` (or `DROP INDEX CONCURRENTLY`) to avoid acquiring exclusive write locks.
- In MySQL: Use `ALGORITHM=INPLACE, LOCK=NONE` or gh-ost / pt-online-schema-change for heavy tables.
## SQL Performance & Query Optimization
- Analyze queries with `EXPLAIN (ANALYZE, BUFFERS)` (Postgres) or `EXPLAIN ANALYZE` (MySQL).
- Eliminate Seq Scans / Full Table Scans on high-cardinality tables by adding composite indexes matching query `WHERE` and `ORDER BY` predicates.
- Prevent N+1 queries by leveraging `JOIN`, eager loading, or DataLoader patterns.

View File

@@ -0,0 +1,51 @@
---
name: documentation-and-adrs
description: Use when documenting architectural decisions, drafting ADRs (Architecture Decision Records), or writing technical specifications and system documentation.
---
# Architecture Decision Records (ADRs) & Technical Documentation
## Purpose
Produce concise, actionable, and structured architectural documentation and ADRs that capture the context, options considered, and tradeoffs made.
## ADR Standard Structure (MADR Format)
```markdown
# [Short title of solved problem and decision]
* **Status:** proposed | accepted | rejected | deprecated | superseded
* **Deciders:** [List of stakeholders/engineers]
* **Date:** YYYY-MM-DD
## Context and Problem Statement
What problem are we solving? What are the constraints, requirements, and background context?
## Decision Drivers
* Driver 1 (e.g. performance under 50ms latency)
* Driver 2 (e.g. zero external infrastructure dependencies)
* Driver 3 (e.g. strict backwards compatibility)
## Considered Options
1. Option A — [Short description]
2. Option B — [Short description]
3. Option C — [Short description]
## Decision Outcome
Chosen option: "Option A", because [justification linking to drivers].
### Positive Consequences
* Clear benefit 1
* Clear benefit 2
### Negative Consequences / Tradeoffs
* Accepted limitation 1
* Migration cost or operational overhead
## Pros and Cons of Options
[Brief comparison table or bullet breakdown]
```
## Documentation Principles
1. **One Home per Fact:** Do not duplicate invariants across multiple files.
2. **Focus on "Why" and "Tradeoffs":** Code shows *how*; documentation must explain *why* this choice was made over alternatives.
3. **No Fluff / Slop:** Direct, concise language. Omit generic platitudes.

View File

@@ -0,0 +1,37 @@
---
name: e2e-playwright-expert
description: Use when writing, maintaining, or debugging end-to-end (E2E) browser tests with Playwright. Ensures rock-solid locators, auto-waiting, network mocking, and flakiness prevention.
---
# Playwright E2E Testing Best Practices
## Purpose
Design resilient, deterministic, and maintainable end-to-end browser automation suites that avoid flakiness and accurately test user flows.
## Core Guidelines
### 1. Locator Strategy (Prioritize Resilient Locators)
- **1st Choice:** Accessibility & Role Locators:
`page.getByRole('button', { name: 'Submit' })`, `page.getByLabel('Username')`, `page.getByPlaceholder('Search...')`
- **2nd Choice:** Text and Test IDs:
`page.getByText('Success', { exact: true })`, `page.getByTestId('checkout-form')`
- **Avoid:** Brittle CSS/XPath selectors tied to styling or DOM depth (e.g. `div > div:nth-child(3) > span`).
### 2. Elimination of Flakiness (No Arbitrary Timeouts)
- **Never use `page.waitForTimeout(5000)`:** Rely on Playwright's built-in auto-waiting and web-first assertions:
`await expect(page.getByRole('alert')).toBeVisible()`
- Wait for explicit state transitions (URL changes, DOM updates, specific API responses).
### 3. Network Management & Mocking
- Mock flaky or rate-limited third-party APIs using `page.route()`:
```ts
await page.route('**/api/v1/payments/**', route =>
route.fulfill({ status: 200, json: { success: true } })
)
```
- Wait for critical requests to finish before proceeding with assertions:
`const responsePromise = page.waitForResponse('**/api/data'); ... await responsePromise;`
### 4. Visual Testing & Screenshots
- Use snapshot comparisons with explicit threshold allowances for anti-aliasing:
`await expect(page).toHaveScreenshot({ maxDiffPixelRatio: 0.05 })`

View File

@@ -0,0 +1,31 @@
---
name: github-actions-workflow-architect
description: Use when designing, optimizing, or securing GitHub Actions CI/CD workflows, caching dependencies, configuring matrix builds, and managing secrets.
---
# GitHub Actions CI/CD Workflow Architecture
## Purpose
Build fast, reliable, secure, and cost-effective GitHub Actions workflows following current DevOps and security best practices.
## Core Best Practices
### 1. Security & Principle of Least Privilege
- **Explicit Permissions:** Always declare top-level `permissions:` explicitly (e.g. `contents: read`, `pull-requests: write`). Avoid default broad permissions.
- **Pin Actions to Commit SHA:** Protect against upstream compromise by pinning third-party actions to full commit hashes:
`uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2`
- **Secrets Isolation:** Never pass secrets directly into `run:` bash strings where they can be echoed. Pass them via `env:`.
### 2. Performance & Caching Strategy
- **Dependency Caching:** Use native setup action caching (`actions/setup-node` with `cache: 'pnpm'`, `actions/setup-python` with `cache: 'pip'`).
- **Concurrency Control:** Cancel in-flight duplicate runs on new commits to the same branch:
```yaml
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
```
- **Matrix Builds:** Run tests across platforms (Ubuntu, Windows, macOS) and runtime versions concurrently.
### 3. Workflow Hygiene
- Set reasonable execution timeouts (`timeout-minutes: 15`).
- Use separate jobs with clear `needs:` dependency DAGs (e.g., `lint` & `typecheck` $\to$ `unit-tests` $\to$ `e2e-tests` $\to$ `deploy`).

23
skills/grill-me/SKILL.md Normal file
View File

@@ -0,0 +1,23 @@
---
name: grill-me
description: Use when the user wants to stress-test an architecture plan, interrogate a design, or explicitly says "grill me". Relentlessly stress-tests technical plans before implementation starts.
---
# Grill Me — Architecture & Plan Stress Testing
## Purpose
Prevent implementation mistakes by rigorously interviewing the developer about their design, assumptions, failure modes, data contracts, and scaling considerations before any code is written.
## Rules of Engagement
1. **One or Two Questions at a Time:** Do not dump a checklist of 10 questions. Ask 1-2 pointed, high-impact questions per turn to keep the discussion focused.
2. **Challenge Assumptions:** Look for hidden single points of failure, unstated latency/concurrency assumptions, state synchronization flaws, and unbounded growth.
3. **Explore Failure Modes:**
- What happens when network calls time out or third-party APIs fail?
- How does the system recover from crash/reboot mid-operation?
- What happens during concurrent writes or race conditions?
4. **Demand Concrete Boundaries:**
- Invariants and preconditions.
- Exact schema and error codes, not vague types.
- Zero-downtime migration and rollback paths.
5. **No Code Until Approved:** Refuse to jump to implementation until the plan is decision-complete and stress-tested.
6. **Closing the Grill:** When all material ambiguities and risks are addressed, summarize the verified architecture plan and ask for confirmation to proceed.

View File

@@ -0,0 +1,71 @@
---
name: lab-imagegen
description: Generate images using the user's home-lab ComfyUI server (SDXL-turbo on 2x AMD Radeon Pro VII). Use when the user asks to generate, render, or create an image or picture.
---
# Lab Image Generation (ComfyUI)
The user's home lab runs a ComfyUI server at `http://192.168.31.240:8188` (server1, 2x AMD Radeon Pro VII 16GB, SDXL-turbo). Use it to generate images on demand. No authentication is required — the API is open on the LAN.
## Workflow
Use `run_code` to generate: submit a JSON workflow, poll `/history/{prompt_id}`, then return the served image URL.
### 1. Submit the prompt
POST `/prompt` with `Content-Type: application/json` and body:
```json
{ "prompt": <workflow>, "client_id": "dsh" }
```
The workflow for SDXL-turbo (4 steps):
```json
{
"3": { "class_type": "KSampler", "inputs": { "seed": 123, "steps": 4, "cfg": 1.0, "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0, "model": ["4", 0], "positive": ["6", 0], "negative": ["7", 0], "latent_image": ["5", 0] } },
"4": { "class_type": "CheckpointLoaderSimple", "inputs": { "ckpt_name": "sdxl_turbo.safetensors" } },
"5": { "class_type": "EmptyLatentImage", "inputs": { "width": 512, "height": 512, "batch_size": 1 } },
"6": { "class_type": "CLIPTextEncode", "inputs": { "text": "<POSITIVE>", "clip": ["4", 1] } },
"7": { "class_type": "CLIPTextEncode", "inputs": { "text": "<NEGATIVE>", "clip": ["4", 1] } },
"8": { "class_type": "VAEDecode", "inputs": { "samples": ["3", 0], "vae": ["4", 2] } },
"9": { "class_type": "SaveImage", "inputs": { "filename_prefix": "dsh", "images": ["8", 0] } }
}
```
Defaults: 512x512, steps 4, cfg 1.0, euler/normal, seed random. The response contains `prompt_id` and `node_errors`. **If `node_errors` is non-empty, the submission failed — report them.**
### 2. Poll for completion
Poll `GET http://192.168.31.240:8188/history/{prompt_id}` every ~1.5s. The result entry under `outputs["9"].images` contains `filename`. Stop polling when the image array appears.
### 3. Return the image
The served image URL is:
`http://192.168.31.240:8188/view?filename=<filename>&subfolder=&type=output`
Return this URL (a well-formed markdown image link if the user wants to view it inline).
## Policy
- **Timeout:** poll no longer than ~120s. SDXL-turbo at 4 steps typically finishes in well under 60s. If it exceeds the budget, report a timeout rather than looping forever.
- **Prompt quality:** SDXL-turbo responds best to a descriptive positive prompt and a modest negative prompt (e.g. `blurry, low quality, distorted`). High `cfg` (>1) and high `steps` are unnecessary for turbo.
- Keep the model `sdxl_turbo.safetensors` unless the user asks otherwise — it is the verified installed checkpoint.
- Do not write the PNG bytes to a local file unless asked; return the server URL.
### Example (run_code)
```js
const base = 'http://192.168.31.240:8188'
const wf = { "3": { "class_type": "KSampler", "inputs": { "seed": 42, "steps": 4, "cfg": 1.0, "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0, "model": ["4", 0], "positive": ["6", 0], "negative": ["7", 0], "latent_image": ["5", 0] } }, "4": { "class_type": "CheckpointLoaderSimple", "inputs": { "ckpt_name": "sdxl_turbo.safetensors" } }, "5": { "class_type": "EmptyLatentImage", "inputs": { "width": 512, "height": 512, "batch_size": 1 } }, "6": { "class_type": "CLIPTextEncode", "inputs": { "text": "a red fox in a snowy forest, photorealistic", "clip": ["4", 1] } }, "7": { "class_type": "CLIPTextEncode", "inputs": { "text": "blurry, low quality, distorted", "clip": ["4", 1] } }, "8": { "class_type": "VAEDecode", "inputs": { "samples": ["3", 0], "vae": ["4", 2] } }, "9": { "class_type": "SaveImage", "inputs": { "filename_prefix": "dsh", "images": ["8", 0] } } }
const r = await (await fetch(base + '/prompt', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: wf, client_id: 'dsh' }) })).json()
if (r.node_errors && Object.keys(r.node_errors).length) throw new Error('node_errors: ' + JSON.stringify(r.node_errors))
let url = null
for (let i = 0; i < 160 && !url; i++) {
const h = await (await fetch(base + '/history/' + r.prompt_id)).json()
const imgs = h[r.prompt_id]?.outputs?.['9']?.images
if (imgs?.length) url = base + '/view?filename=' + encodeURIComponent(imgs[0].filename) + '&subfolder=&type=output'
else await new Promise(s => setTimeout(s, 1500))
}
return url
```

View File

@@ -0,0 +1,68 @@
---
name: lab-pdf-ocr
description: Extract text from PDF documents using the user's home-lab Docling OCR server (GPU-backed). Use when the user wants to recognize text, OCR a PDF, or convert a scanned or structured PDF to markdown text.
---
# Lab PDF OCR (Docling)
The user's home lab runs a Docling OCR server at `http://192.168.31.159:5001` (server2, CUDA GPU). Use it to extract text from PDFs. No authentication is required — the API is open on the LAN.
## Workflow
Use `run_code` to upload the PDF, poll the task, then return the extracted markdown text.
### 1. Upload the PDF
POST `/v1/convert/file/async` with multipart form-data. Field `files` = the PDF blob (Content-Type `application/pdf`); `options` = `{}` (JSON).
Response:
```json
{ "task_id": "<uuid>", "task_type": "convert", "task_status": "pending" }
```
### 2. Poll for completion
Poll `GET {base}/v1/status/poll/{task_id}?wait=2` every ~1.2s until `task_status` is `success`. If it is `failed`, fetch the result to get the error.
### 3. Fetch the result
`GET {base}/v1/result/{task_id}` returns:
```json
{
"document": { "filename": "scan.pdf", "md_content": "<recognized markdown text>" },
"status": "success",
"errors": []
}
```
Return `document.md_content` — the recognized markdown text.
## Policy
- **Timeout:** poll no longer than ~120s for typical PDFs. Large or heavily scanned PDFs may take longer; if the budget is exceeded, report a timeout.
- **File source:** read the PDF via `ctx.fs.readBytes(target, signal, maxBytes)` (cap ~20MB).
- Trim leading/trailing whitespace when returning the text. The `md_content` is the authoritative result — ignore `html_content`/`json_content` unless the user specifically wants structure.
### Example (run_code)
```js
const base = 'http://192.168.31.159:5001'
const bytes = await tools.read({ file_path: '/path/to/file.pdf' }) // read via fs tool
// build multipart FormData with the pdf blob
const fd = new FormData()
fd.append('files', new Blob([bytes], { type: 'application/pdf' }), 'file.pdf')
fd.append('options', JSON.stringify({}))
const r = await (await fetch(base + '/v1/convert/file/async', { method: 'POST', body: fd })).json()
if (!r.task_id) throw new Error('no task_id: ' + JSON.stringify(r))
for (let i = 0; i < 120; i++) {
const s = await (await fetch(base + '/v1/status/poll/' + r.task_id + '?wait=2')).json()
if (s.task_status === 'success') {
const res = await (await fetch(base + '/v1/result/' + r.task_id)).json()
return (res.document?.md_content ?? '').trim()
}
if (s.task_status === 'failed' || s.task_status === 'error') throw new Error('Docling failed: ' + s.task_status)
await new Promise(sl => setTimeout(sl, 1200))
}
throw new Error('Docling OCR timed out')
```

View File

@@ -0,0 +1,56 @@
---
name: lab-speech-to-text
description: Transcribe speech from audio files (wav, mp3, ogg, m4a) using the user's home-lab Whishper speech-to-text server (GPU-backed). Use when the user wants to convert audio/voice to text, transcribe a recording, or subtitle.
---
# Lab Speech-to-Text (Whishper)
The user's home lab runs a Whishper speech-to-text server at `http://192.168.31.159:8082` (server2, CUDA GPU, small model). Use it to transcribe audio into text. No authentication is required — the API is open on the LAN.
## Workflow
Use `run_code` to upload the audio, poll the transcription, then return the recognized text.
### 1. Upload the audio
POST `/api/transcriptions` with multipart form-data. Field `files` = the audio blob (mime: `audio/wav`, `audio/mpeg`, `audio/ogg`, or `audio/mp4`). Optional fields: `language` (e.g. `ru`, `en`), `modelSize`.
Response:
```json
{ "id": "<uuid>", "status": 0, "task": "transcribe", "device": "cuda", "result": { "text": "" } }
```
### 2. Poll for the result
`GET {base}/api/transcriptions/{id}`. A `status` of `-1` means the job is still queued or running. When `status >= 0` and `result.text` is non-empty, transcription is done.
### 3. Return the text
The transcription text is in `result.text`. Return it (trimmed). Also note `result.language` and `result.duration` if useful.
## Policy
- **Timeout:** poll no longer than ~120s for typical clips. Longer audio may exceed that; report a timeout rather than looping forever.
- **File source:** read the audio via `ctx.fs.readBytes(target, signal, maxBytes)` (cap ~20MB). Prefer a local path to the file.
- If the user wants a language hint, pass it as `language` (e.g. `ru`).
### Example (run_code)
```js
const base = 'http://192.168.31.159:8082'
// read the audio file bytes first
const fd = new FormData()
fd.append('files', new Blob([audioBytes], { type: 'audio/wav' }), 'note.wav')
fd.append('language', 'ru') // optional
const up = await (await fetch(base + '/api/transcriptions', { method: 'POST', body: fd })).json()
if (!up.id) throw new Error('no id: ' + JSON.stringify(up))
let text = null
for (let i = 0; i < 80 && !text; i++) {
const s = await (await fetch(base + '/api/transcriptions/' + up.id)).json()
const t = s?.result?.text
if (typeof t === 'string' && t.length > 0 && s.status !== -1) text = t
else await new Promise(sl => setTimeout(sl, 1500))
}
if (!text) throw new Error('Transcription timed out')
return text.trim()
```

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Lan Zheng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,31 @@
---
name: research-add-fields
description: Add field definitions to existing research outline.
user-invocable: true
---
# Research Add Fields - Supplement Research Fields
## Trigger
`/research-add-fields`
## Workflow
### Step 1: Auto-locate Fields File
Find `*/fields.yaml` file in current working directory, auto-read existing fields definitions.
### Step 2: Get Supplement Source
Ask user to choose:
- **A. User direct input**: User provides field names and descriptions
- **B. Web Search**: Launch a web-search subagent via the `subagent` tool to search common fields in this domain (methodology: `.agents/skills/research/agents/web-search-agent.md`)
### Step 3: Display and Confirm
- Display suggested new fields list
- User confirms which fields to add
- User specifies field category and detail_level
### Step 4: Save Update
Append confirmed fields to fields.yaml, save file.
## Output
Updated `{topic}/fields.yaml` file (in-place modification, requires user confirmation)

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Lan Zheng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,29 @@
---
name: research-add-items
description: Add items (research objects) to existing research outline.
user-invocable: true
---
# Research Add Items - Supplement Research Objects
## Trigger
`/research-add-items`
## Workflow
### Step 1: Auto-locate Outline
Find `*/outline.yaml` file in current working directory, auto-read.
### Step 2: Get Supplement Sources in Parallel
Simultaneously:
- **A. Ask user**: What items to supplement? Any specific names?
- **B. Ask if Web Search needed**: Launch a web-search subagent via the `subagent` tool to search for more items (methodology: `.agents/skills/research/agents/web-search-agent.md`)?
### Step 3: Merge and Update
- Append new items to outline.yaml
- Display to user for confirmation
- Avoid duplicates
- Save updated outline
## Output
Updated `{topic}/outline.yaml` file (in-place modification)

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Lan Zheng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,104 @@
---
name: research-deep
description: Read research outline, launch independent agent for each item for deep research. Disable task output.
user-invocable: true
---
# Research Deep - Deep Research
## Trigger
`/research-deep`
## Workflow
### Step 1: Auto-locate Outline
Find `*/outline.yaml` file in current working directory, read items list, execution config (including items_per_agent).
### Step 2: Resume Check
- Check completed JSON files in output_dir
- Skip completed items
### Step 3: Batch Execution
- Batch by batch_size (before launching the next batch, ask the user to confirm via `ask_user_question`)
- Each agent handles items_per_agent items
- Launch one background web-search subagent per batch via the `subagent` tool (run_in_background: true). Its prompt is the Prompt Template below with the {xxx} variables filled, immediately followed by the research methodology loaded from `.agents/skills/research/agents/web-search-agent.md` (resolved against the session workspace) with every `{RESEARCH_SKILL_DIR}` placeholder replaced by the absolute `research` skill directory. The subagent writes its JSON file itself and returns only a one-line completion note (task output disabled).
**Parameter Retrieval**:
- `{topic}`: topic field from outline.yaml
- `{item_name}`: item's name field
- `{item_related_info}`: item's complete yaml content (name + category + description etc.)
- `{output_dir}`: execution.output_dir from outline.yaml (default: ./results)
- `{fields_path}`: absolute path to {topic}/fields.yaml
- `{output_path}`: absolute path to {output_dir}/{item_name_slug}.json (slugify item_name: replace spaces with _, remove special chars)
- `{validator_path}`: absolute path to this skill's bundled `validate_json.py` (this skill's Base directory from `<skill_resources>` + `validate_json.py`)
**Hard Constraint**: The following prompt must be strictly reproduced, only replacing variables in {xxx}, do not modify structure or wording.
**Prompt Template**:
```python
prompt = f"""## Task
Research {item_related_info}, output structured JSON to {output_path}
## Field Definitions
Read {fields_path} to get all field definitions
## Output Requirements
1. Output JSON according to fields defined in fields.yaml
2. Mark uncertain field values with [uncertain]
3. Add uncertain array at the end of JSON, listing all uncertain field names
4. All field values must be in English
## Output Path
{output_path}
## Validation
After completing JSON output, run validation script to ensure complete field coverage:
python3 {validator_path} -f {fields_path} -j {output_path}
Task is complete only after validation passes.
"""
```
**One-shot Example** (assuming researching GitHub Copilot):
```
## Task
Research name: GitHub Copilot
category: International Product
description: Developed by Microsoft/GitHub, first mainstream AI coding assistant, ~40% market share, output structured JSON to {project_dir}/results/GitHub_Copilot.json
## Field Definitions
Read {project_dir}/fields.yaml to get all field definitions
## Output Requirements
1. Output JSON according to fields defined in fields.yaml
2. Mark uncertain field values with [uncertain]
3. Add uncertain array at the end of JSON, listing all uncertain field names
4. All field values must be in English
## Output Path
{project_dir}/results/GitHub_Copilot.json
## Validation
After completing JSON output, run validation script to ensure complete field coverage:
python3 {validator_path} -f {project_dir}/fields.yaml -j {project_dir}/results/GitHub_Copilot.json
Task is complete only after validation passes.
```
### Step 4: Wait and Monitor
- Wait for current batch to complete
- Launch next batch
- Display progress
### Step 5: Summary Report
After all complete, output:
- Completion count
- Failed/uncertain marked items
- Output directory
## Agent Config
- Background execution: Yes
- Task Output: Disabled (agent has explicit output file when complete)
- Resume support: Yes
## Prerequisites
Require python3 with PyYAML. Export RESEARCH_DEEP_SKILL_DIR as this skill's absolute directory (the Base directory from `<skill_resources>`) on its own line before running the validator, e.g. `python3 "$RESEARCH_DEEP_SKILL_DIR/validate_json.py" -f <fields.yaml> -j <result.json>`; the launcher fills `{validator_path}` with that absolute path. (On the Windows shell tool the export is `$env:RESEARCH_DEEP_SKILL_DIR = "<path>"` on its own line within the same pwsh invocation.)

View File

@@ -0,0 +1,198 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import sys
from collections import defaultdict
from pathlib import Path
import yaml
CATEGORY_MAPPING = {
"basic_info": ["basic_info", "Basic Info"],
"technical_features": ["technical_features", "technical_characteristics", "Technical Features"],
"performance_metrics": ["performance_metrics", "performance", "Performance Metrics"],
"milestone_significance": ["milestone_significance", "milestones", "Milestone Significance"],
"business_info": ["business_info", "commercial_info", "Business Info"],
"competition_ecosystem": ["competition_ecosystem", "competition", "Competition Ecosystem"],
"history": ["history", "History"],
"market_positioning": ["market_positioning", "market", "Market Positioning"],
}
_SKIP_KEYS = {"_source_file", "uncertain"}
def load_fields_yaml(fields_path):
"""Parse fields.yaml in the single schema the research skills emit:
fields:
<category>:
- {name: ..., description: ..., detail_level: ...}
...
uncertain: []
This is the ONLY accepted shape. A fields.yaml that does not match fails
loudly instead of silently passing with zero fields.
Required semantics (so the validator can never pass vacuously / "lie"):
- if ANY field carries an explicit `required:` key -> opt-in, preserve it
- else (detail_level-style, no markers) -> ALL fields required, because the
script's stated purpose is COMPLETE field coverage.
"""
with fields_path.open(encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
defs = [] # (name, category, required_or_None)
fn = data.get("fields")
if not isinstance(fn, dict):
print(f"[ERROR] fields.yaml must use the `fields: {{<category>: [{{name, ...}}]}}` shape; got {type(fn).__name__ if fn is not None else 'None'}.")
sys.exit(1)
for cname, flist in fn.items():
if cname in _SKIP_KEYS:
continue
if not isinstance(flist, list):
print(f"[ERROR] category `{cname}` must map to a list of field dicts; got {type(flist).__name__}.")
sys.exit(1)
for field in flist:
if isinstance(field, dict) and "name" in field:
defs.append((str(field["name"]), str(cname), field.get("required", None)))
else:
print(f"[ERROR] field entry under `{cname}` must be a dict with a `name` key; got {field!r}.")
sys.exit(1)
if not defs:
print("[ERROR] fields.yaml parsed zero fields. Ensure at least one category with field dicts.")
sys.exit(1)
all_fields = {n for n, _, _ in defs}
if any(r is not None for _, _, r in defs):
required_fields = {n for n, _, r in defs if r}
else:
required_fields = set(all_fields)
field_categories = {n: c for n, c, _ in defs}
return all_fields, required_fields, field_categories
def extract_json_fields(data, category_mapping=None):
category_mapping = CATEGORY_MAPPING if category_mapping is None else category_mapping
nested_keys = {k for keys in category_mapping.values() for k in keys}
fields = set()
stack = [(data, True)]
while stack:
obj, is_category_level = stack.pop()
if isinstance(obj, dict):
for k, v in obj.items():
if k in _SKIP_KEYS:
continue
if is_category_level and k in nested_keys:
if isinstance(v, dict):
stack.append((v, True))
continue
fields.add(k)
elif isinstance(obj, list):
stack.extend((item, is_category_level) for item in obj if isinstance(item, dict))
return fields
def validate_json(json_path, all_fields, required_fields, field_categories):
with json_path.open(encoding="utf-8") as f:
data = json.load(f)
json_fields = extract_json_fields(data)
covered = all_fields & json_fields
missing = all_fields - json_fields
extra = json_fields - all_fields
missing_required = missing & required_fields
missing_by_category = defaultdict(list)
for field in missing:
missing_by_category[field_categories.get(field, "Unknown")].append(field)
return {
"file": json_path.name,
"total_defined": len(all_fields),
"covered": len(covered),
"missing": len(missing),
"extra": len(extra),
"coverage_rate": len(covered) / len(all_fields) * 100 if all_fields else 100,
"missing_required": sorted(missing_required),
"missing_optional": sorted(missing - required_fields),
"missing_by_category": {k: sorted(v) for k, v in missing_by_category.items()},
"extra_fields": sorted(extra),
"valid": len(missing_required) == 0,
}
def print_result(result, verbose=True):
status = "PASS" if result["valid"] else "FAIL"
line = "=" * 60
print(f"\n{line}")
print(f"[{status}] {result['file']}")
print(line)
print(f"Coverage: {result['coverage_rate']:.1f}% ({result['covered']}/{result['total_defined']})")
if result["missing_required"]:
print(f"\n[ERROR] Missing required fields ({len(result['missing_required'])}):")
print("\n".join(f" - {f}" for f in result["missing_required"]))
if verbose and result["missing_optional"]:
missing_required = set(result["missing_required"])
print(f"\n[WARN] Missing optional fields ({len(result['missing_optional'])}):")
for cat in sorted(result["missing_by_category"]):
optional = [f for f in result["missing_by_category"][cat] if f not in missing_required]
if optional:
print(f" [{cat}]: {', '.join(optional)}")
if verbose and result["extra_fields"]:
extra = result["extra_fields"]
print(f"\n[INFO] Extra fields ({len(extra)}):")
print(f" {', '.join(extra[:10])}")
if len(extra) > 10:
print(f" ... and {len(extra) - 10} more")
def main():
import argparse
parser = argparse.ArgumentParser(description="Validate whether JSON files cover all fields defined in fields.yaml")
parser.add_argument("--fields", "-f", type=str, help="Path to fields.yaml", default="fields.yaml")
parser.add_argument("--json", "-j", type=str, nargs="*", help="JSON file paths to validate")
parser.add_argument("--dir", "-d", type=str, help="Directory containing JSON files", default="results")
parser.add_argument("--quiet", "-q", action="store_true", help="Show summary only")
args = parser.parse_args()
fields_path = Path(args.fields)
if not fields_path.exists():
for p in (Path.cwd() / "fields.yaml", Path.cwd().parent / "fields.yaml"):
if p.exists():
fields_path = p
break
if not fields_path.exists():
print(f"[ERROR] fields.yaml not found: {fields_path}")
sys.exit(1)
print(f"Field definition file: {fields_path}")
all_fields, required_fields, field_categories = load_fields_yaml(fields_path)
print(f"Total fields: {len(all_fields)} (required: {len(required_fields)}, optional: {len(all_fields) - len(required_fields)})")
json_files = (
[Path(p) for p in args.json]
if args.json
else sorted(Path(args.dir).glob("*.json")) if Path(args.dir).exists() else []
)
if not json_files:
print("[WARN] No JSON files found")
sys.exit(0)
results = []
for json_path in json_files:
if not json_path.exists():
print(f"[WARN] File not found: {json_path}")
continue
result = validate_json(json_path, all_fields, required_fields, field_categories)
results.append(result)
print_result(result, verbose=not args.quiet)
line = "=" * 60
print(f"\n{line}")
print("Summary")
print(line)
passed = sum(1 for r in results if r["valid"])
avg_coverage = sum(r["coverage_rate"] for r in results) / len(results) if results else 0
print(f"Validation passed: {passed}/{len(results)}")
print(f"Average coverage: {avg_coverage:.1f}%")
if passed < len(results):
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Lan Zheng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,96 @@
---
name: research-report
description: Summarize deep research results into markdown report, cover all fields, skip uncertain values.
user-invocable: true
---
# Research Report - Summary Report
## Trigger
`/research-report`
## Workflow
### Step 1: Locate Results Directory
Find `*/outline.yaml` in current working directory, read topic and output_dir config.
### Step 2: Scan Optional Summary Fields
Read all JSON results, extract fields suitable for TOC display (numeric, short metrics), e.g.:
- github_stars
- google_scholar_cites
- swe_bench_score
- user_scale
- valuation
- release_date
Use ask_user_question to ask user:
- Which fields to display in TOC besides item name?
- Provide dynamic options list (based on actual fields in JSON)
### Step 3: Generate Python Conversion Script
Generate `generate_report.py` in `{topic}/` directory, script requirements:
- Read all JSON from output_dir
- Read fields.yaml to get field structure
- Cover all field values from each JSON
- Skip fields with values containing [uncertain]
- Skip fields listed in uncertain array
- Generate markdown report format: Table of contents (with anchor links + user-selected summary fields) + Detailed content (by field category)
- Save to `{topic}/report.md`
**TOC Format Requirements**:
- Must include every item
- Each item displays: number, name (anchor link), user-selected summary fields
- Example: `1. [GitHub Copilot](#github-copilot) - Stars: 10k | Score: 85%`
#### Script Technical Requirements (Must Follow)
**1. JSON Structure Compatibility**
Support two JSON structures:
- Flat structure: Fields directly at top level `{"name": "xxx", "release_date": "xxx"}`
- Nested structure: Fields in category sub-dict `{"basic_info": {"name": "xxx"}, "technical_features": {...}}`
Field lookup order: Top level -> category mapping key -> Traverse all nested dicts
**2. Category Multi-language Mapping**
fields.yaml category names and JSON keys can be any combination (CN-CN, CN-EN, EN-CN, EN-EN). Must establish bidirectional mapping:
```python
CATEGORY_MAPPING = {
"Basic Info": ["basic_info", "Basic Info"],
"Technical Features": ["technical_features", "technical_characteristics", "Technical Features"],
"Performance Metrics": ["performance_metrics", "performance", "Performance Metrics"],
"Milestone Significance": ["milestone_significance", "milestones", "Milestone Significance"],
"Business Info": ["business_info", "commercial_info", "Business Info"],
"Competition & Ecosystem": ["competition_ecosystem", "competition", "Competition & Ecosystem"],
"History": ["history", "History"],
"Market Positioning": ["market_positioning", "market", "Market Positioning"],
}
```
**3. Complex Value Formatting**
- list of dicts (e.g., key_events, funding_history): Format each dict as one line, separate kv with ` | `
- Normal list: Short lists joined with comma, long lists displayed with line breaks
- Nested dict: Recursive formatting, display with semicolon or line breaks
- Long text strings (over 100 chars): Add line breaks `<br>` or use blockquote format for readability
**4. Extra Fields Collection**
Collect fields that exist in JSON but not defined in fields.yaml, put in "Other Info" category. Note to filter:
- Internal fields: `_source_file`, `uncertain`
- Nested structure top-level keys: `basic_info`, `technical_features` etc.
- `uncertain` array: Display each field name on separate line, don't compress into one line
**5. Uncertain Value Skipping**
Skip conditions:
- Field value contains `[uncertain]` string
- Field name is in `uncertain` array
- Field value is None or empty string
### Step 4: Execute Script
Run the generated script with the shell tool (`pwsh` on Windows, `bash` on POSIX): `python3 "<absolute {topic} dir>/generate_report.py"`
## Output
- `{topic}/generate_report.py` - Conversion script
- `{topic}/report.md` - Summary report
## Prerequisites
Require python3 with PyYAML.

21
skills/research/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Lan Zheng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

148
skills/research/SKILL.md Normal file
View File

@@ -0,0 +1,148 @@
---
name: research
description: Conduct preliminary research on a topic and generate research outline. For academic research, benchmark research, technology selection, etc.
user-invocable: true
---
# Research Skill - Preliminary Research
## Trigger
`/research <topic>`
## Workflow
### Step 1: Generate Initial Framework from Model Knowledge
Based on topic, use model's existing knowledge to generate:
- Main research objects/items list in this domain
- Suggested research field framework
Output {step1_output}, use ask_user_question to confirm:
- Need to add/remove items?
- Does field framework meet requirements?
### Step 2: Web Search Supplement
Use ask_user_question to ask for time range (e.g., last 6 months, since 2024, unlimited).
**Parameter Retrieval**:
- `{topic}`: User input research topic
- `{YYYY-MM-DD}`: Current date
- `{step1_output}`: Complete output from Step 1
- `{time_range}`: User specified time range
**Hard Constraint**: The following prompt must be strictly reproduced, only replacing variables in {xxx}, do not modify structure or wording.
Launch 1 background web-search subagent via the `subagent` tool (run_in_background: true). Its prompt is the Prompt Template below with the {xxx} variables filled, immediately followed by the research methodology loaded from `$RESEARCH_SKILL_DIR/agents/web-search-agent.md` with every `{RESEARCH_SKILL_DIR}` placeholder replaced by `$RESEARCH_SKILL_DIR`.
```python
prompt = f"""## Task
Research topic: {topic}
Current date: {YYYY-MM-DD}
Based on the following initial framework, supplement latest items and recommended research fields.
## Existing Framework
{step1_output}
## Goals
1. Verify if existing items are missing important objects
2. Supplement items based on missing objects
3. Continue searching for {topic} related items within {time_range} and supplement
4. Supplement new fields
## Output Requirements
Return structured results directly (do not write files):
### Supplementary Items
- item_name: Brief explanation (why it should be added)
...
### Recommended Supplementary Fields
- field_name: Field description (why this dimension is needed)
...
### Sources
- [Source1](url1)
- [Source2](url2)
"""
```
**One-shot Example** (assuming researching AI Coding History):
```
## Task
Research topic: AI Coding History
Current date: 2025-12-30
Based on the following initial framework, supplement latest items and recommended research fields.
## Existing Framework
### Items List
1. GitHub Copilot: Developed by Microsoft/GitHub, first mainstream AI coding assistant
2. Cursor: AI-first IDE, based on VSCode
...
### Field Framework
- Basic Info: name, release_date, company
- Technical Features: underlying_model, context_window
...
## Goals
1. Verify if existing items are missing important objects
2. Supplement items based on missing objects
3. Continue searching for AI Coding History related items within since 2024 and supplement
4. Supplement new fields
## Output Requirements
Return structured results directly (do not write files):
### Supplementary Items
- item_name: Brief explanation (why it should be added)
...
### Recommended Supplementary Fields
- field_name: Field description (why this dimension is needed)
...
### Sources
- [Source1](url1)
- [Source2](url2)
```
### Step 3: Ask User for Existing Fields
Use ask_user_question to ask if user has existing field definition file, if so read and merge.
### Step 4: Generate Outline (Separate Files)
Merge {step1_output}, {step2_output} and user's existing fields, generate two files:
**outline.yaml** (items + config):
- topic: Research topic
- items: Research objects list
- execution:
- batch_size: Number of parallel agents (confirm with ask_user_question)
- items_per_agent: Items per agent (confirm with ask_user_question)
- output_dir: Results output directory (default: ./results)
**fields.yaml** (field definitions):
- Field categories and definitions
- Each field's name, description, detail_level
- detail_level hierarchy: brief -> moderate -> detailed
- uncertain: Uncertain fields list (reserved field, auto-filled in deep phase)
### Step 5: Output and Confirm
- Create directory: `./{topic_slug}/`
- Save: `outline.yaml` and `fields.yaml`
- Show to user for confirmation
## Output Path
```
{current_working_directory}/{topic_slug}/
├── outline.yaml # items list + execution config
└── fields.yaml # field definitions
```
## Follow-up Commands
- `/research-add-items` - Supplement items
- `/research-add-fields` - Supplement fields
- `/research-deep` - Start deep research
## Resources
This skill bundles its research subagent at `agents/web-search-agent.md` and strategy modules under `agents/web-search-modules/` (5 files: academic-papers.md, chinese-tech.md, general-web.md, github-debug.md, stackoverflow.md). Set `RESEARCH_SKILL_DIR` to this skill's Base directory shown in `<skill_resources>`. The module path used inside web-search-agent.md is `{RESEARCH_SKILL_DIR}/agents/web-search-modules/`.

View File

@@ -0,0 +1,126 @@
---
name: web-search-agent
description: Use this agent when you need to research information on the internet, particularly for debugging issues, finding solutions to technical problems, or gathering comprehensive information from multiple sources. This agent excels at finding relevant discussions. Use when you need creative search strategies, thorough investigation of a topic, or compilation of findings from diverse sources.
---
You are an elite internet researcher specializing in finding relevant information across diverse online sources. Your expertise lies in creative search strategies, thorough investigation, and comprehensive compilation of findings.
**Core Capabilities:**
- You excel at crafting multiple search query variations to uncover hidden gems of information
- You systematically explore GitHub Issues, Reddit, Stack Overflow, Stack Exchange, technical forums, official documentation, blog posts, Dev.to, Medium, Hacker News, Discord, X/Twitter, Google Scholar, arXiv, Hugging Face Papers, bioRxiv, ResearchGate, Semantic Scholar, ACM Digital Library, IEEE Xplore, CSDN, Juejin, SegmentFault, Zhihu, Cnblogs, OSChina, V2EX, Tencent Cloud and Alibaba Cloud developer communities
- You never settle for surface-level results - you dig deep to find the most relevant and helpful information
- You are particularly skilled at debugging assistance, finding others who've encountered similar issues
- You understand context and can identify patterns across disparate sources
**Research Methodology:**
0. **Get Current Date**: The harness provides today's date (YYYY-MM-DD) in the agent context; use it for time-sensitive searches.
1. **Query Generation Phase**: When given a topic or problem, you will:
- Generate 5-10 different search query variations to maximize coverage
- Include technical terms, error messages, library names, and common misspellings
- Think of how different people might describe the same issue (novice vs. expert terminology)
- Consider searching for both the problem AND potential solutions
- Use exact phrases in quotes for error messages
- Include version numbers and environment details when relevant
**Scenario-Specific Query Strategies (MANDATORY Module Loading)**:
Before executing any web_search or web_fetch, you MUST use the read tool to load the relevant strategy module(s) from `{RESEARCH_SKILL_DIR}/agents/web-search-modules/`. Based on the research type, read the corresponding file(s):
- **Debugging/GitHub Issues** -> read `github-debug.md`
Sources: GitHub Issues (open/closed)
- **Best Practices/Comparative Research** -> read `general-web.md`
Sources: Reddit, Official Docs, Blogs, Hacker News, Dev.to, Medium, Discord, X/Twitter
- **Academic Paper Search** -> read `academic-papers.md`
Sources: Google Scholar, arXiv, HuggingFace Papers, bioRxiv, ResearchGate, Semantic Scholar, ACM DL, IEEE Xplore
- **Chinese Tech Community** -> read `chinese-tech.md`
Sources: CSDN, Juejin, SegmentFault, Zhihu, Cnblogs, OSChina, V2EX, Tencent/Alibaba Cloud
- **Technical Q&A** -> read `stackoverflow.md`
Sources: Stack Overflow, Stack Exchange, technical forums
DO NOT skip this step. DO NOT call web_search or web_fetch before loading at least one module.
**Module Routing**: Each search may be routed to one or multiple modules:
- **Single module**: When the task clearly belongs to one domain, load only that module
- e.g. "search vllm memory leak issue" -> read `github-debug` only
- **Multi-module**: When complex tasks require cross-domain coverage, load multiple modules
- e.g. "transformers OOM problem" -> read `github-debug` + `stackoverflow` + `chinese-tech`
- e.g. "attention mechanism papers and open-source implementations" -> read `academic-papers` + `github-debug`
- The agent recommends modules based on task content; users can also specify explicitly
2. **Source Prioritization**: Systematically search across sources defined in the routed modules above. Each module specifies its own prioritized source list. When multiple modules are routed, merge their source lists and deduplicate.
3. **Information Gathering Standards**: You will:
- Read beyond the first few results - valuable information is often buried
- Look for patterns in solutions across different sources
- Pay attention to dates to ensure relevance (note if solutions are outdated)
- Note different approaches to the same problem and their trade-offs
- Identify authoritative sources and experienced contributors
- Check for updated solutions or superseded approaches
- Verify if issues have been resolved in newer versions
4. **Compilation Standards**: When presenting findings, you will:
- **Caller's requested format takes priority** - satisfy their requirements first
- Start with key findings summary (2-3 sentences)
- Organize information by relevance and reliability
- Provide direct links to all sources
- Include relevant code snippets or configuration examples
- Note any conflicting information and explain the differences
- Highlight the most promising solutions or approaches
- Include timestamps, version numbers, and environment details when relevant
- Clearly mark experimental or unverified solutions
**Quality Assurance:**
- Verify information across multiple sources when possible
- Clearly indicate when information is speculative or unverified
- Date-stamp findings to indicate currency
- Distinguish between official solutions and community workarounds
- Note the credibility of sources (official docs vs. random blog post vs. maintainer comment)
- Flag deprecated or outdated information
- Highlight security implications if relevant
- **Self-check before presenting**: Have I explored diverse sources? Any gaps? Is info current? Actionable next steps?
- **If insufficient info found**: State what was searched, explain limitations, suggest alternatives or communities to ask
**Standard Output Format**:
```
=== IF caller specified format ===
[Caller's requested format/content]
## Sources and References ← ALWAYS REQUIRED
1. [Link with description]
2. [Link with description]
=== ELSE use standard format ===
## Executive Summary
[Key findings in 2-3 sentences - what you found and the recommended path forward]
## Detailed Findings
[Organized by relevance/approach, with clear headings]
### [Approach/Solution 1]
- Description
- Source links
- Code examples if applicable
- Pros/Cons
- Version/environment requirements
### [Approach/Solution 2]
[Same structure]
## Sources and References ← ALWAYS REQUIRED
1. [Link with description]
2. [Link with description]
## Recommendations
[If applicable - your analysis of the best approach based on findings]
## Additional Notes
[Caveats, warnings, areas needing more research, or conflicting information]
```
Remember: You are not just a search engine - you are a research specialist who understands context, can identify patterns, and knows how to find information that others might miss. Your goal is to provide comprehensive, actionable intelligence that saves time and provides clarity. Every research task should leave the user better informed and with clear next steps.

View File

@@ -0,0 +1,28 @@
# Academic Papers Module
> 从 web-search-agent.md 提取的学术论文搜索专用策略
**触发场景**: 论文查找、学术研究、算法原理
## 搜索源 (Academic Sources)
- **Google Scholar** (scholar.google.com) - comprehensive academic search engine
- **arXiv** (arxiv.org) - preprints in physics, math, CS, and related fields
- **Hugging Face Papers** (huggingface.co/papers) - daily/monthly trending ML/AI papers with community upvotes
- **bioRxiv** (biorxiv.org) - preprints in biology and life sciences
- **ResearchGate** (researchgate.net) - academic social network with papers and author profiles
- **Semantic Scholar** (semanticscholar.org) - AI-powered academic search
- **ACM Digital Library** and **IEEE Xplore** - CS and engineering papers
## 查询策略 (1.3 Academic Paper Search)
- Use Google Scholar as primary source with advanced search operators
- Search by author names, paper titles, DOI numbers, institutions, and publication years
- Use quotation marks for exact titles and author name combinations
- Include year ranges to find seminal works and recent publications
- Look for related papers and citation patterns to identify seminal works
- Search for preprints on arXiv, bioRxiv, and institutional repositories
- Check author profiles and ResearchGate for publications and PDFs
- Identify open-access versions and legal paper download sources
- Track citation networks to understand research evolution
- Note impact factors, h-index, and citation counts for relevance assessment
- Search for conference proceedings, journals, and workshop papers
- Identify funding agencies and research grants for context

View File

@@ -0,0 +1,20 @@
# Chinese Tech Module
> 从 web-search-agent.md 提取的中文技术社区专用策略
**触发场景**: 中文技术问题、国内框架、中文社区解决方案
## 搜索源 (Chinese Technical Sites)
- **CSDN** (csdn.net) - China's largest IT community with extensive technical articles and solutions
- **Juejin** (juejin.cn) - high-quality Chinese developer community with modern tech focus
- **SegmentFault** (segmentfault.com) - Chinese Q&A platform similar to Stack Overflow
- **Zhihu** (zhihu.com) - Chinese knowledge-sharing platform with technical discussions
- **Cnblogs** (cnblogs.com) - Chinese blogging platform with deep technical content
- **OSChina** (oschina.net) - Chinese open source community and technical news
- **V2EX** (v2ex.com) - Chinese developer community with active discussions
- **Tencent Cloud** and **Alibaba Cloud** developer communities - enterprise-level solutions
## 查询策略 (Bilingual Research)
- **For bilingual research**: Generate queries in both English and Chinese (中文)
- Use Chinese technical terms and common translations (e.g., "报错" for errors, "解决方案" for solutions)
- Search Chinese sites with Chinese keywords for better results from Chinese developer communities

View File

@@ -0,0 +1,27 @@
# General Web Module
> 从 web-search-agent.md 提取的通用网页搜索策略
**触发场景**: 通用信息、新闻、产品对比、最佳实践
## 搜索源
- **Reddit** (r/programming, r/webdev, r/javascript, and topic-specific subreddits) - real-world experiences
- **Official documentation** and changelogs - authoritative information
- **Blog posts** and tutorials - detailed explanations
- **Hacker News** discussions - high-quality technical discourse
- **Dev.to** (dev.to) - developer community with high-quality technical articles
- **Medium** (medium.com) - technical blog platform with in-depth articles
- **Discord** - official discussion channels for many open source projects
- **X/Twitter** - technical announcements and discussions from developers and maintainers
## 查询策略 (1.2 Best Practices & Comparative Research)
- Look for official recommendations first
- Cross-reference with community consensus
- Find examples from production codebases
- Identify anti-patterns and common pitfalls
- Note evolving best practices and deprecated approaches
- Create structured comparisons with clear criteria
- Find real-world usage examples and case studies
- Look for performance benchmarks and user experiences
- Identify trade-offs and decision factors
- Consider scalability, maintenance, and learning curve

View File

@@ -0,0 +1,18 @@
# GitHub Debug Module
> 从 web-search-agent.md 提取的 GitHub/Debug 专用策略
**触发场景**: 项目bug、error调试、issue查找、版本特定问题
## 搜索源
- **GitHub Issues** (both open and closed) - excellent for known bugs and workarounds
## 查询策略 (1.1 Debugging Assistance)
- Search for exact error messages in quotes
- Look for issue templates that match the problem pattern
- Find workarounds, not just explanations
- Check if it's a known bug with existing patches or PRs
- Look for similar issues even if not exact matches
- Identify if the issue is version-specific
- Search for both the library name + error and more general descriptions
- Check closed issues for resolution patterns

View File

@@ -0,0 +1,9 @@
# Stack Overflow Module
> 从 web-search-agent.md 提取的技术问答专用策略
**触发场景**: 编程问答、代码实现、API用法
## 搜索源
- **Stack Overflow** and other Stack Exchange sites - technical Q&A
- **Technical forums** and discussion boards - community wisdom

View File

@@ -0,0 +1,35 @@
---
name: security-audit
description: Use when performing security audits, vulnerability scanning, threat modeling, or reviewing code for OWASP Top 10 vulnerabilities, injection flaws, and authentication/authorization issues.
---
# Security Audit & Threat Modeling
## Purpose
Rigorously review code, APIs, and infrastructure configurations for security vulnerabilities, information leaks, authorization flaws, and untrusted input exploitation.
## Core Audit Vectors
### 1. Injection & Deserialization
- **SQL / NoSQL Injection:** Are queries parameterized? Are dynamic clauses safely validated against strict allowlists?
- **Command Injection:** Are subprocess arguments passed as arrays (`argv`) rather than concatenated shell strings? Is shell evaluation (`shell: true`, `eval`, `exec`) avoided?
- **Unsafe Deserialization:** Is arbitrary YAML/JSON deserialization guarded against code execution (`js-yaml` with `DEFAULT_SCHEMA` vs dangerous constructors)?
### 2. Authentication & Access Control (Broken Object-Level Auth)
- Are access checks enforced on every endpoint/resolver, or solely in the UI?
- Can user A access or mutate resources of user B by altering IDs/keys in requests (IDOR)?
- Are session tokens and credentials rotated and scrubbed from telemetry/logs?
### 3. File System & Path Traversal
- Are file paths normalized and verified to stay within designated workspace/sandbox boundaries (`path.resolve`, canonical path traversal checks)?
- Are symlinks resolved to prevent sandbox escaping?
### 4. Data Exposure & Secrets Management
- Are API keys, tokens, and database passwords excluded from git commits and client bundles?
- Are errors sanitized in production to avoid leaking internal stack traces and server topology?
- Is CORS and CSP configured to minimum required access?
## Deliverables
1. **Threat Model:** Identified attack surfaces and threat actors.
2. **Vulnerabilities List:** Ranked by CVSS/Severity (Critical, High, Medium, Low) with concrete PoC scenarios.
3. **Remediation Plan:** Immediate patch and long-term architectural defense-in-depth.

View File

@@ -0,0 +1,33 @@
---
name: systematic-debugging
description: Use when debugging complex bugs, unexpected test failures, race conditions, or production anomalies. Enforces a rigorous scientific debugging method over trial-and-error edits.
---
# Systematic Debugging — The Scientific Method for Bug Fixing
## Core Discipline
Never guess, shotgun edit, or apply speculative fixes without proving the root cause. Follow the 5-phase scientific debugging loop.
## Phase 1: Reproduce & Isolate
1. **Deterministic Reproduction:** Create a minimal, self-contained test case or command that reliably reproduces the failure.
2. **Eliminate Variables:** Strip away unrelated components, mocks, or background noise.
3. **Capture Ground Truth:** Inspect actual inputs, outputs, error codes, and stack traces — do not rely on memory or assumptions.
## Phase 2: Formulate Hypotheses
1. Brainstorm candidate root causes based on observed behavior.
2. Rank hypotheses by likelihood.
3. For each hypothesis, define an empirical test: *"If hypothesis X is true, observing Y will yield Z."*
## Phase 3: Test Hypotheses (Binary Search & Instrumentation)
1. Add targeted logs, breakpoints, or assertion guards at key boundary points.
2. Use bisection (git bisect or code division) to narrow down when/where state deviates from expected invariants.
3. Invalidate or confirm hypotheses one by one.
## Phase 4: Root Cause Fix
1. Fix the underlying design flaw, invariant violation, or race condition — not just the symptom.
2. Verify that the fix does not break related code or introduce regressions.
3. Clean up all temporary debug logging and instrumentation.
## Phase 5: Regression Prevention
1. Commit the automated reproduction test (unit/integration test) alongside the fix.
2. Add explicit invariants or typing to prevent this class of bug at compile or boot time.

View File

@@ -0,0 +1,31 @@
---
name: test-driven-development
description: Use when building new features, refactoring existing modules, or fixing bugs using Test-Driven Development (TDD: Red-Green-Refactor cycle).
---
# Test-Driven Development (TDD)
## Purpose
Build robust, well-designed, and thoroughly tested software by writing automated tests *before* writing production code.
## The Red-Green-Refactor Cycle
### 1. 🔴 RED — Write a Failing Test
- Define the desired behavior from the caller's perspective.
- Write a focused test asserting that behavior.
- **Run the test** and verify that it fails for the *expected* reason (e.g. missing method or assertion mismatch, not a syntax/import error).
### 2. 🟢 GREEN — Write the Minimal Implementation
- Write just enough code to make the failing test pass.
- Resist the temptation to implement speculative future features or premature optimizations.
- **Run the test suite** and verify that all tests pass.
### 3. 🔵 REFACTOR — Clean Up & Optimize
- Eliminate duplication and code smells.
- Improve naming, types, and module structure.
- Ensure all invariants hold while keeping the test suite green at all times.
## Best Testing Practices
- **Test Behavior, Not Implementation Details:** Avoid asserting private state or internal methods. Test through public interfaces.
- **Fast and Deterministic:** Unit tests should run in milliseconds without relying on real network calls or unstable timing delays.
- **AAA Pattern:** Arrange (setup data), Act (call function/method), Assert (check outcome and side-effects).

View File

@@ -0,0 +1,26 @@
---
name: web-performance-audit
description: Use when analyzing web application performance, Core Web Vitals (LCP, INP, CLS), JavaScript bundle size optimization, rendering bottlenecks, and memory leaks.
---
# Web Performance & Core Web Vitals Optimization
## Purpose
Systematically audit, profile, and optimize frontend web applications for load speed, rendering responsiveness, and minimal memory footprints.
## Key Audit Areas
### 1. Core Web Vitals
- **LCP (Largest Contentful Paint < 2.5s):** Optimize hero images (priority hints `fetchpriority="high"`, modern formats WebP/AVIF), preload critical fonts, eliminate render-blocking CSS/JS.
- **INP (Interaction to Next Paint < 200ms):** Break long JavaScript tasks into chunks (`requestIdleCallback`, `scheduler.yield()`), debounce high-frequency input handlers, offload heavy calculations to Web Workers.
- **CLS (Cumulative Layout Shift < 0.1):** Set explicit `width` and `height` on images and embeds, reserve space for dynamic ads/widgets, avoid injecting DOM elements above existing content.
### 2. Bundle Size & Code Splitting
- Run visual bundle analyzers (`rollup-plugin-visualizer` / `webpack-bundle-analyzer`).
- Replace bloated libraries with lightweight alternatives (e.g., date-fns or native `Intl` over moment.js).
- Implement route-based and component-based lazy loading (`React.lazy()`, dynamic `import()`).
### 3. Rendering & React Performance
- Prevent unnecessary re-renders with targeted memoization (`useMemo`, `useCallback`, `React.memo`), but avoid speculative over-memoization.
- Virtualize large lists (`tanstack-virtual` / `react-window`) when rendering hundreds of DOM nodes.
- Minimize layout thrashing (batch DOM reads before writes).