crafting-rules
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "crafting-rules":https://skillpi.com/zh/skills/deepskill-feb5ec96876eca2396425cec1483204a925b90fc53fa105eca540cc1e829f326。安装前核对上游来源和版本:https://github.com/frap129/opencode-rules。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
在创建或修改 OpenCode 规则(.md/.mdc 文件)以自定义代理行为时使用。触发场景包括用户希望创建规则、将重复指令规范化、在会话间持久化指导,或将规则限定到特定文件、提示、环境或工作流时。
介绍来源: third_party · frap129 · 0.0.1 参考来源
SkillPi 解读
- 能完成的任务
- 翻译待完成,请参阅来源文档。
- 实测状态
- 未测试
文件浏览
Frontmatter
name: crafting-rules
description: Use when creating or modifying OpenCode rules (.md/.mdc files) that customize agent behavior. Trigger when user wants to create a rule, codify repeated instructions, persist guidance across sessions, or scope rules to specific files, prompts, environments, or workflows.Crafting Rules
Overview
Rules are markdown files with optional YAML frontmatter, injected into the system prompt to guide agent behavior. Scope them with filters or leave unconditional for global standards.
Field Reference
| Field | Type | Category | Purpose |
|---|---|---|---|
globs |
string[] |
Legacy | Apply when any observed file's path matches a pattern |
fileContains |
string | string[] |
Legacy | Apply when an observed file's text contains a literal substring |
keywords |
string[] |
Legacy | Apply when the user's latest prompt matches a keyword |
tools |
string[] |
Legacy | Apply when any listed tool ID is available |
model |
string[] |
Runtime | Match against the current LLM model ID |
agent |
string[] |
Runtime | Match against the current agent type (e.g., programmer) |
command |
string[] |
Runtime | Match against the current slash command (e.g., /plan) |
project |
string[] |
Runtime | Match against detected project tags (e.g., node, rust) |
branch |
string[] |
Runtime | Match against git branch name (supports glob patterns) |
os |
string[] |
Runtime | Match against OS (linux, darwin, win32) |
ci |
boolean |
Runtime | Match against CI environment (true = in CI) |
match |
'any' | 'all' |
Combinator | any (default): OR logic. all: AND logic. |
- All fields are optional; no frontmatter means the rule always applies.
- With
match: any(default), the rule applies if ANY declared condition matches. - With
match: all, the rule applies only if ALL declared conditions match. globsandfileContainsform one file-observation family: when both are declared, the same observed file must satisfy both. The family counts as one condition in the algebra.- File observations come only from successful live Read, Write, Edit, Apply Patch, and path-associated LSP tool events. Grep, Glob, shell, custom/MCP tools, message prose, and historical tool events contribute nothing to
globs/fileContains. - A durable rule first matched by a live file observation takes effect at that earliest dispatch — not on the next user message.
- When a runtime value is unavailable (e.g., no git repo), that dimension is a non-match.
Rule Format
---
globs:
- '**/*.ts'
keywords:
- 'vitest'
model:
- claude-sonnet-4
agent:
- programmer
branch:
- feature/*
match: any
---
# Rule Title
- Write rules as concrete, actionable instructions.
Matching Strategy
- Use
globswhen the rule is about code in specific files/directories. - Use
fileContainswhen the rule targets code patterns inside files (e.g.,unsafe {,TODO: fix); combine withglobsto scope content to file types. - Use
keywordswhen the rule is about a topic that may not include files. - Use
toolswhen the rule depends on specific MCP tools being available. - Use runtime filters (
model,agent,command,project,branch,os,ci) to scope rules to specific environments or workflows. - Use
match: allwhen you need every declared condition to be true (AND logic). - Use
match: any(or omitmatch) when any single condition should trigger (OR logic). - Use no filters for global standards (tone, structure, safety, commit conventions).
Important constraints:
- Keyword matching is case-insensitive word-boundary prefix matching (e.g.,
testmatchestestsandtesting). fileContainsmatching is case-sensitive literal substring matching (metacharacters are literal; literals may span lines). A declaredfileContainswith no valid literal makes the rule never match.- Branch patterns support globs via minimatch (e.g.,
feature/*,release/**). - Missing runtime context (e.g., no git repo for
branch) counts as a non-match for that dimension.
Keyword Selection
Keywords use case-insensitive word-boundary prefix matching — short or generic words over-match.
Denylist: generic nouns (code, file, project, repo, bug, issue, change), common verbs (add, update, remove, fix, make, create, implement), over-broad topics (testing, performance, security, deployment, database, api), single-token abbreviations (ci, cd, db, ui, ux).
Allowlist: tool/framework names (vitest, jest, pytest, playwright, cypress, eslint, prettier, typescript, terraform, kubernetes), compound phrases (unit test, integration test, snapshot test, lint rule, error boundary, api endpoint, rest api), high-intent verbs (refactor, rollback, migrate, deprecate).
Audit checklist:
- Would this keyword appear in prompts where the rule should NOT apply?
- Is it likely to appear as part of another word due to prefix matching?
- Can you scope via globs instead?
- Prefer globs (file-scoped) over denylisted keywords.
- Replace generic keywords with compound phrases or tool names that capture intent.
Extracting Rules from Patterns
Signals a pattern should become a rule:
- Explicit: "always do X", "never do Y", "remember to...", "from now on..."
- Corrections: the user fixes the same agent behavior more than once
- Preferences: consistent style/process guidance (tests, commits, PRs, error handling)
- Frustration indicators: "I told you before", "again"
Analysis questions:
- Is this recurring, or a one-off for the current task?
- Does this apply to specific files, or all work?
- Is there an existing rule/config that already encodes this (AGENTS.md, lint config, Prettier, etc.)?
- Would this conflict with project conventions?
Workflow:
- Identify the behavioral delta (what should change?).
- Determine scope (globs, keywords, or always-on).
- Check existing rules/configs for overlap/conflict.
- Draft the minimal rule (one concept per rule when practical).
- Choose location (global vs project).
Conversation extraction examples:
- User: "Use early returns instead of nested if/else" -> always-on code style rule.
- User: "In unit tests, always use describe/it blocks" -> prefer glob-scoped rule (e.g.,
**/*.{test,spec}.*,**/__tests__/**); if prompt-scoped, use allowlisted keywords likeunit test,vitest,jest(avoidtest/testing). - User repeatedly fixes import ordering -> glob-scoped rule for the relevant languages/files.
Storage Location
~/.config/opencode/rules/: personal preferences you want across projects..opencode/rules/: project/team conventions and repo-specific behavior.
Writing Guidelines
- Use imperative voice: "Do X", "Prefer Y", "Avoid Z".
- Make rules executable: instructions the agent can follow.
- Stay minimal: avoid restating generic best practices.
- Prefer examples over prose when a pattern is subtle.
Examples
Glob-based: TypeScript conventions
---
globs:
- '**/*.ts'
- '**/*.tsx'
---
# TypeScript
- Prefer `type` over `interface` unless you need declaration merging.
- Avoid `any`; use `unknown` and narrow.
File-content rule: unsafe Rust review
---
globs:
- '**/*.rs'
fileContains: 'unsafe {'
---
# Unsafe Rust
- Document every unsafe block with a SAFETY comment.
Keyword-based: unit test guidance (allowlisted terms)
---
keywords:
- 'unit test'
- 'integration test'
- 'vitest'
- 'jest'
---
# Unit Tests
- Follow Arrange-Act-Assert.
- Name tests: `it('should <expected> when <condition>')`.
Unconditional: always-on standards
# Code Style
- Prefer early returns over deep nesting.
- Extract magic numbers to named constants.
Runtime filters with match: all: feature branch development
---
agent:
- programmer
branch:
- feature/*
os:
- linux
- darwin
ci: false
match: all
---
# Feature Branch Dev
- Create atomic commits with clear messages.
- Run tests before pushing.
Common Mistakes
- Using denylisted keywords:
testfires on nearly every prompt — useunit testor globs instead. - Forgetting
match: all: Two filters with default OR means EITHER triggers — addmatch: allfor AND logic. - Assuming globs + fileContains are separate OR conditions: They form one family that ANDs over the same observed file; use
match: allwith other conditions for broader AND logic. - Overloading a single rule: 6+ dimensions are hard to reason about — split into focused rules.
- Duplicating lint/formatter config: Check Prettier/ESLint before adding a style rule.
- Using
cias a keyword: Prefix-matchescircuit,citizen— useci: trueboolean filter instead.
版本历史
-
v2.0.0
GitHub ↗
原版更新说明
**Full Changelog**: https://github.com/frap129/opencode-rules/compare/v0.8.0...v2.0.0
-
v1.0.0
GitHub ↗
原版更新说明
## What's Changed * version 1.0 by @frap129 in https://github.com/frap129/opencode-rules/pull/69 **Full Changelog**: https://github.com/frap129/opencode-rules/compare/v0.8.0...v1.0.0
-
v0.8.0
GitHub ↗
原版更新说明
20 commits | 82 files changed **Breaking Changes** - feat!: remove system-prompt injection in favor of persisted synthetic parts **Features** - feat: deliver pending hook injections transiently on every model dispatch - feat: persist rules as synthetic parts on user messages via chat.message - feat: rebuild injected-part tracking from history and rescan after compaction - feat: add synthetic-injection module for persisted rule parts **Bug Fixes** - fix(runtime): stamp sessionID and messageID onto synthetic parts - fix(runtime): invoke session.messages with its receiver - fix: align message-context to real {info, parts} payload and skip synthetic parts in path extraction - fix(tui): retry unevaluated rule state - fix(tui): preserve in-flight rules refreshes - fix(runtime): capture canonical message context - fix: stop bundling @opentui/solid-js so the TUI plugin loads and stays reactive - fix: consolidate system array in place instead of rebinding to string **Refactoring** - refactor: add injection-tracking state and per-rule matchRules **Documentation** - docs: describe synthetic-part rule delivery and retire silent-message doc - docs: Update AGENTS.md **Tests** - test: lock synthetic-part delivery lifecycle end-to-end
-
v0.7.0
GitHub ↗
原版更新说明
57 commits | 42 files changed **Features** - feat: deliver pending hook injections via system transform - feat: add tool.execute.after handler for PostToolUse hooks - feat: wire PreToolUse hook evaluation into tool.execute.before - feat: add pendingHookInjections to SessionState - feat: add rule-hooks evaluation module - feat: parse hooks frontmatter for PreToolUse/PostToolUse triggers **Bug Fixes** - fix: consolidate multiple system messages into single string for model compatibility - fix(bun-compat): achieve 100% pass rate by eliminating vi.mock and adding dependency injection - fix: improve error consistency, fix cross-module imports, and update tests - fix(deps): align @opentui versions in manifest with lock file (0.1.93→0.1.97) - fix(deps): remove redundant @types/minimatch - fix(deps): add @opentui/* as optional peerDependencies - fix(deps): remove duplicated @opentui/* and solid-js from devDependencies - fix(active-rules-state): throw on invalid sessionId to align with getStateFilePath - fix(message-context): strictly require role === user in extractLatestUserPrompt - fix(tests): eliminate flaky concurrent-writes test by awaiting write promises - fix: narrow sessionID type in onSystemTransform - fix: add fetch-depth 0 to beta release workflow - fix: global block scan and deduplicate rule content per hook evaluation - fix: check PreToolUse block before any queuing or side-effects - fix: clone pendingHookInjections in snapshot() to prevent mutation leaks **Documentation** - docs(utils): explicitly document internal modules not re-exported by facade - docs(utils): clarify barrel file as intentional public API facade - docs: add hook-based triggers to README features and architecture - docs: add hook-based rule triggers documentation **Refactoring** - refactor(error-consistency): add await to write call, fix type duplication, document exception contracts - refactor: fix convention drift, naming, and AI debt across 10 files - refactor(tui): consolidate loadRules and deduplicate metadata display in SidebarContent - refactor(rule-filter): extract repeated condition checks into evaluateConditionChecks helper - refactor: extend utils.ts facade for TUI needs and update cross-package imports - refactor: extract shared hasConditions to rule-metadata and deduplicate callers - refactor(runtime): add completion audit log for hook side-effects - refactor(runtime): replace as any cast with typed OpenCodeClient interface - refactor: standardize I/O boundary error returns to null instead of undefined - refactor(active-rules-state): remove fire-and-forget catch so callers can handle errors - refactor(runtime-context): move debugLog and projectDirectory into BuildFilterContextOptions - refactor: extract shared logWarning helper and remove redundant guard - refactor: remove pass-through wrappers createSessionStore and extractUserPromptFromParts **Tests** - test: add edge case tests for array system message consolidation - test: verify hook run side-effect execution - test: verify PreToolUse block: true throws and prevents execution - test: add explicit test for PreToolUse excluding PostToolUse hooks - test: correct rule-hooks test expectations to match regex semantics **Build & CI** - build: Allow builds for aube - build: switch to NodeNext module resolution for strict ESM enforcement **Styles** - style(tui): add .js extension to cross-package imports from src - style(active-rules-state): rename sessionId to sessionID to match convention - style: add node: prefix to all Node built-in module imports - style: add .js extension to local imports in active-rules-state and rule-discovery - style(test-fixtures): rename duplicate section headers to be unique - style: remove restating comments in rule-discovery, rule-metadata, and active-rules-state
-
v0.6.4
GitHub ↗
原版更新说明
3 commits | 7 files changed **Bug Fixes** - fix(tui): load sidebar from source entry **Documentation** - docs: Update notes formatting in README.md
此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗
当前收录版本
0.0.1
安全与评测信息
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 提供 OpenCode 规则编写完整指南,帮助用户自定义代理行为
- 覆盖多种触发场景和过滤条件,实用性强
亮点
- 触发词精准完整,覆盖创建、修改、规范化、持久化等多种场景
- 边界清晰,避免与其他 Skill 重叠
待提升项
-
文档长度 原报告严重程度:轻微
文档内容较丰富,总行数约450行,可能影响阅读体验
改进建议:建议增加目录导航或适当拆分为多个子章节
亮点
- 结构清晰,包含完整的使用指南、字段参考、示例和常见错误
- 提供了详尽的匹配策略和关键字选择建议
亮点
- 提供了详尽的字段说明和匹配逻辑,参数定义准确
- 覆盖了主要异常场景和常见错误规避建议
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。