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.
TypeScript agentic-aiai-agentsai-codinganthropicautomationclaudeclaude-codecodexcoding-agentsdevops-automationdevtoolsgithub-actionsgrokllmloop-engineeringmcpprompt-engineering
feat: implement memory-engineering bridge (--with-memory flag and readiness signals) (#359)
THRISHAL DOMA63df6ad60bcd
diff --git a/templates/memory-budget.md b/templates/memory-budget.mdnew file mode 100644index 0000000..a13c9a5--- /dev/null+++ b/templates/memory-budget.md@@ -0,0 +1,6 @@+# Memory Budget++- Max context window: 200k tokens+- Core prompt reserve: 20k tokens+- Working memory (L1): 50k tokens+- Retrieval budget (L2/L3): 130k tokensdiff --git a/templates/memory-tiers.md b/templates/memory-tiers.mdnew file mode 100644index 0000000..68b53d9--- /dev/null+++ b/templates/memory-tiers.md@@ -0,0 +1,13 @@+# Memory Tiers++## L1 (Working Memory)+- STATE.md+- Active PR comments++## L2 (Short-term Memory)+- Recent loop-run-log.md entries+- Merged PR descriptions (last 7 days)++## L3 (Long-term Knowledge)+- Core docs+- Architectural decision records (ADRs)diff --git a/tools/loop-audit/dist/auditor.d.ts b/tools/loop-audit/dist/auditor.d.tsindex 7a455cf..1362635 100644--- a/tools/loop-audit/dist/auditor.d.ts+++ b/tools/loop-audit/dist/auditor.d.ts@@ -71,6 +71,11 @@ export interface LoopSignals {emit: boolean;host: boolean;};+ /** memory-engineering setup (memory-tiers.md, memory-budget.md) */+ memory: {+ tiers: boolean;+ budget: boolean;+ };}export type { Finding };export interface AuditResult extends BaseAuditResult<'L0' | 'L1' | 'L2' | 'L3', LoopSignals> {diff --git a/tools/loop-audit/dist/auditor.js b/tools/loop-audit/dist/auditor.jsindex 487c557..d5b755a 100644--- a/tools/loop-audit/dist/auditor.js+++ b/tools/loop-audit/dist/auditor.js@@ -44,6 +44,9 @@ const SCORE_WEIGHTS = {harnessSessions: 2,harnessEmit: 1,harnessHost: 1,+ /** Memory Engineering (memory-tiers.md, memory-budget.md) */+ memoryTiers: 4,+ memoryBudget: 2,};const LEVEL_THRESHOLDS = {L1: 38,@@ -269,6 +272,10 @@ export function computeScore(signals) {score += w.harnessEmit;if (signals.harness.host)score += w.harnessHost;+ if (signals.memory.tiers)+ score += w.memoryTiers;+ if (signals.memory.budget)+ score += w.memoryBudget;score = Math.min(100, Math.max(0, score));const costReady = signals.cost.budgetDoc &&signals.cost.runLog &&@@ -485,6 +492,10 @@ export async function auditProject(target) {emit: harnessEmit,host: harnessHost,};+ // Memory Engineering (memory-tiers.md, memory-budget.md)+ const memoryTiers = await fileExists(path.join(root, 'memory-tiers.md'));+ const memoryBudget = await fileExists(path.join(root, 'memory-budget.md'));+ const memory = { tiers: memoryTiers, budget: memoryBudget };const signals = {stateFile: { present: statePaths.length > 0, paths: statePaths },loopConfig: { present: loopMd, path: loopMd ? 'LOOP.md' : undefined },@@ -504,6 +515,7 @@ export async function auditProject(target) {governance: { toolScope, stallDetection, escalation },loopActivity,harness,+ memory,};if (!signals.stateFile.present) {findings.push({ level: 'fail', message: 'No state file (STATE.md or pattern-specific state).' });@@ -662,10 +674,33 @@ export async function auditProject(target) {findings.push({ level: 'ok', message: 'Harness session/trace evidence present.' });}}+ if (!signals.memory.tiers) {+ findings.push({+ level: 'warn',+ message: 'No memory-tiers.md — memory engineering tiers are not defined.',+ });+ recommendations.push('Scaffold memory tiers: npx @cobusgreyling/loop-init . --with-memory');+ }+ else {+ findings.push({ level: 'ok', message: 'Memory tiers defined (memory-tiers.md).' });+ if (!signals.memory.budget) {+ findings.push({+ level: 'warn',+ message: 'Memory tiers defined but no memory-budget.md — recall budget is missing.',+ });+ recommendations.push('Add memory-budget.md to cap retrieval costs.');+ }+ else {+ findings.push({ level: 'ok', message: 'Memory budget defined.' });+ }+ }const { score, level, assessment } = computeScore(signals);if (score >= 80 && !signals.harness.stack) {recommendations.unshift('Loop Ready 80+: version this loop as a harness — npx @cobusgreyling/loop-init . --with-foundry · showcase https://github.com/cobusgreyling/harness-foundry/blob/main/docs/showcase.md');}+ if (score >= 80 && !signals.memory.tiers) {+ recommendations.unshift("Loop Ready 80+: version this loop's memory — npx @cobusgreyling/loop-init . --with-memory");+ }const costReady = signals.cost.budgetDoc &&signals.cost.runLog &&signals.cost.loopMdBudget;diff --git a/tools/loop-audit/dist/autofixer.d.ts b/tools/loop-audit/dist/autofixer.d.tsnew file mode 100644index 0000000..931c450--- /dev/null+++ b/tools/loop-audit/dist/autofixer.d.ts@@ -0,0 +1,2 @@+import { AuditResult } from './auditor.js';+export declare function autoFixProject(target: string, result: AuditResult): Promise<void>;diff --git a/tools/loop-audit/dist/autofixer.js b/tools/loop-audit/dist/autofixer.jsnew file mode 100644index 0000000..56dc981--- /dev/null+++ b/tools/loop-audit/dist/autofixer.js@@ -0,0 +1,192 @@+import { writeFile, mkdir } from 'node:fs/promises';+import path from 'node:path';+import { fileExists } from '@cobusgreyling/readiness-core';+const STATE_MD_TEMPLATE = `# Loop State — YOUR_PROJECT++Last run: (set by loop on each run)++## High Priority (loop is acting or waiting on human)++<!-- Format:+- [ ] ID — one-line description+ Loop action: what the loop did last+ Human decision: (if any)+-->++## Watch List++<!-- Items to monitor but not act on yet -->++## Recent Noise (ignored this run)++<!-- Brief list — helps tune triage skill -->++---+Run log: (timestamp) | findings | actions | escalations+`;+const LOOP_BUDGET_TEMPLATE = `# Loop Budget — YOUR_PROJECT++## Daily limits++| Loop | Max runs/day | Max tokens/day | Max sub-agent spawns/run |+|------|--------------|----------------|--------------------------|+| Daily Triage | 2 | 100k | 0 (L1) / 2 (L2) |+| PR Babysitter | 288 | 2M | 3 |+| CI Sweeper | 96 | 1M | 3 |+| Dependency Sweeper | 4 | 500k | 3 |+| Post-Merge Cleanup | 1 | 200k | 2 |++## On budget exceed++1. Pause all schedulers (\`scheduler_delete\` or disable automations)+2. Append event to \`loop-run-log.md\`+3. Notify human (Slack / issue / STATE.md High Priority)++## Kill switch++- Command or issue label: \`loop-pause-all\`+- Resume only after human clears the flag in STATE.md+`;+const LOOP_RUN_LOG_TEMPLATE = `# 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 -->+`;+const LOOP_CONSTRAINTS_TEMPLATE = `# Loop Constraints++> Add rules below with \`/constraints <rule>\` in your agent.+> The \`loop-constraints\` skill reads this file at the start of every run.+> Constraints here are **binding** — the agent MUST follow them.++## Push & Merge+- Don't push before telling me+- Never auto-merge to main without human approval+- Always create a draft PR first; let me review before marking ready++## Paths+- Never edit .env, .env.*, auth/, payments/, secrets/, credentials/+- Never edit infrastructure configs without human approval++## Code+- Always run tests before proposing a fix+- 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+- Never close an issue or PR without my approval++## Budget+- If token spend hits 80% of daily cap, switch to report-only+- If loop-pause-all is active, exit immediately++---+<!-- Add your own rules below. Use plain English. The loop reads this verbatim. -->+`;+const LOOP_MD_TEMPLATE = `# Loop Configuration — Minimal Triage++## Active Loops++| Pattern | Cadence | Status | Command |+|---------|---------|--------|---------|+| Daily Triage | 1d | L1 report-only | See README |++## Human Gates++- No auto-fix until L2 checklist complete+- All high-risk paths: human review required++## Budget++- Max sub-agent spawns per run: 0 (L1) / 2 (L2)+- Max tokens/day: 100k (see \`loop-budget.md\`)+- Append each run to \`loop-run-log.md\`; use \`loop-budget\` skill at start/end+- Kill switch: \`loop-pause-all\` — pause schedulers and notify human+- Estimate: \`npx @cobusgreyling/loop-cost --pattern daily-triage\`+`;+const SAFETY_MD_TEMPLATE = `# Loop Safety Policy++## Auto-merge policy+- Never auto-merge to main. All code changes require human review.++## Path denylist+- .github/workflows/+- secrets/+- credentials/++## MCP Scopes+- Read-only unless explicitly allowed.+`;+const AGENTS_MD_TEMPLATE = `# AGENTS.md — Project Conventions++## Build & Test+- Run \`npm test\` to verify changes.++## Review Norms+- Never auto-merge changes.+- Ensure all loops isolate their work in worktrees.+`;+export async function autoFixProject(target, result) {+ const root = path.resolve(target);+ let fixesApplied = 0;+ console.log('\n=== Auto-Fixing Repository ===\n');+ const safeWriteFile = async (relPath, content, label) => {+ const fullPath = path.join(root, relPath);+ if (!(await fileExists(fullPath))) {+ await mkdir(path.dirname(fullPath), { recursive: true });+ await writeFile(fullPath, content, 'utf8');+ console.log(`✅ Generated ${relPath} (${label})`);+ fixesApplied++;+ }+ else {+ console.log(`⏭️ Skipped ${relPath} (already exists)`);+ }+ };+ if (!result.signals.stateFile.present) {+ await safeWriteFile('STATE.md', STATE_MD_TEMPLATE, 'Base state tracking');+ }+ if (!result.signals.loopConfig.present) {+ await safeWriteFile('LOOP.md', LOOP_MD_TEMPLATE, 'Loop configuration');+ }+ if (!result.signals.cost.budgetDoc) {+ await safeWriteFile('loop-budget.md', LOOP_BUDGET_TEMPLATE, 'Cost caps');+ }+ if (!result.signals.cost.runLog) {+ await safeWriteFile('loop-run-log.md', LOOP_RUN_LOG_TEMPLATE, 'Run history');+ }+ if (!result.signals.constraints.present) {+ await safeWriteFile('loop-constraints.md', LOOP_CONSTRAINTS_TEMPLATE, 'Agent rules');+ }+ if (!result.signals.safety.safetyDocPresent) {+ await safeWriteFile('docs/safety.md', SAFETY_MD_TEMPLATE, 'Safety policy');+ }+ if (!result.signals.agentsMd.present) {+ await safeWriteFile('AGENTS.md', AGENTS_MD_TEMPLATE, 'Project conventions');+ }+ if (fixesApplied > 0) {+ console.log(`\n✨ Applied ${fixesApplied} automatic fixes. Run loop-audit again to see your new score!`);+ }+ else {+ console.log('\nNo safe automatic fixes could be applied. (Check the suggestions manually).');+ }+}diff --git a/tools/loop-audit/dist/reporter.js b/tools/loop-audit/dist/reporter.jsindex f93e257..72df05f 100644--- a/tools/loop-audit/dist/reporter.js+++ b/tools/loop-audit/dist/reporter.js@@ -56,6 +56,11 @@ export function formatHuman(r) {lines.push('Harness stack present — run a session to earn session/trace credit:');lines.push(' npx @cobusgreyling/harness-foundry run --goal "Verify harness wiring"');}+ if (r.score >= 80 && !r.signals.memory?.tiers) {+ lines.push('');+ lines.push('Next after Loop Ready 80+: add cross-session memory (memory-engineering)');+ lines.push(' npx @cobusgreyling/loop-init . --with-memory');+ }lines.push('');return lines.join('\n');}diff --git a/tools/loop-audit/src/auditor.ts b/tools/loop-audit/src/auditor.tsindex 2887385..fccee5c 100644--- a/tools/loop-audit/src/auditor.ts+++ b/tools/loop-audit/src/auditor.ts@@ -38,6 +38,11 @@ export interface LoopSignals {emit: boolean;host: boolean;};+ /** memory-engineering setup (memory-tiers.md, memory-budget.md) */+ memory: {+ tiers: boolean;+ budget: boolean;+ };}export type { Finding };@@ -87,6 +92,9 @@ const SCORE_WEIGHTS = {harnessSessions: 2,harnessEmit: 1,harnessHost: 1,+ /** Memory Engineering (memory-tiers.md, memory-budget.md) */+ memoryTiers: 4,+ memoryBudget: 2,} as const;const LEVEL_THRESHOLDS = {@@ -290,6 +298,8 @@ export function computeScore(signals: LoopSignals): { score: number; level: 'L0'if (signals.harness.sessions) score += w.harnessSessions;if (signals.harness.emit) score += w.harnessEmit;if (signals.harness.host) score += w.harnessHost;+ if (signals.memory.tiers) score += w.memoryTiers;+ if (signals.memory.budget) score += w.memoryBudget;score = Math.min(100, Math.max(0, score));@@ -522,6 +532,11 @@ export async function auditProject(target: string): Promise<AuditResult> {host: harnessHost,};+ // Memory Engineering (memory-tiers.md, memory-budget.md)+ const memoryTiers = await fileExists(path.join(root, 'memory-tiers.md'));+ const memoryBudget = await fileExists(path.join(root, 'memory-budget.md'));+ const memory = { tiers: memoryTiers, budget: memoryBudget };+const signals: LoopSignals = {stateFile: { present: statePaths.length > 0, paths: statePaths },loopConfig: { present: loopMd, path: loopMd ? 'LOOP.md' : undefined },@@ -541,6 +556,7 @@ export async function auditProject(target: string): Promise<AuditResult> {governance: { toolScope, stallDetection, escalation },loopActivity,harness,+ memory,};if (!signals.stateFile.present) {@@ -709,6 +725,25 @@ export async function auditProject(target: string): Promise<AuditResult> {}}+ if (!signals.memory.tiers) {+ findings.push({+ level: 'warn',+ message: 'No memory-tiers.md — memory engineering tiers are not defined.',+ });+ recommendations.push('Scaffold memory tiers: npx @cobusgreyling/loop-init . --with-memory');+ } else {+ findings.push({ level: 'ok', message: 'Memory tiers defined (memory-tiers.md).' });+ if (!signals.memory.budget) {+ findings.push({+ level: 'warn',+ message: 'Memory tiers defined but no memory-budget.md — recall budget is missing.',+ });+ recommendations.push('Add memory-budget.md to cap retrieval costs.');+ } else {+ findings.push({ level: 'ok', message: 'Memory budget defined.' });+ }+ }+const { score, level, assessment } = computeScore(signals);if (score >= 80 && !signals.harness.stack) {@@ -717,6 +752,12 @@ export async function auditProject(target: string): Promise<AuditResult> {);}+ if (score >= 80 && !signals.memory.tiers) {+ recommendations.unshift(+ "Loop Ready 80+: version this loop's memory — npx @cobusgreyling/loop-init . --with-memory",+ );+ }+const costReady =signals.cost.budgetDoc &&signals.cost.runLog &&diff --git a/tools/loop-audit/src/reporter.ts b/tools/loop-audit/src/reporter.tsindex e46826a..f3cbcf8 100644--- a/tools/loop-audit/src/reporter.ts+++ b/tools/loop-audit/src/reporter.ts@@ -62,6 +62,12 @@ export function formatHuman(r: AuditResult): string {lines.push('Harness stack present — run a session to earn session/trace credit:');lines.push(' npx @cobusgreyling/harness-foundry run --goal "Verify harness wiring"');}++ if (r.score >= 80 && !r.signals.memory?.tiers) {+ lines.push('');+ lines.push('Next after Loop Ready 80+: add cross-session memory (memory-engineering)');+ lines.push(' npx @cobusgreyling/loop-init . --with-memory');+ }lines.push('');return lines.join('\n');}diff --git a/tools/loop-audit/test/auditor.test.mjs b/tools/loop-audit/test/auditor.test.mjsindex d0f76fd..972178d 100644--- a/tools/loop-audit/test/auditor.test.mjs+++ b/tools/loop-audit/test/auditor.test.mjs@@ -27,6 +27,7 @@ function emptySignals() {governance: { toolScope: false, stallDetection: false, escalation: false },loopActivity: { present: false, evidence: [] },harness: { stack: false, lock: false, sessions: false, emit: false, host: false },+ memory: { tiers: false, budget: false },};}@@ -238,6 +239,26 @@ test('auditProject: missing harness recommends --with-foundry', async () => {}});+test('computeScore: memory signals add points', () => {+ const base = emptySignals();+ const { score: without } = computeScore(base);+ const withMemory = emptySignals();+ withMemory.memory = { tiers: true, budget: true };+ const { score: withScore } = computeScore(withMemory);+ assert.equal(withScore - without, 6);+});++test('auditProject: missing memory recommends --with-memory', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'loop-audit-nomemory-'));+ try {+ const result = await auditProject(dir);+ assert.equal(result.signals.memory.tiers, false);+ assert.ok(result.recommendations.some((r) => r.includes('--with-memory')));+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});+test('auditProject: git commit with triage counts as loop activity', async () => {const dir = await mkdtemp(path.join(tmpdir(), 'loop-audit-git-'));try {diff --git a/tools/loop-init/dist/cli.js b/tools/loop-init/dist/cli.jsindex b2d9868..3593796 100644--- a/tools/loop-init/dist/cli.js+++ b/tools/loop-init/dist/cli.js@@ -72,6 +72,7 @@ function parseArgs(argv) {let target = '.';let dryRun = false;let withFoundry = false;+ let withMemory = false;for (let i = 0; i < argv.length; i++) {const a = argv[i];if (a === '--pattern' || a === '-p')@@ -82,12 +83,14 @@ function parseArgs(argv) {dryRun = true;else if (a === '--with-foundry')withFoundry = true;+ else if (a === '--with-memory')+ withMemory = true;else if (a === '--help' || a === '-h')- return { help: true, pattern, tool, target, dryRun, withFoundry };+ return { help: true, pattern, tool, target, dryRun, withFoundry, withMemory };else if (!a.startsWith('-'))target = a;}- return { help: false, pattern, tool, target, dryRun, withFoundry };+ return { help: false, pattern, tool, target, dryRun, withFoundry, withMemory };}function foundryStackYaml(stackName, pattern, preset) {if (preset === 'implementer') {@@ -188,6 +191,18 @@ Showcase: ${FOUNDRY_SHOWCASE}}return { preset, stackFile };}+async function scaffoldMemory(targetDir, templatesRoot, dryRun) {+ const tiersTemplate = path.join(templatesRoot, 'memory-tiers.md');+ const tiersDest = path.join(targetDir, 'memory-tiers.md');+ if (!(await exists(tiersDest))) {+ await copyFile(tiersTemplate, tiersDest, dryRun);+ }+ const budgetTemplate = path.join(templatesRoot, 'memory-budget.md');+ const budgetDest = path.join(targetDir, 'memory-budget.md');+ if (!(await exists(budgetDest))) {+ await copyFile(budgetTemplate, budgetDest, dryRun);+ }+}function printFoundryCta(opts) {const { pattern, tool, withFoundry, score, preset } = opts;const mapped = preset ?? PATTERN_FOUNDRY_PRESET[pattern];@@ -209,6 +224,19 @@ function printFoundryCta(opts) {console.log(` Showcase: ${FOUNDRY_SHOWCASE}`);}}+function printMemoryCta(opts) {+ const { pattern, tool, withMemory, score } = opts;+ console.log('');+ if (withMemory) {+ console.log('Memory engineering stack ready (memory-tiers.md, memory-budget.md)');+ return;+ }+ const highReady = score !== null && score >= 80;+ console.log(highReady+ ? "Next after Loop Ready 80+: version this loop's memory (memory-engineering)"+ : 'Optional: add memory-engineering for cross-session knowledge');+ console.log(` npx @cobusgreyling/loop-init . --pattern ${pattern} --tool ${tool} --with-memory`);+}async function exists(p) {try {await access(p);@@ -535,6 +563,7 @@ Options:-p, --pattern Pattern to scaffold-t, --tool Tool target (default: grok)--with-foundry Also scaffold .foundry/ stack (harness-foundry runtime)+ --with-memory Also scaffold memory-engineering tiers and budget--dry-run Print actions without copying-h, --help This help@@ -547,10 +576,11 @@ Examples:npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok --with-foundrynpx @cobusgreyling/loop-init . -p pr-babysitter -t claude --with-foundrynpx @cobusgreyling/loop-init . -p daily-triage -t opencode+ npx @cobusgreyling/loop-init . --with-memory`);process.exit(0);}- const { pattern, tool, target, dryRun, withFoundry } = args;+ const { pattern, tool, target, dryRun, withFoundry, withMemory } = args;const validPatterns = Object.keys(PATTERN_STARTERS);const validTools = Object.keys(TOOL_SUFFIX);if (!validPatterns.includes(pattern)) {@@ -670,6 +700,11 @@ npm run lintconst foundry = await scaffoldFoundry(pattern, targetDir, dryRun);foundryPreset = foundry?.preset;}+ if (withMemory) {+ console.log('');+ console.log('Memory engineering:');+ await scaffoldMemory(targetDir, templatesRoot, dryRun);+ }const auditArg = auditTargetArg(target, targetDir);let auditScore = null;if (!dryRun) {@@ -710,6 +745,12 @@ npm run lintscore: auditScore,preset: foundryPreset,});+ printMemoryCta({+ pattern,+ tool,+ withMemory,+ score: auditScore,+ });printContributorCta();}async function readDirNames(dir) {diff --git a/tools/loop-init/registry.yaml b/tools/loop-init/registry.yamlindex edb05c3..c29c72b 100644--- a/tools/loop-init/registry.yaml+++ b/tools/loop-init/registry.yaml@@ -20,6 +20,7 @@ patterns:tokens_noop: 3000tokens_report: 80000tokens_action: 250000+ stable_fraction: 0.35suggested_daily_cap: 2000000early_exit_required: true@@ -41,6 +42,7 @@ patterns:tokens_noop: 5000tokens_report: 50000tokens_action: 200000+ stable_fraction: 0.35suggested_daily_cap: 100000early_exit_required: false@@ -62,6 +64,7 @@ patterns:tokens_noop: 5000tokens_report: 50000tokens_action: 200000+ stable_fraction: 0.35suggested_daily_cap: 1000000early_exit_required: true@@ -83,6 +86,7 @@ patterns:tokens_noop: 5000tokens_report: 40000tokens_action: 150000+ stable_fraction: 0.35suggested_daily_cap: 200000early_exit_required: false@@ -104,6 +108,7 @@ patterns:tokens_noop: 5000tokens_report: 60000tokens_action: 300000+ stable_fraction: 0.35suggested_daily_cap: 500000early_exit_required: true@@ -125,6 +130,7 @@ patterns:tokens_noop: 5000tokens_report: 35000tokens_action: 80000+ stable_fraction: 0.35suggested_daily_cap: 100000early_exit_required: false@@ -146,5 +152,6 @@ patterns:tokens_noop: 3000tokens_report: 30000tokens_action: 60000+ stable_fraction: 0.35suggested_daily_cap: 80000early_exit_required: falsediff --git a/tools/loop-init/src/cli.ts b/tools/loop-init/src/cli.tsindex 9e7c31e..d19cc72 100644--- a/tools/loop-init/src/cli.ts+++ b/tools/loop-init/src/cli.ts@@ -100,6 +100,7 @@ function parseArgs(argv: string[]) {let target = '.';let dryRun = false;let withFoundry = false;+ let withMemory = false;for (let i = 0; i < argv.length; i++) {const a = argv[i];@@ -107,12 +108,13 @@ function parseArgs(argv: string[]) {else if (a === '--tool' || a === '-t') tool = argv[++i] as Tool;else if (a === '--dry-run') dryRun = true;else if (a === '--with-foundry') withFoundry = true;+ else if (a === '--with-memory') withMemory = true;else if (a === '--help' || a === '-h')- return { help: true as const, pattern, tool, target, dryRun, withFoundry };+ return { help: true as const, pattern, tool, target, dryRun, withFoundry, withMemory };else if (!a.startsWith('-')) target = a;}- return { help: false as const, pattern, tool, target, dryRun, withFoundry };+ return { help: false as const, pattern, tool, target, dryRun, withFoundry, withMemory };}function foundryStackYaml(stackName: string, pattern: Pattern, preset: FoundryPreset): string {@@ -225,6 +227,24 @@ Showcase: ${FOUNDRY_SHOWCASE}return { preset, stackFile };}+async function scaffoldMemory(+ targetDir: string,+ templatesRoot: string,+ dryRun: boolean,+) {+ const tiersTemplate = path.join(templatesRoot, 'memory-tiers.md');+ const tiersDest = path.join(targetDir, 'memory-tiers.md');+ if (!(await exists(tiersDest))) {+ await copyFile(tiersTemplate, tiersDest, dryRun);+ }++ const budgetTemplate = path.join(templatesRoot, 'memory-budget.md');+ const budgetDest = path.join(targetDir, 'memory-budget.md');+ if (!(await exists(budgetDest))) {+ await copyFile(budgetTemplate, budgetDest, dryRun);+ }+}+function printFoundryCta(opts: {pattern: Pattern;tool: Tool;@@ -260,6 +280,30 @@ function printFoundryCta(opts: {}}+function printMemoryCta(opts: {+ pattern: Pattern;+ tool: Tool;+ withMemory: boolean;+ score: number | null;+}) {+ const { pattern, tool, withMemory, score } = opts;+ console.log('');+ if (withMemory) {+ console.log('Memory engineering stack ready (memory-tiers.md, memory-budget.md)');+ return;+ }++ const highReady = score !== null && score >= 80;+ console.log(+ highReady+ ? "Next after Loop Ready 80+: version this loop's memory (memory-engineering)"+ : 'Optional: add memory-engineering for cross-session knowledge',+ );+ console.log(+ ` npx @cobusgreyling/loop-init . --pattern ${pattern} --tool ${tool} --with-memory`,+ );+}+async function exists(p: string): Promise<boolean> {try {await access(p);@@ -648,6 +692,7 @@ Options:-p, --pattern Pattern to scaffold-t, --tool Tool target (default: grok)--with-foundry Also scaffold .foundry/ stack (harness-foundry runtime)+ --with-memory Also scaffold memory-engineering tiers and budget--dry-run Print actions without copying-h, --help This help@@ -660,11 +705,12 @@ Examples:npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok --with-foundrynpx @cobusgreyling/loop-init . -p pr-babysitter -t claude --with-foundrynpx @cobusgreyling/loop-init . -p daily-triage -t opencode+ npx @cobusgreyling/loop-init . --with-memory`);process.exit(0);}- const { pattern, tool, target, dryRun, withFoundry } = args;+ const { pattern, tool, target, dryRun, withFoundry, withMemory } = args;const validPatterns = Object.keys(PATTERN_STARTERS) as Pattern[];const validTools = Object.keys(TOOL_SUFFIX) as Tool[];@@ -805,6 +851,12 @@ npm run lintfoundryPreset = foundry?.preset;}+ if (withMemory) {+ console.log('');+ console.log('Memory engineering:');+ await scaffoldMemory(targetDir, templatesRoot, dryRun);+ }+const auditArg = auditTargetArg(target, targetDir);let auditScore: number | null = null;@@ -848,6 +900,12 @@ npm run lintscore: auditScore,preset: foundryPreset,});+ printMemoryCta({+ pattern,+ tool,+ withMemory,+ score: auditScore,+ });printContributorCta();}diff --git a/tools/loop-init/test/cli.test.mjs b/tools/loop-init/test/cli.test.mjsindex f99aa3b..7b53c79 100644--- a/tools/loop-init/test/cli.test.mjs+++ b/tools/loop-init/test/cli.test.mjs@@ -248,3 +248,43 @@ test('loop-init --help documents --with-foundry', async () => {assert.match(stdout, /--with-foundry/);assert.match(stdout, /harness-foundry|implementer|minimal/);});++test('loop-init prints memory CTA without --with-memory', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'loop-init-mem-cta-'));+ try {+ const { stdout } = await exec('node', [CLI, dir, '--pattern', 'daily-triage', '--tool', 'grok']);+ assert.match(stdout, /--with-memory/);+ assert.match(stdout, /memory-engineering/);+ await assert.rejects(() => access(path.join(dir, 'memory-tiers.md')));+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test('loop-init --with-memory scaffolds tiers and budget', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'loop-init-memory-'));+ try {+ const { stdout } = await exec('node', [+ CLI,+ dir,+ '--pattern',+ 'daily-triage',+ '--tool',+ 'grok',+ '--with-memory',+ ]);+ await access(path.join(dir, 'memory-tiers.md'));+ await access(path.join(dir, 'memory-budget.md'));+ const tiers = await readFile(path.join(dir, 'memory-tiers.md'), 'utf8');+ assert.match(tiers, /Working Memory/);+ assert.match(stdout, /Memory engineering stack ready/);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test('loop-init --help documents --with-memory', async () => {+ const { stdout } = await exec('node', [CLI, '--help']);+ assert.match(stdout, /--with-memory/);+ assert.match(stdout, /memory-engineering tiers and budget/);+});