From 9de7b1771da018de19edfac315616e06e48c1c4d Mon Sep 17 00:00:00 2001 From: juwonllee2024-dotcom <266584234+juwonllee2024-dotcom@users.noreply.github.com> Date: Fri, 21 Aug 2026 08:17:01 -0700 Subject: [PATCH] feat: add context lens explanations --- .github/workflows/release.yml | 12 +- CHANGELOG.md | 13 ++ README.md | 37 +++- SPECIFICATION.md | 5 +- docs/verification/context-lens-v1.2.md | 43 +++++ package-lock.json | 4 +- package.json | 2 +- src/cli.ts | 19 +- src/explain/index.ts | 242 +++++++++++++++++++++++++ src/index.ts | 1 + tests/explain.test.ts | 84 +++++++++ 11 files changed, 450 insertions(+), 12 deletions(-) create mode 100644 docs/verification/context-lens-v1.2.md create mode 100644 src/explain/index.ts create mode 100644 tests/explain.test.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 812362b..cbacb05 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -27,10 +27,20 @@ jobs: npm test npm run build + - name: Pack verified CLI tarball + run: | + mkdir -p release + package_version="${GITHUB_REF_NAME#v}" + npm pack --pack-destination release + tar -tzf "release/rulesync-${package_version}.tgz" >/dev/null + sha256sum "release/rulesync-${package_version}.tgz" > "release/rulesync-${package_version}.tgz.sha256" + - name: Create GitHub Release uses: softprops/action-gh-release@v1 with: - files: dist/* + files: | + dist/* + release/* draft: false prerelease: false env: diff --git a/CHANGELOG.md b/CHANGELOG.md index 65e1363..cee07f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,19 @@ All notable changes to `RuleSync` will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.2.0] - 2026-08-21 + +### Added + +- `rulesync explain ` (Context Lens) predicts which canonical rules apply to a workspace file and shows each decision's source line, scope, and reason. +- Pretty, JSON, and Markdown Context Lens output for local review, CI, and pull requests. +- Verified release tarball attached to GitHub Releases for installation when the public npm `rulesync` name resolves to another project. + +### Security + +- Context Lens never prints rule bodies, calls a network, executes shell commands, or reads outside the workspace boundary. +- Output explicitly states that static scope prediction does not prove provider runtime loading or compliance. + ## [1.1.0] - 2026-08-18 ### Added diff --git a/README.md b/README.md index 5797802..ea6398b 100644 --- a/README.md +++ b/README.md @@ -52,16 +52,23 @@ Try `RuleSync` immediately in any project without installation: ```bash +# Download the verified rulesync-1.2.0.tgz asset from GitHub Releases. +# The public npm name `rulesync` currently belongs to another project. +npm install --global ./rulesync-1.2.0.tgz + # 1. Bootstrap canonical AGENTS.md rule file and configuration -npx rulesync init +rulesync init -# 2. Lint your AI agent rules for conflicts, duplication, and token bloat -npx rulesync lint +# 2. Ask why a rule applies to one file +rulesync explain src/app.ts --target cursor -# 3. Cross-compile target instruction files for all installed AI tools -npx rulesync build +# 3. Lint and cross-compile target instruction files +rulesync lint +rulesync build ``` +> **Package note:** `npx rulesync` is not safe before installing the release tarball because the npm registry name currently resolves to a different package. Each release includes a SHA-256 file beside the tarball so installation stays reviewable and offline after download. + ### See exactly what your agent receives Rule files can be synchronized and still be unclear at review time. `receipt` creates a local fingerprint for the canonical source and every compiled target: @@ -79,6 +86,18 @@ npx rulesync receipt --check --format json --output .rulesync/context-receipt.js Share the context ID in a pull request when someone asks, β€œWhich instructions did the agent see?” A receipt fingerprints expected compiled bytes; it does not claim runtime loading. +### Context Lens: answer β€œwhy did this rule apply?” + +`receipt` proves generated bytes are synchronized. `explain` answers the next question: **for this exact file, which rules are included, which are excluded, and which glob caused the decision?** It prints rule names and source lines, never rule bodies: + +```bash +rulesync explain src/payments/checkout.ts --target cursor +rulesync explain tests/checkout.spec.ts --format markdown --output .rulesync/checkout-context.md +rulesync explain src/payments/checkout.ts --format json +``` + +Context Lens is a local static prediction. It does not claim that Cursor, Claude, Copilot, or another provider loaded or obeyed the resulting instructions at runtime. + --- ## πŸ” Why RuleSync? @@ -166,6 +185,14 @@ npx rulesync diff [--target cursor] Creates a machine-readable, Markdown, or standalone HTML fingerprint of every configured target. `--check` exits with code `1` when a target is missing or drifted. ```bash npx rulesync receipt [--format json|markdown|html] [--output ] [--check] + +### `rulesync explain ` + +Predict which canonical rules apply to one workspace-relative file. Use `--target` to show the generated target path and `--format pretty|json|markdown` for terminal, CI, or pull-request output. + +```bash +rulesync explain src/index.ts --target claude +``` ``` --- diff --git a/SPECIFICATION.md b/SPECIFICATION.md index 6aaf576..6b1f6f6 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -1,4 +1,4 @@ -# RuleSync Product Specification & Architecture (v1.0.0) +# RuleSync Product Specification & Architecture (v1.2.0) ## 1. Product Vision & Mission `RuleSync` is an open-source CLI engine, static analyzer, and cross-format compiler for AI agent context instruction rules. It acts as the "ESLint & Babel for AI Agent Rules", allowing developers and engineering teams to maintain a single canonical source of truth (`AGENTS.md` or `.rulesync/`) and automatically compile, lint, optimize, and synchronize instructions across Cursor (`.cursor/rules/`), Anthropic Claude Code (`CLAUDE.md`), GitHub Copilot (`.github/copilot-instructions.md`), Cline / RooCode (`.cline/instructions.json`), Windsurf (`.windsurfrules`), and OpenCode. @@ -25,6 +25,7 @@ | `rulesync check` | CI verification mode β€” checks if generated target files are up to date with source rules | `--quiet`, `--strict` | | `rulesync watch` | File-system watcher mode β€” auto-compiles targets whenever source rule files change | `--debounce ` | | `rulesync diff` | Displays colorized diff preview between source rules and target compiled rule files | `--target ` | +| `rulesync explain ` | Predicts which canonical rules apply to one workspace file and records the source line, scope, and decision reason | `--target `, `--format ` | --- @@ -111,7 +112,7 @@ * **CLI UX**: Commander.js + Picocolors (Zero external bloat, sub-5ms boot time) * **Build System**: Tsup / Esbuild (Single bundle CLI output + ESM/CJS exports) * **Test Runner**: Vitest (Unit tests, compiler snapshots, linter matrix tests) -* **Distribution**: npm (`npx rulesync`), GitHub Releases binary, Homebrew formula template. +* **Distribution**: verified GitHub Release tarball (npm registry name collision documented), with future npm publication possible under owner-controlled credentials. --- diff --git a/docs/verification/context-lens-v1.2.md b/docs/verification/context-lens-v1.2.md new file mode 100644 index 0000000..3775a42 --- /dev/null +++ b/docs/verification/context-lens-v1.2.md @@ -0,0 +1,43 @@ +# Context Lens v1.2.0 verification record + +Date: 2026-08-21 (America/Los_Angeles) + +## Real execution + +Input: this repository's canonical `AGENTS.md`, configured targets, and the workspace-relative path `src/cli.ts`. + +```text +node dist/cli.js explain src/cli.ts --target cursor --format markdown + +Summary: 2 applies Β· 1 excluded Β· 3 total +Code Style & Standards: applies, glob-match +Testing & Quality: excluded, glob-miss +Security & Privacy Guidelines: applies, unscoped +``` + +The JSON and Markdown reports expose rule names, source lines, scopes, statuses, and reasons. They do not print rule bodies. The report explicitly says it is a static scope prediction and does not prove provider runtime loading or compliance. + +## TDD evidence + +- RED: focused `tests/explain.test.ts` failed because `src/explain/index.js` did not exist. +- GREEN: focused suite passed 4/4 after the minimal Context Lens implementation. +- Regression coverage includes glob matches and misses, Windows path normalization, workspace traversal blocking, review-safe Markdown, and JSON output. + +## Release gates + +| Gate | Result | +| --- | --- | +| `npm test` | PASS β€” 7 files, 28 tests | +| `npm run typecheck` | PASS | +| `npm run lint` | PASS | +| `npm run build` | PASS β€” CJS, ESM, declarations | +| `npm audit --omit=dev` | PASS β€” 0 vulnerabilities | +| `npm pack --dry-run` | PASS β€” `rulesync-1.2.0.tgz` | +| Release tarball package smoke | PASS β€” installed tarball reports `1.2.0` and runs `explain` | +| `git diff --check` | PASS | + +Local tarball SHA-256: `438eb2919ba1251ab8f72f22c2f58f88bcd6e3952999014267dc9306b93ba4a6`. + +## Distribution boundary + +The public npm package named `rulesync` currently resolves to `dyoshikawa/rulesync` v16.14.0, not this repository. v1.2.0 therefore ships a verified GitHub Release tarball for explicit installation; npm publication remains unavailable without an owner-controlled npm token. diff --git a/package-lock.json b/package-lock.json index 0488987..149ab3d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rulesync", - "version": "1.1.0", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rulesync", - "version": "1.1.0", + "version": "1.2.0", "license": "MIT", "dependencies": { "commander": "^12.0.0", diff --git a/package.json b/package.json index 4d46ba9..681324e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rulesync", - "version": "1.1.0", + "version": "1.2.0", "description": "The ESLint & Babel for AI Agent Rules β€” Compile, lint, optimize, and sync instructions across AGENTS.md, CLAUDE.md, .cursor/rules, and Copilot.", "main": "./dist/index.js", "module": "./dist/index.mjs", diff --git a/src/cli.ts b/src/cli.ts index 9b640e1..e9d9480 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -13,13 +13,14 @@ import { handleCheck } from './commands/check.js'; import { handleWatch } from './commands/watch.js'; import { handleDiff } from './commands/diff.js'; import { handleReceipt } from './receipt/index.js'; +import { handleExplain } from './explain/index.js'; const program = new Command(); program .name('rulesync') .description('The ESLint & Babel for AI Agent Rules β€” Compile, lint, optimize, and sync instructions across AGENTS.md, CLAUDE.md, .cursor/rules, and Copilot.') - .version('1.0.0'); + .version('1.2.0'); program .command('init') @@ -120,4 +121,20 @@ program } }); +program + .command('explain ') + .description('Explain which canonical rules apply to one workspace file') + .option('-t, --target ', 'Target to explain (claude | cursor | copilot | cline | windsurf | agents)') + .option('--format ', 'Output format (pretty | json | markdown)', 'pretty') + .option('-o, --output ', 'Write the explanation to an explicit workspace-relative path') + .action(async (inputPath, options) => { + try { + const success = handleExplain(inputPath, options); + if (!success) process.exit(1); + } catch (err: any) { + console.error(pc.red(`??Explain failed: ${err.message}`)); + process.exit(1); + } + }); + program.parse(process.argv); diff --git a/src/explain/index.ts b/src/explain/index.ts new file mode 100644 index 0000000..bf4cc1c --- /dev/null +++ b/src/explain/index.ts @@ -0,0 +1,242 @@ +/** + * Context Lens: explain which canonical rules match one workspace file. + * + * This is a static scope prediction. It does not claim that a provider + * loaded or obeyed the generated instructions at runtime. + */ + +import * as fs from 'fs'; +import * as path from 'path'; +import { compileToTargets } from '../compiler/matrix.js'; +import { loadConfig } from '../config/index.js'; +import { parseMarkdownToART } from '../parser/art.js'; +import { TargetAdapterName } from '../types/index.js'; +import { normalizeRelativePath, sanitizeWorkspacePath } from '../utils/path.js'; + +export type ExplainFormat = 'pretty' | 'json' | 'markdown'; +export type ExplainRuleStatus = 'applies' | 'excluded'; +export type ExplainRuleReason = 'always-apply' | 'unscoped' | 'glob-match' | 'glob-miss'; + +export interface ExplainRule { + id: string; + title: string; + line: number; + globs: string[]; + status: ExplainRuleStatus; + reason: ExplainRuleReason; +} + +export interface ExplainTarget { + target: TargetAdapterName; + path: string; +} + +export interface ContextExplanation { + schemaVersion: 1; + generatedAt: string; + input: { path: string }; + source: { path: string }; + target?: ExplainTarget; + targets: ExplainTarget[]; + rules: ExplainRule[]; + summary: { applies: number; excluded: number; total: number }; + caveat: string; +} + +export interface ExplainOptions { + cwd?: string; + target?: TargetAdapterName; + format?: ExplainFormat; + output?: string; + generatedAt?: string; +} + +function escapeRegExp(value: string): string { + return value.replace(/[|\\{}()[\]^$+?.]/g, '\\$&'); +} + +function globToRegExp(glob: string): RegExp { + const normalized = glob.replace(/\\/g, '/').replace(/^\.\//, ''); + let source = '^'; + + for (let index = 0; index < normalized.length; index += 1) { + const character = normalized[index]; + if (character === '*' && normalized[index + 1] === '*') { + if (normalized[index + 2] === '/') { + source += '(?:.*/)?'; + index += 2; + } else { + source += '.*'; + index += 1; + } + } else if (character === '*') { + source += '[^/]*'; + } else if (character === '?') { + source += '[^/]'; + } else if (character === '{') { + const close = normalized.indexOf('}', index + 1); + if (close === -1) { + source += escapeRegExp(character); + } else { + const alternatives = normalized + .slice(index + 1, close) + .split(',') + .map((alternative) => escapeRegExp(alternative)) + .join('|'); + source += `(?:${alternatives})`; + index = close; + } + } else { + source += escapeRegExp(character); + } + } + + return new RegExp(`${source}$`); +} + +function matchesGlob(inputPath: string, pattern: string): boolean { + return globToRegExp(pattern).test(inputPath); +} + +function explainRule( + rule: ReturnType['rules'][number], + globalGlobs: string[] | undefined, + inputPath: string, +): ExplainRule { + const globs = rule.metadata.globs ?? globalGlobs ?? []; + if (rule.metadata.alwaysApply) { + return { id: rule.metadata.id, title: rule.metadata.title, line: rule.line, globs, status: 'applies', reason: 'always-apply' }; + } + if (globs.length === 0) { + return { id: rule.metadata.id, title: rule.metadata.title, line: rule.line, globs, status: 'applies', reason: 'unscoped' }; + } + const matched = globs.some((glob) => matchesGlob(inputPath, glob)); + return { + id: rule.metadata.id, + title: rule.metadata.title, + line: rule.line, + globs, + status: matched ? 'applies' : 'excluded', + reason: matched ? 'glob-match' : 'glob-miss', + }; +} + +export function createContextExplanation( + inputPath: string, + options: Pick = {}, +): ContextExplanation { + const cwd = options.cwd || process.cwd(); + if (!inputPath.trim()) throw new Error('Input path is required.'); + + const absoluteInputPath = sanitizeWorkspacePath(inputPath, cwd); + const relativeInputPath = normalizeRelativePath(absoluteInputPath, cwd); + if (!relativeInputPath || relativeInputPath === '.') throw new Error('Input path must identify a workspace file.'); + + const config = loadConfig(cwd); + const sourcePath = sanitizeWorkspacePath(config.source, cwd); + if (!fs.existsSync(sourcePath)) { + throw new Error(`Source rule file "${config.source}" not found. Run "rulesync init" first.`); + } + + const markdown = fs.readFileSync(sourcePath, 'utf8'); + const art = parseMarkdownToART(markdown, config.source); + const targetOutputs = compileToTargets(art, options.target ? [options.target] : config.targets, config); + const rules = art.rules.map((rule) => explainRule(rule, art.globalGlobs, relativeInputPath)); + const applies = rules.filter((rule) => rule.status === 'applies').length; + + return { + schemaVersion: 1, + generatedAt: options.generatedAt || new Date().toISOString(), + input: { path: relativeInputPath }, + source: { path: config.source }, + ...(options.target && targetOutputs[0] + ? { target: { target: targetOutputs[0].target, path: targetOutputs[0].relativePath } } + : {}), + targets: targetOutputs.map((output) => ({ target: output.target, path: output.relativePath })), + rules, + summary: { applies, excluded: rules.length - applies, total: rules.length }, + caveat: 'Static scope prediction only; it does not prove an agent loaded or obeyed these rules at runtime.', + }; +} + +function escapeMarkdown(value: string): string { + return value.replace(/\\/g, '\\\\').replace(/\|/g, '\\|'); +} + +export function renderExplainJson(report: ContextExplanation): string { + return `${JSON.stringify(report, null, 2)}\n`; +} + +export function renderExplainMarkdown(report: ContextExplanation): string { + const targetLabel = report.target + ? `\`${report.target.target}\` β†’ \`${escapeMarkdown(report.target.path)}\`` + : report.targets.map((target) => `\`${target.target}\``).join(', '); + const lines = [ + '# RuleSync Context Lens', + '', + `Input: \`${escapeMarkdown(report.input.path)}\``, + `Source: \`${escapeMarkdown(report.source.path)}\``, + `Target: ${targetLabel}`, + `Summary: ${report.summary.applies} applies Β· ${report.summary.excluded} excluded Β· ${report.summary.total} total`, + '', + '| Status | Rule | Source line | Scope | Reason |', + '| --- | --- | ---: | --- | --- |', + ...report.rules.map((rule) => [ + rule.status.toUpperCase(), + escapeMarkdown(rule.title), + String(rule.line), + rule.globs.length > 0 ? `\`${escapeMarkdown(rule.globs.join(', '))}\`` : 'global', + rule.reason, + ].join(' | ')), + '', + report.caveat, + '', + ]; + return lines.join('\n'); +} + +export function renderExplainPretty(report: ContextExplanation): string { + const targetLabel = report.target + ? `${report.target.target} β†’ ${report.target.path}` + : report.targets.map((target) => target.target).join(', '); + const lines = [ + 'RuleSync Context Lens', + `Input: ${report.input.path}`, + `Target: ${targetLabel}`, + '', + 'Rules:', + ...report.rules.map((rule) => { + const scope = rule.globs.length > 0 ? ` [${rule.globs.join(', ')}]` : ''; + return ` ${rule.status === 'applies' ? 'APPLIES' : 'EXCLUDED'} ${rule.title} (line ${rule.line}) β€” ${rule.reason}${scope}`; + }), + '', + `Summary: ${report.summary.applies} applies, ${report.summary.excluded} excluded, ${report.summary.total} total`, + report.caveat, + '', + ]; + return lines.join('\n'); +} + +export function handleExplain(inputPath: string, options: ExplainOptions = {}): boolean { + const cwd = options.cwd || process.cwd(); + const report = createContextExplanation(inputPath, options); + const format = options.format || 'pretty'; + const content = format === 'json' + ? renderExplainJson(report) + : format === 'markdown' + ? renderExplainMarkdown(report) + : format === 'pretty' + ? renderExplainPretty(report) + : (() => { throw new Error(`Unsupported explanation format: ${format}`); })(); + + if (options.output) { + const outputPath = sanitizeWorkspacePath(options.output, cwd); + const parentDir = path.dirname(outputPath); + if (!fs.existsSync(parentDir)) fs.mkdirSync(parentDir, { recursive: true }); + fs.writeFileSync(outputPath, content, 'utf8'); + console.log(`Wrote ${format} context explanation: ${outputPath}`); + } else { + console.log(content); + } + return true; +} diff --git a/src/index.ts b/src/index.ts index ed0f362..04e1c63 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,3 +10,4 @@ export { loadConfig, saveConfig, DEFAULT_CONFIG } from './config/index.js'; export { generateUnifiedDiff } from './utils/diff.js'; export { sanitizeWorkspacePath, normalizeRelativePath } from './utils/path.js'; export * from './receipt/index.js'; +export * from './explain/index.js'; diff --git a/tests/explain.test.ts b/tests/explain.test.ts new file mode 100644 index 0000000..a846532 --- /dev/null +++ b/tests/explain.test.ts @@ -0,0 +1,84 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import * as fs from 'fs'; +import * as path from 'path'; +import { + createContextExplanation, + handleExplain, + renderExplainMarkdown, +} from '../src/explain/index.js'; + +describe('Context Lens explanation', () => { + const testDir = path.join(process.cwd(), 'tests', 'tmp_explain_workspace'); + + beforeEach(() => { + if (fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true }); + fs.mkdirSync(path.join(testDir, '.rulesync'), { recursive: true }); + fs.writeFileSync(path.join(testDir, 'AGENTS.md'), `# Repository Rules + +## TypeScript + +Use strict TypeScript. + +## Tests + +Test every behavior. + +## Safety +Never execute destructive commands. +`, 'utf8'); + fs.writeFileSync(path.join(testDir, '.rulesync', 'config.json'), JSON.stringify({ + source: 'AGENTS.md', + targets: ['cursor', 'claude'], + }), 'utf8'); + }); + + afterEach(() => { + if (fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true }); + }); + + it('explains which scoped rules apply to a file and why', () => { + const report = createContextExplanation('src/app.ts', { cwd: testDir, target: 'cursor' }); + + expect(report.input.path).toBe('src/app.ts'); + expect(report.target).toEqual({ target: 'cursor', path: '.cursor/rules/rulesync.mdc' }); + expect(report.rules.map((rule) => [rule.title, rule.status, rule.reason])).toEqual([ + ['TypeScript', 'applies', 'glob-match'], + ['Tests', 'excluded', 'glob-miss'], + ['Safety', 'applies', 'unscoped'], + ]); + expect(report.summary).toEqual({ applies: 2, excluded: 1, total: 3 }); + }); + + it('normalizes Windows paths and blocks workspace escape', () => { + const report = createContextExplanation('src\\app.ts', { cwd: testDir }); + + expect(report.input.path).toBe('src/app.ts'); + expect(() => createContextExplanation('../outside.ts', { cwd: testDir })).toThrow(/Security Exception/); + }); + + it('renders a review-safe markdown explanation without rule contents', () => { + const report = createContextExplanation('tests/example.ts', { cwd: testDir, target: 'claude' }); + const markdown = renderExplainMarkdown(report); + + expect(markdown).toContain('# RuleSync Context Lens'); + expect(markdown).toContain('`tests/example.ts`'); + expect(markdown).toContain('APPLIES'); + expect(markdown).toContain('EXCLUDED'); + expect(markdown).toContain('Static scope prediction'); + expect(markdown).not.toContain('Use strict TypeScript.'); + }); + + it('writes machine-readable JSON for CI or pull requests', () => { + const outputPath = path.join(testDir, '.rulesync', 'context-lens.json'); + const result = handleExplain('src/app.ts', { + cwd: testDir, + format: 'json', + output: outputPath, + }); + + expect(result).toBe(true); + const parsed = JSON.parse(fs.readFileSync(outputPath, 'utf8')); + expect(parsed.input.path).toBe('src/app.ts'); + expect(parsed.summary.applies).toBe(2); + }); +});