Compare commits

...

39 Commits

Author SHA1 Message Date
Frank
b994a076c2 docs: add guidance for project documentation capture (#355) 2026-03-07 14:48:11 -08:00
Pangerkumzuk Longkumer
e2d78d6def Add Contributor Covenant Code of Conduct (#330)
Added Contributor Covenant Code of Conduct to promote a harassment-free community.
2026-03-07 14:48:09 -08:00
Dang Nguyen
9b69dd0d03 feat(CLI): Add Antigravity IDE support via --target antigravity flag (#332)
* feat(CLI): Add Antigravity IDE support via `--target antigravity` flag

This Pull Request introduces `--target antigravity` support within the installation script to bridge Everything Claude Code configurations smoothly onto the Antigravity IDE ecosystem.

### Key Changes
- Modified `install.sh` to parse and act on the new `--target antigravity` CLI arg.
- **Flattened Rules Conversion**: Logic automatically copies Language-agnostic (Common/Globs) rules as well as specific language stack rules into `common-*.md` and `{lang}-*.md` structures within `.agent/rules/`.
- **Workflow & Agent Aggregation**: Commands safely fall in `.agent/workflows/`, and `agents/` alongside `skills/` components are merged into `.agent/skills/`.
- Contains overwrite warnings to ensure local customized rules aren't completely overridden without consent.
- Minor updates to `README.md` to properly document the flag addition.

* Update install.sh

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: dangnd1 <dangnd1@vnpay.vn>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-03-07 14:48:07 -08:00
zdoc.app
abcf38b085 docs(zh-CN): sync Chinese docs with latest upstream changes (#341)
* docs(zh-CN): sync Chinese docs with latest upstream changes

* docs(zh-CN): update link

---------

Co-authored-by: neo <neo.dowithless@gmail.com>
2026-03-07 14:48:02 -08:00
Pangerkumzuk Longkumer
da17d33ac3 Fixed CI Workflows Failure fixed (in response to PR#286) (#291)
* Initial plan

* fix: remove malformed copilot-setup-steps.yml and fix hooks.json regex

Co-authored-by: pangerlkr <73515951+pangerlkr@users.noreply.github.com>

---------

Co-authored-by: anthropic-code-agent[bot] <242468646+Claude@users.noreply.github.com>
2026-03-07 14:47:53 -08:00
zzzhizhi
177dd36e23 fix(hooks): allow tmux-wrapped dev server commands (#321)
* fix(hooks): fix shell splitter redirection/escape bugs, extract shared module

- Fix single & incorrectly splitting redirection operators (&>, >&, 2>&1)
- Fix escaped quotes (\", \') not being handled inside quoted strings
- Extract splitShellSegments into shared scripts/lib/shell-split.js
  to eliminate duplication between hooks.json, before-shell-execution.js,
  and pre-bash-dev-server-block.js
- Add comprehensive tests for shell splitting edge cases

* fix(hooks): handle backslash escapes outside quotes in shell splitter

Escaped operators like \&& and \; outside quotes were still being
treated as separators. Add escape handling for unquoted context.
2026-03-07 14:47:49 -08:00
Helbetica
7bed751db0 fix: auto-start dev servers in tmux instead of blocking (#344)
* fix: auto-start development servers in tmux instead of blocking

Replace blocking PreToolUse hook that used process.exit(2) with an auto-transform hook that:
- Detects development server commands
- Wraps them in tmux with directory-based session names
- Runs server detached so Claude Code is not blocked
- Provides confirmation message with log viewing instructions

Benefits:
- Development servers no longer block Claude Code execution
- Each project gets its own tmux session (allows multiple projects)
- Logs remain accessible via 'tmux capture-pane -t <session>'
- Non-blocking: if tmux unavailable, command still runs (graceful fallback)

Implementation:
- Created scripts/hooks/auto-tmux-dev.js with transform logic
- Updated hooks.json to reference the script instead of inline node command
- Applied same fix to cached plugin version (1.4.1) for immediate effect

* fix: resolve PR #344 code review issues in auto-tmux-dev.js

Critical fixes:
- Fix variable scope: declare 'input' before try block, not inside
- Fix shell injection: sanitize sessionName and escape cmd for shell
- Replace unused execFileSync import with spawnSync

Improvements:
- Add real Windows support using cmd /k window launcher
- Add tmux availability check with graceful fallback
- Update header comment to accurately describe platform support

Test coverage:
- Valid JSON input: transforms command for respective platform
- Invalid JSON: passes through raw data unchanged
- Unsupported tools: gracefully falls back to original command
- Shell metacharacters: sanitized in sessionName, escaped in cmd

* fix: correct cmd.exe escape sequence for double quotes on Windows

Use double-quote doubling ('""') instead of backslash-escape ('\\\") for cmd.exe syntax.
Backslash escaping is Unix convention and not recognized by cmd.exe. This fixes quoted
arguments in dev server commands on Windows (e.g., 'npm run dev --filter="my-app"').
2026-03-07 14:47:46 -08:00
Frank
e9577e34f1 fix: force UTF-8 for instinct CLI file IO (#353) 2026-03-07 14:47:35 -08:00
jtzingsheim1
9661a6f042 fix(hooks): scrub secrets and harden hook security (#348)
* fix(hooks): scrub secrets and harden hook security

- Scrub common secret patterns (api_key, token, password, etc.) from
  observation logs before persisting to JSONL (observe.sh)
- Auto-purge observation files older than 30 days (observe.sh)
- Strip embedded credentials from git remote URLs before saving to
  projects.json (detect-project.sh)
- Add command prefix allowlist to runCommand — only git, node, npx,
  which, where are permitted (utils.js)
- Sanitize CLAUDE_SESSION_ID in temp file paths to prevent path
  traversal (suggest-compact.js)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(hooks): address review feedback from CodeRabbit and Cubic

- Reject shell command-chaining operators (;|&`) in runCommand, strip
  quoted sections before checking to avoid false positives (utils.js)
- Remove command string from blocked error message to avoid leaking
  secrets (utils.js)
- Fix Python regex quoting: switch outer shell string from double to
  single quotes so regex compiles correctly (observe.sh)
- Add optional auth scheme match (Bearer, Basic) to secret scrubber
  regex (observe.sh)
- Scope auto-purge to current project dir and match only archived
  files (observations-*.jsonl), not live queue (observe.sh)
- Add second fallback after session ID sanitization to prevent empty
  string (suggest-compact.js)
- Preserve backward compatibility when credential stripping changes
  project hash — detect and migrate legacy directories
  (detect-project.sh)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(hooks): block $() substitution, fix Bearer redaction, add security tests

- Add $ and \n to blocked shell metacharacters in runCommand to prevent
  command substitution via $(cmd) and newline injection (utils.js)
- Make auth scheme group capturing so Bearer/Basic is preserved in
  redacted output instead of being silently dropped (observe.sh)
- Add 10 unit tests covering runCommand allowlist blocking (rm, curl,
  bash prefixes) and metacharacter rejection (;|&`$ chaining), plus
  error message leak prevention (utils.test.js)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(hooks): scrub parse-error fallback, strengthen security tests

Address remaining reviewer feedback from CodeRabbit and Cubic:

- Scrub secrets in observe.sh parse-error fallback path (was writing
  raw unsanitized input to observations file)
- Remove redundant re.IGNORECASE flag ((?i) inline flag already set)
- Add inline comment documenting quote-stripping limitation trade-off
- Fix misleading test name for error-output test
- Add 5 new security tests: single-quote passthrough, mixed
  quoted+unquoted metacharacters, prefix boundary (no trailing space),
  npx acceptance, and newline injection
- Improve existing quoted-metacharacter test to actually exercise
  quote-stripping logic

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(security): block $() and backtick inside quotes in runCommand

Shell evaluates $() and backticks inside double quotes, so checking
only the unquoted portion was insufficient. Now $ and ` are rejected
anywhere in the command string, while ; | & remain quote-aware.

Addresses CodeRabbit and Cubic review feedback on PR #348.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 14:47:31 -08:00
Sense_wang
03b3e0d0da docs: add upstream tracking flag to push example (#327)
Co-authored-by: Hao Wang <haosen.wang@example.com>
2026-03-05 15:36:36 -08:00
Affaan Mustafa
1797e79129 Merge pull request #334 from affaan-m/codex/release-1.8.0-core
feat: v1.8.0 harness release (core reliability + parity + new commands)
2026-03-05 12:48:57 -08:00
Affaan Mustafa
1f8b3eaba7 fix: normalize hook command execution in integration tests 2026-03-05 12:43:53 -08:00
Affaan Mustafa
d1f44e89e2 fix: stabilize windows hook and claw tests 2026-03-05 12:37:24 -08:00
Affaan Mustafa
5fe40f4a63 docs: add sponsorship playbook and monthly metrics automation 2026-03-04 16:17:12 -08:00
Affaan Mustafa
c4a5a69dbd docs: strengthen sponsor optics with live metrics and tiers 2026-03-04 15:29:37 -08:00
Dang Nguyen
5e1472263d Update install.sh
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-03-04 14:51:06 -08:00
dangnd1
61485f91ad feat(CLI): Add Antigravity IDE support via --target antigravity flag
This Pull Request introduces `--target antigravity` support within the installation script to bridge Everything Claude Code configurations smoothly onto the Antigravity IDE ecosystem.

- Modified `install.sh` to parse and act on the new `--target antigravity` CLI arg.
- **Flattened Rules Conversion**: Logic automatically copies Language-agnostic (Common/Globs) rules as well as specific language stack rules into `common-*.md` and `{lang}-*.md` structures within `.agent/rules/`.
- **Workflow & Agent Aggregation**: Commands safely fall in `.agent/workflows/`, and `agents/` alongside `skills/` components are merged into `.agent/skills/`.
- Contains overwrite warnings to ensure local customized rules aren't completely overridden without consent.
- Minor updates to `README.md` to properly document the flag addition.
2026-03-04 14:51:06 -08:00
Hao Wang
57eb9361db docs: add upstream tracking flag to push example 2026-03-04 14:49:53 -08:00
Pangerkumzuk Longkumer
98643ef6e6 Add Contributor Covenant Code of Conduct
Added Contributor Covenant Code of Conduct to promote a harassment-free community.
2026-03-04 14:49:53 -08:00
to.watanabe
f94707d429 fix(commands): make ace-tool MCP optional in multi-* commands with built-in fallbacks
The multi-* commands (multi-plan, multi-execute, multi-workflow, multi-backend,
multi-frontend) previously required ace-tool MCP (Augment Code) which is a paid
service. This change makes ace-tool completely optional by:

- Changing "MUST call" to "If ace-tool MCP is available" for enhance_prompt
- Changing mandatory search_context calls to optional with fallback procedures
- Adding detailed fallback instructions using Claude Code built-in tools
  (Glob, Grep, Read, Task/Explore agent) when ace-tool is unavailable
- Updating all translations (ja-JP, zh-CN) to match

This ensures multi-* commands work out of the box without ace-tool MCP configured.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 14:49:53 -08:00
Affaan Mustafa
48b883d741 feat: deliver v1.8.0 harness reliability and parity updates 2026-03-04 14:48:06 -08:00
Affaan Mustafa
32e9c293f0 chore: replace external repo links with @username attribution 2026-03-03 12:32:35 -08:00
Affaan Mustafa
cd129edef0 feat(skills): add autonomous-loops and plankton-code-quality skills
- autonomous-loops: 6 loop patterns from simple claude -p pipelines to
  RFC-driven DAG orchestration (Ralphinho, infinite-agentic-loop,
  continuous-claude, de-sloppify pattern)
- plankton-code-quality: write-time enforcement integration guide
- README: updated directory listing and Plankton description

Sources: enitrat/ralphinho, disler/infinite-agentic-loop,
AnandChowdhary/continuous-claude, alexfazio/plankton
2026-03-03 12:16:57 -08:00
Affaan Mustafa
9dc76fd27b Merge pull request #323 from pythonstrup/chore/add-prettierrc
chore: add .prettierrc and fix pre-existing lint errors
2026-03-03 07:56:15 -08:00
Jonghyeok Park
3260c7449e fix(lint): remove unnecessary escape characters in regex patterns
- doc-file-warning.js: \/ → / inside character classes (4 occurrences)
- project-detect.js: \[ → [ inside character classes (2 occurrences)

These are pre-existing no-useless-escape errors on upstream main.
2026-03-03 22:11:51 +09:00
Jonghyeok Park
66143eaf74 chore: add .prettierrc for consistent code formatting
The post-edit-format hook runs Prettier on JS/TS files after edits,
but without a project-level config it applied default settings (double
quotes, etc.) that conflicted with the existing code style. Adding
.prettierrc ensures the hook respects the project conventions.

Settings derived from existing codebase analysis:
- singleQuote: true
- trailingComma: none
- arrowParens: avoid
- printWidth: 200
2026-03-03 22:06:09 +09:00
zdoc.app
ada4cd75a3 docs(zh-CN): sync Chinese docs with latest upstream changes (#304)
* docs(zh-CN): sync Chinese docs with latest upstream changes

* update

---------

Co-authored-by: neo <neo.dowithless@gmail.com>
2026-03-02 22:28:27 -08:00
zzzhizhi
adc0f67008 fix(continuous-learning-v2): observer background process crashes immediately (#312)
* fix(continuous-learning-v2): observer background process crashes immediately

Three bugs prevent the observer from running:

1. Nested session detection: When launched from a Claude Code session,
   the child process inherits CLAUDECODE env var, causing `claude` CLI
   to refuse with "cannot be launched inside another session". Fix: unset
   CLAUDECODE in the background process.

2. set -e kills the loop: The parent script's `set -e` is inherited by
   the subshell. When `claude` exits non-zero (e.g. max turns reached),
   the entire observer loop dies. Fix: `set +e` in the background process.

3. Subshell dies when parent exits: `( ... ) & disown` loses IO handles
   when the parent shell exits, killing the background process. Fix: use
   `nohup /bin/bash -c '...'` for full detachment, and `sleep & wait`
   to allow SIGUSR1 to interrupt sleep without killing the process.

Additionally, the prompt for Haiku now includes the exact instinct file
format inline (YAML frontmatter with id/trigger/confidence/domain/source
fields), since the previous prompt referenced "the observer agent spec"
which Haiku could not actually read, resulting in instinct files that
the CLI parser could not parse.

* fix: address review feedback on observer process management

- Use `env` to pass variables to child process instead of quote-splicing,
  avoiding shell injection risk from special chars in paths
- Add USR1_FIRED flag to prevent double analysis when SIGUSR1 interrupts
  the sleep/wait cycle
- Track SLEEP_PID and kill it in both TERM trap and USR1 handler to
  prevent orphaned sleep processes from accumulating
- Consolidate cleanup logic into a dedicated cleanup() function

* fix: guard PID file cleanup against race condition on restart

Only remove PID file in cleanup trap if it still belongs to the
current process, preventing a restarted observer from losing its
PID file when the old process exits.
2026-03-02 22:23:01 -08:00
Affaan Mustafa
3bfd29bb46 fix(hooks): exclude .history/ directory from doc file warning
Incorporates the fix from #316 into the standalone script.
2026-03-02 22:16:58 -08:00
Affaan Mustafa
1df0a53f22 fix: resolve CI failures on main — lint, hooks validator, and test alignment
- Fix MD012 trailing blank lines in commands/projects.md and commands/promote.md
- Fix MD050 strong-style in continuous-learning-v2 (escape __tests__ as inline code)
- Extract doc-file-warning hook to standalone script to fix hooks validator regex parsing
- Update session-end test to match #317 behavior (always update summary content)
- Allow shell script hooks in integration test format validation

All 992 tests passing.
2026-03-02 22:15:46 -08:00
justtrance-web
912df24f4a feat: automatic project type and framework detection (#293)
Add SessionStart hook integration that auto-detects project languages
and frameworks by inspecting marker files and dependency manifests.

Supports 12 languages (Python, TypeScript, Go, Rust, Ruby, Java, C#,
Swift, Kotlin, Elixir, PHP, JavaScript) and 25+ frameworks (Next.js,
React, Django, FastAPI, Rails, Laravel, Spring, etc.).

Detection output is injected into Claude's context as JSON, enabling
context-aware recommendations without loading irrelevant rules.

- New: scripts/lib/project-detect.js (cross-platform detection library)
- Modified: scripts/hooks/session-start.js (integration)
- New: tests/lib/project-detect.test.js (28 tests, all passing)

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-02 22:07:10 -08:00
will
e000bbe5e4 fix(session-end): always update session summary content (#317)
* fix(session-end): always update session summary content

Previously, session-end.js would only write content to session files
on first creation. Subsequent sessions would only update the timestamp,
causing stale content (e.g., old tasks, resolved issues) to persist
indefinitely.

This fix ensures that every session end updates the summary section
with fresh content from the current transcript, keeping cross-session
context accurate and relevant.

Fixes: #187 (partially - addresses stale content issue)

Changes:
- Remove the blank-template-only check
- Replace entire Session Summary section on every session end
- Keep timestamp update separate from content update

* fix(session-end): match both summary headers and prevent duplicate stats

Fixes two issues identified in PR #317 code review:

1. CodeRabbit: Updated regex to match both `## Session Summary` and
   `## Current State` headers, ensuring files created from blank template
   can be updated with fresh summaries.

2. Cubic: Changed regex lookahead `(?=### Stats|$)` to end-of-string `$`
   to prevent duplicate `### Stats` sections. The old pattern stopped before
   `### Stats` without consuming it, but buildSummarySection() also emits
   a `### Stats` block, causing duplication on each session update.

Changes:
- Regex now: `/## (?:Session Summary|Current State)[\s\S]*?$/`
- Matches both header variants used in blank template and populated sessions
- Matches to end-of-string to cleanly replace entire summary section

---------

Co-authored-by: will <will@192.168.5.31>
2026-03-02 22:00:33 -08:00
Pangerkumzuk Longkumer
bc64712b5d Delete .github/workflows/copilot-setup-steps.yml (#319) 2026-03-02 21:58:20 -08:00
Harry Kwok
5818e8adc7 feat: project-scoped instinct isolation
* feat: add project-scoped instinct isolation

* fix(continuous-learning-v2): harden instinct loading and promotion safety; sync v2.1 command docs

* fix(ci): make copilot-setup-steps a valid GitHub Actions workflow

* fix(hooks): stabilize docs warning inline JS regex parsing
2026-03-01 12:07:13 -08:00
Affaan Mustafa
2d3be88bb5 docs: update positioning to performance optimization system, add Plankton reference 2026-02-28 10:09:51 -08:00
Affaan Mustafa
87a2ed51dc feat: add exa-web-search to MCP config template 2026-02-28 10:09:51 -08:00
Affaan Mustafa
b68558d749 feat: expand research-first mandate in development workflow 2026-02-28 10:09:51 -08:00
Affaan Mustafa
1fa22efd90 chore: clean up FUNDING.yml format 2026-02-28 10:09:51 -08:00
Codex
dc8455dd10 feat: separate core vs niche skills and enforce research-first default
* Initial plan

* docs: document core skill scope

---------

Co-authored-by: openai-code-agent[bot] <242516109+Codex@users.noreply.github.com>
2026-02-28 10:06:43 -08:00
303 changed files with 22290 additions and 6682 deletions

View File

@@ -14,7 +14,7 @@
"name": "everything-claude-code",
"source": "./",
"description": "The most comprehensive Claude Code plugin — 14+ agents, 56+ skills, 33+ commands, and production-ready hooks for TDD, security scanning, code review, and continuous learning",
"version": "1.7.0",
"version": "1.8.0",
"author": {
"name": "Affaan Mustafa",
"email": "me@affaanmustafa.com"

View File

@@ -1,6 +1,6 @@
{
"name": "everything-claude-code",
"version": "1.7.0",
"version": "1.8.0",
"description": "Complete collection of battle-tested Claude Code configs from an Anthropic hackathon winner - agents, skills, hooks, and rules evolved over 10+ months of intensive daily use",
"author": {
"name": "Affaan Mustafa",

View File

@@ -29,13 +29,14 @@ function transformToClaude(cursorInput, overrides = {}) {
return {
tool_input: {
command: cursorInput.command || cursorInput.args?.command || '',
file_path: cursorInput.path || cursorInput.file || '',
file_path: cursorInput.path || cursorInput.file || cursorInput.args?.filePath || '',
...overrides.tool_input,
},
tool_output: {
output: cursorInput.output || cursorInput.result || '',
...overrides.tool_output,
},
transcript_path: cursorInput.transcript_path || cursorInput.transcriptPath || cursorInput.session?.transcript_path || '',
_cursor: {
conversation_id: cursorInput.conversation_id,
hook_event_name: cursorInput.hook_event_name,
@@ -59,4 +60,22 @@ function runExistingHook(scriptName, stdinData) {
}
}
module.exports = { readStdin, getPluginRoot, transformToClaude, runExistingHook };
function hookEnabled(hookId, allowedProfiles = ['standard', 'strict']) {
const rawProfile = String(process.env.ECC_HOOK_PROFILE || 'standard').toLowerCase();
const profile = ['minimal', 'standard', 'strict'].includes(rawProfile) ? rawProfile : 'standard';
const disabled = new Set(
String(process.env.ECC_DISABLED_HOOKS || '')
.split(',')
.map(v => v.trim().toLowerCase())
.filter(Boolean)
);
if (disabled.has(String(hookId || '').toLowerCase())) {
return false;
}
return allowedProfiles.includes(profile);
}
module.exports = { readStdin, getPluginRoot, transformToClaude, runExistingHook, hookEnabled };

View File

@@ -1,13 +1,13 @@
#!/usr/bin/env node
const { readStdin } = require('./adapter');
const { readStdin, hookEnabled } = require('./adapter');
readStdin().then(raw => {
try {
const input = JSON.parse(raw);
const cmd = input.command || '';
const output = input.output || input.result || '';
const input = JSON.parse(raw || '{}');
const cmd = String(input.command || input.args?.command || '');
const output = String(input.output || input.result || '');
// PR creation logging
if (/gh pr create/.test(cmd)) {
if (hookEnabled('post:bash:pr-created', ['standard', 'strict']) && /\bgh\s+pr\s+create\b/.test(cmd)) {
const m = output.match(/https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+/);
if (m) {
console.error('[ECC] PR created: ' + m[0]);
@@ -17,10 +17,12 @@ readStdin().then(raw => {
}
}
// Build completion notice
if (/(npm run build|pnpm build|yarn build)/.test(cmd)) {
if (hookEnabled('post:bash:build-complete', ['standard', 'strict']) && /(npm run build|pnpm build|yarn build)/.test(cmd)) {
console.error('[ECC] Build completed');
}
} catch {}
} catch {
// noop
}
process.stdout.write(raw);
}).catch(() => process.exit(0));

View File

@@ -1,27 +1,41 @@
#!/usr/bin/env node
const { readStdin } = require('./adapter');
readStdin().then(raw => {
try {
const input = JSON.parse(raw);
const cmd = input.command || '';
const { readStdin, hookEnabled } = require('./adapter');
const { splitShellSegments } = require('../../scripts/lib/shell-split');
// 1. Block dev server outside tmux
if (process.platform !== 'win32' && /(npm run dev\b|pnpm( run)? dev\b|yarn dev\b|bun run dev\b)/.test(cmd)) {
console.error('[ECC] BLOCKED: Dev server must run in tmux for log access');
console.error('[ECC] Use: tmux new-session -d -s dev "npm run dev"');
process.exit(2);
readStdin()
.then(raw => {
try {
const input = JSON.parse(raw || '{}');
const cmd = String(input.command || input.args?.command || '');
if (hookEnabled('pre:bash:dev-server-block', ['standard', 'strict']) && process.platform !== 'win32') {
const segments = splitShellSegments(cmd);
const tmuxLauncher = /^\s*tmux\s+(new|new-session|new-window|split-window)\b/;
const devPattern = /\b(npm\s+run\s+dev|pnpm(?:\s+run)?\s+dev|yarn\s+dev|bun\s+run\s+dev)\b/;
const hasBlockedDev = segments.some(segment => devPattern.test(segment) && !tmuxLauncher.test(segment));
if (hasBlockedDev) {
console.error('[ECC] BLOCKED: Dev server must run in tmux for log access');
console.error('[ECC] Use: tmux new-session -d -s dev "npm run dev"');
process.exit(2);
}
}
if (
hookEnabled('pre:bash:tmux-reminder', ['strict']) &&
process.platform !== 'win32' &&
!process.env.TMUX &&
/(npm (install|test)|pnpm (install|test)|yarn (install|test)?|bun (install|test)|cargo build|make\b|docker\b|pytest|vitest|playwright)/.test(cmd)
) {
console.error('[ECC] Consider running in tmux for session persistence');
}
if (hookEnabled('pre:bash:git-push-reminder', ['strict']) && /\bgit\s+push\b/.test(cmd)) {
console.error('[ECC] Review changes before push: git diff origin/main...HEAD');
}
} catch {
// noop
}
// 2. Tmux reminder for long-running commands
if (process.platform !== 'win32' && !process.env.TMUX &&
/(npm (install|test)|pnpm (install|test)|yarn (install|test)?|bun (install|test)|cargo build|make\b|docker\b|pytest|vitest|playwright)/.test(cmd)) {
console.error('[ECC] Consider running in tmux for session persistence');
}
// 3. Git push review reminder
if (/git push/.test(cmd)) {
console.error('[ECC] Review changes before push: git diff origin/main...HEAD');
}
} catch {}
process.stdout.write(raw);
}).catch(() => process.exit(0));
process.stdout.write(raw);
})
.catch(() => process.exit(0));

View File

@@ -1,9 +1,10 @@
#!/usr/bin/env node
const { readStdin, runExistingHook, transformToClaude } = require('./adapter');
const { readStdin, runExistingHook, transformToClaude, hookEnabled } = require('./adapter');
readStdin().then(raw => {
const input = JSON.parse(raw);
const input = JSON.parse(raw || '{}');
const claudeInput = transformToClaude(input);
runExistingHook('session-end.js', claudeInput);
runExistingHook('evaluate-session.js', claudeInput);
if (hookEnabled('session:end:marker', ['minimal', 'standard', 'strict'])) {
runExistingHook('session-end-marker.js', claudeInput);
}
process.stdout.write(raw);
}).catch(() => process.exit(0));

View File

@@ -1,8 +1,10 @@
#!/usr/bin/env node
const { readStdin, runExistingHook, transformToClaude } = require('./adapter');
const { readStdin, runExistingHook, transformToClaude, hookEnabled } = require('./adapter');
readStdin().then(raw => {
const input = JSON.parse(raw);
const input = JSON.parse(raw || '{}');
const claudeInput = transformToClaude(input);
runExistingHook('session-start.js', claudeInput);
if (hookEnabled('session:start', ['minimal', 'standard', 'strict'])) {
runExistingHook('session-start.js', claudeInput);
}
process.stdout.write(raw);
}).catch(() => process.exit(0));

View File

@@ -1,7 +1,21 @@
#!/usr/bin/env node
const { readStdin, runExistingHook, transformToClaude } = require('./adapter');
const { readStdin, runExistingHook, transformToClaude, hookEnabled } = require('./adapter');
readStdin().then(raw => {
const claudeInput = JSON.parse(raw || '{}');
runExistingHook('check-console-log.js', transformToClaude(claudeInput));
const input = JSON.parse(raw || '{}');
const claudeInput = transformToClaude(input);
if (hookEnabled('stop:check-console-log', ['standard', 'strict'])) {
runExistingHook('check-console-log.js', claudeInput);
}
if (hookEnabled('stop:session-end', ['minimal', 'standard', 'strict'])) {
runExistingHook('session-end.js', claudeInput);
}
if (hookEnabled('stop:evaluate-session', ['minimal', 'standard', 'strict'])) {
runExistingHook('evaluate-session.js', claudeInput);
}
if (hookEnabled('stop:cost-tracker', ['minimal', 'standard', 'strict'])) {
runExistingHook('cost-tracker.js', claudeInput);
}
process.stdout.write(raw);
}).catch(() => process.exit(0));

15
.github/FUNDING.yml vendored
View File

@@ -1,15 +1,2 @@
# These are supported funding model platforms
github: [affaan-m]
# patreon: # Replace with a single Patreon username
# open_collective: # Replace with a single Open Collective username
# ko_fi: # Replace with a single Ko-fi username
# tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
# community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-hierarchical-namespace-controller
# liberapay: # Replace with a single Liberapay username
# issuehunt: # Replace with a single IssueHunt username
# lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-hierarchical-namespace-controller
# polar: # Replace with a single Polar username
# buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
# thanks_dev: # Replace with a single thanks.dev username
github: affaan-m
custom: ['https://ecc.tools']

20
.github/release.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
changelog:
categories:
- title: Core Harness
labels:
- enhancement
- feature
- title: Reliability & Bug Fixes
labels:
- bug
- fix
- title: Docs & Guides
labels:
- docs
- title: Tooling & CI
labels:
- ci
- chore
exclude:
labels:
- skip-changelog

View File

@@ -1,18 +0,0 @@
steps:
- name: Setup Go environment
uses: actions/setup-go@v6.2.0
with:
# The Go version to download (if necessary) and use. Supports semver spec and ranges. Be sure to enclose this option in single quotation marks.
go-version: # optional
# Path to the go.mod, go.work, .go-version, or .tool-versions file.
go-version-file: # optional
# Set this option to true if you want the action to always check for the latest available version that satisfies the version spec
check-latest: # optional
# Used to pull Go distributions from go-versions. Since there's a default, this is typically not supplied by the user. When running this action on github.com, the default value is sufficient. When running on GHES, you can pass a personal access token for github.com if you are experiencing rate limiting.
token: # optional, default is ${{ github.server_url == 'https://github.com' && github.token || '' }}
# Used to specify whether caching is needed. Set to true, if you'd like to enable caching.
cache: # optional, default is true
# Used to specify the path to a dependency file - go.sum
cache-dependency-path: # optional
# Target architecture for Go to use. Examples: x86, x64. Will use system architecture by default.
architecture: # optional

185
.github/workflows/monthly-metrics.yml vendored Normal file
View File

@@ -0,0 +1,185 @@
name: Monthly Metrics Snapshot
on:
schedule:
- cron: '0 14 1 * *' # Monthly on the 1st at 14:00 UTC
workflow_dispatch:
permissions:
contents: read
issues: write
jobs:
snapshot:
name: Update metrics issue
runs-on: ubuntu-latest
steps:
- name: Update monthly metrics issue
uses: actions/github-script@v7
with:
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
const title = "Monthly Metrics Snapshot";
const label = "metrics-snapshot";
const monthKey = new Date().toISOString().slice(0, 7);
function parseLastPage(linkHeader) {
if (!linkHeader) return null;
const match = linkHeader.match(/&page=(\d+)>; rel="last"/);
return match ? Number(match[1]) : null;
}
function fmt(value) {
if (value === null || value === undefined) return "n/a";
return Number(value).toLocaleString("en-US");
}
async function getNpmDownloads(range, pkg) {
try {
const res = await fetch(`https://api.npmjs.org/downloads/point/${range}/${pkg}`);
if (!res.ok) return null;
const data = await res.json();
return data.downloads ?? null;
} catch {
return null;
}
}
async function getContributorsCount() {
try {
const resp = await github.rest.repos.listContributors({
owner,
repo,
per_page: 1,
anon: "false"
});
return parseLastPage(resp.headers.link) ?? resp.data.length;
} catch {
return null;
}
}
async function getReleasesCount() {
try {
const resp = await github.rest.repos.listReleases({
owner,
repo,
per_page: 1
});
return parseLastPage(resp.headers.link) ?? resp.data.length;
} catch {
return null;
}
}
async function getTraffic(metric) {
try {
const route = metric === "clones"
? "GET /repos/{owner}/{repo}/traffic/clones"
: "GET /repos/{owner}/{repo}/traffic/views";
const resp = await github.request(route, { owner, repo });
return resp.data?.count ?? null;
} catch {
return null;
}
}
const [
mainWeek,
shieldWeek,
mainMonth,
shieldMonth,
repoData,
contributors,
releases,
views14d,
clones14d
] = await Promise.all([
getNpmDownloads("last-week", "ecc-universal"),
getNpmDownloads("last-week", "ecc-agentshield"),
getNpmDownloads("last-month", "ecc-universal"),
getNpmDownloads("last-month", "ecc-agentshield"),
github.rest.repos.get({ owner, repo }),
getContributorsCount(),
getReleasesCount(),
getTraffic("views"),
getTraffic("clones")
]);
const stars = repoData.data.stargazers_count;
const forks = repoData.data.forks_count;
const tableHeader = [
"| Month (UTC) | ecc-universal (week) | ecc-agentshield (week) | ecc-universal (30d) | ecc-agentshield (30d) | Stars | Forks | Contributors | GitHub App installs (manual) | Views (14d) | Clones (14d) | Releases |",
"|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|"
].join("\n");
const row = `| ${monthKey} | ${fmt(mainWeek)} | ${fmt(shieldWeek)} | ${fmt(mainMonth)} | ${fmt(shieldMonth)} | ${fmt(stars)} | ${fmt(forks)} | ${fmt(contributors)} | n/a | ${fmt(views14d)} | ${fmt(clones14d)} | ${fmt(releases)} |`;
const intro = [
"# Monthly Metrics Snapshot",
"",
"Automated monthly snapshot for sponsor/partner reporting.",
"",
"- `GitHub App installs (manual)` is intentionally manual until a stable public API path is available.",
"- Traffic metrics are 14-day rolling windows from the GitHub traffic API and can show `n/a` if unavailable.",
"",
tableHeader
].join("\n");
try {
await github.rest.issues.getLabel({ owner, repo, name: label });
} catch (error) {
if (error.status === 404) {
await github.rest.issues.createLabel({
owner,
repo,
name: label,
color: "0e8a16",
description: "Automated monthly project metrics snapshots"
});
} else {
throw error;
}
}
const issuesResp = await github.rest.issues.listForRepo({
owner,
repo,
state: "open",
labels: label,
per_page: 100
});
let issue = issuesResp.data.find((item) => item.title === title);
if (!issue) {
const created = await github.rest.issues.create({
owner,
repo,
title,
labels: [label],
body: `${intro}\n${row}\n`
});
console.log(`Created issue #${created.data.number}`);
return;
}
const currentBody = issue.body || "";
if (currentBody.includes(`| ${monthKey} |`)) {
console.log(`Issue #${issue.number} already has snapshot row for ${monthKey}`);
return;
}
const body = currentBody.includes("| Month (UTC) |")
? `${currentBody.trimEnd()}\n${row}\n`
: `${intro}\n${row}\n`;
await github.rest.issues.update({
owner,
repo,
issue_number: issue.number,
body
});
console.log(`Updated issue #${issue.number}`);

View File

@@ -37,23 +37,31 @@ jobs:
exit 1
fi
- name: Generate changelog
id: changelog
- name: Generate release highlights
id: highlights
env:
TAG_NAME: ${{ github.ref_name }}
run: |
PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
if [ -z "$PREV_TAG" ]; then
COMMITS=$(git log --pretty=format:"- %s" HEAD)
else
COMMITS=$(git log --pretty=format:"- %s" ${PREV_TAG}..HEAD)
fi
echo "commits<<EOF" >> $GITHUB_OUTPUT
echo "$COMMITS" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
TAG_VERSION="${TAG_NAME#v}"
cat > release_body.md <<EOF
## ECC ${TAG_VERSION}
### What This Release Focuses On
- Harness reliability and hook stability across Claude Code, Cursor, OpenCode, and Codex
- Stronger eval-driven workflows and quality gates
- Better operator UX for autonomous loop execution
### Notable Changes
- Session persistence and hook lifecycle fixes
- Expanded skills and command coverage for harness performance work
- Improved release-note generation and changelog hygiene
### Notes
- For migration tips and compatibility notes, see README and CHANGELOG.
EOF
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
body: |
## Changes
${{ steps.changelog.outputs.commits }}
generate_release_notes: false
body_path: release_body.md
generate_release_notes: true

View File

@@ -34,26 +34,23 @@ jobs:
exit 1
fi
- name: Generate changelog
id: changelog
- name: Generate release highlights
env:
TAG_NAME: ${{ inputs.tag }}
run: |
PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
if [ -z "$PREV_TAG" ]; then
COMMITS=$(git log --pretty=format:"- %s" HEAD)
else
COMMITS=$(git log --pretty=format:"- %s" ${PREV_TAG}..HEAD)
fi
# Use unique delimiter to prevent truncation if commit messages contain EOF
DELIMITER="COMMITS_END_$(date +%s)"
echo "commits<<${DELIMITER}" >> $GITHUB_OUTPUT
echo "$COMMITS" >> $GITHUB_OUTPUT
echo "${DELIMITER}" >> $GITHUB_OUTPUT
TAG_VERSION="${TAG_NAME#v}"
cat > release_body.md <<EOF
## ECC ${TAG_VERSION}
### What This Release Focuses On
- Harness reliability and cross-platform compatibility
- Eval-driven quality improvements
- Better workflow and operator ergonomics
EOF
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ inputs.tag }}
body: |
## Changes
${{ steps.changelog.outputs.commits }}
body_path: release_body.md
generate_release_notes: ${{ inputs.generate-notes }}

View File

@@ -258,6 +258,8 @@ After migration, ALL 23 commands are available:
| `/instinct-import` | Import instincts |
| `/instinct-export` | Export instincts |
| `/evolve` | Cluster instincts into skills |
| `/promote` | Promote project instincts to global scope |
| `/projects` | List known projects and instinct stats |
## Available Agents

View File

@@ -67,7 +67,7 @@ opencode
| go-build-resolver | Go build errors |
| database-reviewer | Database optimization |
### Commands (24)
### Commands (31)
| Command | Description |
|---------|-------------|
@@ -95,6 +95,13 @@ opencode
| `/instinct-import` | Import instincts |
| `/instinct-export` | Export instincts |
| `/evolve` | Cluster instincts |
| `/promote` | Promote project instincts |
| `/projects` | List known projects |
| `/harness-audit` | Audit harness reliability and eval readiness |
| `/loop-start` | Start controlled agentic loops |
| `/loop-status` | Check loop state and checkpoints |
| `/quality-gate` | Run quality gates on file/repo scope |
| `/model-route` | Route tasks by model and budget |
### Plugin Hooks
@@ -128,6 +135,18 @@ OpenCode's plugin system maps to Claude Code hooks:
OpenCode has 20+ additional events not available in Claude Code.
### Hook Runtime Controls
OpenCode plugin hooks honor the same runtime controls used by Claude Code/Cursor:
```bash
export ECC_HOOK_PROFILE=standard
export ECC_DISABLED_HOOKS="pre:bash:tmux-reminder,post:edit:typecheck"
```
- `ECC_HOOK_PROFILE`: `minimal`, `standard` (default), `strict`
- `ECC_DISABLED_HOOKS`: comma-separated hook IDs to disable
## Skills
The default OpenCode config loads 11 curated ECC skills via the `instructions` array:

View File

@@ -1,112 +1,36 @@
---
description: Cluster instincts into skills
description: Analyze instincts and suggest or generate evolved structures
agent: build
---
# Evolve Command
Cluster related instincts into structured skills: $ARGUMENTS
Analyze and evolve instincts in continuous-learning-v2: $ARGUMENTS
## Your Task
Analyze instincts and promote clusters to skills.
Run:
## Evolution Process
### Step 1: Analyze Instincts
Group instincts by:
- Trigger similarity
- Action patterns
- Category tags
- Confidence levels
### Step 2: Identify Clusters
```
Cluster: Error Handling
├── Instinct: Catch specific errors (0.85)
├── Instinct: Wrap errors with context (0.82)
├── Instinct: Log errors with stack trace (0.78)
└── Instinct: Return meaningful error messages (0.80)
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" evolve $ARGUMENTS
```
### Step 3: Generate Skill
If `CLAUDE_PLUGIN_ROOT` is unavailable, use:
When cluster has:
- 3+ instincts
- Average confidence > 0.75
- Cohesive theme
Generate SKILL.md:
```markdown
# Error Handling Skill
## Overview
Patterns for robust error handling learned from session observations.
## Patterns
### 1. Catch Specific Errors
**Trigger**: When catching errors with generic catch
**Action**: Use specific error types
### 2. Wrap Errors with Context
**Trigger**: When re-throwing errors
**Action**: Add context with fmt.Errorf or Error.cause
### 3. Log with Stack Trace
**Trigger**: When logging errors
**Action**: Include stack trace for debugging
### 4. Meaningful Messages
**Trigger**: When returning errors to users
**Action**: Provide actionable error messages
```bash
python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py evolve $ARGUMENTS
```
### Step 4: Archive Instincts
## Supported Args (v2.1)
Move evolved instincts to `archived/` with reference to skill.
- no args: analysis only
- `--generate`: also generate files under `evolved/{skills,commands,agents}`
## Evolution Report
## Behavior Notes
```
Evolution Summary
=================
Clusters Found: X
Cluster 1: Error Handling
- Instincts: 5
- Avg Confidence: 0.82
- Status: ✅ Promoted to skill
Cluster 2: Testing Patterns
- Instincts: 3
- Avg Confidence: 0.71
- Status: ⏳ Needs more confidence
Cluster 3: Git Workflow
- Instincts: 2
- Avg Confidence: 0.88
- Status: ⏳ Needs more instincts
Skills Created:
- skills/error-handling/SKILL.md
Instincts Archived: 5
Remaining Instincts: 12
```
## Thresholds
| Metric | Threshold |
|--------|-----------|
| Min instincts per cluster | 3 |
| Min average confidence | 0.75 |
| Min cluster cohesion | 0.6 |
---
**TIP**: Run `/evolve` periodically to graduate instincts to skills as confidence grows.
- Uses project + global instincts for analysis.
- Shows skill/command/agent candidates from trigger and domain clustering.
- Shows project -> global promotion candidates.
- With `--generate`, output path is:
- project context: `~/.claude/homunculus/projects/<project-id>/evolved/`
- global fallback: `~/.claude/homunculus/evolved/`

View File

@@ -0,0 +1,58 @@
# Harness Audit Command
Audit the current repository's agent harness setup and return a prioritized scorecard.
## Usage
`/harness-audit [scope] [--format text|json]`
- `scope` (optional): `repo` (default), `hooks`, `skills`, `commands`, `agents`
- `--format`: output style (`text` default, `json` for automation)
## What to Evaluate
Score each category from `0` to `10`:
1. Tool Coverage
2. Context Efficiency
3. Quality Gates
4. Memory Persistence
5. Eval Coverage
6. Security Guardrails
7. Cost Efficiency
## Output Contract
Return:
1. `overall_score` out of 70
2. Category scores and concrete findings
3. Top 3 actions with exact file paths
4. Suggested ECC skills to apply next
## Checklist
- Inspect `hooks/hooks.json`, `scripts/hooks/`, and hook tests.
- Inspect `skills/`, command coverage, and agent coverage.
- Verify cross-harness parity for `.cursor/`, `.opencode/`, `.codex/`.
- Flag broken or stale references.
## Example Result
```text
Harness Audit (repo): 52/70
- Quality Gates: 9/10
- Eval Coverage: 6/10
- Cost Efficiency: 4/10
Top 3 Actions:
1) Add cost tracking hook in scripts/hooks/cost-tracker.js
2) Add pass@k docs and templates in skills/eval-harness/SKILL.md
3) Add command parity for /harness-audit in .opencode/commands/
```
## Arguments
$ARGUMENTS:
- `repo|hooks|skills|commands|agents` (optional scope)
- `--format text|json` (optional output format)

View File

@@ -1,75 +1,29 @@
---
description: View learned instincts with confidence scores
description: Show learned instincts (project + global) with confidence
agent: build
---
# Instinct Status Command
Display learned instincts and their confidence scores: $ARGUMENTS
Show instinct status from continuous-learning-v2: $ARGUMENTS
## Your Task
Read and display instincts from the continuous-learning-v2 system.
Run:
## Instinct Location
Global: `~/.claude/instincts/`
Project: `.claude/instincts/`
## Status Display
### Instinct Summary
| Category | Count | Avg Confidence |
|----------|-------|----------------|
| Coding | X | 0.XX |
| Testing | X | 0.XX |
| Security | X | 0.XX |
| Git | X | 0.XX |
### High Confidence Instincts (>0.8)
```
[trigger] → [action] (confidence: 0.XX)
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" status
```
### Learning Progress
If `CLAUDE_PLUGIN_ROOT` is unavailable, use:
- Total instincts: X
- This session: X
- Promoted to skills: X
### Recent Instincts
Last 5 instincts learned:
1. **[timestamp]** - [trigger] → [action]
2. **[timestamp]** - [trigger] → [action]
...
## Instinct Structure
```json
{
"id": "instinct-123",
"trigger": "When I see a try-catch without specific error type",
"action": "Suggest using specific error types for better handling",
"confidence": 0.75,
"applications": 5,
"successes": 4,
"source": "session-observation",
"timestamp": "2025-01-15T10:30:00Z"
}
```bash
python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py status
```
## Confidence Calculation
## Behavior Notes
```
confidence = (successes + 1) / (applications + 2)
```
Bayesian smoothing ensures new instincts don't have extreme confidence.
---
**TIP**: Use `/evolve` to cluster related instincts into skills when confidence is high.
- Output includes both project-scoped and global instincts.
- Project instincts override global instincts when IDs conflict.
- Output is grouped by domain with confidence bars.
- This command does not support extra filters in v2.1.

View File

@@ -0,0 +1,32 @@
# Loop Start Command
Start a managed autonomous loop pattern with safety defaults.
## Usage
`/loop-start [pattern] [--mode safe|fast]`
- `pattern`: `sequential`, `continuous-pr`, `rfc-dag`, `infinite`
- `--mode`:
- `safe` (default): strict quality gates and checkpoints
- `fast`: reduced gates for speed
## Flow
1. Confirm repository state and branch strategy.
2. Select loop pattern and model tier strategy.
3. Enable required hooks/profile for the chosen mode.
4. Create loop plan and write runbook under `.claude/plans/`.
5. Print commands to start and monitor the loop.
## Required Safety Checks
- Verify tests pass before first loop iteration.
- Ensure `ECC_HOOK_PROFILE` is not disabled globally.
- Ensure loop has explicit stop condition.
## Arguments
$ARGUMENTS:
- `<pattern>` optional (`sequential|continuous-pr|rfc-dag|infinite`)
- `--mode safe|fast` optional

View File

@@ -0,0 +1,24 @@
# Loop Status Command
Inspect active loop state, progress, and failure signals.
## Usage
`/loop-status [--watch]`
## What to Report
- active loop pattern
- current phase and last successful checkpoint
- failing checks (if any)
- estimated time/cost drift
- recommended intervention (continue/pause/stop)
## Watch Mode
When `--watch` is present, refresh status periodically and surface state changes.
## Arguments
$ARGUMENTS:
- `--watch` optional

View File

@@ -0,0 +1,26 @@
# Model Route Command
Recommend the best model tier for the current task by complexity and budget.
## Usage
`/model-route [task-description] [--budget low|med|high]`
## Routing Heuristic
- `haiku`: deterministic, low-risk mechanical changes
- `sonnet`: default for implementation and refactors
- `opus`: architecture, deep review, ambiguous requirements
## Required Output
- recommended model
- confidence level
- why this model fits
- fallback model if first attempt fails
## Arguments
$ARGUMENTS:
- `[task-description]` optional free-text
- `--budget low|med|high` optional

View File

@@ -0,0 +1,23 @@
---
description: List registered projects and instinct counts
agent: build
---
# Projects Command
Show continuous-learning-v2 project registry and stats: $ARGUMENTS
## Your Task
Run:
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" projects
```
If `CLAUDE_PLUGIN_ROOT` is unavailable, use:
```bash
python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py projects
```

View File

@@ -0,0 +1,23 @@
---
description: Promote project instincts to global scope
agent: build
---
# Promote Command
Promote instincts in continuous-learning-v2: $ARGUMENTS
## Your Task
Run:
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" promote $ARGUMENTS
```
If `CLAUDE_PLUGIN_ROOT` is unavailable, use:
```bash
python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py promote $ARGUMENTS
```

View File

@@ -0,0 +1,29 @@
# Quality Gate Command
Run the ECC quality pipeline on demand for a file or project scope.
## Usage
`/quality-gate [path|.] [--fix] [--strict]`
- default target: current directory (`.`)
- `--fix`: allow auto-format/fix where configured
- `--strict`: fail on warnings where supported
## Pipeline
1. Detect language/tooling for target.
2. Run formatter checks.
3. Run lint/type checks when available.
4. Produce a concise remediation list.
## Notes
This command mirrors hook behavior but is operator-invoked.
## Arguments
$ARGUMENTS:
- `[path|.]` optional target path
- `--fix` optional
- `--strict` optional

View File

@@ -303,6 +303,14 @@
"evolve": {
"description": "Cluster instincts into skills",
"template": "{file:.opencode/commands/evolve.md}\n\n$ARGUMENTS"
},
"promote": {
"description": "Promote project instincts to global scope",
"template": "{file:.opencode/commands/promote.md}\n\n$ARGUMENTS"
},
"projects": {
"description": "List known projects and instinct stats",
"template": "{file:.opencode/commands/projects.md}\n\n$ARGUMENTS"
}
},
"permission": {

View File

@@ -1,6 +1,6 @@
{
"name": "ecc-universal",
"version": "1.7.0",
"version": "1.8.0",
"description": "Everything Claude Code (ECC) plugin for OpenCode - agents, commands, hooks, and skills",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View File

@@ -21,6 +21,8 @@ export const ECCHooksPlugin = async ({
directory,
worktree,
}: PluginInput) => {
type HookProfile = "minimal" | "standard" | "strict"
// Track files edited in current session for console.log audit
const editedFiles = new Set<string>()
@@ -28,6 +30,40 @@ export const ECCHooksPlugin = async ({
const log = (level: "debug" | "info" | "warn" | "error", message: string) =>
client.app.log({ body: { service: "ecc", level, message } })
const normalizeProfile = (value: string | undefined): HookProfile => {
if (value === "minimal" || value === "strict") return value
return "standard"
}
const currentProfile = normalizeProfile(process.env.ECC_HOOK_PROFILE)
const disabledHooks = new Set(
(process.env.ECC_DISABLED_HOOKS || "")
.split(",")
.map((item) => item.trim())
.filter(Boolean)
)
const profileOrder: Record<HookProfile, number> = {
minimal: 0,
standard: 1,
strict: 2,
}
const profileAllowed = (required: HookProfile | HookProfile[]): boolean => {
if (Array.isArray(required)) {
return required.some((entry) => profileOrder[currentProfile] >= profileOrder[entry])
}
return profileOrder[currentProfile] >= profileOrder[required]
}
const hookEnabled = (
hookId: string,
requiredProfile: HookProfile | HookProfile[] = "standard"
): boolean => {
if (disabledHooks.has(hookId)) return false
return profileAllowed(requiredProfile)
}
return {
/**
* Prettier Auto-Format Hook
@@ -41,7 +77,7 @@ export const ECCHooksPlugin = async ({
editedFiles.add(event.path)
// Auto-format JS/TS files
if (event.path.match(/\.(ts|tsx|js|jsx)$/)) {
if (hookEnabled("post:edit:format", ["standard", "strict"]) && event.path.match(/\.(ts|tsx|js|jsx)$/)) {
try {
await $`prettier --write ${event.path} 2>/dev/null`
log("info", `[ECC] Formatted: ${event.path}`)
@@ -51,7 +87,7 @@ export const ECCHooksPlugin = async ({
}
// Console.log warning check
if (event.path.match(/\.(ts|tsx|js|jsx)$/)) {
if (hookEnabled("post:edit:console-warn", ["standard", "strict"]) && event.path.match(/\.(ts|tsx|js|jsx)$/)) {
try {
const result = await $`grep -n "console\\.log" ${event.path} 2>/dev/null`.text()
if (result.trim()) {
@@ -80,6 +116,7 @@ export const ECCHooksPlugin = async ({
) => {
// Check if a TypeScript file was edited
if (
hookEnabled("post:edit:typecheck", ["standard", "strict"]) &&
input.tool === "edit" &&
input.args?.filePath?.match(/\.tsx?$/)
) {
@@ -98,7 +135,11 @@ export const ECCHooksPlugin = async ({
}
// PR creation logging
if (input.tool === "bash" && input.args?.toString().includes("gh pr create")) {
if (
hookEnabled("post:bash:pr-created", ["standard", "strict"]) &&
input.tool === "bash" &&
input.args?.toString().includes("gh pr create")
) {
log("info", "[ECC] PR created - check GitHub Actions status")
}
},
@@ -115,6 +156,7 @@ export const ECCHooksPlugin = async ({
) => {
// Git push review reminder
if (
hookEnabled("pre:bash:git-push-reminder", "strict") &&
input.tool === "bash" &&
input.args?.toString().includes("git push")
) {
@@ -126,6 +168,7 @@ export const ECCHooksPlugin = async ({
// Block creation of unnecessary documentation files
if (
hookEnabled("pre:write:doc-file-warning", ["standard", "strict"]) &&
input.tool === "write" &&
input.args?.filePath &&
typeof input.args.filePath === "string"
@@ -146,7 +189,7 @@ export const ECCHooksPlugin = async ({
}
// Long-running command reminder
if (input.tool === "bash") {
if (hookEnabled("pre:bash:tmux-reminder", "strict") && input.tool === "bash") {
const cmd = String(input.args?.command || input.args || "")
if (
cmd.match(/^(npm|pnpm|yarn|bun)\s+(install|build|test|run)/) ||
@@ -169,7 +212,9 @@ export const ECCHooksPlugin = async ({
* Action: Loads context and displays welcome message
*/
"session.created": async () => {
log("info", "[ECC] Session started - Everything Claude Code hooks active")
if (!hookEnabled("session:start", ["minimal", "standard", "strict"])) return
log("info", `[ECC] Session started - profile=${currentProfile}`)
// Check for project-specific context files
try {
@@ -190,6 +235,7 @@ export const ECCHooksPlugin = async ({
* Action: Runs console.log audit on all edited files
*/
"session.idle": async () => {
if (!hookEnabled("stop:check-console-log", ["minimal", "standard", "strict"])) return
if (editedFiles.size === 0) return
log("info", "[ECC] Session idle - running console.log audit")
@@ -244,6 +290,7 @@ export const ECCHooksPlugin = async ({
* Action: Final cleanup and state saving
*/
"session.deleted": async () => {
if (!hookEnabled("session:end-marker", ["minimal", "standard", "strict"])) return
log("info", "[ECC] Session ended - cleaning up")
editedFiles.clear()
},
@@ -285,8 +332,10 @@ export const ECCHooksPlugin = async ({
*/
"shell.env": async () => {
const env: Record<string, string> = {
ECC_VERSION: "1.6.0",
ECC_VERSION: "1.8.0",
ECC_PLUGIN: "true",
ECC_HOOK_PROFILE: currentProfile,
ECC_DISABLED_HOOKS: process.env.ECC_DISABLED_HOOKS || "",
PROJECT_ROOT: worktree || directory,
}
@@ -343,7 +392,7 @@ export const ECCHooksPlugin = async ({
const contextBlock = [
"# ECC Context (preserve across compaction)",
"",
"## Active Plugin: Everything Claude Code v1.6.0",
"## Active Plugin: Everything Claude Code v1.8.0",
"- Hooks: file.edited, tool.execute.before/after, session.created/idle/deleted, shell.env, compacting, permission.ask",
"- Tools: run-tests, check-coverage, security-audit, format-code, lint-check, git-summary",
"- Agents: 13 specialized (planner, architect, tdd-guide, code-reviewer, security-reviewer, build-error-resolver, e2e-runner, refactor-cleaner, doc-updater, go-reviewer, go-build-resolver, database-reviewer, python-reviewer)",

View File

@@ -1,66 +1,68 @@
/**
* ECC Custom Tool: Format Code
*
* Language-aware code formatter that auto-detects the project's formatter.
* Supports: Biome/Prettier (JS/TS), Black (Python), gofmt (Go), rustfmt (Rust)
* Returns the formatter command that should be run for a given file.
* This avoids shell execution assumptions while still giving precise guidance.
*/
import { tool } from "@opencode-ai/plugin"
import { z } from "zod"
import { tool } from "@opencode-ai/plugin/tool"
import * as path from "path"
import * as fs from "fs"
type Formatter = "biome" | "prettier" | "black" | "gofmt" | "rustfmt"
export default tool({
name: "format-code",
description: "Format a file using the project's configured formatter. Auto-detects Biome, Prettier, Black, gofmt, or rustfmt.",
parameters: z.object({
filePath: z.string().describe("Path to the file to format"),
formatter: z.string().optional().describe("Override formatter: biome, prettier, black, gofmt, rustfmt (default: auto-detect)"),
}),
execute: async ({ filePath, formatter }, { $ }) => {
const ext = filePath.split(".").pop()?.toLowerCase() || ""
// Auto-detect formatter based on file extension and config files
let detected = formatter
if (!detected) {
if (["ts", "tsx", "js", "jsx", "json", "css", "scss"].includes(ext)) {
// Check for Biome first, then Prettier
try {
await $`test -f biome.json || test -f biome.jsonc`
detected = "biome"
} catch {
detected = "prettier"
}
} else if (["py", "pyi"].includes(ext)) {
detected = "black"
} else if (ext === "go") {
detected = "gofmt"
} else if (ext === "rs") {
detected = "rustfmt"
}
}
description:
"Detect formatter for a file and return the exact command to run (Biome, Prettier, Black, gofmt, rustfmt).",
args: {
filePath: tool.schema.string().describe("Path to the file to format"),
formatter: tool.schema
.enum(["biome", "prettier", "black", "gofmt", "rustfmt"])
.optional()
.describe("Optional formatter override"),
},
async execute(args, context) {
const cwd = context.worktree || context.directory
const ext = args.filePath.split(".").pop()?.toLowerCase() || ""
const detected = args.formatter || detectFormatter(cwd, ext)
if (!detected) {
return { formatted: false, message: `No formatter detected for .${ext} files` }
return JSON.stringify({
success: false,
message: `No formatter detected for .${ext} files`,
})
}
const commands: Record<string, string> = {
biome: `npx @biomejs/biome format --write ${filePath}`,
prettier: `npx prettier --write ${filePath}`,
black: `black ${filePath}`,
gofmt: `gofmt -w ${filePath}`,
rustfmt: `rustfmt ${filePath}`,
}
const cmd = commands[detected]
if (!cmd) {
return { formatted: false, message: `Unknown formatter: ${detected}` }
}
try {
const result = await $`${cmd}`.text()
return { formatted: true, formatter: detected, output: result }
} catch (error: unknown) {
const err = error as { stderr?: string }
return { formatted: false, formatter: detected, error: err.stderr || "Format failed" }
}
const command = buildFormatterCommand(detected, args.filePath)
return JSON.stringify({
success: true,
formatter: detected,
command,
instructions: `Run this command:\n\n${command}`,
})
},
})
function detectFormatter(cwd: string, ext: string): Formatter | null {
if (["ts", "tsx", "js", "jsx", "json", "css", "scss", "md", "yaml", "yml"].includes(ext)) {
if (fs.existsSync(path.join(cwd, "biome.json")) || fs.existsSync(path.join(cwd, "biome.jsonc"))) {
return "biome"
}
return "prettier"
}
if (["py", "pyi"].includes(ext)) return "black"
if (ext === "go") return "gofmt"
if (ext === "rs") return "rustfmt"
return null
}
function buildFormatterCommand(formatter: Formatter, filePath: string): string {
const commands: Record<Formatter, string> = {
biome: `npx @biomejs/biome format --write ${filePath}`,
prettier: `npx prettier --write ${filePath}`,
black: `black ${filePath}`,
gofmt: `gofmt -w ${filePath}`,
rustfmt: `rustfmt ${filePath}`,
}
return commands[formatter]
}

View File

@@ -1,56 +1,54 @@
/**
* ECC Custom Tool: Git Summary
*
* Provides a comprehensive git status including branch info, status,
* recent log, and diff against base branch.
* Returns branch/status/log/diff details for the active repository.
*/
import { tool } from "@opencode-ai/plugin"
import { z } from "zod"
import { tool } from "@opencode-ai/plugin/tool"
import { execSync } from "child_process"
export default tool({
name: "git-summary",
description: "Get comprehensive git summary: branch, status, recent log, and diff against base branch.",
parameters: z.object({
depth: z.number().optional().describe("Number of recent commits to show (default: 5)"),
includeDiff: z.boolean().optional().describe("Include diff against base branch (default: true)"),
baseBranch: z.string().optional().describe("Base branch for comparison (default: main)"),
}),
execute: async ({ depth = 5, includeDiff = true, baseBranch = "main" }, { $ }) => {
const results: Record<string, string> = {}
description:
"Generate git summary with branch, status, recent commits, and optional diff stats.",
args: {
depth: tool.schema
.number()
.optional()
.describe("Number of recent commits to include (default: 5)"),
includeDiff: tool.schema
.boolean()
.optional()
.describe("Include diff stats against base branch (default: true)"),
baseBranch: tool.schema
.string()
.optional()
.describe("Base branch for diff comparison (default: main)"),
},
async execute(args, context) {
const cwd = context.worktree || context.directory
const depth = args.depth ?? 5
const includeDiff = args.includeDiff ?? true
const baseBranch = args.baseBranch ?? "main"
try {
results.branch = (await $`git branch --show-current`.text()).trim()
} catch {
results.branch = "unknown"
}
try {
results.status = (await $`git status --short`.text()).trim()
} catch {
results.status = "unable to get status"
}
try {
results.log = (await $`git log --oneline -${depth}`.text()).trim()
} catch {
results.log = "unable to get log"
const result: Record<string, string> = {
branch: run("git branch --show-current", cwd) || "unknown",
status: run("git status --short", cwd) || "clean",
log: run(`git log --oneline -${depth}`, cwd) || "no commits found",
}
if (includeDiff) {
try {
results.stagedDiff = (await $`git diff --cached --stat`.text()).trim()
} catch {
results.stagedDiff = ""
}
try {
results.branchDiff = (await $`git diff ${baseBranch}...HEAD --stat`.text()).trim()
} catch {
results.branchDiff = `unable to diff against ${baseBranch}`
}
result.stagedDiff = run("git diff --cached --stat", cwd) || ""
result.branchDiff = run(`git diff ${baseBranch}...HEAD --stat`, cwd) || `unable to diff against ${baseBranch}`
}
return results
return JSON.stringify(result)
},
})
function run(command: string, cwd: string): string {
try {
return execSync(command, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim()
} catch {
return ""
}
}

View File

@@ -1,74 +1,85 @@
/**
* ECC Custom Tool: Lint Check
*
* Multi-language linter that auto-detects the project's linting tool.
* Supports: ESLint/Biome (JS/TS), Pylint/Ruff (Python), golangci-lint (Go)
* Detects the appropriate linter and returns a runnable lint command.
*/
import { tool } from "@opencode-ai/plugin"
import { z } from "zod"
import { tool } from "@opencode-ai/plugin/tool"
import * as path from "path"
import * as fs from "fs"
type Linter = "biome" | "eslint" | "ruff" | "pylint" | "golangci-lint"
export default tool({
name: "lint-check",
description: "Run linter on files or directories. Auto-detects ESLint, Biome, Ruff, Pylint, or golangci-lint.",
parameters: z.object({
target: z.string().optional().describe("File or directory to lint (default: current directory)"),
fix: z.boolean().optional().describe("Auto-fix issues if supported (default: false)"),
linter: z.string().optional().describe("Override linter: eslint, biome, ruff, pylint, golangci-lint (default: auto-detect)"),
}),
execute: async ({ target = ".", fix = false, linter }, { $ }) => {
// Auto-detect linter
let detected = linter
if (!detected) {
try {
await $`test -f biome.json || test -f biome.jsonc`
detected = "biome"
} catch {
try {
await $`test -f .eslintrc.json || test -f .eslintrc.js || test -f .eslintrc.cjs || test -f eslint.config.js || test -f eslint.config.mjs`
detected = "eslint"
} catch {
try {
await $`test -f pyproject.toml && grep -q "ruff" pyproject.toml`
detected = "ruff"
} catch {
try {
await $`test -f .golangci.yml || test -f .golangci.yaml`
detected = "golangci-lint"
} catch {
// Fall back based on file extensions in target
detected = "eslint"
}
}
}
}
}
description:
"Detect linter for a target path and return command for check/fix runs.",
args: {
target: tool.schema
.string()
.optional()
.describe("File or directory to lint (default: current directory)"),
fix: tool.schema
.boolean()
.optional()
.describe("Enable auto-fix mode"),
linter: tool.schema
.enum(["biome", "eslint", "ruff", "pylint", "golangci-lint"])
.optional()
.describe("Optional linter override"),
},
async execute(args, context) {
const cwd = context.worktree || context.directory
const target = args.target || "."
const fix = args.fix ?? false
const detected = args.linter || detectLinter(cwd)
const fixFlag = fix ? " --fix" : ""
const commands: Record<string, string> = {
biome: `npx @biomejs/biome lint${fix ? " --write" : ""} ${target}`,
eslint: `npx eslint${fixFlag} ${target}`,
ruff: `ruff check${fixFlag} ${target}`,
pylint: `pylint ${target}`,
"golangci-lint": `golangci-lint run${fixFlag} ${target}`,
}
const cmd = commands[detected]
if (!cmd) {
return { success: false, message: `Unknown linter: ${detected}` }
}
try {
const result = await $`${cmd}`.text()
return { success: true, linter: detected, output: result, issues: 0 }
} catch (error: unknown) {
const err = error as { stdout?: string; stderr?: string }
return {
success: false,
linter: detected,
output: err.stdout || "",
errors: err.stderr || "",
}
}
const command = buildLintCommand(detected, target, fix)
return JSON.stringify({
success: true,
linter: detected,
command,
instructions: `Run this command:\n\n${command}`,
})
},
})
function detectLinter(cwd: string): Linter {
if (fs.existsSync(path.join(cwd, "biome.json")) || fs.existsSync(path.join(cwd, "biome.jsonc"))) {
return "biome"
}
const eslintConfigs = [
".eslintrc.json",
".eslintrc.js",
".eslintrc.cjs",
"eslint.config.js",
"eslint.config.mjs",
]
if (eslintConfigs.some((name) => fs.existsSync(path.join(cwd, name)))) {
return "eslint"
}
const pyprojectPath = path.join(cwd, "pyproject.toml")
if (fs.existsSync(pyprojectPath)) {
try {
const content = fs.readFileSync(pyprojectPath, "utf-8")
if (content.includes("ruff")) return "ruff"
} catch {
// ignore read errors and keep fallback logic
}
}
if (fs.existsSync(path.join(cwd, ".golangci.yml")) || fs.existsSync(path.join(cwd, ".golangci.yaml"))) {
return "golangci-lint"
}
return "eslint"
}
function buildLintCommand(linter: Linter, target: string, fix: boolean): string {
if (linter === "biome") return `npx @biomejs/biome lint${fix ? " --write" : ""} ${target}`
if (linter === "eslint") return `npx eslint${fix ? " --fix" : ""} ${target}`
if (linter === "ruff") return `ruff check${fix ? " --fix" : ""} ${target}`
if (linter === "pylint") return `pylint ${target}`
return `golangci-lint run ${target}`
}

8
.prettierrc Normal file
View File

@@ -0,0 +1,8 @@
{
"singleQuote": true,
"trailingComma": "none",
"semi": true,
"tabWidth": 2,
"printWidth": 200,
"arrowParens": "avoid"
}

View File

@@ -92,7 +92,12 @@ Troubleshoot failures: check test isolation → verify mocks → fix implementat
1. **Plan** — Use planner agent, identify dependencies and risks, break into phases
2. **TDD** — Use tdd-guide agent, write tests first, implement, refactor
3. **Review** — Use code-reviewer agent immediately, address CRITICAL/HIGH issues
4. **Commit** — Conventional commits format, comprehensive PR summaries
4. **Capture knowledge in the right place**
- Personal debugging notes, preferences, and temporary context → auto memory
- Team/project knowledge (architecture decisions, API changes, runbooks) → the project's existing docs structure
- If the current task already produces the relevant docs or code comments, do not duplicate the same information elsewhere
- If there is no obvious project doc location, ask before creating a new top-level file
5. **Commit** — Conventional commits format, comprehensive PR summaries
## Git Workflow

46
CHANGELOG.md Normal file
View File

@@ -0,0 +1,46 @@
# Changelog
## 1.8.0 - 2026-03-04
### Highlights
- Harness-first release focused on reliability, eval discipline, and autonomous loop operations.
- Hook runtime now supports profile-based control and targeted hook disabling.
- NanoClaw v2 adds model routing, skill hot-load, branching, search, compaction, export, and metrics.
### Core
- Added new commands: `/harness-audit`, `/loop-start`, `/loop-status`, `/quality-gate`, `/model-route`.
- Added new skills:
- `agent-harness-construction`
- `agentic-engineering`
- `ralphinho-rfc-pipeline`
- `ai-first-engineering`
- `enterprise-agent-ops`
- `nanoclaw-repl`
- `continuous-agent-loop`
- Added new agents:
- `harness-optimizer`
- `loop-operator`
### Hook Reliability
- Fixed SessionStart root resolution with robust fallback search.
- Moved session summary persistence to `Stop` where transcript payload is available.
- Added quality-gate and cost-tracker hooks.
- Replaced fragile inline hook one-liners with dedicated script files.
- Added `ECC_HOOK_PROFILE` and `ECC_DISABLED_HOOKS` controls.
### Cross-Platform
- Improved Windows-safe path handling in doc warning logic.
- Hardened observer loop behavior to avoid non-interactive hangs.
### Notes
- `autonomous-loops` is kept as a compatibility alias for one release; `continuous-agent-loop` is the canonical name.
### Credits
- inspired by [zarazhangrui](https://github.com/zarazhangrui)
- homunculus-inspired by [humanplane](https://github.com/humanplane)

128
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

View File

@@ -62,7 +62,7 @@ cp -r skills/my-skill ~/.claude/skills/ # for skills
# Then test with Claude Code
# 5. Submit PR
git add . && git commit -m "feat: add my-skill" && git push
git add . && git commit -m "feat: add my-skill" && git push -u origin feat/my-contribution
```
---

124
README.md
View File

@@ -5,6 +5,9 @@
[![Stars](https://img.shields.io/github/stars/affaan-m/everything-claude-code?style=flat)](https://github.com/affaan-m/everything-claude-code/stargazers)
[![Forks](https://img.shields.io/github/forks/affaan-m/everything-claude-code?style=flat)](https://github.com/affaan-m/everything-claude-code/network/members)
[![Contributors](https://img.shields.io/github/contributors/affaan-m/everything-claude-code?style=flat)](https://github.com/affaan-m/everything-claude-code/graphs/contributors)
[![npm ecc-universal](https://img.shields.io/npm/dw/ecc-universal?label=ecc-universal%20weekly%20downloads&logo=npm)](https://www.npmjs.com/package/ecc-universal)
[![npm ecc-agentshield](https://img.shields.io/npm/dw/ecc-agentshield?label=ecc-agentshield%20weekly%20downloads&logo=npm)](https://www.npmjs.com/package/ecc-agentshield)
[![GitHub App Install](https://img.shields.io/badge/GitHub%20App-150%20installs-2ea44f?logo=github)](https://github.com/marketplace/ecc-tools)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
![Shell](https://img.shields.io/badge/-Shell-4EAA25?logo=gnu-bash&logoColor=white)
![TypeScript](https://img.shields.io/badge/-TypeScript-3178C6?logo=typescript&logoColor=white)
@@ -27,9 +30,29 @@
---
**The complete collection of Claude Code configs from an Anthropic hackathon winner.**
**The performance optimization system for AI agent harnesses. From an Anthropic hackathon winner.**
Production-ready agents, skills, hooks, commands, rules, and MCP configurations evolved over 10+ months of intensive daily use building real products.
Not just configs. A complete system: skills, instincts, memory optimization, continuous learning, security scanning, and research-first development. Production-ready agents, hooks, commands, rules, and MCP configurations evolved over 10+ months of intensive daily use building real products.
Works across **Claude Code**, **Codex**, **Cowork**, and other AI agent harnesses.
---
## Traction & Distribution
Use these live signals when presenting ECC to sponsors, platforms, or ecosystem partners:
- **Main package installs:** [`ecc-universal` on npm](https://www.npmjs.com/package/ecc-universal)
- **Security companion installs:** [`ecc-agentshield` on npm](https://www.npmjs.com/package/ecc-agentshield)
- **GitHub App distribution:** [ECC Tools marketplace listing](https://github.com/marketplace/ecc-tools)
- **Automated monthly metrics issue:** powered by `.github/workflows/monthly-metrics.yml`
- **Repo adoption signal:** stars/forks/contributors badges at the top of this README
Download counts for Claude Code plugin installs are not currently exposed as a public API. For partner reporting, combine npm metrics with GitHub App installs and repository traffic/fork growth.
For a sponsor-call metrics checklist and command snippets, see [`docs/business/metrics-and-sponsorship.md`](docs/business/metrics-and-sponsorship.md).
[**Sponsor ECC**](https://github.com/sponsors/affaan-m) | [Sponsor Tiers](SPONSORS.md) | [Sponsorship Program](SPONSORING.md)
---
@@ -69,6 +92,16 @@ This repo is the raw code only. The guides explain everything.
## What's New
### v1.8.0 — Harness Performance System (Mar 2026)
- **Harness-first release** — ECC is now explicitly framed as an agent harness performance system, not just a config pack.
- **Hook reliability overhaul** — SessionStart root fallback, Stop-phase session summaries, and script-based hooks replacing fragile inline one-liners.
- **Hook runtime controls** — `ECC_HOOK_PROFILE=minimal|standard|strict` and `ECC_DISABLED_HOOKS=...` for runtime gating without editing hook files.
- **New harness commands** — `/harness-audit`, `/loop-start`, `/loop-status`, `/quality-gate`, `/model-route`.
- **NanoClaw v2** — model routing, skill hot-load, session branch/search/export/compact/metrics.
- **Cross-harness parity** — behavior tightened across Claude Code, Cursor, OpenCode, and Codex app/CLI.
- **997 internal tests passing** — full suite green after hook/runtime refactor and compatibility updates.
### v1.7.0 — Cross-Platform Expansion & Presentation Builder (Feb 2026)
- **Codex app + CLI support** — Direct `AGENTS.md`-based Codex support, installer targeting, and Codex docs
@@ -145,6 +178,8 @@ cd everything-claude-code
# ./install.sh typescript python golang
# or target cursor:
# ./install.sh --target cursor typescript
# or target antigravity:
# ./install.sh --target antigravity typescript
```
For manual install instructions see the README in the `rules/` folder.
@@ -162,13 +197,13 @@ For manual install instructions see the README in the `rules/` folder.
/plugin list everything-claude-code@everything-claude-code
```
**That's it!** You now have access to 13 agents, 56 skills, and 32 commands.
**That's it!** You now have access to 16 agents, 65 skills, and 40 commands.
---
## 🌐 Cross-Platform Support
This plugin now fully supports **Windows, macOS, and Linux**. All hooks and scripts have been rewritten in Node.js for maximum compatibility.
This plugin now fully supports **Windows, macOS, and Linux**, alongside tight integration across major IDEs (Cursor, OpenCode, Antigravity) and CLI harnesses. All hooks and scripts have been rewritten in Node.js for maximum compatibility.
### Package Manager Detection
@@ -199,6 +234,18 @@ node scripts/setup-package-manager.js --detect
Or use the `/setup-pm` command in Claude Code.
### Hook Runtime Controls
Use runtime flags to tune strictness or disable specific hooks temporarily:
```bash
# Hook strictness profile (default: standard)
export ECC_HOOK_PROFILE=standard
# Comma-separated hook IDs to disable
export ECC_DISABLED_HOOKS="pre:bash:tmux-reminder,post:edit:typecheck"
```
---
## 📦 What's Inside
@@ -281,6 +328,8 @@ everything-claude-code/
| |-- liquid-glass-design/ # iOS 26 Liquid Glass design system (NEW)
| |-- foundation-models-on-device/ # Apple on-device LLM with FoundationModels (NEW)
| |-- swift-concurrency-6-2/ # Swift 6.2 Approachable Concurrency (NEW)
| |-- autonomous-loops/ # Autonomous loop patterns: sequential pipelines, PR loops, DAG orchestration (NEW)
| |-- plankton-code-quality/ # Write-time code quality enforcement with Plankton hooks (NEW)
|
|-- commands/ # Slash commands for quick execution
| |-- tdd.md # /tdd - Test-driven development
@@ -440,6 +489,10 @@ Use `/security-scan` in Claude Code to run it, or add to CI with the [GitHub Act
[GitHub](https://github.com/affaan-m/agentshield) | [npm](https://www.npmjs.com/package/ecc-agentshield)
### 🔬 Plankton — Write-Time Code Quality Enforcement
Plankton (credit: @alxfazio) is a recommended companion for write-time code quality enforcement. It runs formatters and 20+ linters on every file edit via PostToolUse hooks, then spawns Claude subprocesses (routed to Haiku/Sonnet/Opus by violation complexity) to fix issues the main agent missed. Three-phase architecture: auto-format silently (40-50% of issues), collect remaining violations as structured JSON, delegate fixes to a subprocess. Includes config protection hooks that prevent agents from modifying linter configs to pass instead of fixing code. Supports Python, TypeScript, Shell, YAML, JSON, TOML, Markdown, and Dockerfile. Use alongside AgentShield for security + quality coverage. See `skills/plankton-code-quality/` for full integration guide.
### 🧠 Continuous Learning v2
The instinct-based learning system automatically learns your patterns:
@@ -557,8 +610,15 @@ cp -r everything-claude-code/rules/golang/* ~/.claude/rules/
# Copy commands
cp everything-claude-code/commands/*.md ~/.claude/commands/
# Copy skills
cp -r everything-claude-code/skills/* ~/.claude/skills/
# Copy skills (core vs niche)
# Recommended (new users): core/general skills only
cp -r everything-claude-code/.agents/skills/* ~/.claude/skills/
cp -r everything-claude-code/skills/search-first ~/.claude/skills/
# Optional: add niche/framework-specific skills only when needed
# for s in django-patterns django-tdd springboot-patterns; do
# cp -r everything-claude-code/skills/$s ~/.claude/skills/
# done
```
#### Add hooks to settings.json
@@ -730,12 +790,13 @@ Each component is fully independent.
</details>
<details>
<summary><b>Does this work with Cursor / OpenCode / Codex?</b></summary>
<summary><b>Does this work with Cursor / OpenCode / Codex / Antigravity?</b></summary>
Yes. ECC is cross-platform:
- **Cursor**: Pre-translated configs in `.cursor/`. See [Cursor IDE Support](#cursor-ide-support).
- **OpenCode**: Full plugin support in `.opencode/`. See [OpenCode Support](#-opencode-support).
- **Codex**: First-class support with adapter drift guards and SessionStart fallback. See PR [#257](https://github.com/affaan-m/everything-claude-code/pull/257).
- **Codex**: First-class support for both macOS app and CLI, with adapter drift guards and SessionStart fallback. See PR [#257](https://github.com/affaan-m/everything-claude-code/pull/257).
- **Antigravity**: Tightly integrated setup for workflows, skills, and flatten rules in `.agent/`.
- **Claude Code**: Native — this is the primary target.
</details>
@@ -843,20 +904,25 @@ alwaysApply: false
---
## Codex CLI Support
## Codex macOS App + CLI Support
ECC provides **first-class Codex CLI support** with a reference configuration, Codex-specific AGENTS.md supplement, and 16 ported skills.
ECC provides **first-class Codex support** for both the macOS app and CLI, with a reference configuration, Codex-specific AGENTS.md supplement, and shared skills.
### Quick Start (Codex)
### Quick Start (Codex App + CLI)
```bash
# Copy the reference config to your home directory
cp .codex/config.toml ~/.codex/config.toml
# Run Codex in the repo — AGENTS.md is auto-detected
# Run Codex CLI in the repo — AGENTS.md is auto-detected
codex
```
Codex macOS app:
- Open this repository as your workspace.
- The root `AGENTS.md` is auto-detected.
- Optional: copy `.codex/config.toml` to `~/.codex/config.toml` for CLI/app behavior consistency.
### What's Included
| Component | Count | Details |
@@ -892,7 +958,7 @@ Skills at `.agents/skills/` are auto-loaded by Codex:
### Key Limitation
Codex CLI does **not yet support hooks** ([GitHub Issue #2109](https://github.com/openai/codex/issues/2109), 430+ upvotes). Security enforcement is instruction-based via `persistent_instructions` in config.toml and the sandbox permission system.
Codex does **not yet provide Claude-style hook execution parity**. ECC enforcement there is instruction-based via `AGENTS.md` and `persistent_instructions`, plus sandbox permissions.
---
@@ -916,9 +982,9 @@ The configuration is automatically detected from `.opencode/opencode.json`.
| Feature | Claude Code | OpenCode | Status |
|---------|-------------|----------|--------|
| Agents | ✅ 13 agents | ✅ 12 agents | **Claude Code leads** |
| Commands | ✅ 33 commands | ✅ 24 commands | **Claude Code leads** |
| Skills | ✅ 50+ skills | ✅ 37 skills | **Claude Code leads** |
| Agents | ✅ 16 agents | ✅ 12 agents | **Claude Code leads** |
| Commands | ✅ 40 commands | ✅ 31 commands | **Claude Code leads** |
| Skills | ✅ 65 skills | ✅ 37 skills | **Claude Code leads** |
| Hooks | ✅ 8 event types | ✅ 11 events | **OpenCode has more!** |
| Rules | ✅ 29 rules | ✅ 13 instructions | **Claude Code leads** |
| MCP Servers | ✅ 14 servers | ✅ Full | **Full parity** |
@@ -938,7 +1004,7 @@ OpenCode's plugin system is MORE sophisticated than Claude Code with 20+ event t
**Additional OpenCode events**: `file.edited`, `file.watcher.updated`, `message.updated`, `lsp.client.diagnostics`, `tui.toast.show`, and more.
### Available Commands (32)
### Available Commands (31+)
| Command | Description |
|---------|-------------|
@@ -972,8 +1038,15 @@ OpenCode's plugin system is MORE sophisticated than Claude Code with 20+ event t
| `/instinct-import` | Import instincts |
| `/instinct-export` | Export instincts |
| `/evolve` | Cluster instincts into skills |
| `/promote` | Promote project instincts to global scope |
| `/projects` | List known projects and instinct stats |
| `/learn-eval` | Extract and evaluate patterns before saving |
| `/setup-pm` | Configure package manager |
| `/harness-audit` | Audit harness reliability, eval readiness, and risk posture |
| `/loop-start` | Start controlled agentic loop execution pattern |
| `/loop-status` | Inspect active loop status and checkpoints |
| `/quality-gate` | Run quality gate checks for paths or entire repo |
| `/model-route` | Route tasks to models by complexity and budget |
### Plugin Installation
@@ -1010,11 +1083,11 @@ ECC is the **first plugin to maximize every major AI coding tool**. Here's how e
| Feature | Claude Code | Cursor IDE | Codex CLI | OpenCode |
|---------|------------|------------|-----------|----------|
| **Agents** | 13 | Shared (AGENTS.md) | Shared (AGENTS.md) | 12 |
| **Commands** | 33 | Shared | Instruction-based | 24 |
| **Skills** | 50+ | Shared | 10 (native format) | 37 |
| **Agents** | 16 | Shared (AGENTS.md) | Shared (AGENTS.md) | 12 |
| **Commands** | 40 | Shared | Instruction-based | 31 |
| **Skills** | 65 | Shared | 10 (native format) | 37 |
| **Hook Events** | 8 types | 15 types | None yet | 11 types |
| **Hook Scripts** | 9 scripts | 16 scripts (DRY adapter) | N/A | Plugin hooks |
| **Hook Scripts** | 20+ scripts | 16 scripts (DRY adapter) | N/A | Plugin hooks |
| **Rules** | 29 (common + lang) | 29 (YAML frontmatter) | Instruction-based | 13 instructions |
| **Custom Tools** | Via hooks | Via hooks | N/A | 6 native tools |
| **MCP Servers** | 14 | Shared (mcp.json) | 4 (command-based) | Full |
@@ -1022,7 +1095,7 @@ ECC is the **first plugin to maximize every major AI coding tool**. Here's how e
| **Context File** | CLAUDE.md + AGENTS.md | AGENTS.md | AGENTS.md | AGENTS.md |
| **Secret Detection** | Hook-based | beforeSubmitPrompt hook | Sandbox-based | Hook-based |
| **Auto-Format** | PostToolUse hook | afterFileEdit hook | N/A | file.edited hook |
| **Version** | Plugin | Plugin | Reference config | 1.6.0 |
| **Version** | Plugin | Plugin | Reference config | 1.8.0 |
**Key architectural decisions:**
- **AGENTS.md** at root is the universal cross-tool file (read by all 4 tools)
@@ -1038,6 +1111,11 @@ I've been using Claude Code since the experimental rollout. Won the Anthropic x
These configs are battle-tested across multiple production applications.
## Inspiration Credits
- inspired by [zarazhangrui](https://github.com/zarazhangrui)
- homunculus-inspired by [humanplane](https://github.com/humanplane)
---
## Token Optimization
@@ -1142,7 +1220,7 @@ These configs work for my workflow. You should:
This project is free and open source. Sponsors help keep it maintained and growing.
[**Become a Sponsor**](https://github.com/sponsors/affaan-m) | [Sponsor Tiers](SPONSORS.md)
[**Become a Sponsor**](https://github.com/sponsors/affaan-m) | [Sponsor Tiers](SPONSORS.md) | [Sponsorship Program](SPONSORING.md)
---

View File

@@ -287,6 +287,8 @@ everything-claude-code/
/instinct-import <file> # 从他人导入直觉
/instinct-export # 导出你的直觉以供分享
/evolve # 将相关直觉聚类到技能中
/promote # 将项目级直觉提升为全局直觉
/projects # 查看已识别项目与直觉统计
```
完整文档见 `skills/continuous-learning-v2/`

43
SPONSORING.md Normal file
View File

@@ -0,0 +1,43 @@
# Sponsoring ECC
ECC is maintained as an open-source agent harness performance system across Claude Code, Cursor, OpenCode, and Codex app/CLI.
## Why Sponsor
Sponsorship directly funds:
- Faster bug-fix and release cycles
- Cross-platform parity work across harnesses
- Public docs, skills, and reliability tooling that remain free for the community
## Sponsorship Tiers
These are practical starting points and can be adjusted for partnership scope.
| Tier | Price | Best For | Includes |
|------|-------|----------|----------|
| Pilot Partner | $200/mo | First sponsor engagement | Monthly metrics update, roadmap preview, prioritized maintainer feedback |
| Growth Partner | $500/mo | Teams actively adopting ECC | Pilot benefits + monthly office-hours sync + workflow integration guidance |
| Strategic Partner | $1,000+/mo | Platform/ecosystem partnerships | Growth benefits + coordinated launch support + deeper maintainer collaboration |
## Sponsor Reporting
Metrics shared monthly can include:
- npm downloads (`ecc-universal`, `ecc-agentshield`)
- Repository adoption (stars, forks, contributors)
- GitHub App install trend
- Release cadence and reliability milestones
For exact command snippets and a repeatable pull process, see [`docs/business/metrics-and-sponsorship.md`](docs/business/metrics-and-sponsorship.md).
## Expectations and Scope
- Sponsorship supports maintenance and acceleration; it does not transfer project ownership.
- Feature requests are prioritized based on sponsor tier, ecosystem impact, and maintenance risk.
- Security and reliability fixes take precedence over net-new features.
## Sponsor Here
- GitHub Sponsors: [https://github.com/sponsors/affaan-m](https://github.com/sponsors/affaan-m)
- Project site: [https://ecc.tools](https://ecc.tools)

View File

@@ -29,6 +29,17 @@ Your sponsorship helps:
- **Better support** — Sponsors get priority responses
- **Shape the roadmap** — Pro+ sponsors vote on features
## Sponsor Readiness Signals
Use these proof points in sponsor conversations:
- Live npm install/download metrics for `ecc-universal` and `ecc-agentshield`
- GitHub App distribution via Marketplace installs
- Public adoption signals: stars, forks, contributors, release cadence
- Cross-harness support: Claude Code, Cursor, OpenCode, Codex app/CLI
See [`docs/business/metrics-and-sponsorship.md`](docs/business/metrics-and-sponsorship.md) for a copy/paste metrics pull workflow.
## Sponsor Tiers
| Tier | Price | Benefits |
@@ -37,6 +48,7 @@ Your sponsorship helps:
| Builder | $10/mo | Premium tools access |
| Pro | $25/mo | Priority support, office hours |
| Team | $100/mo | 5 seats, team configs |
| Harness Partner | $200/mo | Monthly roadmap sync, prioritized maintainer feedback, release-note mention |
| Business | $500/mo | 25 seats, consulting credit |
| Enterprise | $2K/mo | Unlimited seats, custom tools |

View File

@@ -146,6 +146,6 @@ claude /schedule-reply "Reply to Sarah about the board meeting"
## Prerequisites
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code)
- Gmail CLI (e.g., [gog](https://github.com/pterm/gog))
- Gmail CLI (e.g., gog by @pterm)
- Node.js 18+ (for calendar-suggest.js)
- Optional: Slack MCP server, Matrix bridge (LINE), Chrome + Playwright (Messenger)

View File

@@ -222,3 +222,16 @@ When available, also check project-specific conventions from `CLAUDE.md` or proj
- State management conventions (Zustand, Redux, Context)
Adapt your review to the project's established patterns. When in doubt, match what the rest of the codebase does.
## v1.8 AI-Generated Code Review Addendum
When reviewing AI-generated changes, prioritize:
1. Behavioral regressions and edge-case handling
2. Security assumptions and trust boundaries
3. Hidden coupling or accidental architecture drift
4. Unnecessary model-cost-inducing complexity
Cost-awareness check:
- Flag workflows that escalate to higher-cost models without clear reasoning need.
- Recommend defaulting to lower-cost tiers for deterministic refactors.

View File

@@ -7,7 +7,7 @@ model: sonnet
# Database Reviewer
You are an expert PostgreSQL database specialist focused on query optimization, schema design, security, and performance. Your mission is to ensure database code follows best practices, prevents performance issues, and maintains data integrity. Incorporates patterns from [Supabase's postgres-best-practices](https://github.com/supabase/agent-skills).
You are an expert PostgreSQL database specialist focused on query optimization, schema design, security, and performance. Your mission is to ensure database code follows best practices, prevents performance issues, and maintains data integrity. Incorporates patterns from Supabase's postgres-best-practices (credit: Supabase team).
## Core Responsibilities
@@ -88,4 +88,4 @@ For detailed index patterns, schema design examples, connection management, conc
**Remember**: Database issues are often the root cause of application performance problems. Optimize queries and schema design early. Use EXPLAIN ANALYZE to verify assumptions. Always index foreign keys and RLS policy columns.
*Patterns adapted from [Supabase Agent Skills](https://github.com/supabase/agent-skills) under MIT license.*
*Patterns adapted from Supabase Agent Skills (credit: Supabase team) under MIT license.*

View File

@@ -0,0 +1,35 @@
---
name: harness-optimizer
description: Analyze and improve the local agent harness configuration for reliability, cost, and throughput.
tools: ["Read", "Grep", "Glob", "Bash", "Edit"]
model: sonnet
color: teal
---
You are the harness optimizer.
## Mission
Raise agent completion quality by improving harness configuration, not by rewriting product code.
## Workflow
1. Run `/harness-audit` and collect baseline score.
2. Identify top 3 leverage areas (hooks, evals, routing, context, safety).
3. Propose minimal, reversible configuration changes.
4. Apply changes and run validation.
5. Report before/after deltas.
## Constraints
- Prefer small changes with measurable effect.
- Preserve cross-platform behavior.
- Avoid introducing fragile shell quoting.
- Keep compatibility across Claude Code, Cursor, OpenCode, and Codex.
## Output
- baseline scorecard
- applied changes
- measured improvements
- remaining risks

36
agents/loop-operator.md Normal file
View File

@@ -0,0 +1,36 @@
---
name: loop-operator
description: Operate autonomous agent loops, monitor progress, and intervene safely when loops stall.
tools: ["Read", "Grep", "Glob", "Bash", "Edit"]
model: sonnet
color: orange
---
You are the loop operator.
## Mission
Run autonomous loops safely with clear stop conditions, observability, and recovery actions.
## Workflow
1. Start loop from explicit pattern and mode.
2. Track progress checkpoints.
3. Detect stalls and retry storms.
4. Pause and reduce scope when failure repeats.
5. Resume only after verification passes.
## Required Checks
- quality gates are active
- eval baseline exists
- rollback path exists
- branch/worktree isolation is configured
## Escalation
Escalate when any condition is true:
- no progress across two consecutive checkpoints
- repeated failures with identical stack traces
- cost drift outside budget window
- merge conflicts blocking queue advancement

View File

@@ -78,3 +78,14 @@ npm run test:coverage
- [ ] Coverage is 80%+
For detailed mocking patterns and framework-specific examples, see `skill: tdd-workflow`.
## v1.8 Eval-Driven TDD Addendum
Integrate eval-driven development into TDD flow:
1. Define capability + regression evals before implementation.
2. Run baseline and capture failure signatures.
3. Implement minimum passing change.
4. Re-run tests and evals; report pass@1 and pass@3.
Release-critical paths should target pass^3 stability before merge.

View File

@@ -1,10 +1,10 @@
---
description: Start the NanoClaw agent REPL — a persistent, session-aware AI assistant powered by the claude CLI.
description: Start NanoClaw v2 — ECC's persistent, zero-dependency REPL with model routing, skill hot-load, branching, compaction, export, and metrics.
---
# Claw Command
Start an interactive AI agent session that persists conversation history to disk and optionally loads ECC skill context.
Start an interactive AI agent session with persistent markdown history and operational controls.
## Usage
@@ -23,57 +23,29 @@ npm run claw
| Variable | Default | Description |
|----------|---------|-------------|
| `CLAW_SESSION` | `default` | Session name (alphanumeric + hyphens) |
| `CLAW_SKILLS` | *(empty)* | Comma-separated skill names to load as system context |
| `CLAW_SKILLS` | *(empty)* | Comma-separated skills loaded at startup |
| `CLAW_MODEL` | `sonnet` | Default model for the session |
## REPL Commands
Inside the REPL, type these commands directly at the prompt:
```
/clear Clear current session history
/history Print full conversation history
/sessions List all saved sessions
/help Show available commands
exit Quit the REPL
```text
/help Show help
/clear Clear current session history
/history Print full conversation history
/sessions List saved sessions
/model [name] Show/set model
/load <skill-name> Hot-load a skill into context
/branch <session-name> Branch current session
/search <query> Search query across sessions
/compact Compact old turns, keep recent context
/export <md|json|txt> [path] Export session
/metrics Show session metrics
exit Quit
```
## How It Works
## Notes
1. Reads `CLAW_SESSION` env var to select a named session (default: `default`)
2. Loads conversation history from `~/.claude/claw/{session}.md`
3. Optionally loads ECC skill context from `CLAW_SKILLS` env var
4. Enters a blocking prompt loop — each user message is sent to `claude -p` with full history
5. Responses are appended to the session file for persistence across restarts
## Session Storage
Sessions are stored as Markdown files in `~/.claude/claw/`:
```
~/.claude/claw/default.md
~/.claude/claw/my-project.md
```
Each turn is formatted as:
```markdown
### [2025-01-15T10:30:00.000Z] User
What does this function do?
---
### [2025-01-15T10:30:05.000Z] Assistant
This function calculates...
---
```
## Examples
```bash
# Start default session
node scripts/claw.js
# Named session
CLAW_SESSION=my-project node scripts/claw.js
# With skill context
CLAW_SKILLS=tdd-workflow,security-review node scripts/claw.js
```
- NanoClaw remains zero-dependency.
- Sessions are stored at `~/.claude/claw/<session>.md`.
- Compaction keeps the most recent turns and writes a compaction header.
- Export supports markdown, JSON turns, and plain text.

View File

@@ -1,6 +1,6 @@
---
name: evolve
description: Cluster related instincts into skills, commands, or agents
description: Analyze instincts and suggest or generate evolved structures
command: true
---
@@ -29,9 +29,7 @@ Analyzes instincts and clusters related ones into higher-level structures:
```
/evolve # Analyze all instincts and suggest evolutions
/evolve --domain testing # Only evolve instincts in testing domain
/evolve --dry-run # Show what would be created without creating
/evolve --threshold 5 # Require 5+ related instincts to cluster
/evolve --generate # Also generate files under evolved/{skills,commands,agents}
```
## Evolution Rules
@@ -78,63 +76,50 @@ Example:
## What to Do
1. Read all instincts from `~/.claude/homunculus/instincts/`
2. Group instincts by:
- Domain similarity
- Trigger pattern overlap
- Action sequence relationship
3. For each cluster of 3+ related instincts:
- Determine evolution type (command/skill/agent)
- Generate the appropriate file
- Save to `~/.claude/homunculus/evolved/{commands,skills,agents}/`
4. Link evolved structure back to source instincts
1. Detect current project context
2. Read project + global instincts (project takes precedence on ID conflicts)
3. Group instincts by trigger/domain patterns
4. Identify:
- Skill candidates (trigger clusters with 2+ instincts)
- Command candidates (high-confidence workflow instincts)
- Agent candidates (larger, high-confidence clusters)
5. Show promotion candidates (project -> global) when applicable
6. If `--generate` is passed, write files to:
- Project scope: `~/.claude/homunculus/projects/<project-id>/evolved/`
- Global fallback: `~/.claude/homunculus/evolved/`
## Output Format
```
🧬 Evolve Analysis
==================
============================================================
EVOLVE ANALYSIS - 12 instincts
Project: my-app (a1b2c3d4e5f6)
Project-scoped: 8 | Global: 4
============================================================
Found 3 clusters ready for evolution:
High confidence instincts (>=80%): 5
## Cluster 1: Database Migration Workflow
Instincts: new-table-migration, update-schema, regenerate-types
Type: Command
Confidence: 85% (based on 12 observations)
## SKILL CANDIDATES
1. Cluster: "adding tests"
Instincts: 3
Avg confidence: 82%
Domains: testing
Scopes: project
Would create: /new-table command
Files:
- ~/.claude/homunculus/evolved/commands/new-table.md
## COMMAND CANDIDATES (2)
/adding-tests
From: test-first-workflow [project]
Confidence: 84%
## Cluster 2: Functional Code Style
Instincts: prefer-functional, use-immutable, avoid-classes, pure-functions
Type: Skill
Confidence: 78% (based on 8 observations)
Would create: functional-patterns skill
Files:
- ~/.claude/homunculus/evolved/skills/functional-patterns.md
## Cluster 3: Debugging Process
Instincts: debug-check-logs, debug-isolate, debug-reproduce, debug-verify
Type: Agent
Confidence: 72% (based on 6 observations)
Would create: debugger agent
Files:
- ~/.claude/homunculus/evolved/agents/debugger.md
---
Run `/evolve --execute` to create these files.
## AGENT CANDIDATES (1)
adding-tests-agent
Covers 3 instincts
Avg confidence: 82%
```
## Flags
- `--execute`: Actually create the evolved structures (default is preview)
- `--dry-run`: Preview without creating
- `--domain <name>`: Only evolve instincts in specified domain
- `--threshold <n>`: Minimum instincts required to form cluster (default: 3)
- `--type <command|skill|agent>`: Only create specified type
- `--generate`: Generate evolved files in addition to analysis output
## Generated File Format

58
commands/harness-audit.md Normal file
View File

@@ -0,0 +1,58 @@
# Harness Audit Command
Audit the current repository's agent harness setup and return a prioritized scorecard.
## Usage
`/harness-audit [scope] [--format text|json]`
- `scope` (optional): `repo` (default), `hooks`, `skills`, `commands`, `agents`
- `--format`: output style (`text` default, `json` for automation)
## What to Evaluate
Score each category from `0` to `10`:
1. Tool Coverage
2. Context Efficiency
3. Quality Gates
4. Memory Persistence
5. Eval Coverage
6. Security Guardrails
7. Cost Efficiency
## Output Contract
Return:
1. `overall_score` out of 70
2. Category scores and concrete findings
3. Top 3 actions with exact file paths
4. Suggested ECC skills to apply next
## Checklist
- Inspect `hooks/hooks.json`, `scripts/hooks/`, and hook tests.
- Inspect `skills/`, command coverage, and agent coverage.
- Verify cross-harness parity for `.cursor/`, `.opencode/`, `.codex/`.
- Flag broken or stale references.
## Example Result
```text
Harness Audit (repo): 52/70
- Quality Gates: 9/10
- Eval Coverage: 6/10
- Cost Efficiency: 4/10
Top 3 Actions:
1) Add cost tracking hook in scripts/hooks/cost-tracker.js
2) Add pass@k docs and templates in skills/eval-harness/SKILL.md
3) Add command parity for /harness-audit in .opencode/commands/
```
## Arguments
$ARGUMENTS:
- `repo|hooks|skills|commands|agents` (optional scope)
- `--format text|json` (optional output format)

View File

@@ -1,6 +1,6 @@
---
name: instinct-export
description: Export instincts for sharing with teammates or other projects
description: Export instincts from project/global scope to a file
command: /instinct-export
---
@@ -18,17 +18,18 @@ Exports instincts to a shareable format. Perfect for:
/instinct-export --domain testing # Export only testing instincts
/instinct-export --min-confidence 0.7 # Only export high-confidence instincts
/instinct-export --output team-instincts.yaml
/instinct-export --scope project --output project-instincts.yaml
```
## What to Do
1. Read instincts from `~/.claude/homunculus/instincts/personal/`
2. Filter based on flags
3. Strip sensitive information:
- Remove session IDs
- Remove file paths (keep only patterns)
- Remove timestamps older than "last week"
4. Generate export file
1. Detect current project context
2. Load instincts by selected scope:
- `project`: current project only
- `global`: global only
- `all`: project + global merged (default)
3. Apply filters (`--domain`, `--min-confidence`)
4. Write YAML-style export to file (or stdout if no output path provided)
## Output Format
@@ -40,52 +41,26 @@ Creates a YAML file:
# Source: personal
# Count: 12 instincts
version: "2.0"
exported_by: "continuous-learning-v2"
export_date: "2025-01-22T10:30:00Z"
---
id: prefer-functional-style
trigger: "when writing new functions"
confidence: 0.8
domain: code-style
source: session-observation
scope: project
project_id: a1b2c3d4e5f6
project_name: my-app
---
instincts:
- id: prefer-functional-style
trigger: "when writing new functions"
action: "Use functional patterns over classes"
confidence: 0.8
domain: code-style
observations: 8
# Prefer Functional Style
- id: test-first-workflow
trigger: "when adding new functionality"
action: "Write test first, then implementation"
confidence: 0.9
domain: testing
observations: 12
- id: grep-before-edit
trigger: "when modifying code"
action: "Search with Grep, confirm with Read, then Edit"
confidence: 0.7
domain: workflow
observations: 6
## Action
Use functional patterns over classes.
```
## Privacy Considerations
Exports include:
- ✅ Trigger patterns
- ✅ Actions
- ✅ Confidence scores
- ✅ Domains
- ✅ Observation counts
Exports do NOT include:
- ❌ Actual code snippets
- ❌ File paths
- ❌ Session transcripts
- ❌ Personal identifiers
## Flags
- `--domain <name>`: Export only specified domain
- `--min-confidence <n>`: Minimum confidence threshold (default: 0.3)
- `--output <file>`: Output file path (default: instincts-export-YYYYMMDD.yaml)
- `--format <yaml|json|md>`: Output format (default: yaml)
- `--include-evidence`: Include evidence text (default: excluded)
- `--min-confidence <n>`: Minimum confidence threshold
- `--output <file>`: Output file path (prints to stdout when omitted)
- `--scope <project|global|all>`: Export scope (default: `all`)

View File

@@ -1,6 +1,6 @@
---
name: instinct-import
description: Import instincts from teammates, Skill Creator, or other sources
description: Import instincts from file or URL into project/global scope
command: true
---
@@ -11,7 +11,7 @@ command: true
Run the instinct CLI using the plugin root path:
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" import <file-or-url> [--dry-run] [--force] [--min-confidence 0.7]
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" import <file-or-url> [--dry-run] [--force] [--min-confidence 0.7] [--scope project|global]
```
Or if `CLAUDE_PLUGIN_ROOT` is not set (manual installation):
@@ -20,18 +20,15 @@ Or if `CLAUDE_PLUGIN_ROOT` is not set (manual installation):
python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py import <file-or-url>
```
Import instincts from:
- Teammates' exports
- Skill Creator (repo analysis)
- Community collections
- Previous machine backups
Import instincts from local file paths or HTTP(S) URLs.
## Usage
```
/instinct-import team-instincts.yaml
/instinct-import https://github.com/org/repo/instincts.yaml
/instinct-import --from-skill-creator acme/webapp
/instinct-import team-instincts.yaml --dry-run
/instinct-import team-instincts.yaml --scope global --force
```
## What to Do
@@ -40,7 +37,9 @@ Import instincts from:
2. Parse and validate the format
3. Check for duplicates with existing instincts
4. Merge or add new instincts
5. Save to `~/.claude/homunculus/instincts/inherited/`
5. Save to inherited instincts directory:
- Project scope: `~/.claude/homunculus/projects/<project-id>/instincts/inherited/`
- Global scope: `~/.claude/homunculus/instincts/inherited/`
## Import Process
@@ -71,60 +70,33 @@ Already have similar instincts:
Import: 0.9 confidence
→ Update to import (higher confidence)
## Conflicting Instincts (1)
These contradict local instincts:
❌ use-classes-for-services
Conflicts with: avoid-classes
→ Skip (requires manual resolution)
---
Import 8 new, update 1, skip 3?
Import 8 new, update 1?
```
## Merge Strategies
## Merge Behavior
### For Duplicates
When importing an instinct that matches an existing one:
- **Higher confidence wins**: Keep the one with higher confidence
- **Merge evidence**: Combine observation counts
- **Update timestamp**: Mark as recently validated
### For Conflicts
When importing an instinct that contradicts an existing one:
- **Skip by default**: Don't import conflicting instincts
- **Flag for review**: Mark both as needing attention
- **Manual resolution**: User decides which to keep
When importing an instinct with an existing ID:
- Higher-confidence import becomes an update candidate
- Equal/lower-confidence import is skipped
- User confirms unless `--force` is used
## Source Tracking
Imported instincts are marked with:
```yaml
source: "inherited"
source: inherited
scope: project
imported_from: "team-instincts.yaml"
imported_at: "2025-01-22T10:30:00Z"
original_source: "session-observation" # or "repo-analysis"
project_id: "a1b2c3d4e5f6"
project_name: "my-project"
```
## Skill Creator Integration
When importing from Skill Creator:
```
/instinct-import --from-skill-creator acme/webapp
```
This fetches instincts generated from repo analysis:
- Source: `repo-analysis`
- Higher initial confidence (0.7+)
- Linked to source repository
## Flags
- `--dry-run`: Preview without importing
- `--force`: Import even if conflicts exist
- `--merge-strategy <higher|local|import>`: How to handle duplicates
- `--from-skill-creator <owner/repo>`: Import from Skill Creator analysis
- `--force`: Skip confirmation prompt
- `--min-confidence <n>`: Only import instincts above threshold
- `--scope <project|global>`: Select target scope (default: `project`)
## Output
@@ -134,7 +106,7 @@ After import:
Added: 8 instincts
Updated: 1 instinct
Skipped: 3 instincts (2 duplicates, 1 conflict)
Skipped: 3 instincts (equal/higher confidence already exists)
New instincts saved to: ~/.claude/homunculus/instincts/inherited/

View File

@@ -1,12 +1,12 @@
---
name: instinct-status
description: Show all learned instincts with their confidence levels
description: Show learned instincts (project + global) with confidence
command: true
---
# Instinct Status Command
Shows all learned instincts with their confidence scores, grouped by domain.
Shows learned instincts for the current project plus global instincts, grouped by domain.
## Implementation
@@ -26,61 +26,34 @@ python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py status
```
/instinct-status
/instinct-status --domain code-style
/instinct-status --low-confidence
```
## What to Do
1. Read all instinct files from `~/.claude/homunculus/instincts/personal/`
2. Read inherited instincts from `~/.claude/homunculus/instincts/inherited/`
3. Display them grouped by domain with confidence bars
1. Detect current project context (git remote/path hash)
2. Read project instincts from `~/.claude/homunculus/projects/<project-id>/instincts/`
3. Read global instincts from `~/.claude/homunculus/instincts/`
4. Merge with precedence rules (project overrides global when IDs collide)
5. Display grouped by domain with confidence bars and observation stats
## Output Format
```
📊 Instinct Status
==================
============================================================
INSTINCT STATUS - 12 total
============================================================
## Code Style (4 instincts)
Project: my-app (a1b2c3d4e5f6)
Project instincts: 8
Global instincts: 4
### prefer-functional-style
Trigger: when writing new functions
Action: Use functional patterns over classes
Confidence: ████████░░ 80%
Source: session-observation | Last updated: 2025-01-22
## PROJECT-SCOPED (my-app)
### WORKFLOW (3)
███████░░░ 70% grep-before-edit [project]
trigger: when modifying code
### use-path-aliases
Trigger: when importing modules
Action: Use @/ path aliases instead of relative imports
Confidence: ██████░░░░ 60%
Source: repo-analysis (github.com/acme/webapp)
## Testing (2 instincts)
### test-first-workflow
Trigger: when adding new functionality
Action: Write test first, then implementation
Confidence: █████████░ 90%
Source: session-observation
## Workflow (3 instincts)
### grep-before-edit
Trigger: when modifying code
Action: Search with Grep, confirm with Read, then Edit
Confidence: ███████░░░ 70%
Source: session-observation
---
Total: 9 instincts (4 personal, 5 inherited)
Observer: Running (last analysis: 5 min ago)
## GLOBAL (apply to all projects)
### SECURITY (2)
█████████░ 85% validate-user-input [global]
trigger: when handling user input
```
## Flags
- `--domain <name>`: Filter by domain (code-style, testing, git, etc.)
- `--low-confidence`: Show only instincts with confidence < 0.5
- `--high-confidence`: Show only instincts with confidence >= 0.7
- `--source <type>`: Filter by source (session-observation, repo-analysis, inherited)
- `--json`: Output as JSON for programmatic use

32
commands/loop-start.md Normal file
View File

@@ -0,0 +1,32 @@
# Loop Start Command
Start a managed autonomous loop pattern with safety defaults.
## Usage
`/loop-start [pattern] [--mode safe|fast]`
- `pattern`: `sequential`, `continuous-pr`, `rfc-dag`, `infinite`
- `--mode`:
- `safe` (default): strict quality gates and checkpoints
- `fast`: reduced gates for speed
## Flow
1. Confirm repository state and branch strategy.
2. Select loop pattern and model tier strategy.
3. Enable required hooks/profile for the chosen mode.
4. Create loop plan and write runbook under `.claude/plans/`.
5. Print commands to start and monitor the loop.
## Required Safety Checks
- Verify tests pass before first loop iteration.
- Ensure `ECC_HOOK_PROFILE` is not disabled globally.
- Ensure loop has explicit stop condition.
## Arguments
$ARGUMENTS:
- `<pattern>` optional (`sequential|continuous-pr|rfc-dag|infinite`)
- `--mode safe|fast` optional

24
commands/loop-status.md Normal file
View File

@@ -0,0 +1,24 @@
# Loop Status Command
Inspect active loop state, progress, and failure signals.
## Usage
`/loop-status [--watch]`
## What to Report
- active loop pattern
- current phase and last successful checkpoint
- failing checks (if any)
- estimated time/cost drift
- recommended intervention (continue/pause/stop)
## Watch Mode
When `--watch` is present, refresh status periodically and surface state changes.
## Arguments
$ARGUMENTS:
- `--watch` optional

26
commands/model-route.md Normal file
View File

@@ -0,0 +1,26 @@
# Model Route Command
Recommend the best model tier for the current task by complexity and budget.
## Usage
`/model-route [task-description] [--budget low|med|high]`
## Routing Heuristic
- `haiku`: deterministic, low-risk mechanical changes
- `sonnet`: default for implementation and refactors
- `opus`: architecture, deep review, ambiguous requirements
## Required Output
- recommended model
- confidence level
- why this model fits
- fallback model if first attempt fails
## Arguments
$ARGUMENTS:
- `[task-description]` optional free-text
- `--budget low|med|high` optional

View File

@@ -85,13 +85,13 @@ EOF",
### Phase 0: Prompt Enhancement (Optional)
`[Mode: Prepare]` - If ace-tool MCP available, call `mcp__ace-tool__enhance_prompt`, **replace original $ARGUMENTS with enhanced result for subsequent Codex calls**
`[Mode: Prepare]` - If ace-tool MCP available, call `mcp__ace-tool__enhance_prompt`, **replace original $ARGUMENTS with enhanced result for subsequent Codex calls**. If unavailable, use `$ARGUMENTS` as-is.
### Phase 1: Research
`[Mode: Research]` - Understand requirements and gather context
1. **Code Retrieval** (if ace-tool MCP available): Call `mcp__ace-tool__search_context` to retrieve existing APIs, data models, service architecture
1. **Code Retrieval** (if ace-tool MCP available): Call `mcp__ace-tool__search_context` to retrieve existing APIs, data models, service architecture. If unavailable, use built-in tools: `Glob` for file discovery, `Grep` for symbol/API search, `Read` for context gathering, `Task` (Explore agent) for deeper exploration.
2. Requirement completeness score (0-10): >=7 continue, <7 stop and supplement
### Phase 2: Ideation

View File

@@ -136,7 +136,7 @@ TaskOutput({ task_id: "<task_id>", block: true, timeout: 600000 })
`[Mode: Retrieval]`
**Must use MCP tool for quick context retrieval, do NOT manually read files one by one**
**If ace-tool MCP is available**, use it for quick context retrieval:
Based on "Key Files" list in plan, call `mcp__ace-tool__search_context`:
@@ -151,7 +151,12 @@ mcp__ace-tool__search_context({
- Extract target paths from plan's "Key Files" table
- Build semantic query covering: entry files, dependency modules, related type definitions
- If results insufficient, add 1-2 recursive retrievals
- **NEVER** use Bash + find/ls to manually explore project structure
**If ace-tool MCP is NOT available**, use Claude Code built-in tools as fallback:
1. **Glob**: Find target files from plan's "Key Files" table (e.g., `Glob("src/components/**/*.tsx")`)
2. **Grep**: Search for key symbols, function names, type definitions across the codebase
3. **Read**: Read the discovered files to gather complete context
4. **Task (Explore agent)**: For broader exploration, use `Task` with `subagent_type: "Explore"`
**After Retrieval**:
- Organize retrieved code snippets

View File

@@ -85,13 +85,13 @@ EOF",
### Phase 0: Prompt Enhancement (Optional)
`[Mode: Prepare]` - If ace-tool MCP available, call `mcp__ace-tool__enhance_prompt`, **replace original $ARGUMENTS with enhanced result for subsequent Gemini calls**
`[Mode: Prepare]` - If ace-tool MCP available, call `mcp__ace-tool__enhance_prompt`, **replace original $ARGUMENTS with enhanced result for subsequent Gemini calls**. If unavailable, use `$ARGUMENTS` as-is.
### Phase 1: Research
`[Mode: Research]` - Understand requirements and gather context
1. **Code Retrieval** (if ace-tool MCP available): Call `mcp__ace-tool__search_context` to retrieve existing components, styles, design system
1. **Code Retrieval** (if ace-tool MCP available): Call `mcp__ace-tool__search_context` to retrieve existing components, styles, design system. If unavailable, use built-in tools: `Glob` for file discovery, `Grep` for component/style search, `Read` for context gathering, `Task` (Explore agent) for deeper exploration.
2. Requirement completeness score (0-10): >=7 continue, <7 stop and supplement
### Phase 2: Ideation

View File

@@ -71,7 +71,7 @@ TaskOutput({ task_id: "<task_id>", block: true, timeout: 600000 })
#### 1.1 Prompt Enhancement (MUST execute first)
**MUST call `mcp__ace-tool__enhance_prompt` tool**:
**If ace-tool MCP is available**, call `mcp__ace-tool__enhance_prompt` tool:
```
mcp__ace-tool__enhance_prompt({
@@ -83,9 +83,11 @@ mcp__ace-tool__enhance_prompt({
Wait for enhanced prompt, **replace original $ARGUMENTS with enhanced result** for all subsequent phases.
**If ace-tool MCP is NOT available**: Skip this step and use the original `$ARGUMENTS` as-is for all subsequent phases.
#### 1.2 Context Retrieval
**Call `mcp__ace-tool__search_context` tool**:
**If ace-tool MCP is available**, call `mcp__ace-tool__search_context` tool:
```
mcp__ace-tool__search_context({
@@ -96,7 +98,12 @@ mcp__ace-tool__search_context({
- Build semantic query using natural language (Where/What/How)
- **NEVER answer based on assumptions**
- If MCP unavailable: fallback to Glob + Grep for file discovery and key symbol location
**If ace-tool MCP is NOT available**, use Claude Code built-in tools as fallback:
1. **Glob**: Find relevant files by pattern (e.g., `Glob("**/*.ts")`, `Glob("src/**/*.py")`)
2. **Grep**: Search for key symbols, function names, class definitions (e.g., `Grep("className|functionName")`)
3. **Read**: Read the discovered files to gather complete context
4. **Task (Explore agent)**: For deeper exploration, use `Task` with `subagent_type: "Explore"` to search across the codebase
#### 1.3 Completeness Check

View File

@@ -15,14 +15,14 @@ Structured development workflow with quality gates, MCP services, and multi-mode
- Task to develop: $ARGUMENTS
- Structured 6-phase workflow with quality gates
- Multi-model collaboration: Codex (backend) + Gemini (frontend) + Claude (orchestration)
- MCP service integration (ace-tool) for enhanced capabilities
- MCP service integration (ace-tool, optional) for enhanced capabilities
## Your Role
You are the **Orchestrator**, coordinating a multi-model collaborative system (Research → Ideation → Plan → Execute → Optimize → Review). Communicate concisely and professionally for experienced developers.
**Collaborative Models**:
- **ace-tool MCP** Code retrieval + Prompt enhancement
- **ace-tool MCP** (optional) Code retrieval + Prompt enhancement
- **Codex** Backend logic, algorithms, debugging (**Backend authority, trustworthy**)
- **Gemini** Frontend UI/UX, visual design (**Frontend expert, backend opinions for reference only**)
- **Claude (self)** Orchestration, planning, execution, delivery
@@ -111,8 +111,8 @@ TaskOutput({ task_id: "<task_id>", block: true, timeout: 600000 })
`[Mode: Research]` - Understand requirements and gather context:
1. **Prompt Enhancement**: Call `mcp__ace-tool__enhance_prompt`, **replace original $ARGUMENTS with enhanced result for all subsequent Codex/Gemini calls**
2. **Context Retrieval**: Call `mcp__ace-tool__search_context`
1. **Prompt Enhancement** (if ace-tool MCP available): Call `mcp__ace-tool__enhance_prompt`, **replace original $ARGUMENTS with enhanced result for all subsequent Codex/Gemini calls**. If unavailable, use `$ARGUMENTS` as-is.
2. **Context Retrieval** (if ace-tool MCP available): Call `mcp__ace-tool__search_context`. If unavailable, use built-in tools: `Glob` for file discovery, `Grep` for symbol search, `Read` for context gathering, `Task` (Explore agent) for deeper exploration.
3. **Requirement Completeness Score** (0-10):
- Goal clarity (0-3), Expected outcome (0-3), Scope boundaries (0-2), Constraints (0-2)
- ≥7: Continue | <7: Stop, ask clarifying questions

39
commands/projects.md Normal file
View File

@@ -0,0 +1,39 @@
---
name: projects
description: List known projects and their instinct statistics
command: true
---
# Projects Command
List project registry entries and per-project instinct/observation counts for continuous-learning-v2.
## Implementation
Run the instinct CLI using the plugin root path:
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" projects
```
Or if `CLAUDE_PLUGIN_ROOT` is not set (manual installation):
```bash
python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py projects
```
## Usage
```bash
/projects
```
## What to Do
1. Read `~/.claude/homunculus/projects.json`
2. For each project, display:
- Project name, id, root, remote
- Personal and inherited instinct counts
- Observation event count
- Last seen timestamp
3. Also display global instinct totals

41
commands/promote.md Normal file
View File

@@ -0,0 +1,41 @@
---
name: promote
description: Promote project-scoped instincts to global scope
command: true
---
# Promote Command
Promote instincts from project scope to global scope in continuous-learning-v2.
## Implementation
Run the instinct CLI using the plugin root path:
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/continuous-learning-v2/scripts/instinct-cli.py" promote [instinct-id] [--force] [--dry-run]
```
Or if `CLAUDE_PLUGIN_ROOT` is not set (manual installation):
```bash
python3 ~/.claude/skills/continuous-learning-v2/scripts/instinct-cli.py promote [instinct-id] [--force] [--dry-run]
```
## Usage
```bash
/promote # Auto-detect promotion candidates
/promote --dry-run # Preview auto-promotion candidates
/promote --force # Promote all qualified candidates without prompt
/promote grep-before-edit # Promote one specific instinct from current project
```
## What to Do
1. Detect current project
2. If `instinct-id` is provided, promote only that instinct (if present in current project)
3. Otherwise, find cross-project candidates that:
- Appear in at least 2 projects
- Meet confidence threshold
4. Write promoted instincts to `~/.claude/homunculus/instincts/personal/` with `scope: global`

29
commands/quality-gate.md Normal file
View File

@@ -0,0 +1,29 @@
# Quality Gate Command
Run the ECC quality pipeline on demand for a file or project scope.
## Usage
`/quality-gate [path|.] [--fix] [--strict]`
- default target: current directory (`.`)
- `--fix`: allow auto-format/fix where configured
- `--strict`: fail on warnings where supported
## Pipeline
1. Detect language/tooling for target.
2. Run formatter checks.
3. Run lint/type checks when available.
4. Produce a concise remediation list.
## Notes
This command mirrors hook behavior but is operator-invoked.
## Arguments
$ARGUMENTS:
- `[path|.]` optional target path
- `--fix` optional
- `--strict` optional

View File

@@ -0,0 +1,74 @@
# Metrics and Sponsorship Playbook
This file is a practical script for sponsor calls and ecosystem partner reviews.
## What to Track
Use four categories in every update:
1. **Distribution** — npm packages and GitHub App installs
2. **Adoption** — stars, forks, contributors, release cadence
3. **Product surface** — commands/skills/agents and cross-platform support
4. **Reliability** — test pass counts and production bug turnaround
## Pull Live Metrics
### npm downloads
```bash
# Weekly downloads
curl -s https://api.npmjs.org/downloads/point/last-week/ecc-universal
curl -s https://api.npmjs.org/downloads/point/last-week/ecc-agentshield
# Last 30 days
curl -s https://api.npmjs.org/downloads/point/last-month/ecc-universal
curl -s https://api.npmjs.org/downloads/point/last-month/ecc-agentshield
```
### GitHub repository adoption
```bash
gh api repos/affaan-m/everything-claude-code \
--jq '{stars:.stargazers_count,forks:.forks_count,contributors_url:.contributors_url,open_issues:.open_issues_count}'
```
### GitHub traffic (maintainer access required)
```bash
gh api repos/affaan-m/everything-claude-code/traffic/views
gh api repos/affaan-m/everything-claude-code/traffic/clones
```
### GitHub App installs
GitHub App install count is currently most reliable in the Marketplace/App dashboard.
Use the latest value from:
- [ECC Tools Marketplace](https://github.com/marketplace/ecc-tools)
## What Cannot Be Measured Publicly (Yet)
- Claude plugin install/download counts are not currently exposed via a public API.
- For partner conversations, use npm metrics + GitHub App installs + repo traffic as the proxy bundle.
## Suggested Sponsor Packaging
Use these as starting points in negotiation:
- **Pilot Partner:** `$200/month`
- Best for first partnership validation and simple monthly sponsor updates.
- **Growth Partner:** `$500/month`
- Includes roadmap check-ins and implementation feedback loop.
- **Strategic Partner:** `$1,000+/month`
- Multi-touch collaboration, launch support, and deeper operational alignment.
## 60-Second Talking Track
Use this on calls:
> ECC is now positioned as an agent harness performance system, not a config repo.
> We track adoption through npm distribution, GitHub App installs, and repository growth.
> Claude plugin installs are structurally undercounted publicly, so we use a blended metrics model.
> The project supports Claude Code, Cursor, OpenCode, and Codex app/CLI with production-grade hook reliability and a large passing test suite.
For launch-ready social copy snippets, see [`social-launch-copy.md`](./social-launch-copy.md).

View File

@@ -0,0 +1,62 @@
# Social Launch Copy (X + LinkedIn)
Use these templates as launch-ready starting points. Replace placeholders before posting.
## X Post: Release Announcement
```text
ECC v1.8.0 is live.
We moved from “config pack” to an agent harness performance system:
- hook reliability fixes
- new harness commands
- cross-tool parity (Claude Code, Cursor, OpenCode, Codex)
Start here: <repo-link>
```
## X Post: Proof + Metrics
```text
If you evaluate agent tooling, use blended distribution metrics:
- npm installs (`ecc-universal`, `ecc-agentshield`)
- GitHub App installs
- repo adoption (stars/forks/contributors)
We now track this monthly in-repo for sponsor transparency.
```
## X Quote Tweet: Eval Skills Article
```text
Strong point on eval discipline.
In ECC we turned this into production checks via:
- /harness-audit
- /quality-gate
- Stop-phase session summaries
This is where harness performance compounds over time.
```
## X Quote Tweet: Plankton / deslop workflow
```text
This workflow direction is right: optimize the harness, not just prompts.
Our v1.8.0 focus was reliability + parity + measurable quality gates across toolchains.
```
## LinkedIn Post: Partner-Friendly Summary
```text
We shipped ECC v1.8.0 with one objective: improve agent harness performance in production.
Highlights:
- more reliable hook lifecycle behavior
- new harness-level quality commands
- parity across Claude Code, Cursor, OpenCode, and Codex
- stronger sponsor-facing metrics tracking
If your team runs AI coding agents daily, this is designed for operational use.
```

View File

@@ -0,0 +1,14 @@
# Continuous Learning v2 Spec
This document captures the v2 continuous-learning architecture:
1. Hook-based observation capture
2. Background observer analysis loop
3. Instinct scoring and persistence
4. Evolution of instincts into reusable skills/commands
Primary implementation lives in:
- `skills/continuous-learning-v2/`
- `scripts/hooks/`
Use this file as the stable reference path for docs and translations.

View File

@@ -7,7 +7,7 @@ model: opus
# データベースレビューアー
あなたはクエリ最適化、スキーマ設計、セキュリティ、パフォーマンスに焦点を当てたエキスパートPostgreSQLデータベーススペシャリストです。あなたのミッションは、データベースコードがベストプラクティスに従い、パフォーマンス問題を防ぎ、データ整合性を維持することを確実にすることです。このエージェントは[SupabaseのPostgreSQLベストプラクティス](https://github.com/supabase/agent-skills)からのパターンを組み込んでいます。
あなたはクエリ最適化、スキーマ設計、セキュリティ、パフォーマンスに焦点を当てたエキスパートPostgreSQLデータベーススペシャリストです。あなたのミッションは、データベースコードがベストプラクティスに従い、パフォーマンス問題を防ぎ、データ整合性を維持することを確実にすることです。このエージェントは[SupabaseのPostgreSQLベストプラクティス](Supabase Agent Skills (credit: Supabase team))からのパターンを組み込んでいます。
## 主な責務
@@ -651,4 +651,4 @@ ORDER BY rank DESC;
**覚えておくこと**: データベースの問題は、アプリケーションパフォーマンス問題の根本原因であることが多いです。クエリとスキーマ設計を早期に最適化してください。仮定を検証するためにEXPLAIN ANALYZEを使用してください。常に外部キーとRLSポリシー列にインデックスを作成してください。
*パターンはMITライセンスの下で[Supabase Agent Skills](https://github.com/supabase/agent-skills)から適応されています。*
*パターンはMITライセンスの下で[Supabase Agent Skills](Supabase Agent Skills (credit: Supabase team))から適応されています。*

View File

@@ -85,13 +85,13 @@ EOF",
### フェーズ 0: プロンプト強化(オプション)
`[Mode: Prepare]` - ace-tool MCPが利用可能な場合、`mcp__ace-tool__enhance_prompt`を呼び出し、**後続のCodex呼び出しのために元の$ARGUMENTSを強化結果で置き換える**
`[Mode: Prepare]` - ace-tool MCPが利用可能な場合、`mcp__ace-tool__enhance_prompt`を呼び出し、**後続のCodex呼び出しのために元の$ARGUMENTSを強化結果で置き換える**。利用できない場合は`$ARGUMENTS`をそのまま使用。
### フェーズ 1: 調査
`[Mode: Research]` - 要件の理解とコンテキストの収集
1. **コード取得**(ace-tool MCPが利用可能な場合): `mcp__ace-tool__search_context`を呼び出して既存のAPI、データモデル、サービスアーキテクチャを取得
1. **コード取得**(ace-tool MCPが利用可能な場合): `mcp__ace-tool__search_context`を呼び出して既存のAPI、データモデル、サービスアーキテクチャを取得。利用できない場合は組み込みツールを使用: `Glob`でファイル検索、`Grep`でシンボル/API検索、`Read`でコンテキスト収集、`Task`(Exploreエージェント)でより深い探索。
2. 要件の完全性スコア(0-10): >=7で継続、<7で停止して補足
### フェーズ 2: アイデア創出

View File

@@ -136,7 +136,7 @@ TaskOutput({ task_id: "<task_id>", block: true, timeout: 600000 })
`[Mode: Retrieval]`
**MCPツールを使用したクイックコンテキスト取得が必須です。ファイルを1つずつ手動で読まないでください**
**ace-tool MCPが利用可能な場合**、クイックコンテキスト取得に使用:
計画の「キーファイル」リストに基づいて、`mcp__ace-tool__search_context`を呼び出します:
@@ -151,7 +151,12 @@ mcp__ace-tool__search_context({
- 計画の「キーファイル」テーブルから対象パスを抽出
- カバー範囲のセマンティッククエリを構築: エントリファイル、依存モジュール、関連する型定義
- 結果が不十分な場合、1-2回の再帰的取得を追加
- **決して**Bash + find/lsを使用してプロジェクト構造を手動で探索しない
**ace-tool MCPが利用できない場合**、Claude Code組み込みツールでフォールバック:
1. **Glob**: 計画の「キーファイル」テーブルから対象ファイルを検索 (例: `Glob("src/components/**/*.tsx")`)
2. **Grep**: キーシンボル、関数名、型定義をコードベース全体で検索
3. **Read**: 発見したファイルを読み取り、完全なコンテキストを収集
4. **Task (Explore エージェント)**: より広範な探索が必要な場合、`Task``subagent_type: "Explore"` で使用
**取得後**:
- 取得したコードスニペットを整理

View File

@@ -85,13 +85,13 @@ EOF",
### フェーズ 0: プロンプト強化(オプション)
`[Mode: Prepare]` - ace-tool MCPが利用可能な場合、`mcp__ace-tool__enhance_prompt`を呼び出し、**後続のGemini呼び出しのために元の$ARGUMENTSを強化結果で置き換える**
`[Mode: Prepare]` - ace-tool MCPが利用可能な場合、`mcp__ace-tool__enhance_prompt`を呼び出し、**後続のGemini呼び出しのために元の$ARGUMENTSを強化結果で置き換える**。利用できない場合は`$ARGUMENTS`をそのまま使用。
### フェーズ 1: 調査
`[Mode: Research]` - 要件の理解とコンテキストの収集
1. **コード取得**(ace-tool MCPが利用可能な場合): `mcp__ace-tool__search_context`を呼び出して既存のコンポーネント、スタイル、デザインシステムを取得
1. **コード取得**(ace-tool MCPが利用可能な場合): `mcp__ace-tool__search_context`を呼び出して既存のコンポーネント、スタイル、デザインシステムを取得。利用できない場合は組み込みツールを使用: `Glob`でファイル検索、`Grep`でコンポーネント/スタイル検索、`Read`でコンテキスト収集、`Task`(Exploreエージェント)でより深い探索。
2. 要件の完全性スコア(0-10): >=7で継続、<7で停止して補足
### フェーズ 2: アイデア創出

View File

@@ -71,7 +71,7 @@ TaskOutput({ task_id: "<task_id>", block: true, timeout: 600000 })
#### 1.1 プロンプト強化(最初に実行する必要があります)
**`mcp__ace-tool__enhance_prompt`ツールを呼び出す必要があります**:
**ace-tool MCPが利用可能な場合**`mcp__ace-tool__enhance_prompt`ツールを呼び出す:
```
mcp__ace-tool__enhance_prompt({
@@ -83,9 +83,11 @@ mcp__ace-tool__enhance_prompt({
強化されたプロンプトを待ち、**後続のすべてのフェーズのために元の$ARGUMENTSを強化結果で置き換える**。
**ace-tool MCPが利用できない場合**: このステップをスキップし、後続のすべてのフェーズで元の`$ARGUMENTS`をそのまま使用する。
#### 1.2 コンテキスト取得
**`mcp__ace-tool__search_context`ツールを呼び出す**:
**ace-tool MCPが利用可能な場合**`mcp__ace-tool__search_context`ツールを呼び出す:
```
mcp__ace-tool__search_context({
@@ -96,7 +98,12 @@ mcp__ace-tool__search_context({
- 自然言語を使用してセマンティッククエリを構築(Where/What/How)
- **仮定に基づいて回答しない**
- MCPが利用できない場合: Glob + Grepにフォールバックしてファイル検出とキーシンボル位置を特定
**ace-tool MCPが利用できない場合**、Claude Code組み込みツールでフォールバック:
1. **Glob**: パターンで関連ファイルを検索 (例: `Glob("**/*.ts")`, `Glob("src/**/*.py")`)
2. **Grep**: キーシンボル、関数名、クラス定義を検索 (例: `Grep("className|functionName")`)
3. **Read**: 発見したファイルを読み取り、完全なコンテキストを収集
4. **Task (Explore エージェント)**: より深い探索が必要な場合、`Task``subagent_type: "Explore"` で使用
#### 1.3 完全性チェック

View File

@@ -15,14 +15,14 @@
- 開発するタスク: $ARGUMENTS
- 品質ゲートを備えた構造化された6フェーズワークフロー
- マルチモデル連携: Codex(バックエンド) + Gemini(フロントエンド) + Claude(オーケストレーション)
- MCPサービス統合(ace-tool)による機能強化
- MCPサービス統合(ace-tool、オプション)による機能強化
## 役割
あなたは**オーケストレーター**として、マルチモデル協調システムを調整します(調査 → アイデア創出 → 計画 → 実装 → 最適化 → レビュー)。経験豊富な開発者向けに簡潔かつ専門的にコミュニケーションします。
**連携モデル**:
- **ace-tool MCP** コード取得 + プロンプト強化
- **ace-tool MCP**(オプション) コード取得 + プロンプト強化
- **Codex** バックエンドロジック、アルゴリズム、デバッグ(**バックエンドの権威、信頼できる**)
- **Gemini** フロントエンドUI/UX、ビジュアルデザイン(**フロントエンドエキスパート、バックエンドの意見は参考のみ**)
- **Claude(自身)** オーケストレーション、計画、実装、配信
@@ -111,8 +111,8 @@ TaskOutput({ task_id: "<task_id>", block: true, timeout: 600000 })
`[Mode: Research]` - 要件の理解とコンテキストの収集:
1. **プロンプト強化**: `mcp__ace-tool__enhance_prompt`を呼び出し、**後続のすべてのCodex/Gemini呼び出しのために元の$ARGUMENTSを強化結果で置き換える**
2. **コンテキスト取得**: `mcp__ace-tool__search_context`を呼び出す
1. **プロンプト強化**(ace-tool MCPが利用可能な場合): `mcp__ace-tool__enhance_prompt`を呼び出し、**後続のすべてのCodex/Gemini呼び出しのために元の$ARGUMENTSを強化結果で置き換える**。利用できない場合は`$ARGUMENTS`をそのまま使用。
2. **コンテキスト取得**(ace-tool MCPが利用可能な場合): `mcp__ace-tool__search_context`を呼び出す。利用できない場合は組み込みツールを使用: `Glob`でファイル検索、`Grep`でシンボル検索、`Read`でコンテキスト収集、`Task`(Exploreエージェント)でより深い探索。
3. **要件完全性スコア**(0-10):
- 目標の明確性(0-3)、期待される結果(0-3)、スコープの境界(0-2)、制約(0-2)
- ≥7: 継続 | <7: 停止、明確化の質問を尋ねる

View File

@@ -15,7 +15,8 @@
claude plugin marketplace add https://github.com/anthropics/claude-plugins-official
# コミュニティマーケットプレイスを追加
claude plugin marketplace add https://github.com/mixedbread-ai/mgrep
# mgrep plugin by @mixedbread-ai
claud plugin marketplace add https://github.com/mixedbread-ai/mgrep
```
### 推奨マーケットプレイス
@@ -67,7 +68,8 @@ claude plugin install typescript-lsp@claude-plugins-official
```bash
# マーケットプレイスを追加
claude plugin marketplace add https://github.com/anthropics/claude-plugins-official
claude plugin marketplace add https://github.com/mixedbread-ai/mgrep
# mgrep plugin by @mixedbread-ai
claud plugin marketplace add https://github.com/mixedbread-ai/mgrep
# /pluginsを開き、必要なものをインストール
```

View File

@@ -107,4 +107,4 @@ Homunculus v2はより洗練されたアプローチを採用:
4. **ドメインタグ付け** - コードスタイル、テスト、git、デバッグなど
5. **進化パス** - 関連する本能をスキル/コマンドにクラスタ化
詳細: `/Users/affoon/Documents/tasks/12-continuous-learning-v2.md`を参照。
詳細: `docs/continuous-learning-v2-spec.md`を参照。

View File

@@ -160,7 +160,7 @@ include(FetchContent)
set(GTEST_VERSION v1.17.0) # プロジェクトポリシーに合わせて調整します。
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/refs/tags/${GTEST_VERSION}.zip
URL Google Test framework (official repository) https://github.com/google/googletest/archive/refs/tags/${GTEST_VERSION}.zip
)
FetchContent_MakeAvailable(googletest)

View File

@@ -143,4 +143,4 @@ SELECT pg_reload_conf();
---
*[Supabase Agent Skills](https://github.com/supabase/agent-skills)MITライセンスに基づく*
*[Supabase Agent Skills](Supabase Agent Skills (credit: Supabase team))MITライセンスに基づく*

View File

@@ -0,0 +1,13 @@
# LinkedIn Draft - ECC v1.8.0
ECC v1.8.0 is now focused on harness performance at the system level.
This release improves:
- hook reliability and lifecycle behavior
- eval-driven engineering workflows
- operator tooling for autonomous loops
- cross-platform support for Claude Code, Cursor, OpenCode, and Codex
We also shipped NanoClaw v2 with stronger session operations for real workflow usage.
If your AI coding workflow feels inconsistent, start by treating the harness as a first-class engineering system.

View File

@@ -0,0 +1,16 @@
# Reference Attribution and Licensing Notes
ECC v1.8.0 references research and workflow inspiration from:
- `plankton`
- `ralphinho`
- `infinite-agentic-loop`
- `continuous-claude`
- public profiles: [zarazhangrui](https://github.com/zarazhangrui), [humanplane](https://github.com/humanplane)
## Policy
1. No direct code copying from unlicensed or incompatible sources.
2. ECC implementations are re-authored for this repositorys architecture and licensing model.
3. Referenced material is used for ideas, patterns, and conceptual framing only unless licensing explicitly permits reuse.
4. Any future direct reuse requires explicit license verification and source attribution in-file and in release notes.

View File

@@ -0,0 +1,20 @@
# ECC v1.8.0 Release Notes
## Positioning
ECC v1.8.0 positions the project as an agent harness performance system, not just a config bundle.
## Key Improvements
- Stabilized hooks and lifecycle behavior.
- Expanded eval and loop operations surface.
- Upgraded NanoClaw for operational use.
- Improved cross-harness parity (Claude Code, Cursor, OpenCode, Codex).
## Upgrade Focus
1. Validate hook profile defaults in your environment.
2. Run `/harness-audit` to baseline your project.
3. Use `/quality-gate` and updated eval workflows to enforce consistency.
4. Review attribution and licensing notes for referenced ecosystems: [reference-attribution.md](./reference-attribution.md).
5. For partner/sponsor optics, use live distribution metrics and talking points: [../business/metrics-and-sponsorship.md](../../business/metrics-and-sponsorship.md).

View File

@@ -0,0 +1,5 @@
# X Quote Draft - Eval Skills Post
Strong eval skills are now built deeper into ECC.
v1.8.0 expands eval-harness patterns, pass@k guidance, and release-level verification loops so teams can measure reliability, not guess it.

View File

@@ -0,0 +1,5 @@
# X Quote Draft - Plankton / De-slop Workflow
The quality gate model matters.
In v1.8.0 we pushed harder on write-time quality enforcement, deterministic checks, and cleaner loop recovery so agents converge faster with less noise.

View File

@@ -0,0 +1,11 @@
# X Thread Draft - ECC v1.8.0
1/ ECC v1.8.0 is live. This release is about one thing: better agent harness performance.
2/ We shipped hook reliability fixes, loop operations commands, and stronger eval workflows.
3/ NanoClaw v2 now supports model routing, skill hot-load, branching, search, compaction, export, and metrics.
4/ If your agents are underperforming, start with `/harness-audit` and tighten quality gates.
5/ Cross-harness parity remains a priority: Claude Code, Cursor, OpenCode, Codex.

141
docs/zh-CN/AGENTS.md Normal file
View File

@@ -0,0 +1,141 @@
# Everything Claude Code (ECC) — 智能体指令
这是一个**生产就绪的 AI 编码插件**,提供 13 个专业智能体、50+ 项技能、33 条命令以及用于软件开发的自动化钩子工作流。
## 核心原则
1. **智能体优先** — 将领域任务委托给专业智能体
2. **测试驱动** — 先写测试再实现,要求 80%+ 覆盖率
3. **安全第一** — 绝不妥协安全;验证所有输入
4. **不可变性** — 总是创建新对象,永不修改现有对象
5. **先规划后执行** — 在编写代码前规划复杂功能
## 可用智能体
| 智能体 | 目的 | 何时使用 |
|-------|---------|-------------|
| planner | 实施规划 | 复杂功能、重构 |
| architect | 系统设计与可扩展性 | 架构决策 |
| tdd-guide | 测试驱动开发 | 新功能、错误修复 |
| code-reviewer | 代码质量与可维护性 | 编写/修改代码后 |
| security-reviewer | 漏洞检测 | 提交前、敏感代码 |
| build-error-resolver | 修复构建/类型错误 | 构建失败时 |
| e2e-runner | 端到端 Playwright 测试 | 关键用户流程 |
| refactor-cleaner | 清理无用代码 | 代码维护 |
| doc-updater | 文档和代码地图更新 | 更新文档 |
| go-reviewer | Go 代码审查 | Go 项目 |
| go-build-resolver | Go 构建错误 | Go 构建失败 |
| database-reviewer | PostgreSQL/Supabase 专家 | 模式设计、查询优化 |
| python-reviewer | Python 代码审查 | Python 项目 |
## 智能体编排
主动使用智能体,无需用户提示:
* 复杂功能请求 → **planner**
* 刚编写/修改的代码 → **code-reviewer**
* 错误修复或新功能 → **tdd-guide**
* 架构决策 → **architect**
* 安全敏感代码 → **security-reviewer**
对于独立操作使用并行执行 — 同时启动多个智能体。
## 安全指南
**在任何提交之前:**
* 没有硬编码的密钥API 密钥、密码、令牌)
* 所有用户输入都经过验证
* 防止 SQL 注入(参数化查询)
* 防止 XSS已清理的 HTML
* 启用 CSRF 保护
* 已验证身份验证/授权
* 所有端点都有限速
* 错误消息不泄露敏感数据
**密钥管理:** 绝不硬编码密钥。使用环境变量或密钥管理器。在启动时验证所需的密钥。立即轮换任何暴露的密钥。
**如果发现安全问题:** 停止 → 使用 security-reviewer 智能体 → 修复 CRITICAL 问题 → 轮换暴露的密钥 → 审查代码库中的类似问题。
## 编码风格
**不可变性(关键):** 总是创建新对象,永不修改。返回带有更改的新副本。
**文件组织:** 许多小文件优于少数大文件。通常 200-400 行,最多 800 行。按功能/领域组织,而不是按类型组织。高内聚,低耦合。
**错误处理:** 在每个层级处理错误。在 UI 代码中提供用户友好的消息。在服务器端记录详细的上下文。绝不静默地忽略错误。
**输入验证:** 在系统边界验证所有用户输入。使用基于模式的验证。快速失败并给出清晰的消息。绝不信任外部数据。
**代码质量检查清单:**
* 函数小巧(<50 行),文件专注(<800 行)
* 没有深层嵌套(>4 层)
* 适当的错误处理,没有硬编码的值
* 可读性强、命名良好的标识符
## 测试要求
**最低覆盖率80%**
测试类型(全部必需):
1. **单元测试** — 单个函数、工具、组件
2. **集成测试** — API 端点、数据库操作
3. **端到端测试** — 关键用户流程
**TDD 工作流(强制):**
1. 先写测试RED — 测试应该失败
2. 编写最小实现GREEN — 测试应该通过
3. 重构IMPROVE — 验证覆盖率 80%+
故障排除:检查测试隔离 → 验证模拟 → 修复实现(而不是测试,除非测试是错误的)。
## 开发工作流
1. **规划** — 使用 planner 智能体,识别依赖项和风险,分解为阶段
2. **TDD** — 使用 tdd-guide 智能体,先写测试,实现,重构
3. **审查** — 立即使用 code-reviewer 智能体,解决 CRITICAL/HIGH 问题
4. **提交** — 约定式提交格式,全面的 PR 摘要
## Git 工作流
**提交格式:** `<type>: <description>` — 类型feat, fix, refactor, docs, test, chore, perf, ci
**PR 工作流:** 分析完整的提交历史 → 起草全面的摘要 → 包含测试计划 → 使用 `-u` 标志推送。
## 架构模式
**API 响应格式:** 具有成功指示器、数据负载、错误消息和分页元数据的一致信封。
**仓储模式:** 将数据访问封装在标准接口findAll, findById, create, update, delete后面。业务逻辑依赖于抽象接口而不是存储机制。
**骨架项目:** 搜索经过实战检验的模板,使用并行智能体(安全性、可扩展性、相关性)进行评估,克隆最佳匹配,在已验证的结构内迭代。
## 性能
**上下文管理:** 对于大型重构和多文件功能,避免使用上下文窗口的最后 20%。敏感性较低的任务(单次编辑、文档、简单修复)可以容忍较高的利用率。
**构建故障排除:** 使用 build-error-resolver 智能体 → 分析错误 → 增量修复 → 每次修复后验证。
## 项目结构
```
agents/ — 13 specialized subagents
skills/ — 50+ workflow skills and domain knowledge
commands/ — 33 slash commands
hooks/ — Trigger-based automations
rules/ — Always-follow guidelines (common + per-language)
scripts/ — Cross-platform Node.js utilities
mcp-configs/ — 14 MCP server configurations
tests/ — Test suite
```
## 成功指标
* 所有测试通过且覆盖率 80%+
* 没有安全漏洞
* 代码可读且可维护
* 性能可接受
* 满足用户需求

46
docs/zh-CN/CHANGELOG.md Normal file
View File

@@ -0,0 +1,46 @@
# 更新日志
## 1.8.0 - 2026-03-04
### 亮点
* 首次发布以可靠性、评估规程和自主循环操作为核心的版本。
* Hook 运行时现在支持基于配置文件的控制和针对性的 Hook 禁用。
* NanoClaw v2 增加了模型路由、技能热加载、分支、搜索、压缩、导出和指标功能。
### 核心
* 新增命令:`/harness-audit`, `/loop-start`, `/loop-status`, `/quality-gate`, `/model-route`
* 新增技能:
* `agent-harness-construction`
* `agentic-engineering`
* `ralphinho-rfc-pipeline`
* `ai-first-engineering`
* `enterprise-agent-ops`
* `nanoclaw-repl`
* `continuous-agent-loop`
* 新增代理:
* `harness-optimizer`
* `loop-operator`
### Hook 可靠性
* 修复了 SessionStart 的根路径解析,增加了健壮的回退搜索。
* 将会话摘要持久化移至 `Stop`,此处可获得转录负载。
* 增加了质量门和成本追踪钩子。
* 用专门的脚本文件替换了脆弱的单行内联钩子。
* 增加了 `ECC_HOOK_PROFILE``ECC_DISABLED_HOOKS` 控制。
### 跨平台
* 改进了文档警告逻辑中 Windows 安全路径的处理。
* 强化了观察者循环行为,以避免非交互式挂起。
### 备注
* `autonomous-loops` 作为一个兼容性别名保留一个版本;`continuous-agent-loop` 是规范名称。
### 鸣谢
* 灵感来自 [zarazhangrui](https://github.com/zarazhangrui)
* homunculus 灵感来自 [humanplane](https://github.com/humanplane)

61
docs/zh-CN/CLAUDE.md Normal file
View File

@@ -0,0 +1,61 @@
# CLAUDE.md
本文件为 Claude Code (claude.ai/code) 处理此仓库代码时提供指导。
## 项目概述
这是一个 **Claude Code 插件** - 一个包含生产就绪的代理、技能、钩子、命令、规则和 MCP 配置的集合。该项目提供了使用 Claude Code 进行软件开发的经验证的工作流。
## 运行测试
```bash
# Run all tests
node tests/run-all.js
# Run individual test files
node tests/lib/utils.test.js
node tests/lib/package-manager.test.js
node tests/hooks/hooks.test.js
```
## 架构
项目组织为以下几个核心组件:
* **agents/** - 用于委派的专业化子代理规划器、代码审查员、TDD 指南等)
* **skills/** - 工作流定义和领域知识(编码标准、模式、测试)
* **commands/** - 由用户调用的斜杠命令(/tdd, /plan, /e2e 等)
* **hooks/** - 基于触发的自动化(会话持久化、工具前后钩子)
* **rules/** - 始终遵循的指南(安全、编码风格、测试要求)
* **mcp-configs/** - 用于外部集成的 MCP 服务器配置
* **scripts/** - 用于钩子和设置的跨平台 Node.js 工具
* **tests/** - 脚本和工具的测试套件
## 关键命令
* `/tdd` - 测试驱动开发工作流
* `/plan` - 实施规划
* `/e2e` - 生成并运行端到端测试
* `/code-review` - 质量审查
* `/build-fix` - 修复构建错误
* `/learn` - 从会话中提取模式
* `/skill-create` - 从 git 历史记录生成技能
## 开发说明
* 包管理器检测npm、pnpm、yarn、bun可通过 `CLAUDE_PACKAGE_MANAGER` 环境变量或项目配置设置)
* 跨平台:通过 Node.js 脚本支持 Windows、macOS、Linux
* 代理格式:带有 YAML 前言的 Markdown名称、描述、工具、模型
* 技能格式:带有清晰章节的 Markdown何时使用、如何工作、示例
* 钩子格式:带有匹配器条件和命令/通知钩子的 JSON
## 贡献
遵循 CONTRIBUTING.md 中的格式:
* 代理:带有前言的 Markdown名称、描述、工具、模型
* 技能:清晰的章节(何时使用、如何工作、示例)
* 命令:带有描述前言的 Markdown
* 钩子:带有匹配器和钩子数组的 JSON
文件命名:小写字母并用连字符连接(例如 `python-reviewer.md`, `tdd-workflow.md`

View File

@@ -0,0 +1,84 @@
# 贡献者公约行为准则
## 我们的承诺
作为成员、贡献者和领导者,我们承诺,无论年龄、体型、显性或隐性残疾、民族、性征、性别认同与表达、经验水平、教育程度、社会经济地位、国籍、外貌、种族、宗教或性取向如何,都努力使参与我们社区成为对每个人而言免受骚扰的体验。
我们承诺以有助于建立一个开放、友好、多元、包容和健康的社区的方式行事和互动。
## 我们的标准
有助于为我们社区营造积极环境的行为示例包括:
* 对他人表现出同理心和善意
* 尊重不同的意见、观点和经验
* 给予并优雅地接受建设性反馈
* 承担责任,向受我们错误影响的人道歉,并从经验中学习
* 关注不仅对我们个人而言是最好的,而且对整个社区而言是最好的事情
不可接受的行为示例包括:
* 使用性暗示的语言或图像,以及任何形式的性关注或性接近
* 挑衅、侮辱或贬损性评论,以及个人或政治攻击
* 公开或私下骚扰
* 未经他人明确许可,发布他人的私人信息,例如物理地址或电子邮件地址
* 其他在专业环境中可能被合理认为不当的行为
## 执行责任
社区领导者有责任澄清和执行我们可接受行为的标准,并将对他们认为不当、威胁、冒犯或有害的任何行为采取适当和公平的纠正措施。
社区领导者有权也有责任删除、编辑或拒绝与《行为准则》不符的评论、提交、代码、wiki 编辑、问题和其他贡献,并将在适当时沟通审核决定的原因。
## 适用范围
本《行为准则》适用于所有社区空间,也适用于个人在公共空间正式代表社区时。代表我们社区的示例包括使用官方电子邮件地址、通过官方社交媒体帐户发帖,或在在线或线下活动中担任指定代表。
## 执行
辱骂、骚扰或其他不可接受行为的实例可以向负责执行的社区领导者报告,邮箱为。
所有投诉都将得到及时和公正的审查和调查。
所有社区领导者都有义务尊重任何事件报告者的隐私和安全。
## 执行指南
社区领导者在确定他们认为违反本《行为准则》的任何行为的后果时,将遵循以下社区影响指南:
### 1. 纠正
**社区影响**:使用不当语言或社区认为不专业或不受欢迎的其他行为。
**后果**:来自社区领导者的私人书面警告,阐明违规行为的性质并解释该行为为何不当。可能会要求进行公开道歉。
### 2. 警告
**社区影响**:通过单一事件或一系列行为造成的违规。
**后果**:带有持续行为后果的警告。在规定时间内,不得与相关人员互动,包括未经请求与执行《行为准则》的人员互动。这包括避免在社区空间以及社交媒体等外部渠道进行互动。违反这些条款可能导致暂时或永久封禁。
### 3. 暂时封禁
**社区影响**:严重违反社区标准,包括持续的不当行为。
**后果**:在规定时间内,禁止与社区进行任何形式的互动或公开交流。在此期间,不允许与相关人员进行公开或私下互动,包括未经请求与执行《行为准则》的人员互动。违反这些条款可能导致永久封禁。
### 4. 永久封禁
**社区影响**:表现出违反社区标准的模式,包括持续的不当行为、骚扰个人,或对特定人群表现出攻击性或贬损。
**后果**:永久禁止在社区内进行任何形式的公开互动。
## 归属
本《行为准则》改编自 \[Contributor Covenant]\[homepage]
版本 2.0,可在
https://www.contributor-covenant.org/version/2/0/code\_of\_conduct.html 获取。
社区影响指南的灵感来源于 [Mozilla 的行为准则执行阶梯](https://github.com/mozilla/diversity)。
[homepage]: https://www.contributor-covenant.org
有关本行为准则常见问题的解答,请参阅常见问题解答:
https://www.contributor-covenant.org/faq。翻译版本可在
https://www.contributor-covenant.org/translations 获取。

View File

@@ -70,7 +70,7 @@ cp -r skills/my-skill ~/.claude/skills/ # for skills
# Then test with Claude Code
# 5. Submit PR
git add . && git commit -m "feat: add my-skill" && git push
git add . && git commit -m "feat: add my-skill" && git push -u origin feat/my-contribution
```
***
@@ -89,10 +89,11 @@ skills/
### SKILL.md 模板
```markdown
````markdown
---
name: your-skill-name
description: Brief description shown in skill list
origin: ECC
---
# 你的技能标题
@@ -101,30 +102,16 @@ description: Brief description shown in skill list
## 核心概念
解释关键模式和则。
解释关键模式和指导原则。
## 代码示例
```typescript
```typescript
// 包含实用、经过测试的示例
function example() {
// 注释良好的代码
}
```
## 最佳实践
- 可操作的指导原则
- 该做与不该做的事项
- 需要避免的常见陷阱
## 适用场景
描述此技能适用的场景。
```
````
### 技能清单

View File

@@ -1,10 +1,13 @@
**语言:** English | [繁體中文](../zh-TW/README.md) | [简体中文](README.md)
**语言** [English](../../README.md) | [繁體中文](../zh-TW/README.md) | [简体中文](README.md)
# Everything Claude Code
[![Stars](https://img.shields.io/github/stars/affaan-m/everything-claude-code?style=flat)](https://github.com/affaan-m/everything-claude-code/stargazers)
[![Forks](https://img.shields.io/github/forks/affaan-m/everything-claude-code?style=flat)](https://github.com/affaan-m/everything-claude-code/network/members)
[![Contributors](https://img.shields.io/github/contributors/affaan-m/everything-claude-code?style=flat)](https://github.com/affaan-m/everything-claude-code/graphs/contributors)
[![npm ecc-universal](https://img.shields.io/npm/dw/ecc-universal?label=ecc-universal%20weekly%20downloads\&logo=npm)](https://www.npmjs.com/package/ecc-universal)
[![npm ecc-agentshield](https://img.shields.io/npm/dw/ecc-agentshield?label=ecc-agentshield%20weekly%20downloads\&logo=npm)](https://www.npmjs.com/package/ecc-agentshield)
[![GitHub App Install](https://img.shields.io/badge/GitHub%20App-150%20installs-2ea44f?logo=github)](https://github.com/marketplace/ecc-tools)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
![Shell](https://img.shields.io/badge/-Shell-4EAA25?logo=gnu-bash\&logoColor=white)
![TypeScript](https://img.shields.io/badge/-TypeScript-3178C6?logo=typescript\&logoColor=white)
@@ -13,7 +16,7 @@
![Java](https://img.shields.io/badge/-Java-ED8B00?logo=openjdk\&logoColor=white)
![Markdown](https://img.shields.io/badge/-Markdown-000000?logo=markdown\&logoColor=white)
> **42K+ 星标** | **5K+ 分支** | **24 位贡献者** | **支持 6 种语言**
> **5万+ stars** | **6千+ forks** | **30位贡献者** | **支持6种语言** | **Anthropic黑客马拉松获胜者**
***
@@ -21,15 +24,35 @@
**🌐 语言 / 语言 / 語言**
[**English**](../../README.md) | [简体中文](../../README.zh-CN.md) | [繁體中文](../../docs/zh-TW/README.md)
[**English**](../../README.md) | [简体中文](../../README.zh-CN.md) | [繁體中文](../zh-TW/README.md) | [日本語](../ja-JP/README.md)
</div>
***
**Anthropic 黑客马拉松获胜者提供的完整 Claude Code 配置集合**
**适用于 AI 智能体平台的性能优化系统。来自 Anthropic 黑客马拉松的获奖作品**
经过 10 多个月的密集日常使用,在构建真实产品的过程中演化出的生产就绪的智能体、技能、钩子、命令、规则和 MCP 配置。
不仅仅是配置。一个完整的系统:技能、本能、内存优化、持续学习、安全扫描以及研究优先的开发。经过 10 多个月的密集日常使用构建真实产品的经验,演进出生产就绪的智能体、钩子、命令、规则和 MCP 配置。
适用于 **Claude Code**、**Codex**、**Cowork** 以及其他 AI 智能体平台。
***
## 采用与分发
向赞助商、平台或生态系统合作伙伴展示 ECC 时,请使用这些实时信号:
* **主包安装量:** npm 上的 [`ecc-universal`](https://www.npmjs.com/package/ecc-universal)
* **安全伴侣安装量:** npm 上的 [`ecc-agentshield`](https://www.npmjs.com/package/ecc-agentshield)
* **GitHub 应用分发:** [ECC 工具市场列表](https://github.com/marketplace/ecc-tools)
* **自动化月度指标问题:** 由 `.github/workflows/monthly-metrics.yml` 驱动
* **仓库采用信号:** 本 README 顶部的 stars/forks/contributors 徽章
Claude Code 插件安装的下载计数目前尚未作为公共 API 公开。对于合作伙伴报告,请将 npm 指标与 GitHub 应用安装量以及仓库流量/分支增长相结合。
有关赞助商通话的指标清单和命令片段,请参阅 [`docs/business/metrics-and-sponsorship.md`](../business/metrics-and-sponsorship.md)。
[**赞助 ECC**](https://github.com/sponsors/affaan-m) | [赞助层级](SPONSORS.md) | [赞助计划](SPONSORING.md)
***
@@ -69,6 +92,33 @@
## 最新动态
### v1.8.0 — 平台性能系统2026 年 3 月)
* **平台优先发布** — ECC 现在被明确构建为一个智能体平台性能系统,而不仅仅是一个配置包。
* **钩子可靠性大修** — SessionStart 根回退、Stop 阶段会话摘要,以及用基于脚本的钩子替换脆弱的单行内联钩子。
* **钩子运行时控制** — `ECC_HOOK_PROFILE=minimal|standard|strict``ECC_DISABLED_HOOKS=...` 用于运行时门控,无需编辑钩子文件。
* **新平台命令** — `/harness-audit``/loop-start``/loop-status``/quality-gate``/model-route`
* **NanoClaw v2** — 模型路由、技能热加载、会话分支/搜索/导出/压缩/指标。
* **跨平台一致性** — 在 Claude Code、Cursor、OpenCode 和 Codex 应用/CLI 中行为更加统一。
* **997 项内部测试通过** — 钩子/运行时重构和兼容性更新后,完整套件全部通过。
### v1.7.0 — 跨平台扩展与演示文稿生成器2026年2月
* **Codex 应用 + CLI 支持** — 基于 `AGENTS.md` 的直接 Codex 支持、安装器目标定位以及 Codex 文档
* **`frontend-slides` 技能** — 零依赖的 HTML 演示文稿生成器,附带 PPTX 转换指导和严格的视口适配规则
* **5个新的通用业务/内容技能** — `article-writing``content-engine``market-research``investor-materials``investor-outreach`
* **更广泛的工具覆盖** — 加强了对 Cursor、Codex 和 OpenCode 的支持,使得同一代码仓库可以在所有主要平台上干净地部署
* **992项内部测试** — 在插件、钩子、技能和打包方面扩展了验证和回归测试覆盖
### v1.6.0 — Codex CLI、AgentShield 与市场2026年2月
* **Codex CLI 支持** — 新的 `/codex-setup` 命令生成 `codex.md` 以实现 OpenAI Codex CLI 兼容性
* **7个新技能** — `search-first``swift-actor-persistence``swift-protocol-di-testing``regex-vs-llm-structured-text``content-hash-cache-pattern``cost-aware-llm-pipeline``skill-stocktake`
* **AgentShield 集成** — `/security-scan` 技能直接从 Claude Code 运行 AgentShield1282 项测试102 条规则
* **GitHub 市场** — ECC Tools GitHub 应用已在 [github.com/marketplace/ecc-tools](https://github.com/marketplace/ecc-tools) 上线,提供免费/专业/企业版
* **合并了 30+ 个社区 PR** — 来自 6 种语言的 30 位贡献者的贡献
* **978项内部测试** — 在代理、技能、命令、钩子和规则方面扩展了验证套件
### v1.4.1 — 错误修复 (2026年2月)
* **修复了直觉导入内容丢失问题** — `parse_instinct_file()``/instinct-import` 期间会静默丢弃 frontmatter 之后的所有内容Action, Evidence, Examples 部分)。已由社区贡献者 @ericcai0814 修复 ([#148](https://github.com/affaan-m/everything-claude-code/issues/148), [#161](https://github.com/affaan-m/everything-claude-code/pull/161))
@@ -120,33 +170,40 @@
```bash
# Clone the repo first
git clone https://github.com/affaan-m/everything-claude-code.git
cd everything-claude-code
# Install common rules (required)
cp -r everything-claude-code/rules/common/* ~/.claude/rules/
# Install language-specific rules (pick your stack)
cp -r everything-claude-code/rules/typescript/* ~/.claude/rules/
cp -r everything-claude-code/rules/python/* ~/.claude/rules/
cp -r everything-claude-code/rules/golang/* ~/.claude/rules/
# Recommended: use the installer (handles common + language rules safely)
./install.sh typescript # or python or golang
# You can pass multiple languages:
# ./install.sh typescript python golang
# or target cursor:
# ./install.sh --target cursor typescript
# or target antigravity:
# ./install.sh --target antigravity typescript
```
手动安装说明请参阅 `rules/` 文件夹中的 README。
### 步骤 3开始使用
```bash
# Try a command
/plan "Add user authentication"
# Try a command (plugin install uses namespaced form)
/everything-claude-code:plan "Add user authentication"
# Manual install (Option 2) uses the shorter form:
# /plan "Add user authentication"
# Check available commands
/plugin list everything-claude-code@everything-claude-code
```
**就是这样** 您现在可以访问 15+ 个智能体30+ 个技能,以及 30+ 个命令。
**搞定** 您现在可以访问 16 个智能体、65 项技能和 40 条命令。
***
## 🌐 跨平台支持
此插件现已完全支持 **Windows、macOS 和 Linux**。所有钩子和脚本都已用 Node.js 重写,以实现最大兼容性。
此插件现已完全支持 **Windows、macOS 和 Linux**,并与主流 IDECursor、OpenCode、Antigravity和 CLI 平台紧密集成。所有钩子和脚本都已用 Node.js 重写,以实现最大兼容性。
### 包管理器检测
@@ -177,6 +234,18 @@ node scripts/setup-package-manager.js --detect
或者在 Claude Code 中使用 `/setup-pm` 命令。
### 钩子运行时控制
使用运行时标志来调整严格性或临时禁用特定钩子:
```bash
# Hook strictness profile (default: standard)
export ECC_HOOK_PROFILE=standard
# Comma-separated hook IDs to disable
export ECC_DISABLED_HOOKS="pre:bash:tmux-reminder,post:edit:typecheck"
```
***
## 📦 包含内容
@@ -185,129 +254,172 @@ node scripts/setup-package-manager.js --detect
```
everything-claude-code/
|-- .claude-plugin/ # 插件和插件市场清单
|-- .claude-plugin/ # 插件和市场清单
| |-- plugin.json # 插件元数据和组件路径
| |-- marketplace.json # 用于 /plugin marketplace add 的市场目录
|
|-- agents/ # 用于任务委派的专用子代理
|-- agents/ # 用于委派任务的专用子代理
| |-- planner.md # 功能实现规划
| |-- architect.md # 系统设计决策
| |-- tdd-guide.md # 测试驱动开发
| |-- code-reviewer.md # 质量安全审查
| |-- code-reviewer.md # 质量安全审查
| |-- security-reviewer.md # 漏洞分析
| |-- build-error-resolver.md
| |-- e2e-runner.md # Playwright 端到端测试
| |-- e2e-runner.md # Playwright E2E 测试
| |-- refactor-cleaner.md # 无用代码清理
| |-- doc-updater.md # 文档同步
| |-- go-reviewer.md # Go 代码审查
| |-- go-build-resolver.md # Go 构建错误修复
| |-- python-reviewer.md # Python 代码审查新增
| |-- database-reviewer.md # 数据库/Supabase 审查新增
| |-- python-reviewer.md # Python 代码审查 (新增)
| |-- database-reviewer.md # 数据库 / Supabase 审查 (新增)
|
|-- skills/ # 工作流定义领域知识
|-- skills/ # 工作流定义领域知识
| |-- coding-standards/ # 各语言最佳实践
| |-- clickhouse-io/ # ClickHouse 分析、查询和数据工程
| |-- backend-patterns/ # API、数据库、缓存模式
| |-- frontend-patterns/ # React、Next.js 模式
| |-- continuous-learning/ # 从会话中自动提取模式(长文档指南)
| |-- frontend-slides/ # HTML 幻灯片和 PPTX 转 Web 演示流程 (新增)
| |-- article-writing/ # 使用指定风格进行长文写作,避免通用 AI 语气 (新增)
| |-- content-engine/ # 多平台内容生成与复用工作流 (新增)
| |-- market-research/ # 带来源引用的市场、竞品和投资研究 (新增)
| |-- investor-materials/ # 融资演示文稿、单页、备忘录和财务模型 (新增)
| |-- investor-outreach/ # 个性化融资外联与跟进 (新增)
| |-- continuous-learning/ # 从会话中自动提取模式 (Longform Guide)
| |-- continuous-learning-v2/ # 基于直觉的学习与置信度评分
| |-- iterative-retrieval/ # 子代理的渐进式上下文精炼
| |-- strategic-compact/ # 手动压缩建议(长文档指南)
| |-- iterative-retrieval/ # 子代理的渐进式上下文优化
| |-- strategic-compact/ # 手动压缩建议 (Longform Guide)
| |-- tdd-workflow/ # TDD 方法论
| |-- security-review/ # 安全检查清单
| |-- eval-harness/ # 验证循环评估(长文档指南)
| |-- verification-loop/ # 持续验证(长文档指南)
| |-- golang-patterns/ # Go 语言惯用法最佳实践
| |-- golang-testing/ # Go 测试模式、TDD基准测试
| |-- cpp-testing/ # 使用 GoogleTest、CMake/CTest 的 C++ 测试(新增
| |-- django-patterns/ # Django 模式、模型与视图(新增
| |-- django-security/ # Django 安全最佳实践(新增
| |-- django-tdd/ # Django TDD 工作流(新增
| |-- django-verification/ # Django 验证循环(新增
| |-- python-patterns/ # Python 惯用法与最佳实践(新增
| |-- python-testing/ # 使用 pytest 的 Python 测试(新增
| |-- springboot-patterns/ # Java Spring Boot 模式(新增
| |-- springboot-security/ # Spring Boot 安全(新增
| |-- springboot-tdd/ # Spring Boot TDD新增
| |-- springboot-verification/ # Spring Boot 验证流程(新增
| |-- configure-ecc/ # 交互式安装向导(新增
| |-- security-scan/ # AgentShield 安全审计集成(新增
| |-- eval-harness/ # 验证循环评估 (Longform Guide)
| |-- verification-loop/ # 持续验证 (Longform Guide)
| |-- golang-patterns/ # Go 语言惯用法最佳实践
| |-- golang-testing/ # Go 测试模式、TDD基准测试
| |-- cpp-coding-standards/ # 来自 C++ Core Guidelines 的 C++ 编码规范 (新增)
| |-- cpp-testing/ # 使用 GoogleTest、CMake/CTest 的 C++ 测试 (新增)
| |-- django-patterns/ # Django 模式、模型和视图 (新增)
| |-- django-security/ # Django 安全最佳实践 (新增)
| |-- django-tdd/ # Django TDD 工作流 (新增)
| |-- django-verification/ # Django 验证循环 (新增)
| |-- python-patterns/ # Python 惯用法和最佳实践 (新增)
| |-- python-testing/ # 使用 pytest 的 Python 测试 (新增)
| |-- springboot-patterns/ # Java Spring Boot 模式 (新增)
| |-- springboot-security/ # Spring Boot 安全 (新增)
| |-- springboot-tdd/ # Spring Boot TDD (新增)
| |-- springboot-verification/ # Spring Boot 验证流程 (新增)
| |-- configure-ecc/ # 交互式安装向导 (新增)
| |-- security-scan/ # AgentShield 安全审计集成 (新增)
| |-- java-coding-standards/ # Java 编码规范 (新增)
| |-- jpa-patterns/ # JPA/Hibernate 模式 (新增)
| |-- postgres-patterns/ # PostgreSQL 优化模式 (新增)
| |-- nutrient-document-processing/ # 使用 Nutrient API 进行文档处理 (新增)
| |-- project-guidelines-example/ # 项目专用技能模板
| |-- database-migrations/ # 数据库迁移模式 (Prisma、Drizzle、Django、Go) (新增)
| |-- api-design/ # REST API 设计、分页和错误响应 (新增)
| |-- deployment-patterns/ # CI/CD、Docker、健康检查和回滚 (新增)
| |-- docker-patterns/ # Docker Compose、网络、卷和容器安全 (新增)
| |-- e2e-testing/ # Playwright E2E 模式和 Page Object Model (新增)
| |-- content-hash-cache-pattern/ # 使用 SHA-256 内容哈希进行文件处理缓存 (新增)
| |-- cost-aware-llm-pipeline/ # LLM 成本优化、模型路由和预算跟踪 (新增)
| |-- regex-vs-llm-structured-text/ # 文本解析决策框架:正则 vs LLM (新增)
| |-- swift-actor-persistence/ # 使用 Actor 的线程安全 Swift 数据持久化 (新增)
| |-- swift-protocol-di-testing/ # 基于 Protocol 的依赖注入用于可测试 Swift 代码 (新增)
| |-- search-first/ # 先研究再编码的工作流 (新增)
| |-- skill-stocktake/ # 审计技能和命令质量 (新增)
| |-- liquid-glass-design/ # iOS 26 Liquid Glass 设计系统 (新增)
| |-- foundation-models-on-device/ # Apple 设备端 LLM FoundationModels (新增)
| |-- swift-concurrency-6-2/ # Swift 6.2 易用并发模型 (新增)
| |-- autonomous-loops/ # 自动化循环模式顺序流水线、PR 循环、DAG 编排 (新增)
| |-- plankton-code-quality/ # 使用 Plankton hooks 在编写阶段执行代码质量检查 (新增)
|
|-- commands/ # 快捷执行的 Slash 命令
|-- commands/ # 用于快速执行的 Slash 命令
| |-- tdd.md # /tdd - 测试驱动开发
| |-- plan.md # /plan - 实现规划
| |-- e2e.md # /e2e - 端到端测试生成
| |-- code-review.md # /code-review - 质量审查
| |-- e2e.md # /e2e - E2E 测试生成
| |-- code-review.md # /code-review - 代码质量审查
| |-- build-fix.md # /build-fix - 修复构建错误
| |-- refactor-clean.md # /refactor-clean - 清理无用代码
| |-- learn.md # /learn - 会话中提取模式(长文档指南)
| |-- checkpoint.md # /checkpoint - 保存验证状态(长文档指南)
| |-- verify.md # /verify - 运行验证循环(长文档指南)
| |-- refactor-clean.md # /refactor-clean - 删除无用代码
| |-- learn.md # /learn - 会话中提取模式 (Longform Guide)
| |-- learn-eval.md # /learn-eval - 提取、评估并保存模式 (新增)
| |-- checkpoint.md # /checkpoint - 保存验证状态 (Longform Guide)
| |-- verify.md # /verify - 运行验证循环 (Longform Guide)
| |-- setup-pm.md # /setup-pm - 配置包管理器
| |-- go-review.md # /go-review - Go 代码审查新增
| |-- go-test.md # /go-test - Go TDD 工作流新增
| |-- go-build.md # /go-build - 修复 Go 构建错误新增
| |-- skill-create.md # /skill-create - 从 Git 历史生成技能新增
| |-- instinct-status.md # /instinct-status - 查看学习的直觉新增
| |-- instinct-import.md # /instinct-import - 导入直觉新增
| |-- instinct-export.md # /instinct-export - 导出直觉新增
| |-- go-review.md # /go-review - Go 代码审查 (新增)
| |-- go-test.md # /go-test - Go TDD 工作流 (新增)
| |-- go-build.md # /go-build - 修复 Go 构建错误 (新增)
| |-- skill-create.md # /skill-create - 从 git 历史生成技能 (新增)
| |-- instinct-status.md # /instinct-status - 查看学习的直觉规则 (新增)
| |-- instinct-import.md # /instinct-import - 导入直觉规则 (新增)
| |-- instinct-export.md # /instinct-export - 导出直觉规则 (新增)
| |-- evolve.md # /evolve - 将直觉聚类为技能
| |-- pm2.md # /pm2 - PM2 服务生命周期管理新增
| |-- multi-plan.md # /multi-plan - 多代理任务拆解新增
| |-- multi-execute.md # /multi-execute - 编排式多代理工作流新增
| |-- multi-backend.md # /multi-backend - 后端多服务编排新增
| |-- multi-frontend.md # /multi-frontend - 前端多服务编排新增
| |-- multi-workflow.md # /multi-workflow - 通用多服务工作流新增
| |-- pm2.md # /pm2 - PM2 服务生命周期管理 (新增)
| |-- multi-plan.md # /multi-plan - 多代理任务拆解 (新增)
| |-- multi-execute.md # /multi-execute - 编排式多代理工作流 (新增)
| |-- multi-backend.md # /multi-backend - 后端多服务编排 (新增)
| |-- multi-frontend.md # /multi-frontend - 前端多服务编排 (新增)
| |-- multi-workflow.md # /multi-workflow - 通用多服务工作流 (新增)
| |-- orchestrate.md # /orchestrate - 多代理协调
| |-- sessions.md # /sessions - 会话历史管理
| |-- eval.md # /eval - 按标准进行评估
| |-- test-coverage.md # /test-coverage - 测试覆盖率分析
| |-- update-docs.md # /update-docs - 更新文档
| |-- update-codemaps.md # /update-codemaps - 更新代码地图
| |-- python-review.md # /python-review - Python 代码审查 (新增)
|
|-- rules/ # 必须遵循的规则复制到 ~/.claude/rules/
| |-- README.md # 结构概览安装指南
| |-- common/ # 与语言无关的通用原则
| | |-- coding-style.md # 不可变性文件组织
| | |-- git-workflow.md # 提交格式PR 流程
| | |-- testing.md # TDD80% 覆盖率要求
| | |-- performance.md # 模型选择上下文管理
| | |-- patterns.md # 设计模式与项目骨架
| | |-- hooks.md # Hook 架构TodoWrite
|-- rules/ # 必须遵循的规则 (复制到 ~/.claude/rules/)
| |-- README.md # 结构概览安装指南
| |-- common/ # 与语言无关的原则
| | |-- coding-style.md # 不可变性文件组织
| | |-- git-workflow.md # 提交格式PR 流程
| | |-- testing.md # TDD80% 覆盖率要求
| | |-- performance.md # 模型选择上下文管理
| | |-- patterns.md # 设计模式、骨架项目
| | |-- hooks.md # Hook 架构TodoWrite
| | |-- agents.md # 何时委派给子代理
| | |-- security.md # 强制安全检查
| | |-- security.md # 必须执行的安全检查
| |-- typescript/ # TypeScript / JavaScript 专用
| |-- python/ # Python 专用
| |-- golang/ # Go 专用
|
|-- hooks/ # 基于触发器的自动化
| |-- hooks.json # 所有 Hook 配置PreToolUse、PostToolUse、Stop 等)
| |-- memory-persistence/ # 会话生命周期 Hook长文档指南
| |-- strategic-compact/ # 压缩建议(长文档指南)
| |-- README.md # Hook 文档、示例和自定义指南
| |-- hooks.json # 所有 Hook 配置 (PreToolUse、PostToolUse、Stop 等)
| |-- memory-persistence/ # 会话生命周期 Hook (Longform Guide)
| |-- strategic-compact/ # 压缩建议 (Longform Guide)
|
|-- scripts/ # 跨平台 Node.js 脚本新增
|-- scripts/ # 跨平台 Node.js 脚本 (新增)
| |-- lib/ # 共享工具
| | |-- utils.js # 跨平台文件/路径/系统工具
| | |-- utils.js # 跨平台文件 / 路径 / 系统工具
| | |-- package-manager.js # 包管理器检测与选择
| |-- hooks/ # Hook 实现
| | |-- session-start.js # 会话开始时加载上下文
| | |-- session-end.js # 会话结束时保存状态
| | |-- pre-compact.js # 压缩前状态保存
| | |-- suggest-compact.js # 战略压缩建议
| | |-- suggest-compact.js # 战略压缩建议
| | |-- evaluate-session.js # 从会话中提取模式
| |-- setup-package-manager.js # 交互式包管理器设置
|
|-- tests/ # 测试套件新增
|-- tests/ # 测试套件 (新增)
| |-- lib/ # 库测试
| |-- hooks/ # Hook 测试
| |-- run-all.js # 运行所有测试
|
|-- contexts/ # 动态系统提示注入上下文(长文档指南)
|-- contexts/ # 动态系统提示上下文注入 (Longform Guide)
| |-- dev.md # 开发模式上下文
| |-- review.md # 代码审查模式上下文
| |-- research.md # 研究/探索模式上下文
| |-- research.md # 研究 / 探索模式上下文
|
|-- examples/ # 示例配置会话
| |-- CLAUDE.md # 项目级配置示例
| |-- user-CLAUDE.md # 用户级配置示例
|-- examples/ # 示例配置会话
| |-- CLAUDE.md # 项目级配置示例
| |-- user-CLAUDE.md # 用户级配置示例
| |-- saas-nextjs-CLAUDE.md # 真实 SaaS 示例 (Next.js + Supabase + Stripe)
| |-- go-microservice-CLAUDE.md # 真实 Go 微服务示例 (gRPC + PostgreSQL)
| |-- django-api-CLAUDE.md # 真实 Django REST API 示例 (DRF + Celery)
| |-- rust-api-CLAUDE.md # 真实 Rust API 示例 (Axum + SQLx + PostgreSQL) (新增)
|
|-- mcp-configs/ # MCP 服务器配置
| |-- mcp-servers.json # GitHub、Supabase、Vercel、Railway 等
|
|-- marketplace.json # 自托管插件市场配置用于 /plugin marketplace add
|-- marketplace.json # 自托管市场配置 (用于 /plugin marketplace add)
```
***
@@ -350,6 +462,8 @@ everything-claude-code/
### AgentShield — 安全审计器
> 在 Claude Code 黑客马拉松Cerebral Valley x Anthropic2026年2月上构建。1282 项测试98% 覆盖率102 条静态分析规则。
扫描您的 Claude Code 配置,查找漏洞、错误配置和注入风险。
```bash
@@ -359,19 +473,27 @@ npx ecc-agentshield scan
# Auto-fix safe issues
npx ecc-agentshield scan --fix
# Deep analysis with Opus 4.6
# Deep analysis with three Opus 4.6 agents
npx ecc-agentshield scan --opus --stream
# Generate secure config from scratch
npx ecc-agentshield init
```
检查 CLAUDE.md、settings.json、MCP 服务器、钩子和智能体定义。生成带有可操作发现的安全等级 (A-F)
**它扫描什么:** CLAUDE.md、settings.json、MCP 配置、钩子、代理定义以及 5 个类别的技能 —— 密钥检测14 种模式、权限审计、钩子注入分析、MCP 服务器风险剖析和代理配置审查
**`--opus` 标志** 在红队/蓝队/审计员管道中运行三个 Claude Opus 4.6 代理。攻击者寻找利用链,防御者评估保护措施,审计员将两者综合成优先风险评估。对抗性推理,而不仅仅是模式匹配。
**输出格式:** 终端(按颜色分级的 A-F、JSONCI 管道、Markdown、HTML。在关键发现时退出代码 2用于构建门控。
在 Claude Code 中使用 `/security-scan` 来运行它,或者通过 [GitHub Action](https://github.com/affaan-m/agentshield) 添加到 CI。
[GitHub](https://github.com/affaan-m/agentshield) | [npm](https://www.npmjs.com/package/ecc-agentshield)
### 🔬 Plankton — 编写时代码质量强制执行
Plankton致谢@alxfazio)是用于编写时代码质量强制执行的推荐伴侣。它通过 PostToolUse 钩子在每次文件编辑时运行格式化程序和 20 多个代码检查器,然后生成 Claude 子进程(根据违规复杂度路由到 Haiku/Sonnet/Opus来修复主智能体遗漏的问题。采用三阶段架构静默自动格式化解决 40-50% 的问题),将剩余的违规收集为结构化 JSON委托给子进程修复。包含配置保护钩子防止智能体修改检查器配置以通过检查而非修复代码。支持 Python、TypeScript、Shell、YAML、JSON、TOML、Markdown 和 Dockerfile。与 AgentShield 结合使用,实现安全 + 质量覆盖。完整集成指南请参阅 `skills/plankton-code-quality/`
### 🧠 持续学习 v2
基于本能的学习系统会自动学习您的模式:
@@ -449,23 +571,23 @@ Duplicate hooks file detected: ./hooks/hooks.json resolves to already-loaded fil
这将使您能够立即访问所有命令、代理、技能和钩子。
> **注意:** Claude Code 插件系统不支持通过插件分发 `rules`[上游限制](https://code.claude.com/docs/en/plugins-reference))。需要手动安装规则:
> **注意:** Claude Code 插件系统不支持通过插件分发 `rules`[上游限制](https://code.claude.com/docs/en/plugins-reference))。需要手动安装规则:
>
> ```bash
> # 首先克隆仓库
> git clone https://github.com/affaan-m/everything-claude-code.git
>
> # 选项 A用户级规则用于所有项目)
> # 选项 A用户级规则用于所有项目)
> mkdir -p ~/.claude/rules
> cp -r everything-claude-code/rules/common/* ~/.claude/rules/
> cp -r everything-claude-code/rules/typescript/* ~/.claude/rules/ # 选择的技术栈
> cp -r everything-claude-code/rules/typescript/* ~/.claude/rules/ # 选择的技术栈
> cp -r everything-claude-code/rules/python/* ~/.claude/rules/
> cp -r everything-claude-code/rules/golang/* ~/.claude/rules/
>
> # 选项 B项目级规则用于当前项目)
> # 选项 B项目级规则用于当前项目)
> mkdir -p .claude/rules
> cp -r everything-claude-code/rules/common/* .claude/rules/
> cp -r everything-claude-code/rules/typescript/* .claude/rules/ # 选择的技术栈
> cp -r everything-claude-code/rules/typescript/* .claude/rules/ # 选择的技术栈
> ```
***
@@ -490,8 +612,15 @@ cp -r everything-claude-code/rules/golang/* ~/.claude/rules/
# Copy commands
cp everything-claude-code/commands/*.md ~/.claude/commands/
# Copy skills
cp -r everything-claude-code/skills/* ~/.claude/skills/
# Copy skills (core vs niche)
# Recommended (new users): core/general skills only
cp -r everything-claude-code/.agents/skills/* ~/.claude/skills/
cp -r everything-claude-code/skills/search-first ~/.claude/skills/
# Optional: add niche/framework-specific skills only when needed
# for s in django-patterns django-tdd springboot-patterns; do
# cp -r everything-claude-code/skills/$s ~/.claude/skills/
# done
```
#### 将钩子添加到 settings.json
@@ -568,6 +697,136 @@ rules/
***
## 🗺️ 我应该使用哪个代理?
不确定从哪里开始?使用这个快速参考:
| 我想要... | 使用此命令 | 使用的代理 |
|--------------|-----------------|------------|
| 规划新功能 | `/everything-claude-code:plan "Add auth"` | planner |
| 设计系统架构 | `/everything-claude-code:plan` + architect agent | architect |
| 先写带测试的代码 | `/tdd` | tdd-guide |
| 审查我刚写的代码 | `/code-review` | code-reviewer |
| 修复失败的构建 | `/build-fix` | build-error-resolver |
| 运行端到端测试 | `/e2e` | e2e-runner |
| 查找安全漏洞 | `/security-scan` | security-reviewer |
| 移除死代码 | `/refactor-clean` | refactor-cleaner |
| 更新文档 | `/update-docs` | doc-updater |
| 审查 Go 代码 | `/go-review` | go-reviewer |
| 审查 Python 代码 | `/python-review` | python-reviewer |
| 审计数据库查询 | *(自动委派)* | database-reviewer |
### 常见工作流
**开始新功能:**
```
/everything-claude-code:plan "Add user authentication with OAuth"
→ planner creates implementation blueprint
/tdd → tdd-guide enforces write-tests-first
/code-review → code-reviewer checks your work
```
**修复错误:**
```
/tdd → tdd-guide: write a failing test that reproduces it
→ implement the fix, verify test passes
/code-review → code-reviewer: catch regressions
```
**准备生产环境:**
```
/security-scan → security-reviewer: OWASP Top 10 audit
/e2e → e2e-runner: critical user flow tests
/test-coverage → verify 80%+ coverage
```
***
## ❓ 常见问题
<details>
<summary><b>How do I check which agents/commands are installed?</b></summary>
```bash
/plugin list everything-claude-code@everything-claude-code
```
这会显示插件中所有可用的代理、命令和技能。
</details>
<details>
<summary><b>My hooks aren't working / I see "Duplicate hooks file" errors</b></summary>
这是最常见的问题。**不要在 `.claude-plugin/plugin.json` 中添加 `"hooks"` 字段。** Claude Code v2.1+ 会自动从已安装的插件加载 `hooks/hooks.json`。显式声明它会导致重复检测错误。参见 [#29](https://github.com/affaan-m/everything-claude-code/issues/29), [#52](https://github.com/affaan-m/everything-claude-code/issues/52), [#103](https://github.com/affaan-m/everything-claude-code/issues/103)。
</details>
<details>
<summary><b>My context window is shrinking / Claude is running out of context</b></summary>
太多的 MCP 服务器会消耗你的上下文。每个 MCP 工具描述都会消耗你 200k 窗口的令牌,可能将其减少到约 70k。
**修复:** 按项目禁用未使用的 MCP
```json
// In your project's .claude/settings.json
{
"disabledMcpServers": ["supabase", "railway", "vercel"]
}
```
保持启用的 MCP 少于 10 个,活动工具少于 80 个。
</details>
<details>
<summary><b>Can I use only some components (e.g., just agents)?</b></summary>
是的。使用选项 2手动安装并仅复制你需要的部分
```bash
# Just agents
cp everything-claude-code/agents/*.md ~/.claude/agents/
# Just rules
cp -r everything-claude-code/rules/common/* ~/.claude/rules/
```
每个组件都是完全独立的。
</details>
<details>
<summary><b>Does this work with Cursor / OpenCode / Codex / Antigravity?</b></summary>
是的。ECC 是跨平台的:
* **Cursor**`.cursor/` 中的预翻译配置。请参阅 [Cursor IDE 支持](#cursor-ide-支持)。
* **OpenCode**`.opencode/` 中的完整插件支持。请参阅 [OpenCode 支持](#-opencode-支持)。
* **Codex**:对 macOS 应用和 CLI 的一流支持,带有适配器漂移防护和 SessionStart 回退。请参阅 PR [#257](https://github.com/affaan-m/everything-claude-code/pull/257)。
* **Antigravity**`.agent/` 中针对工作流、技能和扁平化规则的紧密集成设置。
* **Claude Code**:原生支持 — 这是主要目标。
</details>
<details>
<summary><b>How do I contribute a new skill or agent?</b></summary>
参见 [CONTRIBUTING.md](CONTRIBUTING.md)。简短版本:
1. Fork 仓库
2.`skills/your-skill-name/SKILL.md` 中创建你的技能(带有 YAML 前言)
3. 或在 `agents/your-agent.md` 中创建代理
4. 提交 PR清晰描述其功能和使用时机
</details>
***
## 🧪 运行测试
该插件包含一个全面的测试套件:
@@ -609,31 +868,115 @@ node tests/hooks/hooks.test.js
## Cursor IDE 支持
ecc-universal 包含为 [Cursor IDE](https://cursor.com) 预翻译的配置。`.cursor/` 目录包含适用于 Cursor 格式的规则、智能体、技能、命令和 MCP 配置。
ECC 提供**完整的 Cursor IDE 支持**,包括为 Cursor 原生格式适配的钩子、规则、代理、技能、命令和 MCP 配置。
### 快速开始 (Cursor)
```bash
# Install the package
npm install ecc-universal
# Install for your language(s)
./install.sh --target cursor typescript
./install.sh --target cursor python golang
./install.sh --target cursor python golang swift
```
### 已翻译内容
### 包含内容
| 组件 | Claude Code → Cursor | 对等性 |
|-----------|---------------------|--------|
| 规则 | 添加了 YAML frontmatter路径扁平化 | 完全 |
| 智能体 | 模型 ID 已扩展,工具 → 只读标志 | 完全 |
| 技能 | 无需更改 (标准相同) | 相同 |
| 命令 | 路径引用已更新,多-\* 已存根 | 部分 |
| MCP 配置 | 环境变量插值语法已更新 | 完全 |
| 钩子 | Cursor 中无等效项 | 参见替代方案 |
| 组件 | 数量 | 详情 |
|-----------|-------|---------|
| 钩子事件 | 15 | sessionStart, beforeShellExecution, afterFileEdit, beforeMCPExecution, beforeSubmitPrompt, 以及另外 10 个 |
| 钩子脚本 | 16 | 通过共享适配器委托给 `scripts/hooks/` 的轻量 Node.js 脚本 |
| 规则 | 29 | 9 条通用规则 (alwaysApply) + 20 条语言特定规则 (TypeScript, Python, Go, Swift) |
| 代理 | 共享 | 通过根目录下的 AGENTS.md被 Cursor 原生读取) |
| 技能 | 共享 + 捆绑 | 通过根目录下的 AGENTS.md 和用于翻译补充的 `.cursor/skills/` |
| 命令 | 共享 | `.cursor/commands/`(如果已安装) |
| MCP 配置 | 共享 | `.cursor/mcp.json`(如果已安装) |
详情请参阅 [.cursor/README.md](.cursor/README.md),完整迁移指南请参阅 [.cursor/MIGRATION.md](.cursor/MIGRATION.md)。
### 钩子架构DRY 适配器模式)
Cursor 的**钩子事件比 Claude Code 多**20 对 8`.cursor/hooks/adapter.js` 模块将 Cursor 的 stdin JSON 转换为 Claude Code 的格式,允许重用现有的 `scripts/hooks/*.js` 而无需重复。
```
Cursor stdin JSON → adapter.js → transforms → scripts/hooks/*.js
(shared with Claude Code)
```
关键钩子:
* **beforeShellExecution** — 阻止在 tmux 外启动开发服务器(退出码 2git push 审查
* **afterFileEdit** — 自动格式化 + TypeScript 检查 + console.log 警告
* **beforeSubmitPrompt** — 检测提示中的密钥sk-、ghp\_、AKIA 模式)
* **beforeTabFileRead** — 阻止 Tab 读取 .env、.key、.pem 文件(退出码 2
* **beforeMCPExecution / afterMCPExecution** — MCP 审计日志记录
### 规则格式
Cursor 规则使用带有 `description``globs``alwaysApply` 的 YAML 前言:
```yaml
---
description: "TypeScript coding style extending common rules"
globs: ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"]
alwaysApply: false
---
```
***
## Codex macOS 应用 + CLI 支持
ECC 为 macOS 应用和 CLI 提供 **一流的 Codex 支持**包括参考配置、Codex 特定的 AGENTS.md 补充文档以及共享技能。
### 快速开始Codex 应用 + CLI
```bash
# Copy the reference config to your home directory
cp .codex/config.toml ~/.codex/config.toml
# Run Codex CLI in the repo — AGENTS.md is auto-detected
codex
```
Codex macOS 应用:
* 将此仓库作为您的工作区打开。
* 根目录的 `AGENTS.md` 会被自动检测。
* 可选:将 `.codex/config.toml` 复制到 `~/.codex/config.toml` 以实现 CLI/应用行为一致性。
### 包含内容
| 组件 | 数量 | 详情 |
|-----------|-------|---------|
| 配置 | 1 | `.codex/config.toml` — 模型、权限、MCP 服务器、持久指令 |
| AGENTS.md | 2 | 根目录(通用)+ `.codex/AGENTS.md`Codex 特定补充) |
| 技能 | 16 | `.agents/skills/` — 每个技能包含 SKILL.md + agents/openai.yaml |
| MCP 服务器 | 4 | GitHub、Context7、Memory、Sequential Thinking基于命令 |
| 配置文件 | 2 | `strict`(只读沙箱)和 `yolo`(完全自动批准) |
### 技能
位于 `.agents/skills/` 的技能会被 Codex 自动加载:
| 技能 | 描述 |
|-------|-------------|
| tdd-workflow | 测试驱动开发,覆盖率 80%+ |
| security-review | 全面的安全检查清单 |
| coding-standards | 通用编码标准 |
| frontend-patterns | React/Next.js 模式 |
| frontend-slides | HTML 演示文稿、PPTX 转换、视觉风格探索 |
| article-writing | 根据笔记和语音参考进行长文写作 |
| content-engine | 平台原生的社交内容和再利用 |
| market-research | 带来源归属的市场和竞争对手研究 |
| investor-materials | 幻灯片、备忘录、模型和一页纸文档 |
| investor-outreach | 个性化外联、跟进和介绍摘要 |
| backend-patterns | API 设计、数据库、缓存 |
| e2e-testing | Playwright 端到端测试 |
| eval-harness | 评估驱动的开发 |
| strategic-compact | 上下文管理 |
| api-design | REST API 设计模式 |
| verification-loop | 构建、测试、代码检查、类型检查、安全 |
### 关键限制
Codex **尚未提供 Claude 风格的钩子执行对等性**。ECC 在该平台上的强制执行是通过 `AGENTS.md``persistent_instructions` 基于指令实现的,外加沙箱权限。
***
@@ -655,15 +998,15 @@ opencode
### 功能对等
| 特性 | Claude Code | OpenCode | 状态 |
| 功能 | Claude Code | OpenCode | 状态 |
|---------|-------------|----------|--------|
| 智能体 | ✅ 14 agents | ✅ 12 agents | **Claude Code 领先** |
| 命令 | ✅ 30 commands | ✅ 24 commands | **Claude Code 领先** |
| 技能 | ✅ 28 skills | ✅ 16 skills | **Claude Code 领先** |
| 钩子 | ✅ 3 phases | ✅ 20+ events | **OpenCode 更多!** |
| 规则 | ✅ 8 rules | ✅ 8 rules | **完全一致** |
| MCP Servers | ✅ Full | ✅ Full | **完全一致** |
| 自定义工具 | ✅ Via hooks | ✅ Native support | **OpenCode 更好** |
| 智能体 | ✅ 16 个智能体 | ✅ 12 个智能体 | **Claude Code 领先** |
| 命令 | ✅ 40 条命令 | ✅ 31 条命令 | **Claude Code 领先** |
| 技能 | ✅ 65 项技能 | ✅ 37 项技能 | **Claude Code 领先** |
| 钩子 | ✅ 8 种事件类型 | ✅ 11 种事件 | **OpenCode 更多!** |
| 规则 | ✅ 29 条规则 | ✅ 13 条指令 | **Claude Code 领先** |
| MCP 服务器 | ✅ 14 个服务器 | ✅ 完整 | **完全对等** |
| 自定义工具 | ✅ 通过钩子 | ✅ 6 个原生工具 | **OpenCode 更好** |
### 通过插件实现的钩子支持
@@ -679,18 +1022,17 @@ OpenCode 的插件系统比 Claude Code 更复杂,有 20 多种事件类型:
**额外的 OpenCode 事件**`file.edited``file.watcher.updated``message.updated``lsp.client.diagnostics``tui.toast.show` 等等。
### 可用命令 (24)
### 可用命令31+
| 命令 | 描述 |
|---------|-------------|
| `/plan` | 创建实施计划 |
| `/tdd` | 强制执行 TDD 工作流 |
| `/code-review` | 审查代码变更 |
| `/security` | 运行安全审查 |
| `/build-fix` | 修复构建错误 |
| `/e2e` | 生成端到端测试 |
| `/refactor-clean` | 移除死代码 |
| `/orchestrate` | 多代理工作流 |
| `/orchestrate` | 多智能体工作流 |
| `/learn` | 从会话中提取模式 |
| `/checkpoint` | 保存验证状态 |
| `/verify` | 运行验证循环 |
@@ -701,12 +1043,28 @@ OpenCode 的插件系统比 Claude Code 更复杂,有 20 多种事件类型:
| `/go-review` | Go 代码审查 |
| `/go-test` | Go TDD 工作流 |
| `/go-build` | 修复 Go 构建错误 |
| `/python-review` | Python 代码审查PEP 8、类型提示、安全性 |
| `/multi-plan` | 多模型协作规划 |
| `/multi-execute` | 多模型协作执行 |
| `/multi-backend` | 后端聚焦的多模型工作流 |
| `/multi-frontend` | 前端聚焦的多模型工作流 |
| `/multi-workflow` | 完整的多模型开发工作流 |
| `/pm2` | 自动生成 PM2 服务命令 |
| `/sessions` | 管理会话历史 |
| `/skill-create` | 从 git 生成技能 |
| `/instinct-status` | 查看习的本能 |
| `/instinct-status` | 查看已学习的本能 |
| `/instinct-import` | 导入本能 |
| `/instinct-export` | 导出本能 |
| `/evolve` | 将本能聚类为技能 |
| `/promote` | 将项目本能提升到全局范围 |
| `/projects` | 列出已知项目和本能统计信息 |
| `/learn-eval` | 保存前提取和评估模式 |
| `/setup-pm` | 配置包管理器 |
| `/harness-audit` | 审计平台可靠性、评估准备情况和风险状况 |
| `/loop-start` | 启动受控的智能体循环执行模式 |
| `/loop-status` | 检查活动循环状态和检查点 |
| `/quality-gate` | 对路径或整个仓库运行质量门检查 |
| `/model-route` | 根据复杂度和预算将任务路由到模型 |
### 插件安装
@@ -740,27 +1098,138 @@ npm install ecc-universal
***
## 跨工具功能对等
ECC 是**第一个最大化利用每个主要 AI 编码工具的插件**。以下是每个平台的比较:
| 功能 | Claude Code | Cursor IDE | Codex CLI | OpenCode |
|---------|------------|------------|-----------|----------|
| **智能体** | 16 | 共享AGENTS.md | 共享AGENTS.md | 12 |
| **命令** | 40 | 共享 | 基于指令 | 31 |
| **技能** | 65 | 共享 | 10原生格式 | 37 |
| **钩子事件** | 8 种类型 | 15 种类型 | 暂无 | 11 种类型 |
| **钩子脚本** | 20+ 个脚本 | 16 个脚本DRY 适配器) | 不适用 | 插件钩子 |
| **规则** | 29通用 + 语言) | 29YAML 前言) | 基于指令 | 13 条指令 |
| **自定义工具** | 通过钩子 | 通过钩子 | 不适用 | 6 个原生工具 |
| **MCP 服务器** | 14 | 共享mcp.json | 4基于命令 | 完整 |
| **配置格式** | settings.json | hooks.json + rules/ | config.toml | opencode.json |
| **上下文文件** | CLAUDE.md + AGENTS.md | AGENTS.md | AGENTS.md | AGENTS.md |
| **秘密检测** | 基于钩子 | beforeSubmitPrompt 钩子 | 基于沙箱 | 基于钩子 |
| **自动格式化** | PostToolUse 钩子 | afterFileEdit 钩子 | 不适用 | file.edited 钩子 |
| **版本** | 插件 | 插件 | 参考配置 | 1.8.0 |
**关键架构决策:**
* 根目录下的 **AGENTS.md** 是通用的跨工具文件(被所有 4 个工具读取)
* **DRY 适配器模式** 让 Cursor 可以重用 Claude Code 的钩子脚本而无需重复
* **技能格式**(带有 YAML 前言的 SKILL.md在 Claude Code、Codex 和 OpenCode 上都能工作
* Codex 缺乏钩子的问题通过 `persistent_instructions` 和沙箱权限来弥补
***
## 📖 背景
我从实验性推出以来就一直在使用 Claude Code。在 2025 年 9 月,与 [@DRodriguezFX](https://x.com/DRodriguezFX) 一起使用 Claude Code 构建 [zenith.chat](https://zenith.chat),赢得了 Anthropic x Forum Ventures 黑客马拉松。
这些配置已在多个生产应用程序中经过实战测试。
## 灵感致谢
* 灵感来自 [zarazhangrui](https://github.com/zarazhangrui)
* homunculus 灵感来自 [humanplane](https://github.com/humanplane)
***
## 令牌优化
如果不管理令牌消耗,使用 Claude Code 可能会很昂贵。这些设置能在不牺牲质量的情况下显著降低成本。
### 推荐设置
添加到 `~/.claude/settings.json`
```json
{
"model": "sonnet",
"env": {
"MAX_THINKING_TOKENS": "10000",
"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "50"
}
}
```
| 设置 | 默认值 | 推荐值 | 影响 |
|---------|---------|-------------|--------|
| `model` | opus | **sonnet** | 约 60% 的成本降低;处理 80%+ 的编码任务 |
| `MAX_THINKING_TOKENS` | 31,999 | **10,000** | 每个请求的隐藏思考成本降低约 70% |
| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | 95 | **50** | 更早压缩 —— 在长会话中质量更好 |
仅在需要深度架构推理时切换到 Opus
```
/model opus
```
### 日常工作流命令
| 命令 | 何时使用 |
|---------|-------------|
| `/model sonnet` | 大多数任务的默认选择 |
| `/model opus` | 复杂架构、调试、深度推理 |
| `/clear` | 在不相关的任务之间(免费,即时重置) |
| `/compact` | 在逻辑任务断点处(研究完成,里程碑达成) |
| `/cost` | 在会话期间监控令牌花费 |
### 策略性压缩
`strategic-compact` 技能(包含在此插件中)建议在逻辑断点处进行 `/compact`,而不是依赖在 95% 上下文时的自动压缩。完整决策指南请参见 `skills/strategic-compact/SKILL.md`
**何时压缩:**
* 研究/探索之后,实施之前
* 完成一个里程碑之后,开始下一个之前
* 调试之后,继续功能工作之前
* 失败的方法之后,尝试新方法之前
**何时不压缩:**
* 实施过程中(你会丢失变量名、文件路径、部分状态)
### 上下文窗口管理
**关键:** 不要一次性启用所有 MCP。每个 MCP 工具描述都会消耗你 200k 窗口的令牌,可能将其减少到约 70k。
* 每个项目保持启用的 MCP 少于 10 个
* 保持活动工具少于 80 个
* 在项目配置中使用 `disabledMcpServers` 来禁用未使用的 MCP
### 代理团队成本警告
代理团队会生成多个上下文窗口。每个团队成员独立消耗令牌。仅用于并行性能提供明显价值的任务(多模块工作、并行审查)。对于简单的顺序任务,子代理更节省令牌。
***
## ⚠️ 重要说明
### 上下文窗口管理
### 令牌优化
**关键:** 不要一次性启用所有 MCP。启用过多工具后你的 200k 上下文窗口可能会缩小到 70k
达到每日限制?参见 **[令牌优化指南](../token-optimization.md)** 获取推荐设置和工作流提示
经验法则
快速见效的方法
* 配置 20-30 个 MCP
* 每个项目保持启用少于 10 个
* 活动工具少于 80 个
```json
// ~/.claude/settings.json
{
"model": "sonnet",
"env": {
"MAX_THINKING_TOKENS": "10000",
"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "50",
"CLAUDE_CODE_SUBAGENT_MODEL": "haiku"
}
}
```
项目配置中使用 `disabledMcpServers` 来禁用未使用的工具
不相关的任务之间使用 `/clear`,在逻辑断点处使用 `/compact`,并使用 `/cost` 来监控花费
### 定制化
@@ -773,6 +1242,14 @@ npm install ecc-universal
***
## 💜 赞助商
这个项目是免费和开源的。赞助商帮助保持其维护和发展。
[**成为赞助商**](https://github.com/sponsors/affaan-m) | [赞助层级](SPONSORS.md) | [赞助计划](SPONSORING.md)
***
## 🌟 Star 历史
[![Star History Chart](https://api.star-history.com/svg?repos=affaan-m/everything-claude-code\&type=Date)](https://star-history.com/#affaan-m/everything-claude-code\&Date)
@@ -781,11 +1258,11 @@ npm install ecc-universal
## 🔗 链接
* **速查指南 (从此开始):** [Claude Code 万事速查指南](https://x.com/affaanmustafa/status/2012378465664745795)
* **详细指南 (进阶):** [Claude Code 万事详细指南](https://x.com/affaanmustafa/status/2014040193557471352)
* **关注:** [@affaanmustafa](https://x.com/affaanmustafa)
* **zenith.chat:** [zenith.chat](https://zenith.chat)
* **技能目录:** awesome-agent-skills社区维护的智能体技能目录
* **速查指南(从这里开始):** [Claude Code 速查指南](https://x.com/affaanmustafa/status/2012378465664745795)
* **详细指南(进阶):** [Claude Code 详细指南](https://x.com/affaanmustafa/status/2014040193557471352)
* **关注** [@affaanmustafa](https://x.com/affaanmustafa)
* **zenith.chat** [zenith.chat](https://zenith.chat)
* **技能目录** awesome-agent-skills社区维护的智能体技能目录
***

43
docs/zh-CN/SPONSORING.md Normal file
View File

@@ -0,0 +1,43 @@
# 赞助 ECC
ECC 作为一个开源智能体性能测试系统,在 Claude Code、Cursor、OpenCode 和 Codex 应用程序/CLI 中得到维护。
## 为何赞助
赞助直接资助以下方面:
* 更快的错误修复和发布周期
* 跨测试平台的平台一致性工作
* 为社区免费提供的公共文档、技能和可靠性工具
## 赞助层级
这些是实用的起点,可以根据合作范围进行调整。
| 层级 | 价格 | 最适合 | 包含内容 |
|------|-------|----------|----------|
| 试点合作伙伴 | $200/月 | 首次赞助合作 | 月度指标更新、路线图预览、优先维护者反馈 |
| 成长合作伙伴 | $500/月 | 积极采用 ECC 的团队 | 试点权益 + 月度办公时间同步 + 工作流集成指导 |
| 战略合作伙伴 | $1,000+/月 | 平台/生态系统合作伙伴 | 成长权益 + 协调发布支持 + 更深入的维护者协作 |
## 赞助报告
每月分享的指标可能包括:
* npm 下载量(`ecc-universal``ecc-agentshield`
* 仓库采用情况(星标、分叉、贡献者)
* GitHub 应用安装趋势
* 发布节奏和可靠性里程碑
有关确切的命令片段和可重复的拉取流程,请参阅 [`docs/business/metrics-and-sponsorship.md`](../business/metrics-and-sponsorship.md)。
## 期望与范围
* 赞助支持维护和加速;不会转移项目所有权。
* 功能请求根据赞助层级、生态系统影响和维护风险进行优先级排序。
* 安全性和可靠性修复优先于全新功能。
## 在此赞助
* GitHub Sponsors: <https://github.com/sponsors/affaan-m>
* 项目网站: <https://ecc.tools>

View File

@@ -29,16 +29,28 @@
* **更好的支持** — 赞助者获得优先响应
* **影响路线图** — Pro+ 赞助者可以对功能进行投票
## 赞助者准备度信号
在赞助者对话中使用这些证明点:
* `ecc-universal``ecc-agentshield` 的实时 npm 安装/下载指标
* 通过 Marketplace 安装的 GitHub App 分发
* 公开采用信号:星标、分叉、贡献者、发布节奏
* 跨平台支持Claude Code、Cursor、OpenCode、Codex 应用/CLI
有关复制/粘贴指标拉取工作流程,请参阅 [`docs/business/metrics-and-sponsorship.md`](../business/metrics-and-sponsorship.md)。
## 赞助等级
| 级 | 价格 | 权益 |
| 级 | 价格 | 权益 |
|------|-------|----------|
| 支持者 | $5/月 | 名字出现在 README 中,早期访问 |
| 建者 | $10/月 | 高级工具访问权限 |
| 专业版 | $25/月 | 优先支持,办公时间咨询 |
| 团队 | $100/月 | 5个席位团队配置 |
| 商业 | $500/月 | 25个席位咨询额度 |
| 企业 | $2K/月 | 无限席位,定制工具 |
| 支持者 | 每月 $5 | 名字出现在 README 中,早期访问 |
| 建者 | 每月 $10 | 高级工具访问权限 |
| 专业版 | 每月 $25 | 优先支持,办公时间 |
| 团队 | 每月 $100 | 5 个席位,团队配置 |
| 平台合作伙伴 | 每月 $200 | 月度路线图同步,优先维护者反馈,发布说明提及 |
| 商业版 | 每月 $500 | 25 个席位,咨询积分 |
| 企业版 | 每月 $2K | 无限制席位,自定义工具 |
[**Become a Sponsor →**](https://github.com/sponsors/affaan-m)

View File

@@ -1,556 +1,119 @@
---
name: build-error-resolver
description: 构建TypeScript错误解决专家。在构建失败或类型错误发生时主动使用。仅通过最小差异修复构建/类型错误,不进行架构编辑。专注于快速使构建变绿
description: 构建TypeScript错误解决专家。在构建失败或类型错误发生时主动使用。仅最小差异修复构建/类型错误,不进行架构编辑。专注于快速使构建通过
tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]
model: opus
model: sonnet
---
# 构建错误解决器
你是一位专注于快速高效修复 TypeScript、编译和构建错误的构建错误解决专家。你的任务是让构建通过且改动最小不进行架构修改
你是一名专业的构建错误解决专家。你的任务是以最小的改动让构建通过——不重构、不改变架构、不进行改进
## 核心职责
1. **TypeScript 错误解决** - 修复类型错误、推断问题、泛型约束
2. **构建错误修复** - 解决编译失败、模块解析问题
3. **依赖问题** - 修复导入错误、缺失包、版本冲突
4. **配置错误** - 解决 tsconfig.json、webpack、Next.js 配置问题
5. **最小差异** -尽可能小的改来修复错误
6. **无架构更改** - 只修复错误,不重构或重新设计
1. **TypeScript 错误解决** 修复类型错误、推断问题、泛型约束
2. **构建错误修复** 解决编译失败、模块解析问题
3. **依赖问题** 修复导入错误、缺失包、版本冲突
4. **配置错误** 解决 tsconfig、webpack、Next.js 配置问题
5. **最小差异** 做尽可能小的改来修复错误
6. **不改变架构** 只修复错误,不重新设计
## 可用的工具
### 构建和类型检查工具
* **tsc** - TypeScript 编译器,用于类型检查
* **npm/yarn** - 包管理
* **eslint** - 代码检查(可能导致构建失败)
* **next build** - Next.js 生产构建
### 诊断命令
## 诊断命令
```bash
# TypeScript type check (no emit)
npx tsc --noEmit
# TypeScript with pretty output
npx tsc --noEmit --pretty
# Show all errors (don't stop at first)
npx tsc --noEmit --pretty --incremental false
# Check specific file
npx tsc --noEmit path/to/file.ts
# ESLint check
npx eslint . --ext .ts,.tsx,.js,.jsx
# Next.js build (production)
npx tsc --noEmit --pretty --incremental false # Show all errors
npm run build
# Next.js build with debug
npm run build -- --debug
npx eslint . --ext .ts,.tsx,.js,.jsx
```
## 错误解决工作流程
## 工作流程
### 1. 收集所有错误
```
a) Run full type check
- npx tsc --noEmit --pretty
- Capture ALL errors, not just first
* 运行 `npx tsc --noEmit --pretty` 获取所有类型错误
* 分类:类型推断、缺失类型、导入、配置、依赖
* 优先级:首先处理阻塞构建的错误,然后是类型错误,最后是警告
b) Categorize errors by type
- Type inference failures
- Missing type definitions
- Import/export errors
- Configuration errors
- Dependency issues
### 2. 修复策略(最小改动)
c) Prioritize by impact
- Blocking build: Fix first
- Type errors: Fix in order
- Warnings: Fix if time permits
```
对于每个错误:
### 2. 修复策略(最小化更改)
1. 仔细阅读错误信息——理解预期与实际结果
2. 找到最小的修复方案(类型注解、空值检查、导入修复)
3. 验证修复不会破坏其他代码——重新运行 tsc
4. 迭代直到构建通过
```
For each error:
### 3. 常见修复
1. Understand the error
- Read error message carefully
- Check file and line number
- Understand expected vs actual type
| 错误 | 修复 |
|-------|-----|
| `implicitly has 'any' type` | 添加类型注解 |
| `Object is possibly 'undefined'` | 可选链 `?.` 或空值检查 |
| `Property does not exist` | 添加到接口或使用可选 `?` |
| `Cannot find module` | 检查 tsconfig 路径、安装包或修复导入路径 |
| `Type 'X' not assignable to 'Y'` | 解析/转换类型或修复类型 |
| `Generic constraint` | 添加 `extends { ... }` |
| `Hook called conditionally` | 将钩子移到顶层 |
| `'await' outside async` | 添加 `async` 关键字 |
2. Find minimal fix
- Add missing type annotation
- Fix import statement
- Add null check
- Use type assertion (last resort)
## 做与不做
3. Verify fix doesn't break other code
- Run tsc again after each fix
- Check related files
- Ensure no new errors introduced
**做:**
4. Iterate until build passes
- Fix one error at a time
- Recompile after each fix
- Track progress (X/Y errors fixed)
```
* 在缺失的地方添加类型注解
* 在需要的地方添加空值检查
* 修复导入/导出
* 添加缺失的依赖项
* 更新类型定义
* 修复配置文件
### 3. 常见错误模式及修复方法
**不做:**
**模式 1类型推断失败**
* 重构无关代码
* 改变架构
* 重命名变量(除非导致错误)
* 添加新功能
* 改变逻辑流程(除非为了修复错误)
* 优化性能或样式
```typescript
// ❌ ERROR: Parameter 'x' implicitly has an 'any' type
function add(x, y) {
return x + y
}
## 优先级等级
// ✅ FIX: Add type annotations
function add(x: number, y: number): number {
return x + y
}
```
| 等级 | 症状 | 行动 |
|-------|----------|--------|
| 严重 | 构建完全中断,开发服务器无法启动 | 立即修复 |
| 高 | 单个文件失败,新代码类型错误 | 尽快修复 |
| 中 | 代码检查警告、已弃用的 API | 在可能时修复 |
**模式 2Null/Undefined 错误**
```typescript
// ❌ ERROR: Object is possibly 'undefined'
const name = user.name.toUpperCase()
// ✅ FIX: Optional chaining
const name = user?.name?.toUpperCase()
// ✅ OR: Null check
const name = user && user.name ? user.name.toUpperCase() : ''
```
**模式 3缺少属性**
```typescript
// ❌ ERROR: Property 'age' does not exist on type 'User'
interface User {
name: string
}
const user: User = { name: 'John', age: 30 }
// ✅ FIX: Add property to interface
interface User {
name: string
age?: number // Optional if not always present
}
```
**模式 4导入错误**
```typescript
// ❌ ERROR: Cannot find module '@/lib/utils'
import { formatDate } from '@/lib/utils'
// ✅ FIX 1: Check tsconfig paths are correct
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
// ✅ FIX 2: Use relative import
import { formatDate } from '../lib/utils'
// ✅ FIX 3: Install missing package
npm install @/lib/utils
```
**模式 5类型不匹配**
```typescript
// ❌ ERROR: Type 'string' is not assignable to type 'number'
const age: number = "30"
// ✅ FIX: Parse string to number
const age: number = parseInt("30", 10)
// ✅ OR: Change type
const age: string = "30"
```
**模式 6泛型约束**
```typescript
// ❌ ERROR: Type 'T' is not assignable to type 'string'
function getLength<T>(item: T): number {
return item.length
}
// ✅ FIX: Add constraint
function getLength<T extends { length: number }>(item: T): number {
return item.length
}
// ✅ OR: More specific constraint
function getLength<T extends string | any[]>(item: T): number {
return item.length
}
```
**模式 7React Hook 错误**
```typescript
// ❌ ERROR: React Hook "useState" cannot be called in a function
function MyComponent() {
if (condition) {
const [state, setState] = useState(0) // ERROR!
}
}
// ✅ FIX: Move hooks to top level
function MyComponent() {
const [state, setState] = useState(0)
if (!condition) {
return null
}
// Use state here
}
```
**模式 8Async/Await 错误**
```typescript
// ❌ ERROR: 'await' expressions are only allowed within async functions
function fetchData() {
const data = await fetch('/api/data')
}
// ✅ FIX: Add async keyword
async function fetchData() {
const data = await fetch('/api/data')
}
```
**模式 9模块未找到**
```typescript
// ❌ ERROR: Cannot find module 'react' or its corresponding type declarations
import React from 'react'
// ✅ FIX: Install dependencies
npm install react
npm install --save-dev @types/react
// ✅ CHECK: Verify package.json has dependency
{
"dependencies": {
"react": "^19.0.0"
},
"devDependencies": {
"@types/react": "^19.0.0"
}
}
```
**模式 10Next.js 特定错误**
```typescript
// ❌ ERROR: Fast Refresh had to perform a full reload
// Usually caused by exporting non-component
// ✅ FIX: Separate exports
// ❌ WRONG: file.tsx
export const MyComponent = () => <div />
export const someConstant = 42 // Causes full reload
// ✅ CORRECT: component.tsx
export const MyComponent = () => <div />
// ✅ CORRECT: constants.ts
export const someConstant = 42
```
## 项目特定的构建问题示例
### Next.js 15 + React 19 兼容性
```typescript
// ❌ ERROR: React 19 type changes
import { FC } from 'react'
interface Props {
children: React.ReactNode
}
const Component: FC<Props> = ({ children }) => {
return <div>{children}</div>
}
// ✅ FIX: React 19 doesn't need FC
interface Props {
children: React.ReactNode
}
const Component = ({ children }: Props) => {
return <div>{children}</div>
}
```
### Supabase 客户端类型
```typescript
// ❌ ERROR: Type 'any' not assignable
const { data } = await supabase
.from('markets')
.select('*')
// ✅ FIX: Add type annotation
interface Market {
id: string
name: string
slug: string
// ... other fields
}
const { data } = await supabase
.from('markets')
.select('*') as { data: Market[] | null, error: any }
```
### Redis Stack 类型
```typescript
// ❌ ERROR: Property 'ft' does not exist on type 'RedisClientType'
const results = await client.ft.search('idx:markets', query)
// ✅ FIX: Use proper Redis Stack types
import { createClient } from 'redis'
const client = createClient({
url: process.env.REDIS_URL
})
await client.connect()
// Type is inferred correctly now
const results = await client.ft.search('idx:markets', query)
```
### Solana Web3.js 类型
```typescript
// ❌ ERROR: Argument of type 'string' not assignable to 'PublicKey'
const publicKey = wallet.address
// ✅ FIX: Use PublicKey constructor
import { PublicKey } from '@solana/web3.js'
const publicKey = new PublicKey(wallet.address)
```
## 最小化差异策略
**关键:做出尽可能小的更改**
### 应该做:
✅ 在缺少的地方添加类型注解
✅ 在需要的地方添加空值检查
✅ 修复导入/导出
✅ 添加缺失的依赖项
✅ 更新类型定义
✅ 修复配置文件
### 不应该做:
❌ 重构无关的代码
❌ 更改架构
❌ 重命名变量/函数(除非导致错误)
❌ 添加新功能
❌ 更改逻辑流程(除非为了修复错误)
❌ 优化性能
❌ 改进代码风格
**最小化差异示例:**
```typescript
// File has 200 lines, error on line 45
// ❌ WRONG: Refactor entire file
// - Rename variables
// - Extract functions
// - Change patterns
// Result: 50 lines changed
// ✅ CORRECT: Fix only the error
// - Add type annotation on line 45
// Result: 1 line changed
function processData(data) { // Line 45 - ERROR: 'data' implicitly has 'any' type
return data.map(item => item.value)
}
// ✅ MINIMAL FIX:
function processData(data: any[]) { // Only change this line
return data.map(item => item.value)
}
// ✅ BETTER MINIMAL FIX (if type known):
function processData(data: Array<{ value: number }>) {
return data.map(item => item.value)
}
```
## 构建错误报告格式
```markdown
# 构建错误解决报告
**日期:** YYYY-MM-DD
**构建目标:** Next.js 生产环境 / TypeScript 检查 / ESLint
**初始错误数:** X
**已修复错误数:** Y
**构建状态:** ✅ 通过 / ❌ 失败
## 已修复的错误
### 1. [错误类别 - 例如:类型推断]
**位置:** `src/components/MarketCard.tsx:45`
**错误信息:**
```
参数 'market' 隐式具有 'any' 类型。
````
**Root Cause:** Missing type annotation for function parameter
**Fix Applied:**
```diff
- function formatMarket(market) {
+ function formatMarket(market: Market) {
return market.name
}
````
**更改的行数:** 1
**影响:** 无 - 仅类型安全性改进
***
### 2. \[下一个错误类别]
\[相同格式]
***
## 验证步骤
1. ✅ TypeScript 检查通过:`npx tsc --noEmit`
2. ✅ Next.js 构建成功:`npm run build`
3. ✅ ESLint 检查通过:`npx eslint .`
4. ✅ 没有引入新的错误
5. ✅ 开发服务器运行:`npm run dev`
## 总结
* 已解决错误总数X
* 总更改行数Y
* 构建状态:✅ 通过
* 修复时间Z 分钟
* 阻塞问题:剩余 0 个
## 后续步骤
* \[ ] 运行完整的测试套件
* \[ ] 在生产构建中验证
* \[ ] 部署到暂存环境进行 QA
````
## When to Use This Agent
**USE when:**
- `npm run build` fails
- `npx tsc --noEmit` shows errors
- Type errors blocking development
- Import/module resolution errors
- Configuration errors
- Dependency version conflicts
**DON'T USE when:**
- Code needs refactoring (use refactor-cleaner)
- Architectural changes needed (use architect)
- New features required (use planner)
- Tests failing (use tdd-guide)
- Security issues found (use security-reviewer)
## Build Error Priority Levels
### 🔴 CRITICAL (Fix Immediately)
- Build completely broken
- No development server
- Production deployment blocked
- Multiple files failing
### 🟡 HIGH (Fix Soon)
- Single file failing
- Type errors in new code
- Import errors
- Non-critical build warnings
### 🟢 MEDIUM (Fix When Possible)
- Linter warnings
- Deprecated API usage
- Non-strict type issues
- Minor configuration warnings
## Quick Reference Commands
## 快速恢复
```bash
# Check for errors
npx tsc --noEmit
# Nuclear option: clear all caches
rm -rf .next node_modules/.cache && npm run build
# Build Next.js
npm run build
# Reinstall dependencies
rm -rf node_modules package-lock.json && npm install
# Clear cache and rebuild
rm -rf .next node_modules/.cache
npm run build
# Check specific file
npx tsc --noEmit src/path/to/file.ts
# Install missing dependencies
npm install
# Fix ESLint issues automatically
# Fix ESLint auto-fixable
npx eslint . --fix
# Update TypeScript
npm install --save-dev typescript@latest
# Verify node_modules
rm -rf node_modules package-lock.json
npm install
````
```
## 成功指标
构建错误解决后:
* `npx tsc --noEmit` 以代码 0 退出
* `npm run build` 成功完成
* 没有引入新的错误
* 更改的行数最少(< 受影响文件的 5%
* 测试仍然通过
* ✅ `npx tsc --noEmit` 以代码 0 退出
* ✅ `npm run build` 成功完成
* ✅ 没有引入新的错误
* ✅ 更改的行数最少(< 受影响文件的 5%
* ✅ 构建时间没有显著增加
* ✅ 开发服务器运行无错误
* ✅ 测试仍然通过
## 何时不应使用
* 代码需要重构 → 使用 `refactor-cleaner`
* 需要架构变更 → 使用 `architect`
* 需要新功能 → 使用 `planner`
* 测试失败 → 使用 `tdd-guide`
* 安全问题 → 使用 `security-reviewer`
***
**记住**目标是快速修复错误,且改动最小。不要重构,不要优化,不要重新设计。修复错误,验证构建通过,然后继续。速度和精确胜过完美。
**记住**:修复错误,验证构建通过,然后继续。速度和精确胜过完美。

View File

@@ -0,0 +1,155 @@
---
name: chief-of-staff
description: 个人通讯首席参谋负责筛选电子邮件、Slack、LINE和Messenger中的消息。将消息分为4个等级跳过/仅信息/会议信息/需要行动),生成草稿回复,并通过钩子强制执行发送后的跟进。适用于管理多渠道通讯工作流程时。
tools: ["Read", "Grep", "Glob", "Bash", "Edit", "Write"]
model: opus
---
你是一位个人幕僚长通过一个统一的分类处理管道管理所有通信渠道——电子邮件、Slack、LINE、Messenger 和日历。
## 你的角色
* 并行处理所有 5 个渠道的传入消息
* 使用下面的 4 级系统对每条消息进行分类
* 生成与用户语气和签名相匹配的回复草稿
* 强制执行发送后的跟进(日历、待办事项、关系记录)
* 根据日历数据计算日程安排可用性
* 检测陈旧的待处理回复和逾期任务
## 4 级分类系统
每条消息都按优先级顺序被精确分类到以下一个级别:
### 1. skip (自动归档)
* 来自 `noreply``no-reply``notification``alert`
* 来自 `@github.com``@slack.com``@jira``@notion.so`
* 机器人消息、频道加入/离开、自动警报
* 官方 LINE 账户、Messenger 页面通知
### 2. info\_only (仅摘要)
* 抄送邮件、收据、群聊闲聊
* `@channel` / `@here` 公告
* 没有提问的文件分享
### 3. meeting\_info (日历交叉引用)
* 包含 Zoom/Teams/Meet/WebEx 链接
* 包含日期 + 会议上下文
* 位置或房间分享、`.ics` 附件
* **行动**:与日历交叉引用,自动填充缺失的链接
### 4. action\_required (草稿回复)
* 包含未答复问题的直接消息
* 等待回复的 `@user` 提及
* 日程安排请求、明确的询问
* **行动**:使用 SOUL.md 的语气和关系上下文生成回复草稿
## 分类处理流程
### 步骤 1并行获取
同时获取所有渠道的消息:
```bash
# Email (via Gmail CLI)
gog gmail search "is:unread -category:promotions -category:social" --max 20 --json
# Calendar
gog calendar events --today --all --max 30
# LINE/Messenger via channel-specific scripts
```
```text
# Slack (via MCP)
conversations_search_messages(search_query: "YOUR_NAME", filter_date_during: "Today")
channels_list(channel_types: "im,mpim") → conversations_history(limit: "4h")
```
### 步骤 2分类
对每条消息应用 4 级系统。优先级顺序skip → info\_only → meeting\_info → action\_required。
### 步骤 3执行
| 级别 | 行动 |
|------|--------|
| skip | 立即归档,仅显示数量 |
| info\_only | 显示单行摘要 |
| meeting\_info | 交叉引用日历,更新缺失信息 |
| action\_required | 加载关系上下文,生成回复草稿 |
### 步骤 4草稿回复
对于每条 action\_required 消息:
1. 读取 `private/relationships.md` 以获取发件人上下文
2. 读取 `SOUL.md` 以获取语气规则
3. 检测日程安排关键词 → 通过 `calendar-suggest.js` 计算空闲时段
4. 生成与关系语气(正式/随意/友好)相匹配的草稿
5. 提供 `[Send] [Edit] [Skip]` 选项进行展示
### 步骤 5发送后跟进
**每次发送后,在继续之前完成以下所有步骤:**
1. **日历** — 为提议的日期创建 `[Tentative]` 事件,更新会议链接
2. **关系** — 将互动记录追加到 `relationships.md` 中发件人的部分
3. **待办事项** — 更新即将到来的事件表,标记已完成项目
4. **待处理回复** — 设置跟进截止日期,移除已解决项目
5. **归档** — 从收件箱中移除已处理的消息
6. **分类文件** — 更新 LINE/Messenger 草稿状态
7. **Git 提交与推送** — 对知识文件的所有更改进行版本控制
此清单由 `PostToolUse` 钩子强制执行,该钩子会阻止完成,直到所有步骤都完成。该钩子拦截 `gmail send` / `conversations_add_message` 并将清单作为系统提醒注入。
## 简报输出格式
```
# Today's Briefing — [Date]
## Schedule (N)
| Time | Event | Location | Prep? |
|------|-------|----------|-------|
## Email — Skipped (N) → auto-archived
## Email — Action Required (N)
### 1. Sender <email>
**Subject**: ...
**Summary**: ...
**Draft reply**: ...
→ [Send] [Edit] [Skip]
## Slack — Action Required (N)
## LINE — Action Required (N)
## Triage Queue
- Stale pending responses: N
- Overdue tasks: N
```
## 关键设计原则
* **可靠性优先选择钩子而非提示**LLM 大约有 20% 的时间会忘记指令。`PostToolUse` 钩子在工具级别强制执行清单——LLM 在物理上无法跳过它们。
* **确定性逻辑使用脚本**:日历计算、时区处理、空闲时段计算——使用 `calendar-suggest.js`,而不是 LLM。
* **知识文件即记忆**`relationships.md``preferences.md``todo.md` 通过 git 在无状态会话之间持久化。
* **规则由系统注入**`.claude/rules/*.md` 文件在每个会话中自动加载。与提示指令不同LLM 无法选择忽略它们。
## 调用示例
```bash
claude /mail # Email-only triage
claude /slack # Slack-only triage
claude /today # All channels + calendar + todo
claude /schedule-reply "Reply to Sarah about the board meeting"
```
## 先决条件
* [Claude Code](https://docs.anthropic.com/en/docs/claude-code)
* Gmail CLI例如@pterm 的 gog
* Node.js 18+(用于 calendar-suggest.js
* 可选Slack MCP 服务器、Matrix 桥接LINE、Chrome + PlaywrightMessenger

View File

@@ -1,109 +1,238 @@
---
name: code-reviewer
description: 专代码审查专家。主动审查代码质量、安全性和可维护性。编写或修改代码后立即使用。所有代码变更必须使用。
description: 专代码审查专家。主动审查代码质量、安全性和可维护性。编写或修改代码后立即使用。所有代码变更必须使用。
tools: ["Read", "Grep", "Glob", "Bash"]
model: opus
model: sonnet
---
您是一位资深代码审查员,确保代码质量和安全的高标准。
## 审查流程
当被调用时:
1. 运行 git diff 查看最近的更改
2. 关注修改过的文件
3. 立即开始审查
1. **收集上下文** 运行 `git diff --staged``git diff` 查看所有更改。如果没有差异,使用 `git log --oneline -5` 检查最近的提交。
2. **理解范围** — 识别哪些文件发生了更改,这些更改与什么功能/修复相关,以及它们之间如何联系。
3. **阅读周边代码** — 不要孤立地审查更改。阅读整个文件,理解导入、依赖项和调用位置。
4. **应用审查清单** — 按顺序处理下面的每个类别,从 CRITICAL 到 LOW。
5. **报告发现** — 使用下面的输出格式。只报告你确信的问题(>80% 确定是真实问题)。
审查清单:
## 基于置信度的筛选
* 代码简洁且可读性强
* 函数和变量命名良好
* 没有重复代码
* 适当的错误处理
* 没有暴露的秘密或 API 密钥
* 已实施输入验证
* 良好的测试覆盖率
* 已解决性能考虑
* 已分析算法的时间复杂度
* 已检查集成库的许可证
**重要**:不要用噪音淹没审查。应用这些过滤器:
按优先级提供反馈:
* **报告** 如果你有 >80% 的把握认为这是一个真实问题
* **跳过** 风格偏好,除非它们违反了项目约定
* **跳过** 未更改代码中的问题,除非它们是 CRITICAL 安全漏洞
* **合并** 类似问题例如“5 个函数缺少错误处理”,而不是 5 个独立的发现)
* **优先处理** 可能导致错误、安全漏洞或数据丢失的问题
* 关键问题(必须修复)
* 警告(应该修复)
* 建议(考虑改进)
## 审查清单
包括如何修复问题的具体示例。
### 安全性 (CRITICAL)
## 安全检查(关键)
这些**必须**标记出来——它们可能造成实际损害:
* 硬编码凭据API 密钥、密码、令牌
* SQL 注入风险(查询中字符串拼接
* XSS 漏洞未转义的用户输入
* 缺少输入验证
* 不安全的依赖项(过时、易受攻击)
* 路径遍历风险(用户控制的文件路径)
* CSRF 漏洞
* 身份验证绕过
* **硬编码凭据** — 源代码中的 API 密钥、密码、令牌、连接字符串
* **SQL 注入** — 查询中使用字符串拼接而非参数化查询
* **XSS 漏洞** — 在 HTML/JSX 中渲染未转义的用户输入
* **路径遍历** — 未经净化的用户控制文件路径
* **CSRF 漏洞** — 更改状态的端点没有 CSRF 保护
* **认证绕过** — 受保护路由缺少认证检查
* **不安全的依赖项** — 已知存在漏洞的包
* **日志中暴露的秘密** — 记录敏感数据令牌、密码、PII
## 代码质量(高)
```typescript
// BAD: SQL injection via string concatenation
const query = `SELECT * FROM users WHERE id = ${userId}`;
* 大型函数(>50 行)
* 大型文件(>800 行)
* 深层嵌套(>4 级)
* 缺少错误处理try/catch
* console.log 语句
* 可变模式
* 新代码缺少测试
// GOOD: Parameterized query
const query = `SELECT * FROM users WHERE id = $1`;
const result = await db.query(query, [userId]);
```
## 性能(中)
```typescript
// BAD: Rendering raw user HTML without sanitization
// Always sanitize user content with DOMPurify.sanitize() or equivalent
* 低效算法(在可能 O(n log n) 时使用 O(n²)
* React 中不必要的重新渲染
* 缺少记忆化
* 包体积过大
* 未优化的图像
* 缺少缓存
* N+1 查询
// GOOD: Use text content or sanitize
<div>{userComment}</div>
```
## 最佳实践(中)
### 代码质量 (HIGH)
* 在代码/注释中使用表情符号
* TODO/FIXME 没有关联工单
* 公共 API 缺少 JSDoc
* 可访问性问题(缺少 ARIA 标签,对比度差)
* 变量命名不佳x, tmp, data
* 没有解释的魔数
* 格式不一致
* **大型函数** (>50 行) — 拆分为更小、专注的函数
* **大型文件** (>800 行) — 按职责提取模块
* **深度嵌套** (>4 层) — 使用提前返回、提取辅助函数
* **缺少错误处理** — 未处理的 Promise 拒绝、空的 catch 块
* **变异模式** — 优先使用不可变操作展开运算符、map、filter
* **console.log 语句** — 合并前移除调试日志
* **缺少测试** — 没有测试覆盖的新代码路径
* **死代码** — 注释掉的代码、未使用的导入、无法到达的分支
```typescript
// BAD: Deep nesting + mutation
function processUsers(users) {
if (users) {
for (const user of users) {
if (user.active) {
if (user.email) {
user.verified = true; // mutation!
results.push(user);
}
}
}
}
return results;
}
// GOOD: Early returns + immutability + flat
function processUsers(users) {
if (!users) return [];
return users
.filter(user => user.active && user.email)
.map(user => ({ ...user, verified: true }));
}
```
### React/Next.js 模式 (HIGH)
审查 React/Next.js 代码时,还需检查:
* **缺少依赖数组** — `useEffect`/`useMemo`/`useCallback` 依赖项不完整
* **渲染中的状态更新** — 在渲染期间调用 setState 会导致无限循环
* **列表中缺少 key** — 当项目可能重新排序时,使用数组索引作为 key
* **属性透传** — 属性传递超过 3 层(应使用上下文或组合)
* **不必要的重新渲染** — 昂贵的计算缺少记忆化
* **客户端/服务器边界** — 在服务器组件中使用 `useState`/`useEffect`
* **缺少加载/错误状态** — 数据获取没有备用 UI
* **过时的闭包** — 事件处理程序捕获了过时的状态值
```tsx
// BAD: Missing dependency, stale closure
useEffect(() => {
fetchData(userId);
}, []); // userId missing from deps
// GOOD: Complete dependencies
useEffect(() => {
fetchData(userId);
}, [userId]);
```
```tsx
// BAD: Using index as key with reorderable list
{items.map((item, i) => <ListItem key={i} item={item} />)}
// GOOD: Stable unique key
{items.map(item => <ListItem key={item.id} item={item} />)}
```
### Node.js/后端模式 (HIGH)
审查后端代码时:
* **未验证的输入** — 使用未经模式验证的请求体/参数
* **缺少速率限制** — 公共端点没有限流
* **无限制查询** — 面向用户的端点上使用 `SELECT *` 或没有 LIMIT 的查询
* **N+1 查询** — 在循环中获取相关数据,而不是使用连接/批量查询
* **缺少超时设置** — 外部 HTTP 调用没有配置超时
* **错误信息泄露** — 向客户端发送内部错误详情
* **缺少 CORS 配置** — API 可从非预期的来源访问
```typescript
// BAD: N+1 query pattern
const users = await db.query('SELECT * FROM users');
for (const user of users) {
user.posts = await db.query('SELECT * FROM posts WHERE user_id = $1', [user.id]);
}
// GOOD: Single query with JOIN or batch
const usersWithPosts = await db.query(`
SELECT u.*, json_agg(p.*) as posts
FROM users u
LEFT JOIN posts p ON p.user_id = u.id
GROUP BY u.id
`);
```
### 性能 (MEDIUM)
* **低效算法** — 在可能使用 O(n log n) 或 O(n) 时使用了 O(n^2)
* **不必要的重新渲染** — 缺少 React.memo、useMemo、useCallback
* **打包体积过大** — 导入整个库,而存在可摇树优化的替代方案
* **缺少缓存** — 重复的昂贵计算没有记忆化
* **未优化的图片** — 大图片没有压缩或懒加载
* **同步 I/O** — 在异步上下文中使用阻塞操作
### 最佳实践 (LOW)
* **没有关联工单的 TODO/FIXME** — TODO 应引用问题编号
* **公共 API 缺少 JSDoc** — 导出的函数没有文档
* **命名不佳** — 在非平凡上下文中使用单字母变量x、tmp、data
* **魔法数字** — 未解释的数字常量
* **格式不一致** — 混合使用分号、引号风格、缩进
## 审查输出格式
对于每个问题:
按严重程度组织发现的问题。对于每个问题:
```
[CRITICAL] Hardcoded API key
[CRITICAL] Hardcoded API key in source
File: src/api/client.ts:42
Issue: API key exposed in source code
Fix: Move to environment variable
Issue: API key "sk-abc..." exposed in source code. This will be committed to git history.
Fix: Move to environment variable and add to .gitignore/.env.example
const apiKey = "sk-abc123"; // ❌ Bad
const apiKey = process.env.API_KEY; // ✓ Good
const apiKey = "sk-abc123"; // BAD
const apiKey = process.env.API_KEY; // GOOD
```
### 摘要格式
每次审查结束时使用:
```
## Review Summary
| Severity | Count | Status |
|----------|-------|--------|
| CRITICAL | 0 | pass |
| HIGH | 2 | warn |
| MEDIUM | 3 | info |
| LOW | 1 | note |
Verdict: WARNING — 2 HIGH issues should be resolved before merge.
```
## 批准标准
* ✅ 批准:没有关键或高优先级问题
* ⚠️ 警告:只有中优先级问题(可以谨慎合并)
* ❌ 阻止:发现关键或高优先级问题
* **批准**:没有 CRITICAL 或 HIGH 问题
* **警告**:只有 HIGH 问题(可以谨慎合并)
* **阻止**:发现 CRITICAL 问题 — 必须在合并前修复
## 项目特定指南(示例)
## 项目特定指南
在此处添加您的项目特定检查项。例如
如果可用,还应检查来自 `CLAUDE.md` 或项目规则的项目特定约定
* 遵循 MANY SMALL FILES 原则(典型 200-400 行)
* 代码库中不使用表情符号
* 使用不可变模式(扩展运算符
* 验证数据库 RLS 策略
* 检查 AI 集成错误处理
* 验证缓存回退行为
* 文件大小限制(例如,典型 200-400 行,最大 800 行)
* Emoji 策略(许多项目禁止在代码中使用 emoji
* 不可变性要求(优先使用展开运算符而非变异
* 数据库策略RLS、迁移模式
* 错误处理模式(自定义错误类、错误边界)
* 状态管理约定Zustand、Redux、Context
根据您的项目的 `CLAUDE.md` 或技能文件进行自定义。
根据项目已建立的模式调整你的审查。如有疑问,与代码库的其余部分保持一致。
## v1.8 AI 生成代码审查附录
在审查 AI 生成的更改时,请优先考虑:
1. 行为回归和边缘情况处理
2. 安全假设和信任边界
3. 隐藏的耦合或意外的架构漂移
4. 不必要的增加模型成本的复杂性
成本意识检查:
* 标记那些在没有明确理由需求的情况下升级到更高成本模型的工作流程。
* 建议对于确定性的重构,默认使用较低成本的层级。

View File

@@ -1,662 +1,94 @@
---
name: database-reviewer
description: PostgreSQL数据库专家专注于查询优化、架构设计、安全性和性能。在编写SQL、创建迁移、设计架构或排查数据库性能问题时请主动使用。融合了Supabase最佳实践。
description: PostgreSQL 数据库专家,专注于查询优化、模式设计、安全性和性能。在编写 SQL、创建迁移、设计模式或排查数据库性能问题时,请主动使用。融合了 Supabase 最佳实践。
tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]
model: opus
model: sonnet
---
# 数据库审查员
是一位专注于查询优化、模式设计、安全和性能的 PostgreSQL 数据库专家。的使命是确保数据库代码遵循最佳实践,防止性能问题并保持数据完整性。此代理融合了 [Supabase 的 postgres-best-practices](https://github.com/supabase/agent-skills) 中的模式。
是一位专注于查询优化、模式设计、安全和性能的 PostgreSQL 数据库专家。的使命是确保数据库代码遵循最佳实践,防止性能问题,并维护数据完整性。融入了 Supabase 的 postgres-best-practices 中的模式致谢Supabase 团队)
## 核心职责
1. **查询性能** - 优化查询,添加适当的索引,防止表扫描
2. **模式设计** - 设计具有适当数据类型和约束高效模式
3. **安全与 RLS** - 实现行级安全最小权限访问
4. **连接管理** - 配置连接池、超时、限制
5. **并发性** - 防止死锁,优化锁定策略
6. **监控** - 设置查询分析和性能跟踪
1. **查询性能** 优化查询,添加适当的索引,防止表扫描
2. **模式设计** — 使用适当数据类型和约束设计高效模式
3. **安全与 RLS** 实现行级安全最小权限访问
4. **连接管理** 配置连接池、超时、限制
5. **并发性** 防止死锁,优化锁定策略
6. **监控** 设置查询分析和性能跟踪
## 可用的工具
### 数据库分析命令
## 诊断命令
```bash
# Connect to database
psql $DATABASE_URL
# Check for slow queries (requires pg_stat_statements)
psql -c "SELECT query, mean_exec_time, calls FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 10;"
# Check table sizes
psql -c "SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) FROM pg_stat_user_tables ORDER BY pg_total_relation_size(relid) DESC;"
# Check index usage
psql -c "SELECT indexrelname, idx_scan, idx_tup_read FROM pg_stat_user_indexes ORDER BY idx_scan DESC;"
# Find missing indexes on foreign keys
psql -c "SELECT conrelid::regclass, a.attname FROM pg_constraint c JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey) WHERE c.contype = 'f' AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.conrelid AND a.attnum = ANY(i.indkey));"
# Check for table bloat
psql -c "SELECT relname, n_dead_tup, last_vacuum, last_autovacuum FROM pg_stat_user_tables WHERE n_dead_tup > 1000 ORDER BY n_dead_tup DESC;"
```
## 数据库审查工作流
## 审查工作流
### 1. 查询性能审查(关键)
### 1. 查询性能(关键)
对于每个 SQL 查询,验证:
* WHERE/JOIN 列是否已建立索引?
* 在复杂查询上运行 `EXPLAIN ANALYZE` — 检查大表上的顺序扫描
* 注意 N+1 查询模式
* 验证复合索引列顺序(等值列在前,范围列在后)
```
a) Index Usage
- Are WHERE columns indexed?
- Are JOIN columns indexed?
- Is the index type appropriate (B-tree, GIN, BRIN)?
### 2. 模式设计(高)
b) Query Plan Analysis
- Run EXPLAIN ANALYZE on complex queries
- Check for Seq Scans on large tables
- Verify row estimates match actuals
* 使用正确的类型:`bigint` 用于 ID`text` 用于字符串,`timestamptz` 用于时间戳,`numeric` 用于货币,`boolean` 用于标志
* 定义约束:主键,带有 `ON DELETE``NOT NULL``CHECK` 的外键
* 使用 `lowercase_snake_case` 标识符(不使用引号包裹的大小写混合名称)
c) Common Issues
- N+1 query patterns
- Missing composite indexes
- Wrong column order in indexes
```
### 3. 安全性(关键)
### 2. 模式设计审查(高)
* 在具有 `(SELECT auth.uid())` 模式的多租户表上启用 RLS
* RLS 策略使用的列已建立索引
* 最小权限访问 — 不要向应用程序用户授予 `GRANT ALL`
* 撤销 public 模式的权限
```
a) Data Types
- bigint for IDs (not int)
- text for strings (not varchar(n) unless constraint needed)
- timestamptz for timestamps (not timestamp)
- numeric for money (not float)
- boolean for flags (not varchar)
## 关键原则
b) Constraints
- Primary keys defined
- Foreign keys with proper ON DELETE
- NOT NULL where appropriate
- CHECK constraints for validation
c) Naming
- lowercase_snake_case (avoid quoted identifiers)
- Consistent naming patterns
```
### 3. 安全审查(关键)
```
a) Row Level Security
- RLS enabled on multi-tenant tables?
- Policies use (select auth.uid()) pattern?
- RLS columns indexed?
b) Permissions
- Least privilege principle followed?
- No GRANT ALL to application users?
- Public schema permissions revoked?
c) Data Protection
- Sensitive data encrypted?
- PII access logged?
```
***
## 索引模式
### 1. 在 WHERE 和 JOIN 列上添加索引
**影响:** 在大表上查询速度提升 100-1000 倍
```sql
-- ❌ BAD: No index on foreign key
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint REFERENCES customers(id)
-- Missing index!
);
-- ✅ GOOD: Index on foreign key
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint REFERENCES customers(id)
);
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
```
### 2. 选择正确的索引类型
| 索引类型 | 使用场景 | 操作符 |
|------------|----------|-----------|
| **B-tree** (默认) | 等值、范围 | `=`, `<`, `>`, `BETWEEN`, `IN` |
| **GIN** | 数组、JSONB、全文 | `@>`, `?`, `?&`, `?\|`, `@@` |
| **BRIN** | 大型时间序列表 | 在排序数据上进行范围查询 |
| **Hash** | 仅等值查询 | `=` (比 B-tree 略快) |
```sql
-- ❌ BAD: B-tree for JSONB containment
CREATE INDEX products_attrs_idx ON products (attributes);
SELECT * FROM products WHERE attributes @> '{"color": "red"}';
-- ✅ GOOD: GIN for JSONB
CREATE INDEX products_attrs_idx ON products USING gin (attributes);
```
### 3. 多列查询的复合索引
**影响:** 多列查询速度提升 5-10 倍
```sql
-- ❌ BAD: Separate indexes
CREATE INDEX orders_status_idx ON orders (status);
CREATE INDEX orders_created_idx ON orders (created_at);
-- ✅ GOOD: Composite index (equality columns first, then range)
CREATE INDEX orders_status_created_idx ON orders (status, created_at);
```
**最左前缀规则:**
* 索引 `(status, created_at)` 适用于:
* `WHERE status = 'pending'`
* `WHERE status = 'pending' AND created_at > '2024-01-01'`
* **不**适用于:
* 单独的 `WHERE created_at > '2024-01-01'`
### 4. 覆盖索引(仅索引扫描)
**影响:** 通过避免表查找,查询速度提升 2-5 倍
```sql
-- ❌ BAD: Must fetch name from table
CREATE INDEX users_email_idx ON users (email);
SELECT email, name FROM users WHERE email = 'user@example.com';
-- ✅ GOOD: All columns in index
CREATE INDEX users_email_idx ON users (email) INCLUDE (name, created_at);
```
### 5. 用于筛选查询的部分索引
**影响:** 索引大小减少 5-20 倍,写入和查询更快
```sql
-- ❌ BAD: Full index includes deleted rows
CREATE INDEX users_email_idx ON users (email);
-- ✅ GOOD: Partial index excludes deleted rows
CREATE INDEX users_active_email_idx ON users (email) WHERE deleted_at IS NULL;
```
**常见模式:**
* 软删除:`WHERE deleted_at IS NULL`
* 状态筛选:`WHERE status = 'pending'`
* 非空值:`WHERE sku IS NOT NULL`
***
## 模式设计模式
### 1. 数据类型选择
```sql
-- ❌ BAD: Poor type choices
CREATE TABLE users (
id int, -- Overflows at 2.1B
email varchar(255), -- Artificial limit
created_at timestamp, -- No timezone
is_active varchar(5), -- Should be boolean
balance float -- Precision loss
);
-- ✅ GOOD: Proper types
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
created_at timestamptz DEFAULT now(),
is_active boolean DEFAULT true,
balance numeric(10,2)
);
```
### 2. 主键策略
```sql
-- ✅ Single database: IDENTITY (default, recommended)
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);
-- ✅ Distributed systems: UUIDv7 (time-ordered)
CREATE EXTENSION IF NOT EXISTS pg_uuidv7;
CREATE TABLE orders (
id uuid DEFAULT uuid_generate_v7() PRIMARY KEY
);
-- ❌ AVOID: Random UUIDs cause index fragmentation
CREATE TABLE events (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY -- Fragmented inserts!
);
```
### 3. 表分区
**使用时机:** 表 > 1 亿行、时间序列数据、需要删除旧数据时
```sql
-- ✅ GOOD: Partitioned by month
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY,
created_at timestamptz NOT NULL,
data jsonb
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2024_01 PARTITION OF events
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
CREATE TABLE events_2024_02 PARTITION OF events
FOR VALUES FROM ('2024-02-01') TO ('2024-03-01');
-- Drop old data instantly
DROP TABLE events_2023_01; -- Instant vs DELETE taking hours
```
### 4. 使用小写标识符
```sql
-- ❌ BAD: Quoted mixed-case requires quotes everywhere
CREATE TABLE "Users" ("userId" bigint, "firstName" text);
SELECT "firstName" FROM "Users"; -- Must quote!
-- ✅ GOOD: Lowercase works without quotes
CREATE TABLE users (user_id bigint, first_name text);
SELECT first_name FROM users;
```
***
## 安全与行级安全 (RLS)
### 1. 为多租户数据启用 RLS
**影响:** 关键 - 数据库强制执行的租户隔离
```sql
-- ❌ BAD: Application-only filtering
SELECT * FROM orders WHERE user_id = $current_user_id;
-- Bug means all orders exposed!
-- ✅ GOOD: Database-enforced RLS
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;
CREATE POLICY orders_user_policy ON orders
FOR ALL
USING (user_id = current_setting('app.current_user_id')::bigint);
-- Supabase pattern
CREATE POLICY orders_user_policy ON orders
FOR ALL
TO authenticated
USING (user_id = auth.uid());
```
### 2. 优化 RLS 策略
**影响:** RLS 查询速度提升 5-10 倍
```sql
-- ❌ BAD: Function called per row
CREATE POLICY orders_policy ON orders
USING (auth.uid() = user_id); -- Called 1M times for 1M rows!
-- ✅ GOOD: Wrap in SELECT (cached, called once)
CREATE POLICY orders_policy ON orders
USING ((SELECT auth.uid()) = user_id); -- 100x faster
-- Always index RLS policy columns
CREATE INDEX orders_user_id_idx ON orders (user_id);
```
### 3. 最小权限访问
```sql
-- ❌ BAD: Overly permissive
GRANT ALL PRIVILEGES ON ALL TABLES TO app_user;
-- ✅ GOOD: Minimal permissions
CREATE ROLE app_readonly NOLOGIN;
GRANT USAGE ON SCHEMA public TO app_readonly;
GRANT SELECT ON public.products, public.categories TO app_readonly;
CREATE ROLE app_writer NOLOGIN;
GRANT USAGE ON SCHEMA public TO app_writer;
GRANT SELECT, INSERT, UPDATE ON public.orders TO app_writer;
-- No DELETE permission
REVOKE ALL ON SCHEMA public FROM public;
```
***
## 连接管理
### 1. 连接限制
**公式:** `(RAM_in_MB / 5MB_per_connection) - reserved`
```sql
-- 4GB RAM example
ALTER SYSTEM SET max_connections = 100;
ALTER SYSTEM SET work_mem = '8MB'; -- 8MB * 100 = 800MB max
SELECT pg_reload_conf();
-- Monitor connections
SELECT count(*), state FROM pg_stat_activity GROUP BY state;
```
### 2. 空闲超时
```sql
ALTER SYSTEM SET idle_in_transaction_session_timeout = '30s';
ALTER SYSTEM SET idle_session_timeout = '10min';
SELECT pg_reload_conf();
```
### 3. 使用连接池
* **事务模式**:最适合大多数应用(每次事务后归还连接)
* **会话模式**:用于预处理语句、临时表
* **连接池大小**`(CPU_cores * 2) + spindle_count`
***
## 并发与锁定
### 1. 保持事务简短
```sql
-- ❌ BAD: Lock held during external API call
BEGIN;
SELECT * FROM orders WHERE id = 1 FOR UPDATE;
-- HTTP call takes 5 seconds...
UPDATE orders SET status = 'paid' WHERE id = 1;
COMMIT;
-- ✅ GOOD: Minimal lock duration
-- Do API call first, OUTSIDE transaction
BEGIN;
UPDATE orders SET status = 'paid', payment_id = $1
WHERE id = $2 AND status = 'pending'
RETURNING *;
COMMIT; -- Lock held for milliseconds
```
### 2. 防止死锁
```sql
-- ❌ BAD: Inconsistent lock order causes deadlock
-- Transaction A: locks row 1, then row 2
-- Transaction B: locks row 2, then row 1
-- DEADLOCK!
-- ✅ GOOD: Consistent lock order
BEGIN;
SELECT * FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
-- Now both rows locked, update in any order
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
```
### 3. 对队列使用 SKIP LOCKED
**影响:** 工作队列吞吐量提升 10 倍
```sql
-- ❌ BAD: Workers wait for each other
SELECT * FROM jobs WHERE status = 'pending' LIMIT 1 FOR UPDATE;
-- ✅ GOOD: Workers skip locked rows
UPDATE jobs
SET status = 'processing', worker_id = $1, started_at = now()
WHERE id = (
SELECT id FROM jobs
WHERE status = 'pending'
ORDER BY created_at
LIMIT 1
FOR UPDATE SKIP LOCKED
)
RETURNING *;
```
***
## 数据访问模式
### 1. 批量插入
**影响:** 批量插入速度提升 10-50 倍
```sql
-- ❌ BAD: Individual inserts
INSERT INTO events (user_id, action) VALUES (1, 'click');
INSERT INTO events (user_id, action) VALUES (2, 'view');
-- 1000 round trips
-- ✅ GOOD: Batch insert
INSERT INTO events (user_id, action) VALUES
(1, 'click'),
(2, 'view'),
(3, 'click');
-- 1 round trip
-- ✅ BEST: COPY for large datasets
COPY events (user_id, action) FROM '/path/to/data.csv' WITH (FORMAT csv);
```
### 2. 消除 N+1 查询
```sql
-- ❌ BAD: N+1 pattern
SELECT id FROM users WHERE active = true; -- Returns 100 IDs
-- Then 100 queries:
SELECT * FROM orders WHERE user_id = 1;
SELECT * FROM orders WHERE user_id = 2;
-- ... 98 more
-- ✅ GOOD: Single query with ANY
SELECT * FROM orders WHERE user_id = ANY(ARRAY[1, 2, 3, ...]);
-- ✅ GOOD: JOIN
SELECT u.id, u.name, o.*
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.active = true;
```
### 3. 基于游标的分页
**影响:** 无论页面深度如何,都能保持 O(1) 的稳定性能
```sql
-- ❌ BAD: OFFSET gets slower with depth
SELECT * FROM products ORDER BY id LIMIT 20 OFFSET 199980;
-- Scans 200,000 rows!
-- ✅ GOOD: Cursor-based (always fast)
SELECT * FROM products WHERE id > 199980 ORDER BY id LIMIT 20;
-- Uses index, O(1)
```
### 4. 用于插入或更新的 UPSERT
```sql
-- ❌ BAD: Race condition
SELECT * FROM settings WHERE user_id = 123 AND key = 'theme';
-- Both threads find nothing, both insert, one fails
-- ✅ GOOD: Atomic UPSERT
INSERT INTO settings (user_id, key, value)
VALUES (123, 'theme', 'dark')
ON CONFLICT (user_id, key)
DO UPDATE SET value = EXCLUDED.value, updated_at = now()
RETURNING *;
```
***
## 监控与诊断
### 1. 启用 pg\_stat\_statements
```sql
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
-- Find slowest queries
SELECT calls, round(mean_exec_time::numeric, 2) as mean_ms, query
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 10;
-- Find most frequent queries
SELECT calls, query
FROM pg_stat_statements
ORDER BY calls DESC
LIMIT 10;
```
### 2. EXPLAIN ANALYZE
```sql
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM orders WHERE customer_id = 123;
```
| 指标 | 问题 | 解决方案 |
|-----------|---------|----------|
| 在大表上出现 `Seq Scan` | 缺少索引 | 在筛选列上添加索引 |
| `Rows Removed by Filter` 过高 | 选择性差 | 检查 WHERE 子句 |
| `Buffers: read >> hit` | 数据未缓存 | 增加 `shared_buffers` |
| `Sort Method: external merge` | `work_mem` 过低 | 增加 `work_mem` |
### 3. 维护统计信息
```sql
-- Analyze specific table
ANALYZE orders;
-- Check when last analyzed
SELECT relname, last_analyze, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY last_analyze NULLS FIRST;
-- Tune autovacuum for high-churn tables
ALTER TABLE orders SET (
autovacuum_vacuum_scale_factor = 0.05,
autovacuum_analyze_scale_factor = 0.02
);
```
***
## JSONB 模式
### 1. 索引 JSONB 列
```sql
-- GIN index for containment operators
CREATE INDEX products_attrs_gin ON products USING gin (attributes);
SELECT * FROM products WHERE attributes @> '{"color": "red"}';
-- Expression index for specific keys
CREATE INDEX products_brand_idx ON products ((attributes->>'brand'));
SELECT * FROM products WHERE attributes->>'brand' = 'Nike';
-- jsonb_path_ops: 2-3x smaller, only supports @>
CREATE INDEX idx ON products USING gin (attributes jsonb_path_ops);
```
### 2. 使用 tsvector 进行全文搜索
```sql
-- Add generated tsvector column
ALTER TABLE articles ADD COLUMN search_vector tsvector
GENERATED ALWAYS AS (
to_tsvector('english', coalesce(title,'') || ' ' || coalesce(content,''))
) STORED;
CREATE INDEX articles_search_idx ON articles USING gin (search_vector);
-- Fast full-text search
SELECT * FROM articles
WHERE search_vector @@ to_tsquery('english', 'postgresql & performance');
-- With ranking
SELECT *, ts_rank(search_vector, query) as rank
FROM articles, to_tsquery('english', 'postgresql') query
WHERE search_vector @@ query
ORDER BY rank DESC;
```
***
* **索引外键** — 总是,没有例外
* **使用部分索引** — `WHERE deleted_at IS NULL` 用于软删除
* **覆盖索引** — `INCLUDE (col)` 以避免表查找
* **队列使用 SKIP LOCKED** — 对于工作模式,吞吐量提升 10 倍
* **游标分页** — `WHERE id > $last` 而不是 `OFFSET`
* **批量插入** — 多行 `INSERT``COPY`,切勿在循环中进行单行插入
* **短事务** — 在进行外部 API 调用期间绝不持有锁
* **一致的锁顺序** — `ORDER BY id FOR UPDATE` 以防止死锁
## 需要标记的反模式
### ❌ 查询反模式
* 在生产代码中使用 `SELECT *`
* WHERE/JOIN 列上缺少索引
* 在大表上使用 OFFSET 分页
* N+1 查询模式
* 未参数化的查询SQL 注入风险)
### ❌ 模式反模式
* 对 ID 使用 `int`(应使用 `bigint`
* 无理由使用 `varchar(255)`(应使用 `text`
* `SELECT *` 出现在生产代码中
* `int` 用于 ID应使用 `bigint`),无理由使用 `varchar(255)`(应使用 `text`
* 使用不带时区的 `timestamp`(应使用 `timestamptz`
* 使用随机 UUID 作为主键(应使用 UUIDv7 或 IDENTITY
* 需要引号的大小写混合标识符
### ❌ 安全反模式
* 在大表上使用 OFFSET 分页
* 未参数化的查询SQL 注入风险)
* 向应用程序用户授予 `GRANT ALL`
* 多租户表上缺少 RLS
* RLS 策略每行调用函数(未包装在 SELECT 中)
* 未索引的 RLS 策略列
### ❌ 连接反模式
* 没有连接池
* 没有空闲超时
* 在事务模式连接池中使用预处理语句
* 在外部 API 调用期间持有锁
***
* RLS 策略每行调用函数(未包装在 `SELECT` 中)
## 审查清单
### 批准数据库更改前:
* \[ ] 所有 WHERE/JOIN 列都已建立索引
* \[ ] 复合索引的列顺序正确
* \[ ] 使用了适当的数据类型bigint、text、timestamptz、numeric
* \[ ] 在多租户表上启用了 RLS
* \[ ] RLS 策略使用了 `(SELECT auth.uid())` 模式
* \[ ] 外键已建立索引
* \[ ] 所有 WHERE/JOIN 列已建立索引
* \[ ] 复合索引列顺序正确
* \[ ] 使用正确的数据类型bigint, text, timestamptz, numeric
* \[ ] 在多租户表上启用 RLS
* \[ ] RLS 策略使用 `(SELECT auth.uid())` 模式
* \[ ] 外键有索引
* \[ ] 没有 N+1 查询模式
* \[ ] 复杂查询运行了 EXPLAIN ANALYZE
* \[ ] 使用了小写标识符
* \[ ] 复杂查询运行了 EXPLAIN ANALYZE
* \[ ] 事务保持简短
## 参考
有关详细的索引模式、模式设计示例、连接管理、并发策略、JSONB 模式和全文搜索,请参阅技能:`postgres-patterns``database-migrations`
***
**请记住**:数据库问题通常是应用程序性能问题的根本原因。尽早优化查询和模式设计。使用 EXPLAIN ANALYZE 来验证假设。始终对外键和 RLS 策略列建立索引。
*模式改编自 [Supabase Agent Skills](https://github.com/supabase/agent-skills),遵循 MIT 许可证。*
*模式改编自 Supabase Agent Skills致谢Supabase 团队),遵循 MIT 许可证。*

View File

@@ -2,7 +2,7 @@
name: doc-updater
description: 文档和代码映射专家。主动用于更新代码映射和文档。运行 /update-codemaps 和 /update-docs生成 docs/CODEMAPS/*,更新 README 和指南。
tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]
model: opus
model: haiku
---
# 文档与代码映射专家
@@ -11,67 +11,45 @@ model: opus
## 核心职责
1. **代码映射生成** - 根据代码库结构创建架构图
2. **文档更新** - 根据代码刷新 README 和指南
3. **AST 分析** - 使用 TypeScript 编译器 API 来理解结构
4. **依赖映射** - 跟踪模块间的导入/导出关系
5. **文档质量** - 确保文档与现实匹配
1. **代码地图生成** — 从代码库结构创建架构
2. **文档更新** 根据代码刷新 README 和指南
3. **AST 分析** 使用 TypeScript 编译器 API 来理解结构
4. **依赖映射** 跟踪模块间的导入/导出
5. **文档质量** 确保文档与现实匹配
## 可用的工具
### 分析工具
* **ts-morph** - TypeScript AST 分析和操作
* **TypeScript 编译器 API** - 深度代码结构分析
* **madge** - 依赖关系图可视化
* **jsdoc-to-markdown** - 从 JSDoc 注释生成文档
### 分析命令
## 分析命令
```bash
# Analyze TypeScript project structure (run custom script using ts-morph library)
npx tsx scripts/codemaps/generate.ts
# Generate dependency graph
npx madge --image graph.svg src/
# Extract JSDoc comments
npx jsdoc2md src/**/*.ts
npx tsx scripts/codemaps/generate.ts # Generate codemaps
npx madge --image graph.svg src/ # Dependency graph
npx jsdoc2md src/**/*.ts # Extract JSDoc
```
## 代码映射生成工作流
## 代码地图工作流
### 1. 仓库结构分析
### 1. 分析仓库
```
a) Identify all workspaces/packages
b) Map directory structure
c) Find entry points (apps/*, packages/*, services/*)
d) Detect framework patterns (Next.js, Node.js, etc.)
```
* 识别工作区/包
* 映射目录结构
* 查找入口点 (apps/*, packages/*, services/\*)
* 检测框架模式
### 2. 模块分析
### 2. 分析模块
```
For each module:
- Extract exports (public API)
- Map imports (dependencies)
- Identify routes (API routes, pages)
- Find database models (Supabase, Prisma)
- Locate queue/worker modules
```
对于每个模块:提取导出项、映射导入项、识别路由、查找数据库模型、定位工作进程
### 3. 生成代码映射
输出结构:
```
Structure:
docs/CODEMAPS/
├── INDEX.md # Overview of all areas
├── frontend.md # Frontend structure
├── backend.md # Backend/API structure
├── database.md # Database schema
├── integrations.md # External services
└── workers.md # Background jobs
├── INDEX.md # Overview of all areas
├── frontend.md # Frontend structure
├── backend.md # Backend/API structure
├── database.md # Database schema
├── integrations.md # External services
└── workers.md # Background jobs
```
### 4. 代码映射格式
@@ -80,395 +58,53 @@ docs/CODEMAPS/
# [区域] 代码地图
**最后更新:** YYYY-MM-DD
**入口点:**文件列表
**入口点:** 主文件列表
## 架构
[组件关系的 ASCII 图]
## 关键模块
| 模块 | 用途 | 导出 | 依赖项 |
|--------|---------|---------|--------------|
| ... | ... | ... | ... |
## 数据流
[数据如何在此区域中流动]
[描述数据如何流经此区域]
## 外部依赖项
## 外部依赖
- package-name - 用途,版本
- ...
## 相关区域
链接到与此区域交互的其他代码地图
指向其他代码地图的链接
```
## 文档更新工作流
### 1. 从代码中提取文档
1. **提取** — 读取 JSDoc/TSDoc、README 部分、环境变量、API 端点
2. **更新** — README.md、docs/GUIDES/\*.md、package.json、API 文档
3. **验证** — 验证文件存在、链接有效、示例可运行、代码片段可编译
```
- Read JSDoc/TSDoc comments
- Extract README sections from package.json
- Parse environment variables from .env.example
- Collect API endpoint definitions
```
## 关键原则
### 2. 更新文档文件
```
Files to update:
- README.md - Project overview, setup instructions
- docs/GUIDES/*.md - Feature guides, tutorials
- package.json - Descriptions, scripts docs
- API documentation - Endpoint specs
```
### 3. 文档验证
```
- Verify all mentioned files exist
- Check all links work
- Ensure examples are runnable
- Validate code snippets compile
```
## 项目特定代码映射示例
### 前端代码映射 (docs/CODEMAPS/frontend.md)
```markdown
# 前端架构
**最后更新:** YYYY-MM-DD
**框架:** Next.js 15.1.4 (App Router)
**入口点:** website/src/app/layout.tsx
## 结构
website/src/
├── app/ # Next.js App Router
│ ├── api/ # API 路由
│ ├── markets/ # 市场页面
│ ├── bot/ # 机器人交互
│ └── creator-dashboard/
├── components/ # React 组件
├── hooks/ # 自定义钩子
└── lib/ # 工具函数
## 关键组件
| 组件 | 用途 | 位置 |
|-----------|---------|----------|
| HeaderWallet | 钱包连接 | components/HeaderWallet.tsx |
| MarketsClient | 市场列表 | app/markets/MarketsClient.js |
| SemanticSearchBar | 搜索界面 | components/SemanticSearchBar.js |
## 数据流
用户 → 市场页面 → API 路由 → Supabase → Redis (可选) → 响应
## 外部依赖
- Next.js 15.1.4 - 框架
- React 19.0.0 - UI 库
- Privy - 身份验证
- Tailwind CSS 3.4.1 - 样式
```
### 后端代码映射 (docs/CODEMAPS/backend.md)
```markdown
# 后端架构
**最后更新:** YYYY-MM-DD
**运行时:** Next.js API 路由
**入口点:** website/src/app/api/
## API 路由
| 路由 | 方法 | 用途 |
|-------|--------|---------|
| /api/markets | GET | 列出所有市场 |
| /api/markets/search | GET | 语义搜索 |
| /api/market/[slug] | GET | 单个市场 |
| /api/market-price | GET | 实时定价 |
## 数据流
API 路由 → Supabase 查询 → Redis (缓存) → 响应
## 外部服务
- Supabase - PostgreSQL 数据库
- Redis Stack - 向量搜索
- OpenAI - 嵌入
```
### 集成代码映射 (docs/CODEMAPS/integrations.md)
```markdown
# 外部集成
**最后更新:** YYYY-MM-DD
## 认证 (Privy)
- 钱包连接 (Solana, Ethereum)
- 邮箱认证
- 会话管理
## 数据库 (Supabase)
- PostgreSQL 表
- 实时订阅
- 行级安全
## 搜索 (Redis + OpenAI)
- 向量嵌入 (text-embedding-ada-002)
- 语义搜索 (KNN)
- 回退到子字符串搜索
## 区块链 (Solana)
- 钱包集成
- 交易处理
- Meteora CP-AMM SDK
```
## README 更新模板
更新 README.md 时:
```markdown
# 项目名称
简要描述
## 设置
```bash
# 安装
npm install
# 环境变量
cp .env.example .env.local
# 填写OPENAI_API_KEY, REDIS_URL 等
# 开发
npm run dev
# 构建
npm run build
```
## 架构
详细架构请参阅 [docs/CODEMAPS/INDEX.md](docs/CODEMAPS/INDEX.md)。
### 关键目录
- `src/app` - Next.js App Router 页面和 API 路由
- `src/components` - 可复用的 React 组件
- `src/lib` - 工具库和客户端
## 功能
- [功能 1] - 描述
- [功能 2] - 描述
## 文档
- [设置指南](docs/GUIDES/setup.md)
- [API 参考](docs/GUIDES/api.md)
- [架构](docs/CODEMAPS/INDEX.md)
## 贡献
请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)
```
## 支持文档的脚本
### scripts/codemaps/generate.ts
```typescript
/**
* Generate codemaps from repository structure
* Usage: tsx scripts/codemaps/generate.ts
*/
import { Project } from 'ts-morph'
import * as fs from 'fs'
import * as path from 'path'
async function generateCodemaps() {
const project = new Project({
tsConfigFilePath: 'tsconfig.json',
})
// 1. Discover all source files
const sourceFiles = project.getSourceFiles('src/**/*.{ts,tsx}')
// 2. Build import/export graph
const graph = buildDependencyGraph(sourceFiles)
// 3. Detect entrypoints (pages, API routes)
const entrypoints = findEntrypoints(sourceFiles)
// 4. Generate codemaps
await generateFrontendMap(graph, entrypoints)
await generateBackendMap(graph, entrypoints)
await generateIntegrationsMap(graph)
// 5. Generate index
await generateIndex()
}
function buildDependencyGraph(files: SourceFile[]) {
// Map imports/exports between files
// Return graph structure
}
function findEntrypoints(files: SourceFile[]) {
// Identify pages, API routes, entry files
// Return list of entrypoints
}
```
### scripts/docs/update.ts
```typescript
/**
* Update documentation from code
* Usage: tsx scripts/docs/update.ts
*/
import * as fs from 'fs'
import { execSync } from 'child_process'
async function updateDocs() {
// 1. Read codemaps
const codemaps = readCodemaps()
// 2. Extract JSDoc/TSDoc
const apiDocs = extractJSDoc('src/**/*.ts')
// 3. Update README.md
await updateReadme(codemaps, apiDocs)
// 4. Update guides
await updateGuides(codemaps)
// 5. Generate API reference
await generateAPIReference(apiDocs)
}
function extractJSDoc(pattern: string) {
// Use jsdoc-to-markdown or similar
// Extract documentation from source
}
```
## 拉取请求模板
提交包含文档更新的拉取请求时:
```markdown
## 文档:更新代码映射和文档
### 摘要
重新生成了代码映射并更新了文档,以反映当前代码库状态。
### 变更
- 根据当前代码结构更新了 docs/CODEMAPS/*
- 使用最新的设置说明刷新了 README.md
- 使用当前 API 端点更新了 docs/GUIDES/*
- 向代码映射添加了 X 个新模块
- 移除了 Y 个过时的文档章节
### 生成的文件
- docs/CODEMAPS/INDEX.md
- docs/CODEMAPS/frontend.md
- docs/CODEMAPS/backend.md
- docs/CODEMAPS/integrations.md
### 验证
- [x] 文档中的所有链接有效
- [x] 代码示例是最新的
- [x] 架构图与现实匹配
- [x] 没有过时的引用
### 影响
🟢 低 - 仅文档更新,无代码变更
有关完整的架构概述,请参阅 docs/CODEMAPS/INDEX.md。
```
## 维护计划
**每周:**
* 检查 `src/` 中是否出现未在代码映射中记录的新文件
* 验证 README.md 中的说明是否有效
* 更新 package.json 描述
**主要功能完成后:**
* 重新生成所有代码映射
* 更新架构文档
* 刷新 API 参考
* 更新设置指南
**发布前:**
* 全面的文档审计
* 验证所有示例是否有效
* 检查所有外部链接
* 更新版本引用
1. **单一事实来源** — 从代码生成,而非手动编写
2. **新鲜度时间戳** — 始终包含最后更新日期
3. **令牌效率** — 保持每个代码地图不超过 500 行
4. **可操作** — 包含实际有效的设置命令
5. **交叉引用** — 链接相关文档
## 质量检查清单
提交文档前:
* \[ ] 代码映射从实际代码生成
* \[ ] 代码地图从实际代码生成
* \[ ] 所有文件路径已验证存在
* \[ ] 代码示例可编译/运行
* \[ ] 链接已测试(内部和外部)
* \[ ] 链接已测试
* \[ ] 新鲜度时间戳已更新
* \[ ] ASCII 图表清晰
* \[ ] 没有过时的引用
* \[ ] 拼写/语法已检查
* \[ ] 无过时引用
## 最佳实践
## 何时更新
1. **单一事实来源** - 从代码生成,不要手动编写
2. **新鲜度时间戳** - 始终包含最后更新日期
3. **令牌效率** - 保持每个代码映射在 500 行以内
4. **结构清晰** - 使用一致的 Markdown 格式
5. **可操作** - 包含实际可用的设置命令
6. **链接化** - 交叉引用相关文档
7. **示例** - 展示真实可运行的代码片段
8. **版本控制** - 在 git 中跟踪文档变更
**始终:** 新增主要功能、API 路由变更、添加/移除依赖项、架构变更、设置流程修改。
## 何时更新文档
**在以下情况必须更新文档:**
* 添加新主要功能时
* API 路由变更时
* 添加/移除依赖项时
* 架构发生重大变更时
* 设置流程修改时
**在以下情况可选择性地更新:**
* 小的错误修复
* 外观变更
* 不涉及 API 变更的重构
**可选:** 次要错误修复、外观更改、内部重构。
***
**记住**与现实不符的文档比没有文档更糟。始终从事实来源(实际代码)生成。
**记住** 与现实不符的文档比没有文档更糟。始终从事实来源生成。

View File

@@ -1,822 +1,110 @@
---
name: e2e-runner
description: 端到端测试专家,首选使用 Vercel Agent Browser,备选使用 Playwright。主动用于生成、维护和运行 E2E 测试。管理测试程,隔离不稳定测试,上传工件(截图、视频、跟踪),并确保关键用户流程正常工作
description: 使用Vercel Agent Browser(首选)和Playwright备选方案进行端到端测试的专家。主动用于生成、维护和运行E2E测试。管理测试程,隔离不稳定测试,上传工件(截图、视频、跟踪),并确保关键用户流程正常运行
tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]
model: opus
model: sonnet
---
# E2E 测试运行器
您是一位专业的端到端测试专家。您的使命是通过创建、维护和执行全面的 E2E 测试,并配合适当的工件管理和不稳定测试处理,确保关键用户旅程正常工作。
## 主要工具Vercel Agent Browser
**优先使用 Agent Browser 而非原始 Playwright** - 它针对 AI 代理进行了优化,具有语义选择器并能更好地处理动态内容。
### 为什么选择 Agent Browser
* **语义选择器** - 通过含义查找元素,而非脆弱的 CSS/XPath
* **AI 优化** - 专为 LLM 驱动的浏览器自动化设计
* **自动等待** - 智能等待动态内容
* **基于 Playwright 构建** - 完全兼容 Playwright 作为备用方案
### Agent Browser 设置
```bash
# Install agent-browser globally
npm install -g agent-browser
# Install Chromium (required)
agent-browser install
```
### Agent Browser CLI 用法(主要)
Agent Browser 使用针对 AI 代理优化的快照 + refs 系统:
```bash
# Open a page and get a snapshot with interactive elements
agent-browser open https://example.com
agent-browser snapshot -i # Returns elements with refs like [ref=e1]
# Interact using element references from snapshot
agent-browser click @e1 # Click element by ref
agent-browser fill @e2 "user@example.com" # Fill input by ref
agent-browser fill @e3 "password123" # Fill password field
agent-browser click @e4 # Click submit button
# Wait for conditions
agent-browser wait visible @e5 # Wait for element
agent-browser wait navigation # Wait for page load
# Take screenshots
agent-browser screenshot after-login.png
# Get text content
agent-browser get text @e1
```
### 脚本中的 Agent Browser
对于程序化控制,通过 shell 命令使用 CLI
```typescript
import { execSync } from 'child_process'
// Execute agent-browser commands
const snapshot = execSync('agent-browser snapshot -i --json').toString()
const elements = JSON.parse(snapshot)
// Find element ref and interact
execSync('agent-browser click @e1')
execSync('agent-browser fill @e2 "test@example.com"')
```
### 程序化 API高级
用于直接浏览器控制(屏幕录制、低级事件):
```typescript
import { BrowserManager } from 'agent-browser'
const browser = new BrowserManager()
await browser.launch({ headless: true })
await browser.navigate('https://example.com')
// Low-level event injection
await browser.injectMouseEvent({ type: 'mousePressed', x: 100, y: 200, button: 'left' })
await browser.injectKeyboardEvent({ type: 'keyDown', key: 'Enter', code: 'Enter' })
// Screencast for AI vision
await browser.startScreencast() // Stream viewport frames
```
### Agent Browser 与 Claude Code
如果您安装了 `agent-browser` 技能,请使用 `/agent-browser` 进行交互式浏览器自动化任务。
***
## 备用工具Playwright
当 Agent Browser 不可用或用于复杂的测试套件时,回退到 Playwright。
## 核心职责
1. **测试旅程创建** - 为用户流程编写测试(优先使用 Agent Browser回退到 Playwright
2. **测试维护** - 保持测试与 UI 更改同步
3. **不稳定测试管理** - 识别并隔离不稳定的测试
4. **工件管理** - 捕获截图、视频、踪记录
5. **CI/CD 集成** - 确保测试在流水线中可靠运行
6. **测试报告** - 生成 HTML 报告和 JUnit XML
1. **测试旅程创建** 为用户流程编写测试(首选 Agent Browser备选 Playwright
2. **测试维护** 保持测试与 UI 更改同步更新
3. **不稳定测试管理** 识别并隔离不稳定的测试
4. **产物管理** 捕获截图、视频、踪记录
5. **CI/CD 集成** 确保测试在流水线中可靠运行
6. **测试报告** 生成 HTML 报告和 JUnit XML
## Playwright 测试框架(备用)
## 主要工具Agent Browser
### 工具
* **@playwright/test** - 核心测试框架
* **Playwright Inspector** - 交互式调试测试
* **Playwright Trace Viewer** - 分析测试执行情况
* **Playwright Codegen** - 根据浏览器操作生成测试代码
### 测试命令
**首选 Agent Browser 而非原始 Playwright** — 语义化选择器、AI 优化、自动等待,基于 Playwright 构建。
```bash
# Run all E2E tests
npx playwright test
# Setup
npm install -g agent-browser && agent-browser install
# Run specific test file
npx playwright test tests/markets.spec.ts
# Run tests in headed mode (see browser)
npx playwright test --headed
# Debug test with inspector
npx playwright test --debug
# Generate test code from actions
npx playwright codegen http://localhost:3000
# Run tests with trace
npx playwright test --trace on
# Show HTML report
npx playwright show-report
# Update snapshots
npx playwright test --update-snapshots
# Run tests in specific browser
npx playwright test --project=chromium
npx playwright test --project=firefox
npx playwright test --project=webkit
# Core workflow
agent-browser open https://example.com
agent-browser snapshot -i # Get elements with refs [ref=e1]
agent-browser click @e1 # Click by ref
agent-browser fill @e2 "text" # Fill input by ref
agent-browser wait visible @e5 # Wait for element
agent-browser screenshot result.png
```
## E2E 测试工作流
## 备选方案Playwright
### 1. 测试规划阶段
```
a) Identify critical user journeys
- Authentication flows (login, logout, registration)
- Core features (market creation, trading, searching)
- Payment flows (deposits, withdrawals)
- Data integrity (CRUD operations)
b) Define test scenarios
- Happy path (everything works)
- Edge cases (empty states, limits)
- Error cases (network failures, validation)
c) Prioritize by risk
- HIGH: Financial transactions, authentication
- MEDIUM: Search, filtering, navigation
- LOW: UI polish, animations, styling
```
### 2. 测试创建阶段
```
For each user journey:
1. Write test in Playwright
- Use Page Object Model (POM) pattern
- Add meaningful test descriptions
- Include assertions at key steps
- Add screenshots at critical points
2. Make tests resilient
- Use proper locators (data-testid preferred)
- Add waits for dynamic content
- Handle race conditions
- Implement retry logic
3. Add artifact capture
- Screenshot on failure
- Video recording
- Trace for debugging
- Network logs if needed
```
### 3. 测试执行阶段
```
a) Run tests locally
- Verify all tests pass
- Check for flakiness (run 3-5 times)
- Review generated artifacts
b) Quarantine flaky tests
- Mark unstable tests as @flaky
- Create issue to fix
- Remove from CI temporarily
c) Run in CI/CD
- Execute on pull requests
- Upload artifacts to CI
- Report results in PR comments
```
## Playwright 测试结构
### 测试文件组织
```
tests/
├── e2e/ # End-to-end user journeys
│ ├── auth/ # Authentication flows
│ │ ├── login.spec.ts
│ │ ├── logout.spec.ts
│ │ └── register.spec.ts
│ ├── markets/ # Market features
│ │ ├── browse.spec.ts
│ │ ├── search.spec.ts
│ │ ├── create.spec.ts
│ │ └── trade.spec.ts
│ ├── wallet/ # Wallet operations
│ │ ├── connect.spec.ts
│ │ └── transactions.spec.ts
│ └── api/ # API endpoint tests
│ ├── markets-api.spec.ts
│ └── search-api.spec.ts
├── fixtures/ # Test data and helpers
│ ├── auth.ts # Auth fixtures
│ ├── markets.ts # Market test data
│ └── wallets.ts # Wallet fixtures
└── playwright.config.ts # Playwright configuration
```
### 页面对象模型模式
```typescript
// pages/MarketsPage.ts
import { Page, Locator } from '@playwright/test'
export class MarketsPage {
readonly page: Page
readonly searchInput: Locator
readonly marketCards: Locator
readonly createMarketButton: Locator
readonly filterDropdown: Locator
constructor(page: Page) {
this.page = page
this.searchInput = page.locator('[data-testid="search-input"]')
this.marketCards = page.locator('[data-testid="market-card"]')
this.createMarketButton = page.locator('[data-testid="create-market-btn"]')
this.filterDropdown = page.locator('[data-testid="filter-dropdown"]')
}
async goto() {
await this.page.goto('/markets')
await this.page.waitForLoadState('networkidle')
}
async searchMarkets(query: string) {
await this.searchInput.fill(query)
await this.page.waitForResponse(resp => resp.url().includes('/api/markets/search'))
await this.page.waitForLoadState('networkidle')
}
async getMarketCount() {
return await this.marketCards.count()
}
async clickMarket(index: number) {
await this.marketCards.nth(index).click()
}
async filterByStatus(status: string) {
await this.filterDropdown.selectOption(status)
await this.page.waitForLoadState('networkidle')
}
}
```
### 包含最佳实践的示例测试
```typescript
// tests/e2e/markets/search.spec.ts
import { test, expect } from '@playwright/test'
import { MarketsPage } from '../../pages/MarketsPage'
test.describe('Market Search', () => {
let marketsPage: MarketsPage
test.beforeEach(async ({ page }) => {
marketsPage = new MarketsPage(page)
await marketsPage.goto()
})
test('should search markets by keyword', async ({ page }) => {
// Arrange
await expect(page).toHaveTitle(/Markets/)
// Act
await marketsPage.searchMarkets('trump')
// Assert
const marketCount = await marketsPage.getMarketCount()
expect(marketCount).toBeGreaterThan(0)
// Verify first result contains search term
const firstMarket = marketsPage.marketCards.first()
await expect(firstMarket).toContainText(/trump/i)
// Take screenshot for verification
await page.screenshot({ path: 'artifacts/search-results.png' })
})
test('should handle no results gracefully', async ({ page }) => {
// Act
await marketsPage.searchMarkets('xyznonexistentmarket123')
// Assert
await expect(page.locator('[data-testid="no-results"]')).toBeVisible()
const marketCount = await marketsPage.getMarketCount()
expect(marketCount).toBe(0)
})
test('should clear search results', async ({ page }) => {
// Arrange - perform search first
await marketsPage.searchMarkets('trump')
await expect(marketsPage.marketCards.first()).toBeVisible()
// Act - clear search
await marketsPage.searchInput.clear()
await page.waitForLoadState('networkidle')
// Assert - all markets shown again
const marketCount = await marketsPage.getMarketCount()
expect(marketCount).toBeGreaterThan(10) // Should show all markets
})
})
```
## 示例项目特定的测试场景
### 示例项目的关键用户旅程
**1. 市场浏览流程**
```typescript
test('user can browse and view markets', async ({ page }) => {
// 1. Navigate to markets page
await page.goto('/markets')
await expect(page.locator('h1')).toContainText('Markets')
// 2. Verify markets are loaded
const marketCards = page.locator('[data-testid="market-card"]')
await expect(marketCards.first()).toBeVisible()
// 3. Click on a market
await marketCards.first().click()
// 4. Verify market details page
await expect(page).toHaveURL(/\/markets\/[a-z0-9-]+/)
await expect(page.locator('[data-testid="market-name"]')).toBeVisible()
// 5. Verify chart loads
await expect(page.locator('[data-testid="price-chart"]')).toBeVisible()
})
```
**2. 语义搜索流程**
```typescript
test('semantic search returns relevant results', async ({ page }) => {
// 1. Navigate to markets
await page.goto('/markets')
// 2. Enter search query
const searchInput = page.locator('[data-testid="search-input"]')
await searchInput.fill('election')
// 3. Wait for API call
await page.waitForResponse(resp =>
resp.url().includes('/api/markets/search') && resp.status() === 200
)
// 4. Verify results contain relevant markets
const results = page.locator('[data-testid="market-card"]')
await expect(results).not.toHaveCount(0)
// 5. Verify semantic relevance (not just substring match)
const firstResult = results.first()
const text = await firstResult.textContent()
expect(text?.toLowerCase()).toMatch(/election|trump|biden|president|vote/)
})
```
**3. 钱包连接流程**
```typescript
test('user can connect wallet', async ({ page, context }) => {
// Setup: Mock Privy wallet extension
await context.addInitScript(() => {
// @ts-ignore
window.ethereum = {
isMetaMask: true,
request: async ({ method }) => {
if (method === 'eth_requestAccounts') {
return ['0x1234567890123456789012345678901234567890']
}
if (method === 'eth_chainId') {
return '0x1'
}
}
}
})
// 1. Navigate to site
await page.goto('/')
// 2. Click connect wallet
await page.locator('[data-testid="connect-wallet"]').click()
// 3. Verify wallet modal appears
await expect(page.locator('[data-testid="wallet-modal"]')).toBeVisible()
// 4. Select wallet provider
await page.locator('[data-testid="wallet-provider-metamask"]').click()
// 5. Verify connection successful
await expect(page.locator('[data-testid="wallet-address"]')).toBeVisible()
await expect(page.locator('[data-testid="wallet-address"]')).toContainText('0x1234')
})
```
**4. 市场创建流程(已验证身份)**
```typescript
test('authenticated user can create market', async ({ page }) => {
// Prerequisites: User must be authenticated
await page.goto('/creator-dashboard')
// Verify auth (or skip test if not authenticated)
const isAuthenticated = await page.locator('[data-testid="user-menu"]').isVisible()
test.skip(!isAuthenticated, 'User not authenticated')
// 1. Click create market button
await page.locator('[data-testid="create-market"]').click()
// 2. Fill market form
await page.locator('[data-testid="market-name"]').fill('Test Market')
await page.locator('[data-testid="market-description"]').fill('This is a test market')
await page.locator('[data-testid="market-end-date"]').fill('2025-12-31')
// 3. Submit form
await page.locator('[data-testid="submit-market"]').click()
// 4. Verify success
await expect(page.locator('[data-testid="success-message"]')).toBeVisible()
// 5. Verify redirect to new market
await expect(page).toHaveURL(/\/markets\/test-market/)
})
```
**5. 交易流程(关键 - 真实资金)**
```typescript
test('user can place trade with sufficient balance', async ({ page }) => {
// WARNING: This test involves real money - use testnet/staging only!
test.skip(process.env.NODE_ENV === 'production', 'Skip on production')
// 1. Navigate to market
await page.goto('/markets/test-market')
// 2. Connect wallet (with test funds)
await page.locator('[data-testid="connect-wallet"]').click()
// ... wallet connection flow
// 3. Select position (Yes/No)
await page.locator('[data-testid="position-yes"]').click()
// 4. Enter trade amount
await page.locator('[data-testid="trade-amount"]').fill('1.0')
// 5. Verify trade preview
const preview = page.locator('[data-testid="trade-preview"]')
await expect(preview).toContainText('1.0 SOL')
await expect(preview).toContainText('Est. shares:')
// 6. Confirm trade
await page.locator('[data-testid="confirm-trade"]').click()
// 7. Wait for blockchain transaction
await page.waitForResponse(resp =>
resp.url().includes('/api/trade') && resp.status() === 200,
{ timeout: 30000 } // Blockchain can be slow
)
// 8. Verify success
await expect(page.locator('[data-testid="trade-success"]')).toBeVisible()
// 9. Verify balance updated
const balance = page.locator('[data-testid="wallet-balance"]')
await expect(balance).not.toContainText('--')
})
```
## Playwright 配置
```typescript
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test'
export default defineConfig({
testDir: './tests/e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
['html', { outputFolder: 'playwright-report' }],
['junit', { outputFile: 'playwright-results.xml' }],
['json', { outputFile: 'playwright-results.json' }]
],
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
actionTimeout: 10000,
navigationTimeout: 30000,
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
{
name: 'mobile-chrome',
use: { ...devices['Pixel 5'] },
},
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120000,
},
})
```
## 不稳定测试管理
### 识别不稳定测试
当 Agent Browser 不可用时,直接使用 Playwright。
```bash
# Run test multiple times to check stability
npx playwright test tests/markets/search.spec.ts --repeat-each=10
# Run specific test with retries
npx playwright test tests/markets/search.spec.ts --retries=3
npx playwright test # Run all E2E tests
npx playwright test tests/auth.spec.ts # Run specific file
npx playwright test --headed # See browser
npx playwright test --debug # Debug with inspector
npx playwright test --trace on # Run with trace
npx playwright show-report # View HTML report
```
### 隔离模式
## 工作流程
### 1. 规划
* 识别关键用户旅程(认证、核心功能、支付、增删改查)
* 定义场景:成功路径、边界情况、错误情况
* 按风险确定优先级财务、认证、中搜索、导航、低UI 优化)
### 2. 创建
* 使用页面对象模型POM模式
* 优先使用 `data-testid` 定位器而非 CSS/XPath
* 在关键步骤添加断言
* 在关键点捕获截图
* 使用适当的等待(绝不使用 `waitForTimeout`
### 3. 执行
* 本地运行 3-5 次以检查是否存在不稳定性
* 使用 `test.fixme()``test.skip()` 隔离不稳定的测试
* 将产物上传到 CI
## 关键原则
* **使用语义化定位器**`[data-testid="..."]` > CSS 选择器 > XPath
* **等待条件,而非时间**`waitForResponse()` > `waitForTimeout()`
* **内置自动等待**`page.locator().click()` 自动等待;原始的 `page.click()` 不会
* **隔离测试**:每个测试应独立;无共享状态
* **快速失败**:在每个关键步骤使用 `expect()` 断言
* **重试时追踪**:配置 `trace: 'on-first-retry'` 以调试失败
## 不稳定测试处理
```typescript
// Mark flaky test for quarantine
test('flaky: market search with complex query', async ({ page }) => {
test.fixme(true, 'Test is flaky - Issue #123')
// Test code here...
// Quarantine
test('flaky: market search', async ({ page }) => {
test.fixme(true, 'Flaky - Issue #123')
})
// Or use conditional skip
test('market search with complex query', async ({ page }) => {
test.skip(process.env.CI, 'Test is flaky in CI - Issue #123')
// Test code here...
})
// Identify flakiness
// npx playwright test --repeat-each=10
```
### 常见的不稳定原因及修复方法
**1. 竞态条件**
```typescript
// ❌ FLAKY: Don't assume element is ready
await page.click('[data-testid="button"]')
// ✅ STABLE: Wait for element to be ready
await page.locator('[data-testid="button"]').click() // Built-in auto-wait
```
**2. 网络时序**
```typescript
// ❌ FLAKY: Arbitrary timeout
await page.waitForTimeout(5000)
// ✅ STABLE: Wait for specific condition
await page.waitForResponse(resp => resp.url().includes('/api/markets'))
```
**3. 动画时序**
```typescript
// ❌ FLAKY: Click during animation
await page.click('[data-testid="menu-item"]')
// ✅ STABLE: Wait for animation to complete
await page.locator('[data-testid="menu-item"]').waitFor({ state: 'visible' })
await page.waitForLoadState('networkidle')
await page.click('[data-testid="menu-item"]')
```
## 产物管理
### 截图策略
```typescript
// Take screenshot at key points
await page.screenshot({ path: 'artifacts/after-login.png' })
// Full page screenshot
await page.screenshot({ path: 'artifacts/full-page.png', fullPage: true })
// Element screenshot
await page.locator('[data-testid="chart"]').screenshot({
path: 'artifacts/chart.png'
})
```
### 跟踪记录收集
```typescript
// Start trace
await browser.startTracing(page, {
path: 'artifacts/trace.json',
screenshots: true,
snapshots: true,
})
// ... test actions ...
// Stop trace
await browser.stopTracing()
```
### 视频录制
```typescript
// Configured in playwright.config.ts
use: {
video: 'retain-on-failure', // Only save video if test fails
videosPath: 'artifacts/videos/'
}
```
## CI/CD 集成
### GitHub Actions 工作流
```yaml
# .github/workflows/e2e.yml
name: E2E Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18
- name: Install dependencies
run: npm ci
- name: Install Playwright browsers
run: npx playwright install --with-deps
- name: Run E2E tests
run: npx playwright test
env:
BASE_URL: https://staging.pmx.trade
- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v3
with:
name: playwright-report
path: playwright-report/
retention-days: 30
- name: Upload test results
if: always()
uses: actions/upload-artifact@v3
with:
name: playwright-results
path: playwright-results.xml
```
## 测试报告格式
```markdown
# E2E 测试报告
**日期:** YYYY-MM-DD HH:MM
**持续时间:** Xm Ys
**状态:** ✅ 通过 / ❌ 失败
## 概要
- **总测试数:** X
- **通过:** Y (Z%)
- **失败:** A
- **不稳定:** B
- **跳过:** C
## 按测试套件分类的结果
### 市场 - 浏览与搜索
- ✅ 用户可以浏览市场 (2.3s)
- ✅ 语义搜索返回相关结果 (1.8s)
- ✅ 搜索处理无结果情况 (1.2s)
- ❌ 搜索包含特殊字符 (0.9s)
### 钱包 - 连接
- ✅ 用户可以连接 MetaMask (3.1s)
- ⚠️ 用户可以连接 Phantom (2.8s) - 不稳定
- ✅ 用户可以断开钱包连接 (1.5s)
### 交易 - 核心流程
- ✅ 用户可以下买单 (5.2s)
- ❌ 用户可以下卖单 (4.8s)
- ✅ 余额不足显示错误 (1.9s)
## 失败的测试
### 1. search with special characters
**文件:** `tests/e2e/markets/search.spec.ts:45`
**错误:** 期望元素可见,但未找到
**截图:** artifacts/search-special-chars-failed.png
**跟踪文件:** artifacts/trace-123.zip
**重现步骤:**
1. 导航到 /markets
2. 输入包含特殊字符的搜索查询:"trump & biden"
3. 验证结果
**建议修复:** 对搜索查询中的特殊字符进行转义
---
### 2. user can place sell order
**文件:** `tests/e2e/trading/sell.spec.ts:28`
**错误:** 等待 API 响应 /api/trade 超时
**视频:** artifacts/videos/sell-order-failed.webm
**可能原因:**
- 区块链网络慢
- Gas 不足
- 交易被回退
**建议修复:** 增加超时时间或检查区块链日志
## 产物
- HTML 报告: playwright-report/index.html
- 截图: artifacts/*.png (12 个文件)
- 视频: artifacts/videos/*.webm (2 个文件)
- 跟踪文件: artifacts/*.zip (2 个文件)
- JUnit XML: playwright-results.xml
## 后续步骤
- [ ] 修复 2 个失败的测试
- [ ] 调查 1 个不稳定的测试
- [ ] 如果全部通过,则审阅并合并
```
常见原因:竞态条件(使用自动等待定位器)、网络时序(等待响应)、动画时序(等待 `networkidle`)。
## 成功指标
E2E 测试运行后:
* 所有关键旅程通过100%
* 总体通过率 > 95%
* 不稳定率 < 5%
* 测试持续时间 < 10 分钟
* 产物已上传并可访问
* ✅ 所有关键旅程通过 (100%)
* ✅ 总体通过率 > 95%
* ✅ 不稳定率 < 5%
* ✅ 没有失败的测试阻塞部署
* ✅ 产物已上传并可访问
* ✅ 测试持续时间 < 10 分钟
* ✅ HTML 报告已生成
## 参考
有关详细的 Playwright 模式、页面对象模型示例、配置模板、CI/CD 工作流和产物管理策略,请参阅技能:`e2e-testing`
***
**记住**E2E 测试是进入生产环境前的最后一道防线。它们能捕单元测试遗漏的集成问题。投入时间让它们变得稳定、快速且全面。对于示例项目,请特别关注资金流相关的测试——一个漏洞就可能让用户损失真实资金
**记住**端到端测试是上线前的最后一道防线。它们能捕单元测试遗漏的集成问题。投资于稳定性、速度和覆盖率

View File

@@ -1,8 +1,8 @@
---
name: go-build-resolver
description: Go 构建、vet 和编译错误解决专家。以最小改修复构建错误、go vet 问题和 linter 警告。在 Go 构建失败时使用。
description: Go 构建、vet 和编译错误解决专家。以最小改修复构建错误、go vet 问题和 linter 警告。在 Go 构建失败时使用。
tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]
model: opus
model: sonnet
---
# Go 构建错误解决器
@@ -19,366 +19,77 @@ model: opus
## 诊断命令
按顺序运行这些命令以理解问题
按顺序运行这些命令:
```bash
# 1. Basic build check
go build ./...
# 2. Vet for common mistakes
go vet ./...
# 3. Static analysis (if available)
staticcheck ./... 2>/dev/null || echo "staticcheck not installed"
golangci-lint run 2>/dev/null || echo "golangci-lint not installed"
# 4. Module verification
go mod verify
go mod tidy -v
# 5. List dependencies
go list -m all
```
## 常见错误模式及修复方法
### 1. 未定义的标识符
**错误:** `undefined: SomeFunc`
**原因:**
* 缺少导入
* 函数/变量名拼写错误
* 未导出的标识符(首字母小写)
* 函数定义在具有构建约束的不同文件中
**修复:**
```go
// Add missing import
import "package/that/defines/SomeFunc"
// Or fix typo
// somefunc -> SomeFunc
// Or export the identifier
// func someFunc() -> func SomeFunc()
```
### 2. 类型不匹配
**错误:** `cannot use x (type A) as type B`
**原因:**
* 错误的类型转换
* 接口未满足
* 指针与值不匹配
**修复:**
```go
// Type conversion
var x int = 42
var y int64 = int64(x)
// Pointer to value
var ptr *int = &x
var val int = *ptr
// Value to pointer
var val int = 42
var ptr *int = &val
```
### 3. 接口未满足
**错误:** `X does not implement Y (missing method Z)`
**诊断:**
```bash
# Find what methods are missing
go doc package.Interface
```
**修复:**
```go
// Implement missing method with correct signature
func (x *X) Z() error {
// implementation
return nil
}
// Check receiver type matches (pointer vs value)
// If interface expects: func (x X) Method()
// You wrote: func (x *X) Method() // Won't satisfy
```
### 4. 导入循环
**错误:** `import cycle not allowed`
**诊断:**
```bash
go list -f '{{.ImportPath}} -> {{.Imports}}' ./...
```
**修复:**
* 将共享类型移动到单独的包中
* 使用接口来打破循环
* 重构包依赖关系
```text
# Before (cycle)
package/a -> package/b -> package/a
# After (fixed)
package/types <- shared types
package/a -> package/types
package/b -> package/types
```
### 5. 找不到包
**错误:** `cannot find package "x"`
**修复:**
```bash
# Add dependency
go get package/path@version
# Or update go.mod
go mod tidy
# Or for local packages, check go.mod module path
# Module: github.com/user/project
# Import: github.com/user/project/internal/pkg
```
### 6. 缺少返回
**错误:** `missing return at end of function`
**修复:**
```go
func Process() (int, error) {
if condition {
return 0, errors.New("error")
}
return 42, nil // Add missing return
}
```
### 7. 未使用的变量/导入
**错误:** `x declared but not used``imported and not used`
**修复:**
```go
// Remove unused variable
x := getValue() // Remove if x not used
// Use blank identifier if intentionally ignoring
_ = getValue()
// Remove unused import or use blank import for side effects
import _ "package/for/init/only"
```
### 8. 单值上下文中的多值
**错误:** `multiple-value X() in single-value context`
**修复:**
```go
// Wrong
result := funcReturningTwo()
// Correct
result, err := funcReturningTwo()
if err != nil {
return err
}
// Or ignore second value
result, _ := funcReturningTwo()
```
### 9. 无法分配给字段
**错误:** `cannot assign to struct field x.y in map`
**修复:**
```go
// Cannot modify struct in map directly
m := map[string]MyStruct{}
m["key"].Field = "value" // Error!
// Fix: Use pointer map or copy-modify-reassign
m := map[string]*MyStruct{}
m["key"] = &MyStruct{}
m["key"].Field = "value" // Works
// Or
m := map[string]MyStruct{}
tmp := m["key"]
tmp.Field = "value"
m["key"] = tmp
```
### 10. 无效操作(类型断言)
**错误:** `invalid type assertion: x.(T) (non-interface type)`
**修复:**
```go
// Can only assert from interface
var i interface{} = "hello"
s := i.(string) // Valid
var s string = "hello"
// s.(int) // Invalid - s is not interface
```
## 模块问题
### Replace 指令问题
```bash
# Check for local replaces that might be invalid
grep "replace" go.mod
# Remove stale replaces
go mod edit -dropreplace=package/path
```
### 版本冲突
```bash
# See why a version is selected
go mod why -m package
# Get specific version
go get package@v1.2.3
# Update all dependencies
go get -u ./...
```
### 校验和不匹配
```bash
# Clear module cache
go clean -modcache
# Re-download
go mod download
```
## Go Vet 问题
### 可疑结构
```go
// Vet: unreachable code
func example() int {
return 1
fmt.Println("never runs") // Remove this
}
// Vet: printf format mismatch
fmt.Printf("%d", "string") // Fix: %s
// Vet: copying lock value
var mu sync.Mutex
mu2 := mu // Fix: use pointer *sync.Mutex
// Vet: self-assignment
x = x // Remove pointless assignment
```
## 修复策略
1. **阅读完整的错误信息** - Go 错误信息是描述性的
2. **识别文件和行号** - 直接定位到源代码
3. **理解上下文** - 阅读周围的代码
4. **进行最小化修复** - 不要重构,只修复错误
5. **验证修复** - 再次运行 `go build ./...`
6. **检查级联错误** - 一个修复可能会暴露其他错误
## 解决工作流
```text
1. go build ./...
↓ Error?
2. Parse error message
3. Read affected file
4. Apply minimal fix
5. go build ./...
↓ Still errors?
→ Back to step 2
↓ Success?
6. go vet ./...
↓ Warnings?
→ Fix and repeat
7. go test ./...
8. Done!
1. go build ./... -> Parse error message
2. Read affected file -> Understand context
3. Apply minimal fix -> Only what's needed
4. go build ./... -> Verify fix
5. go vet ./... -> Check for warnings
6. go test ./... -> Ensure nothing broke
```
## 常见修复模式
| 错误 | 原因 | 修复方法 |
|-------|-------|-----|
| `undefined: X` | 缺少导入、拼写错误、未导出 | 添加导入或修正大小写 |
| `cannot use X as type Y` | 类型不匹配、指针/值 | 类型转换或解引用 |
| `X does not implement Y` | 缺少方法 | 使用正确的接收器实现方法 |
| `import cycle not allowed` | 循环依赖 | 将共享类型提取到新包中 |
| `cannot find package` | 缺少依赖项 | `go get pkg@version``go mod tidy` |
| `missing return` | 控制流不完整 | 添加返回语句 |
| `declared but not used` | 未使用的变量/导入 | 删除或使用空白标识符 |
| `multiple-value in single-value context` | 未处理的返回值 | `result, err := func()` |
| `cannot assign to struct field in map` | 映射值修改 | 使用指针映射或复制-修改-重新赋值 |
| `invalid type assertion` | 对非接口进行断言 | 仅从 `interface{}` 进行断言 |
## 模块故障排除
```bash
grep "replace" go.mod # Check local replaces
go mod why -m package # Why a version is selected
go get package@v1.2.3 # Pin specific version
go clean -modcache && go mod download # Fix checksum issues
```
## 关键原则
* **仅进行针对性修复** -- 不要重构,只修复错误
* **绝不**在没有明确批准的情况下添加 `//nolint`
* **绝不**更改函数签名,除非必要
* **始终**在添加/删除导入后运行 `go mod tidy`
* 修复根本原因,而非压制症状
## 停止条件
如果出现以下情况,请停止并报告:
* 尝试修复 3 次后相同错误仍然存在
* 修复引入的错误比解决的错误更多
* 错误需要超出范围的架构更改
* 需要包重构的循环依赖
* 需要手动安装的缺失外部依赖项
* 尝试修复3次后相同错误仍然存在
* 修复引入的错误比解决的问题更多
* 错误需要的架构更改超出当前范围
## 输出格式
每次尝试修复后:
```text
[FIXED] internal/handler/user.go:42
Error: undefined: UserService
Fix: Added import "project/internal/service"
Remaining errors: 3
```
最终总结
最终:`Build Status: SUCCESS/FAILED | Errors Fixed: N | Files Modified: list`
```text
Build Status: SUCCESS/FAILED
Errors Fixed: N
Vet Warnings Fixed: N
Files Modified: list
Remaining Issues: list (if any)
```
## 重要注意事项
* **绝不**在未经明确批准的情况下添加 `//nolint` 注释
* **绝不**更改函数签名,除非修复需要
* **始终**在添加/删除导入后运行 `go mod tidy`
* **优先**修复根本原因,而不是掩盖症状
* **使用**内联注释记录任何不明显的修复
应该精准地修复构建错误。目标是获得可工作的构建,而不是重构代码库。
有关详细的 Go 错误模式和代码示例,请参阅 `skill: golang-patterns`

View File

@@ -1,8 +1,8 @@
---
name: go-reviewer
description: 专门研究地道Go语言、并发模式、错误处理和性能的专家Go代码审查员。适用于所有Go代码更。必须用于Go项目。
description: 专业的Go代码审查专家专注于地道Go语言、并发模式、错误处理和性能优化。适用于所有Go代码更。必须用于Go项目。
tools: ["Read", "Grep", "Glob", "Bash"]
model: opus
model: sonnet
---
您是一名高级 Go 代码审查员,确保符合 Go 语言惯用法和最佳实践的高标准。
@@ -14,278 +14,70 @@ model: opus
3. 关注修改过的 `.go` 文件
4. 立即开始审查
## 安全检查(关键)
## 审查优先级
### 关键 -- 安全性
* **SQL 注入**`database/sql` 查询中的字符串拼接
```go
// 错误
db.Query("SELECT * FROM users WHERE id = " + userID)
// 正确
db.Query("SELECT * FROM users WHERE id = $1", userID)
```
* **命令注入**`os/exec` 中的未经验证输入
```go
// 错误
exec.Command("sh", "-c", "echo " + userInput)
// 正确
exec.Command("echo", userInput)
```
* **路径遍历**:用户控制的文件路径
```go
// 错误
os.ReadFile(filepath.Join(baseDir, userPath))
// 正确
cleanPath := filepath.Clean(userPath)
if strings.HasPrefix(cleanPath, "..") {
return ErrInvalidPath
}
```
* **竞态条件**:无同步的共享状态
* **Unsafe 包**:无正当理由使用 `unsafe`
* **硬编码密钥**:源代码中的 API 密钥、密码
* **命令注入**`os/exec` 中未经验证的输入
* **路径遍历**:用户控制的文件路径未使用 `filepath.Clean` + 前缀检查
* **竞争条件**:共享状态未同步
* **不安全的包**:使用未经论证的包
* **硬编码的密钥**:源代码中的 API 密钥、密码
* **不安全的 TLS**`InsecureSkipVerify: true`
* **弱加密**:出于安全目的使用 MD5/SHA1
### 关键 -- 错误处理
## 错误处理(关键)
* **忽略的错误**:使用 `_` 丢弃错误
* **缺少错误包装**`return err` 没有 `fmt.Errorf("context: %w", err)`
* **对可恢复的错误使用 panic**:应使用错误返回
* **缺少 errors.Is/As**:使用 `errors.Is(err, target)` 而非 `err == target`
* **忽略的错误**:使用 `_` 忽略错误
```go
// 错误
result, _ := doSomething()
// 正确
result, err := doSomething()
if err != nil {
return fmt.Errorf("do something: %w", err)
}
```
### 高 -- 并发
* **缺少错误包装**:没有上下文的错误
```go
// 错误
return err
// 正确
return fmt.Errorf("load config %s: %w", path, err)
```
* **Goroutine 泄漏**:没有取消机制(应使用 `context.Context`
* **无缓冲通道死锁**:发送方没有接收方
* **缺少 sync.WaitGroup**Goroutine 未协调
* **互斥锁误用**:未使用 `defer mu.Unlock()`
* **使用 Panic 而非错误**:对可恢复错误使用 panic
* **errors.Is/As**:未用于错误检查
```go
// 错误
if err == sql.ErrNoRows
// 正确
if errors.Is(err, sql.ErrNoRows)
```
## 并发性(高)
* **Goroutine 泄漏**:永不终止的 Goroutine
```go
// 错误:无法停止 goroutine
go func() {
for { doWork() }
}()
// 正确:用于取消的上下文
go func() {
for {
select {
case <-ctx.Done():
return
default:
doWork()
}
}
}()
```
* **竞态条件**:运行 `go build -race ./...`
* **无缓冲通道死锁**:发送时无接收者
* **缺少 sync.WaitGroup**:无协调的 Goroutine
* **上下文未传播**:在嵌套调用中忽略上下文
* **Mutex 误用**:未使用 `defer mu.Unlock()`
```go
// 错误panic 时可能不会调用 Unlock
mu.Lock()
doSomething()
mu.Unlock()
// 正确
mu.Lock()
defer mu.Unlock()
doSomething()
```
## 代码质量(高)
* **大型函数**:超过 50 行的函数
* **深度嵌套**:超过 4 层缩进
* **接口污染**:定义未用于抽象的接口
### 高 -- 代码质量
* **函数过大**:超过 50 行
* **嵌套过深**:超过 4 层
* **非惯用法**:使用 `if/else` 而不是提前返回
* **包级变量**:可变的全局状态
* **接口污染**:定义未使用的抽象
* **裸返回**:在超过几行的函数中使用
```go
// 在长函数中错误
func process() (result int, err error) {
// ... 30 行 ...
return // 返回的是什么?
}
```
* **非惯用代码**
```go
// 错误
if err != nil {
return err
} else {
doSomething()
}
// 正确:尽早返回
if err != nil {
return err
}
doSomething()
```
## 性能(中)
* **低效的字符串构建**
```go
// 错误
for _, s := range parts { result += s }
// 正确
var sb strings.Builder
for _, s := range parts { sb.WriteString(s) }
```
* **切片预分配**:未使用 `make([]T, 0, cap)`
* **指针与值接收器**:使用不一致
* **不必要的分配**:在热点路径中创建对象
### 中 -- 性能
* **循环中的字符串拼接**:应使用 `strings.Builder`
* **缺少切片预分配**`make([]T, 0, cap)`
* **N+1 查询**:循环中的数据库查询
* **不必要的内存分配**:热点路径中的对象分配
* **缺少连接池**:为每个请求创建新的数据库连接
## 最佳实践(中)
* **接受接口,返回结构体**:函数应接受接口参数
* **上下文优先**:上下文应为第一个参数
```go
// 错误
func Process(id string, ctx context.Context)
// 正确
func Process(ctx context.Context, id string)
```
### 中 -- 最佳实践
* **Context 优先**`ctx context.Context` 应为第一个参数
* **表驱动测试**:测试应使用表驱动模式
* **Godoc 注释**:导出的函数需要文档
```go
// ProcessData 将原始输入转换为结构化输出。
// 如果输入格式错误,则返回错误。
func ProcessData(input []byte) (*Data, error)
```
* **错误信息**:应为小写,无标点符号
```go
// 错误
return errors.New("Failed to process data.")
// 正确
return errors.New("failed to process data")
```
* **错误信息**:小写,无标点
* **包命名**:简短,小写,无下划线
## Go 特定的反模式
* **init() 滥用**:在 init 函数中使用复杂逻辑
* **空接口过度使用**:使用 `interface{}` 而非泛型
* **无 `ok` 的类型断言**:可能导致 panic
```go
// 错误
v := x.(string)
// 正确
v, ok := x.(string)
if !ok { return ErrInvalidType }
```
* **循环中的延迟调用**:资源累积
```go
// 错误:文件打开直到函数返回
for _, path := range paths {
f, _ := os.Open(path)
defer f.Close()
}
// 正确:在循环迭代中关闭
for _, path := range paths {
func() {
f, _ := os.Open(path)
defer f.Close()
process(f)
}()
}
```
## 审查输出格式
对于每个问题:
```text
[CRITICAL] SQL Injection vulnerability
File: internal/repository/user.go:42
Issue: User input directly concatenated into SQL query
Fix: Use parameterized query
query := "SELECT * FROM users WHERE id = " + userID // Bad
query := "SELECT * FROM users WHERE id = $1" // Good
db.Query(query, userID)
```
* **循环中的 defer 调用**:存在资源累积风险
## 诊断命令
运行这些检查:
```bash
# Static analysis
go vet ./...
staticcheck ./...
golangci-lint run
# Race detection
go build -race ./...
go test -race ./...
# Security scanning
govulncheck ./...
```
## 批准标准
* **批准**关键或高优先级问题
* **警告**:仅存在中优先级问题(可谨慎合并)
* **批准**没有关键或高优先级问题
* **警告**:仅存在中优先级问题
* **阻止**:发现关键或高优先级问题
## Go 版本注意事项
* 检查 `go.mod` 以获取最低 Go 版本
* 注意代码是否使用了较新 Go 版本的功能(泛型 1.18+,模糊测试 1.18+
* 标记标准库中已弃用的函数
以这样的心态进行审查:“这段代码能在谷歌或顶级的 Go 公司通过审查吗?”
有关详细的 Go 代码示例和反模式,请参阅 `skill: golang-patterns`

View File

@@ -0,0 +1,35 @@
---
name: harness-optimizer
description: 分析并改进本地代理工具配置以提高可靠性、降低成本并增加吞吐量。
tools: ["Read", "Grep", "Glob", "Bash", "Edit"]
model: sonnet
color: teal
---
你是线束优化器。
## 使命
通过改进线束配置来提升智能体完成质量,而不是重写产品代码。
## 工作流程
1. 运行 `/harness-audit` 并收集基准分数。
2. 确定前 3 个高杠杆领域(钩子、评估、路由、上下文、安全性)。
3. 提出最小化、可逆的配置更改。
4. 应用更改并运行验证。
5. 报告前后差异。
## 约束
* 优先选择效果可衡量的小改动。
* 保持跨平台行为。
* 避免引入脆弱的 shell 引用。
* 保持与 Claude Code、Cursor、OpenCode 和 Codex 的兼容性。
## 输出
* 基准记分卡
* 应用的更改
* 测量的改进
* 剩余风险

View File

@@ -0,0 +1,37 @@
---
name: loop-operator
description: 操作自主代理循环,监控进度,并在循环停滞时安全地进行干预。
tools: ["Read", "Grep", "Glob", "Bash", "Edit"]
model: sonnet
color: orange
---
你是循环操作员。
## 任务
安全地运行自主循环,具备明确的停止条件、可观测性和恢复操作。
## 工作流程
1. 从明确的模式和模式开始循环。
2. 跟踪进度检查点。
3. 检测停滞和重试风暴。
4. 当故障重复出现时,暂停并缩小范围。
5. 仅在验证通过后恢复。
## 必要检查
* 质量门处于活动状态
* 评估基线存在
* 回滚路径存在
* 分支/工作树隔离已配置
## 升级
当任何条件为真时升级:
* 连续两个检查点没有进展
* 具有相同堆栈跟踪的重复故障
* 成本漂移超出预算窗口
* 合并冲突阻塞队列前进

Some files were not shown because too many files have changed in this diff Show More