diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..f936c19 --- /dev/null +++ b/.npmignore @@ -0,0 +1,14 @@ +# Exclusions handled by package.json "files" negation patterns +# This file is kept for documentation purposes + +# Test files - excluded via !src/**/*.test.ts, !tui/**/*.test.ts patterns +# *.test.ts +# *.test.tsx +# *.spec.ts +# *.spec.tsx + +# Test fixtures - excluded via !src/test-fixtures.ts +# src/test-fixtures.ts + +# Compile-time type checks - excluded via !src/api-surface.typecheck.ts +# src/api-surface.typecheck.ts diff --git a/README.md b/README.md index f50e75b..673f2da 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,9 @@ This approach allows you to dynamically include rules automatically like style g guidance on specific actions, etc. Unlike skills, which are called on by the agent, rules use a simple matching approach. +> _Note:_ The name `opencode-rules` is to be concise about what this plugin does. It is in no way affiliated with Anomaly Co. or +> the official OpenCode project. + ## Features - **Dual-format support**: Load rules from both `.md` and `.mdc` files @@ -33,11 +36,19 @@ approach. - **Zero-configuration**: Works out of the box with XDG Base Directory specification - **TypeScript-first**: Built with TypeScript for type safety and developer experience - **Performance optimized**: Efficient file discovery and minimal startup overhead +- **TUI sidebar**: Real-time sidebar in the OpenCode TUI showing rule status with active/inactive indicators ## Quick Start ### Installation +```bash +opencode plugin opencode-rules@latest --global +``` + +
+Manual installation + Add the plugin to your opencode config: ```json @@ -47,6 +58,17 @@ Add the plugin to your opencode config: } ``` +To enable the TUI sidebar, add the same plugin entry to your TUI config: + +```json +// ~/.config/opencode/tui.json +{ + "plugin": ["opencode-rules@latest"] +} +``` + +
+ ### Create Your First Rule 1. Create the global rules directory: @@ -69,6 +91,28 @@ Add the plugin to your opencode config: That's it! The rule will now be automatically injected into all AI agent prompts. +## How It Works + +1. **Discovery**: Scan global and project directories for `.md` and `.mdc` files (at plugin init) +2. **Parsing**: Extract metadata from files with YAML front matter +3. **Tool Execution**: `tool.execute.before` hook captures file paths before tools run +4. **Message Flow**: `chat.message` hook updates user prompt as messages arrive +5. **Initial Seeding**: `experimental.chat.messages.transform` extracts context from message history once +6. **Rule Filtering**: `experimental.chat.system.transform` evaluates rules based on context and injects into system prompt +7. **State Persistence**: After filtering, matched rule paths are written to `~/.opencode/state/opencode-rules/{sessionId}.json` for TUI consumption +8. **Compaction Persistence**: `experimental.session.compacting` preserves context during session compression + +## Performance + +- Rule discovery performed once at plugin initialization +- Rule content cached with mtime-based invalidation for fast re-reads +- Incremental session state tracking (set of paths, not message rescanning) +- Per-session state pruned after 100 concurrent sessions to prevent memory growth +- Efficient glob matching with `minimatch` +- Tool-based path capture is non-blocking with minimal overhead +- Session context cleaned up when exceeded (LRU eviction) +- Minimal memory footprint with efficient state management + ## Configuration ### Rule Discovery Locations @@ -85,6 +129,110 @@ Both directories are scanned recursively, allowing you to organize rules into su - `.md` - Standard markdown files with optional metadata - `.mdc` - Markdown files with optional metadata +## Metadata Format + +Both `.md` and `.mdc` files support optional YAML metadata for conditional rule application: + +```yaml +--- +globs: + - 'src/**/*.ts' + - 'lib/**/*.js' +keywords: + - 'refactoring' + - 'cleanup' +tools: + - 'mcp_websearch' + - 'mcp_lsp' +model: + - gpt-5.3-codex + - claude-sonnet-4 +agent: + - programmer +command: + - /plan + - /review +project: + - node + - monorepo +branch: + - main + - feature/* +os: + - linux + - darwin +ci: false +# Matching mode +match: any +--- +``` + +### Supported Fields + +- `globs` (optional): Array of glob patterns for file-based matching + - Rule applies when any file in context matches a pattern +- `keywords` (optional): Array of keywords for prompt-based matching + - Rule applies when the user's prompt contains any keyword + - Case-insensitive, word-boundary matching (e.g., "test" matches "testing") + - Does NOT match mid-word (e.g., "test" does NOT match "contest") +- `tools` (optional): Array of tool IDs for tool-availability matching + - Rule applies when any listed tool is available to the agent + - Uses exact string matching against tool IDs (e.g., `mcp_websearch`, `mcp_bash`) + - Enable debug logging (`OPENCODE_RULES_DEBUG=1`) to see available tool IDs +- `model` (optional): Array of model IDs to match against the current LLM + - Example: `['gpt-5.3-codex', 'claude-sonnet-4']` +- `agent` (optional): Array of agent types to match + - Example: `['programmer', 'planner']` +- `command` (optional): Array of slash commands to match + - Example: `['/plan', '/review']` +- `project` (optional): Array of project type tags to match + - Detected automatically from marker files (e.g., `package.json` -> `node`) + - Supported tags: `node`, `python`, `go`, `rust`, `monorepo`, `browser-extension` +- `branch` (optional): Array of git branch patterns to match + - Supports exact names and glob patterns (e.g., `feature/*`, `release/**`) + - Uses minimatch for glob matching +- `os` (optional): Array of operating systems to match + - Values: `linux`, `darwin`, `win32` +- `ci` (optional): Boolean to match CI environment + - `true` matches when running in CI, `false` matches when not in CI +- `match` (optional): Matching mode for multiple conditions + - `any` (default): Rule applies if ANY declared condition matches + - `all`: Rule applies only if ALL declared conditions match + +**Note:** When a runtime context value is unavailable (e.g., not in a git repository), that dimension is treated as a non-match. + +### Matching Behavior + +- **No metadata**: Rule applies unconditionally (always included) +- **Only globs**: Rule applies when any context file matches +- **Only keywords**: Rule applies when the user's prompt contains any keyword +- **Only tools**: Rule applies when any listed tool is available +- **Multiple conditions with `match: any` (default)**: Rule applies when ANY condition matches (OR logic across all fields) +- **Multiple conditions with `match: all`**: Rule applies only when ALL declared conditions match + +## Glob Pattern Reference + +The plugin uses `minimatch` for pattern matching: + +| Pattern | Matches | +| ----------------------------- | ----------------------------------------------- | +| `src/**/*.ts` | All TypeScript files in src and subdirectories | +| `**/*.test.ts` | All test files at any depth | +| `src/components/**/*.tsx` | React components in components directory | +| `*.json` | JSON files in root directory only | +| `lib/{utils,helpers}/**/*.js` | JavaScript files in specific lib subdirectories | + +## Included Skill: crafting-rules + +This repository includes a `crafting-rules/` skill that teaches AI agents how to create well-formatted rules. The skill provides: + +- **Rule format reference** - Frontmatter fields (`globs`, `keywords`, `tools`, `model`, `agent`, `command`, `project`, `branch`, `os`, `ci`, `match`) and markdown body structure +- **Matching strategy guidance** - When to use globs vs keywords vs runtime filters vs combinations +- **Pattern extraction workflow** - How to identify repeated conversation patterns that should become rules +- **Keyword safety guidelines** - Denylist of overly broad keywords to avoid, allowlist of safe alternatives, and an audit checklist + +To use the skill, copy `skills/crafting-rules/` to `~/.config/opencode/skills/` or reference it directly. The skill triggers when users ask to create rules, codify preferences, or persist guidance across sessions. + ## Usage Examples For real-world examples, see the [`.opencode/rules/`](.opencode/rules/) directory in this repository. @@ -284,117 +432,6 @@ globs: - Co-locate styles with components ``` -## Metadata Format - -Both `.md` and `.mdc` files support optional YAML metadata for conditional rule application: - -```yaml ---- -# Legacy filters -globs: - - 'src/**/*.ts' - - 'lib/**/*.js' -keywords: - - 'refactoring' - - 'cleanup' -tools: - - 'mcp_websearch' - - 'mcp_lsp' -# Runtime environment filters -model: - - gpt-5.3-codex - - claude-sonnet-4 -agent: - - programmer -command: - - /plan - - /review -project: - - node - - monorepo -branch: - - main - - feature/* -os: - - linux - - darwin -ci: false -# Matching mode -match: any ---- -``` - -### Supported Fields - -#### Legacy Filters - -- `globs` (optional): Array of glob patterns for file-based matching - - Rule applies when any file in context matches a pattern -- `keywords` (optional): Array of keywords for prompt-based matching - - Rule applies when the user's prompt contains any keyword - - Case-insensitive, word-boundary matching (e.g., "test" matches "testing") - - Does NOT match mid-word (e.g., "test" does NOT match "contest") -- `tools` (optional): Array of tool IDs for tool-availability matching - - Rule applies when any listed tool is available to the agent - - Uses exact string matching against tool IDs (e.g., `mcp_websearch`, `mcp_bash`) - - Enable debug logging (`OPENCODE_RULES_DEBUG=1`) to see available tool IDs - -#### Runtime Environment Filters - -- `model` (optional): Array of model IDs to match against the current LLM - - Example: `['gpt-5.3-codex', 'claude-sonnet-4']` -- `agent` (optional): Array of agent types to match - - Example: `['programmer', 'planner']` -- `command` (optional): Array of slash commands to match - - Example: `['/plan', '/review']` -- `project` (optional): Array of project type tags to match - - Detected automatically from marker files (e.g., `package.json` -> `node`) - - Supported tags: `node`, `python`, `go`, `rust`, `monorepo`, `browser-extension` -- `branch` (optional): Array of git branch patterns to match - - Supports exact names and glob patterns (e.g., `feature/*`, `release/**`) - - Uses minimatch for glob matching -- `os` (optional): Array of operating systems to match - - Values: `linux`, `darwin`, `win32` -- `ci` (optional): Boolean to match CI environment - - `true` matches when running in CI, `false` matches when not in CI -- `match` (optional): Matching mode for multiple conditions - - `any` (default): Rule applies if ANY declared condition matches - - `all`: Rule applies only if ALL declared conditions match - -**Note:** When a runtime context value is unavailable (e.g., not in a git repository), that dimension is treated as a non-match. - -### Matching Behavior - -- **No metadata**: Rule applies unconditionally (always included) -- **Only globs**: Rule applies when any context file matches -- **Only keywords**: Rule applies when the user's prompt contains any keyword -- **Only tools**: Rule applies when any listed tool is available -- **Multiple conditions with `match: any` (default)**: Rule applies when ANY condition matches (OR logic across all fields) -- **Multiple conditions with `match: all`**: Rule applies only when ALL declared conditions match - -## Glob Pattern Reference - -The plugin uses `minimatch` for pattern matching: - -| Pattern | Matches | -| ----------------------------- | ----------------------------------------------- | -| `src/**/*.ts` | All TypeScript files in src and subdirectories | -| `**/*.test.ts` | All test files at any depth | -| `src/components/**/*.tsx` | React components in components directory | -| `*.json` | JSON files in root directory only | -| `lib/{utils,helpers}/**/*.js` | JavaScript files in specific lib subdirectories | - -## Included Skill: crafting-rules - -This repository includes a `crafting-rules/` skill that teaches AI agents how to create well-formatted rules. The skill provides: - -- **Rule format reference** - Frontmatter fields (`globs`, `keywords`, `tools`, `model`, `agent`, `command`, `project`, `branch`, `os`, `ci`, `match`) and markdown body structure -- **Matching strategy guidance** - When to use globs vs keywords vs runtime filters vs combinations -- **Pattern extraction workflow** - How to identify repeated conversation patterns that should become rules -- **Keyword safety guidelines** - Denylist of overly broad keywords to avoid, allowlist of safe alternatives, and an audit checklist - -To use the skill, copy `skills/crafting-rules/` to `~/.config/opencode/skills/` or reference it directly. The skill triggers when users ask to create rules, codify preferences, or persist guidance across sessions. - ## Development ### Project Structure (Abridged) @@ -417,10 +454,20 @@ opencode-rules/ │ ├── project-fingerprint.ts # Project type detection (Node.js, Python, etc.) │ ├── mcp-tools.ts # MCP tool ID extraction │ ├── git-branch.ts # Git branch detection +│ ├── active-rules-state.ts # Persists matched rules per session for TUI │ ├── debug.ts # Debug logging utilities │ ├── utils.ts # Re-export facade for backwards compatibility │ ├── test-fixtures.ts # Shared test fixtures and builders │ └── *.test.ts # Unit/integration tests (11 test files) +├── tui/ +│ ├── index.tsx # TUI entrypoint, exports { id, tui } +│ ├── slots/ +│ │ └── sidebar-content.tsx # Sidebar widget component +│ ├── data/ +│ │ ├── rules.ts # Rule discovery + formatting for sidebar +│ │ └── rules.test.ts # Data layer tests +│ └── types/ +│ └── opencode-plugin-tui.d.ts # Vendored type shim ├── docs/ │ └── rules.md # Detailed usage documentation ├── openspec/ # Project specifications and proposals @@ -436,15 +483,36 @@ The following highlights the primary runtime modules: - **runtime-chat.ts** - Extracts text from chat message parts for keyword matching - **rule-discovery.ts** - Recursively scans directories for `.md`/`.mdc` rule files - **rule-metadata.ts** - Parses YAML frontmatter into typed `RuleMetadata` -- **rule-filter.ts** - Evaluates rules against context (globs, keywords, tools, runtime filters) +- **rule-filter.ts** - Evaluates rules against context (globs, keywords, tools, runtime filters); returns `FilterResult` with `formattedRules` and `matchedPaths` - **message-paths.ts** - Extracts file paths from tool invocation arguments and message text - **message-context.ts** - Extracts user prompt text, slash commands, and session IDs from message parts - **session-store.ts** - Manages per-session state with LRU eviction - **project-fingerprint.ts** - Detects project type from marker files (e.g., `package.json`) - **mcp-tools.ts** - Maps connected MCP clients to tool IDs for `tools` condition matching - **git-branch.ts** - Resolves current git branch for `branch` condition matching +- **active-rules-state.ts** - Persists which rules matched per session to `~/.opencode/state/opencode-rules/{sessionId}.json` for TUI consumption (atomic writes, per-session queuing) - **utils.ts** - Thin facade re-exporting from decomposed modules +### TUI Sidebar + +The plugin registers a `sidebar_content` slot in the OpenCode TUI, displaying all discovered rules (global and project-local) with their active state and metadata. + +**Requirements:** `@opencode-ai/plugin` ^1.3.7 with TUI support. + +**What it shows:** + +- Collapsible "Project" and "Global" sections grouping rules by scope +- Active/inactive status indicators (green bullet for active, muted for inactive) based on persisted state from the current session +- Condition summary for conditional rules ("always active" for unconditional ones) +- Expandable detail panel with all metadata fields (globs, keywords, tools, model, agent, command, project, branch, os, ci, match) +- Loading, error, and empty states + +**Behavior:** + +- Active rules are sorted to the top within each section +- Subscribes to `message.updated` and `session.status` events for real-time refresh (150ms debounce, filtered by session ID) +- Active state is read from `~/.opencode/state/opencode-rules/{sessionId}.json`, written by the server plugin after each rule evaluation + ### Build and Test ```bash @@ -517,14 +585,6 @@ This plugin uses OpenCode's hook system for incremental, stateful rule injection - Injects current context paths into the compaction context - Prevents rules from being lost during session compression -### Benefits Over Previous Approach - -- **Incremental state tracking** - Builds context incrementally rather than rescanning messages each turn -- **Authoritative path capture** - Tool hooks provide verified file paths directly from the tool definition -- **Real-time responsiveness** - Context updates as tools execute and messages arrive -- **Compaction-aware** - Context persists through session compression -- **Efficient caching** - Rule discovery happens once at startup, not on every LLM call - ### Experimental API Notice This plugin depends on experimental OpenCode APIs: @@ -535,27 +595,6 @@ This plugin depends on experimental OpenCode APIs: These APIs may change in future OpenCode versions. Check OpenCode release notes when upgrading. -## How It Works - -1. **Discovery**: Scan global and project directories for `.md` and `.mdc` files (at plugin init) -2. **Parsing**: Extract metadata from files with YAML front matter -3. **Tool Execution**: `tool.execute.before` hook captures file paths before tools run -4. **Message Flow**: `chat.message` hook updates user prompt as messages arrive -5. **Initial Seeding**: `experimental.chat.messages.transform` extracts context from message history once -6. **Rule Filtering**: `experimental.chat.system.transform` evaluates rules based on context and injects into system prompt -7. **Compaction Persistence**: `experimental.session.compacting` preserves context during session compression - -## Performance - -- Rule discovery performed once at plugin initialization -- Rule content cached with mtime-based invalidation for fast re-reads -- Incremental session state tracking (set of paths, not message rescanning) -- Per-session state pruned after 100 concurrent sessions to prevent memory growth -- Efficient glob matching with `minimatch` -- Tool-based path capture is non-blocking with minimal overhead -- Session context cleaned up when exceeded (LRU eviction) -- Minimal memory footprint with efficient state management - ## Debug Logging To enable debug logging, set the `OPENCODE_RULES_DEBUG` environment variable: diff --git a/eslint.config.js b/eslint.config.js index 2a77604..1a977e2 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -45,4 +45,59 @@ export default [ '@typescript-eslint/no-explicit-any': 'off', }, }, + // TUI production files + { + files: ['tui/**/*.ts', 'tui/**/*.tsx'], + ignores: [ + 'tui/**/*.test.ts', + 'tui/**/*.test.tsx', + 'tui/**/*.spec.ts', + 'tui/**/*.spec.tsx', + ], + languageOptions: { + parser: typescriptParser, + parserOptions: { + ecmaVersion: 2020, + sourceType: 'module', + project: './tsconfig.json', + }, + }, + plugins: { + '@typescript-eslint': typescriptPlugin, + }, + rules: { + ...typescriptPlugin.configs.recommended.rules, + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_' }, + ], + }, + }, + // TUI test files + { + files: [ + 'tui/**/*.test.ts', + 'tui/**/*.test.tsx', + 'tui/**/*.spec.ts', + 'tui/**/*.spec.tsx', + ], + languageOptions: { + parser: typescriptParser, + parserOptions: { + ecmaVersion: 2020, + sourceType: 'module', + }, + }, + plugins: { + '@typescript-eslint': typescriptPlugin, + }, + rules: { + ...typescriptPlugin.configs.recommended.rules, + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_' }, + ], + '@typescript-eslint/no-explicit-any': 'off', + }, + }, ]; diff --git a/package.json b/package.json index debce26..4a7af17 100644 --- a/package.json +++ b/package.json @@ -1,18 +1,22 @@ { "name": "opencode-rules", - "version": "0.5.0", + "version": "0.6.0-beta", "description": "OpenCode plugin that discovers and injects markdown rules into system prompts", - "main": "dist/index.js", - "types": "dist/index.d.ts", + "main": "dist/src/index.js", + "types": "dist/src/index.d.ts", "type": "module", + "oc-plugin": [ + "server", + "tui" + ], "scripts": { "build": "tsc", "dev": "tsc --watch", "test": "vitest", "test:run": "vitest run", - "lint": "eslint src", - "format": "prettier --write src/**/*.ts", - "format:check": "prettier --check src/**/*.ts", + "lint": "eslint src tui", + "format": "prettier --write 'src/**/*.ts' 'tui/**/*.tsx' 'tui/**/*.ts'", + "format:check": "prettier --check 'src/**/*.ts' 'tui/**/*.tsx' 'tui/**/*.ts'", "clean": "rm -rf dist", "prepublishOnly": "npm run clean && npm run build" }, @@ -34,28 +38,63 @@ }, "files": [ "dist", + "!dist/**/*.test.*", + "!dist/**/*.spec.*", + "!dist/**/test-fixtures.*", + "!dist/**/api-surface.typecheck.*", + "src/", + "!src/**/*.test.ts", + "!src/**/*.spec.ts", + "!src/test-fixtures.ts", + "!src/api-surface.typecheck.ts", + "tui/", + "!tui/**/*.test.ts", + "!tui/**/*.test.tsx", + "!tui/**/*.spec.ts", + "!tui/**/*.spec.tsx", "README.md", "LICENSE" ], "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.js" + "types": "./dist/src/index.d.ts", + "import": "./dist/src/index.js" + }, + "./tui": { + "types": "./dist/tui/index.d.ts", + "import": "./tui/index.tsx" + } + }, + "peerDependencies": { + "@opencode-ai/plugin": "^1.3.7", + "@opencode-ai/sdk": "^1.3.7", + "@opentui/solid": ">=0.1.92", + "@opentui/core": ">=0.1.92" + }, + "peerDependenciesMeta": { + "@opentui/solid": { + "optional": true + }, + "@opentui/core": { + "optional": true } }, "devDependencies": { + "@opencode-ai/plugin": "^1.3.9", + "@opencode-ai/sdk": "^1.3.9", + "@opentui/core": "^0.1.93", + "@opentui/solid": "^0.1.93", "@types/minimatch": "^5.1.2", "@types/node": "^20.19.30", "@typescript-eslint/eslint-plugin": "^6.21.0", "@typescript-eslint/parser": "^6.21.0", "eslint": "^8.57.1", "prettier": "^3.8.1", + "solid-js": "1.9.11", "typescript": "^5.9.3", "vitest": "^1.6.1" }, "dependencies": { - "@opencode-ai/plugin": "^1.1.34", - "@opencode-ai/sdk": "^1.1.34", "minimatch": "^9.0.5", "yaml": "^2.8.2" } diff --git a/src/active-rules-state.test.ts b/src/active-rules-state.test.ts new file mode 100644 index 0000000..86de4fe --- /dev/null +++ b/src/active-rules-state.test.ts @@ -0,0 +1,262 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import * as fs from 'node:fs/promises'; +import * as path from 'node:path'; +import * as os from 'node:os'; +import { + resolveStateDir, + getStateFilePath, + writeActiveRulesState, + readActiveRulesState, + _setStateDirForTesting, +} from './active-rules-state.js'; + +describe('active-rules-state', () => { + let testStateDir: string; + + beforeEach(async () => { + // Create a temp directory for tests + const testDir = await fs.mkdtemp( + path.join(os.tmpdir(), 'active-rules-test-') + ); + testStateDir = path.join(testDir, 'state'); + + // Use test override instead of mocking os.homedir + _setStateDirForTesting(testStateDir); + }); + + afterEach(async () => { + // Reset the override + _setStateDirForTesting(null); + + // Clean up test directory + if (testStateDir) { + try { + // Go up one level to remove the whole temp dir + const parentDir = path.dirname(testStateDir); + await fs.rm(parentDir, { recursive: true }); + } catch { + // Ignore cleanup errors + } + } + }); + + describe('resolveStateDir', () => { + it('returns overridden path when set', () => { + const stateDir = resolveStateDir(); + expect(stateDir).toBe(testStateDir); + }); + + it('returns default path when not overridden', () => { + _setStateDirForTesting(null); + const stateDir = resolveStateDir(); + expect(stateDir).toBe( + path.join(os.homedir(), '.opencode', 'state', 'opencode-rules') + ); + }); + }); + + describe('getStateFilePath', () => { + it('returns session-specific JSON path', () => { + const filePath = getStateFilePath('ses_123'); + expect(filePath).toBe(path.join(testStateDir, 'ses_123.json')); + }); + + it('throws for sessionId with path traversal', () => { + expect(() => getStateFilePath('../escape')).toThrow('Invalid sessionId'); + expect(() => getStateFilePath('foo/bar')).toThrow('Invalid sessionId'); + expect(() => getStateFilePath('/absolute')).toThrow('Invalid sessionId'); + }); + + it('throws for sessionId with special characters', () => { + expect(() => getStateFilePath('ses.123')).toThrow('Invalid sessionId'); + expect(() => getStateFilePath('ses 123')).toThrow('Invalid sessionId'); + expect(() => getStateFilePath('')).toThrow('Invalid sessionId'); + }); + }); + + describe('writeActiveRulesState and readActiveRulesState', () => { + it('write/read round-trip preserves data', async () => { + const sessionId = 'ses_roundtrip'; + const matchedPaths = ['/path/to/rule1.md', '/path/to/rule2.md']; + + writeActiveRulesState(sessionId, matchedPaths); + + // Wait for the fire-and-forget write to complete + await waitForFile(getStateFilePath(sessionId)); + + const state = await readActiveRulesState(sessionId); + + expect(state).not.toBeNull(); + expect(state!.sessionId).toBe(sessionId); + expect(state!.matchedRulePaths).toEqual(matchedPaths); + expect(typeof state!.evaluatedAt).toBe('number'); + expect(state!.evaluatedAt).toBeLessThanOrEqual(Date.now()); + }); + + it('returns null for missing file', async () => { + const state = await readActiveRulesState('ses_nonexistent'); + expect(state).toBeNull(); + }); + + it('returns null for corrupt/invalid JSON', async () => { + await fs.mkdir(testStateDir, { recursive: true }); + + const filePath = getStateFilePath('ses_corrupt'); + await fs.writeFile(filePath, 'not valid json {{{', 'utf-8'); + + const state = await readActiveRulesState('ses_corrupt'); + expect(state).toBeNull(); + }); + + it('returns null for invalid state format', async () => { + await fs.mkdir(testStateDir, { recursive: true }); + + const filePath = getStateFilePath('ses_invalid'); + await fs.writeFile(filePath, JSON.stringify({ foo: 'bar' }), 'utf-8'); + + const state = await readActiveRulesState('ses_invalid'); + expect(state).toBeNull(); + }); + + it('returns null for wrong-type values in state', async () => { + await fs.mkdir(testStateDir, { recursive: true }); + + const filePath = getStateFilePath('ses_wrongtypes'); + await fs.writeFile( + filePath, + JSON.stringify({ + sessionId: 123, + matchedRulePaths: 'not-an-array', + evaluatedAt: 'not-a-number', + }), + 'utf-8' + ); + + const state = await readActiveRulesState('ses_wrongtypes'); + expect(state).toBeNull(); + }); + + it('returns null for array with non-string items', async () => { + await fs.mkdir(testStateDir, { recursive: true }); + + const filePath = getStateFilePath('ses_badarray'); + await fs.writeFile( + filePath, + JSON.stringify({ + sessionId: 'ses_badarray', + matchedRulePaths: ['/valid.md', 123, null], + evaluatedAt: Date.now(), + }), + 'utf-8' + ); + + const state = await readActiveRulesState('ses_badarray'); + expect(state).toBeNull(); + }); + + it('silently ignores write with invalid sessionId', async () => { + writeActiveRulesState('../escape', ['/rule.md']); + writeActiveRulesState('foo/bar', ['/rule.md']); + + // Give time for any writes to occur + await new Promise(resolve => setTimeout(resolve, 50)); + + // Verify no files were created + try { + await fs.access(testStateDir); + const files = await fs.readdir(testStateDir); + expect(files).toHaveLength(0); + } catch { + // Directory doesn't exist, which is expected + } + }); + + it('returns null for read with invalid sessionId', async () => { + const state = await readActiveRulesState('../escape'); + expect(state).toBeNull(); + }); + + it('no temp file remains after write', async () => { + const sessionId = 'ses_no_temp'; + const matchedPaths = ['/rule.md']; + + writeActiveRulesState(sessionId, matchedPaths); + + // Wait for write to complete + await waitForFile(getStateFilePath(sessionId)); + + // Check that no temp files remain + const files = await fs.readdir(testStateDir); + const tempFiles = files.filter(f => f.endsWith('.tmp')); + + expect(tempFiles).toHaveLength(0); + }); + + it('serializes concurrent writes for same session', async () => { + const sessionId = 'ses_concurrent'; + + // Fire multiple writes concurrently + writeActiveRulesState(sessionId, ['path1']); + writeActiveRulesState(sessionId, ['path2']); + writeActiveRulesState(sessionId, ['path3']); + + // Wait for all writes to complete + await waitForFile(getStateFilePath(sessionId)); + + // Give a bit more time for all queued writes to finish + await new Promise(resolve => setTimeout(resolve, 100)); + + // The final state should reflect the last write + const state = await readActiveRulesState(sessionId); + expect(state).not.toBeNull(); + expect(state!.matchedRulePaths).toEqual(['path3']); + }); + + it('creates state directory when it does not exist', async () => { + const sessionId = 'ses_newdir'; + const matchedPaths = ['/rule.md']; + + // Verify directory doesn't exist yet + await expect(fs.access(testStateDir)).rejects.toThrow(); + + writeActiveRulesState(sessionId, matchedPaths); + + // Wait for write to complete + await waitForFile(getStateFilePath(sessionId)); + + // Verify directory now exists + await expect(fs.access(testStateDir)).resolves.toBeUndefined(); + }); + + it('handles writes to different sessions independently', async () => { + writeActiveRulesState('ses_a', ['ruleA']); + writeActiveRulesState('ses_b', ['ruleB']); + + // Wait for both writes + await Promise.all([ + waitForFile(getStateFilePath('ses_a')), + waitForFile(getStateFilePath('ses_b')), + ]); + + const stateA = await readActiveRulesState('ses_a'); + const stateB = await readActiveRulesState('ses_b'); + + expect(stateA!.matchedRulePaths).toEqual(['ruleA']); + expect(stateB!.matchedRulePaths).toEqual(['ruleB']); + }); + }); +}); + +// Helper to wait for a file to exist +async function waitForFile(filePath: string, timeoutMs = 1000): Promise { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + try { + await fs.access(filePath); + return; + } catch { + await new Promise(resolve => setTimeout(resolve, 10)); + } + } + throw new Error(`Timed out waiting for file: ${filePath}`); +} diff --git a/src/active-rules-state.ts b/src/active-rules-state.ts new file mode 100644 index 0000000..fd22bfd --- /dev/null +++ b/src/active-rules-state.ts @@ -0,0 +1,166 @@ +import * as fs from 'node:fs/promises'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import * as crypto from 'node:crypto'; +import { createDebugLog } from './debug.js'; + +const debugLog = createDebugLog(); + +export interface ActiveRulesState { + sessionId: string; + matchedRulePaths: string[]; + evaluatedAt: number; +} + +// Per-session write queue to serialize concurrent writes +const writeQueues = new Map>(); + +// Allows tests to override the state directory +let stateDirOverride: string | null = null; + +// Strict pattern for safe sessionId: alphanumeric, underscore, hyphen only +const SAFE_SESSION_ID_PATTERN = /^[A-Za-z0-9_-]+$/; + +function isValidSessionId(sessionId: string): boolean { + return SAFE_SESSION_ID_PATTERN.test(sessionId); +} + +/** @internal Test-only: override the state directory */ +export function _setStateDirForTesting(dir: string | null): void { + stateDirOverride = dir; +} + +export function resolveStateDir(): string { + if (stateDirOverride !== null) { + return stateDirOverride; + } + return path.join(os.homedir(), '.opencode', 'state', 'opencode-rules'); +} + +export function getStateFilePath(sessionId: string): string { + if (!isValidSessionId(sessionId)) { + throw new Error(`Invalid sessionId: ${sessionId}`); + } + return path.join(resolveStateDir(), `${sessionId}.json`); +} + +export function writeActiveRulesState( + sessionId: string, + matchedPaths: string[] +): void { + if (!isValidSessionId(sessionId)) { + debugLog(`Invalid sessionId rejected: ${sessionId}`); + return; + } + + const state: ActiveRulesState = { + sessionId, + matchedRulePaths: matchedPaths, + evaluatedAt: Date.now(), + }; + + // Chain onto existing queue for this session, or start fresh + const previousWrite = writeQueues.get(sessionId) ?? Promise.resolve(); + + const currentWrite = previousWrite.then(async () => { + await doAtomicWrite(sessionId, state); + }); + + writeQueues.set(sessionId, currentWrite); + + // Fire-and-forget: catch errors to prevent unhandled rejection + currentWrite.catch(() => { + // Errors already logged in doAtomicWrite + }); +} + +async function doAtomicWrite( + sessionId: string, + state: ActiveRulesState +): Promise { + const stateDir = resolveStateDir(); + const finalPath = getStateFilePath(sessionId); + const tempPath = path.join( + stateDir, + `.${sessionId}-${crypto.randomBytes(8).toString('hex')}.tmp` + ); + + try { + // Ensure directory exists + await fs.mkdir(stateDir, { recursive: true }); + + // Write to temp file + const content = JSON.stringify(state); + await fs.writeFile(tempPath, content, 'utf-8'); + + // Atomic rename + await fs.rename(tempPath, finalPath); + } catch (error) { + debugLog( + `Failed to write active rules state for session ${sessionId}: ${error}` + ); + + // Clean up temp file if it exists + try { + await fs.unlink(tempPath); + } catch { + // Ignore cleanup errors + } + } +} + +export async function readActiveRulesState( + sessionId: string +): Promise { + if (!isValidSessionId(sessionId)) { + debugLog(`Invalid sessionId rejected: ${sessionId}`); + return null; + } + + const filePath = getStateFilePath(sessionId); + + try { + const content = await fs.readFile(filePath, 'utf-8'); + const parsed: unknown = JSON.parse(content); + + if (!isValidActiveRulesState(parsed)) { + debugLog(`Invalid active rules state format for session ${sessionId}`); + return null; + } + + return parsed; + } catch (error) { + debugLog( + `Failed to read active rules state for session ${sessionId}: ${error}` + ); + return null; + } +} + +function isValidActiveRulesState(value: unknown): value is ActiveRulesState { + if (typeof value !== 'object' || value === null) { + return false; + } + + const obj = value as Record; + + if (typeof obj['sessionId'] !== 'string') { + return false; + } + + if (typeof obj['evaluatedAt'] !== 'number') { + return false; + } + + if (!Array.isArray(obj['matchedRulePaths'])) { + return false; + } + + for (const item of obj['matchedRulePaths']) { + if (typeof item !== 'string') { + return false; + } + } + + return true; +} diff --git a/src/index.integration.test.ts b/src/index.integration.test.ts index 009f275..8ffb146 100644 --- a/src/index.integration.test.ts +++ b/src/index.integration.test.ts @@ -42,18 +42,20 @@ describe('readAndFormatRules', () => { writeFileSync(rule1Path, '# Rule 1\nContent of rule 1'); writeFileSync(rule2Path, '# Rule 2\nContent of rule 2'); - const formatted = await readAndFormatRules(toRules([rule1Path, rule2Path])); + const { formattedRules } = await readAndFormatRules( + toRules([rule1Path, rule2Path]) + ); - expect(formatted).toContain('OpenCode Rules'); - expect(formatted).toContain('rule1.md'); - expect(formatted).toContain('rule2.md'); - expect(formatted).toContain('Rule 1'); - expect(formatted).toContain('Rule 2'); + expect(formattedRules).toContain('OpenCode Rules'); + expect(formattedRules).toContain('rule1.md'); + expect(formattedRules).toContain('rule2.md'); + expect(formattedRules).toContain('Rule 1'); + expect(formattedRules).toContain('Rule 2'); }); it('should return empty string when no files provided', async () => { - const formatted = await readAndFormatRules([]); - expect(formatted).toBe(''); + const { formattedRules } = await readAndFormatRules([]); + expect(formattedRules).toBe(''); }); it('should handle file read errors gracefully', async () => { @@ -62,10 +64,10 @@ describe('readAndFormatRules', () => { const validFile = path.join(globalRulesDir, 'valid.md'); writeFileSync(validFile, '# Valid Rule'); - const formatted = await readAndFormatRules( + const { formattedRules } = await readAndFormatRules( toRules([nonExistentFile, validFile]) ); - expect(formatted).toContain('valid.md'); + expect(formattedRules).toContain('valid.md'); }); it('should include filename as subheader in output', async () => { @@ -73,8 +75,8 @@ describe('readAndFormatRules', () => { const rulePath = path.join(globalRulesDir, 'my-rules.md'); writeFileSync(rulePath, 'Rule content'); - const formatted = await readAndFormatRules(toRules([rulePath])); - expect(formatted).toMatch(/##\s+my-rules\.md/); + const { formattedRules } = await readAndFormatRules(toRules([rulePath])); + expect(formattedRules).toMatch(/##\s+my-rules\.md/); }); it('should include rule when file matches glob pattern in metadata', async () => { @@ -88,12 +90,14 @@ globs: This is a rule for TypeScript components.`; writeFileSync(rulePath, ruleContent); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { contextFilePaths: ['src/components/button.ts'], }); - expect(formatted).toContain('typescript.mdc'); - expect(formatted).toContain('This is a rule for TypeScript components.'); + expect(formattedRules).toContain('typescript.mdc'); + expect(formattedRules).toContain( + 'This is a rule for TypeScript components.' + ); }); it('should exclude rule when file does not match glob pattern in metadata', async () => { @@ -107,11 +111,11 @@ globs: This is a rule for TypeScript components.`; writeFileSync(rulePath, ruleContent); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { contextFilePaths: ['src/utils/helpers.js'], }); - expect(formatted).toBe(''); + expect(formattedRules).toBe(''); }); it('should include rule when user prompt matches keywords', async () => { @@ -128,12 +132,12 @@ keywords: Follow testing best practices.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { userPrompt: 'I need help testing this function', }); - expect(formatted).toContain('testing-rule.mdc'); - expect(formatted).toContain('Follow testing best practices'); + expect(formattedRules).toContain('testing-rule.mdc'); + expect(formattedRules).toContain('Follow testing best practices'); }); it('should include rule when tool is available', async () => { @@ -149,12 +153,12 @@ tools: Use web search best practices.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { availableToolIDs: ['mcp_bash', 'mcp_websearch', 'mcp_read'], }); - expect(formatted).toContain('websearch-rule.mdc'); - expect(formatted).toContain('Use web search best practices'); + expect(formattedRules).toContain('websearch-rule.mdc'); + expect(formattedRules).toContain('Use web search best practices'); }); describe('new filter dimensions', () => { @@ -172,12 +176,12 @@ model: Model-specific rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { modelID: 'claude-opus', }); - expect(formatted).toContain('model-rule.mdc'); - expect(formatted).toContain('Model-specific rule'); + expect(formattedRules).toContain('model-rule.mdc'); + expect(formattedRules).toContain('Model-specific rule'); }); it('should include rule when agent matches', async () => { @@ -194,12 +198,12 @@ agent: Agent-specific rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { agentType: 'programmer', }); - expect(formatted).toContain('agent-rule.mdc'); - expect(formatted).toContain('Agent-specific rule'); + expect(formattedRules).toContain('agent-rule.mdc'); + expect(formattedRules).toContain('Agent-specific rule'); }); it('should include rule when os matches', async () => { @@ -216,12 +220,12 @@ os: Unix-specific rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { os: 'linux', }); - expect(formatted).toContain('os-rule.mdc'); - expect(formatted).toContain('Unix-specific rule'); + expect(formattedRules).toContain('os-rule.mdc'); + expect(formattedRules).toContain('Unix-specific rule'); }); it('should include rule when ci is true and rule requires ci', async () => { @@ -236,12 +240,12 @@ ci: true CI-specific rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { ci: true, }); - expect(formatted).toContain('ci-rule.mdc'); - expect(formatted).toContain('CI-specific rule'); + expect(formattedRules).toContain('ci-rule.mdc'); + expect(formattedRules).toContain('CI-specific rule'); }); it('should include rule when branch matches glob pattern', async () => { @@ -258,12 +262,12 @@ branch: Feature branch rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { gitBranch: 'feature/add-login', }); - expect(formatted).toContain('branch-glob-rule.mdc'); - expect(formatted).toContain('Feature branch rule'); + expect(formattedRules).toContain('branch-glob-rule.mdc'); + expect(formattedRules).toContain('Feature branch rule'); }); }); @@ -285,14 +289,14 @@ os: Default any match rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { modelID: 'claude-opus', agentType: 'reviewer', os: 'linux', }); - expect(formatted).toContain('any-default.mdc'); - expect(formatted).toContain('Default any match rule'); + expect(formattedRules).toContain('any-default.mdc'); + expect(formattedRules).toContain('Default any match rule'); }); it('should require all declared dimensions when match is all', async () => { @@ -313,14 +317,14 @@ match: all All dimensions must match.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { modelID: 'claude-opus', agentType: 'programmer', os: 'linux', }); - expect(formatted).toContain('all-match.mdc'); - expect(formatted).toContain('All dimensions must match'); + expect(formattedRules).toContain('all-match.mdc'); + expect(formattedRules).toContain('All dimensions must match'); }); it('should exclude rule when match: all and one dimension fails', async () => { @@ -341,13 +345,13 @@ match: all All dimensions must match.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { modelID: 'claude-opus', agentType: 'programmer', os: 'darwin', }); - expect(formatted).toBe(''); + expect(formattedRules).toBe(''); }); }); @@ -362,9 +366,9 @@ All dimensions must match.` const result1 = await readAndFormatRules(rules); const result2 = await readAndFormatRules(rules); - expect(result1).toContain('Cached Rule'); - expect(result2).toContain('Cached Rule'); - expect(result1).toBe(result2); + expect(result1.formattedRules).toContain('Cached Rule'); + expect(result2.formattedRules).toContain('Cached Rule'); + expect(result1.formattedRules).toBe(result2.formattedRules); }); it('should invalidate cache when file is modified', async () => { @@ -375,7 +379,7 @@ All dimensions must match.` const rules = toRules([rulePath]); const result1 = await readAndFormatRules(rules); - expect(result1).toContain('Original Content'); + expect(result1.formattedRules).toContain('Original Content'); // Write new content and explicitly set mtime to future to ensure cache invalidation // This avoids flaky timing issues on CI/different filesystems @@ -385,8 +389,8 @@ All dimensions must match.` const result2 = await readAndFormatRules(rules); - expect(result2).toContain('Modified Content'); - expect(result2).not.toContain('Original Content'); + expect(result2.formattedRules).toContain('Modified Content'); + expect(result2.formattedRules).not.toContain('Original Content'); }); it('should handle clearRuleCache correctly', async () => { @@ -400,7 +404,7 @@ All dimensions must match.` clearRuleCache(); const result = await readAndFormatRules(rules); - expect(result).toContain('Test Content'); + expect(result.formattedRules).toContain('Test Content'); }); }); }); @@ -473,8 +477,10 @@ Rule with explicit match any.` context ); - expect(omittedResult).toContain('Rule with omitted match'); - expect(explicitResult).toContain('Rule with explicit match any'); + expect(omittedResult.formattedRules).toContain('Rule with omitted match'); + expect(explicitResult.formattedRules).toContain( + 'Rule with explicit match any' + ); }); it('should exclude rule with omitted match when no dimension matches', async () => { @@ -493,12 +499,12 @@ agent: Rule that should not match.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { modelID: 'claude-opus', agentType: 'reviewer', }); - expect(formatted).toBe(''); + expect(formattedRules).toBe(''); }); }); @@ -525,7 +531,7 @@ agent: Mixed legacy and new filters rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { contextFilePaths: ['src/index.ts'], userPrompt: 'help with debugging', availableToolIDs: ['mcp_bash'], @@ -533,7 +539,7 @@ Mixed legacy and new filters rule.` agentType: 'reviewer', }); - expect(formatted).toContain('Mixed legacy and new filters rule'); + expect(formattedRules).toContain('Mixed legacy and new filters rule'); }); it('should include rule when only new model filter matches (all legacy mismatch)', async () => { @@ -558,7 +564,7 @@ agent: New model filter matches rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { contextFilePaths: ['src/index.ts'], userPrompt: 'help with typescript', availableToolIDs: ['mcp_bash'], @@ -566,7 +572,7 @@ New model filter matches rule.` agentType: 'programmer', }); - expect(formatted).toContain('New model filter matches rule'); + expect(formattedRules).toContain('New model filter matches rule'); }); }); @@ -596,7 +602,7 @@ match: all All dimensions match rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { contextFilePaths: ['src/utils.ts'], userPrompt: 'help me refactor this code', availableToolIDs: ['mcp_bash', 'mcp_read'], @@ -605,7 +611,7 @@ All dimensions match rule.` os: 'linux', }); - expect(formatted).toContain('All dimensions match rule'); + expect(formattedRules).toContain('All dimensions match rule'); }); it('should exclude rule when one legacy dimension fails (keywords mismatch)', async () => { @@ -629,14 +635,14 @@ match: all Keywords fail rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { contextFilePaths: ['src/utils.ts'], userPrompt: 'help me refactor this code', availableToolIDs: ['mcp_bash'], modelID: 'claude-opus', }); - expect(formatted).toBe(''); + expect(formattedRules).toBe(''); }); }); @@ -660,13 +666,15 @@ model: Conditional rule for gpt-5 only.` ); - const formatted = await readAndFormatRules( + const { formattedRules } = await readAndFormatRules( toRules([unconditionalPath, conditionalPath]), { modelID: 'claude-opus' } ); - expect(formatted).toContain('This rule always applies unconditionally'); - expect(formatted).not.toContain('Conditional rule for gpt-5 only'); + expect(formattedRules).toContain( + 'This rule always applies unconditionally' + ); + expect(formattedRules).not.toContain('Conditional rule for gpt-5 only'); }); it('should include unconditional rules even when filter context is empty', async () => { @@ -690,13 +698,13 @@ keywords: Only for special files.` ); - const formatted = await readAndFormatRules( + const { formattedRules } = await readAndFormatRules( toRules([unconditionalPath, conditionalPath]), {} ); - expect(formatted).toContain('No metadata means always apply'); - expect(formatted).not.toContain('Only for special files'); + expect(formattedRules).toContain('No metadata means always apply'); + expect(formattedRules).not.toContain('Only for special files'); }); it('should include unconditional rules when called with no context at all', async () => { @@ -708,9 +716,109 @@ Only for special files.` '# Bare Rule\nShould always be included.' ); - const formatted = await readAndFormatRules(toRules([unconditionalPath])); + const { formattedRules } = await readAndFormatRules( + toRules([unconditionalPath]) + ); + + expect(formattedRules).toContain('Should always be included'); + }); + }); + + describe('matchedPaths tracking', () => { + it('should return matchedPaths with file paths of included rules', async () => { + const { globalRulesDir } = getTestDirs(); + const rule1Path = path.join(globalRulesDir, 'rule1.md'); + const rule2Path = path.join(globalRulesDir, 'rule2.md'); + writeFileSync(rule1Path, '# Rule 1\nContent'); + writeFileSync(rule2Path, '# Rule 2\nContent'); + + const { formattedRules, matchedPaths } = await readAndFormatRules( + toRules([rule1Path, rule2Path]) + ); + + expect(formattedRules).toContain('Rule 1'); + expect(matchedPaths).toHaveLength(2); + expect(matchedPaths).toContain(rule1Path); + expect(matchedPaths).toContain(rule2Path); + }); + + it('should return empty matchedPaths when no rules match', async () => { + const { globalRulesDir } = getTestDirs(); + const rulePath = path.join(globalRulesDir, 'conditional.mdc'); + writeFileSync( + rulePath, + `--- +model: + - gpt-5 +--- + +Conditional rule.` + ); + + const { formattedRules, matchedPaths } = await readAndFormatRules( + toRules([rulePath]), + { modelID: 'claude-opus' } + ); + + expect(formattedRules).toBe(''); + expect(matchedPaths).toHaveLength(0); + }); + + it('should return empty matchedPaths when files array is empty', async () => { + const { formattedRules, matchedPaths } = await readAndFormatRules([]); + + expect(formattedRules).toBe(''); + expect(matchedPaths).toHaveLength(0); + }); + + it('should only include matching rules in matchedPaths (not filtered-out rules)', async () => { + const { globalRulesDir } = getTestDirs(); + const includedPath = path.join(globalRulesDir, 'included.mdc'); + const excludedPath = path.join(globalRulesDir, 'excluded.mdc'); + + writeFileSync( + includedPath, + `--- +model: + - claude-opus +--- + +Included rule.` + ); + writeFileSync( + excludedPath, + `--- +model: + - gpt-5 +--- + +Excluded rule.` + ); + + const { formattedRules, matchedPaths } = await readAndFormatRules( + toRules([includedPath, excludedPath]), + { modelID: 'claude-opus' } + ); + + expect(formattedRules).toContain('Included rule'); + expect(formattedRules).not.toContain('Excluded rule'); + expect(matchedPaths).toHaveLength(1); + expect(matchedPaths).toContain(includedPath); + expect(matchedPaths).not.toContain(excludedPath); + }); + + it('should include unconditional rules in matchedPaths', async () => { + const { globalRulesDir } = getTestDirs(); + const unconditionalPath = path.join(globalRulesDir, 'always.md'); + + writeFileSync(unconditionalPath, '# Always\nUnconditional rule.'); + + const { matchedPaths } = await readAndFormatRules( + toRules([unconditionalPath]) + ); - expect(formatted).toContain('Should always be included'); + expect(matchedPaths).toHaveLength(1); + expect(matchedPaths).toContain(unconditionalPath); }); }); }); @@ -748,7 +856,9 @@ Use React best practices for components.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -807,7 +917,9 @@ Use React best practices for components.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -870,7 +982,9 @@ Special rule content.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -940,7 +1054,10 @@ describe('Session compacting behavior', () => { const { testDir } = getTestDirs(); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] @@ -970,7 +1087,10 @@ describe('Session compacting behavior', () => { const { testDir } = getTestDirs(); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] @@ -1007,7 +1127,10 @@ describe('Session compacting behavior', () => { const { testDir } = getTestDirs(); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] @@ -1039,7 +1162,10 @@ describe('Session compacting behavior', () => { const { testDir } = getTestDirs(); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] @@ -1080,7 +1206,9 @@ MCP Context7 rule content`; writeFileSync(path.join(globalRulesDir, 'context7.md'), ruleContent); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir, mcpStatus: { context7: { status: 'connected' } }, diff --git a/src/index.runtime.test.ts b/src/index.runtime.test.ts index 8086dc4..5726933 100644 --- a/src/index.runtime.test.ts +++ b/src/index.runtime.test.ts @@ -4,7 +4,7 @@ */ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import path from 'path'; -import { writeFileSync, mkdirSync } from 'fs'; +import { writeFileSync, mkdirSync, readdirSync } from 'fs'; import { setupTestDirs, teardownTestDirs, @@ -26,6 +26,10 @@ import * as sessionStoreModule from './session-store.js'; import * as runtimeContextModule from './runtime-context.js'; import * as runtimeChatModule from './runtime-chat.js'; import { __testOnly } from './index.js'; +import { + _setStateDirForTesting, + readActiveRulesState, +} from './active-rules-state.js'; describe('module boundary tests', () => { it('should re-export discoverRuleFiles from rule-discovery module', () => { @@ -179,9 +183,10 @@ describe('OpenCodeRulesPlugin', () => { } }); - it('should export a default plugin function', async () => { - const { default: plugin } = await import('./index.js'); - expect(typeof plugin).toBe('function'); + it('should export a plugin module with id and server', async () => { + const { default: pluginModule } = await import('./index.js'); + expect(pluginModule).toHaveProperty('id', 'opencode-rules'); + expect(typeof pluginModule.server).toBe('function'); }); it('should return transform hooks even when no rules exist', async () => { @@ -191,7 +196,9 @@ describe('OpenCodeRulesPlugin', () => { recursive: true, }); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir: path.join(testDir, 'empty-project'), }); @@ -212,7 +219,9 @@ describe('OpenCodeRulesPlugin', () => { writeFileSync(path.join(globalRulesDir, 'rule.md'), '# Test Rule'); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -230,7 +239,9 @@ describe('OpenCodeRulesPlugin', () => { ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -255,7 +266,9 @@ describe('OpenCodeRulesPlugin', () => { writeFileSync(path.join(globalRulesDir, 'rule.md'), '# My Rule'); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -279,7 +292,9 @@ describe('OpenCodeRulesPlugin', () => { writeFileSync(path.join(globalRulesDir, 'rule.md'), '# Rule Content'); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -300,7 +315,9 @@ describe('OpenCodeRulesPlugin', () => { writeFileSync(path.join(globalRulesDir, 'rule.md'), '# Rule'); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const originalMessages = [ @@ -324,7 +341,9 @@ describe('OpenCodeRulesPlugin', () => { it('seeds session state once from messages.transform and does not rescan', async () => { const { testDir } = getTestDirs(); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -395,7 +414,9 @@ describe('SessionState', () => { it('updates lastUserPrompt from chat.message', async () => { const { testDir } = getTestDirs(); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -422,7 +443,10 @@ describe('SessionState', () => { it('extracts text from mixed parts using shared extraction logic', async () => { const { testDir } = getTestDirs(); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -453,7 +477,10 @@ describe('SessionState', () => { it('stores lastModelID from chat.message for user messages', async () => { const { testDir } = getTestDirs(); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -478,7 +505,10 @@ describe('SessionState', () => { it('stores lastAgentType from chat.message for user messages', async () => { const { testDir } = getTestDirs(); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -503,7 +533,10 @@ describe('SessionState', () => { it('stores both model and agent from chat.message', async () => { const { testDir } = getTestDirs(); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -533,7 +566,10 @@ describe('SessionState', () => { it('does not update model/agent for non-user messages', async () => { const { testDir } = getTestDirs(); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -575,7 +611,10 @@ describe('SessionState', () => { it('updates model/agent on subsequent user messages', async () => { const { testDir } = getTestDirs(); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( @@ -624,7 +663,9 @@ describe('SessionState', () => { `---\nglobs:\n - "src/components/**/*.tsx"\n---\n\nUse React best practices.` ); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] @@ -661,7 +702,10 @@ describe('SessionState', () => { ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin, __testOnly } = await import('./index.js'); + const { + default: { server: plugin }, + __testOnly, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] @@ -685,6 +729,144 @@ describe('SessionState', () => { }); }); +describe('Active rules state persistence', () => { + let savedEnvXDG: string | undefined; + let stateDir: string; + + beforeEach(() => { + setupTestDirs(); + savedEnvXDG = process.env.XDG_CONFIG_HOME; + const { testDir } = getTestDirs(); + stateDir = path.join(testDir, 'state'); + mkdirSync(stateDir, { recursive: true }); + _setStateDirForTesting(stateDir); + }); + + afterEach(async () => { + teardownTestDirs(); + _setStateDirForTesting(null); + const { __testOnly } = await import('./index.js'); + __testOnly.resetSessionState(); + if (savedEnvXDG === undefined) { + delete process.env.XDG_CONFIG_HOME; + } else { + process.env.XDG_CONFIG_HOME = savedEnvXDG; + } + }); + + it('writes matched rule paths to state file when rules match', async () => { + const { testDir, globalRulesDir } = getTestDirs(); + const rulePath = path.join(globalRulesDir, 'always-apply.md'); + writeFileSync(rulePath, '# Always Apply\nThis rule always applies.'); + process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); + + const { + default: { server: plugin }, + } = await import('./index.js'); + const mockInput = createMockPluginInput({ testDir }); + const hooks = await plugin( + mockInput as unknown as Parameters[0] + ); + + const sessionID = 'ses-state-match'; + const systemTransform = hooks['experimental.chat.system.transform'] as ( + input: { sessionID?: string }, + output: { system: string } + ) => Promise<{ system: string }>; + + const result = await systemTransform( + { sessionID }, + { system: 'Base prompt.' } + ); + + expect(result.system).toContain('Always Apply'); + + // Wait for fire-and-forget write to complete + await new Promise(resolve => setTimeout(resolve, 50)); + + const state = await readActiveRulesState(sessionID); + expect(state).not.toBeNull(); + expect(state?.sessionId).toBe(sessionID); + expect(state?.matchedRulePaths).toHaveLength(1); + expect(state?.matchedRulePaths[0]).toBe(rulePath); + }); + + it('writes empty matchedPaths to state file when no rules match', async () => { + const { testDir, globalRulesDir } = getTestDirs(); + const rulePath = path.join(globalRulesDir, 'conditional.mdc'); + writeFileSync( + rulePath, + `--- +model: + - gpt-5 +--- + +Conditional rule for gpt-5 only.` + ); + process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); + + const { + default: { server: plugin }, + } = await import('./index.js'); + const mockInput = createMockPluginInput({ testDir }); + const hooks = await plugin( + mockInput as unknown as Parameters[0] + ); + + const sessionID = 'ses-state-nomatch'; + const systemTransform = hooks['experimental.chat.system.transform'] as ( + input: { sessionID?: string }, + output: { system: string } + ) => Promise<{ system: string }>; + + const result = await systemTransform( + { sessionID }, + { system: 'Base prompt.' } + ); + + // No rules should match (model is not gpt-5) + expect(result.system).not.toContain('Conditional rule'); + + // Wait for fire-and-forget write to complete + await new Promise(resolve => setTimeout(resolve, 50)); + + const state = await readActiveRulesState(sessionID); + expect(state).not.toBeNull(); + expect(state?.sessionId).toBe(sessionID); + expect(state?.matchedRulePaths).toHaveLength(0); + }); + + it('does not write state when sessionID is missing', async () => { + const { testDir, globalRulesDir } = getTestDirs(); + writeFileSync(path.join(globalRulesDir, 'rule.md'), '# Test Rule\nContent'); + process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); + + const { + default: { server: plugin }, + } = await import('./index.js'); + const mockInput = createMockPluginInput({ testDir }); + const hooks = await plugin( + mockInput as unknown as Parameters[0] + ); + + const systemTransform = hooks['experimental.chat.system.transform'] as ( + input: { sessionID?: string }, + output: { system: string } + ) => Promise<{ system: string }>; + + // Call without sessionID + await systemTransform({}, { system: 'Base prompt.' }); + + // Wait briefly + await new Promise(resolve => setTimeout(resolve, 50)); + + // Verify no state files were created in the state directory + const files = readdirSync(stateDir); + const jsonFiles = files.filter(f => f.endsWith('.json')); + expect(jsonFiles).toHaveLength(0); + }); +}); + describe('utils runtime exports', () => { it('exports only expected functions at runtime', () => { const exportedKeys = Object.keys(utilsModule).sort(); @@ -740,7 +922,9 @@ describe('CI environment detection', () => { clearCiEnvVars(); process.env.CI = 'true'; - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] @@ -766,7 +950,9 @@ describe('CI environment detection', () => { clearCiEnvVars(); process.env.CI = 'false'; - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] @@ -792,7 +978,9 @@ describe('CI environment detection', () => { clearCiEnvVars(); process.env.CI = '0'; - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] @@ -818,7 +1006,9 @@ describe('CI environment detection', () => { clearCiEnvVars(); process.env.GITHUB_ACTIONS = 'true'; - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] @@ -844,7 +1034,9 @@ describe('CI environment detection', () => { clearCiEnvVars(); process.env.BUILD_NUMBER = 'false'; - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockInput = createMockPluginInput({ testDir }); const hooks = await plugin( mockInput as unknown as Parameters[0] diff --git a/src/index.test.ts b/src/index.test.ts index 815efa1..fdf804f 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -65,7 +65,9 @@ Model-specific guidelines.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -113,7 +115,9 @@ Agent-specific guidelines.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -161,7 +165,9 @@ Planning guidelines.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -210,7 +216,9 @@ Platform-specific guidelines.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -245,7 +253,9 @@ CI-authoritative guidelines.` process.env.CI = 'false'; process.env.GITHUB_ACTIONS = 'true'; - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -283,7 +293,9 @@ All dimensions must match.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -340,7 +352,9 @@ All dimensions must match.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -396,7 +410,9 @@ Node.js project guidelines.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -435,7 +451,9 @@ Feature branch guidelines.` .mockResolvedValue('feature/add-login'); try { - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -470,7 +488,9 @@ Feature branch guidelines.` const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); try { - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => { @@ -509,7 +529,9 @@ Feature branch guidelines.` ); process.env.XDG_CONFIG_HOME = path.join(testDir, '.config'); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -540,7 +562,9 @@ Feature branch guidelines.` const nonGitDir = path.join(testDir, 'not-a-git-repo'); mkdirSync(nonGitDir, { recursive: true }); - const { default: plugin } = await import('./index.js'); + const { + default: { server: plugin }, + } = await import('./index.js'); const mockClient = { tool: { ids: vi.fn(async () => ({ data: [] })) } }; const hooks = await plugin({ client: mockClient as unknown, @@ -593,13 +617,13 @@ tools: Tools rule.` ); - const formatted = await readAndFormatRules(toRules([rulePath]), { + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), { userPrompt: 'some prompt', availableToolIDs: ['mcp_websearch', 'mcp_bash'], }); - expect(formatted).toContain('tools-rule.mdc'); - expect(formatted).toContain('Tools rule'); + expect(formattedRules).toContain('tools-rule.mdc'); + expect(formattedRules).toContain('Tools rule'); }); it('should ignore array passed as second arg (legacy positional pattern rejected)', async () => { @@ -616,11 +640,11 @@ Legacy globs rule.` ); // eslint-disable-next-line @typescript-eslint/no-explicit-any - const formatted = await readAndFormatRules(toRules([rulePath]), [ + const { formattedRules } = await readAndFormatRules(toRules([rulePath]), [ 'src/app.ts', ] as any); - expect(formatted).toBe(''); + expect(formattedRules).toBe(''); }); it('should ignore third positional arg (legacy userPrompt rejected)', async () => { @@ -637,13 +661,13 @@ Legacy keywords rule.` ); // eslint-disable-next-line @typescript-eslint/no-explicit-any - const formatted = await (readAndFormatRules as any)( + const { formattedRules } = await (readAndFormatRules as any)( toRules([rulePath]), {}, 'help with testing' ); - expect(formatted).toBe(''); + expect(formattedRules).toBe(''); }); it('should ignore fourth positional arg (legacy availableToolIDs rejected)', async () => { @@ -660,13 +684,13 @@ Legacy tools rule.` ); // eslint-disable-next-line @typescript-eslint/no-explicit-any - const formatted = await (readAndFormatRules as any)( + const { formattedRules } = await (readAndFormatRules as any)( toRules([rulePath]), {}, undefined, ['mcp_websearch', 'mcp_bash'] ); - expect(formatted).toBe(''); + expect(formattedRules).toBe(''); }); }); diff --git a/src/index.ts b/src/index.ts index 112550d..7d82167 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,7 +4,7 @@ * Discovers markdown rule files and injects them into the system prompt. */ -import type { PluginInput } from '@opencode-ai/plugin'; +import type { Plugin, PluginInput } from '@opencode-ai/plugin'; import { discoverRuleFiles } from './utils.js'; import { OpenCodeRulesRuntime } from './runtime.js'; import { createSessionStore, type SessionState } from './session-store.js'; @@ -62,5 +62,7 @@ const __testOnly = Object.freeze( }) ); -export default openCodeRulesPlugin; +const id = 'opencode-rules' as const; +const server = openCodeRulesPlugin satisfies Plugin; +export default { id, server }; export { __testOnly }; diff --git a/src/rule-filter.ts b/src/rule-filter.ts index c65e051..706a70f 100644 --- a/src/rule-filter.ts +++ b/src/rule-filter.ts @@ -59,6 +59,14 @@ export function toolsMatchAvailable( return requiredTools.some(tool => availableSet.has(tool)); } +/** + * Result of reading and formatting rules + */ +export interface FilterResult { + formattedRules: string; + matchedPaths: string[]; +} + /** * Runtime filter context for conditional rule matching */ @@ -93,12 +101,13 @@ export interface RuleFilterContext { export async function readAndFormatRules( files: DiscoveredRule[], context: RuleFilterContext = {} -): Promise { +): Promise { if (files.length === 0) { - return ''; + return { formattedRules: '', matchedPaths: [] }; } const ruleContents: string[] = []; + const matchedPaths: string[] = []; const availableToolSet = context.availableToolIDs && context.availableToolIDs.length > 0 ? new Set(context.availableToolIDs) @@ -244,14 +253,17 @@ export async function readAndFormatRules( // Use cached stripped content for output // Use relativePath for unique headings instead of just filename ruleContents.push(`## ${relativePath}\n\n${strippedContent}`); + matchedPaths.push(filePath); } if (ruleContents.length === 0) { - return ''; + return { formattedRules: '', matchedPaths: [] }; } - return ( - `# OpenCode Rules\n\nPlease follow the following rules:\n\n` + - ruleContents.join('\n\n---\n\n') - ); + return { + formattedRules: + `# OpenCode Rules\n\nPlease follow the following rules:\n\n` + + ruleContents.join('\n\n---\n\n'), + matchedPaths, + }; } diff --git a/src/runtime.ts b/src/runtime.ts index 33bddd9..f198fde 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -21,6 +21,7 @@ import { type ChatMessageInput, type ChatMessageOutput, } from './runtime-chat.js'; +import { writeActiveRulesState } from './active-rules-state.js'; interface MessagesTransformOutput { messages: MessageWithInfo[]; @@ -217,11 +218,15 @@ export class OpenCodeRulesRuntime { this.debugLog ); - const formattedRules = await readAndFormatRules( + const { formattedRules, matchedPaths } = await readAndFormatRules( this.ruleFiles, filterContext ); + if (sessionID) { + writeActiveRulesState(sessionID, matchedPaths); + } + if (!formattedRules) { this.debugLog('No applicable rules for current context'); return output ?? {}; diff --git a/src/utils.ts b/src/utils.ts index dae9e4a..d92062a 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -25,6 +25,7 @@ export { toolsMatchAvailable, readAndFormatRules, type RuleFilterContext, + type FilterResult, } from './rule-filter.js'; // Re-export from message-paths diff --git a/tsconfig.json b/tsconfig.json index 9b75f56..fbe2351 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,8 +4,9 @@ "module": "ESNext", "moduleResolution": "bundler", "lib": ["ES2022"], + "jsx": "react-jsx", "outDir": "./dist", - "rootDir": "./src", + "rootDir": ".", "strict": true, "esModuleInterop": true, "skipLibCheck": true, @@ -27,6 +28,13 @@ "isolatedModules": true, "verbatimModuleSyntax": true }, - "include": ["src/**/*"], - "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"] + "include": ["src/**/*", "tui/**/*"], + "exclude": [ + "node_modules", + "dist", + "**/*.test.ts", + "**/*.spec.ts", + "**/*.test.tsx", + "**/*.spec.tsx" + ] } diff --git a/tui/data/rules.test.ts b/tui/data/rules.test.ts new file mode 100644 index 0000000..f2dc669 --- /dev/null +++ b/tui/data/rules.test.ts @@ -0,0 +1,502 @@ +// tui/data/rules.test.ts +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import path from 'path'; +import os from 'os'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync, chmodSync } from 'fs'; +import { clearRuleCache } from '../../src/rule-discovery.js'; +import { + _setStateDirForTesting, + writeActiveRulesState, +} from '../../src/active-rules-state.js'; +import { + ruleSource, + hasConditions, + formatConditionSummary, + disambiguateNames, + loadSidebarRules, + type SidebarRuleEntry, +} from './rules.js'; + +// ────────────────────────────────────────────── +// ruleSource +// ────────────────────────────────────────────── + +describe('ruleSource', () => { + it('returns "global" when projectDir is null', () => { + expect(ruleSource('/home/user/.config/opencode/rules/foo.md', null)).toBe( + 'global' + ); + }); + + it('returns "project" for files under projectDir/.opencode/rules/', () => { + expect(ruleSource('/project/.opencode/rules/foo.md', '/project')).toBe( + 'project' + ); + }); + + it('returns "project" for files in subdirectories under project rules', () => { + expect(ruleSource('/project/.opencode/rules/sub/deep.md', '/project')).toBe( + 'project' + ); + }); + + it('returns "global" for files not under projectDir/.opencode/rules/', () => { + expect( + ruleSource('/home/user/.config/opencode/rules/foo.md', '/project') + ).toBe('global'); + }); + + it('does not match partial path prefixes', () => { + // /project/.opencode/rules-extra/ should NOT match /project/.opencode/rules/ + expect( + ruleSource('/project/.opencode/rules-extra/foo.md', '/project') + ).toBe('global'); + }); +}); + +// ────────────────────────────────────────────── +// hasConditions +// ────────────────────────────────────────────── + +describe('hasConditions', () => { + it('returns false for undefined metadata', () => { + expect(hasConditions(undefined)).toBe(false); + }); + + it('returns false for empty metadata', () => { + expect(hasConditions({})).toBe(false); + }); + + it('returns true when globs is set', () => { + expect(hasConditions({ globs: ['**/*.ts'] })).toBe(true); + }); + + it('returns true when ci is false (still a condition)', () => { + expect(hasConditions({ ci: false })).toBe(true); + }); + + it('returns true for any single field', () => { + expect(hasConditions({ keywords: ['test'] })).toBe(true); + expect(hasConditions({ tools: ['mcp_bash'] })).toBe(true); + expect(hasConditions({ model: ['gpt-5'] })).toBe(true); + expect(hasConditions({ agent: ['coder'] })).toBe(true); + expect(hasConditions({ command: ['/plan'] })).toBe(true); + expect(hasConditions({ project: ['node'] })).toBe(true); + expect(hasConditions({ branch: ['main'] })).toBe(true); + expect(hasConditions({ os: ['linux'] })).toBe(true); + }); +}); + +// ────────────────────────────────────────────── +// formatConditionSummary +// ────────────────────────────────────────────── + +describe('formatConditionSummary', () => { + it('formats single array field', () => { + expect(formatConditionSummary({ globs: ['**/*.ts'] })).toBe( + 'globs: **/*.ts' + ); + }); + + it('formats multiple array values with commas', () => { + expect(formatConditionSummary({ keywords: ['auth', 'security'] })).toBe( + 'keywords: auth, security' + ); + }); + + it('formats multiple fields with commas', () => { + const result = formatConditionSummary({ + globs: ['**/*.ts'], + keywords: ['test'], + }); + expect(result).toBe('globs: **/*.ts, keywords: test'); + }); + + it('includes ci boolean', () => { + expect(formatConditionSummary({ ci: true })).toBe('ci: true'); + }); + + it('includes match mode', () => { + expect(formatConditionSummary({ model: ['gpt-5'], match: 'all' })).toBe( + 'model: gpt-5, match: all' + ); + }); + + it('formats all fields in canonical order', () => { + const result = formatConditionSummary({ + os: ['linux'], + globs: ['*.md'], + ci: false, + match: 'all', + }); + expect(result).toBe('globs: *.md, os: linux, ci: false, match: all'); + }); +}); + +// ────────────────────────────────────────────── +// disambiguateNames +// ────────────────────────────────────────────── + +describe('disambiguateNames', () => { + it('assigns filename stem for unique names', () => { + const entries: SidebarRuleEntry[] = [ + makeEntry({ path: 'foo.md' }), + makeEntry({ path: 'bar.mdc' }), + ]; + disambiguateNames(entries); + expect(entries[0]!.name).toBe('foo'); + expect(entries[1]!.name).toBe('bar'); + }); + + it('adds parent dir prefix for duplicate stems', () => { + const entries: SidebarRuleEntry[] = [ + makeEntry({ path: 'frontend/security.md' }), + makeEntry({ path: 'backend/security.md' }), + ]; + disambiguateNames(entries); + expect(entries[0]!.name).toBe('frontend/security'); + expect(entries[1]!.name).toBe('backend/security'); + }); + + it('falls back to full path for triple collisions after parent prefix', () => { + const entries: SidebarRuleEntry[] = [ + makeEntry({ path: 'apps/web/security.mdc' }), + makeEntry({ path: 'packages/web/security.mdc' }), + makeEntry({ path: 'other/security.md' }), + ]; + disambiguateNames(entries); + // web/security appears twice, falls back to full path (with extension) for those + expect(entries[0]!.name).toBe('apps/web/security.mdc'); + expect(entries[1]!.name).toBe('packages/web/security.mdc'); + // other/security is unique after parent prefix + expect(entries[2]!.name).toBe('other/security'); + }); + + it('disambiguates same-directory collisions with different extensions', () => { + const entries: SidebarRuleEntry[] = [ + makeEntry({ path: 'dup.md' }), + makeEntry({ path: 'dup.mdc' }), + ]; + disambiguateNames(entries); + // Both stem to "dup", no parent dir to prefix (dirname is "."). + // Falls back to full path with extension. + expect(entries[0]!.name).toBe('dup.md'); + expect(entries[1]!.name).toBe('dup.mdc'); + }); + + it('handles entries with subdirectory paths and different extensions', () => { + const entries: SidebarRuleEntry[] = [ + makeEntry({ path: 'rules/dup.md' }), + makeEntry({ path: 'rules/dup.mdc' }), + ]; + disambiguateNames(entries); + // Both stem to "dup", same parent "rules" -> "rules/dup" for both. + // Still ambiguous, falls back to full path with extension. + expect(entries[0]!.name).toBe('rules/dup.md'); + expect(entries[1]!.name).toBe('rules/dup.mdc'); + }); + + it('preserves multi-dot filenames correctly', () => { + const entries: SidebarRuleEntry[] = [ + makeEntry({ path: 'my.config.md' }), + makeEntry({ path: 'other.md' }), + ]; + disambiguateNames(entries); + // lastIndexOf('.') gives "my.config", not "my" + expect(entries[0]!.name).toBe('my.config'); + expect(entries[1]!.name).toBe('other'); + }); +}); + +// ────────────────────────────────────────────── +// loadSidebarRules (integration) +// ────────────────────────────────────────────── + +describe('loadSidebarRules', () => { + let testDir: string; + let savedXDG: string | undefined; + + beforeEach(() => { + testDir = mkdtempSync(path.join(os.tmpdir(), 'tui-rules-test-')); + savedXDG = process.env['XDG_CONFIG_HOME']; + clearRuleCache(); + }); + + afterEach(() => { + rmSync(testDir, { recursive: true, force: true }); + if (savedXDG === undefined) { + delete process.env['XDG_CONFIG_HOME']; + } else { + process.env['XDG_CONFIG_HOME'] = savedXDG; + } + }); + + it('discovers global rules when projectDir is null', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + writeFileSync(path.join(globalDir, 'rule.md'), '# Always'); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + const { rules, skippedCount } = await loadSidebarRules(null); + + expect(rules).toHaveLength(1); + expect(rules[0]!.source).toBe('global'); + expect(rules[0]!.name).toBe('rule'); + expect(rules[0]!.isConditional).toBe(false); + expect(rules[0]!.conditionSummary).toBe('always active'); + expect(skippedCount).toBe(0); + }); + + it('discovers both global and project rules', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + const projDir = path.join(testDir, 'project'); + const projRulesDir = path.join(projDir, '.opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + mkdirSync(projRulesDir, { recursive: true }); + writeFileSync(path.join(globalDir, 'global.md'), '# Global'); + writeFileSync(path.join(projRulesDir, 'local.md'), '# Local'); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + const { rules } = await loadSidebarRules(projDir); + + expect(rules).toHaveLength(2); + // Project rules sort first + expect(rules[0]!.source).toBe('project'); + expect(rules[1]!.source).toBe('global'); + }); + + it('parses metadata for conditional rules', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + writeFileSync( + path.join(globalDir, 'conditional.mdc'), + `---\nglobs:\n - "**/*.ts"\nkeywords:\n - testing\n---\nRule content` + ); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + const { rules } = await loadSidebarRules(null); + + expect(rules).toHaveLength(1); + expect(rules[0]!.isConditional).toBe(true); + expect(rules[0]!.conditionSummary).toContain('globs'); + expect(rules[0]!.conditionSummary).toContain('keywords'); + expect(rules[0]!.metadata.globs).toEqual(['**/*.ts']); + }); + + it('sorts project rules before global, alphabetical within group', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + const projDir = path.join(testDir, 'project'); + const projRulesDir = path.join(projDir, '.opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + mkdirSync(projRulesDir, { recursive: true }); + writeFileSync(path.join(globalDir, 'zebra.md'), '# Z'); + writeFileSync(path.join(globalDir, 'alpha.md'), '# A'); + writeFileSync(path.join(projRulesDir, 'beta.md'), '# B'); + writeFileSync(path.join(projRulesDir, 'aardvark.md'), '# AA'); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + const { rules } = await loadSidebarRules(projDir); + + expect(rules.map(r => `${r.source}:${r.name}`)).toEqual([ + 'project:aardvark', + 'project:beta', + 'global:alpha', + 'global:zebra', + ]); + }); + + it('increments skippedCount for unreadable files', async () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + writeFileSync(path.join(globalDir, 'readable.md'), '# OK'); + const unreadable = path.join(globalDir, 'unreadable.md'); + writeFileSync(unreadable, '# Nope'); + chmodSync(unreadable, 0o000); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + const { rules, skippedCount } = await loadSidebarRules(null); + + // One readable, one unreadable + expect(rules).toHaveLength(1); + expect(rules[0]!.name).toBe('readable'); + expect(skippedCount).toBe(1); + + // getCachedRule() logs its own warning for read failures — + // loadSidebarRules does NOT add a second one (no duplicate logs). + // But getCachedRule's internal warning should still fire: + expect(warnSpy).toHaveBeenCalled(); + + // Restore permissions for cleanup + chmodSync(unreadable, 0o644); + warnSpy.mockRestore(); + }); +}); + +// ────────────────────────────────────────────── +// loadSidebarRules isActive behavior +// ────────────────────────────────────────────── + +describe('loadSidebarRules isActive behavior', () => { + let testDir: string; + let stateDir: string; + let savedXDG: string | undefined; + + beforeEach(() => { + testDir = mkdtempSync(path.join(os.tmpdir(), 'tui-rules-active-test-')); + stateDir = path.join(testDir, 'state'); + mkdirSync(stateDir, { recursive: true }); + savedXDG = process.env['XDG_CONFIG_HOME']; + clearRuleCache(); + _setStateDirForTesting(stateDir); + }); + + afterEach(() => { + _setStateDirForTesting(null); + rmSync(testDir, { recursive: true, force: true }); + if (savedXDG === undefined) { + delete process.env['XDG_CONFIG_HOME']; + } else { + process.env['XDG_CONFIG_HOME'] = savedXDG; + } + }); + + it('sets hasEvaluationState to false when no sessionId provided', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + writeFileSync(path.join(globalDir, 'rule.md'), '# Always'); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + const result = await loadSidebarRules(null); + + expect(result.hasEvaluationState).toBe(false); + }); + + it('sets hasEvaluationState to false when state file does not exist', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + writeFileSync(path.join(globalDir, 'rule.md'), '# Always'); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + const result = await loadSidebarRules(null, 'nonexistent-session'); + + expect(result.hasEvaluationState).toBe(false); + }); + + it('sets hasEvaluationState to true when state file exists', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + writeFileSync(path.join(globalDir, 'rule.md'), '# Always'); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + writeActiveRulesState('test-session', []); + // Wait for async write to complete + await new Promise(resolve => setTimeout(resolve, 50)); + + const result = await loadSidebarRules(null, 'test-session'); + + expect(result.hasEvaluationState).toBe(true); + }); + + it('sets isActive to true for unconditional rules without state file', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + writeFileSync(path.join(globalDir, 'always.md'), '# Always active'); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + const { rules } = await loadSidebarRules(null); + + expect(rules[0]!.isConditional).toBe(false); + expect(rules[0]!.isActive).toBe(true); + }); + + it('sets isActive to null for conditional rules without state file', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + writeFileSync( + path.join(globalDir, 'conditional.mdc'), + `---\nglobs:\n - "**/*.ts"\n---\nConditional rule` + ); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + const { rules } = await loadSidebarRules(null); + + expect(rules[0]!.isConditional).toBe(true); + expect(rules[0]!.isActive).toBe(null); + }); + + it('sets isActive based on matchedRulePaths when state file exists', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + const matchedPath = path.join(globalDir, 'matched.md'); + const unmatchedPath = path.join(globalDir, 'unmatched.md'); + writeFileSync(matchedPath, '# Matched'); + writeFileSync(unmatchedPath, '# Unmatched'); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + writeActiveRulesState('test-session', [matchedPath]); + await new Promise(resolve => setTimeout(resolve, 50)); + + const { rules } = await loadSidebarRules(null, 'test-session'); + + const matched = rules.find(r => r.name === 'matched'); + const unmatched = rules.find(r => r.name === 'unmatched'); + + expect(matched!.isActive).toBe(true); + expect(unmatched!.isActive).toBe(false); + }); + + it('correctly matches conditional rules with state file', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + const conditionalPath = path.join(globalDir, 'conditional.mdc'); + writeFileSync( + conditionalPath, + `---\nglobs:\n - "**/*.ts"\n---\nConditional rule` + ); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + // Conditional rule is in matchedRulePaths + writeActiveRulesState('test-session', [conditionalPath]); + await new Promise(resolve => setTimeout(resolve, 50)); + + const { rules } = await loadSidebarRules(null, 'test-session'); + + expect(rules[0]!.isConditional).toBe(true); + expect(rules[0]!.isActive).toBe(true); + }); + + it('marks conditional rules as inactive when not in matchedRulePaths', async () => { + const globalDir = path.join(testDir, '.config', 'opencode', 'rules'); + mkdirSync(globalDir, { recursive: true }); + writeFileSync( + path.join(globalDir, 'conditional.mdc'), + `---\nglobs:\n - "**/*.ts"\n---\nConditional rule` + ); + process.env['XDG_CONFIG_HOME'] = path.join(testDir, '.config'); + + // Empty matchedRulePaths - nothing matched + writeActiveRulesState('test-session', []); + await new Promise(resolve => setTimeout(resolve, 50)); + + const { rules } = await loadSidebarRules(null, 'test-session'); + + expect(rules[0]!.isConditional).toBe(true); + expect(rules[0]!.isActive).toBe(false); + }); +}); + +/** Helper to create a minimal SidebarRuleEntry for disambiguation tests */ +function makeEntry( + overrides: Partial & { path: string } +): SidebarRuleEntry { + return { + name: '', + path: overrides.path, + source: overrides.source ?? 'global', + isConditional: overrides.isConditional ?? false, + conditionSummary: overrides.conditionSummary ?? 'always active', + metadata: overrides.metadata ?? {}, + isActive: overrides.isActive ?? true, + }; +} diff --git a/tui/data/rules.ts b/tui/data/rules.ts new file mode 100644 index 0000000..01ee163 --- /dev/null +++ b/tui/data/rules.ts @@ -0,0 +1,230 @@ +// tui/data/rules.ts +import { discoverRuleFiles, getCachedRule } from '../../src/rule-discovery.js'; +import type { RuleMetadata } from '../../src/rule-metadata.js'; +import { readActiveRulesState } from '../../src/active-rules-state.js'; +import path from 'path'; + +/** Represents a rule as displayed in the sidebar */ +export interface SidebarRuleEntry { + /** Display name (filename stem, disambiguated if needed) */ + name: string; + /** Relative file path from the rules directory root */ + path: string; + /** Whether this rule came from global or project-local rules dir */ + source: 'global' | 'project'; + /** Whether the rule has any conditional metadata */ + isConditional: boolean; + /** Human-readable condition summary */ + conditionSummary: string; + /** Full metadata for expanded view */ + metadata: RuleMetadata; + /** + * Active state of the rule. + * - true: rule is active (matched by evaluation or unconditional without state file) + * - false: rule is not active (not matched by evaluation) + * - null: state not yet determined (conditional rule without state file) + */ + isActive: boolean | null; +} + +export interface LoadSidebarRulesResult { + rules: SidebarRuleEntry[]; + skippedCount: number; + /** Whether active rules state was successfully read from disk */ + hasEvaluationState: boolean; +} + +/** + * Load all discovered rules formatted for sidebar display. + * Reuses discoverRuleFiles/getCachedRule from the server plugin. + * + * @param projectDir - Project directory or null (global rules only) + * @param sessionId - Optional session ID to read active rules state + */ +export async function loadSidebarRules( + projectDir: string | null, + sessionId?: string +): Promise { + // discoverRuleFiles accepts string | undefined, not null + const discovered = await discoverRuleFiles(projectDir ?? undefined); + + // Read active rules state if sessionId provided + const activeState = sessionId ? await readActiveRulesState(sessionId) : null; + const hasEvaluationState = activeState !== null; + const matchedPathsSet = hasEvaluationState + ? new Set(activeState.matchedRulePaths) + : null; + + const entries: SidebarRuleEntry[] = []; + let skippedCount = 0; + + for (const rule of discovered) { + const cached = await getCachedRule(rule.filePath); + if (!cached) { + // getCachedRule() already logs a warning for read failures, + // so we only increment the counter here — no duplicate log. + skippedCount++; + continue; + } + + const meta = cached.metadata; + const source = ruleSource(rule.filePath, projectDir); + const isConditional = hasConditions(meta); + const conditionSummary = isConditional + ? formatConditionSummary(meta!) + : 'always active'; + + // Determine isActive based on state file or fallback logic + let isActive: boolean | null; + if (matchedPathsSet !== null) { + // With state file: check if this rule's absolute path is in matchedPaths + isActive = matchedPathsSet.has(rule.filePath); + } else { + // Without state file: unconditional = true, conditional = null + isActive = isConditional ? null : true; + } + + entries.push({ + name: '', // placeholder — set in disambiguation pass + path: rule.relativePath, + source, + isConditional, + conditionSummary, + metadata: meta ?? {}, + isActive, + }); + } + + disambiguateNames(entries); + + // Sort: project first, then global. Active rules to top, then alpha by name. + const activeOrder = (v: boolean | null): number => + v === true ? 0 : v === null ? 1 : 2; + entries.sort((a, b) => { + if (a.source !== b.source) return a.source === 'project' ? -1 : 1; + const activeCmp = activeOrder(a.isActive) - activeOrder(b.isActive); + if (activeCmp !== 0) return activeCmp; + const nameCompare = a.name.localeCompare(b.name); + if (nameCompare !== 0) return nameCompare; + return a.path.localeCompare(b.path); + }); + + return { rules: entries, skippedCount, hasEvaluationState }; +} + +/** + * Determine if a rule file is project-local or global. + * Uses path.sep boundary check to avoid matching partial prefixes + * (e.g., /project/.opencode/rules-extra/ should not match). + */ +export function ruleSource( + filePath: string, + projectDir: string | null +): 'global' | 'project' { + if (!projectDir) return 'global'; + const projectRulesPrefix = + path.join(projectDir, '.opencode', 'rules') + path.sep; + return filePath.startsWith(projectRulesPrefix) ? 'project' : 'global'; +} + +/** + * Check if metadata has any conditional fields set. + */ +export function hasConditions(meta: RuleMetadata | undefined): boolean { + if (!meta) return false; + return !!( + meta.globs || + meta.keywords || + meta.tools || + meta.model || + meta.agent || + meta.command || + meta.project || + meta.branch || + meta.os || + meta.ci !== undefined + ); +} + +/** + * Build a human-readable, comma-separated summary of active conditions. + * E.g., "globs: src/*.ts, keywords: auth, security" + */ +export function formatConditionSummary(meta: RuleMetadata): string { + const parts: string[] = []; + + const arrayFields: Array<[keyof RuleMetadata, string]> = [ + ['globs', 'globs'], + ['keywords', 'keywords'], + ['tools', 'tools'], + ['model', 'model'], + ['agent', 'agent'], + ['command', 'command'], + ['project', 'project'], + ['branch', 'branch'], + ['os', 'os'], + ]; + + for (const [field, label] of arrayFields) { + const value = meta[field]; + if (Array.isArray(value) && value.length > 0) { + parts.push(`${label}: ${(value as string[]).join(', ')}`); + } + } + + if (meta.ci !== undefined) { + parts.push(`ci: ${String(meta.ci)}`); + } + + if (meta.match) { + parts.push(`match: ${meta.match}`); + } + + return parts.join(', '); +} + +/** + * Three-pass name disambiguation. + * Pass 1: Extract filename stem from each entry's path. + * Pass 2: For duplicate stems, prefix with parent directory. + * Pass 3: If still ambiguous (same parent or root-level), use full relative + * path (including extension) as the display name. + * + * Mutates entries[].name in place. + */ +export function disambiguateNames(entries: SidebarRuleEntry[]): void { + // Pass 1: assign stem names (filename without extension, using last dot) + for (const entry of entries) { + const basename = path.basename(entry.path); + const dotIndex = basename.lastIndexOf('.'); + entry.name = dotIndex > 0 ? basename.substring(0, dotIndex) : basename; + } + + // Pass 2: detect and resolve collisions with parent directory prefix + const stemCounts = new Map(); + for (const entry of entries) { + stemCounts.set(entry.name, (stemCounts.get(entry.name) ?? 0) + 1); + } + + for (const entry of entries) { + if ((stemCounts.get(entry.name) ?? 0) <= 1) continue; + + const dir = path.dirname(entry.path); + if (dir && dir !== '.') { + const parent = path.basename(dir); + entry.name = `${parent}/${entry.name}`; + } + } + + // Pass 3: if still ambiguous, use full relative path WITH extension + const nameCounts = new Map(); + for (const entry of entries) { + nameCounts.set(entry.name, (nameCounts.get(entry.name) ?? 0) + 1); + } + + for (const entry of entries) { + if ((nameCounts.get(entry.name) ?? 0) > 1) { + entry.name = entry.path; + } + } +} diff --git a/tui/index.tsx b/tui/index.tsx new file mode 100644 index 0000000..11a9818 --- /dev/null +++ b/tui/index.tsx @@ -0,0 +1,23 @@ +// tui/index.tsx +/** @jsxImportSource @opentui/solid */ +import type { TuiPlugin } from '@opencode-ai/plugin/tui'; +import { SidebarContent } from './slots/sidebar-content.js'; + +const id = 'opencode-rules' as const; + +const tui: TuiPlugin = async api => { + api.slots.register({ + order: 350, + slots: { + sidebar_content: (ctx, props) => ( + + ), + }, + }); +}; + +export default { id, tui }; diff --git a/tui/slots/sidebar-content.tsx b/tui/slots/sidebar-content.tsx new file mode 100644 index 0000000..ee6ff54 --- /dev/null +++ b/tui/slots/sidebar-content.tsx @@ -0,0 +1,364 @@ +// tui/slots/sidebar-content.tsx +/** @jsxImportSource @opentui/solid */ +import { + createSignal, + createEffect, + createMemo, + onCleanup, + Show, + For, + type JSX, +} from 'solid-js'; +import type { TuiPluginApi, TuiTheme } from '@opencode-ai/plugin/tui'; +import { loadSidebarRules, type SidebarRuleEntry } from '../data/rules.js'; + +interface SidebarContentProps { + sessionId: string; + api: TuiPluginApi; + theme: TuiTheme; +} + +type ThemeColor = string | import('@opentui/core').RGBA; + +interface ThemeColors { + text: ThemeColor; + textMuted: ThemeColor; + success: ThemeColor; + [key: string]: unknown; +} + +interface RuleSectionProps { + title: string; + rules: SidebarRuleEntry[]; + theme: ThemeColors; + open: boolean; + onToggle: () => void; + expandedIndex: number | null; + globalOffset: number; + onExpandToggle: (globalIndex: number) => void; + hasEvaluationState: boolean; +} + +function RuleSection(props: RuleSectionProps): JSX.Element { + const activeCount = createMemo( + () => props.rules.filter(r => r.isActive === true).length + ); + + const headerCount = createMemo(() => { + if (props.hasEvaluationState) { + return `(${activeCount()}/${props.rules.length})`; + } + return `(${props.rules.length})`; + }); + + const bulletColor = (rule: SidebarRuleEntry): ThemeColor => { + return rule.isActive === true ? props.theme.success : props.theme.textMuted; + }; + + return ( + 0}> + + props.onToggle()}> + {props.open ? '▼' : '▶'} + + {props.title} + + + {' '} + {headerCount()} + + + + + + + {(rule, localIndex) => { + const globalIndex = () => props.globalOffset + localIndex(); + return ( + props.onExpandToggle(globalIndex())} + > + + • + {rule.name} + + + + {rule.path} + 0}> + + Globs: {rule.metadata.globs!.join(', ')} + + + 0}> + + Keywords: {rule.metadata.keywords!.join(', ')} + + + 0}> + + Tools: {rule.metadata.tools!.join(', ')} + + + 0}> + + Model: {rule.metadata.model!.join(', ')} + + + 0}> + + Agent: {rule.metadata.agent!.join(', ')} + + + 0}> + + Command: {rule.metadata.command!.join(', ')} + + + 0}> + + Project: {rule.metadata.project!.join(', ')} + + + 0}> + + Branch: {rule.metadata.branch!.join(', ')} + + + 0}> + + OS: {rule.metadata.os!.join(', ')} + + + + + CI: {String(rule.metadata.ci)} + + + + + Match: {rule.metadata.match} + + + + + + ); + }} + + + + + ); +} + +export function SidebarContent(props: SidebarContentProps): JSX.Element { + const [rules, setRules] = createSignal([]); + const [status, setStatus] = createSignal<'loading' | 'loaded' | 'error'>( + 'loading' + ); + const [skippedCount, setSkippedCount] = createSignal(0); + const [hasEvaluationState, setHasEvaluationState] = createSignal(false); + const [expandedIndex, setExpandedIndex] = createSignal(null); + const [lastDir, setLastDir] = createSignal( + undefined + ); + const [lastSessionId, setLastSessionId] = createSignal( + undefined + ); + const [projectOpen, setProjectOpen] = createSignal(false); + const [globalOpen, setGlobalOpen] = createSignal(false); + const [refreshCounter, setRefreshCounter] = createSignal(0); + + const theme = (): ThemeColors => props.theme.current as ThemeColors; + + const resolveProjectDir = (): string | null => { + return props.api.state.path.directory ?? null; + }; + + // Monotonic counter to detect stale async results + let requestId = 0; + // Debounce timer for event-driven refresh + let debounceTimer: ReturnType | null = null; + + // Initial load: triggered by session/directory change, resets all UI state + const loadRulesInitial = async (): Promise => { + const thisRequest = ++requestId; + const dir = resolveProjectDir(); + const sessionId = props.sessionId; + + setLastDir(dir); + setLastSessionId(sessionId); + setStatus('loading'); + + try { + const result = await loadSidebarRules(dir, sessionId); + // Discard if a newer request started + if (requestId !== thisRequest) return; + setRules(result.rules); + setSkippedCount(result.skippedCount); + setHasEvaluationState(result.hasEvaluationState); + setStatus('loaded'); + } catch (err) { + // Discard if a newer request started + if (requestId !== thisRequest) return; + console.error('[opencode-rules] Failed to load rules:', err); + setStatus('error'); + } + }; + + // Refresh load: triggered by events, only updates rule data (no UI state reset) + const loadRulesRefresh = async (): Promise => { + // Skip refresh if initial load is still in flight + if (status() === 'loading') return; + + const thisRequest = ++requestId; + const dir = resolveProjectDir(); + const sessionId = props.sessionId; + + try { + const result = await loadSidebarRules(dir, sessionId); + // Discard if a newer request started + if (requestId !== thisRequest) return; + setRules(result.rules); + setSkippedCount(result.skippedCount); + setHasEvaluationState(result.hasEvaluationState); + setStatus('loaded'); + } catch (err) { + // Discard if a newer request started + if (requestId !== thisRequest) return; + console.error('[opencode-rules] Failed to refresh rules:', err); + } + }; + + // Effect 1: Initial load on session/directory change + createEffect(() => { + const currentSessionId = props.sessionId; + const currentDir = resolveProjectDir(); + + // Check if session or directory changed + if (currentSessionId !== lastSessionId() || currentDir !== lastDir()) { + // Clear pending debounce from previous session + if (debounceTimer !== null) { + clearTimeout(debounceTimer); + debounceTimer = null; + } + // Reset UI state on session/directory change + setExpandedIndex(null); + setProjectOpen(false); + setGlobalOpen(false); + void loadRulesInitial(); + } + }); + + // Effect 2: Refresh on event-driven updates (refreshCounter changes) + createEffect(() => { + const counter = refreshCounter(); + if (counter > 0) { + void loadRulesRefresh(); + } + }); + + // Subscribe to OpenCode events with debounce + const triggerRefresh = (event: { + type: string; + properties: Record; + }): void => { + // Filter events to current sessionId before debouncing + // OpenCode SDK events nest sessionID inside properties: { type, properties: { sessionID, ... } } + const eventSessionID = event.properties.sessionID; + if ( + typeof eventSessionID === 'string' && + eventSessionID !== props.sessionId + ) { + return; + } + + if (debounceTimer !== null) { + clearTimeout(debounceTimer); + } + debounceTimer = setTimeout(() => { + debounceTimer = null; + setRefreshCounter(c => c + 1); + }, 150); + }; + + const unsubMessageUpdated = props.api.event.on( + 'message.updated', + triggerRefresh + ); + const unsubSessionStatus = props.api.event.on( + 'session.status', + triggerRefresh + ); + + onCleanup(() => { + if (debounceTimer !== null) { + clearTimeout(debounceTimer); + } + unsubMessageUpdated(); + unsubSessionStatus(); + }); + + const toggleExpand = (index: number): void => { + setExpandedIndex(prev => (prev === index ? null : index)); + }; + + const projectRules = createMemo(() => + rules().filter(r => r.source === 'project') + ); + const globalRules = createMemo(() => + rules().filter(r => r.source === 'global') + ); + + return ( + + + Rules + + + + Loading... + + + Failed to load rules + + + + 0} + fallback={No rules found} + > + setProjectOpen(x => !x)} + expandedIndex={expandedIndex()} + globalOffset={0} + onExpandToggle={toggleExpand} + hasEvaluationState={hasEvaluationState()} + /> + setGlobalOpen(x => !x)} + expandedIndex={expandedIndex()} + globalOffset={projectRules().length} + onExpandToggle={toggleExpand} + hasEvaluationState={hasEvaluationState()} + /> + + 0}> + + {skippedCount()} rules skipped (unreadable) + + + + + ); +} diff --git a/tui/types/opencode-plugin-tui.d.ts b/tui/types/opencode-plugin-tui.d.ts new file mode 100644 index 0000000..4e11948 --- /dev/null +++ b/tui/types/opencode-plugin-tui.d.ts @@ -0,0 +1,78 @@ +// tui/types/opencode-plugin-tui.d.ts +// +// Vendored type declarations for @opencode-ai/plugin/tui. +// Allows tsc to compile TUI code without requiring the optional +// peer dependency to be installed at compile time. +// +// Source: @opencode-ai/plugin v1.3.7 (packages/plugin/src/tui.ts) +// If bumping @opencode-ai/plugin, re-verify these types match. + +declare module '@opencode-ai/plugin/tui' { + export interface TuiTheme { + [key: string]: unknown; + } + + export interface TuiSlotMap { + sidebar_content: { session_id: string }; + } + + export interface TuiSlotContext { + theme: TuiTheme; + } + + export type SlotRenderer = ( + ctx: Readonly, + props: TuiSlotMap[K] + ) => JSX.Element; + + export interface TuiSlotPlugin { + id?: never; + order?: number; + setup?: (ctx: Readonly, renderer: unknown) => void; + dispose?: () => void; + slots: { + [K in keyof TuiSlotMap]?: SlotRenderer; + }; + } + + export interface TuiSlots { + register: (plugin: TuiSlotPlugin) => string; + } + + export interface TuiWorkspace { + current: () => string | undefined; + set: (id?: string) => void; + } + + export interface TuiState { + readonly path: { + state: string; + config: string; + worktree: string; + directory: string; + }; + workspace: { + get: (id: string) => { directory: string | null } | undefined; + }; + } + + export interface TuiEventBus { + on: ( + type: string, + handler: (event: { + type: string; + properties: Record; + }) => void + ) => () => void; + } + + export interface TuiPluginApi { + slots: TuiSlots; + workspace: TuiWorkspace; + state: TuiState; + kv: unknown; + event: TuiEventBus; + } + + export type TuiPlugin = (api: TuiPluginApi) => Promise | void; +} diff --git a/vitest.config.ts b/vitest.config.ts index 776fc9b..02a948d 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -4,7 +4,7 @@ export default defineConfig({ test: { globals: true, environment: 'node', - include: ['src/**/*.{test,spec}.{ts,tsx}'], + include: ['src/**/*.{test,spec}.{ts,tsx}', 'tui/**/*.{test,spec}.{ts,tsx}'], exclude: ['node_modules', 'dist'], coverage: { provider: 'v8',