npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

opencode-rag

v1.1.0

Published

RAG enforcement, context management, and utilities plugin for OpenCode

Readme

opencode-rag

RAG (Retrieval-Augmented Generation) enforcement plugin for OpenCode. Enforces context discipline by gating read operations until repo_facts has been run.

Features

  • Repo Facts Gating: Blocks read-like operations until repository context is established
  • Session Management: Tracks RAG-related metrics per session
  • Bundle Statistics: Logs and tracks context bundle efficiency
  • Auto-Trigger: Optional automatic repo_facts execution on session start
  • Observability: Detailed logging for RAG optimization analysis

Why RAG Discipline?

AI agents often suffer from "blind coding" - making changes without understanding the codebase structure. This plugin enforces a discipline:

  1. Run repo_facts first to understand the project
  2. Use context_bundle to gather relevant context
  3. Read files with full understanding of the project

This prevents:

  • Blind refactoring that breaks things
  • Duplicating existing functionality
  • Ignoring project conventions
  • Making changes without understanding architecture

Installation

npm install opencode-rag

Usage

As a Plugin

import plugin from "opencode-rag";

export default plugin;

What Gets Blocked

The following tools are blocked until repo_facts is run:

  • read
  • grep
  • glob
  • list
  • find_symbol
  • find_rejects
  • And other read-like operations

What Gets Through

Non-code files are always accessible:

  • Configuration files
  • Documentation
  • Logs
  • Build artifacts

Configuration

Configure via .serena/opencode-power.jsonc. Note that Smart RAG v2.0 features (Cache, Risk-based Gating, Query Classification) are enabled by default for maximum efficiency.

{
  "rag": {
    // Discipline modes:
    // - "strict": block read-like tools until repo_facts is seen (except exempt paths)
    // - "soft": allow reads but clamp aggressively until repo_facts is seen
    // - "auto": strict for code paths, soft for docs/config paths (default)
    "disciplineMode": "auto",
    "autoRepoFactsOnSessionStart": true,
    "autoRepoFactsOnFirstRead": false,
    "enforceGating": true,
    "v2": {
      "cacheEnabled": true,
      "gatingEnabled": true,
      "queryClassifierEnabled": true
    }
  },
}

Discipline Modes (Strict + Soft)

This plugin supports both styles:

  • Strict: Enforces “repo_facts first” by blocking read-like tools until repo facts are loaded.
  • Soft: Allows reads, but clamps large reads early to reduce token usage.
  • Auto (default): Strict for code-like paths, soft for low-risk docs/config paths.

You can override the mode via env var:

OPENCODE_RAG_DISCIPLINE_MODE=strict opencode ...
# or
OPENCODE_RAG_DISCIPLINE_MODE=soft opencode ...

Note: the plugin cannot reliably execute repo_facts on your behalf; auto behavior logs a suggestion event and strict mode will still require the agent to run repo_facts.

Disabling Gating

For quick scripts or exploration, you can disable gating:

Via configuration:

{
  "rag": {
    "enforceGating": false,
  },
}

Via environment variable:

OPENCODE_RAG_ENFORCE=false opencode ...

Metrics & Observability

The plugin logs RAG-related events to _logs/:

rag-maximizer.jsonl

Tracks bundle efficiency and session metrics.

rag-enforcer.jsonl

Tracks blocked operations.

Example Workflow

Without Gating (Prone to Errors)

1. User: "Fix the auth bug"
2. Agent: reads auth.ts immediately
3. Agent: makes changes without understanding project structure
4. Result: May break other auth functionality

With Gating (Disciplined)

1. User: "Fix the auth bug"
2. Agent: tries to read auth.ts
3. ❌ BLOCKED: "Run repo_facts first"
4. Agent: runs repo_facts → learns about project structure
5. Agent: reads auth.ts with full context
6. Agent: makes informed changes
7. Result: Changes are architecture-aware

FAQ

"What if I don't want repo_facts?"

Disable gating via configuration or environment variable.

"Does this slow down the agent?"

Minimal overhead - session tracking, gating checks, and bundle logging are all efficient.

"Can I whitelist certain paths?"

The plugin automatically allows configuration files, documentation, logs, and build artifacts.

"What about CI/CD runs?"

CI/CD environments can disable gating via environment variable.

RAG Utilities

The plugin also exports utility functions for token estimation, text processing, and RAG workflows:

Token Estimation

import { estimateTokensFromText, RAG_CONFIG } from "opencode-rag";

const text = "Your code or documentation here";
const tokens = estimateTokensFromText(text);

console.log(`Estimated tokens: ${tokens}`);
console.log(`Token budget: ${RAG_CONFIG.tokenBudget}`);

Text Clamping

import { clampTextByChars, clampTextByTokens } from "opencode-rag";

// Clamp by character count
const clampedByChars = clampTextByChars(longText, 1000, "tail");

// Clamp by token count
const clampedByTokens = clampTextByTokens(longText, 500, 2000);

RAG Workflow Helpers

import {
  shouldBlockTool,
  isReadLikeTool,
  isExemptPath,
  buildSystemNotice,
} from "opencode-rag";

// Check if tool should be blocked
const blocked = shouldBlockTool("read", args, filePath, repoFactsSeen);

// Check if tool is read-like
const isRead = isReadLikeTool("grep");

// Check if path is exempt from gating
const exempt = isExemptPath("package.json");

// Build system notice for RAG context
const notice = buildSystemNotice(true);

Configuration

import { RAG_CONFIG } from "opencode-rag";

console.log(RAG_CONFIG.tokenBudget);        // 7000
console.log(RAG_CONFIG.smallReadMaxBytes);  // 2048
console.log(RAG_CONFIG.injectionMarker);    // "[[RAG-INJECT:v1]]"

API Reference

Exported Functions

  • estimateTokensFromText(text: string, language?: string): number
  • clampTextByChars(text: string, maxChars: number, strategy?: "head" | "tail"): string
  • clampTextByTokens(text: string, maxTokens: number, fallbackMaxChars: number): string
  • shouldBlockTool(tool: string, args: any, filePath: string, repoFactsSeen: boolean): boolean
  • isReadLikeTool(tool: string): boolean
  • isExemptPath(filePath: string): boolean
  • buildSystemNotice(repoFactsAvailable: boolean): string
  • getRequestedBytes(args: any): number | null
  • isSmallReadBypass(tool: string, args: any): boolean
  • shouldInjectSystemNotice(existingSystem: unknown): boolean

Configuration Object

const RAG_CONFIG = {
  tokenBudget: 7000,
  outputClampChars: 16000,
  smallReadMaxBytes: 2048,
  injectionMarker: "[[RAG-INJECT:v1]]",
  injectionMaxChars: 900,
  enableContextBundleDedupe: true,
};

License

MIT