refactor(brewcode): remove grepai skill, agent, hooks and all references

This commit is contained in:
kochetkov-ma
2026-08-02 17:51:22 +01:00
parent 86190135f9
commit 822e822718
93 changed files with 242 additions and 4016 deletions
+5 -5
View File
@@ -6,13 +6,13 @@
},
"metadata": {
"description": "Claude Code plugin suite: brewcode for infinite task execution, brewdoc for documentation tools, brewtools for text utilities, brewui for UI/visual/creative tools",
"version": "4.3.0"
"version": "4.4.0"
},
"plugins": [
{
"name": "brewcode",
"description": "Brewcode - full-featured development platform for Claude Code: infinite focus tasks, prompt optimization, skill/agent creation, quorum reviews, rules management",
"version": "4.3.0",
"version": "4.4.0",
"category": "productivity",
"keywords": [
"brewcode",
@@ -46,7 +46,7 @@
{
"name": "brewdoc",
"description": "Brewdoc - Claude Code documentation tools: my-claude installation docs, memory sync, md-to-pdf conversion",
"version": "4.3.0",
"version": "4.4.0",
"category": "productivity",
"keywords": [
"brewdoc",
@@ -72,7 +72,7 @@
{
"name": "brewtools",
"description": "Brewtools - universal utilities for Claude Code: text optimization, humanization, secrets scanning",
"version": "4.3.0",
"version": "4.4.0",
"category": "productivity",
"keywords": [
"brewtools",
@@ -100,7 +100,7 @@
{
"name": "brewui",
"description": "Placeholder for future UI/visual/creative tools (currently empty, installable)",
"version": "4.3.0",
"version": "4.4.0",
"category": "productivity",
"keywords": [
"ui",
@@ -60,8 +60,8 @@ plus optional `[scope]` hint. The fine-tune prompt is woven into the emitted ski
### Phase 1 — Analyze the TARGET project
Gather everything the emitted skill must be wired to. Prefer `grepai_search` first for code exploration; fall back to
Bash search (`grep`->ugrep / `find`->bfs on macOS CC).
Gather everything the emitted skill must be wired to. Explore the code with Bash search (`grep`->ugrep / `find`->bfs
on macOS CC; native Grep/Glob are no-ops there).
**EXECUTE** using shell (project scan):
```bash
@@ -232,7 +232,7 @@ over-complexity`, citing the project best-practices + avoid rules. Every agent r
}
```
Each agent MUST search-first (grep / verify imports, prefer `mcp__grepai__search` if available) before flagging any
Each agent MUST search-first (Bash `grep`/`rg` + verify imports) before flagging any
reuse/duplicate, and read the ACTUAL code at every cited line. Collect every agent's findings into one pool
`{CANDIDATES}` (tag each finding with its producing agent as `source`).
@@ -357,7 +357,7 @@ superreview does NOT run /simplify or any skill and does NOT edit code — these
| Validator agent | `{VALIDATOR_AGENT}` (fallback built-in `general-purpose`) | Phase 3 merge + validate |
| Report dir | `.codex/reports/{TIMESTAMP}_superreview/` | Merged report, findings sorted P0 -> P3 |
| Max files | 50 (except `FULL_PROJECT`) | Warn + suggest narrowing above this |
| Search tool | `mcp__grepai__search` if available, else `Grep`/`Glob`/Bash | reuse-first search; note which in report |
| Search tool | Bash `rg`/`grep`/`git ls-files` | reuse-first search; note which in report |
---
@@ -369,7 +369,6 @@ superreview does NOT run /simplify or any skill and does NOT edit code — these
| >50 files | Warn the user; suggest narrowing (per-folder or per-commit) |
| A domain agent unavailable | Fall back to built-in `Explore` with the same prompt; note in report |
| `{VALIDATOR_AGENT}` unavailable | Run Phase 3 validation prompt on the built-in `general-purpose`; note in report |
| `grepai` unavailable | Fall back to `Grep`/`Glob`/Bash; state which path was used in the report |
| Agent timeout | Retry once, then mark that source unavailable + warn in report |
| Validation rejects everything | Report "No issues survived validation" — verdict APPROVED |
| All sources clean | Report "No issues found across standards, architecture, and correctness" — verdict APPROVED |
@@ -11,8 +11,7 @@ Codex delegation brief (task_role="{AGENT}", message="
You review ONLY the files below. Read the ACTUAL code. Report STANDARDS + ARCHITECTURE + CORRECTNESS issues.
**SEARCH-FIRST (HARD rule — reuse-first):** before flagging a 'duplicate' or 'reuse' miss, grep the repo
(Bash grep/find over the shared/util/common/domain/adapters dirs) and verify imports. If grepai
(mcp__grepai__search) is available, prefer it for semantic search.
(Bash grep/find over the shared/util/common/domain/adapters dirs) and verify imports.
**Files:** {FILE_LIST}
**Focus:** {FOCUS}
@@ -10,7 +10,7 @@ Output: `.codex/reports/{TIMESTAMP}_superreview/REPORT.md`. ONE consolidated, va
**Scope:** {concrete scope — commit range | branch-vs-main | folder | working-tree vs HEAD | full project}
**Focus:** {resolved focus — user directive, else default ordering; security only if P0}
**Files Reviewed:** {COUNT}
**Search tool used:** {grepai | Grep/Glob/Bash fallback}
**Search tool used:** {Bash rg/grep/git ls-files}
**Agents run (targeted fan-out):** {AGENT_LIST}
> Findings section below is MANDATORY-sorted by priority P0 -> P3 (highest severity first).
@@ -45,7 +45,7 @@ const UserCard: React.FC<UserCardProps> = ({ user, onEdit }) => {
| `useRef` | Using for state |
Custom hooks: `use*` prefix, extract reusable logic, return object for >2 values. **Check existing hooks first**
(`hooks/`, `use*.ts`, grepai_search) before creating.
(`hooks/`, `use*.ts`, Bash `grep`) before creating.
## TypeScript Type Safety
@@ -189,13 +189,7 @@ Keep project-specific ticket patterns (INTELDEV-XXXXX, JIRA-XXXXX). Remove gener
### Scan Pattern
```
# Semantic search queries for grepai_search:
grepai_search("private methods with javadoc")
grepai_search("trivial param documentation")
grepai_search("test helper classes")
grepai_search("DTO classes with javadoc")
# Fallback grep patterns:
# grep patterns:
grep -n "^\s*/\*\*" <file> // Find all JavaDoc
grep -n "private.*{" <file> // Find private methods
```
@@ -218,12 +218,7 @@ def mock_user():
### Scan Pattern
```
# Semantic search:
grepai_search("private methods with docstrings")
grepai_search("trivial docstring parameters")
grepai_search("test file documentation")
# Fallback grep:
# grep patterns:
grep -n '"""' <file> # Find docstrings
grep -n "def _" <file> # Find private methods
```
@@ -183,12 +183,7 @@ export const createMockUser = () => { }
### Scan Pattern
```
# Semantic search:
grepai_search("jsdoc on private functions")
grepai_search("redundant type annotations")
grepai_search("test file documentation")
# Fallback grep:
# grep patterns:
grep -n "/\*\*" <file> // Find JSDoc
grep -n "^const.*=" <file> // Find functions
```
-132
View File
@@ -219,29 +219,6 @@ Use Codex collaboration only when the user or active repository instructions exp
'brewcode/e2e': `# End-to-end testing
Translate the requested behavior into GIVEN/WHEN/THEN scenarios, inspect the active application and test stack, then implement the smallest deterministic end-to-end suite. Use Codex collaboration agents only when the user or project instructions explicitly request delegation. Run against mocks or local services unless live side effects are explicitly authorized, and report exact commands and failures.`,
'brewcode/grepai': `# grepai for Codex
Resolve the mode first with \`scripts/detect-mode.sh\`: \`setup\`, \`status\`, \`start\`, \`stop\`, \`reindex\`, \`optimize\`, \`upgrade\`, or \`prompt\`.
## Setup
1. Run \`scripts/infra-check.sh\`; install only pinned prerequisites approved by the user.
2. Verify MCP state with \`codex mcp list\`. Register the installed CLI exactly with \`codex mcp add grepai -- grepai mcp-serve\`.
3. Generate or review \`.grepai/config.yaml\` from \`config.yaml.example\` without overwriting local choices.
4. Initialize the index with \`scripts/init-index.sh\`, then verify it with \`scripts/verify.sh\`.
5. Offer the project rule produced by \`scripts/create-rule.sh\` as a reviewable patch.
6. Install optional reminders from \`assets/INSTALL.md\` into the selected \`.codex/hooks.json\`; preserve unrelated hooks and require \`/hooks\` review.
## Operational modes
- \`status\`: run \`scripts/status.sh\` and \`scripts/mcp-check.sh status\` without mutation.
- \`start\` / \`stop\`: use the matching script and report process state.
- \`reindex\`: confirm destructive index replacement, then run \`scripts/reindex.sh\` and verify.
- \`optimize\`: back up config, run \`scripts/optimize.sh\`, reindex, and compare status.
- \`upgrade\`: report current and target pinned versions before \`scripts/upgrade.sh\`.
- \`prompt\`: inspect the request and perform semantic search without changing configuration.
Never edit Codex plugin caches or use an unpinned dependency command.`,
'brewcode/rules': `# Codex project rules
Use only when the user explicitly requests rule creation, synchronization, improvement, review, or inventory.
@@ -678,114 +655,6 @@ After a change, review the exact hook definition with \`/hooks\`. Removal delete
`);
}
if (plugin === 'brewcode' && skill === 'grepai') {
writeFile(path.join(targetDir, 'assets', 'INSTALL.md'), `# Codex grepai hook runbook
Copy \`grepai-session.mjs\` and \`grepai-reminder.mjs\` into \`<project-root>/.codex/hooks/grepai/\`, then merge the following handlers into \`<project-root>/.codex/hooks.json\` without replacing unrelated entries:
- \`SessionStart\`: matcher \`startup|resume|clear|compact\`, one command string \`node "<absolute-hook-directory>/grepai-session.mjs"\`, \`timeout: 2\`.
- \`PreToolUse\`: matcher \`^Bash$\`, one command string \`node "<absolute-hook-directory>/grepai-reminder.mjs"\`, \`timeout: 2\`.
Use no matcher for events whose schema forbids one. Deduplicate by exact command string and review the changed definition with \`/hooks\`. To remove, delete only handlers whose commands name these two scripts, then remove their copied files.
Register the MCP server with \`codex mcp add grepai -- grepai mcp-serve\` and verify with \`codex mcp list\`.
`);
writeFile(path.join(targetDir, 'assets', 'grepai-session.mjs'), `#!/usr/bin/env node
import { existsSync } from 'node:fs';
import path from 'node:path';
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
let input = {};
try { input = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); } catch {}
const cwd = typeof input.cwd === 'string' ? input.cwd : process.cwd();
if (!existsSync(path.join(cwd, '.grepai'))) {
process.stdout.write('{}');
} else {
process.stdout.write(JSON.stringify({
hookSpecificOutput: {
hookEventName: 'SessionStart',
additionalContext: 'grepai is configured for this repository; prefer grepai semantic search for code exploration.'
}
}));
}
`, 0o755);
writeFile(path.join(targetDir, 'assets', 'grepai-reminder.mjs'), `#!/usr/bin/env node
import { existsSync } from 'node:fs';
import path from 'node:path';
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
let input = {};
try { input = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); } catch {}
const cwd = typeof input.cwd === 'string' ? input.cwd : process.cwd();
const command = typeof input.tool_input?.command === 'string' ? input.tool_input.command : '';
const searchesCode = /(?:^|[|;&(])\\s*(?:command\\s+)?(?:grep|egrep|fgrep|ugrep|rg|ag|ack|find|bfs)\\b/.test(command);
if (!searchesCode || !existsSync(path.join(cwd, '.grepai'))) {
process.stdout.write('{}');
} else {
process.stdout.write(JSON.stringify({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
additionalContext: 'Prefer grepai semantic search before broad shell-based code search.'
}
}));
}
`, 0o755);
writeFile(path.join(targetDir, 'scripts', 'mcp-check.sh'), `#!/usr/bin/env bash
set -euo pipefail
action="\${1:-status}"
case "$action" in
status)
codex mcp list
;;
add)
command -v grepai >/dev/null
codex mcp add grepai -- grepai mcp-serve
;;
*)
echo "usage: mcp-check.sh [status|add]" >&2
exit 2
;;
esac
`, 0o755);
for (const name of ['grepai-session.mjs', 'grepai-reminder.mjs']) {
copySelected(path.join(sourceDir, 'assets', name), path.join(targetDir, 'assets', name));
}
writeFile(path.join(targetDir, 'scripts', 'infra-check.sh'), `#!/usr/bin/env bash
set -euo pipefail
check_exact() {
local label="$1" actual="$2" expected="$3"
test "$actual" = "$expected" || { echo "$label requires exact version $expected; found \${actual:-missing}" >&2; return 1; }
}
command -v grepai >/dev/null || { echo "grepai 0.26.0 is required" >&2; exit 1; }
command -v ollama >/dev/null || { echo "ollama 0.15.2 is required" >&2; exit 1; }
check_exact grepai "$(grepai version 2>/dev/null | awk '{print $NF}')" 0.26.0
check_exact ollama "$(ollama --version 2>/dev/null | awk '{print $NF}')" 0.15.2
echo "Pinned grepai infrastructure is ready."
`, 0o755);
writeFile(path.join(targetDir, 'scripts', 'install.sh'), `#!/usr/bin/env bash
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
if "$HERE/infra-check.sh"; then exit 0; fi
echo "Install exact grepai 0.26.0 and ollama 0.15.2 from approved pinned package sources, then rerun setup." >&2
exit 1
`, 0o755);
writeFile(path.join(targetDir, 'scripts', 'upgrade.sh'), `#!/usr/bin/env bash
set -euo pipefail
target="\${1:-0.26.0}"
test "$target" = 0.26.0 || { echo "Unsupported unpinned target: $target" >&2; exit 2; }
actual="$(grepai version 2>/dev/null | awk '{print $NF}' || true)"
test "$actual" = "$target" || { echo "Install exact grepai $target through an approved pinned package source; automatic floating upgrades are disabled." >&2; exit 1; }
echo "grepai $target is installed."
`, 0o755);
}
if (plugin === 'brewtools' && skill === 'plugin-update') {
writeFile(path.join(targetDir, 'scripts', 'discover-plugins.sh'), `#!/usr/bin/env bash
set -euo pipefail
@@ -1012,7 +881,6 @@ function generateAgent(plugin, agentName) {
'agent-creator': `Create or improve Codex custom-agent TOMLs. Use one standalone file per agent under project .codex/agents/ or personal ~/.codex/agents/. Require name, description, and developer_instructions. Use only supported optional configuration keys. Validate TOML with Python tomllib and keep the role narrow.`,
architect: `Design changes from repository evidence. Identify system boundaries, ownership, data flow, contracts, failure modes, migration constraints, and verification before recommending an implementation. Preserve existing behavior unless the task explicitly changes it. Return concrete decisions, affected files, and unresolved risks.`,
'bash-expert': `Write and review portable shell automation. Default to strict mode, quote expansions, avoid destructive operations, keep output deterministic, and make failure states explicit. Validate syntax with bash -n and use shellcheck when available. Never expose secrets or mutate systems outside the requested scope.`,
'bc-grepai-configurator': `Configure and diagnose grepai for Codex repositories. Inspect current grepai and MCP state first, use native codex mcp list and codex mcp add commands, and keep hook definitions under the selected .codex/hooks.json. Pin versions, test with local fixtures, and never edit installed plugin caches.`,
developer: `Implement scoped repository changes from existing architecture and instructions. Reuse established patterns, preserve unrelated user edits, keep dependencies pinned, and verify behavior with the narrowest reliable tests. Report exact files changed, commands run, and any remaining risk.`,
'hook-creator': `Create or improve Codex hooks using current official schemas. Use hooks.json or config.toml at an active .codex layer. Command handlers use one command string, timeout in seconds, and JSON stdin and stdout. Respect matcher limitations, test malformed input and timeout behavior, and explain review through /hooks after definitions change.`,
reviewer: `Review changes without modifying them unless explicitly asked. Prioritize correctness, regressions, security, contracts, and missing tests. Cite precise files and lines, assign severity only when justified, and distinguish confirmed defects from questions or optional improvements.`,
+4 -10
View File
@@ -121,9 +121,8 @@ claude --plugin-dir ./brewcode --plugin-dir ./brewdoc --plugin-dir ./brewtools -
### brewcode -- infinite task execution
```bash
/brewcode:grepai # 1. Set up semantic code search (one-time)
/brewcode:spec "Implement JWT authorization" # 2. Research codebase + create specification
/brewcode:superreview # 3. Generate a project-tailored deep-review skill
/brewcode:spec "Implement JWT authorization" # 1. Research codebase + create specification
/brewcode:superreview # 2. Generate a project-tailored deep-review skill
```
Skills orchestrate, agents execute. Each spawn is a bounded unit with a six-field brief, and the `forced-eval` hook re-states the manager role and the split rule on every prompt, so work stays observable across compaction cycles.
@@ -155,9 +154,6 @@ Placeholder plugin, currently empty. No commands yet -- coming soon.
## How It Works
```
/brewcode:grepai --> semantic index over the repo (one-time setup)
v
/brewcode:spec "..." --> 5-10 parallel research agents + user Q&A --> SPEC.md
v
@@ -188,12 +184,11 @@ Every spawn prompt carries six fields:
## Skills Reference
### Brewcode (9 skills)
### Brewcode (8 skills)
| Skill | Purpose |
|-------|---------|
| `/brewcode:spec` | Research codebase + user dialog -> SPEC.md |
| `/brewcode:grepai` | Semantic code search: setup, status, start, stop, reindex, optimize, upgrade, uninstall |
| `/brewcode:superreview` | Generate a project-tailored deep-review skill: domain-expert routing + scope discipline + mechanical gates + adversarial validation |
| `/brewcode:teams` | Create and manage dynamic teams of domain-specific agents |
| `/brewcode:convention` | Extract etalon classes, patterns, architecture into convention docs |
@@ -242,7 +237,7 @@ Self-contained `SKILL.md` folders that ship outside the four plugins -- drop the
| `brewpage-publish` | Claude Code | [`skills/brewpage-publish`](skills/brewpage-publish/) |
| `brewpage-publish` | OpenClaw / AgentSkills | [`openclaw/brewpage-publish`](openclaw/brewpage-publish/) |
## Agents (13 total)
## Agents (12 total)
| Agent | Plugin | Model | Purpose |
|-------|--------|-------|---------|
@@ -254,7 +249,6 @@ Self-contained `SKILL.md` folders that ship outside the four plugins -- drop the
| agent-creator | brewcode | inherit | Create and improve Claude Code agents |
| hook-creator | brewcode | inherit | Create and debug Claude Code hooks |
| bash-expert | brewcode | inherit | Create professional shell scripts |
| bc-grepai-configurator | brewcode | sonnet | Internal: spawned by /brewcode:grepai |
| bc-rules-organizer | brewcode | haiku | Internal: spawned by /brewcode:rules |
| text-optimizer | brewtools | sonnet | Optimize text and docs for LLM efficiency |
| ssh-admin | brewtools | inherit | Linux server administration via SSH |
+40
View File
@@ -2,6 +2,46 @@
---
## v4.4.0 (2026-08-02)
> **grepai removed.** The `/brewcode:grepai` skill, the `bc-grepai-configurator` agent, the two project hooks it self-installed, the `grepai-first` rule template and every "use `grepai_search` first" instruction across all four plugins are gone. Every place that pointed at semantic search now points at the Bash search path (`grep`->ugrep, `find`->bfs, `rg`) that this macOS Claude Code build actually has. brewcode is now **8 skills / 9 agents**.
> Docs: [brewcode overview](https://doc-claude.brewcode.app/brewcode/overview/) | [brewcode skills](https://doc-claude.brewcode.app/brewcode/skills/) | [brewcode agents](https://doc-claude.brewcode.app/brewcode/agents/) | [brewcode hooks](https://doc-claude.brewcode.app/brewcode/hooks/) | [spec](https://doc-claude.brewcode.app/brewcode/skills/spec/) | [convention](https://doc-claude.brewcode.app/brewcode/skills/convention/) | [superreview](https://doc-claude.brewcode.app/brewcode/skills/superreview/) | [architect](https://doc-claude.brewcode.app/brewcode/agents/architect/) | [developer](https://doc-claude.brewcode.app/brewcode/agents/developer/) | [reviewer](https://doc-claude.brewcode.app/brewcode/agents/reviewer/) | [skill-creator](https://doc-claude.brewcode.app/brewcode/agents/skill-creator/) | [agent-creator](https://doc-claude.brewcode.app/brewcode/agents/agent-creator/) | [guide](https://doc-claude.brewcode.app/brewdoc/skills/guide/) | [text-human](https://doc-claude.brewcode.app/brewtools/skills/text-human/) | [getting-started](https://doc-claude.brewcode.app/getting-started/) | [installation](https://doc-claude.brewcode.app/installation/) | [quickstart](https://doc-claude.brewcode.app/quickstart/)
### brewcode
#### Removed
- **grepai skill:** `skills/grepai/` deleted whole — SKILL.md, README, `config.yaml.example`, 14 shell scripts, `scripts/lib/index-common.sh`, and the two hook assets (`grepai-session.mjs`, `grepai-reminder.mjs`) it installed into consumer projects
- **bc-grepai-configurator:** the internal config-generating agent is gone; agent roster 10 -> 9
- **docs + template:** `docs/grepai.md` and `templates/rules/grepai-first.md.template` deleted
- **hooks:** `bc-grepai-configurator` dropped from the system-agent allowlist in `hooks/lib/utils.mjs`
#### Changed
- **architect / reviewer agents:** reuse-first discovery and the "similar exists?" check now run through Bash (`grep`/`rg`/`find`) instead of `grepai_search`. The instruction survives — only the tool changed
- **convention skill:** discovery step moved to Bash search + Read; the "grepai unavailable" error row is gone
- **superreview:** Phase 1 exploration, the emitted `SKILL.md.template` search-first rule, the generated report's "Search tool used" field and the TypeScript/React hook-existence check all retargeted to `rg`/`grep`/`git ls-files`
- **skill-creator / agent-creator:** "grepai injection" generalised to "hook context injection" — the claim was always about UserPromptSubmit context, not about grepai
- **docs:** `docs/commands.md` renumbered (grepai was command 2), `docs/file-tree.md` statistics recounted — 9 agents, 8 skills, 9 scripts, 2 templates, 5 docs
### brewdoc
#### Changed
- **guide:** grepai removed from the skills catalog (brewcode 9 -> 8), the agents catalog (15 -> 12 plugin agents), the advanced-topics list (section 1 deleted, 2-4 renumbered), the installation smoke test (now `/brewcode:skills status`) and the overview workflow. The Plugin Suite ASCII diagram was redrawn rather than line-deleted; brewui, which was missing entirely, is now shown
### brewtools
#### Changed
- **text-human:** the semantic-search block in the java/python/typescript references is gone; the grep block is promoted from "fallback" to the primary pattern
### repo
#### Changed
- **docs site:** `brewcode/skills/grepai.mdx` deleted, nav entry removed, 6 dead links to `/brewcode/skills/grepai/` fixed, and Ollama + bge-m3 dropped from the installation prerequisites — they were only ever needed as grepai's embedder. All counts and card grids recomputed; `npm run build` green, 57 pages
- **rules:** `.claude/rules/grepai-first.md` deleted; the `last_index_time` entry in `avoid.md` went with it (the lesson was purely about grepai's own YAML)
- **codex compat:** `.codex/scripts/generate-compat.mjs` no longer enumerates or generates the grepai skill mirror (-132 lines), so regeneration cannot reintroduce it
---
## v4.3.0 (2026-08-02)
> Repo-wide prompt audit (delegation contract, scope guards, dead-weight removal) **plus** subagent resource limits: verified frontmatter contract, calibrated `maxTurns` across all agents, and the new `agent-deadline` skill — a soft wall-clock deadline that forces a subagent to finalize instead of being killed.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "brewcode",
"version": "4.3.0",
"version": "4.4.0",
"description": "Brewcode - full-featured development platform for Claude Code: infinite focus tasks, prompt optimization, skill/agent creation, quorum reviews, rules management",
"author": {
"name": "Maksim Kochetkov",
+2 -2
View File
@@ -60,8 +60,8 @@ plus optional `[scope]` hint. The fine-tune prompt is woven into the emitted ski
### Phase 1 — Analyze the TARGET project
Gather everything the emitted skill must be wired to. Prefer `grepai_search` first for code exploration; fall back to
Bash search (`grep`->ugrep / `find`->bfs on macOS CC).
Gather everything the emitted skill must be wired to. Explore the code with Bash search (`grep`->ugrep / `find`->bfs
on macOS CC; native Grep/Glob are no-ops there).
**EXECUTE** using shell (project scan):
```bash
@@ -232,7 +232,7 @@ over-complexity`, citing the project best-practices + avoid rules. Every agent r
}
```
Each agent MUST search-first (grep / verify imports, prefer `mcp__grepai__search` if available) before flagging any
Each agent MUST search-first (Bash `grep`/`rg` + verify imports) before flagging any
reuse/duplicate, and read the ACTUAL code at every cited line. Collect every agent's findings into one pool
`{CANDIDATES}` (tag each finding with its producing agent as `source`).
@@ -357,7 +357,7 @@ superreview does NOT run /simplify or any skill and does NOT edit code — these
| Validator agent | `{VALIDATOR_AGENT}` (fallback built-in `general-purpose`) | Phase 3 merge + validate |
| Report dir | `.codex/reports/{TIMESTAMP}_superreview/` | Merged report, findings sorted P0 -> P3 |
| Max files | 50 (except `FULL_PROJECT`) | Warn + suggest narrowing above this |
| Search tool | `mcp__grepai__search` if available, else `Grep`/`Glob`/Bash | reuse-first search; note which in report |
| Search tool | Bash `rg`/`grep`/`git ls-files` | reuse-first search; note which in report |
---
@@ -369,7 +369,6 @@ superreview does NOT run /simplify or any skill and does NOT edit code — these
| >50 files | Warn the user; suggest narrowing (per-folder or per-commit) |
| A domain agent unavailable | Fall back to built-in `Explore` with the same prompt; note in report |
| `{VALIDATOR_AGENT}` unavailable | Run Phase 3 validation prompt on the built-in `general-purpose`; note in report |
| `grepai` unavailable | Fall back to `Grep`/`Glob`/Bash; state which path was used in the report |
| Agent timeout | Retry once, then mark that source unavailable + warn in report |
| Validation rejects everything | Report "No issues survived validation" — verdict APPROVED |
| All sources clean | Report "No issues found across standards, architecture, and correctness" — verdict APPROVED |
@@ -11,8 +11,7 @@ Codex delegation brief (task_role="{AGENT}", message="
You review ONLY the files below. Read the ACTUAL code. Report STANDARDS + ARCHITECTURE + CORRECTNESS issues.
**SEARCH-FIRST (HARD rule — reuse-first):** before flagging a 'duplicate' or 'reuse' miss, grep the repo
(Bash grep/find over the shared/util/common/domain/adapters dirs) and verify imports. If grepai
(mcp__grepai__search) is available, prefer it for semantic search.
(Bash grep/find over the shared/util/common/domain/adapters dirs) and verify imports.
**Files:** {FILE_LIST}
**Focus:** {FOCUS}
@@ -10,7 +10,7 @@ Output: `.codex/reports/{TIMESTAMP}_superreview/REPORT.md`. ONE consolidated, va
**Scope:** {concrete scope — commit range | branch-vs-main | folder | working-tree vs HEAD | full project}
**Focus:** {resolved focus — user directive, else default ordering; security only if P0}
**Files Reviewed:** {COUNT}
**Search tool used:** {grepai | Grep/Glob/Bash fallback}
**Search tool used:** {Bash rg/grep/git ls-files}
**Agents run (targeted fan-out):** {AGENT_LIST}
> Findings section below is MANDATORY-sorted by priority P0 -> P3 (highest severity first).
@@ -45,7 +45,7 @@ const UserCard: React.FC<UserCardProps> = ({ user, onEdit }) => {
| `useRef` | Using for state |
Custom hooks: `use*` prefix, extract reusable logic, return object for >2 values. **Check existing hooks first**
(`hooks/`, `use*.ts`, grepai_search) before creating.
(`hooks/`, `use*.ts`, Bash `grep`) before creating.
## TypeScript Type Safety
+1 -2
View File
@@ -190,5 +190,4 @@ CLAUDE_DEBUG=1 claude --plugin-dir ./brewcode
| Document | Description |
|----------|-------------|
| [README.md](README.md) | Plugin overview and commands |
| [grepai.md](docs/grepai.md) | Semantic search integration |
| [/brewcode:grepai](skills/grepai/README.md) | Semantic search setup (includes prerequisites installation) |
| [commands.md](docs/commands.md) | Skills and agents reference |
+4 -7
View File
@@ -4,7 +4,7 @@
| Field | Value |
|-------|-------|
| Version | 4.3.0 |
| Version | 4.4.0 |
| Skills | 9 |
| Agents | 10 |
| Hooks | 2 |
@@ -65,8 +65,7 @@ claude --plugin-dir ./brewcode
## Quick Start
```bash
/brewcode:grepai # 1. Set up semantic code search (one-time)
/brewcode:spec "Implement JWT authorization" # 2. Research + specification
/brewcode:spec "Implement JWT authorization" # Research + specification
```
## Skills
@@ -74,7 +73,6 @@ claude --plugin-dir ./brewcode
| Skill | Purpose |
|-------|---------|
| [`/brewcode:spec`](skills/spec/README.md) | Research codebase + user dialog -> SPEC.md |
| [`/brewcode:grepai`](skills/grepai/README.md) | Manages grepai semantic code search: setup, status, start, stop, reindex, optimize, upgrade, uninstall |
| [`/brewcode:superreview`](skills/superreview/README.md) | Generate a project-tailored deep-review skill: domain-expert routing + scope discipline + mechanical gates + adversarial validation |
| [`/brewcode:teams`](skills/teams/README.md) | Dynamic agent team creation, management, and performance tracking |
| [`/brewcode:convention`](skills/convention/README.md) | Extract etalon classes, patterns, architecture into convention docs and rules |
@@ -99,7 +97,6 @@ claude --plugin-dir ./brewcode
| [agent-creator](agents/agent-creator.md) | inherit | Creates and improves Claude Code agents |
| [hook-creator](agents/hook-creator.md) | inherit | Creates and debugs Claude Code hooks |
| [bash-expert](agents/bash-expert.md) | inherit | Creates sh/bash scripts for Mac/Linux |
| bc-grepai-configurator | sonnet | Internal: spawned by /brewcode:grepai |
| bc-rules-organizer | haiku | Internal: spawned by /brewcode:rules |
> **Dynamic teams:** Use `/brewcode:teams create` to generate 5-20 project-specific agents with self-selection protocol and performance tracking.
@@ -116,8 +113,8 @@ brewcode/
| +-- forced-eval.mjs # UserPromptSubmit: manager-role + split-discipline reminder
| +-- hooks.json # Event bindings
| +-- lib/utils.mjs # Shared utilities
+-- agents/ # 10 agents
+-- skills/ # 9 skills
+-- agents/ # 9 agents
+-- skills/ # 8 skills
+-- templates/ # Rule templates
```
+1 -1
View File
@@ -187,7 +187,7 @@ claude --agents '{
## Spawn From Main Conversation Only (BC workflow)
**CC capability:** since v2.1.172, SAs can spawn their own SAs (up to 5 levels deep). **BC workflow stance:** spawn ONLY from main conversation. Nested spawns bypass session binding + grepai injection.
**CC capability:** since v2.1.172, SAs can spawn their own SAs (up to 5 levels deep). **BC workflow stance:** spawn ONLY from main conversation. Nested spawns bypass session binding + hook context injection.
**Nesting-depth guidance:** depth cap is configurable via `CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH` (v2.1.219+) -- verify the live cap, !=hardcode "5". Each level multiplies token cost + loses ctx fidelity. Prefer flat fan-out from main. Give Task/AG TL to an AG only when it genuinely orchestrates.
+4 -4
View File
@@ -47,15 +47,15 @@ On resume: read that file first, continue from the last component covered.
| Check | How |
|-------|-----|
| Utilities | `grepai_search` for similar functionality |
| Patterns | Grep for established conventions |
| Utilities | Bash `grep`/`rg` for similar functionality |
| Patterns | Bash `grep` for established conventions |
| Base classes | Find abstractions to extend |
| Common modules | Check shared/common/utils dirs |
| Libraries | Prefer battle-tested: JDK → Apache Commons → Guava |
### Reuse Flow
`Need → grepai search → Found? → extend/adapt | Not found? → library? → use | Create new`
`Need → Bash grep/find search → Found? → extend/adapt | Not found? → library? → use | Create new`
### Checklist
- [ ] Searched codebase for similar functionality
@@ -115,4 +115,4 @@ Scope → Discover → Assess → Identify → Recommend → Prioritize
## Tools
`grepai_search` FIRST for patterns and boundaries, then Grep/Glob/Read for structure, Bash for git log + dep graphs, WebSearch for external research.
Bash `grep`/`rg`/`find` FIRST for patterns and boundaries (on macOS CC builds `grep`→ugrep, `find`→bfs are shadowed; native Grep/Glob are no-ops), then Read for structure, Bash for git log + dep graphs, WebSearch for external research.
-471
View File
@@ -1,471 +0,0 @@
---
name: bc-grepai-configurator
description: Internal. Spawned only by /brewcode:grepai. No direct/auto use.
model: sonnet
maxTurns: 60
tools: Read, Write, Edit, Bash, WebFetch, Glob, Grep
---
# grepai Configurator
**See also:** [README](../README.md) | [grepai.md](../docs/grepai.md) | [/brewcode:grepai](../skills/grepai/SKILL.md)
**Role:** Isolated specialist for grepai config via deep project analysis.
**Scope:** Config generation only. Assumes grepai/ollama installed.
> One bounded unit briefed by `/brewcode:grepai`. Anything outside config generation — report it back instead of expanding scope.
> Brief without CONTEXT (what the skill already did) or CONSUMER (what reads the config next) — say what you assumed, or ask once; write the config so that consumer can use it as-is.
## Checkpointing
`maxTurns: 60` = anti-loop stop, != budget. On hit the run aborts and the final report is lost;
written config survives. After each workflow step (analysis, config write, index, verify) append
step + result to `.claude/reports/YYYYMMDD-HHMMSS_grepai-config/report.md`, != hold to the end.
On resume: read that file first, continue from the last completed step -- !=re-run indexing.
## Environment
| Constraint | Value | Source |
|------------|-------|--------|
| Embedder | Ollama (bge-m3:1024) | Default |
| Storage | GOB (local) | Fast |
| Languages | Java, Kotlin, JS, TS | Scope |
| Platform | Claude Code | MCP |
| Parallelism | 1 (REQ) | [ollama#12591](https://github.com/ollama/ollama/issues/12591) |
> Remove `watch.last_index_time` when changing config — files with ModTime < last_index_time are SKIPPED!
## gitignore Behavior
> grepai respects `.gitignore` (local + global) — gitignored files NOT indexed!
| Layer | Source | Effect |
|-------|--------|--------|
| Global | `~/.gitignore_global` | Applied first |
| Local | `.gitignore` | Adds to global |
| Config | `.grepai/config.yaml` `ignore:` | Adds exclusions only |
| Cannot | Why |
|--------|-----|
| Index gitignored files | Reads gitignore before scan |
| Use `!pattern` negation | Config only adds exclusions |
| Override via config | No `include:` option |
| Symlink bypass | Symlinks to gitignored also skip |
**Workarounds:** Remove from `~/.gitignore_global` | `git update-index --no-assume-unchanged` | Separate workspace
**Diagnostics:**
- `git check-ignore -v path/to/file`
- `git config --global core.excludesfile`
- `git status --ignored --porcelain | grep '^!!'`
`external_gitignore: ~/.config/git/ignore` — adds restrictions, use for team patterns.
## Embedder Models
| Model | Dims | Size | RAM | Speed | Quality | Use |
|-------|------|------|-----|-------|---------|-----|
| `bge-m3` | 1024 | 1.2GB | 1.5GB | ⚡ | ★★★★★ | Multilingual (default) |
| `mxbai-embed-large` | 1024 | 670MB | 1GB | ⚡⚡ | ★★★★★ | English, max accuracy |
| `nomic-embed-text-v2-moe` | 768 | 500MB | 800MB | ⚡⚡ | ★★★★ | 100+ langs, light |
| `nomic-embed-text` | 768 | 274MB | 500MB | ⚡⚡⚡ | ★★★ | Fast, small projects |
## Workflow
### Phase 1: Infrastructure Check
**EXECUTE** using Bash tool:
```bash
echo "=== Infrastructure Check ==="
which grepai >/dev/null && echo "✅ grepai: $(grepai version 2>/dev/null || echo 'installed')" || echo "❌ grepai: NOT FOUND"
curl -s localhost:11434/api/tags >/dev/null && echo "✅ ollama: running" || echo "❌ ollama: stopped"
ollama list 2>/dev/null | grep -q bge-m3 && echo "✅ bge-m3: installed" || echo "❌ bge-m3: missing"
```
> **STOP if any ❌** — report missing components.
### Phase 2: Project Analysis (Direct Tool Calls)
Run ALL analyses using available tools (Glob, Grep, Read):
| # | Analysis | Tool | Pattern/Target |
|---|----------|------|----------------|
| 1 | **LANGUAGES** | `Glob` | `**/pom.xml`, `**/build.gradle*`, `**/package.json`, `**/tsconfig.json` |
| 1b | **Embedded SQL** | `Grep` | Pattern: `JdbcTemplate\|NamedParameterJdbcTemplate\|@Query\|String sql\|"""\s*SELECT``HAS_EMBEDDED_SQL = true/false` |
| 2 | **TEST PATTERNS** | `Glob` | `**/test/`, `**/tests/`, `**/__tests__/`, `**/*.test.*`, `**/*.spec.*`, `**/*Test.java` |
| 3 | **GENERATED CODE** | `Glob` | `**/generated/`, `**/.gen.*`, `**/codegen/`, `**/openapi/`, `**/swagger/` |
| 4 | **SOURCE STRUCTURE** | `Glob` | `**/src/`, `**/lib/`, `**/app/`, `**/core/`, `**/modules/`, `**/components/`, `**/services/`, `**/domain/` |
| 5 | **IGNORE PATTERNS** | `Read` | `.gitignore` + `~/.gitignore_global` (via `git config --global core.excludesfile`) |
Run Glob/Grep/Read calls in parallel. Aggregate into a single analysis structure for Phase 3.
### Phase 3: Generate Config
**EXECUTE** — create dir and reset:
```bash
mkdir -p .grepai && echo "✅ .grepai/ created" || echo "❌ failed"
grep -v 'last_index_time:' .grepai/config.yaml > .grepai/config.yaml.tmp 2>/dev/null && mv .grepai/config.yaml.tmp .grepai/config.yaml || true
rm -f .grepai/index.gob .grepai/symbols.gob 2>/dev/null && echo "✅ Index reset" || echo "⚠️ No existing index"
```
**WRITE** `.grepai/config.yaml`:
> **If HAS_EMBEDDED_SQL = true** — add header:
> ```yaml
> # ⚠️ TRACE LIMITATION: Embedded SQL in code.
> # trace_graph unreliable (SQL keywords → false edges).
> # Use trace_callers/trace_callees instead.
> # Tip: --compact --format toon for minimal output.
> ```
```yaml
version: 1
embedder:
provider: ollama
model: bge-m3
endpoint: http://localhost:11434
dimensions: 1024
parallelism: 1
store:
backend: gob
chunking:
size: 512 # → 768-1024 for Java/Kotlin
overlap: 50 # → 75-100 for verbose languages
watch:
debounce_ms: 500
search:
boost:
enabled: true
penalties:
# From Phase 2 TEST PATTERNS: Tests (0.5), Mocks (0.4)
# From Phase 2 GENERATED CODE: Generated (0.4)
bonuses:
# From Phase 2 SOURCE STRUCTURE: Main source (1.1), Core (1.2)
hybrid:
enabled: false # → true for Java/Kotlin
k: 60
trace:
mode: fast # fast | precise (AST)
enabled_languages:
# From Phase 2 LANGUAGES — ONLY detected extensions
exclude_patterns:
# From Phase 2 TEST PATTERNS
update:
check_on_startup: false
ignore:
- .git
- .grepai
# From Phase 2 IGNORE PATTERNS
```
**Config Rules:**
| Setting | Rule | Reason |
|---------|------|--------|
| `embedder.parallelism` | Always `1` | Ollama bug |
| `embedder.dimensions` | Match model (bge-m3: 1024) | Mismatch breaks index |
| `chunking.size` | 512; 768-1024 Java/Kotlin | Verbose syntax |
| `chunking.overlap` | 50; 75-100 Java/Kotlin | Context |
| `search.boost.penalties` | Tests: 0.5, Mocks: 0.4, Generated: 0.4 | Prioritize prod |
| `search.boost.bonuses` | Main: 1.1, Core: 1.2 | Boost important |
| `search.hybrid.enabled` | true Java/Kotlin | Long identifiers |
| `search.hybrid.k` | 60 (balanced) | RRF smoothing |
| `trace.mode` | fast; precise for complex | Regex vs AST |
| `trace.enabled_languages` | Only detected | Avoid parse errors |
| `watch.debounce_ms` | 500; 100 responsive; 1000 less | Change grouping |
| `watch.last_index_time` | **NEVER include** | Causes skip bug |
> Index build scripts (build.gradle, pom.xml)!
### Phase 4: MCP Integration
**EXECUTE** — check MCP:
```bash
if [ -f .mcp.json ]; then
echo "✅ MCP (project): .mcp.json" && jq '.mcpServers.grepai' .mcp.json 2>/dev/null || echo "⚠️ grepai not configured"
elif [ -f ~/.claude.json ]; then
echo "✅ MCP (global): ~/.claude.json" && jq '.mcpServers.grepai' ~/.claude.json 2>/dev/null || echo "⚠️ grepai not configured"
else
echo "⚠️ No MCP config — use: claude mcp add grepai -- grepai mcp-serve"
fi
```
Add to `.mcp.json` (project) or `~/.claude.json` (global):
```json
{"mcpServers":{"grepai":{"command":"grepai","args":["mcp-serve"],"cwd":"/path/to/project"}}}
```
Quick: `claude mcp add grepai -- grepai mcp-serve`
### Phase 5: Verify
**EXECUTE**:
```bash
echo "=== Verify Config ==="
test -f .grepai/config.yaml && echo "✅ config exists" || echo "❌ config missing"
grepai search "main entry point" --json --compact 2>&1 | head -30 && echo "✅ search works" || echo "⚠️ needs index"
test -f .grepai/index.gob && echo "✅ index.gob: $(du -h .grepai/index.gob | cut -f1)" || echo "⚠️ index missing"
grep -q '"grepai"' ~/.claude.json 2>/dev/null && echo "✅ MCP configured" || echo "⚠️ MCP not configured"
```
**If HAS_EMBEDDED_SQL = true**:
```bash
echo "=== Trace SQL Method Test ==="
grepai trace callers "findBy" --compact 2>&1 | head -5
# If output > 1000 lines → SQL parsing issue
```
> **Indexing time:** <500 files: 1-3min | 1-5k: 5-15min | 5-10k: 15-30min | 10k+: 30+min
> Log: `.grepai/logs/grepai-watch.log`
---
## Configuration Reference
### File Extensions
| Category | Extensions | Notes |
|----------|------------|-------|
| **Java** | `.java` | Spring Boot, JPA, Hibernate, JDBC |
| **Kotlin** | `.kt`, `.kts` | Kotlin DSL, coroutines, Spring |
| **JavaScript** | `.js`, `.jsx` | React, Node.js, Express |
| **TypeScript** | `.ts`, `.tsx` | React, NestJS, Angular |
| **SQL** | `.sql` | Migrations, schemas, stored procs |
| **Config/Build** | `.yaml`, `.yml`, `.xml`, `.json`, `.toml` | pom.xml, build.gradle, package.json |
| **Web** | `.html`, `.css`, `.scss`, `.vue`, `.svelte` | Templates, styles |
| **Docs** | `.md`, `.txt` | README, docs |
| **Shell** | `.sh`, `.bash` | Scripts |
**Index build files:** `pom.xml`, `build.gradle`, `build.gradle.kts`, `package.json`, `tsconfig.json`
**Not indexed:** `.mjs`, `.cjs`, `.mts`, `.cts`
**Auto-excluded:** `.min.js`, `.min.css`, `.bundle.js`, binaries, >1MB, non-UTF-8
### Language Detection
| Build File | Stack | Extensions | Frameworks |
|------------|-------|------------|------------|
| `pom.xml` | Java/Maven | .java, .kt, .xml | Spring Boot, JPA, Hibernate |
| `build.gradle`, `build.gradle.kts` | Java/Kotlin/Gradle | .java, .kt, .kts, .groovy | Spring, Ktor |
| `package.json` | JS/TS/Node | .js, .ts, .jsx, .tsx | React, Next.js, Express, NestJS |
| `tsconfig.json` | TypeScript | .ts, .tsx | Angular, React |
### Ignore by Project Type
**Java/Kotlin (Maven/Gradle):**
- Build: `target/`, `build/`, `out/`, `.gradle/`
- Generated: `build/generated/`, `target/generated-sources/`
- Artifacts: `*.class`, `*.jar`, `*.war`
- IDE: `.idea/`, `*.iml`
**JavaScript/TypeScript (Node/React):**
- Deps: `node_modules/`
- Build: `dist/`, `build/`, `.next/`, `.nuxt/`
- Bundle: `*.min.js`, `*.min.css`, `*.map`, `*.bundle.js`
- Lock: `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`
- Cache: `.cache/`, `.parcel-cache/`
**Always ignore:** `.git/`, `.grepai/`, `.idea/`, `.vscode/`, `coverage/`
### Chunking
| Stack | size | overlap | Why |
|-------|------|---------|-----|
| **Java/Kotlin** (Spring, JPA) | **768-1024** | **75-100** | Long classes, annotations, verbose |
| **TypeScript** (React, NestJS) | 512-768 | 50-75 | Component classes, decorators |
| **JavaScript** (React, Node) | 512 | 50 | Balanced |
| **SQL** | 384 | 40 | Statements, schemas |
By architecture:
- Microservices (small services): 384/40
- Monolith (large classes): 768-1024/100
- React components: 512/50
- Spring Boot: 768/75
### Hybrid Search
Semantic + keyword via RRF.
| k value | Effect |
|---------|--------|
| 30 | More weight to top-ranked |
| 60 | Balanced (default) |
| 100 | Weight docs found by both |
**Enable:** Java/Kotlin (long identifiers), mixed queries, exact name search
**Disable:** Pure semantic, large codebase (100k+ chunks), docs-heavy
### Trace Settings
| Parameter | Options | Description |
|-----------|---------|-------------|
| `mode` | `fast` \| `precise` | Regex vs Tree-sitter AST |
| `enabled_languages` | `.java`, `.kt`, `.kts`, `.ts`, `.tsx`, `.js`, `.jsx` | Extensions to trace |
| `exclude_patterns` | `*.spec.ts`, `*.test.tsx`, `*Test.java` | Globs to skip |
| Mode | Speed | Accuracy | Use |
|------|-------|----------|-----|
| `fast` | Fast | Good | Large codebases, standard patterns |
| `precise` | Slow | Excellent | Complex Spring/React, edge cases |
**Supported:**
- Excellent: `.ts`, `.tsx`, `.js`, `.jsx`
- Good: `.java`, `.kt`, `.kts`, `.py`, `.php`
> Only include extensions that exist — non-existent cause parse errors.
### Trace Limitations: Embedded SQL
> For Java/Kotlin with JDBC, JOOQ, raw SQL strings!
grepai parses SQL keywords in string literals as function calls:
```java
var sql = """
SELECT ... FROM %s WHERE ... AND ... IN (:ids)
ORDER BY L2Distance(...)
"""; // grepai sees FROM, AND, IN, L2Distance as "callees"
```
**Result:** 2000+ false edges, even depth: 1.
| Symptom | Cause |
|---------|-------|
| trace_graph returns MB | SQL keywords → symbols |
| trace_graph timeout | Graph explosion |
| Wrong symbols (switch, of) | AST misattribution |
**Detection:** Phase 2 LANGUAGES agent → `HAS_EMBEDDED_SQL`
| Use | Command |
|-----|---------|
| callers instead of graph | `grepai trace callers "method" --compact` |
| callees instead of graph | `grepai trace callees "method" --compact` |
| Minimal output | `--format toon` |
> `trace.exclude_patterns` won't help — problem is in string literals.
### Watch Daemon
| debounce_ms | Behavior |
|-------------|----------|
| 100 | Responsive, frequent reindex |
| 500 | Balanced (default) |
| 1000 | Less responsive, fewer ops |
---
## Troubleshooting
**EXECUTE** — diagnostics:
```bash
echo "=== GrepAI Diagnostics ==="
grepai version && echo "✅ version" || echo "❌ not installed"
grepai status 2>&1 && echo "✅ status" || echo "❌ status failed"
cat .grepai/config.yaml 2>/dev/null | head -10 && echo "✅ config" || echo "❌ no config"
ls -lh .grepai/*.gob 2>/dev/null && echo "✅ index files" || echo "❌ no index"
curl -s localhost:11434/api/tags >/dev/null && echo "✅ ollama" || echo "❌ ollama down"
```
### Common Issues
| Issue | Solution |
|-------|----------|
| Index not found | `grepai watch` |
| Cannot connect Ollama | `ollama serve` |
| Model not found | `ollama pull bge-m3` |
| Search empty | Check `grepai status`, verify not ignored |
| File not indexed | `git check-ignore -v <file>` |
| Need gitignored file | Remove from gitignore (no config override) |
| Index outdated | `rm .grepai/index.gob && grepai watch` |
| Slow indexing | Add ignores, smaller model |
| Trace missing symbols | Check `enabled_languages` |
| MCP unavailable | Restart Claude Code |
| Changes not detected | Reduce `debounce_ms` |
| Out of memory | Smaller model, reduce parallelism |
| trace_graph MB of data | Embedded SQL → use `trace_callers` |
| trace_graph timeout | SQL keywords → `trace_callers --compact` |
| Wrong trace symbols | SQL parsing → `--format toon` |
**Force reindex:**
```bash
rm -f .grepai/index.gob .grepai/symbols.gob
grep -v 'last_index_time:' .grepai/config.yaml > .grepai/config.yaml.tmp 2>/dev/null && mv .grepai/config.yaml.tmp .grepai/config.yaml || true
grepai watch && echo "✅ reindexing" || echo "❌ failed"
```
**Index time:** ~100 files: 30s | ~1k: 5min | ~10k: 30min
> Use `nomic-embed-text` for faster initial indexing.
---
## MCP Tools
| Tool | Description | Params |
|------|-------------|--------|
| `grepai_search` | Semantic search | `query`, `limit`, `compact`, `format` |
| `grepai_trace_callers` | Find callers | `symbol`, `compact`, `format` |
| `grepai_trace_callees` | Find callees | `symbol`, `compact`, `format` |
| `grepai_trace_graph` | Call graph (⚠️ unreliable w/ SQL) | `symbol`, `depth`, `compact`, `format` |
| `grepai_index_status` | Index health | `verbose`, `format` |
**Format:** `json` (default), `toon` (~60% less tokens)
**Compact** (`--json --compact`): ~80% reduction
```json
{"q":"auth","r":[{"s":0.92,"f":"src/main/java/auth/AuthService.java","l":"15-45"}],"t":1}
```
Keys: `q`=query, `r`=results, `s`=score, `f`=file, `l`=lines, `t`=total
---
## Output Format
```markdown
# grepai Configuration Report
## Infrastructure
| Component | Status |
|-----------|--------|
| grepai | ✅ v0.24.0 |
| Ollama | ✅ Running |
| bge-m3 | ✅ Installed |
## Project Analysis
| Category | Detected |
|----------|----------|
| Language | Java/Kotlin |
| Tests | `Test.java`, `/test/` |
| Generated | `/build/generated/` |
| Source | `src/main/`, `core/` |
## Config: `.grepai/config.yaml`
| Setting | Value |
|---------|-------|
| Model | bge-m3 (1024) |
| Chunking | 768/75 |
| Hybrid | enabled (k=60) |
| Trace | fast, .java/.kt/.kts/.ts/.tsx |
## Verification
| Check | Status |
|-------|--------|
| config.yaml | ✅ |
| index.gob | ✅ 12.5 MB |
| Search | ✅ 5 results |
| MCP | ✅ |
## Next
- `grepai watch --background`
- Restart Claude Code
- `grepai search "query"`
```
---
**Sources:** [Configuration](https://yoanbernabeu.github.io/grepai/configuration/) | [Hybrid Search](https://yoanbernabeu.github.io/grepai/hybrid-search/) | [Trace](https://yoanbernabeu.github.io/grepai/trace/)
+1 -1
View File
@@ -44,7 +44,7 @@ Read ALL rules: `.claude/rules/*-best-practice.md`, `.claude/rules/*-avoid.md`,
| Check | Action |
|-------|--------|
| Similar exists? | `grepai_search` codebase |
| Similar exists? | Bash `grep`/`rg` the codebase |
| Utility exists? | Check common/utils/shared |
| Pattern established? | Find existing impl |
| Library available? | Prefer library over custom |
+5 -5
View File
@@ -245,14 +245,14 @@ Research $ARGUMENTS:
# SA Spawning Constraints
CC allows nesting up to 5 levels (v2.1.172), but brewcode workflow requires spawns from main conversation only: nested spawns bypass session binding + grepai injection.
CC allows nesting up to 5 levels (v2.1.172), but brewcode workflow requires spawns from main conversation only: nested spawns bypass session binding + hook context injection.
| Scenario | brewcode workflow | Why |
|----------|------------------|-----|
| SK with FORK from **main conversation** | **Use this** | Lock binding + grepai injection intact |
| SK with FORK from **main conversation** | **Use this** | Lock binding + hook context injection intact |
| SK with FORK from **SA** | **Avoid** | CC: up to 5 levels (v2.1.172); bypasses session binding + coordinator loop |
| Task tool from **SA** | **Avoid** | Nested spawn bypasses session binding + grepai injection |
| Skill tool from **SA** | **Avoid** | Bypasses grepai injection |
| Task tool from **SA** | **Avoid** | Nested spawn bypasses session binding + hook context injection |
| Skill tool from **SA** | **Avoid** | Bypasses hook context injection |
| Inline SK (no CTX) from SA | **Avoid** | Same binding/injection bypass |
Design: spawn from main only. For SAs use `skills:` FM (preload at startup). Multi-agent orchestration — chain from main, not nested.
@@ -288,7 +288,7 @@ Custom agents: `.claude/agents/` | `~/.claude/agents/` via `agent: my-custom-age
|-------|----------|----------|
| fable-5 | Mythos-class tier above Opus (`claude-fable-5`, v2.1.170) | Hardest reasoning/orchestration |
| opus | Complex orchestration, multi-phase | setup, create, review |
| sonnet | Medium complexity, optimization | rules, grepai |
| sonnet | Medium complexity, optimization | rules, convention |
| haiku | Simple, fast, cleanup | teardown, clean-cache |
# Tool Restrictions
+18 -78
View File
@@ -13,22 +13,21 @@ description: Detailed description of all brewcode plugin commands
| # | Command | Purpose | Context | Model | Deps |
|---|---------|---------|---------|-------|------|
| 1 | `/brewcode:spec` | Create task SP | session | opus | -- |
| 2 | `/brewcode:grepai` | Semantic code search | session | sonnet | -- |
| 3 | `/brewcode:superreview` | Generate project-tailored deep-review skill | fork | opus | -- |
| 4 | `/brewcode:rules` | Sync KB/session learnings → project rules | session | sonnet | -- |
| 5 | `/brewcode:skills` | SK status/list/create/improve/review/sync | session | opus | -- |
| 6 | `/brewcode:agents` | AG status/list/create/improve/review/sync | session | opus | -- |
| 7 | `/brewcode:convention` | Extract conventions/patterns/architecture → rules + docs | session | opus | -- |
| 8 | `/brewcode:teams` | Create/manage specialized AG teams | session | opus | -- |
| 9 | `/brewcode:e2e` | E2E testing: BDD scenarios, autotests, review | session | opus | -- |
| ~~10~~ | ~~`/bc:secrets-scan`~~ | **moved to brewtools** | -- | -- | -- |
| ~~11~~ | ~~`/bc:text-optimize`~~ | **moved to brewtools** | -- | -- | -- |
| ~~12~~ | ~~`/bc:text-human`~~ | **moved to brewtools** | -- | -- | -- |
| 2 | `/brewcode:superreview` | Generate project-tailored deep-review skill | fork | opus | -- |
| 3 | `/brewcode:rules` | Sync KB/session learnings → project rules | session | sonnet | -- |
| 4 | `/brewcode:skills` | SK status/list/create/improve/review/sync | session | opus | -- |
| 5 | `/brewcode:agents` | AG status/list/create/improve/review/sync | session | opus | -- |
| 6 | `/brewcode:convention` | Extract conventions/patterns/architecture → rules + docs | session | opus | -- |
| 7 | `/brewcode:teams` | Create/manage specialized AG teams | session | opus | -- |
| 8 | `/brewcode:e2e` | E2E testing: BDD scenarios, autotests, review | session | opus | -- |
| ~~9~~ | ~~`/bc:secrets-scan`~~ | **moved to brewtools** | -- | -- | -- |
| ~~10~~ | ~~`/bc:text-optimize`~~ | **moved to brewtools** | -- | -- | -- |
| ~~11~~ | ~~`/bc:text-human`~~ | **moved to brewtools** | -- | -- | -- |
## Execution Order
```
grepai --> spec --> superreview --> rules
spec --> superreview --> rules
```
---
@@ -37,7 +36,6 @@ grepai --> spec --> superreview --> rules
| AG | Model | Purpose |
|----|-------|---------|
| `bc-grepai-configurator` | sonnet | Gen `.grepai/config.yaml` via deep project analysis |
| `bc-rules-organizer` | haiku | Create/optimize `.claude/rules/*.md` |
---
@@ -86,63 +84,7 @@ Input: text → task desc; path → read file as task desc. Naming: `YYYYMMDD_HH
---
## 2. `/brewcode:grepai`
Setup + mgmt of semantic code search (grepai: Ollama + bge-m3). Modes: setup, status, start, stop, reindex, optimize, upgrade, uninstall.
| Param | Value |
|-------|-------|
| Args | `[setup\|status\|start\|stop\|reindex\|optimize\|upgrade\|uninstall]` |
| Context | session |
| Model | sonnet |
| Deps | none |
| Tools | Read, Write, Edit, Bash, Task, AskUserQuestion |
### Created Files (setup)
| Path | Purpose |
|------|---------|
| `.grepai/config.yaml` | grepai cfg for project |
| `.grepai/logs/grepai-watch.log` | Indexing log |
| `.claude/rules/grepai-first.md` | "Use grepai FIRST" rule |
| `.claude/grepai/hooks/*.mjs` + `settings.json` entries | self-installed SessionStart + PreToolUse hooks (Phase 6) |
### Bash Scripts
`detect-mode.sh`, `infra-check.sh`, `install.sh`, `mcp-check.sh`, `init-index.sh`, `create-rule.sh`, `verify.sh`, `status.sh`, `start.sh`, `stop.sh`, `reindex.sh`, `optimize.sh`, `upgrade.sh`, `uninstall.sh` — one per mode/phase, under `${CLAUDE_SKILL_DIR}/scripts/`.
### Agents
| AG | Model | Mode | Purpose |
|----|-------|------|---------|
| `bc-grepai-configurator` | sonnet | setup, optimize | Analyze project, gen config.yaml |
### Modes
| Mode | Description |
|------|-------------|
| `setup` | infra check (auto-install offer) → MCP → cfg → index → rule → hooks self-install → verify |
| `status` | State: CLI, ollama, model, MCP, index, watch |
| `start` | Start watcher |
| `stop` | Stop watcher |
| `reindex` | stop → clean → rebuild → start |
| `optimize` | Backup cfg → regen via bc-grepai-configurator → reindex |
| `upgrade` | Update grepai CLI via Homebrew |
| `uninstall` | Stop watch, remove project hooks + rule, unwire `settings.json`; optional `.grepai/` purge |
| `prompt` | Interactive mode selection (unrecognized text) |
Auto: empty args + `.grepai/` exists → `start`; empty args + no `.grepai/``setup`.
```
/brewcode:grepai setup
/brewcode:grepai status
/brewcode:grepai reindex
/brewcode:grepai uninstall
```
---
## 3. `/brewcode:superreview`
## 2. `/brewcode:superreview`
GENERATOR skill (human-invoked). Analyzes the TARGET project and WRITES a self-contained, project-local `.claude/skills/superreview/` — a merged deep-review skill (domain-expert routing + scope discipline + mechanical gates + adversarial validation). Does not review code itself; it emits the skill that does.
@@ -199,7 +141,7 @@ All three treat the ENTIRE `$ARGUMENTS` as ONE free-form prompt — no keyword g
---
## 4. `/brewcode:rules`
## 3. `/brewcode:rules`
Manages `.claude/rules/*.md` from a free-form prompt (see shared pattern above, no `sync`). Syncs KB (`KNOWLEDGE.jsonl`) or session learnings into deduplicated, table-form rules. Project scope only — never `~/.claude/rules/`.
@@ -221,7 +163,7 @@ Manages `.claude/rules/*.md` from a free-form prompt (see shared pattern above,
---
## 5. `/brewcode:skills`
## 4. `/brewcode:skills`
Manages Claude Code skills from a free-form prompt (see shared pattern above, incl. `sync`).
@@ -245,7 +187,7 @@ Manages Claude Code skills from a free-form prompt (see shared pattern above, in
---
## 6. `/brewcode:agents`
## 5. `/brewcode:agents`
Manages Claude Code subagents from a free-form prompt (see shared pattern above, incl. `sync`, same engine as `skills`).
@@ -271,7 +213,7 @@ Manages Claude Code subagents from a free-form prompt (see shared pattern above,
---
## 7. `/brewcode:convention`
## 6. `/brewcode:convention`
Analyzes project to extract etalon classes, patterns, architecture by layer. Generates convention docs in `.claude/convention/` + organizes rules in `.claude/rules/`.
@@ -320,7 +262,7 @@ Analyzes project to extract etalon classes, patterns, architecture by layer. Gen
---
## 8. `/brewcode:teams`
## 7. `/brewcode:teams`
Creates + manages dynamic teams of domain-specific AGs w/ tracking framework. Analyzes project, proposes team (5-20 AGs), creates w/ self-selection protocol + performance tracking + quorum review.
@@ -358,7 +300,7 @@ Creates + manages dynamic teams of domain-specific AGs w/ tracking framework. An
---
## 9. `/brewcode:e2e`
## 8. `/brewcode:e2e`
Full-cycle E2E testing: setup testing AGs, create BDD scenarios, write autotests, QR. Stack-agnostic, layered test architecture.
@@ -401,8 +343,6 @@ Hooks-only, no external runtime. Claude Code hooks provide ctx mgmt.
| `session-start.mjs` | SessionStart | Session init: version-check, plan-symlink, permission tag |
| `forced-eval.mjs` | UserPromptSubmit | Skill activation reminder ([SKILL?] injection) |
> grepai hooks (`grepai-session.mjs`, `grepai-reminder.mjs`) self-install per-project via `/brewcode:grepai setup` — they are not part of the plugin's always-on hook set.
## KB Format
```jsonl
+11 -36
View File
@@ -22,7 +22,6 @@ brewcode/ # Plugin root directory
│ └── forced-eval.mjs # UserPromptSubmit: skill activation reminder (~9K additionalContext bound)
├── agents/ # Plugin agents (system prompts in Markdown)
│ ├── bc-grepai-configurator.md # grepai configurator (opus): project analysis, config.yaml via 5 parallel investigations
│ ├── bc-rules-organizer.md # Rules organizer (sonnet): creates/optimizes .claude/rules/*.md
│ ├── agent-creator.md # Agent creator (opus): Agent Architect Process, System Prompt Patterns
│ ├── skill-creator.md # Skill creator (opus): Six-Step Creation Process, word budget 1500-2000
@@ -34,29 +33,11 @@ brewcode/ # Plugin root directory
│ ├── reviewer.md # Reviewer (opus): code review, quality, security, performance
│ └── tester.md # Tester (sonnet): SDET/QA - runs tests, analyzes failures
├── skills/ # Skills - plugin commands (9 total)
├── skills/ # Skills - plugin commands (8 total)
│ │
│ ├── spec/ # /brewcode:spec - Specification creation
│ │ └── SKILL.md # 7 steps: investigation (5-10 parallel agents), dialog, review (opus, session)
│ │
│ ├── grepai/ # /brewcode:grepai - Semantic search management
│ │ ├── SKILL.md # 7 modes: setup/status/start/stop/reindex/optimize/upgrade (sonnet, session)
│ │ ├── config.yaml.example # Example grepai config: embedder, chunking, trace, ignore
│ │ └── scripts/
│ │ ├── detect-mode.sh # Argument parsing: operation mode
│ │ ├── infra-check.sh # grepai CLI, ollama, bge-m3
│ │ ├── install.sh # grepai via Homebrew
│ │ ├── mcp-check.sh # MCP server: settings.json, allowedTools
│ │ ├── init-index.sh # Index init: grepai watch, waits for build
│ │ ├── start.sh # Starts grepai watch in background
│ │ ├── stop.sh # Stops grepai watch
│ │ ├── reindex.sh # Rebuild: stop → clean → rebuild → restart
│ │ ├── optimize.sh # Reanalysis, new config.yaml with backup
│ │ ├── upgrade.sh # brew upgrade grepai
│ │ ├── status.sh # Diagnostics: CLI, ollama, bge-m3, MCP, index, versions
│ │ ├── verify.sh # Full functionality check
│ │ └── create-rule.sh # Creates grepai-first.md in .claude/rules/
│ │
│ ├── superreview/ # /brewcode:superreview - Generate project-tailored deep-review skill
│ │ ├── SKILL.md # Generator: emits .claude/skills/superreview/ into target project (opus, fork)
│ │ ├── references/ # Per-stack reviewer guidelines + SKILL.md.template
@@ -97,21 +78,17 @@ brewcode/ # Plugin root directory
├── templates/
│ │
── rules/
├── avoid.md.template # Anti-patterns: Avoid/Instead/Why table with YAML frontmatter
── best-practice.md.template # Best practices: Practice/Context/Source table with YAML frontmatter
│ │ └── grepai-first.md.template # grepai priority rule: call examples, tool selection table
── rules/
├── avoid.md.template # Anti-patterns: Avoid/Instead/Why table with YAML frontmatter
── best-practice.md.template # Best practices: Practice/Context/Source table with YAML frontmatter
├── docs/
│ ├── file-tree.md # This file
│ ├── grepai.md # grepai integration: ecosystem, attention architecture, MCP, gitignore limitations
│ ├── commands.md # Command reference: all /brewcode:* skills, arguments, examples
── flow.md # Execution flow diagrams: hook lifecycle, 2-step protocol, compaction
│ └── hooks.md # Hook reference: events, timeouts, input/output contracts
── flow.md # Execution flow diagrams: hook lifecycle, 2-step protocol, compaction
├── README.md # Components, commands, agents, hooks, architecture, flow diagrams
├── INSTALL.md # Installation: plugin-dir, marketplace, embedding, troubleshooting
├── RELEASE-NOTES.md # Version history: v2.0.41 - v3.0.0, Breaking Changes, migration
└── package.json # npm: claude-plugin-brewcode@3.1.0, build/publish scripts
```
@@ -156,7 +133,6 @@ Files created by the plugin in the user's project:
└── rules/
├── avoid.md # Anti-patterns (from /brewcode:rules)
├── best-practice.md # Best practices (from /brewcode:rules)
└── grepai-first.md # grepai priority rule (from /brewcode:grepai setup)
```
## Statistics
@@ -165,13 +141,13 @@ Files created by the plugin in the user's project:
|----------|-------|-------|
| Plugin configuration | 2 | plugin.json, hooks.json |
| Hooks | 2 | forced-eval, session-start |
| Agents | 10 | bc-grepai-configurator, bc-rules-organizer, agent-creator, skill-creator, bash-expert, hook-creator, architect, developer, reviewer, tester |
| Skills (SKILL.md) | 9 | spec, grepai, superreview, convention, rules, skills, agents, teams, e2e |
| Bash scripts | 22 | grepai(13), teams(3), skills(2), superreview(1), convention(1), rules(1), e2e(1) |
| Templates | 3 | rules(3) |
| Documentation | 7 | README, INSTALL, RELEASE-NOTES, grepai.md, file-tree.md, commands.md, flow.md, hooks.md |
| Agents | 9 | bc-rules-organizer, agent-creator, skill-creator, bash-expert, hook-creator, architect, developer, reviewer, tester |
| Skills (SKILL.md) | 8 | spec, superreview, convention, rules, skills, agents, teams, e2e |
| Bash scripts | 9 | teams(3), skills(2), superreview(1), convention(1), rules(1), e2e(1) |
| Templates | 2 | rules(2) |
| Documentation | 5 | README, INSTALL, file-tree.md, commands.md, flow.md |
| npm | 1 | package.json |
| **Total** | **69** | |
| **Total** | **38** | |
## Hook Events
@@ -184,4 +160,3 @@ Files created by the plugin in the user's project:
| Agent | Model | Purpose |
|-------|-------|---------|
| bc-grepai-configurator | opus | Project analysis, config.yaml generation |
-476
View File
@@ -1,476 +0,0 @@
[DICT: GA=grepai, BGC=bc-grepai-configurator, SS=SessionStart, PTU=PreToolUse, AC=additionalContext, CFG=config.yaml, CE=code exploration, INJ=injection point, OL=Ollama]
# GA Integration
> Semantic CE via embeddings. Integrated into brewcode via MCP with forced AI attention system.
**See also:** [README.md](README.md) | [INSTALL.md](INSTALL.md) | [BGC](agents/bc-grepai-configurator.md) | [/brewcode:grepai](skills/grepai/SKILL.md)
## Architecture
```
Claude Code CLI
|
+-- [project-installed] SS hook: grepai-session.mjs (health check + status)
+-- [project-installed] PTU:Bash: grepai-reminder.mjs (remind to use grepai_search)
|
v
Unified Reminder: "grepai: USE grepai_search FIRST for code exploration"
|
+-- Explore/Plan/Bash agents
+-- developer/tester/reviewer agents
+-- custom agents
```
## Directory Structure
```
{PROJECT}/
├── .grepai/
│ ├── config.yaml # Generated by BGC
│ ├── config.yaml.backup # Created during optimize
│ ├── index.gob # Vector embeddings (created by watch)
│ ├── symbols.gob # Call graph data
│ └── logs/grepai-watch.log # Daemon log
├── .claude/
│ ├── grepai/hooks/ # Hook assets installed by /brewcode:grepai setup
│ │ ├── grepai-session.mjs # Copied from brewcode/skills/grepai/assets/
│ │ └── grepai-reminder.mjs # Copied from brewcode/skills/grepai/assets/
│ ├── rules/grepai-first.md # Attention-forcing rule
│ └── logs/brewcode.log # Hook diagnostic log
└── CLAUDE.md # Contains "CRITICAL: Use grepai_search FIRST"
brewcode/
├── skills/grepai/
│ ├── SKILL.md
│ ├── config.yaml.example
│ ├── assets/
│ │ ├── grepai-session.mjs # SS hook asset (installed by setup)
│ │ ├── grepai-reminder.mjs # PTU:Bash hook asset (installed by setup)
│ │ └── INSTALL.md # Install instructions
│ └── scripts/ # 11 bash scripts (detect-mode, infra-check, mcp-check, init-index,
│ # start, stop, reindex, optimize, upgrade, status, verify, create-rule)
├── agents/bc-grepai-configurator.md
└── templates/rules/grepai-first.md.template
```
---
# ATTENTION SYSTEM
> 5 INJs ensuring GA priority. INJ #1 and #2 active only after /brewcode:grepai setup installs hooks.
**Unified reminder:** `grepai: USE grepai_search FIRST for code exploration`
- Prefix `grepai:` for categorization
- Uppercase `USE...FIRST` for imperative force
- Exact tool name: `grepai_search`
## 5 INJ Points
| # | Point | Hook/File | Event | Scope | Strength |
|---|-------|-----------|-------|-------|----------|
| 1 | SS | grepai-session.mjs (project-installed) | SS | Session ctx | MUST |
| 2 | PTU:Bash | grepai-reminder.mjs (project-installed) | PTU | Bash calls | MUST |
| 3 | Rule file | grepai-first.md.template:7 | Always | All files (`**/*`) | CRITICAL |
| 4 | CLAUDE.md | create-rule.sh:18 | Persistent | Project cfg | CRITICAL |
| 5 | Root CLAUDE.md | CLAUDE.md:101 | Always | Global | CRITICAL |
## INJ Flow
```
SS → INJ #1 (grepai-session.mjs, project-installed):
Check: .grepai/ exists? + OL running? + index.gob exists?
YES → AC: "grepai: USE grepai_search FIRST..."
→ systemMessage: "grepai: ready | index: 150MB"
User triggers Bash →
Bash → INJ #2 (grepai-reminder.mjs, project-installed): AC reminder
Persistent (always active):
INJ #4: .claude/rules/grepai-first.md (paths: **/*)
INJ #5: {PROJECT}/CLAUDE.md (via create-rule.sh)
INJ #6: root CLAUDE.md (line 101)
```
## Detailed INJ Mechanisms
### INJ #1: grepai-session.mjs (SS, project-installed)
```javascript
// skills/grepai/assets/grepai-session.mjs (project-installed by /brewcode:grepai setup)
if (status.length === 0) { // All systems healthy
hookSpecificOutput.additionalContext =
'grepai: USE grepai_search FIRST for code exploration';
}
```
Trigger conditions: `.grepai/` exists + OL running (`curl localhost:11434/api/tags`) + `index.gob` exists + `grepai watch` active. Requires prior setup install.
### INJ #2: grepai-reminder.mjs (PTU:Bash, project-installed)
```javascript
// skills/grepai/assets/grepai-reminder.mjs (project-installed by /brewcode:grepai setup)
if (existsSync(grepaiDir)) {
output({ hookSpecificOutput: {
hookEventName: 'PreToolUse',
additionalContext: 'grepai: USE grepai_search FIRST for code exploration'
}});
}
```
Trigger: every Bash call (PTU:Bash, when installed by setup). Reminds about semantic alternative.
### INJ #3: grepai-first.md.template (Rule)
```markdown
---
paths:
- "**/*"
description: grepai-first - semantic search FIRST for code exploration
---
# grepai-first
> **FIRST** `grepai` mcp for code exploration. Params → MCP descriptions.
| Need | Tool | Params |
|------|------|--------|
| Explore (<=5 results) | search | `limit:5` → read content directly |
| Explore (>5 results) | search | `limit:10, compact:true` → then Read |
| Who calls X? | trace_callers | `symbol:"X"` |
| What X calls? | trace_callees | `symbol:"X"` |
| Full dependency tree | trace_graph | `symbol:"X", depth:2` |
**Decision:** "Need exact text/pattern?" → YES: Grep/Glob, NO: grepai
```
### INJ #4 & #5: CLAUDE.md (project + root)
```markdown
## Code Search
> **CRITICAL:** Use `grepai_search` FIRST for code exploration.
```
## Attention Strength Escalation
| Version | Message | Strength |
|---------|---------|----------|
| v2.0.57 | `consider grepai_search FIRST` | Advisory |
| v2.0.58 | `USE grepai_search FIRST` | Imperative |
## Install State Design
```
.grepai/ exists?
NO → graceful skip, no injection from any hook
YES + hooks project-installed (via /brewcode:grepai setup)?
grepai-session.mjs → injects AC at SS
grepai-reminder.mjs → injects AC at PTU:Bash
YES + hooks NOT installed?
run /brewcode:grepai setup to self-install:
copies assets to .claude/grepai/hooks/
merges SessionStart + PTU:Bash entries into .claude/settings.json (jq + python3 fallback)
idempotent — safe to re-run
```
---
# CONTEXT COMPOSITION
> What Claude sees: 4 context layers.
## Context Layers
| Layer | Source | Content |
|-------|--------|---------|
| 1 - System prompt (static) | Claude Code base | Instructions + tool definitions + env info |
| 1a - MCP Server Instructions | `grepai` server `instructions` field | "Use semantic search for CE..." |
| 2 - Tools array | MCP server `tools` | `mcp__grepai__grepai_search` schema with full param descriptions |
| 3 - User messages (dynamic) | CLAUDE.md + rules + hook AC | grepai-first.md rule injected each turn |
| 4 - Hook injections | grepai-session.mjs (project-installed), grepai-reminder.mjs (project-installed) | AC at SS + PTU:Bash |
## Attention Flow: Rule → MCP Tool Descriptions
```
USER: "Find authentication code"
→ Rule (grepai-first.md): "Params → MCP descriptions" [~50 tokens]
→ Claude reads tool def for mcp__grepai__grepai_search [~200 tokens, already loaded]
→ Invokes: grepai_search(query="authentication flow", limit=10)
```
**Design principle:** Rule = pointer (minimal tokens). Full details in tool definition already in context.
```
Rule (50 tokens): "Params → MCP descriptions"
|
Tool def (0 extra tokens): query/limit/compact descriptions
```
## MCP Server Instructions
```javascript
// grepai MCP server registration
{
"name": "grepai",
"instructions": "Use semantic search for code exploration. Prefer grepai_search over Glob/Grep.",
"tools": [...]
}
```
Result in system prompt:
```
## grepai
Use semantic search for code exploration...
```
## All INJ Points Summary
| Scope | Source | Mechanism |
|-------|--------|-----------|
| System prompt (static) | MCP server `instructions` + `tools` | GA instructions + tool defs |
| User messages (dynamic) | CLAUDE.md + grepai-first.md + hook AC | Per-turn rule + hook context |
---
# CONFIGURATION
## config.yaml Structure
```yaml
version: 1
embedder:
provider: ollama
model: bge-m3 # Multilingual, 1024 dims
endpoint: http://localhost:11434
dimensions: 1024
parallelism: 1 # CRITICAL: Always 1 (Ollama limitation)
store:
backend: gob # Local file storage
chunking:
size: 512 # 768-1024 for Java/Kotlin
overlap: 50 # 75-100 for verbose languages
watch:
debounce_ms: 500 # 100 (responsive) | 500 (balanced) | 1000 (calm)
# NEVER include last_index_time - causes skip bug
search:
boost:
enabled: true
penalties:
- pattern: "**/test/**" # Tests: 0.5
factor: 0.5
- pattern: "**/*Mock*" # Mocks: 0.4
factor: 0.4
- pattern: "**/generated/**" # Generated: 0.4
factor: 0.4
bonuses:
- pattern: "**/src/main/**" # Main source: 1.1
factor: 1.1
- pattern: "**/core/**" # Core: 1.2
factor: 1.2
hybrid:
enabled: false # true for Java/Kotlin
k: 60 # RRF smoothing
trace:
mode: fast # fast (regex) | precise (AST)
enabled_languages:
- .java
- .kt
- .kts
exclude_patterns:
- "*Test.java"
- "*Spec.kt"
ignore:
- .git
- .grepai
- node_modules
- vendor
- dist
- build
- target
```
## Language-Specific Defaults
| Setting | Java/Kotlin | JS/TS | Go/Rust | Python |
|---------|-------------|-------|---------|--------|
| chunking.size | 768-1024 | 512 | 256-384 | 512 |
| chunking.overlap | 75-100 | 50 | 30-40 | 50 |
| search.hybrid.enabled | true | false | false | false |
| trace.mode | precise/fast | fast | fast | fast |
## Critical CFG Rules
| Rule | Why |
|------|-----|
| `parallelism: 1` | OL limitation (https://github.com/ollama/ollama/issues/12591) |
| !=`watch.last_index_time` | Files with ModTime < this value are SKIPPED |
| dimensions match model | bge-m3: 1024, nomic: 768 |
## gitignore Behavior
gitignore layers (additive only):
1. Global: `~/.gitignore_global` or `~/.config/git/ignore`
2. Local: `{PROJECT}/.gitignore`
3. GA CFG: `.grepai/config.yaml` `ignore:` section
Rules: GA respects ALL layers combined | !=override gitignore via cfg | !=negation patterns (`!pattern`)
Diagnostic: `git check-ignore -v <path>`
---
# MCP TOOLS
| Tool | Parameters | Description |
|------|-----------|-------------|
| `grepai_search` | `query`, `limit`, `compact` | Semantic CE |
| `grepai_trace_callers` | `symbol`, `compact` | Find all callers of symbol |
| `grepai_trace_callees` | `symbol`, `compact` | Find all callees of symbol |
| `grepai_trace_graph` | `symbol`, `depth`, `compact` | Build call graph |
| `grepai_index_status` | `verbose` | Check index health |
## Compact Mode (80% token reduction)
```json
// Normal response
{"query":"authentication flow","results":[{"score":0.92,"file":"src/auth/LoginService.java","lines":"15-45","content":"public class LoginService..."}],"total":1}
// Compact response
{"q":"auth","r":[{"s":0.92,"f":"src/auth.go","l":"15-45"}],"t":1}
```
Key mapping: `q`=query, `r`=results, `s`=score, `f`=file, `l`=lines, `t`=total
## MCP Configuration
```json
// .mcp.json (project) or ~/.claude.json (global)
{
"mcpServers": {
"grepai": {
"command": "grepai",
"args": ["mcp-serve"],
"cwd": "/path/to/project"
}
}
}
```
CLI: `claude mcp add grepai -- grepai mcp-serve`
## Permissions (allowedTools)
```json
// ~/.claude/settings.json
{ "allowedTools": ["mcp__grepai__*"] }
```
Why: MCP tools marked `[destructive]` by default; all GA tools are read-only.
---
# SKILL: /brewcode:grepai
## Modes
| Mode | Trigger | Purpose |
|------|---------|---------|
| `setup` | setup, install, configure, init | Full installation |
| `status` | status, doctor, check, health | Health check |
| `start` | start, watch | Start watcher daemon |
| `stop` | stop, halt, kill | Stop watcher |
| `reindex` | reindex, rebuild, refresh | Full index rebuild |
| `optimize` | optimize, update | Regenerate cfg |
| `upgrade` | upgrade, brew | Update CLI via Homebrew |
## Scripts
| Script | Purpose |
|--------|---------|
| detect-mode.sh | Parse args, determine mode |
| infra-check.sh | Verify GA/OL/bge-m3 |
| mcp-check.sh | Configure MCP + permissions |
| init-index.sh | Build index (sync) |
| start.sh | Start watch daemon |
| stop.sh | Stop watch daemon |
| reindex.sh | Full rebuild |
| optimize.sh | Backup cfg |
| upgrade.sh | Homebrew upgrade |
| status.sh | Health check |
| verify.sh | Test search |
| create-rule.sh | Generate grepai-first.md |
---
# AGENT: BGC
**Model:** Opus 4.5 | **Type:** Subagent | **Permission:** acceptEdits
## Workflow
```
Phase 1: Infra check — verify GA binary + OL + bge-m3 model
Phase 2: Parallel project analysis (5 Explore agents):
LANGUAGES - build files (pom.xml, package.json, go.mod)
TEST PATTERNS - test dirs
GENERATED - codegen patterns
SOURCE - main dirs
IGNORE - gitignore analysis
Phase 3: Generate .grepai/config.yaml
Phase 4: MCP integration — configure Claude Code access
Phase 5: Verification — test search, check index
```
---
# EMBEDDER MODELS
| Model | Dims | Size | RAM | Speed | Quality | Use Case |
|-------|------|------|-----|-------|---------|----------|
| bge-m3 | 1024 | 1.2GB | ~1.5GB | Fast | Excellent | Multilingual (default) |
| mxbai-embed-large | 1024 | 670MB | ~1GB | Very Fast | Excellent | English-only, max accuracy |
| nomic-embed-text-v2-moe | 768 | 500MB | ~800MB | Very Fast | Very Good | 100+ langs, lightweight |
| nomic-embed-text | 768 | 274MB | ~500MB | Fastest | Good | Fast, small projects |
---
# INDEXING TIME
| Files | Time |
|-------|------|
| <100 | ~30s |
| ~1,000 | ~5 min |
| ~10,000 | ~30 min |
---
# QUERY TIPS
| Do | Don't |
|----|-------|
| English | Other languages |
| 3-7 words | Single word |
| Intent: "user authentication flow" | Syntax: "validateUser()" |
| Specific: "handles login errors" | Vague: "error handling" |
---
# TROUBLESHOOTING
| Issue | Solution |
|-------|----------|
| Files not indexed | `git check-ignore -v <path>` |
| Index outdated | `/brewcode:grepai reindex` |
| OL not running | `ollama serve` |
| Watch not starting | Check `.grepai/logs/grepai-watch.log` |
| Slow indexing | Check `parallelism: 1` in cfg |
| Poor search quality | Adjust `chunking.size` for language |
-1
View File
@@ -43,7 +43,6 @@ const DEFAULT_CONFIG = {
},
agents: {
system: [
'bc-grepai-configurator', 'brewcode:bc-grepai-configurator',
'Explore', 'Plan', 'Bash', 'general-purpose',
'claude-code-guide', 'skill-creator', 'agent-creator',
'text-optimizer', 'statusline-setup'
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "claude-plugin-brewcode",
"version": "4.3.0",
"version": "4.4.0",
"description": "Infinite task execution with automatic handoff for Claude Code",
"keywords": [
"claude-code",
@@ -36,6 +36,6 @@
},
"claude-plugin": {
"name": "brewcode",
"version": "4.3.0"
"version": "4.4.0"
}
}
+1 -2
View File
@@ -144,7 +144,7 @@ Stack: {DETECTED_STACK}
Layer definitions:
{LAYER_CRITERIA_FROM_ANALYSIS_LAYERS_MD}
Use grepai_search FIRST for file discovery, then Glob/Grep for verification.
Use Bash search for file discovery (`grep`->ugrep / `find`->bfs on macOS CC), then Read for verification.
CONSUMER: P3 (1 architect) merges all 10 reports and picks 1-2 etalons per layer, then P4
writes .claude/convention/*.md from that. Your tables are parsed as-is — keep the exact
@@ -372,7 +372,6 @@ Next Steps: Review `.claude/convention/` | `/brewcode:convention rules` to re-ex
| >1000 source files | Warn user, suggest `paths` mode |
| Unknown stack | Continue with generic analysis (no stack-specific layers) |
| Agent timeout | Log warning, continue with available results |
| grepai unavailable | Fall back to Glob + Grep for file discovery |
| Convention doc generation fails | Retry once, then present partial results |
</instructions>
-23
View File
@@ -1,23 +0,0 @@
MIT License
Copyright (c) 2025-2026 Maxim Kochetkov (kochetkov-ma)
https://github.com/kochetkov-ma/claude-brewcode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-109
View File
@@ -1,109 +0,0 @@
# Grepai
Sets up and manages semantic code search powered by grepai (Ollama + bge-m3 embeddings). Lets Claude find code by meaning rather than exact keywords -- search for "user authentication" and find `validateCredentials()`.
## Quick Start
```
/brewcode:grepai setup
```
First-time setup takes 5-30+ minutes depending on project size. It checks infrastructure, configures MCP, generates an optimal config, builds the index, and creates a Claude rule.
## Modes
| Mode | Trigger keywords | What it does |
|------|-----------------|--------------|
| `setup` | setup, configure, init | Full installation: infra check, MCP config, config generation (via bc-grepai-configurator agent), initial indexing, rule creation |
| `status` | status, doctor, check, health | Reports health of all components: CLI, Ollama, bge-m3, MCP, index, watcher |
| `start` | start, watch | Starts the file watcher -- auto-indexes on code changes |
| `stop` | stop, halt, kill | Stops the file watcher |
| `reindex` | reindex, rebuild, refresh | Full index rebuild: stops watcher, cleans index, rebuilds from scratch, restarts watcher |
| `optimize` | optimize, update | Backs up current config, re-analyzes the project, regenerates config, then reindexes |
| `upgrade` | upgrade | Updates grepai CLI to the latest version via Homebrew |
| `uninstall` | uninstall, remove | Removes grepai from this project: stops watch, deletes + unwires both hooks, drops the rule; asks before deleting `.grepai/`. Keeps CLI, ollama, bge-m3, MCP entry |
| `prompt` | (unrecognized text) | Interactive menu -- asks which operation to run |
**Auto-detection:** Running `/brewcode:grepai` with no arguments defaults to `start` if `.grepai/` exists, or `setup` if it does not.
## Examples
### Good Usage
```
# First-time setup on a new project
/brewcode:grepai setup
# Check if everything is healthy after a restart
/brewcode:grepai status
# Start the watcher at the beginning of a work session
/brewcode:grepai start
# Rebuild the index after a large merge or branch switch
/brewcode:grepai reindex
# Re-analyze and regenerate config after adding a new module
/brewcode:grepai optimize
```
### Common Mistakes
```
# Searching before the index is built -- run setup first
/brewcode:grepai start <-- watcher starts but index is empty
# Running setup again when grepai is already configured -- use reindex or optimize instead
/brewcode:grepai setup <-- overwrites existing config
# Missing prerequisites -- install Homebrew, Ollama, and the grepai CLI first
/brewcode:grepai setup <-- fails on missing Ollama or bge-m3
```
## Hook Self-Install
On first `/brewcode:grepai` setup run, the skill self-installs two project hooks:
1. Detects whether `.claude/grepai/hooks/` already exists (idempotent -- safe to re-run).
2. Default scope: PROJECT. Asks via AskUserQuestion only when scope is ambiguous.
3. Copies `assets/grepai-session.mjs` and `assets/grepai-reminder.mjs` to `.claude/grepai/hooks/`.
4. Merges SessionStart and PreToolUse:Bash entries into `.claude/settings.json` (jq + python3 fallback, no clobber).
5. Reports what was created.
After install, grepai reminders fire automatically at session start (SS) and on every Bash call (PTU:Bash).
## Output
After `setup` completes, the following is created in your project:
| Path | Purpose |
|------|---------|
| `.grepai/config.yaml` | Project-specific search configuration (languages, boost patterns, exclusions) |
| `.grepai/logs/grepai-watch.log` | Watcher and indexing logs |
| `.grepai/index.gob`, `.grepai/symbols.gob` | Embedded search index + symbol table (GOB storage) |
| `.claude/rules/grepai-first.md` | Rule: grepai FIRST for code exploration, compact output by default |
| `.claude/grepai/hooks/*.mjs` | SessionStart + PreToolUse:Bash hooks (see below) |
| `CLAUDE.md` | `## Code Search` section appended if absent |
MCP server is configured with `grepai_search` and related tools (`trace_callers`, `trace_callees`, `trace_graph`).
## Compact-first (enforced)
Full-content results from 10 chunks can flood the context in a single call. The rule, the CLAUDE.md entry, and both hooks all push the same policy:
| | Rule |
|---|---|
| Default | `compact:true, format:"toon", limit:10` -> path+lines only -> `Read` the top 1-3 hits |
| `compact:false` only if | a compact pass already ran, `limit<=3`, one narrow query |
| Never | `compact:false` as the first call, with `limit>3`, or on a broad query |
## Tips
- **Monitor long indexing runs** with `tail -f .grepai/logs/grepai-watch.log` -- large projects (5k+ files) can take 10-30+ minutes.
- **Install prerequisites first** (Homebrew, Ollama, grepai CLI) if you do not have them; `setup` runs an infra check and reports what is missing.
- **Use `optimize` after structural changes** (new modules, renamed packages, changed build config) to regenerate the config with fresh project analysis.
- **Check `status` when search results seem off** -- it validates every component from CLI to index integrity.
## Documentation
Full docs: [grepai](https://doc-claude.brewcode.app/brewcode/skills/grepai/)
-466
View File
@@ -1,466 +0,0 @@
---
name: brewcode:grepai
description: "Manages grepai semantic code search: setup, status, start, stop, reindex, optimize, upgrade, uninstall. Triggers: grepai, semantic search, reindex, index status."
disable-model-invocation: true
argument-hint: "[setup|status|start|stop|reindex|optimize|upgrade|uninstall]"
allowed-tools: Read, Write, Edit, Bash, Task, AskUserQuestion
model: sonnet
---
# grepai Skill
> **Environment:** Ollama + bge-m3 | GOB storage | Java/Kotlin/JS/TS
<instructions>
## Mode Detection
### Step 1: Detect Mode (MANDATORY FIRST STEP)
**EXECUTE** using Bash tool — detect mode from skill arguments:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/detect-mode.sh" "$ARGUMENTS"
```
Output format:
```
ARGS: [arguments received]
MODE: [detected mode]
```
**Use the MODE value and GOTO that section below.**
### Mode Reference
| Keyword in args | MODE |
|-----------------|------|
| uninstall, remove, удали, снеси | uninstall |
| upgrade, апгрейд | upgrade |
| optimize, update, улучши, обнови | optimize |
| stop, halt, kill | stop |
| start, watch | start |
| status, doctor, check, health | status |
| setup, configure, init | setup |
| reindex, rebuild, refresh | reindex |
| (empty) + .grepai/ exists | start |
| (empty) + no .grepai/ | setup |
| (unrecognized text) | prompt |
> **Prerequisites:** Homebrew, Ollama, the bge-m3 model, and the grepai CLI. The `setup` mode below runs `infra-check.sh` to verify them and, if anything is missing, offers to auto-install everything via `scripts/install.sh` (after confirmation).
---
## Mode: setup
Full grepai installation and project setup.
### Phase 1: Infrastructure Check & Auto-Install
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/infra-check.sh" && echo "✅ infra-check" || echo "⚠️ infra-check: prerequisites missing"
```
- Printed `✅ infra-check` (all present) -> skip to Phase 2.
- Printed `⚠️ infra-check: prerequisites missing` -> continue to auto-install below.
#### Offer Auto-Install
> `scripts/install.sh` installs every missing prerequisite via Homebrew: brew, coreutils + `timeout` symlink, jq, ollama (+ service start), the bge-m3 embedding model, and the grepai CLI. It is idempotent — already-installed components are skipped.
**ASK** (AskUserQuestion): "grepai prerequisites are missing. Auto-install them now? This creates a `timeout` symlink (coreutils) and downloads the grepai CLI + bge-m3 model (~1.5GB)."
Options: "Yes, install" | "Cancel"
> **If Cancel** -> STOP: "grepai setup cancelled. Install prerequisites manually, then re-run `/brewcode:grepai setup`."
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/install.sh" && echo "✅ install" || echo "❌ install FAILED"
```
> **STOP if ❌** — check the install output for the failed component and install it manually.
#### Re-verify
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/infra-check.sh" && echo "✅ infra-check" || echo "❌ infra-check FAILED"
```
> **STOP if ❌** — prerequisites still missing after install; inspect the install output above.
### Phase 2: MCP Configuration & Permissions
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/mcp-check.sh" && echo "✅ mcp-check" || echo "❌ mcp-check FAILED"
```
This script configures MCP server and allowedTools permissions.
> **STOP if ❌** — fix MCP configuration before continuing.
### Phase 3: Generate Config
**SPAWN** the `bc-grepai-configurator` agent using Task tool:
| Parameter | Value |
|-----------|-------|
| `subagent_type` | `brewcode:bc-grepai-configurator` |
| `prompt` | see the delegation brief below |
| `model` | `sonnet` (matches the agent's own pin — do NOT override to opus) |
**Delegation brief — applies to every Task spawn in this skill.**
A big task handed to one agent = an agent gone for an hour: you cannot observe it, cannot correct
it, and it usually drifts off-target. One subagent = ONE bounded unit — one deliverable
(here: ONE config file), ~<=5 files, ~<=10 steps. Bigger MUST be split into N tasks, all spawned
in ONE message.
Every spawn prompt MUST carry:
| Field | Content |
|-------|---------|
| GOAL | the overall task and why it exists — the point beyond the file edit |
| ROLE | what this agent owns; what it must NOT touch |
| SCOPE | exact paths/commands in bounds + explicit out-of-bounds |
| CONTEXT | what is already done, by whom, what runs in parallel — trimmed to what THIS agent needs |
| CONSUMER | who or what uses the result next, and the shape it must fit |
| DONE | acceptance criteria + the exact report shape you want back |
A bare one-line task is never enough. Filled in for this phase:
```
GOAL: this project is being wired for semantic code search; this task delivers the ONE
config file that drives indexing quality.
ROLE: you own .grepai/config.yaml only. Do NOT touch source code, .claude/settings.json,
hooks, or the index itself.
SCOPE: read build files, test patterns, source structure; write .grepai/config.yaml.
Out of bounds: everything else.
CONTEXT: Phases 1-2 already installed and verified the grepai CLI and the MCP server — do not
re-install or re-check them. You are the only agent running; Phases 5-6 install the
project hooks and merge .claude/settings.json afterwards, so leave both alone.
CONSUMER: Phase 4 runs `grepai index` straight off this file and Phase 5 keeps it watched;
every later grepai_search hit is only as good as these globs. A wrong exclude silently
hides code rather than erroring — flag what you could not infer instead of guessing.
DONE: valid config.yaml written; report as: languages | include/exclude globs | boost
patterns | anything you could not infer.
```
> **Context:** the agent resolves its plugin root natively via `${CLAUDE_PLUGIN_ROOT}` (substituted in its .md at Task spawn).
> **WAIT** for agent to complete before proceeding.
### Phase 4: Initialize Index
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/init-index.sh" && echo "✅ init-index" || echo "❌ init-index FAILED"
```
> **STOP if ❌** — check `.grepai/logs/grepai-watch.log` for errors.
> ⏳ **Synchronous — Large projects (5k+ files) take 10-30+ min.** Monitor: `tail -f .grepai/logs/grepai-watch.log`
### Phase 5: Create Rule
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/create-rule.sh" && echo "✅ create-rule" || echo "❌ create-rule FAILED"
```
> **STOP if ❌** — manually create rule in `.claude/rules/`.
### Phase 6: Install grepai Hooks (self-install)
> grepai ships two self-contained hooks that travel into the user's project (NOT
> the plugin): `grepai-session.mjs` (SessionStart — auto-starts `grepai watch` and
> injects "USE grepai_search FIRST" when the index is live) and
> `grepai-reminder.mjs` (PreToolUse:Bash — nudges toward `grepai_search` when a
> `grep/find/rg` command runs). Self-install is idempotent. Runbook + jq/python3
> merge details: `${CLAUDE_SKILL_DIR}/assets/INSTALL.md`.
#### Step 1: Detect (idempotent — skip if already installed)
**EXECUTE** using Bash tool:
```bash
SETTINGS="$PWD/.claude/settings.json"
if [ -f "$SETTINGS" ] && grep -q 'grepai-session.mjs' "$SETTINGS" 2>/dev/null; then
echo "✅ hooks already installed — skip Phase 6"
else
echo "⚠️ hooks not installed — continue"
fi
```
- Printed `✅ hooks already installed` -> SKIP to Phase 7. Do NOT re-copy/re-merge.
- Printed `⚠️ hooks not installed` -> continue.
#### Step 2: Choose scope
Scope is PROJECT by default. grepai setup always runs against THIS repo, so the
scope is unambiguous — **default to PROJECT and SKIP the questions**.
Ask via `AskUserQuestion` ONLY when scope is genuinely ambiguous (e.g. the user
explicitly says "for all my projects" / "globally", or there is no obvious single
project root):
- "Install grepai hooks for this Project or Globally?" (options: **Project** / **Global**)
- Confirm hook creation: "grepai will copy two SessionStart + PreToolUse:Bash hooks into `<scope>/.claude/grepai/hooks/` and merge them into `settings.json`. Proceed?" (options: **Yes, install** / **Skip hooks**)
> Skip hooks -> note it and GOTO Phase 7 (search config still works via MCP; only
> the auto-watch + reminder are skipped).
#### Step 3: Copy + merge (no clobber)
Follow the runbook. `SRC` = this skill's assets dir; `DST`/`SETTINGS` by scope.
PROJECT writes freely; GLOBAL (`~/.claude/*`) MUST go through the Bash tool only
(protected path — Bash `cp`/`jq`/`python3`/`mv` are allowed, Write/Edit are not).
**EXECUTE** using Bash tool (PROJECT scope shown; for GLOBAL set the two GLOBAL
paths from the comments):
```bash
SRC="${CLAUDE_SKILL_DIR}/assets"
# PROJECT: DST="$PWD/.claude/grepai/hooks"; SETTINGS="$PWD/.claude/settings.json"
# GLOBAL: DST="$HOME/.claude/grepai/hooks"; SETTINGS="$HOME/.claude/settings.json"
DST="$PWD/.claude/grepai/hooks"
SETTINGS="$PWD/.claude/settings.json"
# Path written INTO settings.json — keep it relocatable (GLOBAL: use "$HOME/.claude/grepai/hooks")
HOOK_REF='$CLAUDE_PROJECT_DIR/.claude/grepai/hooks'
mkdir -p "$DST" && cp "$SRC/grepai-session.mjs" "$SRC/grepai-reminder.mjs" "$DST/" \
&& echo "✅ copied to $DST" || { echo "❌ copy FAILED"; exit 1; }
mkdir -p "$(dirname "$SETTINGS")"
[ -f "$SETTINGS" ] || echo '{}' > "$SETTINGS"
S_CMD="node $HOOK_REF/grepai-session.mjs"
R_CMD="node $HOOK_REF/grepai-reminder.mjs"
if command -v jq >/dev/null 2>&1; then
TMP="$(mktemp)"
jq --arg scmd "$S_CMD" --arg rcmd "$R_CMD" '
.hooks = (.hooks // {})
| .hooks.SessionStart = (.hooks.SessionStart // [])
| (if (.hooks.SessionStart | map(.hooks // [] | map(.command // "") | any(test("grepai-session\\.mjs"))) | any)
then .
else (if (.hooks.SessionStart | length) > 0
then .hooks.SessionStart[0].hooks += [{"type":"command","command":$scmd}]
else .hooks.SessionStart += [{"hooks":[{"type":"command","command":$scmd}]}] end)
end)
| .hooks.PreToolUse = (.hooks.PreToolUse // [])
| (if (.hooks.PreToolUse | map(.hooks // [] | map(.command // "") | any(test("grepai-reminder\\.mjs"))) | any)
then .
else (.hooks.PreToolUse | map((.matcher // "") == "Bash") | index(true)) as $i
| (if $i != null
then .hooks.PreToolUse[$i].hooks += [{"type":"command","command":$rcmd}]
else .hooks.PreToolUse += [{"matcher":"Bash","hooks":[{"type":"command","command":$rcmd}]}] end)
end)
' "$SETTINGS" > "$TMP" && mv "$TMP" "$SETTINGS" \
&& jq empty "$SETTINGS" >/dev/null 2>&1 && echo "✅ merged $SETTINGS (jq)" || echo "❌ merge FAILED"
elif command -v python3 >/dev/null 2>&1; then
SETTINGS="$SETTINGS" S_CMD="$S_CMD" R_CMD="$R_CMD" python3 - <<'PY'
import json, os
f = os.environ["SETTINGS"]; scmd = os.environ["S_CMD"]; rcmd = os.environ["R_CMD"]
try: data = json.load(open(f))
except Exception: data = {}
hooks = data.setdefault("hooks", {})
def has(groups, basename):
return any(basename in (h.get("command") or "") for g in groups for h in g.get("hooks", []))
ss = hooks.setdefault("SessionStart", [])
if not has(ss, "grepai-session.mjs"):
(ss[0].setdefault("hooks", []).append({"type":"command","command":scmd}) if ss
else ss.append({"hooks":[{"type":"command","command":scmd}]}))
pt = hooks.setdefault("PreToolUse", [])
if not has(pt, "grepai-reminder.mjs"):
bg = next((g for g in pt if g.get("matcher") == "Bash"), None)
(bg.setdefault("hooks", []).append({"type":"command","command":rcmd}) if bg is not None
else pt.append({"matcher":"Bash","hooks":[{"type":"command","command":rcmd}]}))
json.dump(data, open(f,"w"), indent=2)
print("OK")
PY
echo "✅ merged $SETTINGS (python3)"
else
echo "❌ neither jq nor python3 — add the two entries from assets/INSTALL.md manually"
fi
```
> **STOP if ❌** — see `${CLAUDE_SKILL_DIR}/assets/INSTALL.md` for the manual entries.
#### Step 4: Report what was created
After install, tell the user EXACTLY what changed:
- Hook files copied: `<scope>/.claude/grepai/hooks/grepai-session.mjs`, `<scope>/.claude/grepai/hooks/grepai-reminder.mjs`
- `settings.json` entries merged: `SessionStart -> node $CLAUDE_PROJECT_DIR/.claude/grepai/hooks/grepai-session.mjs`, `PreToolUse(matcher "Bash") -> node $CLAUDE_PROJECT_DIR/.claude/grepai/hooks/grepai-reminder.mjs`
- Reminder: a NEW session picks them up (SessionStart fires on next `claude` start / `--resume`); no `/reload-plugins` needed.
### Phase 7: Verification
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/verify.sh" && echo "✅ verify" || echo "❌ verify FAILED"
```
---
## Mode: status
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/status.sh" && echo "✅ status" || echo "❌ status FAILED"
```
---
## Mode: start
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/start.sh" && echo "✅ start" || echo "❌ start FAILED"
```
---
## Mode: stop
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/stop.sh" && echo "✅ stop" || echo "❌ stop FAILED"
```
---
## Mode: reindex
Full index rebuild: stop watch → clean → rebuild → restart.
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/reindex.sh" && echo "✅ reindex" || echo "❌ reindex FAILED"
```
> ⏳ **Synchronous — Monitor: `tail -f .grepai/logs/grepai-watch.log`**
---
## Mode: optimize
Re-analyze project and regenerate config with backup.
### Step 1: Backup current config
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/optimize.sh" && echo "✅ optimize-backup" || echo "❌ optimize-backup FAILED"
```
> **STOP if ❌** — check if .grepai/config.yaml exists.
### Step 2: Regenerate config
**SPAWN** the `bc-grepai-configurator` agent using Task tool:
| Parameter | Value |
|-----------|-------|
| `subagent_type` | `brewcode:bc-grepai-configurator` |
| `prompt` | `Re-analyze project and regenerate .grepai/config.yaml. Compare with existing config, optimize boost patterns, update trace languages.` |
| `model` | `sonnet` (matches the agent's own pin — do NOT override to opus) |
> **Context:** the agent resolves its plugin root natively via `${CLAUDE_PLUGIN_ROOT}` (substituted in its .md at Task spawn).
> **WAIT** for agent to complete.
### Step 3: Reindex with new config
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/reindex.sh" && echo "✅ reindex" || echo "❌ reindex FAILED"
```
---
## Mode: uninstall
Removes grepai from THIS project: stops watch, deletes the two hook files, unwires
them from `.claude/settings.json` (jq, backup kept), drops `.claude/rules/grepai-first.md`.
Keeps the CLI, ollama, bge-m3 and the user-scope MCP entry.
**ASK** (AskUserQuestion): "Also delete `.grepai/` (config + index)? Rebuilding it later takes a full reindex."
Options: "Keep index" | "Delete everything"
**EXECUTE** using Bash tool (add `--purge-index` only for "Delete everything"):
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/uninstall.sh" && echo "✅ uninstall" || echo "❌ uninstall FAILED"
```
> Tell the user the `## Code Search` section stays in `CLAUDE.md` and must be removed by hand.
---
## Mode: upgrade
Update grepai CLI via Homebrew.
**EXECUTE** using Bash tool:
```bash
bash "${CLAUDE_SKILL_DIR}/scripts/upgrade.sh" && echo "✅ upgrade" || echo "❌ upgrade FAILED"
```
---
## Mode: prompt
Use AskUserQuestion to ask which operation to run:
```
header: "grepai"
question: "Which grepai operation do you want to run?"
options:
- label: "setup"
description: "Initialize and configure semantic search for this project"
- label: "status"
description: "Check health, index stats, doctor"
- label: "start / watch"
description: "Start watch mode (auto-index on file changes)"
- label: "optimize"
description: "Update and rebuild the search index"
```
For stop, reindex, upgrade — user types via Other. After answer, GOTO that mode section.
</instructions>
---
## Output Format
```markdown
# grepai [MODE]
## Detection
| Field | Value |
|-------|-------|
| Arguments | `$ARGUMENTS` |
| Mode | `[detected mode]` |
## Status
| Component | Status |
|-----------|--------|
| grepai CLI | [✅/❌] |
| ollama | [✅/❌] |
| bge-m3 model | [✅/❌] |
| MCP | [✅/❌] |
| Permissions | [✅/❌] allowedTools |
| .grepai/ | [✅/❌] |
| index | [size/indexing] |
| watch | [running/stopped] |
| rule | [✅/⚠️] |
## Actions Taken
- [action 1]
- [action 2]
## Next Steps
- [if any issues, list resolution steps]
```
-172
View File
@@ -1,172 +0,0 @@
# grepai hooks — install runbook
Self-contained hook assets. The `/brewcode:grepai` skill copies these into a
target hooks dir and wires `settings.json`. Both files are independent (no shared
lib, no plugin-root deps) and travel together:
| File | Event | Channel |
|------|-------|---------|
| `grepai-session.mjs` | SessionStart | `systemMessage` (status line) + `additionalContext` ("USE grepai_search FIRST" + compact-first directive: `compact:true` + `format:"toon"` by default, full content only after a compact pass with `limit<=3`) when index+ollama+mcp are all up; also auto-starts `grepai watch --background` when an index exists and ollama is running |
| `grepai-reminder.mjs` | PreToolUse `Bash` | `additionalContext` ("USE grepai_search FIRST" + compact-first directive: `compact:true` + `format:"toon"` by default, full content only after a compact pass with `limit<=3`) when a `grep/find/rg/...` command is run AND the project has `.grepai/index.gob`; self-throttled to once / 60s via `.grepai/.reminder-ts` |
> Scripts are pure ESM, Node built-ins only (`fs`, `path`, `child_process`), no
> plugin-root / npm deps. Each reads stdin, never throws, always exits 0. They
> read project state from `<cwd>/.grepai/` at runtime — copy location does not
> matter, so they can live anywhere under the project.
---
## Target install dir
`.claude/grepai/hooks/` under the chosen scope:
- PROJECT scope -> `<repo>/.claude/grepai/hooks/`
- GLOBAL scope -> `~/.claude/grepai/hooks/` (expanded)
---
## settings.json hook entries
`<hookdir>` = the hooks dir the 2 files were copied into — write it relocatable:
`$CLAUDE_PROJECT_DIR/.claude/grepai/hooks` for project scope, expanded
`~/.claude/grepai/hooks` (absolute) for global scope.
```json
{
"hooks": {
"SessionStart": [
{ "hooks": [ { "type": "command", "command": "node <hookdir>/grepai-session.mjs" } ] }
],
"PreToolUse": [
{ "matcher": "Bash", "hooks": [ { "type": "command", "command": "node <hookdir>/grepai-reminder.mjs" } ] }
]
}
}
```
> The exact `command` string form follows the project's existing convention. If
> the project already wires hooks as `{"type":"command","command":"node",
> "args":["..."]}`, mirror that shape instead. Both forms are accepted by CC.
Merge rule: APPEND into the existing `SessionStart` / `PreToolUse` arrays — never
overwrite. If a project hook already exists for `SessionStart` (or for
`PreToolUse` with `matcher` `Bash`), inject the grepai command INTO that group's
`hooks` array rather than adding a new sibling group. Dedupe by the grepai script
basename: if any existing entry references `grepai-session.mjs` /
`grepai-reminder.mjs`, skip (idempotent re-install).
---
## INSTALL (project or global)
Set `DST` and `SETTINGS` by scope, then run two steps: (1) copy files, (2) merge
settings (jq with python3 fallback). Project paths are writable with normal
tools; for GLOBAL (`~/.claude/*`) use the Bash tool only — that path is
harness-protected against the Write/Edit tools.
### Step 1 — copy the 2 hook files
`SRC` = this `assets/` dir (the skill passes its absolute path). EXECUTE with the
Bash tool:
```bash
# PROJECT: DST="$PWD/.claude/grepai/hooks"
# GLOBAL: DST="$HOME/.claude/grepai/hooks"
mkdir -p "$DST" && \
cp "$SRC/grepai-session.mjs" "$SRC/grepai-reminder.mjs" "$DST/" && \
echo "✅ copied to $DST" || echo "❌ copy FAILED"
```
### Step 2 — merge settings.json (jq, python3 fallback)
Idempotent append + dedupe by script basename, injecting into an existing
SessionStart / PreToolUse(Bash) group when present. EXECUTE with the Bash tool:
```bash
# PROJECT: SETTINGS="$PWD/.claude/settings.json"
# GLOBAL: SETTINGS="$HOME/.claude/settings.json"
mkdir -p "$(dirname "$SETTINGS")"
[ -f "$SETTINGS" ] || echo '{}' > "$SETTINGS"
# Path written INTO settings.json — relocatable for project scope
# PROJECT: HOOK_REF='$CLAUDE_PROJECT_DIR/.claude/grepai/hooks' (single quotes — keep the var literal)
# GLOBAL: HOOK_REF="$HOME/.claude/grepai/hooks"
S_CMD="node $HOOK_REF/grepai-session.mjs"
R_CMD="node $HOOK_REF/grepai-reminder.mjs"
if command -v jq >/dev/null 2>&1; then
TMP="$(mktemp)"
jq --arg scmd "$S_CMD" --arg rcmd "$R_CMD" '
.hooks = (.hooks // {})
# SessionStart: reuse a group if any, else create one; dedupe by grepai-session.mjs
| .hooks.SessionStart = (.hooks.SessionStart // [])
| (if (.hooks.SessionStart | map(.hooks // [] | map(.command // "") | any(test("grepai-session\\.mjs"))) | any)
then .
else (if (.hooks.SessionStart | length) > 0
then .hooks.SessionStart[0].hooks += [{"type":"command","command":$scmd}]
else .hooks.SessionStart += [{"hooks":[{"type":"command","command":$scmd}]}] end)
end)
# PreToolUse: reuse a Bash-matcher group if any, else create; dedupe by grepai-reminder.mjs
| .hooks.PreToolUse = (.hooks.PreToolUse // [])
| (if (.hooks.PreToolUse | map(.hooks // [] | map(.command // "") | any(test("grepai-reminder\\.mjs"))) | any)
then .
else (.hooks.PreToolUse | map((.matcher // "") == "Bash") | index(true)) as $i
| (if $i != null
then .hooks.PreToolUse[$i].hooks += [{"type":"command","command":$rcmd}]
else .hooks.PreToolUse += [{"matcher":"Bash","hooks":[{"type":"command","command":$rcmd}]}] end)
end)
' "$SETTINGS" > "$TMP" && mv "$TMP" "$SETTINGS" && \
jq empty "$SETTINGS" >/dev/null 2>&1 && echo "✅ merged $SETTINGS (jq)" || echo "❌ merge FAILED"
elif command -v python3 >/dev/null 2>&1; then
SETTINGS="$SETTINGS" S_CMD="$S_CMD" R_CMD="$R_CMD" python3 - <<'PY'
import json, os
f = os.environ["SETTINGS"]; scmd = os.environ["S_CMD"]; rcmd = os.environ["R_CMD"]
try:
data = json.load(open(f))
except Exception:
data = {}
hooks = data.setdefault("hooks", {})
def has(groups, basename):
for g in groups:
for h in g.get("hooks", []):
if basename in (h.get("command") or ""):
return True
return False
ss = hooks.setdefault("SessionStart", [])
if not has(ss, "grepai-session.mjs"):
if ss:
ss[0].setdefault("hooks", []).append({"type": "command", "command": scmd})
else:
ss.append({"hooks": [{"type": "command", "command": scmd}]})
pt = hooks.setdefault("PreToolUse", [])
if not has(pt, "grepai-reminder.mjs"):
bash_group = next((g for g in pt if g.get("matcher") == "Bash"), None)
if bash_group is not None:
bash_group.setdefault("hooks", []).append({"type": "command", "command": rcmd})
else:
pt.append({"matcher": "Bash", "hooks": [{"type": "command", "command": rcmd}]})
json.dump(data, open(f, "w"), indent=2)
print("OK")
PY
echo "✅ merged $SETTINGS (python3)"
else
echo "❌ neither jq nor python3 available — add the two entries above to $SETTINGS manually"
fi
```
> GLOBAL note: `~/.claude/*` blocks the Write/Edit/MultiEdit TOOLS in all
> permission modes, but Bash file writes (`cp`, `jq`, `python3`, `mv`) are
> allowed. Do the global install entirely through the Bash tool, never Edit/Write.
---
## After install
`/reload-plugins` is NOT needed — these are plain `settings.json` hooks, not
plugin hooks. A NEW session picks them up: SessionStart fires on the next
`claude` start / `--resume`; the PreToolUse:Bash reminder fires immediately in
the next session's tool calls.
@@ -1,100 +0,0 @@
#!/usr/bin/env node
/**
* grepai PreToolUse:Bash Hook (self-contained installed into a user project)
*
* Native Grep/Glob tools were removed on this CC build; code search runs via Bash
* (shadow grep->ugrep / find->bfs / rg). Reminds Claude to prefer grepai_search
* when a grep/find/rg search command is run through Bash.
*
* SELF-CONTAINED: readStdin / output / log are inlined below. No plugin-root
* paths, no shared lib import. Pure ESM, Node built-ins only. Exits 0 always.
*/
import { existsSync, statSync, writeFileSync } from 'fs';
import { join } from 'path';
// --- inlined helpers (from brewcode hooks lib/utils.mjs) -------------------
async function readStdin() {
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
const input = Buffer.concat(chunks).toString('utf8');
try {
return JSON.parse(input);
} catch (e) {
throw new Error(`Invalid stdin JSON: ${e.message}. Input: ${input.substring(0, 100)}`);
}
}
function output(response) {
try {
console.log(JSON.stringify(response));
} catch (e) {
console.log(JSON.stringify({ error: `Serialization failed: ${e.message}` }));
}
}
// Minimal log: stderr only for warn/error, never throws, no file deps.
function log(level, prefix, message) {
if (level === 'error' || level === 'warn') {
try { console.error(`${prefix} ${message}`); } catch {}
}
}
// ---------------------------------------------------------------------------
const SEARCH_RE = /(?:^|[|;&(]|&&|\|\|)\s*(?:command\s+)?(grep|egrep|fgrep|ugrep|rg|ag|ack|find|bfs)\b/;
async function main() {
let cwd = null;
try {
cwd = process.cwd();
const input = await readStdin();
cwd = input.cwd || cwd;
const command = input.tool_input && input.tool_input.command;
if (!command) {
output({});
return;
}
if (!SEARCH_RE.test(command)) {
output({});
return;
}
const grepaiDir = join(cwd, '.grepai');
const indexFile = join(grepaiDir, 'index.gob');
if (existsSync(grepaiDir) && existsSync(indexFile)) {
// Throttle: remind at most once per 60 seconds
const tsFile = join(grepaiDir, '.reminder-ts');
try {
if (existsSync(tsFile)) {
const age = Date.now() - statSync(tsFile).mtimeMs;
if (age < 60_000) {
output({});
return;
}
}
writeFileSync(tsFile, '');
} catch (e) {
log('warn', '[grepai-reminder]', `Throttle write failed: ${e.message}`);
}
output({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
additionalContext:
'grepai: USE grepai_search FIRST for code exploration — compact:true + format:"toon", ' +
'then Read the top hits. Full content (compact:false) only with limit<=3 after a compact pass.'
}
});
} else {
output({});
}
} catch (err) {
log('error', '[grepai-reminder]', `Error: ${err.message}`);
output({});
}
}
main();
@@ -1,240 +0,0 @@
#!/usr/bin/env node
/**
* grepai SessionStart Hook (self-contained installed into a user project)
*
* Auto-starts grepai watch when entering a project with .grepai/ configured.
* Provides status information via systemMessage.
*
* NEVER blocks session start - all errors are informational only.
* Platform: macOS/Linux only. Windows lacks pgrep - auto-start disabled.
*
* SELF-CONTAINED: readStdin / output / log are inlined below. No plugin-root
* paths, no shared lib import. Pure ESM, Node built-ins only. Exits 0 always.
*/
import { execSync, spawn } from 'child_process';
import { existsSync, mkdirSync, statSync, readFileSync } from 'fs';
import { join } from 'path';
// --- inlined helpers (from brewcode hooks lib/utils.mjs) -------------------
async function readStdin() {
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
const input = Buffer.concat(chunks).toString('utf8');
try {
return JSON.parse(input);
} catch (e) {
throw new Error(`Invalid stdin JSON: ${e.message}. Input: ${input.substring(0, 100)}`);
}
}
function output(response) {
try {
console.log(JSON.stringify(response));
} catch (e) {
console.log(JSON.stringify({ error: `Serialization failed: ${e.message}` }));
}
}
// Minimal log: stderr only for warn/error, never throws, no file deps.
function log(level, prefix, message) {
if (level === 'error' || level === 'warn') {
try { console.error(`${prefix} ${message}`); } catch {}
}
}
// ---------------------------------------------------------------------------
async function main() {
let cwd = null;
let session_id = null;
try {
cwd = process.cwd();
const input = await readStdin();
session_id = input.session_id;
cwd = input.cwd || cwd;
const result = await checkGrepai(cwd, session_id);
output(result);
} catch (err) {
log('error', '[grepai]', `Hook error: ${err.message}`);
output({});
}
}
async function checkGrepai(cwd, session_id = null) {
const grepaiDir = join(cwd, '.grepai'); // nosemgrep: path-join-resolve-traversal
const indexPath = join(grepaiDir, 'index.gob'); // nosemgrep: path-join-resolve-traversal
const logsDir = join(grepaiDir, 'logs'); // nosemgrep: path-join-resolve-traversal
// No .grepai directory - skip silently (grepai not configured for this project)
if (!existsSync(grepaiDir)) {
return { systemMessage: 'grepai: not configured' };
}
const status = [];
let indexStatus = null;
let shouldAutoStart = false;
// Check ollama
const ollamaRunning = checkOllama();
if (!ollamaRunning) {
status.push('ollama: stopped');
}
// Check index with size-based file estimation
const hasIndex = existsSync(indexPath);
if (hasIndex) {
try {
const stats = statSync(indexPath);
const sizeKB = Math.round(stats.size / 1024);
// Estimate: ~10KB per file on average
// <20KB = likely <2 files (nearly empty, warn)
// 20-100KB = small project (display KB)
// >100KB = normal project (display MB)
if (stats.size < 20000) {
indexStatus = `⚠️ ${sizeKB}KB`;
} else if (stats.size < 100000) {
indexStatus = `${sizeKB}KB`;
} else {
const sizeMB = (stats.size / (1024 * 1024)).toFixed(1);
indexStatus = `${sizeMB}MB`;
}
} catch (err) {
indexStatus = 'error';
log('warn', '[grepai]', `index stat failed: ${err.message}`);
}
} else {
status.push('index: missing');
}
// Check watch process
const watchRunning = checkWatchRunning(cwd);
if (!watchRunning && hasIndex && ollamaRunning && process.platform !== 'win32') {
shouldAutoStart = true;
}
// Check MCP server
const mcpRunning = checkMcpServer(cwd);
if (!mcpRunning) {
status.push('mcp-serve: stopped');
}
// Auto-start watch if conditions met
if (shouldAutoStart) {
try {
if (!existsSync(logsDir)) {
mkdirSync(logsDir, { recursive: true });
}
const child = spawn('grepai', ['watch', '--background', '--log-dir', logsDir], {
cwd: cwd,
detached: true,
stdio: 'ignore'
});
child.on('error', (err) => {
log('warn', '[grepai]', `Watch spawn error: ${err.message}`);
});
child.unref();
status.push('watch: starting');
} catch (err) {
log('warn', '[grepai]', `Watch auto-start failed: ${err.message}`);
status.push('watch: start failed');
}
} else if (!watchRunning) {
status.push('watch: stopped');
}
// Build status message
let statusMessage;
if (status.length === 0) {
statusMessage = indexStatus ? `ready | index: ${indexStatus}` : 'ready';
} else {
statusMessage = indexStatus
? `${status.join(', ')} | index: ${indexStatus}`
: status.join(', ');
}
const result = { systemMessage: `grepai: ${statusMessage}` };
// Reminder for Claude: only when grepai_search is actually usable (index + ollama + mcp)
if (hasIndex && ollamaRunning && mcpRunning) {
result.hookSpecificOutput = {
hookEventName: 'SessionStart',
additionalContext:
'grepai: USE grepai_search FIRST for code exploration. ALWAYS compact:true + format:"toon" ' +
'(returns path+lines only) -> then Read the top 1-3 hits. compact:false ONLY after a compact ' +
'pass, with limit<=3 — full content of many chunks overflows the context.'
};
}
return result;
}
function checkOllama() {
try {
execSync('curl -s --max-time 1 localhost:11434/api/tags', {
timeout: 1500,
stdio: 'ignore'
});
return true;
} catch {
return false;
}
}
function checkWatchRunning(cwd) {
if (process.platform === 'win32') return false;
// Check for grepai PID file first (project-specific)
const pidFile = join(cwd, '.grepai', 'watch.pid'); // nosemgrep: path-join-resolve-traversal
if (existsSync(pidFile)) {
try {
const pid = readFileSync(pidFile, 'utf8').trim();
if (pid && /^\d+$/.test(pid)) {
process.kill(parseInt(pid), 0);
return true;
}
} catch {
// Process not running, PID file is stale
}
}
// Fallback: system-wide check (may match other projects)
try {
const result = execSync('pgrep -f "grepai watch"', {
encoding: 'utf8',
timeout: 1000,
stdio: ['ignore', 'pipe', 'ignore']
});
return result.trim().length > 0;
} catch {
return false;
}
}
function checkMcpServer(cwd) {
if (process.platform === 'win32') return false;
const pidFile = join(cwd, '.grepai', 'mcp-serve.pid'); // nosemgrep: path-join-resolve-traversal
if (existsSync(pidFile)) {
try {
const pid = readFileSync(pidFile, 'utf8').trim();
if (pid && /^\d+$/.test(pid)) {
process.kill(parseInt(pid), 0);
return true;
}
} catch {}
}
try {
const result = execSync('pgrep -f "grepai mcp-serve"', {
encoding: 'utf8',
timeout: 1000,
stdio: ['ignore', 'pipe', 'ignore']
});
return result.trim().length > 0;
} catch {
return false;
}
}
main();
@@ -1,96 +0,0 @@
# grepai config example
# Copy to .grepai/config.yaml and adapt to your project
version: 1
embedder:
provider: ollama
model: bge-m3 # Best multilingual model, 1.2GB
endpoint: http://localhost:11434
dimensions: 1024 # bge-m3 native dimension
# CRITICAL: Ollama does NOT support parallel embeddings!
# See: https://github.com/ollama/ollama/issues/12591
# Always keep parallelism: 1 for Ollama provider
parallelism: 1
store:
backend: gob # Fast local storage
chunking:
size: 512 # Chars per chunk (smaller = more precise)
overlap: 50 # Overlap between chunks
watch:
debounce_ms: 500 # Wait before re-indexing on file change
search:
boost:
enabled: true
# Penalties: reduce score for test/mock/generated files
penalties:
- pattern: /tests/
factor: 0.5
- pattern: /test/
factor: 0.5
- pattern: _test.
factor: 0.5
- pattern: .test.
factor: 0.5
- pattern: .spec.
factor: 0.5
- pattern: /mocks/
factor: 0.4
- pattern: /fixtures/
factor: 0.4
- pattern: /generated/
factor: 0.4
- pattern: .gen.
factor: 0.4
- pattern: .md
factor: 0.6
- pattern: /docs/
factor: 0.6
# Bonuses: boost score for main source directories
bonuses:
- pattern: /src/
factor: 1.1
- pattern: /lib/
factor: 1.1
- pattern: /app/
factor: 1.1
hybrid:
enabled: false # Hybrid search (semantic + keyword)
k: 60
trace:
mode: fast # Call graph tracing mode
enabled_languages: # Languages for trace analysis
- .go
- .js
- .ts
- .tsx
- .py
- .java
- .rs
exclude_patterns: # Exclude test files from trace
- '*_test.go'
- '*.spec.ts'
- '*.test.ts'
- __tests__/*
update:
check_on_startup: false # Don't check for grepai updates
# Directories to ignore (never index)
ignore:
- .git
- .grepai
- node_modules
- vendor
- dist
- build
- target
- __pycache__
- .venv
- .idea
- .vscode
@@ -1,73 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai Create Rule + CLAUDE.md entry
echo "=== Create Rule ==="
RULE_FILE=".claude/rules/grepai-first.md"
CLAUDE_MD="CLAUDE.md"
GREPAI_MARKER="grepai_search"
mkdir -p .claude/rules
append_claude_md_entry() {
{
echo ""
echo "## Code Search"
echo ""
echo "> **CRITICAL:** Use \`grepai_search\` FIRST for code exploration."
echo "> **ALWAYS \`compact:true\` + \`format:\"toon\"\`** → path+lines only, then \`Read\` the top hits."
echo "> Full content (\`compact:false\`) only as an exception, after a compact pass, with \`limit<=3\` — it overflows the context."
} >> "$1"
}
if [ ! -f "$CLAUDE_MD" ]; then
echo "# CLAUDE.md" > "$CLAUDE_MD"
append_claude_md_entry "$CLAUDE_MD"
echo "✅ CLAUDE.md created with grepai entry"
elif ! grep -q "$GREPAI_MARKER" "$CLAUDE_MD" 2>/dev/null; then
append_claude_md_entry "$CLAUDE_MD"
echo "✅ CLAUDE.md updated with grepai entry"
else
echo "⏭️ CLAUDE.md already has grepai entry"
fi
# Self-location: derive plugin root from script path
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Path: scripts/create-rule.sh -> skills/grepai/scripts -> skills/grepai -> skills -> PLUGIN_ROOT
PLUGIN_ROOT="$(dirname "$(dirname "$(dirname "$SCRIPT_DIR")")")"
PLUGIN_TEMPLATES="$PLUGIN_ROOT/templates"
if [ -f "$PLUGIN_TEMPLATES/rules/grepai-first.md.template" ]; then
cp "$PLUGIN_TEMPLATES/rules/grepai-first.md.template" "$RULE_FILE"
echo "✅ Rule updated: $RULE_FILE"
else
echo "⚠️ Template not found, creating default rule"
cat > "$RULE_FILE" << 'RULE'
---
paths:
- "**/*"
description: grepai-first - semantic search FIRST for code exploration
---
# grepai-first
Use grepai as PRIMARY search tool for semantic code search.
## Compact-first (HARD)
| | Rule |
|---|---|
| Default call | `compact:true, format:"toon", limit:10` → path+lines only → `Read` top 1-3 hits |
| `compact:false` ONLY if | compact pass already ran AND `limit<=3` AND one narrow query |
| NEVER | `compact:false` first, or `limit>3`, or on a broad query — full chunks overflow the context |
| Task | Tool |
|------|------|
| Search by intent | `grepai_search` |
| Exact text / path pattern | Bash (`grep`/`rg`, `find`) |
**Decision:** "Need exact text/pattern?" → YES: Bash grep/find, NO: grepai (compact)
RULE
echo "✅ Rule updated (default): $RULE_FILE"
fi
@@ -1,45 +0,0 @@
#!/bin/bash
set -euo pipefail
# Detect grepai mode from arguments
# Usage: detect-mode.sh "$ARGUMENTS"
# Output: ARGS and MODE for debugging
ARGS="${1:-}"
ARGS_LOWER=$(echo "$ARGS" | tr '[:upper:]' '[:lower:]')
# Debug output
echo "ARGS: [$ARGS]"
# Determine mode
MODE=""
# Check keywords (order matters - first match wins)
if [[ "$ARGS_LOWER" =~ (uninstall|remove|удали|снеси) ]]; then
MODE="uninstall"
elif [[ "$ARGS_LOWER" =~ (upgrade|апгрейд) ]]; then
MODE="upgrade"
elif [[ "$ARGS_LOWER" =~ (optimize|update|улучши|обнови) ]]; then
MODE="optimize"
elif [[ "$ARGS_LOWER" =~ (stop|halt|kill) ]]; then
MODE="stop"
elif [[ "$ARGS_LOWER" =~ (start|watch) ]]; then
MODE="start"
elif [[ "$ARGS_LOWER" =~ (status|doctor|check|health) ]]; then
MODE="status"
elif [[ "$ARGS_LOWER" =~ (setup|configure|init) ]]; then
MODE="setup"
elif [[ "$ARGS_LOWER" =~ (reindex|rebuild|refresh) ]]; then
MODE="reindex"
elif [[ -z "$ARGS" ]]; then
# No arguments - check filesystem
if [[ -d ".grepai" ]]; then
MODE="start"
else
MODE="setup"
fi
else
# Has args but no keyword match
MODE="prompt"
fi
echo "MODE: $MODE"
@@ -1,36 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai Infrastructure Check
echo "=== Infrastructure Check ==="
ERRORS=0
# grepai CLI
if command -v grepai >/dev/null 2>&1; then
echo "✅ grepai: $(grepai version 2>/dev/null || echo 'installed')"
else
echo "❌ grepai: NOT FOUND"
echo " Install: brew install yoanbernabeu/tap/grepai"
ERRORS=$((ERRORS + 1))
fi
# Ollama
if curl -s --connect-timeout 3 --max-time 5 localhost:11434/api/tags >/dev/null 2>&1; then
echo "✅ ollama: running"
else
echo "❌ ollama: not running"
echo " Install: brew install ollama && brew services start ollama"
ERRORS=$((ERRORS + 1))
fi
# bge-m3 model
if ollama list 2>/dev/null | grep -q bge-m3; then
echo "✅ bge-m3: installed"
else
echo "❌ bge-m3: not installed"
echo " Install: ollama pull bge-m3"
ERRORS=$((ERRORS + 1))
fi
exit $ERRORS
@@ -1,52 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai Initialize Index
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=lib/index-common.sh
. "$SCRIPT_DIR/lib/index-common.sh"
echo "=== Initialize Index ==="
if [ ! -d .grepai ]; then
echo "❌ .grepai/ not found. Run setup first: /brewcode:grepai setup"
exit 1
fi
mkdir -p .grepai/logs
echo ""
echo "--- File Count ---"
estimate_timeout "$(count_indexable_files)"
echo ""
# Index already present -> just make sure watch is up
if [ -f .grepai/index.gob ]; then
echo "⏭️ index.gob already exists ($(du -h .grepai/index.gob | cut -f1))"
echo ""
echo "--- Starting Watch ---"
if pgrep -f "grepai watch" >/dev/null; then
echo "✅ grepai watch: already running (PID: $(pgrep -f 'grepai watch' | tr '\n' ' '))"
else
start_watch_bg
fi
echo ""
echo "=== Init Complete ==="
report_index_state
exit 0
fi
echo "--- Building Index ---"
: > "$WATCH_LOG"
echo ""
echo " Log: $WATCH_LOG"
echo " Monitor: tail -f $WATCH_LOG"
echo ""
start_watch_bg
wait_for_initial_scan "$TIMEOUT"
echo ""
echo "=== Init Complete ==="
report_index_state
echo "✅ Duration: ${ELAPSED}s"
-196
View File
@@ -1,196 +0,0 @@
#!/bin/bash
set -euo pipefail
# Install grepai prerequisites via Homebrew
echo "=== grepai Prerequisites Install ==="
INSTALLED=()
FAILED=()
# 1. Homebrew
echo ""
echo "--- Homebrew ---"
if command -v brew &>/dev/null; then
echo "✅ brew: $(brew --version | head -1)"
else
echo "⚠️ brew: not found, installing..."
if /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"; then # nosemgrep: curl-pipe-bash
eval "$(/opt/homebrew/bin/brew shellenv)" 2>/dev/null || eval "$(/usr/local/bin/brew shellenv)" 2>/dev/null || true
echo "✅ brew: installed"
INSTALLED+=("brew")
else
echo "❌ brew: install failed"
FAILED+=("brew")
fi
fi
# Exit early if no brew
if ! command -v brew &>/dev/null; then
echo ""
echo "=== Install Failed ==="
echo "❌ Homebrew is required for all other dependencies"
echo "Manual install: https://brew.sh"
exit 1
fi
# 2. timeout (from coreutils)
echo ""
echo "--- timeout ---"
if command -v timeout &>/dev/null; then
echo "✅ timeout: $(timeout --version 2>&1 | head -1)"
else
echo "⚠️ timeout: not found, installing coreutils..."
if brew install coreutils &>/dev/null; then
echo "✅ coreutils: installed"
INSTALLED+=("coreutils")
# Create symlink for timeout command
BREW_BIN=$(brew --prefix)/bin
if [ -w "$BREW_BIN" ]; then
ln -sf "$(brew --prefix)/opt/coreutils/libexec/gnubin/timeout" "$BREW_BIN/timeout"
echo "✅ timeout: symlink created"
fi
else
echo "❌ coreutils: install failed"
FAILED+=("coreutils")
fi
fi
# 3. jq (JSON processor)
echo ""
echo "--- jq ---"
if command -v jq &>/dev/null; then
echo "✅ jq: $(jq --version)"
else
echo "⚠️ jq: not found, installing..."
if brew install jq &>/dev/null; then
echo "✅ jq: installed"
INSTALLED+=("jq")
else
echo "❌ jq: install failed"
FAILED+=("jq")
fi
fi
# 4. ollama (embedding server)
echo ""
echo "--- ollama ---"
if command -v ollama &>/dev/null; then
echo "✅ ollama: $(ollama --version 2>&1 | head -1)"
# Check if running
if curl -s --connect-timeout 3 --max-time 5 localhost:11434/api/tags &>/dev/null; then
echo "✅ ollama: running"
else
echo "⚠️ ollama: installed but not running"
echo " Starting ollama service..."
if ! brew services start ollama &>/dev/null; then
nohup ollama serve &>/dev/null &
fi
sleep 2
if curl -s --connect-timeout 3 --max-time 5 localhost:11434/api/tags &>/dev/null; then
echo "✅ ollama: started"
else
echo "⚠️ ollama: start manually with 'ollama serve'"
fi
fi
else
echo "⚠️ ollama: not found, installing..."
if brew install ollama &>/dev/null; then
echo "✅ ollama: installed"
INSTALLED+=("ollama")
echo " Starting ollama service..."
brew services start ollama &>/dev/null || true
sleep 2
else
echo "❌ ollama: install failed"
FAILED+=("ollama")
fi
fi
# 5. bge-m3 model (for ollama)
echo ""
echo "--- bge-m3 model ---"
if command -v ollama &>/dev/null && curl -s --connect-timeout 3 --max-time 5 localhost:11434/api/tags &>/dev/null; then
if ollama list 2>/dev/null | grep -q bge-m3; then
echo "✅ bge-m3: installed"
else
echo "⚠️ bge-m3: not found, pulling..."
if ollama pull bge-m3; then
echo "✅ bge-m3: installed"
INSTALLED+=("bge-m3")
else
echo "❌ bge-m3: pull failed"
FAILED+=("bge-m3")
fi
fi
else
echo "⏭️ bge-m3: skipped (ollama not available)"
fi
# 6. grepai CLI
echo ""
echo "--- grepai ---"
if command -v grepai &>/dev/null; then
echo "✅ grepai: $(grepai version 2>&1)"
else
echo "⚠️ grepai: not found, installing..."
if brew install yoanbernabeu/tap/grepai &>/dev/null; then
echo "✅ grepai: installed"
INSTALLED+=("grepai")
else
echo "❌ grepai: install failed"
FAILED+=("grepai")
fi
fi
# Summary
echo ""
echo "=== Install Summary ==="
echo ""
echo "| Component | Status |"
echo "|-----------|--------|"
# Check each component
check_status() {
local name=$1
local cmd=$2
if command -v "$cmd" &>/dev/null; then
echo "| $name | ✅ |"
else
echo "| $name | ❌ |"
fi
}
check_status "brew" "brew"
check_status "timeout" "timeout"
check_status "jq" "jq"
check_status "ollama" "ollama"
check_status "grepai" "grepai"
# bge-m3 special check
if command -v ollama &>/dev/null && ollama list 2>/dev/null | grep -q bge-m3; then
echo "| bge-m3 | ✅ |"
else
echo "| bge-m3 | ❌ |"
fi
# ollama running check
if curl -s --connect-timeout 3 --max-time 5 localhost:11434/api/tags &>/dev/null; then
echo "| ollama running | ✅ |"
else
echo "| ollama running | ❌ |"
fi
echo ""
if [ ${#INSTALLED[@]} -gt 0 ]; then
echo "Installed: ${INSTALLED[*]}"
fi
if [ ${#FAILED[@]} -gt 0 ]; then
echo "Failed: ${FAILED[*]}"
exit 1
fi
echo ""
echo "✅ All prerequisites installed"
exit 0
@@ -1,98 +0,0 @@
#!/bin/bash
# Shared index-build helpers for init-index.sh and reindex.sh.
# Source it: . "$(dirname "$0")/lib/index-common.sh"
WATCH_LOG=".grepai/logs/grepai-watch.log"
INDEX_EXTS=(java kt kts js ts tsx jsx go py rs sh md yaml yml json)
INDEX_PRUNE=(node_modules .git target build dist .grepai)
# Echoes the estimated number of indexable files.
count_indexable_files() {
local find_args=() ext prune first=1
for ext in "${INDEX_EXTS[@]}"; do
if [ "$first" -eq 1 ]; then
find_args+=(-name "*.$ext"); first=0
else
find_args+=(-o -name "*.$ext")
fi
done
local prune_args=()
for prune in "${INDEX_PRUNE[@]}"; do
prune_args+=(-not -path "*/$prune/*")
done
find . -type f \( "${find_args[@]}" \) "${prune_args[@]}" 2>/dev/null | wc -l | tr -d ' '
}
# Sets TIMEOUT + EST_TIME from a file count, and prints both.
estimate_timeout() {
local count="$1"
if [ "$count" -lt 100 ]; then
EST_TIME="<1 min"; TIMEOUT=120
elif [ "$count" -lt 500 ]; then
EST_TIME="1-3 min"; TIMEOUT=300
elif [ "$count" -lt 1000 ]; then
EST_TIME="3-7 min"; TIMEOUT=600
elif [ "$count" -lt 5000 ]; then
EST_TIME="10-30 min"; TIMEOUT=1800
else
EST_TIME="30+ min"; TIMEOUT=3600
fi
echo "Files to index: ~$count"
echo "Estimated time: $EST_TIME"
}
# Starts `grepai watch` detached; exits 1 with the log tail if it does not come up.
start_watch_bg() {
mkdir -p .grepai/logs
grepai watch --background --log-dir .grepai/logs 2>/dev/null || true
sleep 1
if ! pgrep -f "grepai watch" >/dev/null; then
echo "❌ Failed to start grepai watch"
cat "$WATCH_LOG" 2>/dev/null || true
exit 1
fi
echo "✅ Watch started (PID: $(pgrep -f 'grepai watch' | tr '\n' ' '))"
}
# Polls the watch log until "Initial scan complete"; sets ELAPSED. Exits 1 on death/timeout.
wait_for_initial_scan() {
local timeout="$1"
ELAPSED=0
echo "⏳ Waiting for indexing to complete..."
while [ "$ELAPSED" -lt "$timeout" ]; do
if grep -q "Initial scan complete" "$WATCH_LOG" 2>/dev/null; then
echo ""
echo "✅ Initial scan complete"
echo " $(grep 'Initial scan complete' "$WATCH_LOG" | tail -1)"
return 0
fi
if ! pgrep -f "grepai watch" >/dev/null; then
echo ""
echo "❌ Watch process died unexpectedly"
cat "$WATCH_LOG" 2>/dev/null || true
exit 1
fi
if [ $((ELAPSED % 5)) -eq 0 ] && [ "$ELAPSED" -gt 0 ]; then
local idx sym last
idx=$(du -h .grepai/index.gob 2>/dev/null | cut -f1 || echo "0")
sym=$(du -h .grepai/symbols.gob 2>/dev/null | cut -f1 || echo "0")
last=$(grep -E "Indexing|Processing" "$WATCH_LOG" 2>/dev/null | tail -1 | head -c 80 || true)
echo "${ELAPSED}s | index: ${idx:-0} | symbols: ${sym:-0}"
[ -n "$last" ] && echo " $last"
fi
sleep 1
ELAPSED=$((ELAPSED + 1))
done
echo ""
echo "❌ Timeout after ${timeout}s"
grepai watch --stop 2>/dev/null || true
exit 1
}
# Final index/watch summary.
report_index_state() {
test -f .grepai/index.gob && echo "✅ index.gob: $(du -h .grepai/index.gob | cut -f1)" || echo "❌ index.gob missing"
test -f .grepai/symbols.gob && echo "✅ symbols.gob: $(du -h .grepai/symbols.gob | cut -f1)" || echo "⚠️ symbols.gob missing"
pgrep -f "grepai watch" >/dev/null && echo "✅ watch: running (PID: $(pgrep -f 'grepai watch' | tr '\n' ' '))" || echo "⚠️ watch: not running"
}
-173
View File
@@ -1,173 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai MCP Configuration Check
# Ensures grepai MCP is registered AND alwaysLoad=true (CC 2.1.115+)
# Falls back to JSON patching if --always-load flag unsupported.
echo "=== MCP Check ==="
CLAUDE_JSON="$HOME/.claude.json"
TMP_FILE=""
TMP_FILE2=""
# Single trap for all temp files (variables can be empty/unset - rm -f is safe)
trap 'rm -f "${TMP_FILE:-}" "${TMP_FILE2:-}"' EXIT
# Helper: check if alwaysLoad already true for grepai
already_always_load() {
command -v jq &>/dev/null || return 1
[ -f "$CLAUDE_JSON" ] || return 1
jq -e '.mcpServers.grepai.alwaysLoad == true' "$CLAUDE_JSON" >/dev/null 2>&1
}
# Helper: detect --always-load flag support
supports_always_load() {
claude mcp add --help 2>&1 | grep -q -- '--always-load'
}
# Helper: backup ~/.claude.json once per invocation if we are about to mutate
backup_claude_json() {
[ -f "$CLAUDE_JSON" ] || return 0
local bak
bak="$CLAUDE_JSON.bak.$(date +%s)"
cp "$CLAUDE_JSON" "$bak" && echo " Backup: $bak"
}
# Phase 1: Check/Add MCP Server
echo ""
echo "--- MCP Server ---"
GREPAI_PRESENT=0
if [ -f "$CLAUDE_JSON" ] && grep -q '"grepai"' "$CLAUDE_JSON" 2>/dev/null; then
GREPAI_PRESENT=1
echo "✅ MCP grepai: already configured"
else
echo "⚠️ MCP grepai: not configured"
echo " Adding via claude CLI..."
if supports_always_load; then
if claude mcp add grepai --always-load --transport stdio --scope user -- grepai mcp-serve; then
echo "✅ MCP grepai: added (alwaysLoad via CLI)"
GREPAI_PRESENT=1
else
echo "❌ MCP grepai: failed to add"
exit 1
fi
else
if claude mcp add --scope user grepai -- grepai mcp-serve; then
echo "✅ MCP grepai: added (legacy CLI, will patch alwaysLoad)"
GREPAI_PRESENT=1
else
echo "❌ MCP grepai: failed to add"
exit 1
fi
fi
fi
# Phase 1b: Ensure alwaysLoad=true for grepai
echo ""
echo "--- alwaysLoad Flag ---"
if [ "$GREPAI_PRESENT" -eq 1 ]; then
if already_always_load; then
echo "✅ alwaysLoad: already true (no changes)"
else
# Try CLI re-registration with --always-load first (idempotent in newer CC)
PATCHED=0
if supports_always_load; then
# `claude mcp add` may refuse to overwrite; try and if it fails, fall through to JSON patch
if claude mcp add grepai --always-load --transport stdio --scope user -- grepai mcp-serve 2>/dev/null; then
if already_always_load; then
echo "✅ alwaysLoad: set via CLI re-register"
PATCHED=1
fi
fi
fi
if [ "$PATCHED" -eq 0 ]; then
# Fallback: JSON patch
if [ ! -f "$CLAUDE_JSON" ]; then
echo "$CLAUDE_JSON does not exist; cannot patch"
exit 1
fi
if ! command -v jq &>/dev/null; then
echo "❌ jq required for fallback patch"
exit 1
fi
backup_claude_json
TMP_FILE=$(mktemp)
jq '.mcpServers.grepai.alwaysLoad = true' "$CLAUDE_JSON" > "$TMP_FILE" && mv "$TMP_FILE" "$CLAUDE_JSON"
# Validate JSON
jq empty "$CLAUDE_JSON" >/dev/null 2>&1 || { echo "❌ Invalid JSON after patch"; exit 1; }
if already_always_load; then
echo "✅ alwaysLoad: set via JSON patch"
else
echo "❌ alwaysLoad: patch did not take effect"
exit 1
fi
fi
fi
else
echo "⏭️ alwaysLoad: skipped (grepai not present)"
fi
# Phase 2: Check/Add allowedTools (prevents [destructive] permission prompts)
echo ""
echo "--- Allowed Tools ---"
SETTINGS_FILE="$HOME/.claude/settings.json"
# Create settings.json if not exists
if [ ! -f "$SETTINGS_FILE" ]; then
mkdir -p "$(dirname "$SETTINGS_FILE")"
echo '{}' > "$SETTINGS_FILE"
echo " Created $SETTINGS_FILE"
fi
# Check if mcp__grepai__ already allowed
if grep -q 'mcp__grepai__' "$SETTINGS_FILE" 2>/dev/null; then
echo "✅ allowedTools: mcp__grepai__* already configured"
else
echo "⚠️ allowedTools: mcp__grepai__* not configured"
echo " Adding to $SETTINGS_FILE..."
# Use jq if available, otherwise use python
if command -v jq &>/dev/null; then
# jq approach
TMP_FILE2=$(mktemp)
jq '.allowedTools = ((.allowedTools // []) + ["mcp__grepai__*"] | unique)' "$SETTINGS_FILE" > "$TMP_FILE2" && mv "$TMP_FILE2" "$SETTINGS_FILE"
jq . "$SETTINGS_FILE" >/dev/null 2>&1 || { echo "❌ Invalid JSON"; exit 1; }
elif command -v python3 &>/dev/null; then
# python approach
SETTINGS_FILE="$SETTINGS_FILE" python3 -c "
import json, os
settings_file = os.environ['SETTINGS_FILE']
with open(settings_file, 'r') as f:
data = json.load(f)
allowed = data.get('allowedTools', [])
if 'mcp__grepai__*' not in allowed:
allowed.append('mcp__grepai__*')
data['allowedTools'] = allowed
with open(settings_file, 'w') as f:
json.dump(data, f, indent=2)
"
python3 -c "import json,sys; json.load(open(sys.argv[1]))" "$SETTINGS_FILE" 2>/dev/null || { echo "❌ Invalid JSON in $SETTINGS_FILE"; exit 1; }
else
echo "❌ Neither jq nor python3 available"
echo " Manually add to $SETTINGS_FILE:"
echo ' {"allowedTools": ["mcp__grepai__*"]}'
exit 1
fi
if grep -q 'mcp__grepai__' "$SETTINGS_FILE" 2>/dev/null; then
echo "✅ allowedTools: mcp__grepai__* added"
else
echo "❌ Failed to add allowedTools"
exit 1
fi
fi
echo ""
echo "=== MCP Check Complete ==="
echo "✅ MCP server: configured"
echo "✅ alwaysLoad: enabled (no ToolSearch preflight needed)"
echo "✅ Permissions: auto-allowed (no prompts)"
echo ""
echo " Restart Claude Code to apply MCP changes"
exit 0
@@ -1,33 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai Config Optimization (backup + reindex)
echo "=== Config Optimization ==="
# Check .grepai exists
if [ ! -d .grepai ]; then
echo "❌ .grepai/ not found. Run setup first: /grepai setup"
exit 1
fi
if [ ! -f .grepai/config.yaml ]; then
echo "❌ config.yaml not found. Run setup first: /grepai setup"
exit 1
fi
# Create backup
BACKUP_DIR=".grepai/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
mkdir -p "$BACKUP_DIR"
cp .grepai/config.yaml "$BACKUP_DIR/config_$TIMESTAMP.yaml"
echo "✅ Backup: $BACKUP_DIR/config_$TIMESTAMP.yaml"
# Remove stale last_index_time to prepare for fresh config
if grep -q "last_index_time:" .grepai/config.yaml 2>/dev/null; then
grep -v 'last_index_time:' .grepai/config.yaml > .grepai/config.yaml.tmp && mv .grepai/config.yaml.tmp .grepai/config.yaml
echo "✅ Removed stale last_index_time"
fi
echo ""
echo "Config backed up. Agent will now analyze and regenerate config."
echo "After config update, run: /grepai reindex"
-62
View File
@@ -1,62 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai Full Reindex: stop, clean, rebuild (sync), leave watch running
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=lib/index-common.sh
. "$SCRIPT_DIR/lib/index-common.sh"
echo "=== Reindex: Stop Watch ==="
grepai watch --stop 2>/dev/null || true
pkill -f "grepai watch" 2>/dev/null || true
sleep 1
if pgrep -f "grepai watch" >/dev/null; then
echo "⚠️ watch still running - force kill"
pgrep -f "grepai watch" | xargs kill -9 2>/dev/null || true
sleep 1
fi
echo "✅ Watch stopped"
if [ ! -d .grepai ]; then
echo "❌ .grepai/ not found. Run setup first: /brewcode:grepai setup"
exit 1
fi
echo ""
echo "=== Reindex: Clean ==="
mkdir -p .grepai/logs
for f in .grepai/index.gob .grepai/symbols.gob; do
if [ -f "$f" ]; then
rm -f "$f" && echo " ✅ removed $(basename "$f")"
else
echo " ⏭️ $(basename "$f") not found"
fi
done
rm -f .grepai/logs/*.log 2>/dev/null && echo " ✅ cleaned old logs" || true
# CRITICAL: Remove last_index_time to force full reindex (index skip bug)
if grep -q "last_index_time:" .grepai/config.yaml 2>/dev/null; then
grep -v 'last_index_time:' .grepai/config.yaml > .grepai/config.yaml.tmp && mv .grepai/config.yaml.tmp .grepai/config.yaml
echo " ✅ removed last_index_time (prevents skip bug)"
fi
echo "✅ Cleanup complete"
echo ""
echo "=== Reindex: File Count ==="
estimate_timeout "$(count_indexable_files)"
echo ""
echo "=== Reindex: Build Index ==="
: > "$WATCH_LOG"
echo "Log: $WATCH_LOG"
echo "Monitor: tail -f $WATCH_LOG"
echo ""
start_watch_bg
wait_for_initial_scan "$TIMEOUT"
echo ""
echo "=== Reindex Complete ==="
report_index_state
echo "✅ Duration: ${ELAPSED}s"
-58
View File
@@ -1,58 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai Start Watch
echo "=== Starting grepai watch ==="
# Check prerequisites
if [ ! -d .grepai ]; then
echo "❌ .grepai/ not found. Run setup first: /grepai setup"
exit 1
fi
# Check if already running
if pgrep -f "grepai watch" >/dev/null; then
echo "⚠️ watch already running (PID: $(pgrep -f 'grepai watch'))"
exit 0
fi
# Create logs directory
mkdir -p .grepai/logs
# Start watch (|| true: set -e must not pre-empt the failure branch below)
grepai watch --background --log-dir .grepai/logs 2>/dev/null || true
# Verify
sleep 1
if pgrep -f "grepai watch" >/dev/null; then
echo "✅ watch started (PID: $(pgrep -f 'grepai watch'))"
echo " Logs: .grepai/logs/"
else
echo "❌ watch failed to start"
echo " Check: grepai watch (foreground) for errors"
exit 1
fi
# Ensure CLAUDE.md has grepai entry
CLAUDE_MD="CLAUDE.md"
GREPAI_MARKER="grepai_search"
append_claude_md_entry() {
{
echo ""
echo "## Code Search"
echo ""
echo "> **CRITICAL:** Use \`grepai_search\` FIRST for code exploration."
echo "> **ALWAYS \`compact:true\` + \`format:\"toon\"\`** → path+lines only, then \`Read\` the top hits."
echo "> Full content (\`compact:false\`) only as an exception, after a compact pass, with \`limit<=3\` — it overflows the context."
} >> "$1"
}
if [ ! -f "$CLAUDE_MD" ]; then
echo "# CLAUDE.md" > "$CLAUDE_MD"
append_claude_md_entry "$CLAUDE_MD"
echo "✅ CLAUDE.md created with grepai entry"
elif ! grep -q "$GREPAI_MARKER" "$CLAUDE_MD" 2>/dev/null; then
append_claude_md_entry "$CLAUDE_MD"
echo "✅ CLAUDE.md updated with grepai entry"
fi
-71
View File
@@ -1,71 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai Status Check
echo "=== grepai Status ==="
echo ""
echo "--- Infrastructure ---"
if command -v grepai &>/dev/null; then
CURRENT=$(grepai version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || true)
LATEST=$(brew info yoanbernabeu/tap/grepai 2>/dev/null | grep -oE 'stable [0-9]+\.[0-9]+\.[0-9]+' | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || true)
if [ -n "$CURRENT" ] && [ -n "$LATEST" ]; then
# Compare versions (newer installed = ok, older = update available)
if [ "$(printf '%s\n' "$LATEST" "$CURRENT" | sort -V | tail -1)" = "$LATEST" ] && [ "$CURRENT" != "$LATEST" ]; then
echo "⚠️ grepai: v$CURRENT → v$LATEST available — run: /grepai upgrade"
else
echo "✅ grepai: v$CURRENT (brew: v$LATEST)"
fi
elif [ -n "$CURRENT" ]; then
echo "✅ grepai: v$CURRENT"
else
echo "✅ grepai: installed"
fi
else
echo "❌ grepai: NOT FOUND"
fi
curl -s --connect-timeout 3 --max-time 5 localhost:11434/api/tags >/dev/null && echo "✅ ollama: running" || echo "❌ ollama: stopped"
ollama list 2>/dev/null | grep -q bge-m3 && echo "✅ bge-m3: installed" || echo "❌ bge-m3: missing"
echo ""
echo "--- Project ---"
test -d .grepai && echo "✅ .grepai/: exists" || echo "❌ .grepai/: missing"
test -f .grepai/config.yaml && echo "✅ config.yaml: exists" || echo "❌ config.yaml: missing"
test -f .grepai/index.gob && echo "✅ index.gob: $(du -h .grepai/index.gob 2>/dev/null | cut -f1)" || echo "⚠️ index.gob: missing"
echo ""
echo "--- Watch ---"
if pgrep -f "grepai watch" >/dev/null; then
echo "✅ watch: running (PID: $(pgrep -f 'grepai watch'))"
# Check if actively indexing (recent log activity)
if [ -f .grepai/logs/grepai-watch.log ]; then
LAST_LOG=$(tail -1 .grepai/logs/grepai-watch.log 2>/dev/null | head -c 100)
if echo "$LAST_LOG" | grep -qiE "index|embed|chunk"; then
echo " ⏳ indexing in progress..."
echo " last: $(echo "$LAST_LOG" | cut -c1-60)..."
fi
fi
else
echo "⚠️ watch: not running"
fi
echo ""
echo "--- Integration ---"
grep -q '"grepai"' ~/.claude.json 2>/dev/null && echo "✅ MCP: configured" || echo "❌ MCP: not configured"
grep -q 'mcp__grepai__' ~/.claude/settings.json 2>/dev/null && echo "✅ Permissions: auto-allowed" || echo "⚠️ Permissions: will prompt (run /grepai setup)"
test -f .claude/rules/grepai-first.md && echo "✅ rule: grepai-first.md" || echo "⚠️ rule: missing"
echo ""
echo "--- Hooks ---"
# Hooks are self-installed into the PROJECT (not the plugin) by /brewcode:grepai setup
HOOK_DIR=".claude/grepai/hooks"
test -f "$HOOK_DIR/grepai-session.mjs" && echo "✅ hook file: grepai-session.mjs" || echo "⚠️ hook file: grepai-session.mjs missing (run /brewcode:grepai setup)"
test -f "$HOOK_DIR/grepai-reminder.mjs" && echo "✅ hook file: grepai-reminder.mjs" || echo "⚠️ hook file: grepai-reminder.mjs missing (run /brewcode:grepai setup)"
grep -q 'grepai-session.mjs' .claude/settings.json 2>/dev/null && echo "✅ hook wired: SessionStart" || echo "⚠️ hook wired: SessionStart missing in .claude/settings.json"
grep -q 'grepai-reminder.mjs' .claude/settings.json 2>/dev/null && echo "✅ hook wired: PreToolUse:Bash" || echo "⚠️ hook wired: PreToolUse:Bash missing in .claude/settings.json"
echo ""
echo "--- MCP Tools ---"
if grep -q '"grepai"' ~/.claude.json 2>/dev/null; then
echo "Available: grepai_search, grepai_trace_callers, grepai_trace_callees, grepai_trace_graph, grepai_index_status"
fi
-23
View File
@@ -1,23 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai Stop Watch
echo "=== Stopping grepai watch ==="
# Try graceful stop first
grepai watch --stop 2>/dev/null || true
# Force kill if still running
if pgrep -f "grepai watch" >/dev/null; then
pkill -f "grepai watch" || true
sleep 1
fi
# Verify
if pgrep -f "grepai watch" >/dev/null; then
echo "❌ watch still running (PID: $(pgrep -f 'grepai watch'))"
echo " Try: kill -9 $(pgrep -f 'grepai watch')"
exit 1
else
echo "✅ watch stopped"
fi
@@ -1,77 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai Uninstall (project scope) — stop watch, unwire hooks, drop rule.
# Usage: uninstall.sh [--purge-index]
# Leaves the grepai CLI, ollama, the bge-m3 model and the user-scope MCP entry alone.
PURGE_INDEX=0
[ "${1:-}" = "--purge-index" ] && PURGE_INDEX=1
echo "=== grepai Uninstall (project) ==="
echo ""
echo "--- Watch ---"
grepai watch --stop 2>/dev/null || true
pkill -f "grepai watch" 2>/dev/null || true
sleep 1
pgrep -f "grepai watch" >/dev/null && echo "⚠️ watch: still running" || echo "✅ watch: stopped"
echo ""
echo "--- Hooks ---"
HOOK_DIR=".claude/grepai/hooks"
SETTINGS=".claude/settings.json"
if [ -d "$HOOK_DIR" ]; then
rm -f "$HOOK_DIR/grepai-session.mjs" "$HOOK_DIR/grepai-reminder.mjs"
rmdir "$HOOK_DIR" 2>/dev/null || true
rmdir ".claude/grepai" 2>/dev/null || true
echo "✅ hook files: removed"
else
echo "⏭️ hook files: none"
fi
if [ -f "$SETTINGS" ] && grep -q 'grepai-\(session\|reminder\)\.mjs' "$SETTINGS" 2>/dev/null; then
if command -v jq >/dev/null 2>&1; then
cp "$SETTINGS" "$SETTINGS.bak"
TMP="$(mktemp)"
jq '
def strip_grepai:
map(.hooks = ((.hooks // []) | map(select((.command // "") | test("grepai-(session|reminder)\\.mjs") | not))))
| map(select((.hooks | length) > 0));
.hooks.SessionStart = ((.hooks.SessionStart // []) | strip_grepai)
| .hooks.PreToolUse = ((.hooks.PreToolUse // []) | strip_grepai)
' "$SETTINGS" > "$TMP" && mv "$TMP" "$SETTINGS"
if jq empty "$SETTINGS" >/dev/null 2>&1 && ! grep -q 'grepai-\(session\|reminder\)\.mjs' "$SETTINGS"; then
echo "✅ settings.json: entries removed (backup: $SETTINGS.bak)"
else
echo "❌ settings.json: unwire failed — restore from $SETTINGS.bak"
exit 1
fi
else
echo "❌ jq not found — remove the grepai hook entries from $SETTINGS manually"
exit 1
fi
else
echo "⏭️ settings.json: no grepai entries"
fi
echo ""
echo "--- Rule ---"
if [ -f .claude/rules/grepai-first.md ]; then
rm -f .claude/rules/grepai-first.md && echo "✅ rule: removed"
else
echo "⏭️ rule: none"
fi
echo ""
echo "--- Index ---"
if [ "$PURGE_INDEX" -eq 1 ]; then
rm -rf .grepai && echo "✅ .grepai/: removed (config + index gone)"
else
test -d .grepai && echo "⏭️ .grepai/ kept (re-run with --purge-index to delete config + index)" || echo "⏭️ .grepai/: none"
fi
echo ""
echo "=== Uninstall Complete ==="
echo " Left untouched: grepai CLI, ollama, bge-m3, user-scope MCP entry in ~/.claude.json"
echo " Remove the '## Code Search' section from CLAUDE.md by hand if you no longer want it"
-54
View File
@@ -1,54 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai CLI Upgrade via Homebrew
echo "=== grepai Upgrade ==="
# Check brew available
if ! command -v brew &>/dev/null; then
echo "❌ Homebrew not found"
exit 1
fi
# Get current version
CURRENT=$(grepai version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || true)
if [ -z "$CURRENT" ]; then
echo "⚠️ grepai not installed, installing..."
brew install yoanbernabeu/tap/grepai && echo "✅ Installed" || { echo "❌ Install failed"; exit 1; }
exit 0
fi
echo "Current: v$CURRENT"
# Get latest from brew
TIMEOUT_CMD=$(command -v timeout || echo "")
if [ -n "$TIMEOUT_CMD" ]; then
LATEST=$($TIMEOUT_CMD 10 brew info yoanbernabeu/tap/grepai 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || true)
else
LATEST=$(brew info yoanbernabeu/tap/grepai 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || true)
fi
if [ -z "$LATEST" ]; then
echo "⚠️ Cannot fetch latest version (network issue?)"
echo "Manual check: brew info yoanbernabeu/tap/grepai"
exit 0
fi
echo "Latest: v$LATEST"
# Compare versions
if [ "$CURRENT" = "$LATEST" ]; then
echo "✅ Already up to date"
exit 0
fi
# Upgrade
echo "Upgrading..."
if brew upgrade yoanbernabeu/tap/grepai 2>&1; then
NEW=$(grepai version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || true)
echo "✅ Upgraded: v$CURRENT → v$NEW"
else
echo "❌ Upgrade failed"
exit 1
fi
exit 0
-31
View File
@@ -1,31 +0,0 @@
#!/bin/bash
set -euo pipefail
# grepai Final Verification
echo "=== Final Verification ==="
# Infrastructure
command -v grepai >/dev/null && echo "✅ grepai CLI" || echo "❌ grepai CLI"
curl -s --connect-timeout 3 --max-time 5 localhost:11434/api/tags >/dev/null && echo "✅ ollama running" || echo "❌ ollama stopped"
ollama list 2>/dev/null | grep -q bge-m3 && echo "✅ bge-m3 model" || echo "❌ bge-m3 missing"
grep -q '"grepai"' ~/.claude.json 2>/dev/null && echo "✅ MCP configured" || echo "❌ MCP missing"
grep -q 'mcp__grepai__' ~/.claude/settings.json 2>/dev/null && echo "✅ Permissions: auto-allowed" || echo "⚠️ Permissions: will prompt"
# Project config
test -d .grepai && echo "✅ .grepai/ directory" || echo "❌ .grepai/ missing"
test -f .grepai/config.yaml && echo "✅ config.yaml" || echo "❌ config.yaml missing"
test -f .grepai/index.gob && echo "✅ index.gob ($(du -h .grepai/index.gob | cut -f1))" || echo "⚠️ index.gob (indexing...)"
test -f .claude/rules/grepai-first.md && echo "✅ grepai-first.md rule" || echo "❌ rule missing"
# Project hooks (self-installed by Phase 6 into the project, not the plugin)
HOOK_DIR=".claude/grepai/hooks"
test -f "$HOOK_DIR/grepai-session.mjs" && echo "✅ hook file: grepai-session.mjs" || echo "⚠️ hook file: grepai-session.mjs missing"
test -f "$HOOK_DIR/grepai-reminder.mjs" && echo "✅ hook file: grepai-reminder.mjs" || echo "⚠️ hook file: grepai-reminder.mjs missing"
grep -q 'grepai-session.mjs' .claude/settings.json 2>/dev/null && echo "✅ hook wired: SessionStart" || echo "⚠️ hook wired: SessionStart missing in .claude/settings.json"
grep -q 'grepai-reminder.mjs' .claude/settings.json 2>/dev/null && echo "✅ hook wired: PreToolUse:Bash" || echo "⚠️ hook wired: PreToolUse:Bash missing in .claude/settings.json"
# Watch status
pgrep -f "grepai watch" >/dev/null && echo "✅ watch running" || echo "⚠️ watch not running"
echo ""
echo "=== Setup Complete ==="
+2 -2
View File
@@ -96,10 +96,10 @@ The full creation pipeline includes Phase 0 Discovery (parallel Explore agents),
/brewcode:skills create a skill that scans for hardcoded API keys
# Improve an existing skill by name
/brewcode:skills improve the grepai skill
/brewcode:skills improve the superreview skill
# Improve a skill by explicit path
/brewcode:skills update brewcode/skills/grepai
/brewcode:skills update brewcode/skills/convention
# Review all skills in a folder for quality
/brewcode:skills review ~/.claude/skills/
+2 -2
View File
@@ -88,8 +88,8 @@ single agent that owns half the repo.
### Phase 1 — Analyze the TARGET project
Gather everything the emitted skill must be wired to. Prefer `grepai_search` first for code exploration; fall back to
Bash search (`grep`->ugrep / `find`->bfs on macOS CC).
Gather everything the emitted skill must be wired to. Explore the code with Bash search (`grep`->ugrep / `find`->bfs
on macOS CC; native Grep/Glob are no-ops there).
**EXECUTE** using Bash tool (project scan):
```bash
@@ -461,7 +461,7 @@ closeout comment.
")
```
Each agent MUST search-first (grep / verify imports, prefer `mcp__grepai__search` if available) before flagging any
Each agent MUST search-first (Bash `grep`/`rg` + verify imports) before flagging any
reuse/duplicate, and read the ACTUAL code at every cited line. Collect every agent's findings into one pool
`{CANDIDATES}` (tag each finding with its producing agent as `source`). Gate failures from Phase 0 step 4 enter the
pool with `source: gate` and verdict `CONFIRMED-BY-EXECUTION`, citing the command + output line: they carry their
@@ -721,7 +721,7 @@ superreview does NOT run /simplify or any skill and does NOT edit code — these
| Validator agent | first non-owning in the Phase 3 chain (`{VALIDATOR_AGENT}` -> `{ARBITER_AGENT}` -> generic) | batches <=40, max 4 spawns, merge/de-dup ONCE over all batches |
| Report dir | `<repo-root>/.claude/reports/{TIMESTAMP}_superreview/` | Merged report, findings sorted P0 -> P3 |
| Max files | 50 (except `FULL_PROJECT`) | AskUserQuestion: narrow or proceed |
| Search tool | `mcp__grepai__search` if available, else Bash `rg`/`grep`/`git ls-files` | reuse-first search; note which in report |
| Search tool | Bash `rg`/`grep`/`git ls-files` | reuse-first search; note which in report |
---
@@ -746,7 +746,6 @@ superreview does NOT run /simplify or any skill and does NOT edit code — these
| `{SCOPE_AGENT_A}` unavailable | Run scope pass A's prompt on `Explore`, note the downgrade |
| `{PR_ISSUE_JSON}` empty | Pass B still runs DELIVERY vs the local task; records `PR: none`, skips closeout `scope#C*` |
| Scope gate cannot be asked (non-interactive) | Report at the priority the finding ENTERED with, tagged `unconfirmed-sanction`; never silently downgrade or upgrade past a cap |
| `grepai` unavailable | Fall back to Bash `rg`/`grep`/`git ls-files`; state which path was used in the report |
| Agent timeout | Retry once, then mark that source unavailable + warn; the verdict inherits INCOMPLETE — a timed-out group was NOT reviewed |
| Validation rejects everything, gates green | Report "No issues survived validation" — verdict APPROVED |
| All sources clean | Report "No issues found across standards, architecture, scope and correctness" — verdict APPROVED |
@@ -74,8 +74,7 @@ be validated or merged and is dropped; the JSON below is the merge contract —
DONE: JSON only, in the schema below; issues only; every finding with exact lines and an actionable suggestion.
**SEARCH-FIRST (HARD rule — reuse-first):** before flagging a 'duplicate' or 'reuse' miss, grep the repo
(Bash grep/find over the shared/util/common/domain/adapters dirs) and verify imports. If grepai
(mcp__grepai__search) is available, prefer it for semantic search. No verification -> no finding.
(Bash grep/find over the shared/util/common/domain/adapters dirs) and verify imports. No verification -> no finding.
NOTE: git-IGNORED = outside the review corpus. Where the instruction tree (`.claude/**`, `CLAUDE.md`) is ignored,
you may READ it as authority (cite a rule id) but never raise a finding ON it. Untracked-but-not-ignored files ARE
in scope — `git ls-files` alone misses them, so add `git ls-files --others --exclude-standard` to any reuse sweep.
@@ -13,7 +13,7 @@ Output: `.claude/reports/{TIMESTAMP}_superreview/REPORT.md`. ONE consolidated, v
**Sanctioned scope:** task {T-ID | none} / issue {id | none | not reached} / decisions {ids | none} — {K}/{COUNT} files outside it
**Gates:** {gate} {OK|FAIL|not run} / ...
**Validation:** {all {N} findings validated | **{U} UNVALIDATED of {N} — run is INCOMPLETE ({reason})**} — every row below carries a verdict
**Search tool used:** {grepai | Bash rg/grep fallback}
**Search tool used:** {Bash rg/grep/git ls-files}
**Agents run (derived from live roster):** {AGENT_LIST}{, DEGRADED: <group> -> generic}
> Findings section below is MANDATORY-sorted by priority P0 -> P3 (highest severity first).
@@ -45,7 +45,7 @@ const UserCard: React.FC<UserCardProps> = ({ user, onEdit }) => {
| `useRef` | Using for state |
Custom hooks: `use*` prefix, extract reusable logic, return object for >2 values. **Check existing hooks first**
(`hooks/`, `use*.ts`, grepai_search) before creating.
(`hooks/`, `use*.ts`, Bash `grep`) before creating.
## TypeScript Type Safety
@@ -1,38 +0,0 @@
---
paths:
- "**/*"
---
> **FIRST** `grepai` mcp for code exploration. **ALWAYS `compact:true` + `format:"toon"`.** Full content = exception, not default.
## Compact-first (HARD)
| | Rule |
|---|---|
| Default call | `compact:true, format:"toon", limit:10` → `{s,f,l}` only → then `Read` top 1-3 files at those lines |
| `compact:false` ONLY if | a compact pass already ran AND `limit<=3` AND one narrow query AND you still cannot pick the file |
| NEVER | `compact:false` as the first call, or with `limit>3`, or on a broad/vague query |
Why: 10 full chunks can blow the context in one call. Compact returns path+lines (~80% smaller); `Read` then fetches only what is needed.
## Examples
**search** `query:"error handling", limit:10, compact:true, format:"toon"` → `{s:0.82, f:"ErrorHandler.java", l:"23-55"}` → `Read` it
**search full** (rare) `query:"jwt claims parse", limit:3` → `{s:0.89, f:"auth/Login.java", l:"15-45", content:"..."}`
**callers** `symbol:"validateToken", compact:true` → `[{f:"AuthFilter.java", l:42, fn:"doFilter"}]`
**callees** `symbol:"processOrder", compact:true` → `[{f:"PaymentService.java", l:88, fn:"charge"}]`
**graph** `symbol:"main", depth:2, compact:true` → `{n:"main", c:[{n:"init", c:[{n:"loadConfig"}]}]}`
## When
| Need | Tool | Params |
|------|------|--------|
| Explore (any breadth) | search | `limit:10, compact:true, format:"toon"` → Read top files |
| Last resort, target known | search | `limit:3` (content on) |
| Who calls X? | trace_callers | `symbol:"X", compact:true` |
| What X calls? | trace_callees | `symbol:"X", compact:true` |
| Full dependency tree | trace_graph | `symbol:"X", depth:2, compact:true` |
## Query Tips
English · 3-7 words · intent not syntax · ✅`"validate credentials"` ❌`"validateUser"`
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "brewdoc",
"version": "4.3.0",
"version": "4.4.0",
"description": "Brewdoc - Claude Code documentation tools: my-claude installation docs, memory sync",
"author": {
"name": "Maksim Kochetkov",
+2 -2
View File
@@ -30,10 +30,10 @@ Guide walks you through every feature of the plugin suite across three progressi
| B: Core Workflow | killer-flow | The infinite task pipeline: spec, plan, start |
| B: Core Workflow | teams | Dynamic agent teams with self-selection and tracking |
| B: Core Workflow | skills-catalog | All 25 skills with trigger examples |
| C: Mastery | agents-catalog | All 14 agents with roles and model selection |
| C: Mastery | agents-catalog | All 12 agents with roles and model selection |
| C: Mastery | customization | Create custom skills, agents, and hooks |
| C: Mastery | integration | CLAUDE.md, rules, memory, teams directory |
| C: Mastery | advanced | Grepai, convention, quorum review, secrets scanning |
| C: Mastery | advanced | Convention extraction, quorum review, secrets scanning |
## Progress Tracking
+1 -1
View File
@@ -250,7 +250,7 @@ bash "${CLAUDE_SKILL_DIR}/scripts/progress.sh" complete "{TOPIC_ID}"
You now know everything about the brewcode plugin suite.
Useful next steps:
- Index your project with /brewcode:grepai
- Extract your project conventions with /brewcode:convention
- Create a team with /brewcode:teams create
- Start a task with /brewcode:spec "your task description"
```
@@ -5,20 +5,21 @@ Pre-drawn diagrams for the guide skill. Reference by name from topic files.
## Diagram: Plugin Suite Architecture
```
┌─────────────────────────────────────────────────┐
claude-brewcode (marketplace) │
├───────────────────────────────┬────────────────┤
│ brewcode │ brewdoc │ brewtools │
│───────────────────────────────────────────────│
│ setup, spec │ docsync │ text-optimize │
plan, start │ my-claude │ text-human │
teams, review │ memory │ secrets-scan │
convention, e2e │ md-to-pdf
rules, grepai │ guide │
│ publish │
│ + 14 agents │
│ + 9 hooks │ │ │
└─────────────────┴──────────────┴────────────────┘
┌───────────────────────────────────────────────────────
│ claude-brewcode (marketplace)
├───────────────────┬────────────────┬──────────────────
brewcode │ brewdoc brewtools
│───────────────────┼────────────────┼──────────────────│
│ spec, superreview │ docsync │ text-optimize
convention, teams │ my-claude │ text-human
rules, skills │ memory │ secrets-scan
agents, e2e │ md-to-pdf │ ssh, deploy
│ guide, publish │ manager, plugins
+ 9 agents │ + 3 agents
│ + 2 hooks │ + 2 hooks
└───────────────────┴────────────────┴──────────────────┘
brewui: placeholder, no skills yet
```
## Diagram: Killer Flow Pipeline
@@ -4,42 +4,7 @@ Domain: Mastery
Deliver section by section. Pause after each section with AskUserQuestion.
## Section 1: Grepai -- Semantic Code Search
Grepai indexes your codebase for semantic search. Much smarter than grep — it understands intent, not just text patterns.
```bash
# Setup grepai for your project
/brewcode:grepai
# After setup, search semantically:
grepai_search query:"user authentication flow"
grepai_search query:"error handling", compact:true
# Trace call chains:
trace_callers symbol:"validateToken"
trace_callees symbol:"processOrder"
trace_graph symbol:"main" depth:2
```
Search modes:
| Tool | Purpose | Example |
|------|---------|---------|
| grepai_search | Find code by meaning | `query:"payment processing"` |
| trace_callers | Who calls this function? | `symbol:"validateToken"` |
| trace_callees | What does this function call? | `symbol:"processOrder"` |
| trace_graph | Full dependency tree | `symbol:"main", depth:2` |
Query tips:
- Use natural English, 3-7 words
- Describe intent, not syntax: "validate credentials" not "validateUser"
- Add `compact:true` for large result sets (returns file + line, no content)
- Add `limit:5` for quick exploration
Grepai auto-activates via the grepai-session hook at conversation start.
## Section 2: Convention Extraction
## Section 1: Convention Extraction
Convention extraction analyzes your existing code to discover patterns and enforce them automatically.
@@ -63,7 +28,7 @@ Output goes to `.claude/rules/` as auto-loaded rule files. New code follows your
The convention skill identifies etalon (reference) classes in your codebase. These become the standard that generated rules point to.
## Section 3: Deep Code Review
## Section 2: Deep Code Review
Quorum code review with multiple independent perspectives.
@@ -89,7 +54,7 @@ Code submitted -> 3 reviewers analyze independently
The quorum approach filters out subjective preferences and focuses on issues that multiple reviewers agree on.
## Section 4: Secrets Scanning
## Section 3: Secrets Scanning
Detect leaked credentials before they reach your repository.
@@ -22,27 +22,24 @@ User request -> Manager analyzes -> Selects best agent -> Task tool spawns agent
Claude Code allows nested spawns up to 5 levels deep (since 2.1.172). The brewcode workflow, however, requires spawning only from the main conversation (manager level): the 2-step report protocol binds the task lock to a single session and delivers report/coordinator instructions to the spawning conversation. Nested spawns bypass session binding, KNOWLEDGE injection, and the coordinator loop — so under brewcode only the manager uses the Task tool.
## Section 2: Plugin Agents (15)
## Section 2: Plugin Agents (12)
These agents ship with the brewcode plugin suite. Available immediately after installation.
| Agent | Plugin | Model | When to Use |
|-------|--------|-------|-------------|
| developer | brewcode | opus | Implement features, write code, fix bugs |
| developer | brewcode | inherit | Implement features, write code, fix bugs |
| tester | brewcode | sonnet | Run tests, analyze failures, debug flaky tests |
| reviewer | brewcode | opus | Code review, architecture, security, performance |
| architect | brewcode | opus | Architecture analysis, patterns, trade-offs, scaling |
| skill-creator | brewcode | opus | Create/improve Claude Code skills (SKILL.md) |
| agent-creator | brewcode | opus | Create/update Claude Code agents |
| hook-creator | brewcode | opus | Create/debug Claude Code hooks |
| bash-expert | brewcode | opus | Create professional sh/bash scripts |
| bc-coordinator | brewcode | haiku | Internal. Spawned only by /brewcode:start + post-task hook. No direct/auto use. |
| bc-knowledge-manager | brewcode | haiku | Internal. Spawned only by /brewcode:start. No direct/auto use. |
| bc-grepai-configurator | brewcode | opus | Internal. Spawned only by /brewcode:grepai. No direct/auto use. |
| bc-rules-organizer | brewcode | sonnet | Internal. Spawned only by /brewcode:rules. No direct/auto use. |
| reviewer | brewcode | inherit | Code review, architecture, security, performance |
| architect | brewcode | inherit | Architecture analysis, patterns, trade-offs, scaling |
| skill-creator | brewcode | inherit | Create/improve Claude Code skills (SKILL.md) |
| agent-creator | brewcode | inherit | Create/update Claude Code agents |
| hook-creator | brewcode | inherit | Create/debug Claude Code hooks |
| bash-expert | brewcode | inherit | Create professional sh/bash scripts |
| bc-rules-organizer | brewcode | haiku | Internal. Spawned only by /brewcode:rules. No direct/auto use. |
| text-optimizer | brewtools | sonnet | Text/docs token optimization |
| ssh-admin | brewtools | opus | SSH server management |
| deploy-admin | brewtools | opus | GitHub Actions deployment |
| ssh-admin | brewtools | inherit | SSH server management |
| deploy-admin | brewtools | inherit | GitHub Actions deployment |
Agents prefixed with `bc-` are internal to brewcode workflows. The rest are user-facing.
@@ -51,10 +51,10 @@ You should see all four plugins with matching version numbers.
Quick smoke test:
```bash
/brewcode:grepai
/brewcode:skills status
```
If the grepai setup starts, installation is working.
If the skill roster prints, installation is working.
## Section 4: Updating
@@ -19,7 +19,7 @@ One marketplace, four plugins, one version number. Install what you need.
| Plugin | Purpose | Key Skills |
|--------|---------|------------|
| brewcode | Spec authoring, semantic search, deep review, agent teams | spec, grepai, superreview, convention, teams, e2e |
| brewcode | Spec authoring, deep review, agent teams, conventions | spec, superreview, convention, teams, rules, e2e |
| brewdoc | Documentation tools: sync, generate, optimize, publish | docsync, my-claude, memory, md-to-pdf, guide, publish |
| brewtools | Universal utilities: text optimization, security scanning | text-optimize, text-human, secrets-scan, ssh, deploy, plugin-update |
| brewui | UI/visual/creative tools (placeholder, empty) | (none yet) |
@@ -44,7 +44,7 @@ The plugins complement each other:
All four share the same version number. They update together from the same marketplace. No version mismatches.
Example workflow:
1. `/brewcode:grepai` indexes the project for semantic search
1. `/brewcode:convention` extracts the project patterns
2. `/brewcode:spec` defines the feature, then you implement it
3. `/brewcode:superreview` reviews it, `/brewdoc:docsync` syncs stale docs
4. `/brewtools:secrets-scan` checks nothing was leaked
@@ -2,14 +2,13 @@
Domain: Core Workflow
## Section 1: Brewcode Skills (9)
## Section 1: Brewcode Skills (8)
The main plugin. Spec authoring, semantic search, code quality.
The main plugin. Spec authoring, deep review, code quality.
| Skill | Purpose |
|-------|---------|
| `/brewcode:spec "desc"` | Create SPEC through research + user interaction |
| `/brewcode:grepai` | Setup grepai semantic code search |
| `/brewcode:superreview` | Deep multi-perspective quorum code review |
| `/brewcode:convention` | Extract code conventions, patterns, architecture |
| `/brewcode:rules` | Prompt-driven rules management: status, create, improve, review |
@@ -18,7 +17,7 @@ The main plugin. Spec authoring, semantic search, code quality.
| `/brewcode:skills` | Prompt-driven skill management: status, create, improve, review, sync |
| `/brewcode:agents` | Prompt-driven agent management: status, create, improve, review, sync |
Typical flow: `spec` -> implement -> `superreview` (use `grepai` for search)
Typical flow: `spec` -> implement -> `superreview`
## Section 2: Brewdoc Skills (6)
@@ -33,7 +32,7 @@ Documentation tools. Sync, generate, optimize, export, publish.
| `/brewdoc:guide` | Interactive teaching for the plugin suite (this guide) |
| `/brewdoc:publish` | Publish content to brewpage.app — text, markdown, or files |
## Section 3: Brewtools Skills (10)
## Section 3: Brewtools Skills (11)
Universal utilities. Work in any project, no setup needed.
@@ -49,6 +48,7 @@ Universal utilities. Work in any project, no setup needed.
| `/brewtools:think-short` | Install terse-mode hooks (project or global) that inject brevity directives to cut token bloat |
| `/brewtools:manager` | Codeword (++m, plan-aware) Manager prompt + opt-in HARD wall blocking mutating tools (RU+EN) |
| `/brewtools:task-board-init` | Deploy a file-based Kanban into any repo via multi-agent analysis |
| `/brewtools:agent-deadline` | Install a soft wall-clock budget for subagents — warn at 80%, block at 100% |
These are standalone — no project configuration required. Run them anywhere.
@@ -70,13 +70,11 @@ Brewui currently ships no skills -- placeholder for future UI/visual/creative to
| Step | Skill | Why |
|------|-------|-----|
| 1 | `/brewcode:grepai` | Enable semantic search |
| 2 | `/brewcode:convention` | Learn existing patterns |
| 3 | `/brewcode:spec "task"` | Define what to build |
| 4 | `/brewcode:superreview` | Review the result |
| 5 | `/brewcode:rules` | Save learnings as rules |
| 1 | `/brewcode:convention` | Learn existing patterns |
| 2 | `/brewcode:spec "task"` | Define what to build |
| 3 | `/brewcode:superreview` | Review the result |
| 4 | `/brewcode:rules` | Save learnings as rules |
**Tips:**
- Skills that modify files always confirm before writing
- Use `/brewcode:grepai` first in any new project — it indexes your code for semantic search
- `/brewcode:convention` extracts patterns so new code matches your existing style
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "brewtools",
"version": "4.3.0",
"version": "4.4.0",
"description": "Brewtools - universal utilities for Claude Code: text optimization, humanization, secrets scanning",
"author": {
"name": "Maksim Kochetkov",
@@ -189,13 +189,7 @@ Keep project-specific ticket patterns (INTELDEV-XXXXX, JIRA-XXXXX). Remove gener
### Scan Pattern
```
# Semantic search queries for grepai_search:
grepai_search("private methods with javadoc")
grepai_search("trivial param documentation")
grepai_search("test helper classes")
grepai_search("DTO classes with javadoc")
# Fallback grep patterns:
# grep patterns:
grep -n "^\s*/\*\*" <file> // Find all JavaDoc
grep -n "private.*{" <file> // Find private methods
```
@@ -218,12 +218,7 @@ def mock_user():
### Scan Pattern
```
# Semantic search:
grepai_search("private methods with docstrings")
grepai_search("trivial docstring parameters")
grepai_search("test file documentation")
# Fallback grep:
# grep patterns:
grep -n '"""' <file> # Find docstrings
grep -n "def _" <file> # Find private methods
```
@@ -183,12 +183,7 @@ export const createMockUser = () => { }
### Scan Pattern
```
# Semantic search:
grepai_search("jsdoc on private functions")
grepai_search("redundant type annotations")
grepai_search("test file documentation")
# Fallback grep:
# grep patterns:
grep -n "/\*\*" <file> // Find JSDoc
grep -n "^const.*=" <file> // Find functions
```
@@ -189,13 +189,7 @@ Keep project-specific ticket patterns (INTELDEV-XXXXX, JIRA-XXXXX). Remove gener
### Scan Pattern
```
# Semantic search queries for grepai_search:
grepai_search("private methods with javadoc")
grepai_search("trivial param documentation")
grepai_search("test helper classes")
grepai_search("DTO classes with javadoc")
# Fallback grep patterns:
# grep patterns:
grep -n "^\s*/\*\*" <file> // Find all JavaDoc
grep -n "private.*{" <file> // Find private methods
```
@@ -218,12 +218,7 @@ def mock_user():
### Scan Pattern
```
# Semantic search:
grepai_search("private methods with docstrings")
grepai_search("trivial docstring parameters")
grepai_search("test file documentation")
# Fallback grep:
# grep patterns:
grep -n '"""' <file> # Find docstrings
grep -n "def _" <file> # Find private methods
```
@@ -183,12 +183,7 @@ export const createMockUser = () => { }
### Scan Pattern
```
# Semantic search:
grepai_search("jsdoc on private functions")
grepai_search("redundant type annotations")
grepai_search("test file documentation")
# Fallback grep:
# grep patterns:
grep -n "/\*\*" <file> // Find JSDoc
grep -n "^const.*=" <file> // Find functions
```
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "brewui",
"version": "4.3.0",
"version": "4.4.0",
"description": "Brewui -- placeholder for future UI/visual/creative tools",
"author": {
"name": "Maksim Kochetkov",
+1 -1
View File
@@ -41,7 +41,7 @@ Example:
Found 4 duplicate/redundant entries (35% of memory):
| Entry | Memory File | Already In | Action |
|-------|-------------|------------|--------|
| "Use grepai first" | MEMORY.md:5 | rules/grepai-first.md | DELETE |
| "Search via Bash grep" | MEMORY.md:5 | rules/code-search.md | DELETE |
| "Constructor injection" | MEMORY.md:12 | CLAUDE.md:## DI | DELETE |
| "No System.out" | MEMORY.md:18 | rules/best-practice.md:7 | DELETE |
| "Edit bottom-up" | MEMORY.md:23 | rules/avoid.md:8 | DELETE |
+1 -1
View File
@@ -67,7 +67,7 @@ rules_files: [paths with content]
Found X duplicate/redundant entries (Y% of memory):
| Entry | Memory File | Already In | Action |
|-------|-------------|------------|--------|
| "Use grepai first" | MEMORY.md:5 | rules/grepai-first.md | DELETE |
| "Search via Bash grep" | MEMORY.md:5 | rules/code-search.md | DELETE |
...
```
4. `AskUserQuestion`: "Delete X duplicate entries (Y% of memory)? This is safe — content exists elsewhere."
@@ -1,6 +1,6 @@
---
title: "Agents"
description: "All 10 brewcode agents: models, tools, triggers, and the shared Scope guard that stops oversized tasks."
description: "All 9 brewcode agents: models, tools, triggers, and the shared Scope guard that stops oversized tasks."
order: 12
---
@@ -9,7 +9,7 @@ import { Card, CardGrid, Callout } from '../../../components/mdx';
# Agents
Agents (brewers) are specialized roles defined in markdown files with frontmatter metadata.
Each agent has its own model, toolset, and system prompt. Brewcode includes 10 agents (8 public + 2 internal helpers),
Each agent has its own model, toolset, and system prompt. Brewcode includes 9 agents (8 public + 1 internal helper),
from developer to task coordination.
## Summary table
@@ -26,10 +26,9 @@ Purpose column = the agent's own `description` frontmatter, verbatim. That strin
| 6 | agent-creator | inherit | Read, Write, Edit, Bash | Creates and improves Claude Code agents. Triggers: create agent, improve agent, scaffold agent. |
| 7 | hook-creator | inherit | Read, Write, Edit, Bash | Creates and debugs Claude Code hooks. Triggers: create hook, PreToolUse hook, debug hook. |
| 8 | bash-expert | inherit | Read, Write, Edit, Bash | Creates sh/bash scripts for Mac/Linux. Triggers: create script, bash script, shell script. |
| 9 | bc-grepai-configurator | sonnet | Read, Write, Edit, Bash | Internal. Spawned only by /brewcode:grepai. No direct/auto use. |
| 10 | bc-rules-organizer | haiku | Read, Write, Edit, Bash | Internal. Spawned only by /brewcode:rules. No direct/auto use. |
| 9 | bc-rules-organizer | haiku | Read, Write, Edit, Bash | Internal. Spawned only by /brewcode:rules. No direct/auto use. |
`model: inherit` means the agent runs on whatever model the session runs on — no per-agent pin. Only `tester` (sonnet) and the two internal helpers (sonnet / haiku) are pinned.
`model: inherit` means the agent runs on whatever model the session runs on — no per-agent pin. Only `tester` (sonnet) and the internal `bc-rules-organizer` (haiku) are pinned.
<CardGrid>
<Card title="developer" icon="code" href="/brewcode/agents/developer/">
@@ -59,7 +58,7 @@ Purpose column = the agent's own `description` frontmatter, verbatim. That strin
</CardGrid>
:::note[Internal agents]
`bc-grepai-configurator` and `bc-rules-organizer` are internal. They are spawned automatically by brewcode skills and hooks, are not user-invokable, and have no dedicated page.
`bc-rules-organizer` is internal. It is spawned automatically by brewcode skills and hooks, is not user-invokable, and has no dedicated page.
:::
## Scope guard — shared by all 8 agents
@@ -84,7 +83,7 @@ Agents deliver for the CONSUMER, not the literal wording: the result must be usa
| Model | Agents | Meaning |
|-------|--------|---------|
| **inherit** | [developer](/brewcode/agents/developer/), [reviewer](/brewcode/agents/reviewer/), [architect](/brewcode/agents/architect/), [skill-creator](/brewcode/agents/skill-creator/), [agent-creator](/brewcode/agents/agent-creator/), [hook-creator](/brewcode/agents/hook-creator/), [bash-expert](/brewcode/agents/bash-expert/) | Runs on the session's model — you control the tier |
| **sonnet** | [tester](/brewcode/agents/tester/), bc-grepai-configurator | Pinned: mechanical, high-volume work |
| **sonnet** | [tester](/brewcode/agents/tester/) | Pinned: mechanical, high-volume work |
| **haiku** | bc-rules-organizer | Pinned: cheap file reorganization |
<Callout type="tip" title="Automatic selection">
@@ -23,7 +23,6 @@ import { Callout, Card, CardGrid, Steps, UpdateNotice } from '../../../../compon
| Model | `inherit` — runs on the session's model |
| Tools | Read, Glob, Grep, Bash, WebFetch, WebSearch |
| Disallowed | Write, Edit, NotebookEdit |
| MCP | grepai |
## Scope guard
@@ -72,7 +71,7 @@ The agent reads every `.claude/rules/` file and `CLAUDE.md` first, then searches
<li>
<div>
<strong>Discovery</strong>
<p>Uses <code>grepai_search</code> first to find similar functionality, patterns, and boundaries. Falls back to Grep for specific deps and Glob for config and schema files. Runs <code>git log</code> via Bash to understand change history.</p>
<p>Greps for similar functionality, patterns, and boundaries, then uses Glob for config and schema files. Runs <code>git log</code> via Bash to understand change history.</p>
</div>
</li>
<li>
@@ -131,7 +130,7 @@ The agent reads every `.claude/rules/` file and `CLAUDE.md` first, then searches
| Trade-off evaluation | Code review (→ reviewer) |
| Scaling strategies | Deployment execution |
**Tool order:** `grepai_search` first for patterns and boundaries, then Grep/Glob/Read for structure, Bash for `git log` and dependency graphs, WebSearch for external research.
**Tool order:** Grep/Glob/Read for patterns, boundaries, and structure, Bash for `git log` and dependency graphs, WebSearch for external research.
</details>
@@ -23,7 +23,6 @@ import { Badge, Callout, Card, CardGrid, Steps, UpdateNotice } from '../../../..
|-------|-------|
| Model | `inherit` — runs on the session's model |
| Tools | Read, Write, Edit, Glob, Grep, Bash, Task, NotebookEdit, WebFetch, WebSearch |
| MCP | grepai |
| Git access | `status`, `diff`, `log`, `show`, `branch` — read-only; never `add`, `commit`, `push` |
| Triggers | "implement", "fix bug", "add feature" |
@@ -23,7 +23,6 @@ import { Callout, Card, CardGrid, Steps, UpdateNotice } from '../../../../compon
| Tools | Read, Glob, Grep, Bash, Task |
| Disallowed tools | Write, Edit |
| Triggers | "review code", "code review", "review PR", "check architecture", "approve changes" |
| MCP | grepai |
| Delegate to | Code changes → [developer](/brewcode/agents/developer/) · Tests → [tester](/brewcode/agents/tester/) |
## Scope guard
@@ -59,7 +58,7 @@ Reviewer sizes the review before starting. One bounded unit = one deliverable, r
"security review — check for injection risks"
```
The agent reads all `.claude/rules/` files first, runs `grepai_search` to find existing patterns, then produces a structured verdict.
The agent reads all `.claude/rules/` files first, greps for existing patterns, then produces a structured verdict.
## Flow
@@ -73,7 +72,7 @@ The agent reads all `.claude/rules/` files first, runs `grepai_search` to find e
<li>
<div>
<strong>Search for existing patterns</strong>
<p>Runs <code>grepai_search</code> across the codebase. Checks <code>common/utils/shared</code> for utilities, finds established patterns, confirms whether the reviewed code reimplements something that already exists.</p>
<p>Greps across the codebase. Checks <code>common/utils/shared</code> for utilities, finds established patterns, confirms whether the reviewed code reimplements something that already exists.</p>
</div>
</li>
<li>
@@ -103,7 +102,7 @@ The agent reads all `.claude/rules/` files first, runs `grepai_search` to find e
| Check | Action |
|-------|--------|
| Similar exists? | `grepai_search` codebase |
| Similar exists? | Grep the codebase |
| Utility exists? | Check common/utils/shared |
| Pattern established? | Find existing impl |
| Library available? | Prefer library over custom |
+1 -10
View File
@@ -4,7 +4,7 @@ description: "Both Brewcode hooks: events, channels, logic"
order: 13
---
import { Card, CardGrid, Callout, Badge } from '../../../components/mdx';
import { Card, CardGrid, Badge } from '../../../components/mdx';
# Hooks
@@ -116,15 +116,6 @@ The hook reads `permission_mode` from the hook payload and appends it to `system
---
## grepai hooks
<Callout type="note" title="grepai hooks are per-project, not always-on">
The grepai hooks are <strong>not</strong> shipped as always-on brewcode hooks.
They are installed per-project by the <code>/brewcode:grepai</code> self-install skill, which copies hook scripts from
<code>skills/grepai/assets/</code> into <code>.claude/grepai/hooks/</code> and merges the entries
into <code>.claude/settings.json</code>.
</Callout>
<CardGrid>
<Card title="Latest Release" icon="rocket" href="https://github.com/kochetkov-ma/claude-brewcode/releases/latest">
Download, changelog, and installation instructions.
+18 -21
View File
@@ -14,7 +14,7 @@ Install the entire suite:
<InstallPrompt plugin="all" mode="install" />
Brewcode is a plugin for Claude Code for spec authoring, semantic code search, and a toolkit of
Brewcode is a plugin for Claude Code for spec authoring, multi-agent review, and a toolkit of
skills and agents. The name is a nod to brewing: skills (recipes) define what to brew, agents
(brewers) do the work, and hooks (processes) manage prompt-time injection.
@@ -25,21 +25,20 @@ skills and agents. The name is a nod to brewing: skills (recipes) define what to
Agents resolve paths via native `${CLAUDE_PLUGIN_ROOT}`, substituted in each agent .md at Task spawn.
No hook injection, no shared runtime state.
</Card>
<Card title="9 skills (recipes)" icon="terminal">
From specification (<a href="/brewcode/skills/spec/">/brewcode:spec</a>) to semantic search (<a href="/brewcode/skills/grepai/">/brewcode:grepai</a>)
<Card title="8 skills (recipes)" icon="terminal">
From specification (<a href="/brewcode/skills/spec/">/brewcode:spec</a>) to convention analysis (<a href="/brewcode/skills/convention/">/brewcode:convention</a>)
and multi-agent review (<a href="/brewcode/skills/superreview/">/brewcode:superreview</a>).
</Card>
<Card title="10 agents (brewers)" icon="users">
<Card title="9 agents (brewers)" icon="users">
Specialized agents: [developer](/brewcode/agents/developer/), [tester](/brewcode/agents/tester/), [reviewer](/brewcode/agents/reviewer/), [architect](/brewcode/agents/architect/), [skill-creator](/brewcode/agents/skill-creator/),
[agent-creator](/brewcode/agents/agent-creator/), [hook-creator](/brewcode/agents/hook-creator/), and bash-expert.
</Card>
<Card title="2 hooks (processes)" icon="settings">
Prompt-time skill-activation reminder and session-start version-check.
grepai hooks self-install per project on demand.
Prompt-time delegation reminder and session-start version-check.
</Card>
<Card title="Semantic search" icon="search">
Integration with grepai -- AI-powered code search via Ollama + bge-m3.
Auto-start, reminders, configurator.
<Card title="E2E testing" icon="check">
BDD scenario authoring and Playwright autotest orchestration
via <a href="/brewcode/skills/e2e/">/brewcode:e2e</a>.
</Card>
<Card title="Code quality" icon="shield">
Standards-review, convention analysis.
@@ -62,7 +61,7 @@ all context is managed through built-in Claude Code events.
│ │
│ Skills (recipes) Agents (brewers) │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ spec, grepai │ │ developer, tester │ │
│ │ spec, e2e │ │ developer, tester │ │
│ │ superreview │ ──────> │ reviewer, architect│ │
│ │ convention,. │ │ + dynamic teams │ │
│ └──────────────┘ └──────────────────┘ │
@@ -91,7 +90,7 @@ brewcode/
│ ├── forced-eval.mjs # [ROLE] delegate + [SPLIT] bounded units
│ └── lib/
│ └── utils.mjs # I/O, version cache, configuration
├── agents/ # 10 agents
├── agents/ # 9 agents
│ ├── developer.md # Feature implementation (opus)
│ ├── tester.md # Testing (sonnet)
│ ├── reviewer.md # Code review (opus)
@@ -100,11 +99,9 @@ brewcode/
│ ├── agent-creator.md # Agent creation (opus)
│ ├── hook-creator.md # Hook creation (opus)
│ ├── bash-expert.md # Bash scripts (opus)
── bc-grepai-configurator.md # grepai configurator (opus)
│ └── bc-rules-organizer.md # Rules organizer (sonnet)
├── skills/ # 9 skills
── bc-rules-organizer.md # Rules organizer (haiku)
├── skills/ # 8 skills
│ ├── spec/ # Specification creation
│ ├── grepai/ # Semantic search (self-install hooks)
│ ├── convention/ # Convention analysis
│ ├── rules/ # Rule extraction
│ ├── superreview/ # Multi-agent quorum review
@@ -120,7 +117,7 @@ brewcode/
<Tabs>
<TabItem label="Skills">
9 skills (recipes) cover spec, search, review, and meta-tooling.
8 skills (recipes) cover spec, review, conventions, and meta-tooling.
See [Skills](/brewcode/skills/) for details.
| Group | Skills | Purpose |
@@ -129,10 +126,10 @@ brewcode/
| Quality | superreview, convention, rules | Multi-agent review, conventions, rule extraction |
| Dynamic | teams | Agent team creation and management |
| Testing | e2e | E2E testing orchestration with BDD scenarios |
| Meta | grepai, skills, agents | Semantic search + skill/agent management |
| Meta | skills, agents | Skill and agent management |
</TabItem>
<TabItem label="Agents">
10 agents (brewers) with different models and specializations.
9 agents (brewers) with different models and specializations.
See the [Agents](/brewcode/agents/) section for details.
| Role | Agents | Model |
@@ -141,7 +138,7 @@ brewcode/
| Review | reviewer | opus |
| Creation | skill-creator, agent-creator, hook-creator | opus |
| Optimization | bash-expert | opus |
| Internal | bc-grepai-configurator, bc-rules-organizer | opus/sonnet |
| Internal | bc-rules-organizer | haiku |
+ dynamic project agents created by [`/brewcode:teams`](/brewcode/skills/teams/)
</TabItem>
@@ -167,8 +164,8 @@ brewcode/
</li>
<li class="step step-primary">
<div>
<strong>Semantic search (optional)</strong> <Badge variant="primary" text="/brewcode:grepai" />
<p>Configure Ollama-backed semantic search for the project. Run once per project.</p>
<strong>Deep review</strong> <Badge variant="primary" text="/brewcode:superreview" />
<p>Generate a project-tailored quorum review skill. Run once per project.</p>
</div>
</li>
<li class="step step-secondary">
+9 -14
View File
@@ -1,6 +1,6 @@
---
title: "Skills"
description: "All 9 Brewcode skills + 1 dynamic per-project review skill"
description: "All 8 Brewcode skills + 1 dynamic per-project review skill"
order: 11
---
@@ -9,10 +9,10 @@ import { Card, CardGrid, Callout, Steps, UpdateNotice } from '../../../component
# Skills
Skills (recipes) are slash commands that define *what* to do. Each skill is described in a `SKILL.md` file
with frontmatter metadata and instructions for agents. Brewcode includes 9 skills covering
with frontmatter metadata and instructions for agents. Brewcode includes 8 skills covering
the full task lifecycle -- from project analysis to E2E testing.
On top of those there is a **dynamic tenth skill**: it is not shipped with the plugin, it is **generated into every target project** by [`/brewcode:superreview`](/brewcode/skills/superreview/) and invoked there as `/superreview`, tailored to that project's tech stack, agents, rules and tracker. See the [emitted skill page](/brewcode/skills/review/) for details.
On top of those there is a **dynamic ninth skill**: it is not shipped with the plugin, it is **generated into every target project** by [`/brewcode:superreview`](/brewcode/skills/superreview/) and invoked there as `/superreview`, tailored to that project's tech stack, agents, rules and tracker. See the [emitted skill page](/brewcode/skills/review/) for details.
## Summary table
@@ -21,12 +21,11 @@ On top of those there is a **dynamic tenth skill**: it is not shipped with the p
| 1 | [agents](/brewcode/skills/agents/) | [`/brewcode:agents`](/brewcode/skills/agents/) | opus | Creates, improves, syncs Claude Code subagents |
| 2 | [convention](/brewcode/skills/convention/) | [`/brewcode:convention`](/brewcode/skills/convention/) | opus | Extracts etalon classes, patterns, architecture into convention docs |
| 3 | [e2e](/brewcode/skills/e2e/) | [`/brewcode:e2e`](/brewcode/skills/e2e/) | opus | Orchestrates e2e testing: BDD scenarios, Playwright autotests |
| 4 | [grepai](/brewcode/skills/grepai/) | [`/brewcode:grepai`](/brewcode/skills/grepai/) | sonnet | Manages grepai semantic code search: setup, status, start, stop, reindex, optimize, upgrade, uninstall |
| 5 | [rules](/brewcode/skills/rules/) | [`/brewcode:rules`](/brewcode/skills/rules/) | sonnet | Syncs KNOWLEDGE.jsonl or session learnings to project rules |
| 6 | [skills](/brewcode/skills/skills/) | [`/brewcode:skills`](/brewcode/skills/skills/) | opus | Lists, improves, creates, syncs Claude Code skills |
| 7 | [spec](/brewcode/skills/spec/) | [`/brewcode:spec`](/brewcode/skills/spec/) | opus | Creates SPEC.md task spec via research + interaction |
| 8 | [superreview](/brewcode/skills/superreview/) | [`/brewcode:superreview`](/brewcode/skills/superreview/) | opus | Generates a project-tailored deep-review skill: domain-expert routing + scope discipline + mechanical gates + adversarial validation |
| 9 | [teams](/brewcode/skills/teams/) | [`/brewcode:teams`](/brewcode/skills/teams/) | opus | Creates and manages dynamic teams of domain agents |
| 4 | [rules](/brewcode/skills/rules/) | [`/brewcode:rules`](/brewcode/skills/rules/) | sonnet | Syncs KNOWLEDGE.jsonl or session learnings to project rules |
| 5 | [skills](/brewcode/skills/skills/) | [`/brewcode:skills`](/brewcode/skills/skills/) | opus | Lists, improves, creates, syncs Claude Code skills |
| 6 | [spec](/brewcode/skills/spec/) | [`/brewcode:spec`](/brewcode/skills/spec/) | opus | Creates SPEC.md task spec via research + interaction |
| 7 | [superreview](/brewcode/skills/superreview/) | [`/brewcode:superreview`](/brewcode/skills/superreview/) | opus | Generates a project-tailored deep-review skill: domain-expert routing + scope discipline + mechanical gates + adversarial validation |
| 8 | [teams](/brewcode/skills/teams/) | [`/brewcode:teams`](/brewcode/skills/teams/) | opus | Creates and manages dynamic teams of domain agents |
| ★ | [superreview (emitted)](/brewcode/skills/review/) | `/superreview` | opus | **Per-project** deep review — written into your repo by `/brewcode:superreview` |
<CardGrid>
@@ -39,9 +38,6 @@ On top of those there is a **dynamic tenth skill**: it is not shipped with the p
<Card title="e2e" icon="check" href="/brewcode/skills/e2e/">
E2E testing: scenarios, autotests, quorum review
</Card>
<Card title="grepai" icon="search" href="/brewcode/skills/grepai/">
Semantic search management
</Card>
<Card title="rules" icon="shield" href="/brewcode/skills/rules/">
Knowledge-to-rules synchronization
</Card>
@@ -62,7 +58,7 @@ On top of those there is a **dynamic tenth skill**: it is not shipped with the p
</Card>
</CardGrid>
## Delegation — one contract, all nine skills
## Delegation — one contract, all eight skills
Every skill here fans work out to subagents, and all of them follow the same sizing rule.
@@ -126,7 +122,6 @@ The recommended skill execution order for a standard project cycle:
```
spec --> superreview --> /superreview (emitted into your repo)
|
+-- grepai (optional)
+-- convention (optional)
+-- rules
+-- teams (optional)
@@ -167,7 +167,6 @@ A P2 layer agent is therefore told: the stack was already detected in P1 (do not
| >1000 source files | Warn user, suggest `paths` mode |
| Unknown stack | Continue with generic analysis |
| Agent timeout | Log warning, continue with available results |
| grepai unavailable | Fall back to Glob + Grep |
| Convention doc generation fails | Retry once, then present partial results |
**Output document paths**
@@ -1,195 +0,0 @@
---
title: "Grepai"
description: "Manages grepai semantic code search: setup, status, start, stop, reindex, optimize, upgrade, uninstall. Triggers: grepai, semantic search, reindex, index status."
order: 1107
---
import { Card, CardGrid, Badge, Callout, Steps, UpdateNotice } from '../../../../components/mdx';
# grepai — set up semantic search
<Badge variant="primary" text="sonnet" /> <Badge variant="secondary" text="session" />
<Callout type="caution" title="Prerequisites">
Run `/brewcode:grepai setup` — it checks/installs Homebrew, Ollama, and the grepai CLI, builds the index, and self-installs the grepai hooks into your project.
</Callout>
<Callout type="note" title="Self-install hooks">
`setup` mode detects whether grepai hooks are present in your project. If not, it copies `grepai-session.mjs` (SessionStart auto-start/health) and `grepai-reminder.mjs` (PreToolUse:Bash reminder) from the plugin's `skills/grepai/assets/` into `.claude/grepai/hooks/`, then merges the SessionStart and PreToolUse:Bash entries into `.claude/settings.json` using jq (python3 fallback, no-clobber, idempotent). The merged commands are written as `$CLAUDE_PROJECT_DIR`-relative paths, so they keep working after a move or a fresh clone. A summary of created files is printed when done.
</Callout>
<Callout type="tip" title="Environment">
Ollama + bge-m3 model · GOB on-disk index · Java / Kotlin / JS / TS projects
</Callout>
<Callout type="warning" title="Compact-first — enforced in four places">
Full search results carry the matched code inline, so ten hits can flood a context window in one call. Setup wires the same policy into the rule, the `CLAUDE.md` entry, and both hooks: search with `compact:true` and `format:"toon"` by default, get back paths and line ranges only, then `Read` the top one to three hits. `compact:false` is the exception — allowed after a compact pass, with `limit` at most 3, never as the opening call on a broad query.
</Callout>
## Quick reference
| Field | Value |
|-------|-------|
| Command | `/brewcode:grepai` |
| Arguments | `[setup\|status\|start\|stop\|reindex\|optimize\|upgrade\|uninstall]` |
| Model | sonnet |
| Context | session |
| Tools | Read, Write, Edit, Bash, Task, AskUserQuestion |
## When to use
| Situation | Command |
|-----------|---------|
| First-time setup on a new project | `/brewcode:grepai setup` |
| Check index health and watch status | `/brewcode:grepai status` |
| Resume watch after restart | `/brewcode:grepai start` |
| Stop the background watch process | `/brewcode:grepai stop` |
| Rebuild stale index after large refactor | `/brewcode:grepai reindex` |
| Tune boost patterns, update trace languages | `/brewcode:grepai optimize` |
| Update grepai CLI via Homebrew | `/brewcode:grepai upgrade` |
| Remove grepai from this project | `/brewcode:grepai uninstall` |
| Not sure which mode | `/brewcode:grepai` (interactive prompt) |
## Examples
**First-time setup**
```
/brewcode:grepai setup
```
The skill runs infra-check, configures MCP, spawns `bc-grepai-configurator` to generate `.grepai/config.yaml`, then builds the initial index synchronously (1030 min on large repos).
**Daily health check**
```
/brewcode:grepai status
```
Reports grepai CLI version, Ollama state, bge-m3 model, MCP connection, index size, watch process, and rule presence.
**Rebuild after a major merge**
```
/brewcode:grepai reindex
```
Stops watch, wipes the index, rebuilds from scratch, restarts watch. Monitor with `tail -f .grepai/logs/grepai-watch.log`.
**Remove grepai from a project**
```
/brewcode:grepai uninstall
```
Stops the watcher, deletes both hook files, unwires their `settings.json` entries (a `.bak` is kept), and drops the rule. It asks before deleting `.grepai/` — answering "keep index" means a later `setup` skips the expensive reindex. The CLI, Ollama, the bge-m3 model, and the user-scope MCP entry are left alone; the `## Code Search` section in `CLAUDE.md` has to go by hand.
## Flow
<Steps>
<li><div><strong>Mode detection</strong><p>The skill runs <code>detect-mode.sh</code> against <code>$ARGUMENTS</code>. Keywords like <code>setup</code>, <code>start</code>, <code>status</code> map to modes; empty args auto-detect from whether <code>.grepai/</code> exists; unrecognized text falls back to interactive prompt.</p></div></li>
<li><div><strong>Infra check (setup/optimize)</strong><p>Verifies Homebrew, Ollama daemon, bge-m3 model download, and grepai CLI. Stops with a clear error if any component is missing.</p></div></li>
<li><div><strong>MCP configuration</strong><p>Registers the grepai MCP server in <code>$HOME/.claude.json</code> at user scope with <code>alwaysLoad: true</code>, and adds <code>{'mcp__grepai__*'}</code> to <code>allowedTools</code> in <code>$HOME/.claude/settings.json</code> so the tools never trigger a permission prompt. Falls back to a jq patch when the CLI lacks <code>--always-load</code>.</p></div></li>
<li><div><strong>Config generation — bc-grepai-configurator agent</strong><p>The bc-grepai-configurator agent (opus) analyzes build files, source layout, and test patterns to produce an optimal <code>.grepai/config.yaml</code> with boost weights and trace-language settings.</p></div></li>
<li><div><strong>Index build</strong><p>Runs <code>init-index.sh</code> synchronously. Embeds all source files via bge-m3 and writes GOB shards to <code>.grepai/</code>. Large repos (5k+ files) take 1030 min — monitor the log.</p></div></li>
<li><div><strong>Rule creation</strong><p>Writes <code>.claude/rules/grepai-first.md</code> and appends a <code>## Code Search</code> section to <code>CLAUDE.md</code>, so Claude reaches for <code>grepai_search</code> / <code>trace_callers</code> / <code>trace_callees</code> before shelling out to grep or find — and does it compact-first.</p></div></li>
<li><div><strong>Hook self-install</strong><p>Copies both hooks into <code>.claude/grepai/hooks/</code> and merges them into <code>.claude/settings.json</code> as <code>$CLAUDE_PROJECT_DIR</code>-relative commands, so the wiring survives a repo move or a fresh clone.</p></div></li>
<li><div><strong>Verification</strong><p>Runs <code>verify.sh</code> — checks the CLI, Ollama, bge-m3, MCP registration, <code>.grepai/</code> contents, the rule, both hook files, and their <code>settings.json</code> wiring. Prints a status table with ✅/⚠️/❌ per component.</p></div></li>
</Steps>
## Delegation
<Callout type="caution" title="Why the rule exists">
A big task handed to one agent = an agent gone for an hour: you cannot observe it, cannot correct it, and it usually drifts off-target.
</Callout>
grepai spawns exactly one subagent — `bc-grepai-configurator` — and it gets a full brief anyway. One subagent = **ONE bounded unit**: here, ONE config file, roughly 5 files, roughly 10 steps. Anything bigger is split into N tasks fired in **ONE message**.
Every spawn prompt carries six fields. A bare one-line task is never enough:
| Field | Content |
|-------|---------|
| GOAL | the overall task and why it exists — the point beyond the file edit |
| ROLE | what this agent owns; what it must NOT touch |
| SCOPE | exact paths/commands in bounds + explicit out-of-bounds |
| CONTEXT | what is already done, by whom, what runs in parallel — trimmed to what THIS agent needs |
| CONSUMER | who or what uses the result next, and the shape it must fit |
| DONE | acceptance criteria + the exact report shape you want back |
For the configurator that reads: it owns `.grepai/config.yaml` and nothing else; Phases 1-2 already installed and verified the CLI and the MCP server, so it must not re-check them; Phases 5-6 will install the hooks and merge `settings.json`, so it leaves both alone. Its CONSUMER line is the sharp one — Phase 4 runs `grepai index` straight off that file, and a wrong exclude glob silently hides code instead of erroring, so the agent must flag what it could not infer rather than guess.
<details>
<summary>Config schema & internals</summary>
**Mode detection table**
| Keyword in args | MODE |
|-----------------|------|
| `uninstall`, `remove` | uninstall |
| `upgrade` | upgrade |
| `optimize`, `update` | optimize |
| `stop`, `halt`, `kill` | stop |
| `start`, `watch` | start |
| `status`, `doctor`, `check`, `health` | status |
| `setup`, `configure`, `init` | setup |
| `reindex`, `rebuild`, `refresh` | reindex |
| (empty) + `.grepai/` exists | start |
| (empty) + no `.grepai/` | setup |
| (unrecognized text) | interactive prompt |
**Scripts executed per mode**
| Mode | Script(s) |
|------|-----------|
| setup | `infra-check.sh` → `mcp-check.sh` → bc-grepai-configurator → `init-index.sh` → `create-rule.sh` → hook self-install → `verify.sh` |
| status | `status.sh` |
| start | `start.sh` |
| stop | `stop.sh` |
| reindex | `reindex.sh` (stop → clean → rebuild → restart) |
| optimize | `optimize.sh` (backup) → bc-grepai-configurator → `reindex.sh` |
| upgrade | `upgrade.sh` (brew upgrade) |
| uninstall | `uninstall.sh` (optional `--purge-index`) |
`init-index.sh` and `reindex.sh` share their file-count, timeout and log-polling logic through `scripts/lib/index-common.sh`.
**Status output format**
The skill always prints a status table after any mode completes:
```
✅ grepai CLI
✅ ollama running
✅ bge-m3 model
✅ MCP configured
✅ Permissions: auto-allowed
✅ .grepai/ directory
✅ config.yaml
✅ index.gob (412M)
✅ grepai-first.md rule
✅ hook file: grepai-session.mjs
✅ hook file: grepai-reminder.mjs
✅ hook wired: SessionStart
✅ hook wired: PreToolUse:Bash
✅ watch running
```
The index lives in two files next to the config: `.grepai/index.gob` (embeddings) and `.grepai/symbols.gob` (the symbol table backing the `trace_*` tools).
**Long-running operations warning**
`setup` (Phase 4) and `reindex` run the embedding pass synchronously. On repos with 5 000+ files, expect 1030 minutes. The process writes progress to `.grepai/logs/grepai-watch.log`.
</details>
<CardGrid>
<Card title="Hooks" icon="document" href="/brewcode/hooks/">
Auto-start and reminder hooks that setup mode installs into your project.
</Card>
<Card title="Source on GitHub" icon="link" href="https://github.com/kochetkov-ma/claude-brewcode/tree/main/brewcode/skills/grepai">
Skill scripts, SKILL.md, and configuration templates.
</Card>
<Card title="brewcode overview" icon="rocket" href="/brewcode/overview/">
Full plugin overview — all skills and agents in one place.
</Card>
</CardGrid>
<UpdateNotice />
@@ -179,8 +179,8 @@ MAX 3 iterations — then surface remaining remarks via AskUserQuestion
</details>
<CardGrid>
<Card title="Semantic Search" icon="document" href="/brewcode/skills/grepai/">
Search the codebase semantically to ground the spec in real code patterns and dependencies.
<Card title="Convention analysis" icon="document" href="/brewcode/skills/convention/">
Extract etalon classes and architecture patterns to ground the spec in real project conventions.
</Card>
<Card title="All Brewcode Skills" icon="star" href="/brewcode/skills/">
Browse every skill available in the brewcode plugin.
@@ -8,17 +8,17 @@ import { Card, CardGrid, Callout, InstallPrompt, Spoiler } from '../../component
# Introduction
**Brewcode** is a plugin suite for Claude Code: spec authoring, semantic code search, multi-agent quorum review, and tooling to build your own skills, agents, and hooks. Recipes (skills) define what to brew, brewers (agents) do the work, and hooks manage prompt-time injection.
**Brewcode** is a plugin suite for Claude Code: spec authoring, multi-agent quorum review, and tooling to build your own skills, agents, and hooks. Recipes (skills) define what to brew, brewers (agents) do the work, and hooks manage prompt-time injection.
<Callout type="tip" title="Spec first, then build">
`spec` → `grepai` → `superreview` — author the spec, index the code for semantic search, then generate a project-tailored deep-review skill.
`spec` → `convention` → `superreview` — author the spec, capture the project's conventions, then generate a project-tailored deep-review skill.
</Callout>
## Four plugins, one suite
<CardGrid>
<Card title="brewcode" icon="infinity" href="/brewcode/overview/">
The core: codebase exploration, quorum review, spec authoring, skill/agent/hook creation. 9 skills · 10 agents · 2 hooks.
The core: codebase exploration, quorum review, spec authoring, skill/agent/hook creation. 8 skills · 9 agents · 2 hooks.
</Card>
<Card title="brewtools" icon="settings" href="/brewtools/overview/">
Universal utilities: prompt optimization, AI artifact removal, secrets scanning, SSH, deploy. 11 skills · 3 agents.
@@ -42,12 +42,12 @@ import { Card, CardGrid, Callout, InstallPrompt, Spoiler } from '../../component
3 to 5 parallel reviewers work independently. Results are merged via a
quorum algorithm (2/3 agreement). Deduplication and ranking by severity.
</Card>
<Card title="Semantic code search" icon="brain" href="/brewcode/skills/grepai/">
grepai indexes the project with Ollama + bge-m3 embeddings. Self-installs its
hooks into the project and steers agents to grepai_search first.
<Card title="Convention capture" icon="book" href="/brewcode/skills/convention/">
Extracts etalon classes, patterns, and architecture into convention docs,
then syncs the distilled rules into <code>.claude/rules/</code>.
</Card>
<Card title="Skills and agents" icon="settings" href="/brewcode/skills/">
25 skills and 13 specialized agents across 4 plugins. Built-in tools for
25 skills and 12 specialized agents across 4 plugins. Built-in tools for
creating your own skills, agents, and hooks. Prompt optimization included.
</Card>
</CardGrid>
@@ -56,7 +56,7 @@ import { Card, CardGrid, Callout, InstallPrompt, Spoiler } from '../../component
| Plugin | Purpose | Skills | Agents | Hooks |
|--------|---------|--------|--------|-------|
| **brewcode** | Spec authoring, codebase exploration, quorum review, skill/agent/hook creation | 9 | 10 | 2 |
| **brewcode** | Spec authoring, codebase exploration, quorum review, skill/agent/hook creation | 8 | 9 | 2 |
| **brewtools** | Text utilities: prompt optimization, AI artifact removal, secrets scanning, SSH, deploy | 11 | 3 | — |
| **brewui** | UI / visual / creative tools (placeholder, empty) | 0 | 0 | — |
| **brewdoc** | Documentation tools: doc-staleness tracking, generation, memory sync, PDF conversion | 6 | 0 | — |
@@ -78,7 +78,7 @@ All four plugins install with a single marketplace and load automatically with e
Set up Brewcode in 2 minutes. One command to add the marketplace, one to install.
</Card>
<Card title="Quick Start" icon="play" href="/quickstart/">
Get started in 15 minutes: [spec](/brewcode/skills/spec/), [semantic search](/brewcode/skills/grepai/), [deep review](/brewcode/skills/superreview/).
Get started in 15 minutes: [spec](/brewcode/skills/spec/), [conventions](/brewcode/skills/convention/), [deep review](/brewcode/skills/superreview/).
</Card>
</CardGrid>
+2 -2
View File
@@ -93,7 +93,7 @@ import { Card, CardGrid, Callout, Steps, Tabs, TabItem, InstallPrompt } from '..
<strong>Author a spec</strong>
<p>Inside a Claude Code session, run:</p>
<pre><a href="/brewcode/skills/spec/"><code>/brewcode:spec</code></a></pre>
<p>Spec runs parallel codebase research and a refinement loop to produce a SPEC.md. For semantic search, run <a href="/brewcode/skills/grepai/"><code>/brewcode:grepai setup</code></a>, which checks/installs prerequisites (brew, ollama, grepai CLI) and self-installs its hooks.</p>
<p>Spec runs parallel codebase research and a refinement loop to produce a SPEC.md. Follow it with <a href="/brewcode/skills/superreview/"><code>/brewcode:superreview</code></a> to generate a project-tailored deep-review skill.</p>
</div>
</li>
</Steps>
@@ -144,7 +144,7 @@ claude plugin update brewui@claude-brewcode
<CardGrid>
<Card title="Quick Start" icon="rocket" href="/quickstart/">
Get started in 15 minutes: [spec](/brewcode/skills/spec/), [semantic search](/brewcode/skills/grepai/), [deep review](/brewcode/skills/superreview/).
Get started in 15 minutes: [spec](/brewcode/skills/spec/), [conventions](/brewcode/skills/convention/), [deep review](/brewcode/skills/superreview/).
</Card>
<Card title="Brewcode Overview" icon="building" href="/brewcode/overview/">
Architecture, concepts, all 25 skills, 14 agents, and 4 hooks.
+10 -11
View File
@@ -1,6 +1,6 @@
---
title: "Quick Start"
description: "Your first 15 minutes with Brewcode: spec, semantic search, deep review"
description: "Your first 15 minutes with Brewcode: spec, conventions, deep review"
order: 3
---
@@ -9,7 +9,7 @@ import { Card, CardGrid, Callout, Steps, Badge } from '../../components/mdx';
# Quick Start
In 15 minutes you will go through the core Brewcode workflow: from writing a structured specification
to indexing your codebase for semantic search and generating a project-tailored deep review skill.
to capturing your project's conventions and generating a project-tailored deep review skill.
<Callout type="note" title="Before you begin">
Make sure Claude Code and the brewcode plugin are installed.
@@ -43,13 +43,12 @@ claude plugin install brewcode@claude-brewcode</code></pre>
</li>
<li class="step step-primary">
<div>
<strong>Index for semantic search</strong> <Badge variant="primary" text="/brewcode:grepai setup" />
<pre><code>/brewcode:grepai setup</code></pre>
<p><strong>What happens:</strong> checks and installs Ollama and the CLI if missing, builds a vector
index of your codebase using the <code>bge-m3</code> embedding model, and self-installs grepai hooks
into the project.</p>
<p><strong>Result:</strong> all subsequent Claude Code sessions can query the project semantically —
faster and more precise context retrieval for every agent working on the spec.</p>
<strong>Capture project conventions</strong> <Badge variant="primary" text="/brewcode:convention" />
<pre><code>/brewcode:convention</code></pre>
<p><strong>What happens:</strong> parallel agents analyze each architectural layer, extract etalon
classes and recurring patterns, and write them into <code>.claude/convention/</code>.</p>
<p><strong>Result:</strong> every later agent has a written reference for how this project does
things — no more guessing at style or structure.</p>
</div>
</li>
<li class="step step-primary">
@@ -98,7 +97,7 @@ claude plugin install brewcode@claude-brewcode</code></pre>
<CardGrid>
<Card title="brewcode" icon="building" href="/brewcode/overview/">
9 skills: spec, semantic search, deep review, conventions, teams, and more.
8 skills: spec, deep review, conventions, rules, teams, and more.
</Card>
<Card title="brewtools" icon="wrench" href="/brewtools/overview/">
11 skills for text utilities: prompt optimization, AI artifact removal,
@@ -112,7 +111,7 @@ claude plugin install brewcode@claude-brewcode</code></pre>
doc generation, memory sync, PDF conversion, publishing.
</Card>
<Card title="All brewcode skills" icon="clipboard" href="/brewcode/skills/">
Full list of 9 brewcode skills with commands, parameters, and dependencies.
Full list of 8 brewcode skills with commands, parameters, and dependencies.
</Card>
<Card title="Dynamic teams" icon="group" href="/brewcode/skills/teams/">
Create 5-20 project-specific agents with self-selection and performance tracking.
-1
View File
@@ -32,7 +32,6 @@ export const navigation: NavSection[] = [
{ title: 'teams', slug: 'brewcode/skills/teams' },
{ title: 'convention', slug: 'brewcode/skills/convention' },
{ title: 'rules', slug: 'brewcode/skills/rules' },
{ title: 'grepai', slug: 'brewcode/skills/grepai' },
{ title: 'review (dynamic)', slug: 'brewcode/skills/review' },
{ title: 'skills', slug: 'brewcode/skills/skills' },
{ title: 'agents', slug: 'brewcode/skills/agents' },