crafting-rules
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "crafting-rules" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-feb5ec96876eca2396425cec1483204a925b90fc53fa105eca540cc1e829f326. Verify the upstream source and version against https://github.com/frap129/opencode-rules before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Use when creating or modifying OpenCode rules (.md/.mdc files) to customize agent behavior. Triggered when a user wants to create rules, normalize repeated instructions, persist guidance across sessions, or constrain rules to specific files, prompts, environments, or workflows.
Introduction source: third_party · frap129 · 0.0.1 Reference
SkillPi interpretation
- Tasks
- 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.
- Testing
- Not tested
Browse files
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.
Version history
-
v2.0.0
GitHub ↗
Original release notes
**Full Changelog**: https://github.com/frap129/opencode-rules/compare/v0.8.0...v2.0.0
-
v1.0.0
GitHub ↗
Original release notes
## 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 ↗
Original release notes
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 ↗
Original release notes
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 ↗
Original release notes
3 commits | 7 files changed **Bug Fixes** - fix(tui): load sidebar from source entry **Documentation** - docs: Update notes formatting in README.md
Only the five most recent versions are shown. View full version history at the source ↗
Current listing version
0.0.1
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供 OpenCode 规则编写完整指南,帮助用户自定义代理行为
- 覆盖多种触发场景和过滤条件,实用性强
Highlights
- 触发词精准完整,覆盖创建、修改、规范化、持久化等多种场景
- 边界清晰,避免与其他 Skill 重叠
Areas to improve
-
文档长度 Reported severity: Minor
文档内容较丰富,总行数约450行,可能影响阅读体验
Recommendation: 建议增加目录导航或适当拆分为多个子章节
Highlights
- 结构清晰,包含完整的使用指南、字段参考、示例和常见错误
- 提供了详尽的匹配策略和关键字选择建议
Highlights
- 提供了详尽的字段说明和匹配逻辑,参数定义准确
- 覆盖了主要异常场景和常见错误规避建议
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.