Skip to content

Commit 3d63fd3

Browse files
authored
Merge pull request anomalyco#233 from andydiaz122/nano_claw_v1
LGTM — NanoClaw agent REPL. Safe, uses only local Claude CLI, good input validation, includes tests.
2 parents f80004e + e0b3a7b commit 3d63fd3

5 files changed

Lines changed: 587 additions & 0 deletions

File tree

‎commands/claw.md‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
---
2+
description: Start the NanoClaw agent REPL — a persistent, session-aware AI assistant powered by the claude CLI.
3+
---
4+
5+
# Claw Command
6+
7+
Start an interactive AI agent session that persists conversation history to disk and optionally loads ECC skill context.
8+
9+
## Usage
10+
11+
```bash
12+
node scripts/claw.js
13+
```
14+
15+
Or via npm:
16+
17+
```bash
18+
npm run claw
19+
```
20+
21+
## Environment Variables
22+
23+
| Variable | Default | Description |
24+
|----------|---------|-------------|
25+
| `CLAW_SESSION` | `default` | Session name (alphanumeric + hyphens) |
26+
| `CLAW_SKILLS` | *(empty)* | Comma-separated skill names to load as system context |
27+
28+
## REPL Commands
29+
30+
Inside the REPL, type these commands directly at the prompt:
31+
32+
```
33+
/clear Clear current session history
34+
/history Print full conversation history
35+
/sessions List all saved sessions
36+
/help Show available commands
37+
exit Quit the REPL
38+
```
39+
40+
## How It Works
41+
42+
1. Reads `CLAW_SESSION` env var to select a named session (default: `default`)
43+
2. Loads conversation history from `~/.claude/claw/{session}.md`
44+
3. Optionally loads ECC skill context from `CLAW_SKILLS` env var
45+
4. Enters a blocking prompt loop — each user message is sent to `claude -p` with full history
46+
5. Responses are appended to the session file for persistence across restarts
47+
48+
## Session Storage
49+
50+
Sessions are stored as Markdown files in `~/.claude/claw/`:
51+
52+
```
53+
~/.claude/claw/default.md
54+
~/.claude/claw/my-project.md
55+
```
56+
57+
Each turn is formatted as:
58+
59+
```markdown
60+
### [2025-01-15T10:30:00.000Z] User
61+
What does this function do?
62+
---
63+
### [2025-01-15T10:30:05.000Z] Assistant
64+
This function calculates...
65+
---
66+
```
67+
68+
## Examples
69+
70+
```bash
71+
# Start default session
72+
node scripts/claw.js
73+
74+
# Named session
75+
CLAW_SESSION=my-project node scripts/claw.js
76+
77+
# With skill context
78+
CLAW_SKILLS=tdd-workflow,security-review node scripts/claw.js
79+
```

‎package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
"scripts/ci/",
6262
"scripts/hooks/",
6363
"scripts/lib/",
64+
"scripts/claw.js",
6465
"scripts/setup-package-manager.js",
6566
"scripts/skill-create-output.js",
6667
"skills/",
@@ -75,6 +76,7 @@
7576
"scripts": {
7677
"postinstall": "echo '\\n ecc-universal installed!\\n Run: npx ecc-install typescript\\n Docs: https://github.com/affaan-m/everything-claude-code\\n'",
7778
"lint": "eslint . && markdownlint '**/*.md' --ignore node_modules",
79+
"claw": "node scripts/claw.js",
7880
"test": "node scripts/ci/validate-agents.js && node scripts/ci/validate-commands.js && node scripts/ci/validate-rules.js && node scripts/ci/validate-skills.js && node scripts/ci/validate-hooks.js && node tests/run-all.js"
7981
},
8082
"devDependencies": {

‎scripts/claw.js‎

Lines changed: 267 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,267 @@
1+
#!/usr/bin/env node
2+
/**
3+
* NanoClaw — Barebones Agent REPL for Everything Claude Code
4+
*
5+
* A persistent, session-aware AI agent loop that delegates to `claude -p`.
6+
* Zero external dependencies. Markdown-as-database. Synchronous REPL.
7+
*
8+
* Usage:
9+
* node scripts/claw.js
10+
* CLAW_SESSION=my-project node scripts/claw.js
11+
* CLAW_SKILLS=tdd-workflow,security-review node scripts/claw.js
12+
*/
13+
14+
'use strict';
15+
16+
const fs = require('fs');
17+
const path = require('path');
18+
const os = require('os');
19+
const { spawnSync } = require('child_process');
20+
const readline = require('readline');
21+
22+
// ─── Session name validation ────────────────────────────────────────────────
23+
24+
const SESSION_NAME_RE = /^[a-zA-Z0-9][-a-zA-Z0-9]*$/;
25+
26+
function isValidSessionName(name) {
27+
return typeof name === 'string' && name.length > 0 && SESSION_NAME_RE.test(name);
28+
}
29+
30+
// ─── Storage Adapter (Markdown-as-Database) ─────────────────────────────────
31+
32+
function getClawDir() {
33+
return path.join(os.homedir(), '.claude', 'claw');
34+
}
35+
36+
function getSessionPath(name) {
37+
return path.join(getClawDir(), name + '.md');
38+
}
39+
40+
function listSessions(dir) {
41+
const clawDir = dir || getClawDir();
42+
if (!fs.existsSync(clawDir)) {
43+
return [];
44+
}
45+
return fs.readdirSync(clawDir)
46+
.filter(f => f.endsWith('.md'))
47+
.map(f => f.replace(/\.md$/, ''));
48+
}
49+
50+
function loadHistory(filePath) {
51+
try {
52+
return fs.readFileSync(filePath, 'utf8');
53+
} catch (_err) {
54+
return '';
55+
}
56+
}
57+
58+
function appendTurn(filePath, role, content, timestamp) {
59+
const ts = timestamp || new Date().toISOString();
60+
const entry = `### [${ts}] ${role}\n${content}\n---\n`;
61+
const dir = path.dirname(filePath);
62+
fs.mkdirSync(dir, { recursive: true });
63+
fs.appendFileSync(filePath, entry, 'utf8');
64+
}
65+
66+
// ─── Context & Delegation Pipeline ──────────────────────────────────────────
67+
68+
function loadECCContext(skillList) {
69+
const raw = skillList !== undefined ? skillList : (process.env.CLAW_SKILLS || '');
70+
if (!raw.trim()) {
71+
return '';
72+
}
73+
74+
const names = raw.split(',').map(s => s.trim()).filter(Boolean);
75+
const chunks = [];
76+
77+
for (const name of names) {
78+
const skillPath = path.join(process.cwd(), 'skills', name, 'SKILL.md');
79+
try {
80+
const content = fs.readFileSync(skillPath, 'utf8');
81+
chunks.push(content);
82+
} catch (_err) {
83+
// Gracefully skip missing skills
84+
}
85+
}
86+
87+
return chunks.join('\n\n');
88+
}
89+
90+
function buildPrompt(systemPrompt, history, userMessage) {
91+
const parts = [];
92+
if (systemPrompt) {
93+
parts.push('=== SYSTEM CONTEXT ===\n' + systemPrompt + '\n');
94+
}
95+
if (history) {
96+
parts.push('=== CONVERSATION HISTORY ===\n' + history + '\n');
97+
}
98+
parts.push('=== USER MESSAGE ===\n' + userMessage);
99+
return parts.join('\n');
100+
}
101+
102+
function askClaude(systemPrompt, history, userMessage) {
103+
const fullPrompt = buildPrompt(systemPrompt, history, userMessage);
104+
105+
const result = spawnSync('claude', ['-p', fullPrompt], {
106+
encoding: 'utf8',
107+
stdio: ['pipe', 'pipe', 'pipe'],
108+
env: { ...process.env, CLAUDECODE: '' },
109+
timeout: 300000 // 5 minute timeout
110+
});
111+
112+
if (result.error) {
113+
return '[Error: ' + result.error.message + ']';
114+
}
115+
116+
if (result.status !== 0 && result.stderr) {
117+
return '[Error: claude exited with code ' + result.status + ': ' + result.stderr.trim() + ']';
118+
}
119+
120+
return (result.stdout || '').trim();
121+
}
122+
123+
// ─── REPL Commands ──────────────────────────────────────────────────────────
124+
125+
function handleClear(sessionPath) {
126+
fs.mkdirSync(path.dirname(sessionPath), { recursive: true });
127+
fs.writeFileSync(sessionPath, '', 'utf8');
128+
console.log('Session cleared.');
129+
}
130+
131+
function handleHistory(sessionPath) {
132+
const history = loadHistory(sessionPath);
133+
if (!history) {
134+
console.log('(no history)');
135+
} else {
136+
console.log(history);
137+
}
138+
}
139+
140+
function handleSessions(dir) {
141+
const sessions = listSessions(dir);
142+
if (sessions.length === 0) {
143+
console.log('(no sessions)');
144+
} else {
145+
console.log('Sessions:');
146+
for (const s of sessions) {
147+
console.log(' - ' + s);
148+
}
149+
}
150+
}
151+
152+
function handleHelp() {
153+
console.log('NanoClaw REPL Commands:');
154+
console.log(' /clear Clear current session history');
155+
console.log(' /history Print full conversation history');
156+
console.log(' /sessions List all saved sessions');
157+
console.log(' /help Show this help message');
158+
console.log(' exit Quit the REPL');
159+
}
160+
161+
// ─── Main REPL ──────────────────────────────────────────────────────────────
162+
163+
function main() {
164+
const sessionName = process.env.CLAW_SESSION || 'default';
165+
166+
if (!isValidSessionName(sessionName)) {
167+
console.error('Error: Invalid session name "' + sessionName + '". Use alphanumeric characters and hyphens only.');
168+
process.exit(1);
169+
}
170+
171+
const clawDir = getClawDir();
172+
fs.mkdirSync(clawDir, { recursive: true });
173+
174+
const sessionPath = getSessionPath(sessionName);
175+
const eccContext = loadECCContext();
176+
177+
const requestedSkills = (process.env.CLAW_SKILLS || '').split(',').map(s => s.trim()).filter(Boolean);
178+
const loadedCount = requestedSkills.filter(name =>
179+
fs.existsSync(path.join(process.cwd(), 'skills', name, 'SKILL.md'))
180+
).length;
181+
182+
console.log('NanoClaw v1.0 — Session: ' + sessionName);
183+
if (loadedCount > 0) {
184+
console.log('Loaded ' + loadedCount + ' skill(s) as context.');
185+
}
186+
console.log('Type /help for commands, exit to quit.\n');
187+
188+
const rl = readline.createInterface({
189+
input: process.stdin,
190+
output: process.stdout
191+
});
192+
193+
const prompt = () => {
194+
rl.question('claw> ', (input) => {
195+
const line = input.trim();
196+
197+
if (!line) {
198+
prompt();
199+
return;
200+
}
201+
202+
if (line === 'exit') {
203+
console.log('Goodbye.');
204+
rl.close();
205+
return;
206+
}
207+
208+
if (line === '/clear') {
209+
handleClear(sessionPath);
210+
prompt();
211+
return;
212+
}
213+
214+
if (line === '/history') {
215+
handleHistory(sessionPath);
216+
prompt();
217+
return;
218+
}
219+
220+
if (line === '/sessions') {
221+
handleSessions();
222+
prompt();
223+
return;
224+
}
225+
226+
if (line === '/help') {
227+
handleHelp();
228+
prompt();
229+
return;
230+
}
231+
232+
// Regular message — send to Claude
233+
const history = loadHistory(sessionPath);
234+
appendTurn(sessionPath, 'User', line);
235+
const response = askClaude(eccContext, history, line);
236+
console.log('\n' + response + '\n');
237+
appendTurn(sessionPath, 'Assistant', response);
238+
239+
prompt();
240+
});
241+
};
242+
243+
prompt();
244+
}
245+
246+
// ─── Exports & CLI Entry ────────────────────────────────────────────────────
247+
248+
module.exports = {
249+
getClawDir,
250+
getSessionPath,
251+
listSessions,
252+
loadHistory,
253+
appendTurn,
254+
loadECCContext,
255+
askClaude,
256+
buildPrompt,
257+
isValidSessionName,
258+
handleClear,
259+
handleHistory,
260+
handleSessions,
261+
handleHelp,
262+
main
263+
};
264+
265+
if (require.main === module) {
266+
main();
267+
}

‎tests/run-all.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const testFiles = [
2020
'hooks/suggest-compact.test.js',
2121
'integration/hooks.test.js',
2222
'ci/validators.test.js',
23+
'scripts/claw.test.js',
2324
'scripts/setup-package-manager.test.js',
2425
'scripts/skill-create-output.test.js'
2526
];

0 commit comments

Comments
 (0)