Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .cline/instructions.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"_generator": "RuleSync (https://github.com/rulesync/rulesync)",
"title": "Repository AI Rules",
"overview": "Canonical repository instructions for AI coding assistants (Claude Code, Cursor, Copilot, Cline, Windsurf).",
"customInstructions": "[Code Style & Standards] (Files: **/*.ts, **/*.tsx)\n<!-- globs: **/*.ts, **/*.tsx -->\n- Always use TypeScript strict mode with explicit return types.\n- Prefer named exports over default exports.\n- Use immutable state updates and modern ES2022+ syntax.\n\n[Testing & Quality] (Files: tests/**/*.ts, **/*.spec.ts)\n<!-- globs: tests/**/*.ts, **/*.spec.ts -->\n- Write unit tests for all business logic using Vitest or Jest.\n- Maintain high test coverage and test edge cases and error paths explicitly.\n\n[Security & Privacy Guidelines]\n- Never hardcode API keys, access tokens, or secrets in source code.\n- Always validate external input and check path resolution bounds.\n- Do not execute destructive shell commands (`rm -rf`, `chmod 777`)."
"customInstructions": "[Code Style & Standards] (Files: **/*.ts, **/*.tsx)\n<!-- globs: **/*.ts, **/*.tsx -->\r\n- Always use TypeScript strict mode with explicit return types.\r\n- Prefer named exports over default exports.\r\n- Use immutable state updates and modern ES2022+ syntax.\n\n[Testing & Quality] (Files: tests/**/*.ts, **/*.spec.ts)\n<!-- globs: tests/**/*.ts, **/*.spec.ts -->\r\n- Write unit tests for all business logic using Vitest or Jest.\r\n- Maintain high test coverage and test edge cases and error paths explicitly.\n\n[Security & Privacy Guidelines]\n- Never hardcode API keys, access tokens, or secrets in source code.\r\n- Always validate external input and check path resolution bounds.\r\n- Do not execute destructive shell commands (`rm -rf`, `chmod 777`)."
}
19 changes: 19 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module.exports = {
root: true,
env: {
node: true,
es2022: true
},
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
plugins: ['@typescript-eslint'],
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
ignorePatterns: ['dist/', 'node_modules/', 'tests/tmp_workspace/', 'tests/tmp_receipt_workspace/'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }]
}
};
6 changes: 3 additions & 3 deletions .windsurfrules
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@

Canonical repository instructions for AI coding assistants (Claude Code, Cursor, Copilot, Cline, Windsurf).

- **Code Style & Standards** (`**/*.ts, **/*.tsx`): <!-- globs: **/*.ts, **/*.tsx --> - Always use TypeScript strict mode with explicit return types. - Prefer named exports over default exports. - Use immutable state updates and modern ES2022+ syntax.
- **Testing & Quality** (`tests/**/*.ts, **/*.spec.ts`): <!-- globs: tests/**/*.ts, **/*.spec.ts --> - Write unit tests for all business logic using Vitest or Jest. - Maintain high test coverage and test edge cases and error paths explicitly.
- **Security & Privacy Guidelines**: - Never hardcode API keys, access tokens, or secrets in source code. - Always validate external input and check path resolution bounds. - Do not execute destructive shell commands (`rm -rf`, `chmod 777`).
- **Code Style & Standards** (`**/*.ts, **/*.tsx`): <!-- globs: **/*.ts, **/*.tsx --> - Always use TypeScript strict mode with explicit return types. - Prefer named exports over default exports. - Use immutable state updates and modern ES2022+ syntax.
- **Testing & Quality** (`tests/**/*.ts, **/*.spec.ts`): <!-- globs: tests/**/*.ts, **/*.spec.ts --> - Write unit tests for all business logic using Vitest or Jest. - Maintain high test coverage and test edge cases and error paths explicitly.
- **Security & Privacy Guidelines**: - Never hardcode API keys, access tokens, or secrets in source code. - Always validate external input and check path resolution bounds. - Do not execute destructive shell commands (`rm -rf`, `chmod 777`).
Expand Down
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,20 @@ 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.1.0] - 2026-08-18

### Added

- `rulesync receipt` creates deterministic JSON, Markdown, or standalone HTML context fingerprints.
- Context receipts show canonical/target SHA-256 values, byte and token estimates, a 12-character context ID, and `synced`/`missing`/`drifted` status.
- `rulesync receipt --check` provides a CI-friendly drift gate without modifying source or target files.
- Cross-platform workspace boundary checks now handle POSIX fixtures on Windows and reject sibling-prefix traversal.
- Repository lint configuration and verification artifacts added.

### Fixed

- Removed lint-blocking unnecessary regular-expression escapes in existing secret and unsafe-command detectors.

## [1.0.0] - 2026-08-05

### Initial Release 🎉
Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,23 @@ npx rulesync lint
npx rulesync build
```

### 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:

```bash
npx rulesync receipt --format html --output .rulesync/context-receipt.html
open .rulesync/context-receipt.html
```

The receipt shows a 12-character context ID, SHA-256 values, byte/token estimates, and `SYNCED`, `MISSING`, or `DRIFTED` status. It never prints rule contents or calls a network. Use it in CI:

```bash
npx rulesync receipt --check --format json --output .rulesync/context-receipt.json
```

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.

---

## 🔍 Why RuleSync?
Expand Down Expand Up @@ -145,6 +162,12 @@ Previews terminal colorized diffs between compiled target outputs and disk files
npx rulesync diff [--target cursor]
```

### `rulesync receipt`
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 <path>] [--check]
```

---

## ⚙️ Configuration (`.rulesync/config.json`)
Expand Down
156 changes: 156 additions & 0 deletions docs/superpowers/plans/2026-08-18-context-receipt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# Context Receipt Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Add a deterministic `rulesync receipt` command that fingerprints canonical and compiled agent context, reports drift, and produces JSON/Markdown/HTML audit artifacts.

**Architecture:** Reuse `loadConfig`, `parseMarkdownToART`, `runLinter`, and `compileToTargets`. A focused receipt module reads bytes, computes hashes, compares expected target output with disk, and owns renderers. Commander wires the command without changing existing build behavior.

**Tech Stack:** TypeScript, Node `crypto`/`fs`/`path`, Commander, Vitest, existing tsup build.

**Spec:** `docs/superpowers/specs/2026-08-18-context-receipt-design.md`

## Global Constraints

- Runtime supports Node `>=18.0.0` and adds no runtime dependency.
- Receipt generation makes no network calls, model calls, shell calls, or source/target mutations.
- Every path must pass `sanitizeWorkspacePath`; output writes only to explicit `--output`.
- Tests follow RED → GREEN → REFACTOR; no production behavior without a failing test first.
- Hashes use SHA-256 over file bytes; token estimate is deterministic `ceil(nonWhitespaceCharacters / 4)`.
- Existing commands and public API remain backward compatible.

---

### Task 1: Cross-platform workspace boundary

**Files:**
- Modify: `tests/security.test.ts`
- Modify: `src/utils/path.ts`

**Interfaces:**
- Preserve `sanitizeWorkspacePath(targetPath: string, rootDir?: string): string`.
- Preserve `normalizeRelativePath(filePath: string, rootDir?: string): string`.

- [ ] **Step 1: Add the sibling-prefix regression test**

Add a test asserting `../workspace-evil/file.md` is rejected when the root is `/home/user/workspace`, while existing POSIX fixture paths remain unchanged.

- [ ] **Step 2: Run the focused test and verify RED**

Run `npm test -- tests/security.test.ts`. Expected: current Windows path resolution fails the POSIX fixture and does not yet provide the robust boundary behavior.

- [ ] **Step 3: Implement minimal platform-aware resolution**

Select `path.posix` when `rootDir` starts with `/`, otherwise the native `path` API. Compare the target against `root + separator` so `/workspace-evil` cannot pass a `/workspace` prefix check.

- [ ] **Step 4: Run focused and full tests**

Run `npm test -- tests/security.test.ts` then `npm test`. Expected: all security and existing tests pass.

- [ ] **Step 5: Commit the baseline fix**

```bash
git add tests/security.test.ts src/utils/path.ts
git commit -m "fix: make workspace guards cross-platform"
```

### Task 2: Receipt contract and core audit

**Files:**
- Modify: `src/types/index.ts`
- Create: `src/receipt/index.ts`
- Create: `tests/receipt.test.ts`

**Interfaces:**
- Export `ContextReceipt`, `ReceiptTarget`, and `ReceiptFormat` from `src/types/index.ts`.
- Export `createContextReceipt(cwd: string, generatedAt?: string): ContextReceipt`.
- Export `receiptIsSynced(receipt: ContextReceipt): boolean`.

- [ ] **Step 1: Write failing core tests**

Create a temporary workspace with `AGENTS.md`, `.rulesync/config.json`, and one generated target. Assert receipt fields, deterministic context ID for fixed input, `synced` status, `missing` status after deleting a target, and `drifted` after changing a target.

- [ ] **Step 2: Run receipt tests and verify RED**

Run `npm test -- tests/receipt.test.ts`. Expected: module/function is missing, not a test typo.

- [ ] **Step 3: Implement minimal receipt assembly**

Load config, parse/lint/compile in memory, hash source and expected output bytes, read actual target bytes when present, calculate token estimates, and derive the 12-character context ID from stable JSON without `generatedAt`.

- [ ] **Step 4: Run receipt tests and full suite**

Run `npm test -- tests/receipt.test.ts` then `npm test`. Expected: receipt tests and all prior tests pass.

### Task 3: Renderers and CLI command

**Files:**
- Modify: `src/cli.ts`
- Modify: `src/index.ts`
- Modify: `src/receipt/index.ts`
- Create: `src/receipt/render.ts`
- Modify: `tests/receipt.test.ts`

**Interfaces:**
- Export `handleReceipt(options: { format?: ReceiptFormat; output?: string; check?: boolean; cwd?: string }): Promise<boolean>`.
- Export `renderReceiptJson`, `renderReceiptMarkdown`, and `renderReceiptHtml`.

- [ ] **Step 1: Add renderer and handler tests**

Assert JSON parses, Markdown contains context ID/status/hash, HTML escapes `<script>` in a path, output is written only to requested file, and `check` returns false for drift.

- [ ] **Step 2: Run focused tests and verify RED**

Run `npm test -- tests/receipt.test.ts`. Expected: renderer and handler exports are missing.

- [ ] **Step 3: Implement escaped renderers and Commander wiring**

Default to Markdown on stdout when no output is supplied. Use `--format json|markdown|html`, `--output <path>`, and `--check`; call `process.exit(1)` only from the command action when handler returns false.

- [ ] **Step 4: Run tests and CLI smoke commands**

Run `npm test`, `npm run typecheck`, and `npm run build`. Then run `node dist/cli.js receipt --help` and a temporary workspace command for each format.

### Task 4: Documentation and verification record

**Files:**
- Modify: `README.md`
- Modify: `CHANGELOG.md`
- Create: `docs/verification/context-receipt-v1.1.md`
- Modify: `.github/workflows/ci.yml` only if current action/runtime check requires it.

- [ ] **Step 1: Update README with the one-minute receipt demo**

Document `rulesync receipt --format html --output .rulesync/context-receipt.html`, the JSON contract, `--check`, status meanings, and explicit limits.

- [ ] **Step 2: Record real execution evidence**

Save commands, output summaries, context ID, test count, package smoke result, `npm audit --omit=dev`, and `git diff --check` results in the verification record. Use synthetic rules only.

- [ ] **Step 3: Run release gates**

Run `npm test`, `npm run typecheck`, `npm run lint`, `npm run build`, `npm audit --omit=dev`, `npm pack --dry-run`, and `git diff --check`.

### Task 5: Publish

**Files:**
- Git history and GitHub branch/release.

- [ ] **Step 1: Inspect diff and staged secret patterns**

Run `git status --short`, `git diff --check`, and a targeted search for private keys, API-key prefixes, and real personal data.

- [ ] **Step 2: Commit intended changes**

```bash
git add src tests README.md CHANGELOG.md docs .github
git commit -m "feat: add agent context receipts"
```

- [ ] **Step 3: Push branch and open draft PR**

Push `agent/context-lock` and open a draft PR into `main` with summary, motivation, checks, and safety boundary.

- [ ] **Step 4: Publish release only after CI is green**

After GitHub Actions passes, create or update the appropriate release/tag with verification record and report the PR/release URLs.
77 changes: 77 additions & 0 deletions docs/superpowers/specs/2026-08-18-context-receipt-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Context Receipt Design

## Problem

RuleSync already compiles one canonical rule source into several agent-specific files and can tell whether those files are synchronized. A maintainer still cannot answer quickly, “What exact instruction bundle did this agent target receive?” A stale file, a changed target adapter, or a different branch can silently change agent behavior.

## Product decision

Add `rulesync receipt`, a local, deterministic audit artifact for the compiled agent context. It reads the canonical source and configuration, compiles target output in memory, hashes the canonical source and every expected/on-disk target, and emits a short context ID plus per-target status.

The receipt is a fingerprint and review surface, not a new source of rules. The target files remain the source of truth for each tool; the receipt proves which bytes were expected and whether disk matches them.

## User flow

```text
AGENTS.md + .rulesync/config.json
↓
rulesync receipt --format html --output .rulesync/context-receipt.html
↓
context ID · target status · hashes · token/byte counts
```

CI can use `rulesync receipt --check --format json`. It exits non-zero when a compiled target is missing, drifted, or blocked by a linter error. Normal receipt generation never writes source or target files; it writes only the explicit output path.

## Data contract

```ts
interface ContextReceipt {
schemaVersion: 1;
generatedAt: string;
source: { path: string; sha256: string; bytes: number; tokenEstimate: number };
contextId: string;
targets: Array<{
target: TargetAdapterName;
path: string;
status: 'synced' | 'missing' | 'drifted';
expectedSha256: string;
actualSha256?: string;
bytes: number;
tokenEstimate: number;
}>;
summary: { synced: number; missing: number; drifted: number; total: number };
}
```

`contextId` is the first 12 hexadecimal characters of SHA-256 over the canonical source hash, target names, and expected target hashes. The same input produces the same ID; `generatedAt` is metadata only.

## Formats

- JSON: stable machine-readable contract for CI and tooling.
- Markdown: concise ledger for pull requests and issue comments.
- HTML: escaped, standalone, searchable card with clear green/yellow/red target status.

## Safety and boundaries

- No network calls, model calls, shell execution, telemetry, or package installation at runtime.
- No source or target mutation during receipt generation.
- Output paths use the existing workspace boundary guard.
- Hashes are computed from bytes; no secret contents are printed.
- Existing linter errors block receipt creation and `--check` returns failure.
- `--check` is the only mode that uses process exit status for drift; normal output remains reviewable.

## Non-goals for v1.1

- No lockfile replacement for package managers.
- No claim that a hash proves an agent actually loaded a file at runtime.
- No remote dashboard, account, or hosted receipt registry.
- No automatic repair; users run the existing `rulesync build` after reviewing drift.

## Acceptance criteria

1. POSIX-style paths behave consistently on Windows and Unix, including traversal and sibling-prefix guards.
2. `rulesync receipt` emits all three formats from a temporary workspace.
3. Missing and drifted target files are distinguished with hashes.
4. `--check` returns false for missing/drifted targets and true for synced targets.
5. HTML and Markdown escape untrusted rule titles and paths.
6. Existing test suite, typecheck, lint, build, audit, and package smoke test pass.
57 changes: 57 additions & 0 deletions docs/verification/context-receipt-v1.1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Context Receipt v1.1 verification record

Date: 2026-08-18 (America/Los_Angeles)

## Real execution

Input: this repository’s canonical `AGENTS.md` and configured five targets.

```text
node dist/cli.js receipt --format json --output docs/verification/context-receipt.json
Wrote json context receipt: .../docs/verification/context-receipt.json

Context ID: 4f1e5284fd95
Source SHA-256: 78920552cda1bfb495779bc46a85e3dae491da2b1d8edd2eba5b0d81265b7387
Targets: 5
Synced: 5
Missing: 0
Drifted: 0
```

The first receipt run intentionally detected all five existing target files as `DRIFTED`. Running the existing `rulesync build` regenerated them; a second receipt run and `receipt --check` reported 5/5 synced. This proves the receipt can surface real repository drift instead of assuming green status.

Generated artifacts:

- `context-receipt.json` — machine-readable evidence.
- `context-receipt.md` — pull-request-friendly ledger.
- `context-receipt.html` — standalone, searchable review card.

## TDD evidence

- Path guard RED: the focused security suite failed on Windows POSIX fixtures and allowed a sibling-prefix path.
- Path guard GREEN: `tests/security.test.ts` passed 3/3 after platform-aware resolution and separator-boundary checks.
- Receipt RED: focused suite failed because `src/receipt/index.ts` did not exist.
- Receipt GREEN: focused suite passed 4/4; full suite passed 24/24.
- Drift regression covers both `missing` and `drifted` target states.

## Release gates

| Gate | Result |
| --- | --- |
| `npm test` | PASS — 6 files, 24 tests |
| `npm run typecheck` | PASS |
| `npm run lint` | PASS |
| `npm run build` | PASS — CJS, ESM, declarations |
| `npm audit` | PASS — 0 vulnerabilities |
| `npm audit --omit=dev` | PASS — 0 vulnerabilities |
| `npm pack --dry-run` | PASS — `rulesync-1.1.0.tgz` |
| `node dist/cli.js receipt --check ...` | PASS — 5 synced |
| `git diff --check` | PASS before publish |

## Security notes

- Receipt hashes bytes and does not print rule contents.
- HTML/Markdown renderers escape target paths and metadata.
- Output writes only to the explicit workspace-contained path.
- Runtime receipt flow has no network, model, shell, telemetry, or installation behavior.
- Dev audit vulnerabilities from Vitest 1.x were removed by upgrading to Vitest 3.2.6 and overriding vulnerable transitive `esbuild`/`nanoid` ranges; Node 18 compatibility remains in CI.
Loading
Loading