From 07ad6c044c530ed0c8b6d5568afdb6edbd103d6a Mon Sep 17 00:00:00 2001 From: TechSphrex TA <42131590+KhaiTrang1995@users.noreply.github.com> Date: Fri, 26 Jun 2026 07:42:07 +0700 Subject: [PATCH 1/4] feat(mcp-server): add MCP server for runtime resource lookup MCP server exposes loop-engineering patterns, skills, state, budget, and safety docs as queryable resources via Model Context Protocol. Agents can query what they need on-demand instead of prompt stuffing. Resources: registry, config, budget, run-log, safety, patterns/{id}, skills/{name}, state/{file} Tools: list_patterns, list_skills, list_state_files, get_pattern, get_skill, get_state, recommend_pattern, estimate_cost Includes 16 tests, CI gate integration, and MCP config example. Co-Authored-By: Claude Haiku 4.5 --- .gitignore | 2 + examples/mcp/loop-engineering.mcp.json | 11 + package.json | 5 +- scripts/ci-validate-gates.sh | 6 + tools/mcp-server/README.md | 95 ++ tools/mcp-server/dist/index.d.ts | 4 + tools/mcp-server/dist/index.js | 320 ++++++ tools/mcp-server/dist/resolver.d.ts | 45 + tools/mcp-server/dist/resolver.js | 121 +++ tools/mcp-server/package-lock.json | 1227 ++++++++++++++++++++++++ tools/mcp-server/package.json | 53 + tools/mcp-server/src/index.ts | 441 +++++++++ tools/mcp-server/src/resolver.ts | 160 +++ tools/mcp-server/test/server.test.mjs | 272 ++++++ tools/mcp-server/tsconfig.json | 13 + 15 files changed, 2773 insertions(+), 2 deletions(-) create mode 100644 examples/mcp/loop-engineering.mcp.json create mode 100644 tools/mcp-server/README.md create mode 100644 tools/mcp-server/dist/index.d.ts create mode 100644 tools/mcp-server/dist/index.js create mode 100644 tools/mcp-server/dist/resolver.d.ts create mode 100644 tools/mcp-server/dist/resolver.js create mode 100644 tools/mcp-server/package-lock.json create mode 100644 tools/mcp-server/package.json create mode 100644 tools/mcp-server/src/index.ts create mode 100644 tools/mcp-server/src/resolver.ts create mode 100644 tools/mcp-server/test/server.test.mjs create mode 100644 tools/mcp-server/tsconfig.json diff --git a/.gitignore b/.gitignore index aa5bd8a..8f61ab3 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,8 @@ build/ **/node_modules/ !tools/loop-audit/dist/ !tools/loop-cost/dist/ +!tools/loop-init/dist/ +!tools/mcp-server/dist/ !tools/goal-audit/dist/ *.egg-info/ diff --git a/examples/mcp/loop-engineering.mcp.json b/examples/mcp/loop-engineering.mcp.json new file mode 100644 index 0000000..2be4734 --- /dev/null +++ b/examples/mcp/loop-engineering.mcp.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "loop-engineering": { + "command": "npx", + "args": ["-y", "@cobusgreyling/loop-mcp-server"], + "env": { + "LOOP_PROJECT_ROOT": "." + } + } + } +} diff --git a/package.json b/package.json index 6cc26c7..c5e57d6 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,9 @@ "test:loop-audit": "cd tools/loop-audit && npm test", "test:loop-init": "cd tools/loop-init && npm test", "test:loop-cost": "cd tools/loop-cost && npm test", - "test:tools": "npm run test:loop-audit && npm run test:loop-init && npm run test:loop-cost", - "build:tools": "cd tools/loop-audit && npm run build && cd ../loop-init && npm run build && cd ../loop-cost && npm run build" + "test:mcp-server": "cd tools/mcp-server && npm test", + "test:tools": "npm run test:loop-audit && npm run test:loop-init && npm run test:loop-cost && npm run test:mcp-server", + "build:tools": "cd tools/loop-audit && npm run build && cd ../loop-init && npm run build && cd ../loop-cost && npm run build && cd ../mcp-server && npm run build" }, "devDependencies": { "ajv": "^8.17.1", diff --git a/scripts/ci-validate-gates.sh b/scripts/ci-validate-gates.sh index 1550c0d..fe489cd 100755 --- a/scripts/ci-validate-gates.sh +++ b/scripts/ci-validate-gates.sh @@ -33,4 +33,10 @@ node scripts/check-loop-init-sync.mjs cd tools/loop-init npm ci npm test + +echo "Building and testing mcp-server…" +cd ../mcp-server +npm ci +npm test + echo "validate gates passed ✓" \ No newline at end of file diff --git a/tools/mcp-server/README.md b/tools/mcp-server/README.md new file mode 100644 index 0000000..99c0e48 --- /dev/null +++ b/tools/mcp-server/README.md @@ -0,0 +1,95 @@ +# @cobusgreyling/loop-mcp-server + +MCP (Model Context Protocol) server for **loop-engineering** — exposes patterns, skills, state, budget, and audit tools as runtime-queryable resources for AI agents. + +Instead of stuffing all loop documentation into the prompt, agents can query only what they need on-demand via MCP. + +## Quick Start + +```bash +npx @cobusgreyling/loop-mcp-server +``` + +### Configure in Claude Code / Grok / any MCP client + +Add to your MCP config (`.mcp.json` or equivalent): + +```json +{ + "mcpServers": { + "loop-engineering": { + "command": "npx", + "args": ["-y", "@cobusgreyling/loop-mcp-server"], + "env": { + "LOOP_PROJECT_ROOT": "." + } + } + } +} +``` + +## Resources + +| URI | Description | +|-----|-------------| +| `loop://registry` | Pattern registry (all 7 patterns with metadata, costs, phases) | +| `loop://config` | LOOP.md — cadence, budget, gates, scheduling | +| `loop://budget` | loop-budget.md — token caps, kill switch | +| `loop://run-log` | loop-run-log.md — append-only run history | +| `loop://safety` | Safety docs — denylists, auto-merge policy, MCP scopes | +| `loop://patterns/{id}` | Full pattern documentation by ID | +| `loop://skills/{name}` | Skill definition (SKILL.md) by name | +| `loop://state/{file}` | State file content | + +## Tools + +| Tool | Description | +|------|-------------| +| `loop_list_patterns` | List all patterns with goals, cadences, risk levels | +| `loop_list_skills` | List available skills with locations | +| `loop_list_state_files` | List state files in the project | +| `loop_get_pattern` | Get full pattern docs + registry metadata | +| `loop_get_skill` | Get SKILL.md content for a named skill | +| `loop_get_state` | Read a state file for current loop status | +| `loop_recommend_pattern` | Recommend patterns for a use case description | +| `loop_estimate_cost` | Estimate daily token cost for a pattern at L1/L2/L3 | + +## Environment + +| Variable | Default | Description | +|----------|---------|-------------| +| `LOOP_PROJECT_ROOT` | `cwd()` | Root directory of the project to serve | + +## Development + +```bash +cd tools/mcp-server +npm install +npm run build +npm test +``` + +## Architecture + +``` +Agent (Claude Code / Grok / Codex) + │ + ├─ MCP Resource Read ──→ loop://patterns/daily-triage + ├─ MCP Tool Call ──→ loop_recommend_pattern("watch CI failures") + └─ MCP Tool Call ──→ loop_estimate_cost("ci-sweeper", "L2") + │ + ▼ +loop-mcp-server (stdio transport) + │ + ├─ resolver.ts ──→ reads patterns/, skills/, STATE.md, LOOP.md, etc. + └─ index.ts ──→ MCP protocol handlers +``` + +The server reads from the local filesystem at `LOOP_PROJECT_ROOT`. It is read-only — it never writes to the project. + +## See Also + +- [Loop Engineering Patterns](../../patterns/) +- [MCP Examples](../../examples/mcp/) +- [Primitives: Plugins & Connectors](../../docs/primitives.md) +- [Safety: MCP Least Privilege](../../docs/safety.md) diff --git a/tools/mcp-server/dist/index.d.ts b/tools/mcp-server/dist/index.d.ts new file mode 100644 index 0000000..bb8a281 --- /dev/null +++ b/tools/mcp-server/dist/index.d.ts @@ -0,0 +1,4 @@ +#!/usr/bin/env node +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +declare const server: McpServer; +export { server }; diff --git a/tools/mcp-server/dist/index.js b/tools/mcp-server/dist/index.js new file mode 100644 index 0000000..35bb267 --- /dev/null +++ b/tools/mcp-server/dist/index.js @@ -0,0 +1,320 @@ +#!/usr/bin/env node +import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { z } from 'zod'; +import { resolveProjectRoot, loadRegistry, loadPatternDoc, listSkills, loadSkill, loadState, listStateFiles, loadLoopConfig, loadBudget, loadRunLog, loadSafetyDoc, listPatternDocs, } from './resolver.js'; +const server = new McpServer({ + name: 'loop-engineering', + version: '1.0.0', +}); +// ── Resources ────────────────────────────────────────────────────── +server.resource('registry', 'loop://registry', { description: 'Machine-readable pattern registry (all 7 patterns with metadata, costs, phases)' }, async () => { + const root = await resolveProjectRoot(); + const registry = await loadRegistry(root); + return { + contents: [{ + uri: 'loop://registry', + mimeType: 'application/json', + text: registry ? JSON.stringify(registry, null, 2) : '{"error": "registry.yaml not found"}', + }], + }; +}); +server.resource('loop-config', 'loop://config', { description: 'LOOP.md — cadence, budget, gates, and scheduling configuration' }, async () => { + const root = await resolveProjectRoot(); + const content = await loadLoopConfig(root); + return { + contents: [{ + uri: 'loop://config', + mimeType: 'text/markdown', + text: content ?? 'LOOP.md not found', + }], + }; +}); +server.resource('budget', 'loop://budget', { description: 'loop-budget.md — token caps, kill switch policy, spending limits' }, async () => { + const root = await resolveProjectRoot(); + const content = await loadBudget(root); + return { + contents: [{ + uri: 'loop://budget', + mimeType: 'text/markdown', + text: content ?? 'loop-budget.md not found', + }], + }; +}); +server.resource('run-log', 'loop://run-log', { description: 'loop-run-log.md — append-only run history with timestamps and outcomes' }, async () => { + const root = await resolveProjectRoot(); + const content = await loadRunLog(root); + return { + contents: [{ + uri: 'loop://run-log', + mimeType: 'text/markdown', + text: content ?? 'loop-run-log.md not found', + }], + }; +}); +server.resource('safety', 'loop://safety', { description: 'Safety documentation — denylists, auto-merge policy, MCP scopes, human gates' }, async () => { + const root = await resolveProjectRoot(); + const content = await loadSafetyDoc(root); + return { + contents: [{ + uri: 'loop://safety', + mimeType: 'text/markdown', + text: content ?? 'No safety documentation found', + }], + }; +}); +// ── Resource Templates (dynamic) ─────────────────────────────────── +server.resource('pattern', new ResourceTemplate('loop://patterns/{patternId}', { list: undefined }), { description: 'Full pattern documentation by ID (e.g. daily-triage, pr-babysitter, ci-sweeper)' }, async (uri, variables) => { + const patternId = variables.patternId; + const root = await resolveProjectRoot(); + const content = await loadPatternDoc(root, patternId); + return { + contents: [{ + uri: uri.href, + mimeType: 'text/markdown', + text: content ?? `Pattern "${patternId}" not found. Use loop_list_patterns to see available patterns.`, + }], + }; +}); +server.resource('skill', new ResourceTemplate('loop://skills/{skillName}', { list: undefined }), { description: 'Skill definition (SKILL.md) by name (e.g. loop-triage, minimal-fix, loop-verifier)' }, async (uri, variables) => { + const skillName = variables.skillName; + const root = await resolveProjectRoot(); + const skill = await loadSkill(root, skillName); + return { + contents: [{ + uri: uri.href, + mimeType: 'text/markdown', + text: skill?.content ?? `Skill "${skillName}" not found. Use loop_list_skills to see available skills.`, + }], + }; +}); +server.resource('state', new ResourceTemplate('loop://state/{stateFile}', { list: undefined }), { description: 'State file content (e.g. STATE.md, pr-babysitter-state.md)' }, async (uri, variables) => { + const stateFile = variables.stateFile; + const root = await resolveProjectRoot(); + const content = await loadState(root, stateFile); + return { + contents: [{ + uri: uri.href, + mimeType: 'text/markdown', + text: content ?? `State file "${stateFile}" not found. Use loop_list_state_files to see available state files.`, + }], + }; +}); +// ── Tools ────────────────────────────────────────────────────────── +server.tool('loop_list_patterns', 'List all available loop engineering patterns with their goals, cadences, and risk levels', {}, async () => { + const root = await resolveProjectRoot(); + const registry = await loadRegistry(root); + if (!registry) { + return { content: [{ type: 'text', text: 'No registry.yaml found in patterns/' }] }; + } + const summary = registry.patterns.map(p => ({ + id: p.id, + name: p.name, + goal: p.goal, + cadence: p.cadence, + risk: p.risk, + week_one_mode: p.week_one_mode, + token_cost: p.token_cost, + state: p.state, + })); + return { content: [{ type: 'text', text: JSON.stringify(summary, null, 2) }] }; +}); +server.tool('loop_list_skills', 'List all available skills with their names and locations', {}, async () => { + const root = await resolveProjectRoot(); + const skills = await listSkills(root); + if (skills.length === 0) { + return { content: [{ type: 'text', text: 'No skills found. Install from starters/ or skills/' }] }; + } + const summary = skills.map(s => ({ name: s.name, path: s.path })); + return { content: [{ type: 'text', text: JSON.stringify(summary, null, 2) }] }; +}); +server.tool('loop_list_state_files', 'List all state files present in the project', {}, async () => { + const root = await resolveProjectRoot(); + const files = await listStateFiles(root); + return { + content: [{ + type: 'text', + text: files.length > 0 + ? JSON.stringify(files, null, 2) + : 'No state files found. Create STATE.md from templates/STATE.md.template', + }], + }; +}); +server.tool('loop_get_pattern', 'Get full documentation for a specific pattern by ID', { patternId: z.string().describe('Pattern ID (e.g. daily-triage, pr-babysitter, ci-sweeper)') }, async ({ patternId }) => { + const root = await resolveProjectRoot(); + const registry = await loadRegistry(root); + const meta = registry?.patterns.find(p => p.id === patternId); + const doc = await loadPatternDoc(root, patternId); + if (!meta && !doc) { + const available = await listPatternDocs(root); + return { + content: [{ + type: 'text', + text: `Pattern "${patternId}" not found. Available: ${available.join(', ')}`, + }], + }; + } + const parts = []; + if (meta) { + parts.push('## Registry Metadata\n```json\n' + JSON.stringify(meta, null, 2) + '\n```\n'); + } + if (doc) { + parts.push('## Pattern Documentation\n\n' + doc); + } + return { content: [{ type: 'text', text: parts.join('\n') }] }; +}); +server.tool('loop_get_skill', 'Get the full SKILL.md definition for a named skill', { skillName: z.string().describe('Skill name (e.g. loop-triage, minimal-fix, loop-verifier)') }, async ({ skillName }) => { + const root = await resolveProjectRoot(); + const skill = await loadSkill(root, skillName); + if (!skill) { + const all = await listSkills(root); + return { + content: [{ + type: 'text', + text: `Skill "${skillName}" not found. Available: ${all.map(s => s.name).join(', ')}`, + }], + }; + } + return { content: [{ type: 'text', text: skill.content }] }; +}); +server.tool('loop_get_state', 'Read a state file to understand current loop status', { stateFile: z.string().optional().describe('State file name (default: STATE.md)') }, async ({ stateFile }) => { + const root = await resolveProjectRoot(); + const content = await loadState(root, stateFile); + if (!content) { + const available = await listStateFiles(root); + return { + content: [{ + type: 'text', + text: `State file "${stateFile ?? 'STATE.md'}" not found. Available: ${available.join(', ') || 'none'}`, + }], + }; + } + return { content: [{ type: 'text', text: content }] }; +}); +server.tool('loop_recommend_pattern', 'Recommend the best loop pattern for a given use case', { + useCase: z.string().describe('Describe what you want the loop to do (e.g. "watch CI failures", "review PRs", "update dependencies")'), +}, async ({ useCase }) => { + const root = await resolveProjectRoot(); + const registry = await loadRegistry(root); + if (!registry) { + return { content: [{ type: 'text', text: 'No registry found' }] }; + } + const lower = useCase.toLowerCase(); + const scored = registry.patterns.map(p => { + let score = 0; + const fields = [p.id, p.name, p.goal, ...p.skills, ...p.phases].join(' ').toLowerCase(); + const words = lower.split(/\s+/); + for (const w of words) { + if (w.length < 3) + continue; + if (fields.includes(w)) + score += 2; + } + if (lower.includes('ci') && p.id.includes('ci')) + score += 5; + if (lower.includes('pr') && p.id.includes('pr')) + score += 5; + if (lower.includes('depend') && p.id.includes('dependency')) + score += 5; + if (lower.includes('changelog') && p.id.includes('changelog')) + score += 5; + if (lower.includes('issue') && p.id.includes('issue')) + score += 5; + if (lower.includes('triage') && p.id.includes('triage')) + score += 3; + if (lower.includes('merge') && p.id.includes('merge')) + score += 5; + if (lower.includes('review') && p.id.includes('pr')) + score += 3; + if (lower.includes('security') && p.id.includes('dependency')) + score += 2; + return { pattern: p, score }; + }); + scored.sort((a, b) => b.score - a.score); + const top = scored.slice(0, 3); + const lines = ['## Recommended Patterns\n']; + for (const { pattern: p, score } of top) { + lines.push(`### ${p.name} (${p.id}) — relevance: ${score}`); + lines.push(`- **Goal:** ${p.goal}`); + lines.push(`- **Cadence:** ${p.cadence} | **Risk:** ${p.risk}`); + lines.push(`- **Start with:** ${p.week_one_mode}`); + lines.push(`- **Skills needed:** ${p.skills.join(', ')}`); + lines.push(`- **Starter:** ${p.starter}`); + lines.push(''); + } + return { content: [{ type: 'text', text: lines.join('\n') }] }; +}); +server.tool('loop_estimate_cost', 'Estimate daily token cost for a pattern at a given readiness level', { + patternId: z.string().describe('Pattern ID from registry'), + level: z.enum(['L1', 'L2', 'L3']).describe('Readiness level'), + cadence: z.string().optional().describe('Override cadence (e.g. "15m", "1d"). Uses pattern default if omitted'), +}, async ({ patternId, level, cadence }) => { + const root = await resolveProjectRoot(); + const registry = await loadRegistry(root); + if (!registry) { + return { content: [{ type: 'text', text: 'No registry found' }] }; + } + const pattern = registry.patterns.find(p => p.id === patternId); + if (!pattern) { + return { + content: [{ + type: 'text', + text: `Pattern "${patternId}" not found. Available: ${registry.patterns.map(p => p.id).join(', ')}`, + }], + }; + } + const effectiveCadence = cadence ?? pattern.cadence; + const parts = effectiveCadence.split('-').map(p => p.trim()); + let runsPerDay; + try { + const intervals = parts.map(p => { + const m = p.match(/^(\d+)([mhd])$/); + if (!m) + throw new Error(`Invalid interval: ${p}`); + const ms = { m: 60_000, h: 3_600_000, d: 86_400_000 }; + return Number(m[1]) * ms[m[2]]; + }); + runsPerDay = Math.floor(86_400_000 / Math.min(...intervals)); + } + catch { + return { content: [{ type: 'text', text: `Invalid cadence: ${effectiveCadence}` }] }; + } + const { cost } = pattern; + const mix = level === 'L1' + ? { noop: 0.7, report: 0.3, action: 0 } + : level === 'L2' + ? { noop: 0.6, report: 0.25, action: 0.15 } + : { noop: 0.4, report: 0.35, action: 0.25 }; + const realisticPerRun = cost.tokens_noop * mix.noop + + cost.tokens_report * mix.report + + cost.tokens_action * mix.action; + const realisticPerDay = Math.round(realisticPerRun * runsPerDay); + const fmt = (n) => n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1_000 ? `${Math.round(n / 1_000)}k` : String(n); + const lines = [ + `## Cost Estimate: ${pattern.name}`, + `- **Cadence:** ${effectiveCadence} (${runsPerDay} runs/day)`, + `- **Level:** ${level}`, + `- **Daily cap:** ${fmt(cost.suggested_daily_cap)}`, + '', + '| Scenario | Per Run | Per Day |', + '|----------|---------|---------|', + `| No-op | ${fmt(cost.tokens_noop)} | ${fmt(cost.tokens_noop * runsPerDay)} |`, + `| Report | ${fmt(cost.tokens_report)} | ${fmt(cost.tokens_report * runsPerDay)} |`, + `| Action | ${fmt(cost.tokens_action)} | ${fmt(cost.tokens_action * runsPerDay)} |`, + `| **Realistic** | **${fmt(Math.round(realisticPerRun))}** | **${fmt(realisticPerDay)}** |`, + ]; + if (realisticPerDay > cost.suggested_daily_cap) { + lines.push('', `> Warning: realistic estimate exceeds daily cap of ${fmt(cost.suggested_daily_cap)}`); + } + return { content: [{ type: 'text', text: lines.join('\n') }] }; +}); +// ── Start ────────────────────────────────────────────────────────── +async function main() { + const transport = new StdioServerTransport(); + await server.connect(transport); +} +main().catch((err) => { + console.error('MCP server failed to start:', err); + process.exit(1); +}); +export { server }; diff --git a/tools/mcp-server/dist/resolver.d.ts b/tools/mcp-server/dist/resolver.d.ts new file mode 100644 index 0000000..939d647 --- /dev/null +++ b/tools/mcp-server/dist/resolver.d.ts @@ -0,0 +1,45 @@ +export declare function fileExists(p: string): Promise; +export declare function resolveProjectRoot(hint?: string): Promise; +export declare function readFileIfExists(filePath: string): Promise; +export interface PatternInfo { + id: string; + name: string; + file: string; + goal: string; + cadence: string; + risk: string; + tools: string[]; + skills: string[]; + state: string; + phases: string[]; + human_gates: string[]; + starter: string; + week_one_mode: string; + token_cost: string; + cost: { + tokens_noop: number; + tokens_report: number; + tokens_action: number; + suggested_daily_cap: number; + early_exit_required: boolean; + }; +} +export interface RegistryData { + patterns: PatternInfo[]; +} +export interface SkillInfo { + name: string; + path: string; + content: string; +} +export declare function loadRegistry(root: string): Promise; +export declare function loadPatternDoc(root: string, patternId: string): Promise; +export declare function listSkills(root: string): Promise; +export declare function loadSkill(root: string, skillName: string): Promise; +export declare function loadState(root: string, stateFile?: string): Promise; +export declare function listStateFiles(root: string): Promise; +export declare function loadLoopConfig(root: string): Promise; +export declare function loadBudget(root: string): Promise; +export declare function loadRunLog(root: string): Promise; +export declare function loadSafetyDoc(root: string): Promise; +export declare function listPatternDocs(root: string): Promise; diff --git a/tools/mcp-server/dist/resolver.js b/tools/mcp-server/dist/resolver.js new file mode 100644 index 0000000..4766860 --- /dev/null +++ b/tools/mcp-server/dist/resolver.js @@ -0,0 +1,121 @@ +import { readdir, readFile, stat } from 'node:fs/promises'; +import path from 'node:path'; +export async function fileExists(p) { + try { + await stat(p); + return true; + } + catch { + return false; + } +} +export async function resolveProjectRoot(hint) { + if (hint) + return path.resolve(hint); + return process.env.LOOP_PROJECT_ROOT + ? path.resolve(process.env.LOOP_PROJECT_ROOT) + : process.cwd(); +} +export async function readFileIfExists(filePath) { + try { + return await readFile(filePath, 'utf8'); + } + catch { + return null; + } +} +export async function loadRegistry(root) { + const registryPath = path.join(root, 'patterns', 'registry.yaml'); + const content = await readFileIfExists(registryPath); + if (!content) + return null; + const { parse } = await import('yaml'); + return parse(content); +} +export async function loadPatternDoc(root, patternId) { + const filePath = path.join(root, 'patterns', `${patternId}.md`); + return readFileIfExists(filePath); +} +export async function listSkills(root) { + const skillDirs = [ + path.join(root, 'skills'), + path.join(root, '.grok', 'skills'), + path.join(root, '.claude', 'skills'), + path.join(root, '.codex', 'skills'), + ]; + const results = []; + for (const dir of skillDirs) { + if (!(await fileExists(dir))) + continue; + try { + const entries = await readdir(dir, { withFileTypes: true }); + for (const e of entries) { + if (!e.isDirectory()) + continue; + const skillMd = path.join(dir, e.name, 'SKILL.md'); + const content = await readFileIfExists(skillMd); + if (content) { + results.push({ name: e.name, path: skillMd, content }); + } + } + } + catch { /* dir unreadable */ } + } + return results; +} +export async function loadSkill(root, skillName) { + const skills = await listSkills(root); + return skills.find(s => s.name === skillName) ?? null; +} +export async function loadState(root, stateFile) { + const target = stateFile ?? 'STATE.md'; + return readFileIfExists(path.join(root, target)); +} +export async function listStateFiles(root) { + const candidates = [ + 'STATE.md', + 'pr-babysitter-state.md', + 'ci-sweeper-state.md', + 'post-merge-state.md', + 'dependency-sweeper-state.md', + 'changelog-drafter-state.md', + 'issue-triage-state.md', + ]; + const found = []; + for (const f of candidates) { + if (await fileExists(path.join(root, f))) + found.push(f); + } + return found; +} +export async function loadLoopConfig(root) { + return readFileIfExists(path.join(root, 'LOOP.md')); +} +export async function loadBudget(root) { + return readFileIfExists(path.join(root, 'loop-budget.md')); +} +export async function loadRunLog(root) { + return readFileIfExists(path.join(root, 'loop-run-log.md')); +} +export async function loadSafetyDoc(root) { + for (const f of ['docs/safety.md', 'safety.md', 'SECURITY.md']) { + const content = await readFileIfExists(path.join(root, f)); + if (content) + return content; + } + return null; +} +export async function listPatternDocs(root) { + const patternsDir = path.join(root, 'patterns'); + if (!(await fileExists(patternsDir))) + return []; + try { + const entries = await readdir(patternsDir); + return entries + .filter(e => e.endsWith('.md') && e !== 'README.md') + .map(e => e.replace('.md', '')); + } + catch { + return []; + } +} diff --git a/tools/mcp-server/package-lock.json b/tools/mcp-server/package-lock.json new file mode 100644 index 0000000..1838419 --- /dev/null +++ b/tools/mcp-server/package-lock.json @@ -0,0 +1,1227 @@ +{ + "name": "@cobusgreyling/loop-mcp-server", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@cobusgreyling/loop-mcp-server", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.12.1", + "yaml": "^2.8.0" + }, + "bin": { + "loop-mcp-server": "dist/index.js" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "typescript": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@hono/node-server": { + "version": "1.19.14", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz", + "integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==", + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.29.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", + "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@types/node": { + "version": "22.20.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.0.tgz", + "integrity": "sha512-QWlFW2wf3nTjC13/DqRnBpR4ZO36VJH/JVBkA/vcnmbTBNQIlnObqyqZE1tUR7+Ni23Lda8R1BxMfbXRpCUx5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.0.tgz", + "integrity": "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.5.2", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz", + "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz", + "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.12.27", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.27.tgz", + "integrity": "sha512-1yrb/+w6HWQJrUCLkJ2IF5jNIPvvFkblV5RNOYl6bV+OA6p9GLcMpHFFGTosSvHvcAUibuUukRqhlYI4z32C7Q==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", + "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz", + "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/yaml": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + } + } +} diff --git a/tools/mcp-server/package.json b/tools/mcp-server/package.json new file mode 100644 index 0000000..49f1848 --- /dev/null +++ b/tools/mcp-server/package.json @@ -0,0 +1,53 @@ +{ + "name": "@cobusgreyling/loop-mcp-server", + "version": "1.0.0", + "description": "MCP server for loop-engineering — exposes patterns, skills, state, and audit tools as runtime-queryable resources for AI agents", + "type": "module", + "bin": { + "loop-mcp-server": "dist/index.js" + }, + "files": [ + "dist", + "README.md" + ], + "scripts": { + "build": "tsc", + "test": "npm run build && node --test test/server.test.mjs", + "prepublishOnly": "npm test", + "start": "node dist/index.js" + }, + "engines": { + "node": ">=18" + }, + "keywords": [ + "loop-engineering", + "mcp", + "model-context-protocol", + "ai-agents", + "claude-code", + "grok", + "codex" + ], + "author": "Cobus Greyling", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/cobusgreyling/loop-engineering.git", + "directory": "tools/mcp-server" + }, + "homepage": "https://cobusgreyling.github.io/loop-engineering/", + "bugs": { + "url": "https://github.com/cobusgreyling/loop-engineering/issues" + }, + "publishConfig": { + "access": "public" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.12.1", + "yaml": "^2.8.0" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "typescript": "^5.0.0" + } +} diff --git a/tools/mcp-server/src/index.ts b/tools/mcp-server/src/index.ts new file mode 100644 index 0000000..3a33cea --- /dev/null +++ b/tools/mcp-server/src/index.ts @@ -0,0 +1,441 @@ +#!/usr/bin/env node + +import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { z } from 'zod'; +import { + resolveProjectRoot, + loadRegistry, + loadPatternDoc, + listSkills, + loadSkill, + loadState, + listStateFiles, + loadLoopConfig, + loadBudget, + loadRunLog, + loadSafetyDoc, + listPatternDocs, +} from './resolver.js'; + +const server = new McpServer({ + name: 'loop-engineering', + version: '1.0.0', +}); + +// ── Resources ────────────────────────────────────────────────────── + +server.resource( + 'registry', + 'loop://registry', + { description: 'Machine-readable pattern registry (all 7 patterns with metadata, costs, phases)' }, + async () => { + const root = await resolveProjectRoot(); + const registry = await loadRegistry(root); + return { + contents: [{ + uri: 'loop://registry', + mimeType: 'application/json', + text: registry ? JSON.stringify(registry, null, 2) : '{"error": "registry.yaml not found"}', + }], + }; + }, +); + +server.resource( + 'loop-config', + 'loop://config', + { description: 'LOOP.md — cadence, budget, gates, and scheduling configuration' }, + async () => { + const root = await resolveProjectRoot(); + const content = await loadLoopConfig(root); + return { + contents: [{ + uri: 'loop://config', + mimeType: 'text/markdown', + text: content ?? 'LOOP.md not found', + }], + }; + }, +); + +server.resource( + 'budget', + 'loop://budget', + { description: 'loop-budget.md — token caps, kill switch policy, spending limits' }, + async () => { + const root = await resolveProjectRoot(); + const content = await loadBudget(root); + return { + contents: [{ + uri: 'loop://budget', + mimeType: 'text/markdown', + text: content ?? 'loop-budget.md not found', + }], + }; + }, +); + +server.resource( + 'run-log', + 'loop://run-log', + { description: 'loop-run-log.md — append-only run history with timestamps and outcomes' }, + async () => { + const root = await resolveProjectRoot(); + const content = await loadRunLog(root); + return { + contents: [{ + uri: 'loop://run-log', + mimeType: 'text/markdown', + text: content ?? 'loop-run-log.md not found', + }], + }; + }, +); + +server.resource( + 'safety', + 'loop://safety', + { description: 'Safety documentation — denylists, auto-merge policy, MCP scopes, human gates' }, + async () => { + const root = await resolveProjectRoot(); + const content = await loadSafetyDoc(root); + return { + contents: [{ + uri: 'loop://safety', + mimeType: 'text/markdown', + text: content ?? 'No safety documentation found', + }], + }; + }, +); + +// ── Resource Templates (dynamic) ─────────────────────────────────── + +server.resource( + 'pattern', + new ResourceTemplate('loop://patterns/{patternId}', { list: undefined }), + { description: 'Full pattern documentation by ID (e.g. daily-triage, pr-babysitter, ci-sweeper)' }, + async (uri, variables) => { + const patternId = variables.patternId as string; + const root = await resolveProjectRoot(); + const content = await loadPatternDoc(root, patternId); + return { + contents: [{ + uri: uri.href, + mimeType: 'text/markdown', + text: content ?? `Pattern "${patternId}" not found. Use loop_list_patterns to see available patterns.`, + }], + }; + }, +); + +server.resource( + 'skill', + new ResourceTemplate('loop://skills/{skillName}', { list: undefined }), + { description: 'Skill definition (SKILL.md) by name (e.g. loop-triage, minimal-fix, loop-verifier)' }, + async (uri, variables) => { + const skillName = variables.skillName as string; + const root = await resolveProjectRoot(); + const skill = await loadSkill(root, skillName); + return { + contents: [{ + uri: uri.href, + mimeType: 'text/markdown', + text: skill?.content ?? `Skill "${skillName}" not found. Use loop_list_skills to see available skills.`, + }], + }; + }, +); + +server.resource( + 'state', + new ResourceTemplate('loop://state/{stateFile}', { list: undefined }), + { description: 'State file content (e.g. STATE.md, pr-babysitter-state.md)' }, + async (uri, variables) => { + const stateFile = variables.stateFile as string; + const root = await resolveProjectRoot(); + const content = await loadState(root, stateFile); + return { + contents: [{ + uri: uri.href, + mimeType: 'text/markdown', + text: content ?? `State file "${stateFile}" not found. Use loop_list_state_files to see available state files.`, + }], + }; + }, +); + +// ── Tools ────────────────────────────────────────────────────────── + +server.tool( + 'loop_list_patterns', + 'List all available loop engineering patterns with their goals, cadences, and risk levels', + {}, + async () => { + const root = await resolveProjectRoot(); + const registry = await loadRegistry(root); + if (!registry) { + return { content: [{ type: 'text' as const, text: 'No registry.yaml found in patterns/' }] }; + } + const summary = registry.patterns.map(p => ({ + id: p.id, + name: p.name, + goal: p.goal, + cadence: p.cadence, + risk: p.risk, + week_one_mode: p.week_one_mode, + token_cost: p.token_cost, + state: p.state, + })); + return { content: [{ type: 'text' as const, text: JSON.stringify(summary, null, 2) }] }; + }, +); + +server.tool( + 'loop_list_skills', + 'List all available skills with their names and locations', + {}, + async () => { + const root = await resolveProjectRoot(); + const skills = await listSkills(root); + if (skills.length === 0) { + return { content: [{ type: 'text' as const, text: 'No skills found. Install from starters/ or skills/' }] }; + } + const summary = skills.map(s => ({ name: s.name, path: s.path })); + return { content: [{ type: 'text' as const, text: JSON.stringify(summary, null, 2) }] }; + }, +); + +server.tool( + 'loop_list_state_files', + 'List all state files present in the project', + {}, + async () => { + const root = await resolveProjectRoot(); + const files = await listStateFiles(root); + return { + content: [{ + type: 'text' as const, + text: files.length > 0 + ? JSON.stringify(files, null, 2) + : 'No state files found. Create STATE.md from templates/STATE.md.template', + }], + }; + }, +); + +server.tool( + 'loop_get_pattern', + 'Get full documentation for a specific pattern by ID', + { patternId: z.string().describe('Pattern ID (e.g. daily-triage, pr-babysitter, ci-sweeper)') }, + async ({ patternId }) => { + const root = await resolveProjectRoot(); + + const registry = await loadRegistry(root); + const meta = registry?.patterns.find(p => p.id === patternId); + const doc = await loadPatternDoc(root, patternId); + + if (!meta && !doc) { + const available = await listPatternDocs(root); + return { + content: [{ + type: 'text' as const, + text: `Pattern "${patternId}" not found. Available: ${available.join(', ')}`, + }], + }; + } + + const parts: string[] = []; + if (meta) { + parts.push('## Registry Metadata\n```json\n' + JSON.stringify(meta, null, 2) + '\n```\n'); + } + if (doc) { + parts.push('## Pattern Documentation\n\n' + doc); + } + + return { content: [{ type: 'text' as const, text: parts.join('\n') }] }; + }, +); + +server.tool( + 'loop_get_skill', + 'Get the full SKILL.md definition for a named skill', + { skillName: z.string().describe('Skill name (e.g. loop-triage, minimal-fix, loop-verifier)') }, + async ({ skillName }) => { + const root = await resolveProjectRoot(); + const skill = await loadSkill(root, skillName); + if (!skill) { + const all = await listSkills(root); + return { + content: [{ + type: 'text' as const, + text: `Skill "${skillName}" not found. Available: ${all.map(s => s.name).join(', ')}`, + }], + }; + } + return { content: [{ type: 'text' as const, text: skill.content }] }; + }, +); + +server.tool( + 'loop_get_state', + 'Read a state file to understand current loop status', + { stateFile: z.string().optional().describe('State file name (default: STATE.md)') }, + async ({ stateFile }) => { + const root = await resolveProjectRoot(); + const content = await loadState(root, stateFile); + if (!content) { + const available = await listStateFiles(root); + return { + content: [{ + type: 'text' as const, + text: `State file "${stateFile ?? 'STATE.md'}" not found. Available: ${available.join(', ') || 'none'}`, + }], + }; + } + return { content: [{ type: 'text' as const, text: content }] }; + }, +); + +server.tool( + 'loop_recommend_pattern', + 'Recommend the best loop pattern for a given use case', + { + useCase: z.string().describe('Describe what you want the loop to do (e.g. "watch CI failures", "review PRs", "update dependencies")'), + }, + async ({ useCase }) => { + const root = await resolveProjectRoot(); + const registry = await loadRegistry(root); + if (!registry) { + return { content: [{ type: 'text' as const, text: 'No registry found' }] }; + } + + const lower = useCase.toLowerCase(); + const scored = registry.patterns.map(p => { + let score = 0; + const fields = [p.id, p.name, p.goal, ...p.skills, ...p.phases].join(' ').toLowerCase(); + const words = lower.split(/\s+/); + for (const w of words) { + if (w.length < 3) continue; + if (fields.includes(w)) score += 2; + } + if (lower.includes('ci') && p.id.includes('ci')) score += 5; + if (lower.includes('pr') && p.id.includes('pr')) score += 5; + if (lower.includes('depend') && p.id.includes('dependency')) score += 5; + if (lower.includes('changelog') && p.id.includes('changelog')) score += 5; + if (lower.includes('issue') && p.id.includes('issue')) score += 5; + if (lower.includes('triage') && p.id.includes('triage')) score += 3; + if (lower.includes('merge') && p.id.includes('merge')) score += 5; + if (lower.includes('review') && p.id.includes('pr')) score += 3; + if (lower.includes('security') && p.id.includes('dependency')) score += 2; + return { pattern: p, score }; + }); + + scored.sort((a, b) => b.score - a.score); + const top = scored.slice(0, 3); + + const lines: string[] = ['## Recommended Patterns\n']; + for (const { pattern: p, score } of top) { + lines.push(`### ${p.name} (${p.id}) — relevance: ${score}`); + lines.push(`- **Goal:** ${p.goal}`); + lines.push(`- **Cadence:** ${p.cadence} | **Risk:** ${p.risk}`); + lines.push(`- **Start with:** ${p.week_one_mode}`); + lines.push(`- **Skills needed:** ${p.skills.join(', ')}`); + lines.push(`- **Starter:** ${p.starter}`); + lines.push(''); + } + + return { content: [{ type: 'text' as const, text: lines.join('\n') }] }; + }, +); + +server.tool( + 'loop_estimate_cost', + 'Estimate daily token cost for a pattern at a given readiness level', + { + patternId: z.string().describe('Pattern ID from registry'), + level: z.enum(['L1', 'L2', 'L3']).describe('Readiness level'), + cadence: z.string().optional().describe('Override cadence (e.g. "15m", "1d"). Uses pattern default if omitted'), + }, + async ({ patternId, level, cadence }) => { + const root = await resolveProjectRoot(); + const registry = await loadRegistry(root); + if (!registry) { + return { content: [{ type: 'text' as const, text: 'No registry found' }] }; + } + + const pattern = registry.patterns.find(p => p.id === patternId); + if (!pattern) { + return { + content: [{ + type: 'text' as const, + text: `Pattern "${patternId}" not found. Available: ${registry.patterns.map(p => p.id).join(', ')}`, + }], + }; + } + + const effectiveCadence = cadence ?? pattern.cadence; + const parts = effectiveCadence.split('-').map(p => p.trim()); + let runsPerDay: number; + try { + const intervals = parts.map(p => { + const m = p.match(/^(\d+)([mhd])$/); + if (!m) throw new Error(`Invalid interval: ${p}`); + const ms: Record = { m: 60_000, h: 3_600_000, d: 86_400_000 }; + return Number(m[1]) * ms[m[2]]; + }); + runsPerDay = Math.floor(86_400_000 / Math.min(...intervals)); + } catch { + return { content: [{ type: 'text' as const, text: `Invalid cadence: ${effectiveCadence}` }] }; + } + + const { cost } = pattern; + const mix = level === 'L1' + ? { noop: 0.7, report: 0.3, action: 0 } + : level === 'L2' + ? { noop: 0.6, report: 0.25, action: 0.15 } + : { noop: 0.4, report: 0.35, action: 0.25 }; + + const realisticPerRun = cost.tokens_noop * mix.noop + + cost.tokens_report * mix.report + + cost.tokens_action * mix.action; + const realisticPerDay = Math.round(realisticPerRun * runsPerDay); + + const fmt = (n: number) => n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1_000 ? `${Math.round(n / 1_000)}k` : String(n); + + const lines = [ + `## Cost Estimate: ${pattern.name}`, + `- **Cadence:** ${effectiveCadence} (${runsPerDay} runs/day)`, + `- **Level:** ${level}`, + `- **Daily cap:** ${fmt(cost.suggested_daily_cap)}`, + '', + '| Scenario | Per Run | Per Day |', + '|----------|---------|---------|', + `| No-op | ${fmt(cost.tokens_noop)} | ${fmt(cost.tokens_noop * runsPerDay)} |`, + `| Report | ${fmt(cost.tokens_report)} | ${fmt(cost.tokens_report * runsPerDay)} |`, + `| Action | ${fmt(cost.tokens_action)} | ${fmt(cost.tokens_action * runsPerDay)} |`, + `| **Realistic** | **${fmt(Math.round(realisticPerRun))}** | **${fmt(realisticPerDay)}** |`, + ]; + + if (realisticPerDay > cost.suggested_daily_cap) { + lines.push('', `> Warning: realistic estimate exceeds daily cap of ${fmt(cost.suggested_daily_cap)}`); + } + + return { content: [{ type: 'text' as const, text: lines.join('\n') }] }; + }, +); + +// ── Start ────────────────────────────────────────────────────────── + +async function main() { + const transport = new StdioServerTransport(); + await server.connect(transport); +} + +main().catch((err) => { + console.error('MCP server failed to start:', err); + process.exit(1); +}); + +export { server }; diff --git a/tools/mcp-server/src/resolver.ts b/tools/mcp-server/src/resolver.ts new file mode 100644 index 0000000..8e85bd5 --- /dev/null +++ b/tools/mcp-server/src/resolver.ts @@ -0,0 +1,160 @@ +import { readdir, readFile, stat } from 'node:fs/promises'; +import path from 'node:path'; + +export async function fileExists(p: string): Promise { + try { + await stat(p); + return true; + } catch { + return false; + } +} + +export async function resolveProjectRoot(hint?: string): Promise { + if (hint) return path.resolve(hint); + return process.env.LOOP_PROJECT_ROOT + ? path.resolve(process.env.LOOP_PROJECT_ROOT) + : process.cwd(); +} + +export async function readFileIfExists(filePath: string): Promise { + try { + return await readFile(filePath, 'utf8'); + } catch { + return null; + } +} + +export interface PatternInfo { + id: string; + name: string; + file: string; + goal: string; + cadence: string; + risk: string; + tools: string[]; + skills: string[]; + state: string; + phases: string[]; + human_gates: string[]; + starter: string; + week_one_mode: string; + token_cost: string; + cost: { + tokens_noop: number; + tokens_report: number; + tokens_action: number; + suggested_daily_cap: number; + early_exit_required: boolean; + }; +} + +export interface RegistryData { + patterns: PatternInfo[]; +} + +export interface SkillInfo { + name: string; + path: string; + content: string; +} + +export async function loadRegistry(root: string): Promise { + const registryPath = path.join(root, 'patterns', 'registry.yaml'); + const content = await readFileIfExists(registryPath); + if (!content) return null; + + const { parse } = await import('yaml'); + return parse(content) as RegistryData; +} + +export async function loadPatternDoc(root: string, patternId: string): Promise { + const filePath = path.join(root, 'patterns', `${patternId}.md`); + return readFileIfExists(filePath); +} + +export async function listSkills(root: string): Promise { + const skillDirs = [ + path.join(root, 'skills'), + path.join(root, '.grok', 'skills'), + path.join(root, '.claude', 'skills'), + path.join(root, '.codex', 'skills'), + ]; + + const results: SkillInfo[] = []; + for (const dir of skillDirs) { + if (!(await fileExists(dir))) continue; + try { + const entries = await readdir(dir, { withFileTypes: true }); + for (const e of entries) { + if (!e.isDirectory()) continue; + const skillMd = path.join(dir, e.name, 'SKILL.md'); + const content = await readFileIfExists(skillMd); + if (content) { + results.push({ name: e.name, path: skillMd, content }); + } + } + } catch { /* dir unreadable */ } + } + return results; +} + +export async function loadSkill(root: string, skillName: string): Promise { + const skills = await listSkills(root); + return skills.find(s => s.name === skillName) ?? null; +} + +export async function loadState(root: string, stateFile?: string): Promise { + const target = stateFile ?? 'STATE.md'; + return readFileIfExists(path.join(root, target)); +} + +export async function listStateFiles(root: string): Promise { + const candidates = [ + 'STATE.md', + 'pr-babysitter-state.md', + 'ci-sweeper-state.md', + 'post-merge-state.md', + 'dependency-sweeper-state.md', + 'changelog-drafter-state.md', + 'issue-triage-state.md', + ]; + const found: string[] = []; + for (const f of candidates) { + if (await fileExists(path.join(root, f))) found.push(f); + } + return found; +} + +export async function loadLoopConfig(root: string): Promise { + return readFileIfExists(path.join(root, 'LOOP.md')); +} + +export async function loadBudget(root: string): Promise { + return readFileIfExists(path.join(root, 'loop-budget.md')); +} + +export async function loadRunLog(root: string): Promise { + return readFileIfExists(path.join(root, 'loop-run-log.md')); +} + +export async function loadSafetyDoc(root: string): Promise { + for (const f of ['docs/safety.md', 'safety.md', 'SECURITY.md']) { + const content = await readFileIfExists(path.join(root, f)); + if (content) return content; + } + return null; +} + +export async function listPatternDocs(root: string): Promise { + const patternsDir = path.join(root, 'patterns'); + if (!(await fileExists(patternsDir))) return []; + try { + const entries = await readdir(patternsDir); + return entries + .filter(e => e.endsWith('.md') && e !== 'README.md') + .map(e => e.replace('.md', '')); + } catch { + return []; + } +} diff --git a/tools/mcp-server/test/server.test.mjs b/tools/mcp-server/test/server.test.mjs new file mode 100644 index 0000000..0ccfa59 --- /dev/null +++ b/tools/mcp-server/test/server.test.mjs @@ -0,0 +1,272 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +import { + resolveProjectRoot, + loadRegistry, + listSkills, + loadSkill, + loadState, + listStateFiles, + loadLoopConfig, + loadBudget, + loadRunLog, + loadSafetyDoc, + listPatternDocs, + loadPatternDoc, +} from '../dist/resolver.js'; + +let tmpRoot; + +async function setup() { + tmpRoot = await mkdtemp(path.join(tmpdir(), 'mcp-test-')); + + // patterns/registry.yaml + await mkdir(path.join(tmpRoot, 'patterns'), { recursive: true }); + await writeFile( + path.join(tmpRoot, 'patterns', 'registry.yaml'), + `patterns: + - id: daily-triage + name: Daily Triage + file: daily-triage.md + goal: Prioritized morning scan + cadence: 1d-2h + risk: low + tools: [grok, claude-code] + skills: [loop-triage, minimal-fix] + state: STATE.md + phases: [report, act-small-wins, escalate] + human_gates: [design-decisions] + starter: starters/minimal-loop + week_one_mode: L1 + token_cost: low + cost: + tokens_noop: 5000 + tokens_report: 50000 + tokens_action: 200000 + suggested_daily_cap: 100000 + early_exit_required: false +`, + ); + + // Pattern doc + await writeFile( + path.join(tmpRoot, 'patterns', 'daily-triage.md'), + '# Daily Triage\n\n## Scheduling\nRun once per day.\n\n## Required Skills\nloop-triage\n\n## Verification Strategy\nmaker/checker via loop-verifier\n', + ); + + // Skills + await mkdir(path.join(tmpRoot, 'skills', 'loop-triage'), { recursive: true }); + await writeFile( + path.join(tmpRoot, 'skills', 'loop-triage', 'SKILL.md'), + '---\nname: loop-triage\ndescription: Triage skill\nuser_invocable: true\n---\n\n# Loop Triage\nYou are a triage agent.', + ); + + // State files + await writeFile( + path.join(tmpRoot, 'STATE.md'), + '# Loop State\n\nLast run: 2026-06-20T08:00Z\n\n## High Priority\n- Fix CI\n', + ); + + // LOOP.md + await writeFile( + path.join(tmpRoot, 'LOOP.md'), + '# Loop Config\n\n## Budget\nMax tokens/day: 100k\nKill switch: loop-pause-all\n', + ); + + // loop-budget.md + await writeFile( + path.join(tmpRoot, 'loop-budget.md'), + '# Loop Budget\n\nDaily cap: 100k tokens\n', + ); + + // loop-run-log.md + await writeFile( + path.join(tmpRoot, 'loop-run-log.md'), + '# Run Log\n\n- 2026-06-20T08:00Z: daily-triage — report — 45k tokens\n', + ); + + // Safety doc + await mkdir(path.join(tmpRoot, 'docs'), { recursive: true }); + await writeFile( + path.join(tmpRoot, 'docs', 'safety.md'), + '# Safety\n\n## Path Denylists\n- .env\n- credentials\n', + ); + + return tmpRoot; +} + +async function cleanup() { + if (tmpRoot) await rm(tmpRoot, { recursive: true, force: true }); +} + +// ── Tests ────────────────────────────────────────────────────────── + +test('resolveProjectRoot uses LOOP_PROJECT_ROOT env var', async () => { + const orig = process.env.LOOP_PROJECT_ROOT; + process.env.LOOP_PROJECT_ROOT = '/some/path'; + const root = await resolveProjectRoot(); + assert.ok(root.includes('some')); + if (orig !== undefined) process.env.LOOP_PROJECT_ROOT = orig; + else delete process.env.LOOP_PROJECT_ROOT; +}); + +test('resolveProjectRoot uses explicit hint over env', async () => { + const root = await resolveProjectRoot('/explicit/path'); + assert.ok(root.includes('explicit')); +}); + +test('loadRegistry parses YAML correctly', async () => { + const root = await setup(); + try { + const registry = await loadRegistry(root); + assert.ok(registry); + assert.equal(registry.patterns.length, 1); + assert.equal(registry.patterns[0].id, 'daily-triage'); + assert.equal(registry.patterns[0].cost.tokens_noop, 5000); + } finally { + await cleanup(); + } +}); + +test('loadRegistry returns null when missing', async () => { + const empty = await mkdtemp(path.join(tmpdir(), 'mcp-empty-')); + try { + const result = await loadRegistry(empty); + assert.equal(result, null); + } finally { + await rm(empty, { recursive: true, force: true }); + } +}); + +test('listSkills finds skills directories', async () => { + const root = await setup(); + try { + const skills = await listSkills(root); + assert.ok(skills.length >= 1); + const names = skills.map(s => s.name); + assert.ok(names.includes('loop-triage')); + } finally { + await cleanup(); + } +}); + +test('loadSkill returns content for existing skill', async () => { + const root = await setup(); + try { + const skill = await loadSkill(root, 'loop-triage'); + assert.ok(skill); + assert.ok(skill.content.includes('triage')); + } finally { + await cleanup(); + } +}); + +test('loadSkill returns null for missing skill', async () => { + const root = await setup(); + try { + const skill = await loadSkill(root, 'nonexistent'); + assert.equal(skill, null); + } finally { + await cleanup(); + } +}); + +test('loadState reads STATE.md', async () => { + const root = await setup(); + try { + const state = await loadState(root); + assert.ok(state); + assert.ok(state.includes('Fix CI')); + } finally { + await cleanup(); + } +}); + +test('listStateFiles finds existing state files', async () => { + const root = await setup(); + try { + const files = await listStateFiles(root); + assert.ok(files.includes('STATE.md')); + } finally { + await cleanup(); + } +}); + +test('loadLoopConfig reads LOOP.md', async () => { + const root = await setup(); + try { + const config = await loadLoopConfig(root); + assert.ok(config); + assert.ok(config.includes('Budget')); + } finally { + await cleanup(); + } +}); + +test('loadBudget reads loop-budget.md', async () => { + const root = await setup(); + try { + const budget = await loadBudget(root); + assert.ok(budget); + assert.ok(budget.includes('100k')); + } finally { + await cleanup(); + } +}); + +test('loadRunLog reads loop-run-log.md', async () => { + const root = await setup(); + try { + const log = await loadRunLog(root); + assert.ok(log); + assert.ok(log.includes('daily-triage')); + } finally { + await cleanup(); + } +}); + +test('loadSafetyDoc reads docs/safety.md', async () => { + const root = await setup(); + try { + const safety = await loadSafetyDoc(root); + assert.ok(safety); + assert.ok(safety.includes('Denylists')); + } finally { + await cleanup(); + } +}); + +test('listPatternDocs finds .md files in patterns/', async () => { + const root = await setup(); + try { + const docs = await listPatternDocs(root); + assert.ok(docs.includes('daily-triage')); + } finally { + await cleanup(); + } +}); + +test('loadPatternDoc returns content', async () => { + const root = await setup(); + try { + const doc = await loadPatternDoc(root, 'daily-triage'); + assert.ok(doc); + assert.ok(doc.includes('# Daily Triage')); + } finally { + await cleanup(); + } +}); + +test('loadPatternDoc returns null for missing pattern', async () => { + const root = await setup(); + try { + const doc = await loadPatternDoc(root, 'nonexistent'); + assert.equal(doc, null); + } finally { + await cleanup(); + } +}); diff --git a/tools/mcp-server/tsconfig.json b/tools/mcp-server/tsconfig.json new file mode 100644 index 0000000..ef0f184 --- /dev/null +++ b/tools/mcp-server/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "outDir": "dist", + "rootDir": "src", + "strict": true, + "skipLibCheck": true, + "declaration": true + }, + "include": ["src/**/*"] +} From 2be885ed1cd71566bce55f87c7d8d1168257c067 Mon Sep 17 00:00:00 2001 From: TechSphrex TA <42131590+KhaiTrang1995@users.noreply.github.com> Date: Fri, 26 Jun 2026 16:38:36 +0700 Subject: [PATCH 2/4] fix(mcp-server): declare zod as direct dependency + add server integration tests zod was imported in src/index.ts but only resolved transitively via @modelcontextprotocol/sdk, so the build could break if the SDK changed its zod range. Declare it explicitly in dependencies. Add 4 integration tests that spawn the real server over stdio and exercise the index.ts tool/resource handlers (tools/list, loop_list_patterns, loop_estimate_cost, pattern resource read), complementing the existing resolver-level unit tests. Suite now 20/20 passing. Co-Authored-By: Claude Opus 4.8 --- tools/mcp-server/package-lock.json | 3 +- tools/mcp-server/package.json | 3 +- tools/mcp-server/test/server.test.mjs | 115 ++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 2 deletions(-) diff --git a/tools/mcp-server/package-lock.json b/tools/mcp-server/package-lock.json index 1838419..e3d5ac1 100644 --- a/tools/mcp-server/package-lock.json +++ b/tools/mcp-server/package-lock.json @@ -10,7 +10,8 @@ "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "^1.12.1", - "yaml": "^2.8.0" + "yaml": "^2.8.0", + "zod": "^3.25 || ^4.0" }, "bin": { "loop-mcp-server": "dist/index.js" diff --git a/tools/mcp-server/package.json b/tools/mcp-server/package.json index 49f1848..56b568d 100644 --- a/tools/mcp-server/package.json +++ b/tools/mcp-server/package.json @@ -44,7 +44,8 @@ }, "dependencies": { "@modelcontextprotocol/sdk": "^1.12.1", - "yaml": "^2.8.0" + "yaml": "^2.8.0", + "zod": "^3.25 || ^4.0" }, "devDependencies": { "@types/node": "^22.0.0", diff --git a/tools/mcp-server/test/server.test.mjs b/tools/mcp-server/test/server.test.mjs index 0ccfa59..24c9c2b 100644 --- a/tools/mcp-server/test/server.test.mjs +++ b/tools/mcp-server/test/server.test.mjs @@ -3,6 +3,8 @@ import assert from 'node:assert/strict'; import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawn } from 'node:child_process'; import { resolveProjectRoot, @@ -103,6 +105,60 @@ async function cleanup() { if (tmpRoot) await rm(tmpRoot, { recursive: true, force: true }); } +const SERVER_ENTRY = fileURLToPath(new URL('../dist/index.js', import.meta.url)); + +// Spawns the real MCP server over stdio, performs the initialize handshake, +// sends the given requests, and returns the collected JSON-RPC responses +// keyed by id. Exercises the index.ts resource/tool handlers end-to-end. +async function callServer(root, requests) { + const child = spawn(process.execPath, [SERVER_ENTRY], { + env: { ...process.env, LOOP_PROJECT_ROOT: root }, + stdio: ['pipe', 'pipe', 'pipe'], + }); + + const responses = new Map(); + const wantedIds = new Set(requests.map(r => r.id)); + let buffer = ''; + + const done = new Promise((resolve, reject) => { + const timer = setTimeout(() => { + child.kill(); + reject(new Error('server did not respond in time')); + }, 10_000); + + child.stdout.on('data', (chunk) => { + buffer += chunk.toString(); + let idx; + while ((idx = buffer.indexOf('\n')) !== -1) { + const line = buffer.slice(0, idx).trim(); + buffer = buffer.slice(idx + 1); + if (!line) continue; + const msg = JSON.parse(line); + if (msg.id !== undefined && wantedIds.has(msg.id)) { + responses.set(msg.id, msg); + if (responses.size === wantedIds.size) { + clearTimeout(timer); + child.kill(); + resolve(responses); + } + } + } + }); + child.on('error', reject); + }); + + child.stdin.write(JSON.stringify({ + jsonrpc: '2.0', id: 0, method: 'initialize', + params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1.0' } }, + }) + '\n'); + child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n'); + for (const req of requests) { + child.stdin.write(JSON.stringify({ jsonrpc: '2.0', ...req }) + '\n'); + } + + return done; +} + // ── Tests ────────────────────────────────────────────────────────── test('resolveProjectRoot uses LOOP_PROJECT_ROOT env var', async () => { @@ -270,3 +326,62 @@ test('loadPatternDoc returns null for missing pattern', async () => { await cleanup(); } }); + +// ── Integration: real server over stdio ──────────────────────────── + +test('server lists all tools over stdio', async () => { + const root = await setup(); + try { + const res = await callServer(root, [{ id: 1, method: 'tools/list', params: {} }]); + const names = res.get(1).result.tools.map(t => t.name); + assert.equal(names.length, 8); + assert.ok(names.includes('loop_list_patterns')); + assert.ok(names.includes('loop_estimate_cost')); + } finally { + await cleanup(); + } +}); + +test('loop_list_patterns tool returns registry patterns', async () => { + const root = await setup(); + try { + const res = await callServer(root, [{ + id: 1, method: 'tools/call', + params: { name: 'loop_list_patterns', arguments: {} }, + }]); + const text = res.get(1).result.content[0].text; + const parsed = JSON.parse(text); + assert.equal(parsed[0].id, 'daily-triage'); + } finally { + await cleanup(); + } +}); + +test('loop_estimate_cost tool computes a cost table', async () => { + const root = await setup(); + try { + const res = await callServer(root, [{ + id: 1, method: 'tools/call', + params: { name: 'loop_estimate_cost', arguments: { patternId: 'daily-triage', level: 'L2' } }, + }]); + const text = res.get(1).result.content[0].text; + assert.ok(text.includes('Cost Estimate')); + assert.ok(text.includes('runs/day')); + } finally { + await cleanup(); + } +}); + +test('pattern resource is readable over stdio', async () => { + const root = await setup(); + try { + const res = await callServer(root, [{ + id: 1, method: 'resources/read', + params: { uri: 'loop://patterns/daily-triage' }, + }]); + const text = res.get(1).result.contents[0].text; + assert.ok(text.includes('# Daily Triage')); + } finally { + await cleanup(); + } +}); From e00f5327fd4ba0de05c43605be3e0f54f01db8fd Mon Sep 17 00:00:00 2001 From: TechSphrex TA <42131590+KhaiTrang1995@users.noreply.github.com> Date: Thu, 2 Jul 2026 07:00:36 +0700 Subject: [PATCH 3/4] feat(loop-context): stateful memory manager with pruner + circuit breaker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds tools/loop-context — a deterministic, dependency-free manager that sits between an agent loop and its durable memory to prevent the two classic long-run failures: context overflow/rot and stagnant/no-progress loops. Before each iteration it can: - summarize what has been tried (factual rollup, no LLM needed), - prune verbose stack traces, collapse repeated errors, and keep only a recent window of attempts, - inject a compact context block into the next prompt. The circuit breaker escalates to a human on stagnation (same error N× in a row), no-progress (N consecutive failures), token budget, or iteration cap — instead of burning tokens in a hopeless loop. Errors are normalized to a stable signature so "the same error" is recognized across volatile details (line numbers, ports, addresses, temp paths). Ships a CLI (--check/--prune/--inject/--summary/--status, stdin or --ledger) with escalate=exit 2, a library API, 18 tests, and CI gate + build wiring. Co-Authored-By: Claude Opus 4.8 --- .gitignore | 1 + package.json | 5 +- scripts/ci-validate-gates.sh | 5 + tools/loop-context/README.md | 107 +++++ tools/loop-context/dist/cli.d.ts | 2 + tools/loop-context/dist/cli.js | 163 ++++++++ tools/loop-context/dist/context-manager.d.ts | 119 ++++++ tools/loop-context/dist/context-manager.js | 248 ++++++++++++ tools/loop-context/package-lock.json | 54 +++ tools/loop-context/package.json | 51 +++ tools/loop-context/src/cli.ts | 174 +++++++++ tools/loop-context/src/context-manager.ts | 369 ++++++++++++++++++ .../test/context-manager.test.mjs | 199 ++++++++++ tools/loop-context/tsconfig.json | 13 + 14 files changed, 1508 insertions(+), 2 deletions(-) create mode 100644 tools/loop-context/README.md create mode 100644 tools/loop-context/dist/cli.d.ts create mode 100644 tools/loop-context/dist/cli.js create mode 100644 tools/loop-context/dist/context-manager.d.ts create mode 100644 tools/loop-context/dist/context-manager.js create mode 100644 tools/loop-context/package-lock.json create mode 100644 tools/loop-context/package.json create mode 100644 tools/loop-context/src/cli.ts create mode 100644 tools/loop-context/src/context-manager.ts create mode 100644 tools/loop-context/test/context-manager.test.mjs create mode 100644 tools/loop-context/tsconfig.json diff --git a/.gitignore b/.gitignore index b1b965b..ff1a8f7 100644 --- a/.gitignore +++ b/.gitignore @@ -31,6 +31,7 @@ build/ !tools/loop-cost/dist/ !tools/loop-init/dist/ !tools/mcp-server/dist/ +!tools/loop-context/dist/ !tools/goal-audit/dist/ *.egg-info/ diff --git a/package.json b/package.json index 9fd7ccc..e66c7c1 100644 --- a/package.json +++ b/package.json @@ -9,9 +9,10 @@ "test:loop-init": "cd tools/loop-init && npm test", "test:loop-cost": "cd tools/loop-cost && npm test", "test:loop-sync": "cd tools/loop-sync && npm test", + "test:loop-context": "cd tools/loop-context && npm test", "test:mcp-server": "cd tools/mcp-server && npm test", - "test:tools": "npm run test:loop-audit && npm run test:loop-init && npm run test:loop-cost && npm run test:loop-sync && npm run test:mcp-server", - "build:tools": "cd tools/loop-audit && npm run build && cd ../loop-init && npm run build && cd ../loop-cost && npm run build && cd ../loop-sync && npm run build && cd ../mcp-server && npm run build" + "test:tools": "npm run test:loop-audit && npm run test:loop-init && npm run test:loop-cost && npm run test:loop-sync && npm run test:loop-context && npm run test:mcp-server", + "build:tools": "cd tools/loop-audit && npm run build && cd ../loop-init && npm run build && cd ../loop-cost && npm run build && cd ../loop-sync && npm run build && cd ../loop-context && npm run build && cd ../mcp-server && npm run build" }, "devDependencies": { "ajv": "^8.17.1", diff --git a/scripts/ci-validate-gates.sh b/scripts/ci-validate-gates.sh index 70214cc..1255542 100755 --- a/scripts/ci-validate-gates.sh +++ b/scripts/ci-validate-gates.sh @@ -39,6 +39,11 @@ cd ../loop-sync npm ci npm test +echo "Building and testing loop-context…" +cd ../loop-context +npm ci +npm test + echo "Building and testing mcp-server…" cd ../mcp-server npm ci diff --git a/tools/loop-context/README.md b/tools/loop-context/README.md new file mode 100644 index 0000000..3cfef18 --- /dev/null +++ b/tools/loop-context/README.md @@ -0,0 +1,107 @@ +# loop-context + +**Stateful memory manager for agent loops.** Keeps the context window clean and stops runaway loops before they burn tokens. + +Long-running agent loops fail in two classic ways the [loop-engineering docs](../../docs/) warn about: + +- **Context overflow & rot** — conversation history and error logs grow until the model loses the original goal or drowns in stale stack traces. +- **Stagnant / no-progress loops** — the agent retries the same failing action forever, quietly blowing the token budget. + +`loop-context` sits between the agent and its durable memory (`STATE.md`, run logs) and, before each iteration, does three things: + +1. **Summarize** what has been tried and what failed. +2. **Prune** verbose stack traces, collapse repeated errors, and drop stale attempts outside a recent window. +3. **Inject** only the essentials into the next prompt. + +A **circuit breaker** watches iteration count, token spend, stagnation (same error N× in a row), and no-progress (too many consecutive failures) — and escalates to a human instead of looping in vain. + +Everything is **deterministic and dependency-free**: no LLM call is needed to summarize or prune, so it is cheap enough to run on every iteration. + +## Install / run + +```bash +npx @cobusgreyling/loop-context --help +# or from this repo: +cd tools/loop-context && npm install && npm test +``` + +## The ledger + +The tool reads a **run ledger** — a JSON record of the loop's goal and its attempts: + +```json +{ + "goal": "Get the failing migration test to pass", + "attempts": [ + { "iteration": 1, "action": "run migration", "outcome": "failure", + "error": "Error: connect ECONNREFUSED 127.0.0.1:5432", "tokensUsed": 1500 }, + { "iteration": 2, "action": "run migration again", "outcome": "failure", + "error": "Error: connect ECONNREFUSED 127.0.0.1:5432", "tokensUsed": 1400 } + ] +} +``` + +`outcome` is `success | failure | noop`. `error` and `tokensUsed` are optional. + +## Usage + +```bash +# Circuit breaker — exit 0 = continue, 2 = escalate (wire into a loop's control flow) +loop-context --check --ledger run.json + +# Compact context block for the next prompt +loop-context --inject --ledger run.json + +# Factual rollup of the run +loop-context --summary --ledger run.json --json + +# Pruned ledger (recent window, trimmed traces, collapsed repeats) +loop-context --prune --ledger run.json + +# Pipe on stdin +cat run.json | loop-context --check +``` + +### Options + +| Flag | Default | Meaning | +|------|---------|---------| +| `--max-iterations ` | 10 | Hard iteration cap | +| `--stagnation ` | 3 | Escalate when the same error repeats N× in a row | +| `--no-progress ` | 5 | Escalate after N consecutive failures | +| `--token-budget ` | none | Escalate when cumulative tokens reach the cap | +| `--window ` | 5 | Attempts kept when pruning | +| `--max-trace-lines ` | 8 | Stack-trace lines kept when pruning | + +Exit codes: `0` continue · `2` escalate · `1` error. + +## In a loop + +```bash +# inside your loop's control script, before each iteration: +if ! loop-context --check --ledger run.json; then + loop-context --inject --ledger run.json > escalation.md # hand a clean summary to the human + exit 0 # stop instead of retrying +fi +``` + +## Library API + +```ts +import { + checkCircuitBreaker, + pruneLedger, + summarizeAttempts, + buildContextInjection, +} from '@cobusgreyling/loop-context'; + +const decision = checkCircuitBreaker(ledger); +if (decision.escalate) escalateToHuman(decision.reason); +else runNextIteration(buildContextInjection(ledger)); +``` + +## Where it fits + +This is the **Memory / State** primitive of loop engineering made dynamic: `STATE.md` stores state statically; `loop-context` manages it across iterations. See [docs/primitives.md](../../docs/primitives.md) and the [operating & safety](../../docs/) guides. + +MIT · part of [loop-engineering](https://github.com/cobusgreyling/loop-engineering) by Cobus Greyling. diff --git a/tools/loop-context/dist/cli.d.ts b/tools/loop-context/dist/cli.d.ts new file mode 100644 index 0000000..b798801 --- /dev/null +++ b/tools/loop-context/dist/cli.d.ts @@ -0,0 +1,2 @@ +#!/usr/bin/env node +export {}; diff --git a/tools/loop-context/dist/cli.js b/tools/loop-context/dist/cli.js new file mode 100644 index 0000000..e04cf63 --- /dev/null +++ b/tools/loop-context/dist/cli.js @@ -0,0 +1,163 @@ +#!/usr/bin/env node +import { readFile } from 'node:fs/promises'; +import { buildContextInjection, checkCircuitBreaker, pruneLedger, summarizeAttempts, DEFAULT_BREAKER, DEFAULT_PRUNE, } from './context-manager.js'; +function parseArgs(argv) { + const breaker = { ...DEFAULT_BREAKER }; + const prune = { ...DEFAULT_PRUNE }; + let op = 'status'; + let ledger; + let json = false; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === '--help' || a === '-h') + return { help: true, op, json, breaker, prune }; + else if (a === '--ledger' || a === '-f') + ledger = argv[++i]; + else if (a === '--check') + op = 'check'; + else if (a === '--prune') + op = 'prune'; + else if (a === '--inject') + op = 'inject'; + else if (a === '--summary') + op = 'summary'; + else if (a === '--status') + op = 'status'; + else if (a === '--json') + json = true; + else if (a === '--max-iterations') + breaker.maxIterations = Number(argv[++i]); + else if (a === '--stagnation') + breaker.stagnationThreshold = Number(argv[++i]); + else if (a === '--no-progress') + breaker.noProgressThreshold = Number(argv[++i]); + else if (a === '--token-budget') + breaker.tokenBudget = Number(argv[++i]); + else if (a === '--window') + prune.window = Number(argv[++i]); + else if (a === '--max-trace-lines') + prune.maxTraceLines = Number(argv[++i]); + } + return { help: false, op, ledger, json, breaker, prune }; +} +async function readLedger(pathArg) { + const raw = pathArg + ? await readFile(pathArg, 'utf8') + : await readStdin(); + if (!raw.trim()) { + throw new Error('No ledger provided. Pass --ledger or pipe JSON on stdin.'); + } + const parsed = JSON.parse(raw); + if (typeof parsed.goal !== 'string' || !Array.isArray(parsed.attempts)) { + throw new Error('Invalid ledger: expected { goal: string, attempts: Attempt[] }.'); + } + return parsed; +} +function readStdin() { + return new Promise((resolve, reject) => { + let data = ''; + process.stdin.setEncoding('utf8'); + process.stdin.on('data', (c) => (data += c)); + process.stdin.on('end', () => resolve(data)); + process.stdin.on('error', reject); + }); +} +const HELP = `loop-context — stateful memory manager for agent loops + +Keeps a loop's context window clean and stops runaway loops. Reads a run ledger +(JSON) and summarizes, prunes, injects, or applies the circuit breaker. + +Usage: + loop-context [operation] [--ledger ] [options] + cat ledger.json | loop-context --check + +Operations (default: --status): + --check Run the circuit breaker. Exit 0 = continue, 2 = escalate. + --prune Emit a pruned ledger (recent window, trimmed traces, collapsed). + --inject Emit the compact context block for the next prompt. + --summary Emit a factual rollup of the run. + --status Human-readable overview (summary + breaker decision). + +Options: + -f, --ledger Ledger JSON file (default: stdin) + --json Machine-readable output where applicable + --max-iterations Iteration cap (default: ${DEFAULT_BREAKER.maxIterations}) + --stagnation Same-error repeat limit (default: ${DEFAULT_BREAKER.stagnationThreshold}) + --no-progress Consecutive-failure limit (default: ${DEFAULT_BREAKER.noProgressThreshold}) + --token-budget Total token cap (default: none) + --window Attempts kept when pruning (default: ${DEFAULT_PRUNE.window}) + --max-trace-lines Stack-trace lines kept (default: ${DEFAULT_PRUNE.maxTraceLines}) + -h, --help This help + +Ledger shape: + { "goal": "...", "attempts": [ { "iteration": 1, "action": "...", + "outcome": "failure", "error": "...", "tokensUsed": 1200 } ] } + +Exit codes: 0 continue · 2 escalate · 1 error +`; +async function main() { + const args = parseArgs(process.argv.slice(2)); + if (args.help) { + console.log(HELP); + return; + } + const ledger = await readLedger(args.ledger); + switch (args.op) { + case 'check': { + const decision = checkCircuitBreaker(ledger, args.breaker); + if (args.json) + console.log(JSON.stringify(decision, null, 2)); + else + console.log(`${decision.escalate ? 'ESCALATE' : 'CONTINUE'} [${decision.trigger}] — ${decision.reason}`); + process.exitCode = decision.escalate ? 2 : 0; + return; + } + case 'prune': + console.log(JSON.stringify(pruneLedger(ledger, args.prune), null, 2)); + return; + case 'summary': { + const summary = summarizeAttempts(ledger); + if (args.json) + console.log(JSON.stringify(summary, null, 2)); + else + console.log(formatSummary(summary)); + return; + } + case 'inject': + console.log(buildContextInjection(ledger, args.breaker, args.prune)); + return; + case 'status': + default: { + const summary = summarizeAttempts(ledger); + const decision = checkCircuitBreaker(ledger, args.breaker); + console.log(formatSummary(summary)); + console.log(''); + console.log(`Circuit breaker: ${decision.escalate ? 'ESCALATE' : 'CONTINUE'} [${decision.trigger}]`); + console.log(` ${decision.reason}`); + process.exitCode = decision.escalate ? 2 : 0; + return; + } + } +} +function formatSummary(s) { + const lines = []; + lines.push(`Attempts: ${s.totalAttempts} (${s.successes} ok · ${s.failures} failed · ${s.noops} no-op)`); + if (s.tokensUsed) + lines.push(`Tokens used: ${s.tokensUsed}`); + if (s.distinctErrors.length) { + lines.push('Distinct errors (most frequent first):'); + for (const g of s.distinctErrors) + lines.push(` (${g.count}×) ${g.sample}`); + } + if (s.actionsTried.length) { + lines.push('Actions tried:'); + for (const a of s.actionsTried) + lines.push(` - ${a}`); + } + return lines.join('\n'); +} +main().catch((err) => { + const msg = err instanceof Error ? err.message : String(err); + console.error('loop-context failed:', msg); + process.exit(1); +}); diff --git a/tools/loop-context/dist/context-manager.d.ts b/tools/loop-context/dist/context-manager.d.ts new file mode 100644 index 0000000..19f5e5a --- /dev/null +++ b/tools/loop-context/dist/context-manager.d.ts @@ -0,0 +1,119 @@ +/** + * Stateful Memory Manager — Context Manager, Pruner, and Circuit Breaker. + * + * Sits between an agent loop and its durable memory (STATE.md, run logs). + * Before each new iteration it can: summarize what has been tried, prune stale + * or verbose context (long stack traces, repeated errors), and inject only the + * essentials into the next prompt — keeping the context window clean and focused. + * + * The circuit breaker detects the two classic loop failures the docs warn about: + * - stagnant runs (retrying the same error N times) + * - no-progress loops (repeated failures with no success) + * and, together with iteration and token caps, escalates to a human instead of + * burning tokens in a hopeless loop. + * + * All logic here is deterministic and dependency-free — no LLM call is required + * to summarize or prune, so it is cheap to run on every iteration and easy to test. + */ +export type Outcome = 'success' | 'failure' | 'noop'; +export interface Attempt { + /** 1-based iteration number within the run. */ + iteration: number; + /** ISO timestamp of the attempt (optional). */ + timestamp?: string; + /** What the agent tried this iteration (a short description). */ + action: string; + /** Result of the attempt. */ + outcome: Outcome; + /** Raw error message or stack trace, if the attempt failed. */ + error?: string; + /** Tokens spent on this iteration, if tracked. */ + tokensUsed?: number; + /** Set by the pruner when consecutive identical failures are collapsed. */ + repeated?: number; +} +export interface Ledger { + /** The loop's original goal — the anchor the agent must not lose. */ + goal: string; + /** ISO timestamp when the run started (optional). */ + startedAt?: string; + /** Ordered list of attempts, oldest first. */ + attempts: Attempt[]; +} +export interface CircuitBreakerConfig { + /** Hard cap on total iterations before escalating. */ + maxIterations: number; + /** Escalate when the same error signature repeats this many times in a row. */ + stagnationThreshold: number; + /** Escalate after this many consecutive failures with no success in between. */ + noProgressThreshold: number; + /** Optional hard cap on cumulative tokens across the run. */ + tokenBudget?: number; +} +export interface PruneConfig { + /** Max lines to keep from any single stack trace. */ + maxTraceLines: number; + /** Number of most-recent attempts to retain in the pruned ledger. */ + window: number; +} +export declare const DEFAULT_BREAKER: CircuitBreakerConfig; +export declare const DEFAULT_PRUNE: PruneConfig; +/** + * Reduce a raw error / stack trace to a stable signature so that "the same + * error" can be recognized across iterations even when volatile details + * (line numbers, addresses, timestamps, ports, temp paths) differ. + */ +export declare function errorSignature(error: string): string; +export type BreakerTrigger = 'ok' | 'stagnation' | 'no-progress' | 'token-budget' | 'max-iterations'; +export interface BreakerDecision { + /** Whether the loop is cleared to run another iteration. */ + shouldContinue: boolean; + /** Whether the loop must hand off to a human. */ + escalate: boolean; + /** Which condition fired (or 'ok'). */ + trigger: BreakerTrigger; + /** Human-readable explanation. */ + reason: string; + iterations: number; + tokensUsed: number; +} +/** + * Decide whether the loop may continue. Checks the most specific and cheapest- + * to-fix conditions first (stagnation, then no-progress) before the absolute + * caps (token budget, iteration count), so the reported reason is the most + * actionable one when several conditions hold. + */ +export declare function checkCircuitBreaker(ledger: Ledger, config?: CircuitBreakerConfig): BreakerDecision; +/** Truncate a stack trace to its most useful head, noting how much was dropped. */ +export declare function pruneStackTrace(trace: string, maxLines: number): string; +/** + * Produce a lean ledger for injection: keep only the most-recent `window` + * attempts, prune verbose traces, and collapse consecutive identical failures + * into a single entry with a repeat count. The full ledger is untouched — this + * returns a new object. + */ +export declare function pruneLedger(ledger: Ledger, config?: PruneConfig): Ledger; +export interface ErrorGroup { + signature: string; + count: number; + sample: string; +} +export interface AttemptSummary { + totalAttempts: number; + successes: number; + failures: number; + noops: number; + tokensUsed: number; + /** Distinct error signatures, most frequent first. */ + distinctErrors: ErrorGroup[]; + /** Unique actions the agent has already tried. */ + actionsTried: string[]; +} +/** Deterministic factual rollup of the whole run — no LLM required. */ +export declare function summarizeAttempts(ledger: Ledger): AttemptSummary; +/** + * Build the compact context block to prepend to the next prompt. Contains only + * what the agent needs to make progress: the goal, what has already been tried + * (so it does not repeat itself), the last pruned error, and the breaker status. + */ +export declare function buildContextInjection(ledger: Ledger, breaker?: CircuitBreakerConfig, prune?: PruneConfig): string; diff --git a/tools/loop-context/dist/context-manager.js b/tools/loop-context/dist/context-manager.js new file mode 100644 index 0000000..a229f70 --- /dev/null +++ b/tools/loop-context/dist/context-manager.js @@ -0,0 +1,248 @@ +/** + * Stateful Memory Manager — Context Manager, Pruner, and Circuit Breaker. + * + * Sits between an agent loop and its durable memory (STATE.md, run logs). + * Before each new iteration it can: summarize what has been tried, prune stale + * or verbose context (long stack traces, repeated errors), and inject only the + * essentials into the next prompt — keeping the context window clean and focused. + * + * The circuit breaker detects the two classic loop failures the docs warn about: + * - stagnant runs (retrying the same error N times) + * - no-progress loops (repeated failures with no success) + * and, together with iteration and token caps, escalates to a human instead of + * burning tokens in a hopeless loop. + * + * All logic here is deterministic and dependency-free — no LLM call is required + * to summarize or prune, so it is cheap to run on every iteration and easy to test. + */ +export const DEFAULT_BREAKER = { + maxIterations: 10, + stagnationThreshold: 3, + noProgressThreshold: 5, +}; +export const DEFAULT_PRUNE = { + maxTraceLines: 8, + window: 5, +}; +// ── Error normalization ──────────────────────────────────────────── +/** + * Reduce a raw error / stack trace to a stable signature so that "the same + * error" can be recognized across iterations even when volatile details + * (line numbers, addresses, timestamps, ports, temp paths) differ. + */ +export function errorSignature(error) { + const firstLine = error.split('\n').find((l) => l.trim().length > 0) ?? ''; + return firstLine + .trim() + .replace(/\b\d{4}-\d{2}-\d{2}[T ][\d:.]+Z?\b/g, '') // ISO timestamps + .replace(/0x[0-9a-fA-F]+/g, '') // hex addresses + .replace(/[A-Za-z]:[\\/][^\s:]+|(?:[\\/][^\s:/\\]+)+/g, (p) => { + const parts = p.split(/[\\/]/); + return parts[parts.length - 1] || p; // collapse paths to basename + }) + .replace(/:\d+(:\d+)?/g, '') // line:col suffixes + .replace(/\b\d+\b/g, '#') // any remaining numbers (ports, ids, counts) + .replace(/\s+/g, ' ') + .trim(); +} +function totalTokens(ledger) { + return ledger.attempts.reduce((sum, a) => sum + (a.tokensUsed ?? 0), 0); +} +/** Length of the trailing run of failures (since the last non-failure). */ +function trailingFailureRun(attempts) { + const run = []; + for (let i = attempts.length - 1; i >= 0; i--) { + if (attempts[i].outcome !== 'failure') + break; + run.unshift(attempts[i]); + } + return run; +} +/** + * Decide whether the loop may continue. Checks the most specific and cheapest- + * to-fix conditions first (stagnation, then no-progress) before the absolute + * caps (token budget, iteration count), so the reported reason is the most + * actionable one when several conditions hold. + */ +export function checkCircuitBreaker(ledger, config = DEFAULT_BREAKER) { + const iterations = ledger.attempts.length; + const tokensUsed = totalTokens(ledger); + const base = { iterations, tokensUsed }; + const failRun = trailingFailureRun(ledger.attempts); + // Stagnation: the same error signature repeated at the tail. + if (failRun.length >= config.stagnationThreshold) { + const lastSig = errorSignature(failRun[failRun.length - 1].error ?? ''); + let same = 0; + for (let i = failRun.length - 1; i >= 0; i--) { + if (errorSignature(failRun[i].error ?? '') === lastSig) + same++; + else + break; + } + if (same >= config.stagnationThreshold) { + return { + ...base, + shouldContinue: false, + escalate: true, + trigger: 'stagnation', + reason: `Same error repeated ${same}× in a row (threshold ${config.stagnationThreshold}): "${lastSig}". Escalating instead of retrying.`, + }; + } + } + // No-progress: many consecutive failures without a success. + if (failRun.length >= config.noProgressThreshold) { + return { + ...base, + shouldContinue: false, + escalate: true, + trigger: 'no-progress', + reason: `${failRun.length} consecutive failures with no progress (threshold ${config.noProgressThreshold}). Escalating.`, + }; + } + // Token budget: absolute spend cap. + if (config.tokenBudget !== undefined && tokensUsed >= config.tokenBudget) { + return { + ...base, + shouldContinue: false, + escalate: true, + trigger: 'token-budget', + reason: `Token budget reached (${tokensUsed} ≥ ${config.tokenBudget}). Escalating to avoid cost blowup.`, + }; + } + // Iteration cap: absolute count. + if (iterations >= config.maxIterations) { + return { + ...base, + shouldContinue: false, + escalate: true, + trigger: 'max-iterations', + reason: `Iteration cap reached (${iterations} ≥ ${config.maxIterations}). Escalating.`, + }; + } + return { + ...base, + shouldContinue: true, + escalate: false, + trigger: 'ok', + reason: 'Within limits — cleared to continue.', + }; +} +// ── Pruning ──────────────────────────────────────────────────────── +/** Truncate a stack trace to its most useful head, noting how much was dropped. */ +export function pruneStackTrace(trace, maxLines) { + const lines = trace.split('\n'); + if (lines.length <= maxLines) + return trace.trim(); + const kept = lines.slice(0, maxLines).join('\n').trimEnd(); + const omitted = lines.length - maxLines; + return `${kept}\n … (${omitted} more line${omitted === 1 ? '' : 's'} pruned)`; +} +/** + * Produce a lean ledger for injection: keep only the most-recent `window` + * attempts, prune verbose traces, and collapse consecutive identical failures + * into a single entry with a repeat count. The full ledger is untouched — this + * returns a new object. + */ +export function pruneLedger(ledger, config = DEFAULT_PRUNE) { + const recent = ledger.attempts.slice(-config.window); + const collapsed = []; + for (const attempt of recent) { + const pruned = { + ...attempt, + ...(attempt.error !== undefined + ? { error: pruneStackTrace(attempt.error, config.maxTraceLines) } + : {}), + }; + const prev = collapsed[collapsed.length - 1]; + const sameFailure = prev !== undefined && + prev.outcome === 'failure' && + pruned.outcome === 'failure' && + errorSignature(prev.error ?? '') === errorSignature(pruned.error ?? ''); + if (sameFailure) { + prev.repeated = (prev.repeated ?? 1) + 1; + prev.iteration = pruned.iteration; // advance to the latest iteration + } + else { + collapsed.push(pruned); + } + } + return { goal: ledger.goal, startedAt: ledger.startedAt, attempts: collapsed }; +} +/** Deterministic factual rollup of the whole run — no LLM required. */ +export function summarizeAttempts(ledger) { + const groups = new Map(); + const actions = new Set(); + let successes = 0; + let failures = 0; + let noops = 0; + for (const a of ledger.attempts) { + actions.add(a.action); + if (a.outcome === 'success') + successes++; + else if (a.outcome === 'noop') + noops++; + else { + failures++; + if (a.error) { + const sig = errorSignature(a.error); + const existing = groups.get(sig); + if (existing) + existing.count++; + else + groups.set(sig, { signature: sig, count: 1, sample: a.error.split('\n')[0].trim() }); + } + } + } + return { + totalAttempts: ledger.attempts.length, + successes, + failures, + noops, + tokensUsed: totalTokens(ledger), + distinctErrors: [...groups.values()].sort((a, b) => b.count - a.count), + actionsTried: [...actions], + }; +} +// ── Injection ────────────────────────────────────────────────────── +/** + * Build the compact context block to prepend to the next prompt. Contains only + * what the agent needs to make progress: the goal, what has already been tried + * (so it does not repeat itself), the last pruned error, and the breaker status. + */ +export function buildContextInjection(ledger, breaker = DEFAULT_BREAKER, prune = DEFAULT_PRUNE) { + const summary = summarizeAttempts(ledger); + const decision = checkCircuitBreaker(ledger, breaker); + const pruned = pruneLedger(ledger, prune); + const lines = []; + lines.push('## Loop Context (managed)'); + lines.push(''); + lines.push(`**Goal:** ${ledger.goal}`); + lines.push(`**Progress:** iteration ${summary.totalAttempts} · ${summary.successes} ok · ${summary.failures} failed` + + (summary.tokensUsed ? ` · ${summary.tokensUsed} tokens` : '')); + lines.push(''); + if (summary.actionsTried.length > 0) { + lines.push('**Already tried (do NOT repeat):**'); + for (const action of summary.actionsTried) + lines.push(`- ${action}`); + lines.push(''); + } + if (summary.distinctErrors.length > 0) { + lines.push('**Failure patterns:**'); + for (const g of summary.distinctErrors) { + lines.push(`- (${g.count}×) ${g.sample}`); + } + lines.push(''); + } + const lastFail = [...pruned.attempts].reverse().find((a) => a.outcome === 'failure'); + if (lastFail?.error) { + lines.push('**Most recent error (pruned):**'); + lines.push('```'); + lines.push(lastFail.error); + lines.push('```'); + lines.push(''); + } + lines.push(decision.escalate + ? `> STOP — circuit breaker tripped (${decision.trigger}). ${decision.reason}` + : `> Circuit breaker: OK (${decision.iterations}/${breaker.maxIterations} iterations used).`); + return lines.join('\n'); +} diff --git a/tools/loop-context/package-lock.json b/tools/loop-context/package-lock.json new file mode 100644 index 0000000..b6db3e1 --- /dev/null +++ b/tools/loop-context/package-lock.json @@ -0,0 +1,54 @@ +{ + "name": "@cobusgreyling/loop-context", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@cobusgreyling/loop-context", + "version": "1.0.0", + "license": "MIT", + "bin": { + "loop-context": "dist/cli.js" + }, + "devDependencies": { + "@types/node": "^20.0.0", + "typescript": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/node": { + "version": "20.19.43", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", + "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/tools/loop-context/package.json b/tools/loop-context/package.json new file mode 100644 index 0000000..2315a38 --- /dev/null +++ b/tools/loop-context/package.json @@ -0,0 +1,51 @@ +{ + "name": "@cobusgreyling/loop-context", + "version": "1.0.0", + "description": "Stateful memory manager for agent loops — summarize, prune, and inject context, with a circuit breaker that escalates stagnant or no-progress runs instead of burning tokens.", + "type": "module", + "bin": { + "loop-context": "dist/cli.js" + }, + "files": [ + "dist", + "README.md" + ], + "scripts": { + "build": "tsc && chmod +x dist/cli.js", + "test": "npm run build && node --test test/context-manager.test.mjs", + "prepublishOnly": "npm test", + "start": "node dist/cli.js" + }, + "engines": { + "node": ">=18" + }, + "keywords": [ + "loop-engineering", + "ai-agents", + "coding-agents", + "context-management", + "circuit-breaker", + "memory", + "claude-code", + "grok", + "devtools" + ], + "author": "Cobus Greyling", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/cobusgreyling/loop-engineering.git", + "directory": "tools/loop-context" + }, + "homepage": "https://cobusgreyling.github.io/loop-engineering/", + "bugs": { + "url": "https://github.com/cobusgreyling/loop-engineering/issues" + }, + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@types/node": "^20.0.0", + "typescript": "^5.0.0" + } +} diff --git a/tools/loop-context/src/cli.ts b/tools/loop-context/src/cli.ts new file mode 100644 index 0000000..d9dbc87 --- /dev/null +++ b/tools/loop-context/src/cli.ts @@ -0,0 +1,174 @@ +#!/usr/bin/env node +import { readFile } from 'node:fs/promises'; +import { + buildContextInjection, + checkCircuitBreaker, + pruneLedger, + summarizeAttempts, + DEFAULT_BREAKER, + DEFAULT_PRUNE, + type Ledger, + type CircuitBreakerConfig, + type PruneConfig, +} from './context-manager.js'; + +type Op = 'check' | 'prune' | 'inject' | 'summary' | 'status'; + +interface Args { + help: boolean; + op: Op; + ledger?: string; + json: boolean; + breaker: CircuitBreakerConfig; + prune: PruneConfig; +} + +function parseArgs(argv: string[]): Args { + const breaker: CircuitBreakerConfig = { ...DEFAULT_BREAKER }; + const prune: PruneConfig = { ...DEFAULT_PRUNE }; + let op: Op = 'status'; + let ledger: string | undefined; + let json = false; + + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === '--help' || a === '-h') return { help: true, op, json, breaker, prune }; + else if (a === '--ledger' || a === '-f') ledger = argv[++i]; + else if (a === '--check') op = 'check'; + else if (a === '--prune') op = 'prune'; + else if (a === '--inject') op = 'inject'; + else if (a === '--summary') op = 'summary'; + else if (a === '--status') op = 'status'; + else if (a === '--json') json = true; + else if (a === '--max-iterations') breaker.maxIterations = Number(argv[++i]); + else if (a === '--stagnation') breaker.stagnationThreshold = Number(argv[++i]); + else if (a === '--no-progress') breaker.noProgressThreshold = Number(argv[++i]); + else if (a === '--token-budget') breaker.tokenBudget = Number(argv[++i]); + else if (a === '--window') prune.window = Number(argv[++i]); + else if (a === '--max-trace-lines') prune.maxTraceLines = Number(argv[++i]); + } + + return { help: false, op, ledger, json, breaker, prune }; +} + +async function readLedger(pathArg?: string): Promise { + const raw = pathArg + ? await readFile(pathArg, 'utf8') + : await readStdin(); + if (!raw.trim()) { + throw new Error('No ledger provided. Pass --ledger or pipe JSON on stdin.'); + } + const parsed = JSON.parse(raw) as Ledger; + if (typeof parsed.goal !== 'string' || !Array.isArray(parsed.attempts)) { + throw new Error('Invalid ledger: expected { goal: string, attempts: Attempt[] }.'); + } + return parsed; +} + +function readStdin(): Promise { + return new Promise((resolve, reject) => { + let data = ''; + process.stdin.setEncoding('utf8'); + process.stdin.on('data', (c) => (data += c)); + process.stdin.on('end', () => resolve(data)); + process.stdin.on('error', reject); + }); +} + +const HELP = `loop-context — stateful memory manager for agent loops + +Keeps a loop's context window clean and stops runaway loops. Reads a run ledger +(JSON) and summarizes, prunes, injects, or applies the circuit breaker. + +Usage: + loop-context [operation] [--ledger ] [options] + cat ledger.json | loop-context --check + +Operations (default: --status): + --check Run the circuit breaker. Exit 0 = continue, 2 = escalate. + --prune Emit a pruned ledger (recent window, trimmed traces, collapsed). + --inject Emit the compact context block for the next prompt. + --summary Emit a factual rollup of the run. + --status Human-readable overview (summary + breaker decision). + +Options: + -f, --ledger Ledger JSON file (default: stdin) + --json Machine-readable output where applicable + --max-iterations Iteration cap (default: ${DEFAULT_BREAKER.maxIterations}) + --stagnation Same-error repeat limit (default: ${DEFAULT_BREAKER.stagnationThreshold}) + --no-progress Consecutive-failure limit (default: ${DEFAULT_BREAKER.noProgressThreshold}) + --token-budget Total token cap (default: none) + --window Attempts kept when pruning (default: ${DEFAULT_PRUNE.window}) + --max-trace-lines Stack-trace lines kept (default: ${DEFAULT_PRUNE.maxTraceLines}) + -h, --help This help + +Ledger shape: + { "goal": "...", "attempts": [ { "iteration": 1, "action": "...", + "outcome": "failure", "error": "...", "tokensUsed": 1200 } ] } + +Exit codes: 0 continue · 2 escalate · 1 error +`; + +async function main() { + const args = parseArgs(process.argv.slice(2)); + if (args.help) { + console.log(HELP); + return; + } + + const ledger = await readLedger(args.ledger); + + switch (args.op) { + case 'check': { + const decision = checkCircuitBreaker(ledger, args.breaker); + if (args.json) console.log(JSON.stringify(decision, null, 2)); + else console.log(`${decision.escalate ? 'ESCALATE' : 'CONTINUE'} [${decision.trigger}] — ${decision.reason}`); + process.exitCode = decision.escalate ? 2 : 0; + return; + } + case 'prune': + console.log(JSON.stringify(pruneLedger(ledger, args.prune), null, 2)); + return; + case 'summary': { + const summary = summarizeAttempts(ledger); + if (args.json) console.log(JSON.stringify(summary, null, 2)); + else console.log(formatSummary(summary)); + return; + } + case 'inject': + console.log(buildContextInjection(ledger, args.breaker, args.prune)); + return; + case 'status': + default: { + const summary = summarizeAttempts(ledger); + const decision = checkCircuitBreaker(ledger, args.breaker); + console.log(formatSummary(summary)); + console.log(''); + console.log(`Circuit breaker: ${decision.escalate ? 'ESCALATE' : 'CONTINUE'} [${decision.trigger}]`); + console.log(` ${decision.reason}`); + process.exitCode = decision.escalate ? 2 : 0; + return; + } + } +} + +function formatSummary(s: ReturnType): string { + const lines: string[] = []; + lines.push(`Attempts: ${s.totalAttempts} (${s.successes} ok · ${s.failures} failed · ${s.noops} no-op)`); + if (s.tokensUsed) lines.push(`Tokens used: ${s.tokensUsed}`); + if (s.distinctErrors.length) { + lines.push('Distinct errors (most frequent first):'); + for (const g of s.distinctErrors) lines.push(` (${g.count}×) ${g.sample}`); + } + if (s.actionsTried.length) { + lines.push('Actions tried:'); + for (const a of s.actionsTried) lines.push(` - ${a}`); + } + return lines.join('\n'); +} + +main().catch((err: unknown) => { + const msg = err instanceof Error ? err.message : String(err); + console.error('loop-context failed:', msg); + process.exit(1); +}); diff --git a/tools/loop-context/src/context-manager.ts b/tools/loop-context/src/context-manager.ts new file mode 100644 index 0000000..376ac6e --- /dev/null +++ b/tools/loop-context/src/context-manager.ts @@ -0,0 +1,369 @@ +/** + * Stateful Memory Manager — Context Manager, Pruner, and Circuit Breaker. + * + * Sits between an agent loop and its durable memory (STATE.md, run logs). + * Before each new iteration it can: summarize what has been tried, prune stale + * or verbose context (long stack traces, repeated errors), and inject only the + * essentials into the next prompt — keeping the context window clean and focused. + * + * The circuit breaker detects the two classic loop failures the docs warn about: + * - stagnant runs (retrying the same error N times) + * - no-progress loops (repeated failures with no success) + * and, together with iteration and token caps, escalates to a human instead of + * burning tokens in a hopeless loop. + * + * All logic here is deterministic and dependency-free — no LLM call is required + * to summarize or prune, so it is cheap to run on every iteration and easy to test. + */ + +export type Outcome = 'success' | 'failure' | 'noop'; + +export interface Attempt { + /** 1-based iteration number within the run. */ + iteration: number; + /** ISO timestamp of the attempt (optional). */ + timestamp?: string; + /** What the agent tried this iteration (a short description). */ + action: string; + /** Result of the attempt. */ + outcome: Outcome; + /** Raw error message or stack trace, if the attempt failed. */ + error?: string; + /** Tokens spent on this iteration, if tracked. */ + tokensUsed?: number; + /** Set by the pruner when consecutive identical failures are collapsed. */ + repeated?: number; +} + +export interface Ledger { + /** The loop's original goal — the anchor the agent must not lose. */ + goal: string; + /** ISO timestamp when the run started (optional). */ + startedAt?: string; + /** Ordered list of attempts, oldest first. */ + attempts: Attempt[]; +} + +export interface CircuitBreakerConfig { + /** Hard cap on total iterations before escalating. */ + maxIterations: number; + /** Escalate when the same error signature repeats this many times in a row. */ + stagnationThreshold: number; + /** Escalate after this many consecutive failures with no success in between. */ + noProgressThreshold: number; + /** Optional hard cap on cumulative tokens across the run. */ + tokenBudget?: number; +} + +export interface PruneConfig { + /** Max lines to keep from any single stack trace. */ + maxTraceLines: number; + /** Number of most-recent attempts to retain in the pruned ledger. */ + window: number; +} + +export const DEFAULT_BREAKER: CircuitBreakerConfig = { + maxIterations: 10, + stagnationThreshold: 3, + noProgressThreshold: 5, +}; + +export const DEFAULT_PRUNE: PruneConfig = { + maxTraceLines: 8, + window: 5, +}; + +// ── Error normalization ──────────────────────────────────────────── + +/** + * Reduce a raw error / stack trace to a stable signature so that "the same + * error" can be recognized across iterations even when volatile details + * (line numbers, addresses, timestamps, ports, temp paths) differ. + */ +export function errorSignature(error: string): string { + const firstLine = error.split('\n').find((l) => l.trim().length > 0) ?? ''; + return firstLine + .trim() + .replace(/\b\d{4}-\d{2}-\d{2}[T ][\d:.]+Z?\b/g, '') // ISO timestamps + .replace(/0x[0-9a-fA-F]+/g, '') // hex addresses + .replace(/[A-Za-z]:[\\/][^\s:]+|(?:[\\/][^\s:/\\]+)+/g, (p) => { + const parts = p.split(/[\\/]/); + return parts[parts.length - 1] || p; // collapse paths to basename + }) + .replace(/:\d+(:\d+)?/g, '') // line:col suffixes + .replace(/\b\d+\b/g, '#') // any remaining numbers (ports, ids, counts) + .replace(/\s+/g, ' ') + .trim(); +} + +// ── Circuit breaker ──────────────────────────────────────────────── + +export type BreakerTrigger = + | 'ok' + | 'stagnation' + | 'no-progress' + | 'token-budget' + | 'max-iterations'; + +export interface BreakerDecision { + /** Whether the loop is cleared to run another iteration. */ + shouldContinue: boolean; + /** Whether the loop must hand off to a human. */ + escalate: boolean; + /** Which condition fired (or 'ok'). */ + trigger: BreakerTrigger; + /** Human-readable explanation. */ + reason: string; + iterations: number; + tokensUsed: number; +} + +function totalTokens(ledger: Ledger): number { + return ledger.attempts.reduce((sum, a) => sum + (a.tokensUsed ?? 0), 0); +} + +/** Length of the trailing run of failures (since the last non-failure). */ +function trailingFailureRun(attempts: Attempt[]): Attempt[] { + const run: Attempt[] = []; + for (let i = attempts.length - 1; i >= 0; i--) { + if (attempts[i].outcome !== 'failure') break; + run.unshift(attempts[i]); + } + return run; +} + +/** + * Decide whether the loop may continue. Checks the most specific and cheapest- + * to-fix conditions first (stagnation, then no-progress) before the absolute + * caps (token budget, iteration count), so the reported reason is the most + * actionable one when several conditions hold. + */ +export function checkCircuitBreaker( + ledger: Ledger, + config: CircuitBreakerConfig = DEFAULT_BREAKER, +): BreakerDecision { + const iterations = ledger.attempts.length; + const tokensUsed = totalTokens(ledger); + const base = { iterations, tokensUsed }; + + const failRun = trailingFailureRun(ledger.attempts); + + // Stagnation: the same error signature repeated at the tail. + if (failRun.length >= config.stagnationThreshold) { + const lastSig = errorSignature(failRun[failRun.length - 1].error ?? ''); + let same = 0; + for (let i = failRun.length - 1; i >= 0; i--) { + if (errorSignature(failRun[i].error ?? '') === lastSig) same++; + else break; + } + if (same >= config.stagnationThreshold) { + return { + ...base, + shouldContinue: false, + escalate: true, + trigger: 'stagnation', + reason: `Same error repeated ${same}× in a row (threshold ${config.stagnationThreshold}): "${lastSig}". Escalating instead of retrying.`, + }; + } + } + + // No-progress: many consecutive failures without a success. + if (failRun.length >= config.noProgressThreshold) { + return { + ...base, + shouldContinue: false, + escalate: true, + trigger: 'no-progress', + reason: `${failRun.length} consecutive failures with no progress (threshold ${config.noProgressThreshold}). Escalating.`, + }; + } + + // Token budget: absolute spend cap. + if (config.tokenBudget !== undefined && tokensUsed >= config.tokenBudget) { + return { + ...base, + shouldContinue: false, + escalate: true, + trigger: 'token-budget', + reason: `Token budget reached (${tokensUsed} ≥ ${config.tokenBudget}). Escalating to avoid cost blowup.`, + }; + } + + // Iteration cap: absolute count. + if (iterations >= config.maxIterations) { + return { + ...base, + shouldContinue: false, + escalate: true, + trigger: 'max-iterations', + reason: `Iteration cap reached (${iterations} ≥ ${config.maxIterations}). Escalating.`, + }; + } + + return { + ...base, + shouldContinue: true, + escalate: false, + trigger: 'ok', + reason: 'Within limits — cleared to continue.', + }; +} + +// ── Pruning ──────────────────────────────────────────────────────── + +/** Truncate a stack trace to its most useful head, noting how much was dropped. */ +export function pruneStackTrace(trace: string, maxLines: number): string { + const lines = trace.split('\n'); + if (lines.length <= maxLines) return trace.trim(); + const kept = lines.slice(0, maxLines).join('\n').trimEnd(); + const omitted = lines.length - maxLines; + return `${kept}\n … (${omitted} more line${omitted === 1 ? '' : 's'} pruned)`; +} + +/** + * Produce a lean ledger for injection: keep only the most-recent `window` + * attempts, prune verbose traces, and collapse consecutive identical failures + * into a single entry with a repeat count. The full ledger is untouched — this + * returns a new object. + */ +export function pruneLedger(ledger: Ledger, config: PruneConfig = DEFAULT_PRUNE): Ledger { + const recent = ledger.attempts.slice(-config.window); + + const collapsed: Attempt[] = []; + for (const attempt of recent) { + const pruned: Attempt = { + ...attempt, + ...(attempt.error !== undefined + ? { error: pruneStackTrace(attempt.error, config.maxTraceLines) } + : {}), + }; + + const prev = collapsed[collapsed.length - 1]; + const sameFailure = + prev !== undefined && + prev.outcome === 'failure' && + pruned.outcome === 'failure' && + errorSignature(prev.error ?? '') === errorSignature(pruned.error ?? ''); + + if (sameFailure) { + prev.repeated = (prev.repeated ?? 1) + 1; + prev.iteration = pruned.iteration; // advance to the latest iteration + } else { + collapsed.push(pruned); + } + } + + return { goal: ledger.goal, startedAt: ledger.startedAt, attempts: collapsed }; +} + +// ── Summarization ────────────────────────────────────────────────── + +export interface ErrorGroup { + signature: string; + count: number; + sample: string; +} + +export interface AttemptSummary { + totalAttempts: number; + successes: number; + failures: number; + noops: number; + tokensUsed: number; + /** Distinct error signatures, most frequent first. */ + distinctErrors: ErrorGroup[]; + /** Unique actions the agent has already tried. */ + actionsTried: string[]; +} + +/** Deterministic factual rollup of the whole run — no LLM required. */ +export function summarizeAttempts(ledger: Ledger): AttemptSummary { + const groups = new Map(); + const actions = new Set(); + let successes = 0; + let failures = 0; + let noops = 0; + + for (const a of ledger.attempts) { + actions.add(a.action); + if (a.outcome === 'success') successes++; + else if (a.outcome === 'noop') noops++; + else { + failures++; + if (a.error) { + const sig = errorSignature(a.error); + const existing = groups.get(sig); + if (existing) existing.count++; + else groups.set(sig, { signature: sig, count: 1, sample: a.error.split('\n')[0].trim() }); + } + } + } + + return { + totalAttempts: ledger.attempts.length, + successes, + failures, + noops, + tokensUsed: totalTokens(ledger), + distinctErrors: [...groups.values()].sort((a, b) => b.count - a.count), + actionsTried: [...actions], + }; +} + +// ── Injection ────────────────────────────────────────────────────── + +/** + * Build the compact context block to prepend to the next prompt. Contains only + * what the agent needs to make progress: the goal, what has already been tried + * (so it does not repeat itself), the last pruned error, and the breaker status. + */ +export function buildContextInjection( + ledger: Ledger, + breaker: CircuitBreakerConfig = DEFAULT_BREAKER, + prune: PruneConfig = DEFAULT_PRUNE, +): string { + const summary = summarizeAttempts(ledger); + const decision = checkCircuitBreaker(ledger, breaker); + const pruned = pruneLedger(ledger, prune); + const lines: string[] = []; + + lines.push('## Loop Context (managed)'); + lines.push(''); + lines.push(`**Goal:** ${ledger.goal}`); + lines.push( + `**Progress:** iteration ${summary.totalAttempts} · ${summary.successes} ok · ${summary.failures} failed` + + (summary.tokensUsed ? ` · ${summary.tokensUsed} tokens` : ''), + ); + lines.push(''); + + if (summary.actionsTried.length > 0) { + lines.push('**Already tried (do NOT repeat):**'); + for (const action of summary.actionsTried) lines.push(`- ${action}`); + lines.push(''); + } + + if (summary.distinctErrors.length > 0) { + lines.push('**Failure patterns:**'); + for (const g of summary.distinctErrors) { + lines.push(`- (${g.count}×) ${g.sample}`); + } + lines.push(''); + } + + const lastFail = [...pruned.attempts].reverse().find((a) => a.outcome === 'failure'); + if (lastFail?.error) { + lines.push('**Most recent error (pruned):**'); + lines.push('```'); + lines.push(lastFail.error); + lines.push('```'); + lines.push(''); + } + + lines.push( + decision.escalate + ? `> STOP — circuit breaker tripped (${decision.trigger}). ${decision.reason}` + : `> Circuit breaker: OK (${decision.iterations}/${breaker.maxIterations} iterations used).`, + ); + + return lines.join('\n'); +} diff --git a/tools/loop-context/test/context-manager.test.mjs b/tools/loop-context/test/context-manager.test.mjs new file mode 100644 index 0000000..43b3c95 --- /dev/null +++ b/tools/loop-context/test/context-manager.test.mjs @@ -0,0 +1,199 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + errorSignature, + checkCircuitBreaker, + pruneStackTrace, + pruneLedger, + summarizeAttempts, + buildContextInjection, + DEFAULT_BREAKER, + DEFAULT_PRUNE, +} from '../dist/context-manager.js'; + +function attempt(iteration, outcome, opts = {}) { + return { iteration, action: opts.action ?? `try ${iteration}`, outcome, ...opts }; +} + +function ledger(attempts, goal = 'make the build green') { + return { goal, attempts }; +} + +// ── errorSignature ───────────────────────────────────────────────── + +test('errorSignature normalizes volatile details to a stable key', () => { + const a = errorSignature('TypeError: cannot read x at /home/u/app/foo.js:12:5'); + const b = errorSignature('TypeError: cannot read x at /tmp/build/foo.js:88:9'); + assert.equal(a, b); +}); + +test('errorSignature collapses ports and addresses', () => { + const a = errorSignature('Error: connect ECONNREFUSED 127.0.0.1:5432'); + const b = errorSignature('Error: connect ECONNREFUSED 127.0.0.1:5433'); + assert.equal(a, b); +}); + +test('errorSignature keeps genuinely different errors distinct', () => { + const a = errorSignature('TypeError: undefined is not a function'); + const b = errorSignature('ReferenceError: foo is not defined'); + assert.notEqual(a, b); +}); + +// ── circuit breaker: stagnation ──────────────────────────────────── + +test('breaker trips on stagnation (same error 3× in a row)', () => { + const err = 'Error: connect ECONNREFUSED 127.0.0.1:5432'; + const l = ledger([ + attempt(1, 'failure', { error: err }), + attempt(2, 'failure', { error: err }), + attempt(3, 'failure', { error: err }), + ]); + const d = checkCircuitBreaker(l); + assert.equal(d.escalate, true); + assert.equal(d.trigger, 'stagnation'); + assert.equal(d.shouldContinue, false); +}); + +test('breaker does not trip when errors differ each time', () => { + const l = ledger([ + attempt(1, 'failure', { error: 'TypeError: a' }), + attempt(2, 'failure', { error: 'ReferenceError: b' }), + ]); + const d = checkCircuitBreaker(l); + assert.equal(d.escalate, false); + assert.equal(d.trigger, 'ok'); +}); + +test('breaker stagnation resets after a success', () => { + const err = 'Error: boom'; + const l = ledger([ + attempt(1, 'failure', { error: err }), + attempt(2, 'failure', { error: err }), + attempt(3, 'success'), + attempt(4, 'failure', { error: err }), + ]); + const d = checkCircuitBreaker(l); + assert.equal(d.escalate, false, 'trailing failure run is only 1 after the success'); +}); + +// ── circuit breaker: no-progress ─────────────────────────────────── + +test('breaker trips on no-progress (consecutive failures, distinct errors)', () => { + const l = ledger([ + attempt(1, 'failure', { error: 'e1' }), + attempt(2, 'failure', { error: 'e2' }), + attempt(3, 'failure', { error: 'e3' }), + attempt(4, 'failure', { error: 'e4' }), + attempt(5, 'failure', { error: 'e5' }), + ]); + const d = checkCircuitBreaker(l, { ...DEFAULT_BREAKER, stagnationThreshold: 99 }); + assert.equal(d.escalate, true); + assert.equal(d.trigger, 'no-progress'); +}); + +// ── circuit breaker: caps ────────────────────────────────────────── + +test('breaker trips on token budget', () => { + const l = ledger([ + attempt(1, 'noop', { tokensUsed: 600 }), + attempt(2, 'noop', { tokensUsed: 600 }), + ]); + const d = checkCircuitBreaker(l, { ...DEFAULT_BREAKER, tokenBudget: 1000 }); + assert.equal(d.trigger, 'token-budget'); + assert.equal(d.tokensUsed, 1200); +}); + +test('breaker trips on iteration cap', () => { + const attempts = []; + for (let i = 1; i <= 10; i++) attempts.push(attempt(i, 'noop')); + const d = checkCircuitBreaker(ledger(attempts), { ...DEFAULT_BREAKER, maxIterations: 10 }); + assert.equal(d.trigger, 'max-iterations'); +}); + +test('breaker clears an empty ledger', () => { + const d = checkCircuitBreaker(ledger([])); + assert.equal(d.shouldContinue, true); + assert.equal(d.iterations, 0); +}); + +// ── pruning ──────────────────────────────────────────────────────── + +test('pruneStackTrace keeps head and notes omissions', () => { + const trace = Array.from({ length: 20 }, (_, i) => `line ${i}`).join('\n'); + const pruned = pruneStackTrace(trace, 5); + assert.ok(pruned.includes('line 0')); + assert.ok(pruned.includes('15 more lines pruned')); + assert.ok(!pruned.includes('line 19')); +}); + +test('pruneStackTrace leaves short traces intact', () => { + const trace = 'line 0\nline 1'; + assert.equal(pruneStackTrace(trace, 5), trace); +}); + +test('pruneLedger keeps only the recent window', () => { + const attempts = []; + for (let i = 1; i <= 12; i++) attempts.push(attempt(i, 'noop')); + const pruned = pruneLedger(ledger(attempts), { ...DEFAULT_PRUNE, window: 3 }); + assert.equal(pruned.attempts.length, 3); + assert.equal(pruned.attempts[2].iteration, 12); +}); + +test('pruneLedger collapses consecutive identical failures with a count', () => { + const err = 'Error: same thing'; + const l = ledger([ + attempt(1, 'failure', { error: err }), + attempt(2, 'failure', { error: err }), + attempt(3, 'failure', { error: err }), + ]); + const pruned = pruneLedger(l, { ...DEFAULT_PRUNE, window: 5 }); + assert.equal(pruned.attempts.length, 1); + assert.equal(pruned.attempts[0].repeated, 3); + assert.equal(pruned.attempts[0].iteration, 3); +}); + +test('pruneLedger does not mutate the input ledger', () => { + const l = ledger([attempt(1, 'failure', { error: 'x'.repeat(10) + '\n'.repeat(20) })]); + const before = JSON.stringify(l); + pruneLedger(l); + assert.equal(JSON.stringify(l), before); +}); + +// ── summarization ────────────────────────────────────────────────── + +test('summarizeAttempts groups errors by signature, most frequent first', () => { + const l = ledger([ + attempt(1, 'failure', { error: 'Error: connect ECONNREFUSED 127.0.0.1:5432', action: 'run migration' }), + attempt(2, 'failure', { error: 'Error: connect ECONNREFUSED 127.0.0.1:5433', action: 'run migration' }), + attempt(3, 'failure', { error: 'TypeError: x', action: 'patch code' }), + attempt(4, 'success', { action: 'patch code' }), + ]); + const s = summarizeAttempts(l); + assert.equal(s.totalAttempts, 4); + assert.equal(s.failures, 3); + assert.equal(s.successes, 1); + assert.equal(s.distinctErrors[0].count, 2, 'ECONNREFUSED collapses to one group of 2'); + assert.deepEqual(s.actionsTried, ['run migration', 'patch code']); +}); + +// ── injection ────────────────────────────────────────────────────── + +test('buildContextInjection includes goal, tried actions, and breaker status', () => { + const err = 'Error: boom'; + const l = ledger([ + attempt(1, 'failure', { error: err, action: 'approach A' }), + attempt(2, 'failure', { error: err, action: 'approach A' }), + attempt(3, 'failure', { error: err, action: 'approach A' }), + ]); + const block = buildContextInjection(l); + assert.ok(block.includes('make the build green')); + assert.ok(block.includes('approach A')); + assert.ok(block.includes('do NOT repeat')); + assert.ok(block.includes('STOP'), 'stagnation should surface a STOP directive'); +}); + +test('buildContextInjection shows OK status for a healthy run', () => { + const l = ledger([attempt(1, 'noop'), attempt(2, 'success')]); + const block = buildContextInjection(l); + assert.ok(block.includes('Circuit breaker: OK')); +}); diff --git a/tools/loop-context/tsconfig.json b/tools/loop-context/tsconfig.json new file mode 100644 index 0000000..ef0f184 --- /dev/null +++ b/tools/loop-context/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "outDir": "dist", + "rootDir": "src", + "strict": true, + "skipLibCheck": true, + "declaration": true + }, + "include": ["src/**/*"] +} From 8ba81f15afe5aa31ce5050bc8856d1e72e793b1a Mon Sep 17 00:00:00 2001 From: TechSphrex TA <42131590+KhaiTrang1995@users.noreply.github.com> Date: Sat, 4 Jul 2026 15:26:06 +0700 Subject: [PATCH 4/4] feat(loop-init): scaffold loop-context circuit breaker for fix patterns loop-context (the stateful memory manager / circuit breaker) shipped in #129, but nothing wired it into a real loop yet. This makes the breaker part of the scaffold so new projects get it by default. - New loop-guard skill template: log each attempt to loop-ledger.json and run `loop-context --check` before retrying; on exit 2, inject a pruned summary and escalate instead of looping. - loop-init now scaffolds the loop-guard skill + a goal-seeded loop-ledger.json for fix-capable patterns (pr-babysitter, ci-sweeper, dependency-sweeper, post-merge-cleanup). Report-only patterns skip it. - Wire the breaker into the ci-sweeper pattern doc and the loop-constraints template, turning the soft "max 3 attempts" rule into a mechanical gate. - Tests: guard + ledger scaffolded for fix patterns (grok and opencode paths) and NOT for report-only daily-triage. Co-Authored-By: Claude Opus 4.8 --- patterns/ci-sweeper.md | 3 +- templates/SKILL.md.loop-guard | 71 +++++++++++++++++++++++++++++++ templates/loop-constraints.md | 1 + tools/loop-init/README.md | 7 +++ tools/loop-init/dist/cli.js | 37 ++++++++++++++++ tools/loop-init/src/cli.ts | 46 ++++++++++++++++++++ tools/loop-init/test/cli.test.mjs | 38 ++++++++++++++++- 7 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 templates/SKILL.md.loop-guard diff --git a/patterns/ci-sweeper.md b/patterns/ci-sweeper.md index f29294f..2bc2258 100644 --- a/patterns/ci-sweeper.md +++ b/patterns/ci-sweeper.md @@ -15,6 +15,7 @@ Slower overnight cadence (30–60m) is fine when no one is watching. - `ci-triage` — Parse CI logs, identify failing job/step, classify failure type (flake, regression, env, config) - `minimal-fix` — Smallest change that addresses the specific failure +- `loop-guard` — Circuit breaker: log each attempt to `loop-ledger.json` and run `loop-context --check` before retrying; escalate instead of looping on the same failure - Project test/lint skill — Build and test commands for your stack ## State @@ -48,7 +49,7 @@ Track: commit SHA, failing job, attempt count, worktree/PR link, outcome. - If actionable: open worktree → implementer drafts fix. 3. Verifier sub-agent checks: fix addresses failure, no unrelated changes, tests pass locally. 4. Open PR or comment on existing PR with proposed fix. -5. If attempts exceed max (e.g. 3): escalate to human with full context. +5. Before each retry, `loop-guard` runs the circuit breaker (`loop-context --check`). If the same failure recurs N× or attempts exceed max (e.g. 3), it trips: escalate to human with a pruned context summary instead of looping. 6. Prune resolved failures from active list. ## Verification Strategy diff --git a/templates/SKILL.md.loop-guard b/templates/SKILL.md.loop-guard new file mode 100644 index 0000000..e46a0c6 --- /dev/null +++ b/templates/SKILL.md.loop-guard @@ -0,0 +1,71 @@ +--- +name: loop-guard +description: > + Circuit breaker for fix-capable loops. Before each iteration, append the last + attempt to loop-ledger.json and run loop-context --check; if it escalates, + stop and hand the human a clean summary instead of looping in vain. +user_invocable: true +--- + +# Loop Guard (Circuit Breaker) + +You keep a fix loop from burning tokens on a problem it cannot solve. You wrap +every iteration of an action skill (`minimal-fix`, `ci-triage`, `dependency-triage`, …) +with a deterministic circuit-breaker check powered by +[`loop-context`](https://github.com/cobusgreyling/loop-engineering/tree/main/tools/loop-context). + +The breaker needs no LLM call, so it is cheap enough to run on every iteration. + +## The ledger + +`loop-ledger.json` records the loop's goal and one entry per attempt: + +```json +{ "goal": "Get failing CI green", "attempts": [] } +``` + +After every iteration, append what you just tried: + +```json +{ "iteration": 3, "action": "patch flaky auth test", "outcome": "failure", + "error": "AssertionError: expected 200 got 500", "tokensUsed": 1800 } +``` + +`outcome` is `success | failure | noop`. Always include `error` on failures — +that is how the breaker detects a repeated (stagnant) failure. + +## Before each iteration + +1. Append the previous attempt to `loop-ledger.json`. +2. Run the breaker: + ```bash + npx @cobusgreyling/loop-context --check --ledger loop-ledger.json + ``` +3. Act on the exit code: + - **0** → continue. Optionally trim the next prompt first: + `npx @cobusgreyling/loop-context --inject --ledger loop-ledger.json` + - **2** → **STOP.** The breaker tripped — same error N× in a row, too many + consecutive failures, the token budget, or the iteration cap. Do not retry. + +## On escalate (exit 2) + +1. Capture a clean, pruned summary for the human: + ```bash + npx @cobusgreyling/loop-context --inject --ledger loop-ledger.json > escalation.md + ``` +2. Write the escalation into STATE.md High Priority (or open an issue). +3. Exit the loop. A human decides the next step. + +## Rules + +- Never widen thresholds just to keep looping — escalation is a feature, not a failure. +- Never edit the ledger to hide a repeated error; the breaker exists to catch it. +- Defaults: 3× same error, 5 consecutive failures, 10 iterations. Tune with + `--stagnation`, `--no-progress`, `--max-iterations`, `--token-budget`. + +## Interaction with other skills + +- `minimal-fix` / `ci-triage` — record each attempt's outcome + error in the ledger. +- `loop-verifier` — a verifier rejection is a `failure`; log it so repeats trip the breaker. +- `loop-constraints` — honors "escalate after N attempts"; this skill makes it mechanical. +- `loop-budget` — `--token-budget` mirrors the daily cap in loop-budget.md. diff --git a/templates/loop-constraints.md b/templates/loop-constraints.md index b08f058..6157dc0 100644 --- a/templates/loop-constraints.md +++ b/templates/loop-constraints.md @@ -18,6 +18,7 @@ - Never disable tests to make CI green - Never refactor unrelated code — one fix per run - Max 3 fix attempts per item; escalate after +- Enforce the attempt limit mechanically: log each try to `loop-ledger.json` and run `loop-context --check` before retrying (see the `loop-guard` skill) ## Communication - Always tell me what you're about to do before doing it diff --git a/tools/loop-init/README.md b/tools/loop-init/README.md index beadd5a..edc9471 100644 --- a/tools/loop-init/README.md +++ b/tools/loop-init/README.md @@ -31,6 +31,13 @@ After scaffolding, always run `npx @cobusgreyling/loop-audit . --suggest` and ac L2 patterns (`ci-sweeper`, `dependency-sweeper`) also copy `minimal-fix` and `loop-verifier` templates when missing from the starter. +Fix-capable patterns (`pr-babysitter`, `ci-sweeper`, `dependency-sweeper`, `post-merge-cleanup`) also get a **circuit breaker**: + +- `loop-guard` skill — logs each attempt to `loop-ledger.json` and runs [`loop-context`](../loop-context) `--check` before retrying +- `loop-ledger.json` — seeded with the pattern's goal and an empty `attempts` array + +The breaker escalates (same error N× in a row, too many consecutive failures, token budget, or iteration cap) instead of looping in vain. Report-only patterns skip it. + Every scaffold also creates: - `loop-budget.md` — pattern-specific daily caps and kill switch diff --git a/tools/loop-init/dist/cli.js b/tools/loop-init/dist/cli.js index 7bbfe52..0883f2d 100644 --- a/tools/loop-init/dist/cli.js +++ b/tools/loop-init/dist/cli.js @@ -142,6 +142,37 @@ async function copyL2Templates(pattern, tool, targetDir, templatesRoot, dryRun) await copyTemplateVerifier(templatesRoot, targetDir, tool, dryRun); } } +/** Per-pattern goal seeded into loop-ledger.json for the circuit breaker. */ +const LEDGER_GOAL = { + 'daily-triage': 'Keep the repo healthy and STATE.md current', + 'pr-babysitter': 'Get the watched PR review-ready and green', + 'ci-sweeper': 'Get failing CI back to green', + 'dependency-sweeper': 'Land safe dependency updates', + 'post-merge-cleanup': 'Clean up regressions from recent merges', + 'changelog-drafter': 'Draft accurate release notes', + 'issue-triage': 'Triage the open issue queue', +}; +/** + * Fix-capable loops retry actions, so they need a circuit breaker: scaffold the + * loop-guard skill plus a seeded loop-ledger.json wired to `loop-context`. + * Report-only patterns (daily-triage, issue-triage, changelog-drafter) don't + * retry fixes, so they skip this to keep the scaffold minimal. + */ +async function scaffoldCircuitBreaker(pattern, tool, targetDir, templatesRoot, dryRun) { + if (!PATTERNS_NEEDING_FIX.has(pattern)) + return; + await copyTemplateSkill(templatesRoot, 'SKILL.md.loop-guard', targetDir, tool, 'loop-guard', dryRun); + const ledgerPath = path.join(targetDir, 'loop-ledger.json'); + if (await exists(ledgerPath)) + return; + const seed = `${JSON.stringify({ goal: LEDGER_GOAL[pattern], attempts: [] }, null, 2)}\n`; + if (dryRun) { + console.log(` would write: ${ledgerPath}`); + return; + } + await writeFile(ledgerPath, seed); + console.log(' created: loop-ledger.json (circuit breaker)'); +} function formatTokenCap(n) { if (n >= 1_000_000) return `${n / 1_000_000}M`; @@ -442,6 +473,7 @@ Examples: await copyFile(loopMd, path.join(targetDir, 'LOOP.md'), dryRun); } await copyL2Templates(pattern, tool, targetDir, templatesRoot, dryRun); + await scaffoldCircuitBreaker(pattern, tool, targetDir, templatesRoot, dryRun); await scaffoldObservability(pattern, tool, targetDir, templatesRoot, dryRun); await scaffoldConstraints(targetDir, templatesRoot, tool, dryRun); if (tool !== 'opencode' && !dryRun && !(await exists(path.join(targetDir, 'AGENTS.md')))) { @@ -475,6 +507,11 @@ npm run lint console.log(` npx @cobusgreyling/loop-audit ${auditArg} --suggest`); } } + if (PATTERNS_NEEDING_FIX.has(pattern)) { + console.log(''); + console.log('Circuit breaker wired (loop-guard skill + loop-ledger.json):'); + console.log(' npx @cobusgreyling/loop-context --check --ledger loop-ledger.json'); + } console.log(''); console.log(`First loop (${tool}):`); console.log(` ${firstLoopCommand(pattern, tool)}`); diff --git a/tools/loop-init/src/cli.ts b/tools/loop-init/src/cli.ts index d0c6cc1..f01413f 100644 --- a/tools/loop-init/src/cli.ts +++ b/tools/loop-init/src/cli.ts @@ -184,6 +184,45 @@ async function copyL2Templates( } } +/** Per-pattern goal seeded into loop-ledger.json for the circuit breaker. */ +const LEDGER_GOAL: Record = { + 'daily-triage': 'Keep the repo healthy and STATE.md current', + 'pr-babysitter': 'Get the watched PR review-ready and green', + 'ci-sweeper': 'Get failing CI back to green', + 'dependency-sweeper': 'Land safe dependency updates', + 'post-merge-cleanup': 'Clean up regressions from recent merges', + 'changelog-drafter': 'Draft accurate release notes', + 'issue-triage': 'Triage the open issue queue', +}; + +/** + * Fix-capable loops retry actions, so they need a circuit breaker: scaffold the + * loop-guard skill plus a seeded loop-ledger.json wired to `loop-context`. + * Report-only patterns (daily-triage, issue-triage, changelog-drafter) don't + * retry fixes, so they skip this to keep the scaffold minimal. + */ +async function scaffoldCircuitBreaker( + pattern: Pattern, + tool: Tool, + targetDir: string, + templatesRoot: string, + dryRun: boolean, +) { + if (!PATTERNS_NEEDING_FIX.has(pattern)) return; + + await copyTemplateSkill(templatesRoot, 'SKILL.md.loop-guard', targetDir, tool, 'loop-guard', dryRun); + + const ledgerPath = path.join(targetDir, 'loop-ledger.json'); + if (await exists(ledgerPath)) return; + const seed = `${JSON.stringify({ goal: LEDGER_GOAL[pattern], attempts: [] }, null, 2)}\n`; + if (dryRun) { + console.log(` would write: ${ledgerPath}`); + return; + } + await writeFile(ledgerPath, seed); + console.log(' created: loop-ledger.json (circuit breaker)'); +} + function formatTokenCap(n: number): string { if (n >= 1_000_000) return `${n / 1_000_000}M`; if (n >= 1_000) return `${n / 1_000}k`; @@ -524,6 +563,7 @@ Examples: } await copyL2Templates(pattern, tool, targetDir, templatesRoot, dryRun); + await scaffoldCircuitBreaker(pattern, tool, targetDir, templatesRoot, dryRun); await scaffoldObservability(pattern, tool, targetDir, templatesRoot, dryRun); await scaffoldConstraints(targetDir, templatesRoot, tool, dryRun); @@ -560,6 +600,12 @@ npm run lint } } + if (PATTERNS_NEEDING_FIX.has(pattern)) { + console.log(''); + console.log('Circuit breaker wired (loop-guard skill + loop-ledger.json):'); + console.log(' npx @cobusgreyling/loop-context --check --ledger loop-ledger.json'); + } + console.log(''); console.log(`First loop (${tool}):`); console.log(` ${firstLoopCommand(pattern, tool)}`); diff --git a/tools/loop-init/test/cli.test.mjs b/tools/loop-init/test/cli.test.mjs index 914ed6a..807776d 100644 --- a/tools/loop-init/test/cli.test.mjs +++ b/tools/loop-init/test/cli.test.mjs @@ -1,6 +1,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { mkdtemp, rm, access } from 'node:fs/promises'; +import { mkdtemp, rm, access, readFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { execFile } from 'node:child_process'; @@ -122,3 +122,39 @@ test('loop-init scaffolds ci-sweeper with bundled assets', async () => { await rm(dir, { recursive: true, force: true }); } }); + +test('loop-init scaffolds circuit breaker (loop-guard + ledger) for fix patterns', async () => { + const dir = await mkdtemp(path.join(tmpdir(), 'loop-init-cb-')); + try { + await exec('node', [CLI, dir, '--pattern', 'ci-sweeper', '--tool', 'grok']); + await access(path.join(dir, '.grok', 'skills', 'loop-guard', 'SKILL.md')); + const ledger = JSON.parse(await readFile(path.join(dir, 'loop-ledger.json'), 'utf8')); + assert.equal(typeof ledger.goal, 'string'); + assert.ok(ledger.goal.length > 0); + assert.deepEqual(ledger.attempts, []); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test('loop-init scaffolds circuit breaker for pr-babysitter (opencode paths)', async () => { + const dir = await mkdtemp(path.join(tmpdir(), 'loop-init-cb-oc-')); + try { + await exec('node', [CLI, dir, '--pattern', 'pr-babysitter', '--tool', 'opencode']); + await access(path.join(dir, 'skills', 'loop-guard', 'SKILL.md')); + await access(path.join(dir, 'loop-ledger.json')); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test('loop-init does NOT scaffold circuit breaker for report-only daily-triage', async () => { + const dir = await mkdtemp(path.join(tmpdir(), 'loop-init-nocb-')); + try { + await exec('node', [CLI, dir, '--pattern', 'daily-triage', '--tool', 'grok']); + await assert.rejects(() => access(path.join(dir, 'loop-ledger.json'))); + await assert.rejects(() => access(path.join(dir, '.grok', 'skills', 'loop-guard', 'SKILL.md'))); + } finally { + await rm(dir, { recursive: true, force: true }); + } +});