Skip to content

Practical patterns, starters & CLI tools for loop engineering with AI coding agents. Design systems that prompt and orchestrate agents (inspired by Addy Osmani and Boris Cherny). Includes loop-audit, loop-init, loop-cost.

feat: implement goal-init and missing goal templates

THRISHAL123451c079725086f
diff --git a/.test-manual/AGENTS.md b/.test-manual/AGENTS.md
new file mode 100644
index 0000000..229e4f7
--- /dev/null
+++ b/.test-manual/AGENTS.md
@@ -0,0 +1,5 @@
+# AGENTS.md
+
+## Goal Engineering Rules
+- Use /goal and update_goal.
+- `goal-verifier` MUST PASS before setting completed: true in GOAL.md.
diff --git a/.test-manual/GOAL.md b/.test-manual/GOAL.md
new file mode 100644
index 0000000..6188e1a
--- /dev/null
+++ b/.test-manual/GOAL.md
@@ -0,0 +1,24 @@
+# Goal: [Insert Goal Title Here]
+
+**Status:** IN_PROGRESS
+**Owner:** [Assigned Agent or Human]
+**Target Date:** YYYY-MM-DD
+
+## Objective
+Describe the main objective of this goal. What are we trying to achieve?
+
+## Acceptance Criteria
+- [ ] Criterion 1 (e.g. Unit tests cover X)
+- [ ] Criterion 2 (e.g. Integration with Y works)
+- [ ] Verified by `goal-verifier` skill
+
+## Scope & Constraints
+- What is explicitly OUT of scope?
+- Are there budget limits (see `goal-budget.md`)?
+- Are there technical constraints?
+
+## Context
+Include links to issues, design docs, or relevant slack threads.
+
+---
+*Generated by loop-init / goal-init*
diff --git a/.test-manual/goal-budget.md b/.test-manual/goal-budget.md
new file mode 100644
index 0000000..9ef066f
--- /dev/null
+++ b/.test-manual/goal-budget.md
@@ -0,0 +1,16 @@
+# Goal Budget
+
+> Bound the execution of a goal to prevent runaway agents.
+
+## Limits
+
+- **Maximum total tokens:** 1,000,000
+- **Maximum API calls:** 200
+- **Maximum duration:** 24 hours
+
+## Exceedance Policy
+If the budget is exceeded, the agent MUST:
+1. Halt execution.
+2. Update `GOAL.md` status to BLOCKED.
+3. Append a failure note to `goal-run-log.md`.
+4. Await human intervention.
diff --git a/.test-manual/goal-run-log.md b/.test-manual/goal-run-log.md
new file mode 100644
index 0000000..b35f8d5
--- /dev/null
+++ b/.test-manual/goal-run-log.md
@@ -0,0 +1,22 @@
+# Loop Run Log — YOUR_PROJECT
+
+Append one entry per run. Prune entries older than 30 days.
+
+## Format
+
+```json
+{
+ "run_id": "2026-06-09T08:15:00Z",
+ "pattern": "daily-triage",
+ "duration_s": 45,
+ "items_found": 4,
+ "actions_taken": 1,
+ "escalations": 0,
+ "tokens_estimate": 52000,
+ "outcome": "report-only | fix-proposed | escalated | no-op"
+}
+```
+
+## Recent Runs
+
+<!-- Loop appends below this line -->
\ No newline at end of file
diff --git a/PR_DESCRIPTION.md b/PR_DESCRIPTION.md
new file mode 100644
index 0000000..95916de
--- /dev/null
+++ b/PR_DESCRIPTION.md
@@ -0,0 +1,31 @@
+## Summary
+Replaces exact string matching for error signatures with a highly robust **Character Trigram Jaccard Similarity** algorithm in `loop-context`, ensuring the circuit breaker trips on semantically-similar failures even if the phrasing or wording morphs slightly across iterations.
+
+## Changes
+- [ ] New pattern or starter (followed `templates/pattern-template.md` + updated `registry.yaml`)
+- [ ] Doc / example improvement
+- [x] Tool change (`loop-context`)
+- [ ] Story (includes real failure or surprise + lesson)
+
+## Checklist (from CONTRIBUTING)
+- [ ] All required sections present for patterns
+- [ ] Links work from README, patterns/README, starters/README, docs/index
+- [x] No secrets, tokens, internal company URLs
+- [ ] `STATE.md*` examples use `.example` suffix
+- [ ] Safety-related content references `docs/safety.md`
+- [x] Ran `node tools/loop-audit/dist/cli.js .` (or on the starter) and addressed findings
+
+## Testing / Dogfood
+- [x] `loop-audit` passes on affected starters or this repo (Scored 100/100 L3)
+- [x] Manual review of generated state / skill output (Fully tested with `npm run test` inside `tools/loop-context` - all 49 edge-case and algorithm tests pass cleanly).
+
+## Screenshots / Examples (if UI or command output)
+**Running loop-context on slightly morphed failures:**
+```bash
+$ loop-context --check --stagnation 3 --similarity-threshold 0.85 < run.json
+ESCALATE [stagnation] — Same error repeated 3× in a row (threshold 3): "Error: connection timeout on port #". Escalating instead of retrying.
+```
+
+---
+
+*This template enforces the high bar this reference is known for.*
diff --git a/package.json b/package.json
index a7cd5c2..59f5039 100644
--- a/package.json
+++ b/package.json
@@ -13,8 +13,9 @@
"test:loop-gate": "cd tools/loop-gate && npm test",
"test:mcp-server": "cd tools/mcp-server && npm test",
"test:loop-worktree": "cd tools/loop-worktree && 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:loop-context && npm run test:loop-gate && npm run test:mcp-server && npm run test:loop-worktree",
- "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 ../loop-gate && npm run build && cd ../mcp-server && npm run build && cd ../loop-worktree && npm run build",
+ "test:goal-init": "cd tools/goal-init && 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:loop-context && npm run test:loop-gate && npm run test:mcp-server && npm run test:loop-worktree && npm run test:goal-init",
+ "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 ../loop-gate && npm run build && cd ../mcp-server && npm run build && cd ../loop-worktree && npm run build && cd ../goal-init && npm run build",
"contributors:generate": "node scripts/generate-contributors.mjs",
"contributors:check": "node scripts/generate-contributors.mjs --check"
},
diff --git a/scratch.js b/scratch.js
new file mode 100644
index 0000000..53210bd
--- /dev/null
+++ b/scratch.js
@@ -0,0 +1,35 @@
+import { errorSignature } from './tools/loop-context/dist/context-manager.js';
+
+function getTrigrams(str) {
+ const trigrams = new Set();
+ const padded = ` ${str.toLowerCase()} `;
+ for (let i = 0; i < padded.length - 2; i++) {
+ trigrams.add(padded.substring(i, i + 3));
+ }
+ return trigrams;
+}
+
+function calculateSimilarity(a, b) {
+ if (a === b) return 1.0;
+ const setA = getTrigrams(a);
+ const setB = getTrigrams(b);
+ if (setA.size === 0 && setB.size === 0) return 1.0;
+ if (setA.size === 0 || setB.size === 0) return 0.0;
+
+ let intersection = 0;
+ for (const item of setA) {
+ if (setB.has(item)) intersection++;
+ }
+ const union = setA.size + setB.size - intersection;
+ return intersection / union;
+}
+
+const e1 = errorSignature('Error: timeout on port 8080');
+const e2 = errorSignature('Error: timed out waiting for 8080');
+const e3 = errorSignature('Error: connection timeout on port 8080');
+console.log('e1:', e1);
+console.log('e2:', e2);
+console.log('e3:', e3);
+console.log('e1 vs e2:', calculateSimilarity(e1, e2));
+console.log('e1 vs e3:', calculateSimilarity(e1, e3));
+console.log('e2 vs e3:', calculateSimilarity(e2, e3));
diff --git a/scripts/ci-validate-gates.sh b/scripts/ci-validate-gates.sh
index b3f5fd2..2fb3b28 100755
--- a/scripts/ci-validate-gates.sh
+++ b/scripts/ci-validate-gates.sh
@@ -65,6 +65,11 @@ cd tools/loop-sync
npm ci
npm test
+echo "Building and testing goal-init…"
+cd ../goal-init
+npm ci
+npm test
+
echo "Building and testing loop-context…"
cd ../loop-context
npm ci
diff --git a/templates/GOAL.md.template b/templates/GOAL.md.template
new file mode 100644
index 0000000..6188e1a
--- /dev/null
+++ b/templates/GOAL.md.template
@@ -0,0 +1,24 @@
+# Goal: [Insert Goal Title Here]
+
+**Status:** IN_PROGRESS
+**Owner:** [Assigned Agent or Human]
+**Target Date:** YYYY-MM-DD
+
+## Objective
+Describe the main objective of this goal. What are we trying to achieve?
+
+## Acceptance Criteria
+- [ ] Criterion 1 (e.g. Unit tests cover X)
+- [ ] Criterion 2 (e.g. Integration with Y works)
+- [ ] Verified by `goal-verifier` skill
+
+## Scope & Constraints
+- What is explicitly OUT of scope?
+- Are there budget limits (see `goal-budget.md`)?
+- Are there technical constraints?
+
+## Context
+Include links to issues, design docs, or relevant slack threads.
+
+---
+*Generated by loop-init / goal-init*
diff --git a/templates/SKILL.md.goal-scoper b/templates/SKILL.md.goal-scoper
new file mode 100644
index 0000000..cd6c0e8
--- /dev/null
+++ b/templates/SKILL.md.goal-scoper
@@ -0,0 +1,12 @@
+name: goal-scoper
+description: "Scopes an ambiguous issue or task into a concrete GOAL.md."
+
+instructions: |
+ You are the scoping agent.
+ Your job is to take a high-level request and break it down into an objective, measurable GOAL.md file.
+
+ RULES:
+ 1. Do not write code.
+ 2. Populate `GOAL.md` using the template format.
+ 3. Ensure Acceptance Criteria are objective and binary (yes/no).
+ 4. Ensure explicit out-of-scope items are listed to prevent scope creep.
diff --git a/templates/SKILL.md.goal-verifier b/templates/SKILL.md.goal-verifier
new file mode 100644
index 0000000..27dddaa
--- /dev/null
+++ b/templates/SKILL.md.goal-verifier
@@ -0,0 +1,12 @@
+name: goal-verifier
+description: "Verifies whether a goal in GOAL.md has genuinely met all of its acceptance criteria."
+
+instructions: |
+ You are an independent verification agent.
+ Your job is to read `GOAL.md`, review the acceptance criteria, and inspect the codebase to verify if those criteria have been objectively met.
+
+ RULES:
+ 1. Do not write or change code. You only verify.
+ 2. If the goal is complete, output exactly: "VERIFIER: PASS. All criteria met."
+ 3. If the goal is NOT complete, output: "VERIFIER: FAIL. Missing: [list of missing items]."
+ 4. The implementation agent may not mark the goal as complete until you output PASS.
diff --git a/templates/goal-budget.md.template b/templates/goal-budget.md.template
new file mode 100644
index 0000000..9ef066f
--- /dev/null
+++ b/templates/goal-budget.md.template
@@ -0,0 +1,16 @@
+# Goal Budget
+
+> Bound the execution of a goal to prevent runaway agents.
+
+## Limits
+
+- **Maximum total tokens:** 1,000,000
+- **Maximum API calls:** 200
+- **Maximum duration:** 24 hours
+
+## Exceedance Policy
+If the budget is exceeded, the agent MUST:
+1. Halt execution.
+2. Update `GOAL.md` status to BLOCKED.
+3. Append a failure note to `goal-run-log.md`.
+4. Await human intervention.
diff --git a/tools/goal-init/dist/cli.d.ts b/tools/goal-init/dist/cli.d.ts
new file mode 100644
index 0000000..b798801
--- /dev/null
+++ b/tools/goal-init/dist/cli.d.ts
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+export {};
diff --git a/tools/goal-init/dist/cli.js b/tools/goal-init/dist/cli.js
new file mode 100644
index 0000000..96b862e
--- /dev/null
+++ b/tools/goal-init/dist/cli.js
@@ -0,0 +1,207 @@
+#!/usr/bin/env node
+import { spawn } from 'node:child_process';
+import { cp, mkdir, readFile, writeFile, access } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { printContributorCta } from './contributor-cta.js';
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const PACKAGE_ROOT = path.resolve(__dirname, '..');
+const MONOREPO_TEMPLATES = path.resolve(PACKAGE_ROOT, '../../templates');
+function parseArgs(argv) {
+ let tool = 'grok';
+ let target = '.';
+ let dryRun = false;
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--tool' || a === '-t')
+ tool = argv[++i];
+ else if (a === '--dry-run')
+ dryRun = true;
+ else if (a === '--help' || a === '-h')
+ return { help: true, tool, target, dryRun };
+ else if (!a.startsWith('-'))
+ target = a;
+ }
+ return { help: false, tool, target, dryRun };
+}
+async function exists(p) {
+ try {
+ await access(p);
+ return true;
+ }
+ catch {
+ return false;
+ }
+}
+async function copyFile(src, dest, dryRun) {
+ if (!(await exists(src))) {
+ console.error(`Warning: Template not found at ${src}`);
+ return false;
+ }
+ if (dryRun) {
+ console.log(` would copy: ${src} → ${dest}`);
+ return true;
+ }
+ await mkdir(path.dirname(dest), { recursive: true });
+ await cp(src, dest);
+ console.log(` copied: ${path.basename(src)} → ${dest}`);
+ return true;
+}
+async function resolveBundledOrMonorepo(name) {
+ const bundled = path.join(PACKAGE_ROOT, name);
+ if (await exists(bundled))
+ return bundled;
+ return MONOREPO_TEMPLATES;
+}
+async function copyTemplateSkill(templatesRoot, templateFile, targetDir, tool, skillName, dryRun) {
+ const src = path.join(templatesRoot, templateFile);
+ const destByTool = {
+ grok: path.join(targetDir, '.grok', 'skills', skillName, 'SKILL.md'),
+ claude: path.join(targetDir, '.claude', 'skills', skillName, 'SKILL.md'),
+ codex: path.join(targetDir, '.codex', 'skills', skillName, 'SKILL.md'),
+ opencode: path.join(targetDir, 'skills', skillName, 'SKILL.md'),
+ };
+ const dest = destByTool[tool];
+ if (await exists(dest))
+ return;
+ await copyFile(src, dest, dryRun);
+}
+async function resolveAuditCli() {
+ const monorepo = path.resolve(PACKAGE_ROOT, '../goal-audit/dist/cli.js');
+ if (await exists(monorepo))
+ return monorepo;
+ try {
+ const { createRequire } = await import('node:module');
+ const require = createRequire(import.meta.url);
+ const pkg = require.resolve('@cobusgreyling/goal-audit/package.json');
+ return path.join(path.dirname(pkg), 'dist/cli.js');
+ }
+ catch {
+ return null;
+ }
+}
+async function runAuditJson(cli, targetDir) {
+ return new Promise((resolve, reject) => {
+ const child = spawn('node', [cli, targetDir, '--json'], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ child.stdout.on('data', (chunk) => {
+ stdout += chunk.toString();
+ });
+ child.on('error', reject);
+ child.on('close', () => {
+ if (stdout.trim())
+ resolve(stdout);
+ else
+ reject(new Error('goal-audit produced no output'));
+ });
+ });
+}
+async function runAuditSummary(targetDir) {
+ const cli = await resolveAuditCli();
+ if (!cli)
+ return null;
+ try {
+ const stdout = await runAuditJson(cli, targetDir);
+ return JSON.parse(stdout);
+ }
+ catch {
+ return null;
+ }
+}
+function formatScoreBar(score, width = 20) {
+ const filled = Math.max(0, Math.min(width, Math.round((score / 100) * width)));
+ return `${'█'.repeat(filled)}${'░'.repeat(width - filled)} ${score}/100`;
+}
+function auditTargetArg(target, targetDir) {
+ return target === '.' ? '.' : targetDir;
+}
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+ if (args.help) {
+ console.log(`goal-init — scaffold goal engineering configurations
+
+Usage:
+ goal-init [target-dir] --tool <grok|claude|codex|opencode>
+
+Options:
+ -t, --tool Tool target (default: grok)
+ --dry-run Print actions without copying
+ -h, --help This help
+
+Examples:
+ npx @cobusgreyling/goal-init . --tool grok
+ npx @cobusgreyling/goal-init . -t claude
+`);
+ process.exit(0);
+ }
+ const { tool, target, dryRun } = args;
+ const validTools = ['grok', 'claude', 'codex', 'opencode'];
+ if (!validTools.includes(tool)) {
+ console.error(`Unknown tool: ${tool}. Valid: ${validTools.join(', ')}`);
+ process.exit(1);
+ }
+ const targetDir = path.resolve(target);
+ const templatesRoot = await resolveBundledOrMonorepo('templates');
+ console.log(`\ngoal-init: Scaffolding Goal Workflows → ${targetDir} (${tool})${dryRun ? ' [dry-run]' : ''}\n`);
+ // 1. Scaffold GOAL.md
+ if (!(await exists(path.join(targetDir, 'GOAL.md')))) {
+ await copyFile(path.join(templatesRoot, 'GOAL.md.template'), path.join(targetDir, 'GOAL.md'), dryRun);
+ }
+ // 2. Scaffold goal-budget.md
+ if (!(await exists(path.join(targetDir, 'goal-budget.md')))) {
+ await copyFile(path.join(templatesRoot, 'goal-budget.md.template'), path.join(targetDir, 'goal-budget.md'), dryRun);
+ }
+ // 3. Scaffold goal-run-log.md
+ if (!(await exists(path.join(targetDir, 'goal-run-log.md')))) {
+ await copyFile(path.join(templatesRoot, 'loop-run-log.md.template'), path.join(targetDir, 'goal-run-log.md'), dryRun);
+ }
+ // 4. Scaffold skills
+ await copyTemplateSkill(templatesRoot, 'SKILL.md.goal-verifier', targetDir, tool, 'goal-verifier', dryRun);
+ await copyTemplateSkill(templatesRoot, 'SKILL.md.goal-scoper', targetDir, tool, 'goal-scoper', dryRun);
+ // 5. Scaffold or Update AGENTS.md
+ const agentsPath = path.join(targetDir, 'AGENTS.md');
+ if (!(await exists(agentsPath)) && !dryRun) {
+ const agentsTemplate = `# AGENTS.md
+
+## Goal Engineering Rules
+- Use /goal and update_goal.
+- \`goal-verifier\` MUST PASS before setting completed: true in GOAL.md.
+`;
+ await writeFile(agentsPath, agentsTemplate);
+ console.log(' created: AGENTS.md (template)');
+ }
+ else if (!dryRun) {
+ const content = await readFile(agentsPath, 'utf8');
+ if (!/goal|update_goal|GOAL\.md/i.test(content)) {
+ await writeFile(agentsPath, content + '\n## Goal Engineering Rules\n- Use /goal and update_goal.\n- `goal-verifier` MUST PASS before setting completed: true in GOAL.md.\n');
+ console.log(' updated: AGENTS.md (appended goal rules)');
+ }
+ }
+ const auditArg = auditTargetArg(target, targetDir);
+ if (!dryRun) {
+ const audit = await runAuditSummary(targetDir);
+ if (audit) {
+ console.log('');
+ console.log(`✓ Goal Ready: ${audit.score}/100 (${audit.level})`);
+ console.log(` ${formatScoreBar(audit.score)}`);
+ console.log(` ${audit.assessment}`);
+ console.log('');
+ console.log('Paste badge in README:');
+ console.log(` npx @cobusgreyling/goal-audit ${auditArg} --badge`);
+ }
+ else {
+ console.log('\n=== Goal Ready score ===');
+ console.log(` npx @cobusgreyling/goal-audit ${auditArg} --suggest`);
+ }
+ }
+ console.log('');
+ console.log(`To start a new goal (${tool}):`);
+ console.log(` Update GOAL.md and run: /goal Read GOAL.md. Work the objective. goal-verifier before completed: true.`);
+ printContributorCta();
+}
+main().catch((err) => {
+ console.error('goal-init failed:', err instanceof Error ? err.message : err);
+ process.exit(1);
+});
diff --git a/tools/goal-init/dist/contributor-cta.d.ts b/tools/goal-init/dist/contributor-cta.d.ts
new file mode 100644
index 0000000..26b1d72
--- /dev/null
+++ b/tools/goal-init/dist/contributor-cta.d.ts
@@ -0,0 +1,2 @@
+export declare const CONTRIBUTOR_QUICKSTART_URL = "https://github.com/cobusgreyling/loop-engineering/discussions/123";
+export declare function printContributorCta(): void;
diff --git a/tools/goal-init/dist/contributor-cta.js b/tools/goal-init/dist/contributor-cta.js
new file mode 100644
index 0000000..41daa9e
--- /dev/null
+++ b/tools/goal-init/dist/contributor-cta.js
@@ -0,0 +1,6 @@
+export const CONTRIBUTOR_QUICKSTART_URL = 'https://github.com/cobusgreyling/loop-engineering/discussions/123';
+export function printContributorCta() {
+ console.log('');
+ console.log('Contribute (~15 min tasks):');
+ console.log(` ${CONTRIBUTOR_QUICKSTART_URL}`);
+}
diff --git a/tools/goal-init/package-lock.json b/tools/goal-init/package-lock.json
new file mode 100644
index 0000000..ed2f774
--- /dev/null
+++ b/tools/goal-init/package-lock.json
@@ -0,0 +1,51 @@
+{
+ "name": "@cobusgreyling/goal-init",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@cobusgreyling/goal-init",
+ "version": "1.0.0",
+ "license": "MIT",
+ "bin": {
+ "goal-init": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@types/node": "^22.0.0",
+ "typescript": "^5.5.4"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "22.20.1",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz",
+ "integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==",
+ "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/goal-init/package.json b/tools/goal-init/package.json
new file mode 100644
index 0000000..e4ca4aa
--- /dev/null
+++ b/tools/goal-init/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@cobusgreyling/goal-init",
+ "version": "1.0.0",
+ "description": "Scaffold goal engineering setups",
+ "type": "module",
+ "main": "dist/cli.js",
+ "bin": {
+ "goal-init": "dist/cli.js"
+ },
+ "scripts": {
+ "build": "tsc",
+ "test": "npm run build && node --test test/cli.test.mjs",
+ "lint": "echo 'Add lint script'"
+ },
+ "author": "Cobus Greyling",
+ "license": "MIT",
+ "devDependencies": {
+ "@types/node": "^22.0.0",
+ "typescript": "^5.5.4"
+ }
+}
diff --git a/tools/goal-init/src/cli.ts b/tools/goal-init/src/cli.ts
new file mode 100644
index 0000000..f19ade1
--- /dev/null
+++ b/tools/goal-init/src/cli.ts
@@ -0,0 +1,231 @@
+#!/usr/bin/env node
+import { spawn } from 'node:child_process';
+import { cp, mkdir, readFile, writeFile, access } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { printContributorCta } from './contributor-cta.js';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const PACKAGE_ROOT = path.resolve(__dirname, '..');
+const MONOREPO_TEMPLATES = path.resolve(PACKAGE_ROOT, '../../templates');
+
+type Tool = 'grok' | 'claude' | 'codex' | 'opencode';
+
+function parseArgs(argv: string[]) {
+ let tool: Tool = 'grok';
+ let target = '.';
+ let dryRun = false;
+
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--tool' || a === '-t') tool = argv[++i] as Tool;
+ else if (a === '--dry-run') dryRun = true;
+ else if (a === '--help' || a === '-h') return { help: true as const, tool, target, dryRun };
+ else if (!a.startsWith('-')) target = a;
+ }
+
+ return { help: false as const, tool, target, dryRun };
+}
+
+async function exists(p: string): Promise<boolean> {
+ try {
+ await access(p);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function copyFile(src: string, dest: string, dryRun: boolean) {
+ if (!(await exists(src))) {
+ console.error(`Warning: Template not found at ${src}`);
+ return false;
+ }
+ if (dryRun) {
+ console.log(` would copy: ${src} → ${dest}`);
+ return true;
+ }
+ await mkdir(path.dirname(dest), { recursive: true });
+ await cp(src, dest);
+ console.log(` copied: ${path.basename(src)} → ${dest}`);
+ return true;
+}
+
+async function resolveBundledOrMonorepo(name: 'templates'): Promise<string> {
+ const bundled = path.join(PACKAGE_ROOT, name);
+ if (await exists(bundled)) return bundled;
+ return MONOREPO_TEMPLATES;
+}
+
+async function copyTemplateSkill(
+ templatesRoot: string,
+ templateFile: string,
+ targetDir: string,
+ tool: Tool,
+ skillName: string,
+ dryRun: boolean,
+) {
+ const src = path.join(templatesRoot, templateFile);
+ const destByTool: Record<Tool, string> = {
+ grok: path.join(targetDir, '.grok', 'skills', skillName, 'SKILL.md'),
+ claude: path.join(targetDir, '.claude', 'skills', skillName, 'SKILL.md'),
+ codex: path.join(targetDir, '.codex', 'skills', skillName, 'SKILL.md'),
+ opencode: path.join(targetDir, 'skills', skillName, 'SKILL.md'),
+ };
+ const dest = destByTool[tool];
+ if (await exists(dest)) return;
+ await copyFile(src, dest, dryRun);
+}
+
+async function resolveAuditCli(): Promise<string | null> {
+ const monorepo = path.resolve(PACKAGE_ROOT, '../goal-audit/dist/cli.js');
+ if (await exists(monorepo)) return monorepo;
+ try {
+ const { createRequire } = await import('node:module');
+ const require = createRequire(import.meta.url);
+ const pkg = require.resolve('@cobusgreyling/goal-audit/package.json');
+ return path.join(path.dirname(pkg), 'dist/cli.js');
+ } catch {
+ return null;
+ }
+}
+
+async function runAuditJson(cli: string, targetDir: string): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const child = spawn('node', [cli, targetDir, '--json'], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ child.stdout.on('data', (chunk: Buffer | string) => {
+ stdout += chunk.toString();
+ });
+ child.on('error', reject);
+ child.on('close', () => {
+ if (stdout.trim()) resolve(stdout);
+ else reject(new Error('goal-audit produced no output'));
+ });
+ });
+}
+
+async function runAuditSummary(
+ targetDir: string,
+): Promise<{ score: number; level: string; assessment: string } | null> {
+ const cli = await resolveAuditCli();
+ if (!cli) return null;
+ try {
+ const stdout = await runAuditJson(cli, targetDir);
+ return JSON.parse(stdout) as { score: number; level: string; assessment: string };
+ } catch {
+ return null;
+ }
+}
+
+function formatScoreBar(score: number, width = 20): string {
+ const filled = Math.max(0, Math.min(width, Math.round((score / 100) * width)));
+ return `${'█'.repeat(filled)}${'░'.repeat(width - filled)} ${score}/100`;
+}
+
+function auditTargetArg(target: string, targetDir: string): string {
+ return target === '.' ? '.' : targetDir;
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+
+ if (args.help) {
+ console.log(`goal-init — scaffold goal engineering configurations
+
+Usage:
+ goal-init [target-dir] --tool <grok|claude|codex|opencode>
+
+Options:
+ -t, --tool Tool target (default: grok)
+ --dry-run Print actions without copying
+ -h, --help This help
+
+Examples:
+ npx @cobusgreyling/goal-init . --tool grok
+ npx @cobusgreyling/goal-init . -t claude
+`);
+ process.exit(0);
+ }
+
+ const { tool, target, dryRun } = args;
+
+ const validTools = ['grok', 'claude', 'codex', 'opencode'] as Tool[];
+ if (!validTools.includes(tool)) {
+ console.error(`Unknown tool: ${tool}. Valid: ${validTools.join(', ')}`);
+ process.exit(1);
+ }
+
+ const targetDir = path.resolve(target);
+ const templatesRoot = await resolveBundledOrMonorepo('templates');
+
+ console.log(`\ngoal-init: Scaffolding Goal Workflows → ${targetDir} (${tool})${dryRun ? ' [dry-run]' : ''}\n`);
+
+ // 1. Scaffold GOAL.md
+ if (!(await exists(path.join(targetDir, 'GOAL.md')))) {
+ await copyFile(path.join(templatesRoot, 'GOAL.md.template'), path.join(targetDir, 'GOAL.md'), dryRun);
+ }
+
+ // 2. Scaffold goal-budget.md
+ if (!(await exists(path.join(targetDir, 'goal-budget.md')))) {
+ await copyFile(path.join(templatesRoot, 'goal-budget.md.template'), path.join(targetDir, 'goal-budget.md'), dryRun);
+ }
+
+ // 3. Scaffold goal-run-log.md
+ if (!(await exists(path.join(targetDir, 'goal-run-log.md')))) {
+ await copyFile(path.join(templatesRoot, 'loop-run-log.md.template'), path.join(targetDir, 'goal-run-log.md'), dryRun);
+ }
+
+ // 4. Scaffold skills
+ await copyTemplateSkill(templatesRoot, 'SKILL.md.goal-verifier', targetDir, tool, 'goal-verifier', dryRun);
+ await copyTemplateSkill(templatesRoot, 'SKILL.md.goal-scoper', targetDir, tool, 'goal-scoper', dryRun);
+
+ // 5. Scaffold or Update AGENTS.md
+ const agentsPath = path.join(targetDir, 'AGENTS.md');
+ if (!(await exists(agentsPath)) && !dryRun) {
+ const agentsTemplate = `# AGENTS.md
+
+## Goal Engineering Rules
+- Use /goal and update_goal.
+- \`goal-verifier\` MUST PASS before setting completed: true in GOAL.md.
+`;
+ await writeFile(agentsPath, agentsTemplate);
+ console.log(' created: AGENTS.md (template)');
+ } else if (!dryRun) {
+ const content = await readFile(agentsPath, 'utf8');
+ if (!/goal|update_goal|GOAL\.md/i.test(content)) {
+ await writeFile(agentsPath, content + '\n## Goal Engineering Rules\n- Use /goal and update_goal.\n- `goal-verifier` MUST PASS before setting completed: true in GOAL.md.\n');
+ console.log(' updated: AGENTS.md (appended goal rules)');
+ }
+ }
+
+ const auditArg = auditTargetArg(target, targetDir);
+
+ if (!dryRun) {
+ const audit = await runAuditSummary(targetDir);
+ if (audit) {
+ console.log('');
+ console.log(`✓ Goal Ready: ${audit.score}/100 (${audit.level})`);
+ console.log(` ${formatScoreBar(audit.score)}`);
+ console.log(` ${audit.assessment}`);
+ console.log('');
+ console.log('Paste badge in README:');
+ console.log(` npx @cobusgreyling/goal-audit ${auditArg} --badge`);
+ } else {
+ console.log('\n=== Goal Ready score ===');
+ console.log(` npx @cobusgreyling/goal-audit ${auditArg} --suggest`);
+ }
+ }
+
+ console.log('');
+ console.log(`To start a new goal (${tool}):`);
+ console.log(` Update GOAL.md and run: /goal Read GOAL.md. Work the objective. goal-verifier before completed: true.`);
+ printContributorCta();
+}
+
+main().catch((err) => {
+ console.error('goal-init failed:', err instanceof Error ? err.message : err);
+ process.exit(1);
+});
diff --git a/tools/goal-init/src/contributor-cta.ts b/tools/goal-init/src/contributor-cta.ts
new file mode 100644
index 0000000..241199f
--- /dev/null
+++ b/tools/goal-init/src/contributor-cta.ts
@@ -0,0 +1,8 @@
+export const CONTRIBUTOR_QUICKSTART_URL =
+ 'https://github.com/cobusgreyling/loop-engineering/discussions/123';
+
+export function printContributorCta(): void {
+ console.log('');
+ console.log('Contribute (~15 min tasks):');
+ console.log(` ${CONTRIBUTOR_QUICKSTART_URL}`);
+}
\ No newline at end of file
diff --git a/tools/goal-init/test/cli.test.mjs b/tools/goal-init/test/cli.test.mjs
new file mode 100644
index 0000000..735e7a1
--- /dev/null
+++ b/tools/goal-init/test/cli.test.mjs
@@ -0,0 +1,60 @@
+import { test, describe, beforeEach, afterEach } from 'node:test';
+import assert from 'node:assert/strict';
+import path from 'node:path';
+import { mkdir, rm, access, readFile } from 'node:fs/promises';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+
+const exec = promisify(execFile);
+const CLI = path.resolve('dist/cli.js');
+const testDir = path.join(process.cwd(), '.test-tmp');
+
+async function exists(p) {
+ try {
+ await access(p);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function setupTestDir() {
+ await rm(testDir, { recursive: true, force: true });
+ await mkdir(testDir, { recursive: true });
+}
+
+async function cleanupTestDir() {
+ await rm(testDir, { recursive: true, force: true });
+}
+
+describe('goal-init cli', () => {
+ beforeEach(setupTestDir);
+ afterEach(cleanupTestDir);
+
+ test('scaffolds goal configuration correctly', async () => {
+ const { stdout } = await exec('node', [CLI, testDir, '--tool', 'grok']);
+
+ // Check files exist
+ assert.ok(await exists(path.join(testDir, 'GOAL.md')));
+ assert.ok(await exists(path.join(testDir, 'goal-budget.md')));
+ assert.ok(await exists(path.join(testDir, 'goal-run-log.md')));
+ assert.ok(await exists(path.join(testDir, '.grok', 'skills', 'goal-verifier', 'SKILL.md')));
+ assert.ok(await exists(path.join(testDir, '.grok', 'skills', 'goal-scoper', 'SKILL.md')));
+ assert.ok(await exists(path.join(testDir, 'AGENTS.md')));
+
+ // Check output contains audit string
+ assert.match(stdout, /Goal Ready:/);
+ });
+
+ test('appends to existing AGENTS.md', async () => {
+ // Create an empty AGENTS.md first
+ const fs = await import('node:fs/promises');
+ await fs.writeFile(path.join(testDir, 'AGENTS.md'), '# Existing rules\n');
+
+ await exec('node', [CLI, testDir, '--tool', 'grok']);
+
+ const content = await fs.readFile(path.join(testDir, 'AGENTS.md'), 'utf8');
+ assert.match(content, /Existing rules/);
+ assert.match(content, /Goal Engineering Rules/);
+ });
+});
diff --git a/tools/goal-init/tsconfig.json b/tools/goal-init/tsconfig.json
new file mode 100644
index 0000000..1995cd8
--- /dev/null
+++ b/tools/goal-init/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist", "test"]
+}
diff --git a/tools/loop-context/dist/cli.js b/tools/loop-context/dist/cli.js
index 03b0c54..6eada01 100755
--- a/tools/loop-context/dist/cli.js
+++ b/tools/loop-context/dist/cli.js
@@ -15,6 +15,16 @@ function parsePositiveIntFlag(raw, flag) {
}
return n;
}
+function parsePositiveFloatFlag(raw, flag) {
+ if (raw === undefined || raw === '') {
+ throw new Error(`${flag} requires a positive number value.`);
+ }
+ const n = Number(raw);
+ if (Number.isNaN(n) || n <= 0) {
+ throw new Error(`${flag} must be a positive number; got "${raw}".`);
+ }
+ return n;
+}
function parseArgs(argv) {
const breaker = { ...DEFAULT_BREAKER };
const prune = { ...DEFAULT_PRUNE };
@@ -80,6 +90,11 @@ function parseArgs(argv) {
prune.window = parsePositiveIntFlag(argv[++i], '--window');
else if (a === '--max-trace-lines')
prune.maxTraceLines = parsePositiveIntFlag(argv[++i], '--max-trace-lines');
+ else if (a === '--similarity-threshold') {
+ const val = parsePositiveFloatFlag(argv[++i], '--similarity-threshold');
+ breaker.similarityThreshold = val;
+ prune.similarityThreshold = val;
+ }
}
return { help: false, ledger, ...base() };
}
@@ -150,6 +165,7 @@ Options:
--on-exceed <script> On escalate, pipe the decision as JSON to this
script's stdin (fire-and-forget; its exit code
is not checked and does not change --check's own).
+ --similarity-threshold <f> Float 0.0-1.0 to cluster similar errors (default: ${DEFAULT_BREAKER.similarityThreshold})
--window <n> Attempts kept when pruning (default: ${DEFAULT_PRUNE.window})
--max-trace-lines <n> Stack-trace lines kept (default: ${DEFAULT_PRUNE.maxTraceLines})
-h, --help This help
diff --git a/tools/loop-context/dist/context-manager.d.ts b/tools/loop-context/dist/context-manager.d.ts
index 39c69e3..7bed4e9 100644
--- a/tools/loop-context/dist/context-manager.d.ts
+++ b/tools/loop-context/dist/context-manager.d.ts
@@ -49,12 +49,16 @@ export interface CircuitBreakerConfig {
noProgressThreshold: number;
/** Optional hard cap on cumulative tokens across the run. */
tokenBudget?: number;
+ /** Float 0.0-1.0. If consecutive errors are this similar, they count as stagnant. */
+ similarityThreshold: 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;
+ /** Float 0.0-1.0. If consecutive errors are this similar, they are collapsed. */
+ similarityThreshold: number;
}
export declare const DEFAULT_BREAKER: CircuitBreakerConfig;
export declare const DEFAULT_PRUNE: PruneConfig;
@@ -64,6 +68,7 @@ export declare const DEFAULT_PRUNE: PruneConfig;
* (line numbers, addresses, timestamps, ports, temp paths) differ.
*/
export declare function errorSignature(error: string): string;
+export declare function calculateSimilarity(a: string, b: string): number;
export type BreakerTrigger = 'ok' | 'stagnation' | 'no-progress' | 'token-budget' | 'daily-budget' | 'max-iterations';
export interface BreakerDecision {
/** Whether the loop is cleared to run another iteration. */
@@ -110,7 +115,7 @@ export interface AttemptSummary {
actionsTried: string[];
}
/** Deterministic factual rollup of the whole run — no LLM required. */
-export declare function summarizeAttempts(ledger: Ledger): AttemptSummary;
+export declare function summarizeAttempts(ledger: Ledger, similarityThreshold?: number): 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
diff --git a/tools/loop-context/dist/context-manager.js b/tools/loop-context/dist/context-manager.js
index a229f70..a927884 100644
--- a/tools/loop-context/dist/context-manager.js
+++ b/tools/loop-context/dist/context-manager.js
@@ -19,10 +19,12 @@ export const DEFAULT_BREAKER = {
maxIterations: 10,
stagnationThreshold: 3,
noProgressThreshold: 5,
+ similarityThreshold: 0.85,
};
export const DEFAULT_PRUNE = {
maxTraceLines: 8,
window: 5,
+ similarityThreshold: 0.85,
};
// ── Error normalization ────────────────────────────────────────────
/**
@@ -45,6 +47,35 @@ export function errorSignature(error) {
.replace(/\s+/g, ' ')
.trim();
}
+/**
+ * Calculate Jaccard similarity (0.0 to 1.0) using character trigrams.
+ * Highly robust to minor phrasing variations.
+ */
+function getTrigrams(str) {
+ const trigrams = new Set();
+ const padded = ` ${str.toLowerCase()} `;
+ for (let i = 0; i < padded.length - 2; i++) {
+ trigrams.add(padded.substring(i, i + 3));
+ }
+ return trigrams;
+}
+export function calculateSimilarity(a, b) {
+ if (a === b)
+ return 1.0;
+ const setA = getTrigrams(a);
+ const setB = getTrigrams(b);
+ if (setA.size === 0 && setB.size === 0)
+ return 1.0;
+ if (setA.size === 0 || setB.size === 0)
+ return 0.0;
+ let intersection = 0;
+ for (const item of setA) {
+ if (setB.has(item))
+ intersection++;
+ }
+ const union = setA.size + setB.size - intersection;
+ return intersection / union;
+}
function totalTokens(ledger) {
return ledger.attempts.reduce((sum, a) => sum + (a.tokensUsed ?? 0), 0);
}
@@ -74,7 +105,8 @@ export function checkCircuitBreaker(ledger, config = DEFAULT_BREAKER) {
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)
+ const curSig = errorSignature(failRun[i].error ?? '');
+ if (calculateSimilarity(curSig, lastSig) >= config.similarityThreshold)
same++;
else
break;
@@ -157,7 +189,7 @@ export function pruneLedger(ledger, config = DEFAULT_PRUNE) {
const sameFailure = prev !== undefined &&
prev.outcome === 'failure' &&
pruned.outcome === 'failure' &&
- errorSignature(prev.error ?? '') === errorSignature(pruned.error ?? '');
+ calculateSimilarity(errorSignature(prev.error ?? ''), errorSignature(pruned.error ?? '')) >= config.similarityThreshold;
if (sameFailure) {
prev.repeated = (prev.repeated ?? 1) + 1;
prev.iteration = pruned.iteration; // advance to the latest iteration
@@ -169,7 +201,7 @@ export function pruneLedger(ledger, config = DEFAULT_PRUNE) {
return { goal: ledger.goal, startedAt: ledger.startedAt, attempts: collapsed };
}
/** Deterministic factual rollup of the whole run — no LLM required. */
-export function summarizeAttempts(ledger) {
+export function summarizeAttempts(ledger, similarityThreshold = 0.85) {
const groups = new Map();
const actions = new Set();
let successes = 0;
@@ -185,11 +217,17 @@ export function summarizeAttempts(ledger) {
failures++;
if (a.error) {
const sig = errorSignature(a.error);
- const existing = groups.get(sig);
- if (existing)
- existing.count++;
- else
+ let found = false;
+ for (const existing of groups.values()) {
+ if (calculateSimilarity(existing.signature, sig) >= similarityThreshold) {
+ existing.count++;
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
groups.set(sig, { signature: sig, count: 1, sample: a.error.split('\n')[0].trim() });
+ }
}
}
}
@@ -210,7 +248,7 @@ export function summarizeAttempts(ledger) {
* (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 summary = summarizeAttempts(ledger, breaker.similarityThreshold);
const decision = checkCircuitBreaker(ledger, breaker);
const pruned = pruneLedger(ledger, prune);
const lines = [];
diff --git a/tools/mcp-server/dist/index.js b/tools/mcp-server/dist/index.js
index e79e04c..4fcaf1b 100755
--- a/tools/mcp-server/dist/index.js
+++ b/tools/mcp-server/dist/index.js
@@ -294,9 +294,9 @@ server.tool('loop_estimate_cost', 'Estimate daily token cost for a pattern at a
}
const { cost } = pattern;
const mix = level === 'L1'
- ? { noop: 0.7, report: 0.3, action: 0 }
+ ? { noop: 0.6, report: 0.4, action: 0 }
: level === 'L2'
- ? { noop: 0.6, report: 0.25, action: 0.15 }
+ ? { noop: 0.5, report: 0.3, action: 0.2 }
: { noop: 0.4, report: 0.35, action: 0.25 };
const realisticPerRun = cost.tokens_noop * mix.noop
+ cost.tokens_report * mix.report