@jsleekr/graft 6.1.0 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * graft import — reverse-compiles a .claude/ harness structure into a .gft file.
3
+ *
4
+ * Reads:
5
+ * .claude/agents/*.md → node declarations
6
+ * .claude/hooks/*.js → edge declarations with transforms
7
+ * .claude/settings.json → model routing, budget
8
+ * .claude/orchestration.md or .claude/CLAUDE.md → graph flow
9
+ *
10
+ * Outputs a valid .gft source string.
11
+ */
12
+ export declare function importHarness(dir: string): string;
@@ -0,0 +1,368 @@
1
+ /**
2
+ * graft import — reverse-compiles a .claude/ harness structure into a .gft file.
3
+ *
4
+ * Reads:
5
+ * .claude/agents/*.md → node declarations
6
+ * .claude/hooks/*.js → edge declarations with transforms
7
+ * .claude/settings.json → model routing, budget
8
+ * .claude/orchestration.md or .claude/CLAUDE.md → graph flow
9
+ *
10
+ * Outputs a valid .gft source string.
11
+ */
12
+ import * as fs from 'node:fs';
13
+ import * as path from 'node:path';
14
+ const MODEL_SHORT = {
15
+ 'claude-haiku-4-5-20251001': 'haiku',
16
+ 'claude-sonnet-4-20250514': 'sonnet',
17
+ 'claude-opus-4-20250514': 'opus',
18
+ 'claude-sonnet-4-6-20250610': 'sonnet',
19
+ 'claude-opus-4-6-20250610': 'opus',
20
+ };
21
+ function shortModel(model) {
22
+ return MODEL_SHORT[model] || model;
23
+ }
24
+ function parseAgent(filePath) {
25
+ const content = fs.readFileSync(filePath, 'utf-8');
26
+ const lines = content.split('\n');
27
+ // Parse YAML frontmatter
28
+ let name = '';
29
+ let model = 'sonnet';
30
+ let inFrontmatter = false;
31
+ let frontmatterEnd = 0;
32
+ for (let i = 0; i < lines.length; i++) {
33
+ const line = lines[i].trim();
34
+ if (i === 0 && line === '---') {
35
+ inFrontmatter = true;
36
+ continue;
37
+ }
38
+ if (inFrontmatter && line === '---') {
39
+ frontmatterEnd = i;
40
+ break;
41
+ }
42
+ if (inFrontmatter) {
43
+ const match = line.match(/^(\w+):\s*(.+)$/);
44
+ if (match) {
45
+ if (match[1] === 'name')
46
+ name = match[2];
47
+ if (match[1] === 'model')
48
+ model = shortModel(match[2]);
49
+ }
50
+ }
51
+ }
52
+ if (!name) {
53
+ name = path.basename(filePath, '.md');
54
+ }
55
+ // Parse reads from "Context Loading" section
56
+ const reads = [];
57
+ const contextRegex = /Load `(\w+)`/g;
58
+ let m;
59
+ while ((m = contextRegex.exec(content)) !== null) {
60
+ reads.push(m[1]);
61
+ }
62
+ // Also check for "Also reads:" or reads from other sources
63
+ const alsoReadsRegex = /Also reads:.*\((\w+)\)/g;
64
+ while ((m = alsoReadsRegex.exec(content)) !== null) {
65
+ if (!reads.includes(m[1]))
66
+ reads.push(m[1]);
67
+ }
68
+ // Parse produces from JSON schema
69
+ let producesName = '';
70
+ const producesFields = [];
71
+ const descMatch = content.match(/description:\s*\w+ agent — produces (\w+)/);
72
+ if (descMatch)
73
+ producesName = descMatch[1];
74
+ // Parse JSON schema block
75
+ const jsonMatch = content.match(/```json\n([\s\S]*?)```/);
76
+ if (jsonMatch) {
77
+ try {
78
+ const schema = JSON.parse(jsonMatch[1]);
79
+ for (const [key, val] of Object.entries(schema)) {
80
+ producesFields.push({ name: key, type: inferGftType(val) });
81
+ }
82
+ }
83
+ catch {
84
+ // Best-effort
85
+ }
86
+ }
87
+ // Parse budgets
88
+ let inputBudget = 4000;
89
+ let outputBudget = 2000;
90
+ const inputMatch = content.match(/Input budget:\s*([\d,]+)\s*tokens/);
91
+ const outputMatch = content.match(/Output budget:\s*([\d,]+)\s*tokens/);
92
+ if (inputMatch)
93
+ inputBudget = parseInt(inputMatch[1].replace(/,/g, ''));
94
+ if (outputMatch)
95
+ outputBudget = parseInt(outputMatch[1].replace(/,/g, ''));
96
+ // Extract proper case from "# Name Agent" heading or description
97
+ const headingMatch = content.match(/^# (\w+) Agent/m);
98
+ const capName = headingMatch ? headingMatch[1] : name.charAt(0).toUpperCase() + name.slice(1);
99
+ if (!producesName)
100
+ producesName = capName + 'Output';
101
+ return {
102
+ name: capName,
103
+ model,
104
+ inputBudget,
105
+ outputBudget,
106
+ reads,
107
+ producesName,
108
+ producesFields,
109
+ };
110
+ }
111
+ function inferGftType(val) {
112
+ if (val === null || val === undefined)
113
+ return 'String';
114
+ if (typeof val === 'string') {
115
+ if (val === '<string>')
116
+ return 'String';
117
+ if (val === '<number>' || val === '<int>')
118
+ return 'Int';
119
+ if (val === '<float>')
120
+ return 'Float';
121
+ if (val === '<bool>' || val === 'true' || val === 'false')
122
+ return 'Bool';
123
+ return 'String';
124
+ }
125
+ if (typeof val === 'number')
126
+ return Number.isInteger(val) ? 'Int' : 'Float';
127
+ if (typeof val === 'boolean')
128
+ return 'Bool';
129
+ if (Array.isArray(val)) {
130
+ if (val.length > 0)
131
+ return `List<${inferGftType(val[0])}>`;
132
+ return 'List<String>';
133
+ }
134
+ if (typeof val === 'object') {
135
+ // Inline struct — for now simplify to String
136
+ return 'String';
137
+ }
138
+ return 'String';
139
+ }
140
+ function parseHook(filePath) {
141
+ const content = fs.readFileSync(filePath, 'utf-8');
142
+ // Parse "Edge: Source -> Target" comment
143
+ const edgeMatch = content.match(/Edge:\s*(\w+)\s*->\s*(\w+)/);
144
+ if (!edgeMatch)
145
+ return null;
146
+ const source = edgeMatch[1];
147
+ const target = edgeMatch[2];
148
+ const transforms = [];
149
+ // Detect select: look for `result = { "field1": data["field1"], ... }`
150
+ const selectMatch = content.match(/let result = \{([^}]+)\}/);
151
+ if (selectMatch) {
152
+ const fields = [];
153
+ const fieldRegex = /"(\w+)":\s*data\["/g;
154
+ let fm;
155
+ while ((fm = fieldRegex.exec(selectMatch[1])) !== null) {
156
+ fields.push(fm[1]);
157
+ }
158
+ if (fields.length > 0) {
159
+ transforms.push(`select(${fields.join(', ')})`);
160
+ }
161
+ }
162
+ // Detect compact
163
+ if (content.includes('function compact(')) {
164
+ transforms.push('compact');
165
+ }
166
+ // Detect filter
167
+ const filterMatch = content.match(/\.filter\(\s*\w+\s*=>\s*\w+\["(\w+)"\]\s*(>=?|<=?|===?|!==?)\s*(.+?)\)/);
168
+ if (filterMatch) {
169
+ transforms.push(`filter(${filterMatch[1]} ${filterMatch[2]} ${filterMatch[3].trim()})`);
170
+ }
171
+ // Detect truncate (look for explicit truncate comment or large slice, not timestamp slicing)
172
+ const truncMatch = content.match(/truncate.*\.slice\(0,\s*(\d+)\)/i);
173
+ if (truncMatch) {
174
+ transforms.push(`truncate(${truncMatch[1]})`);
175
+ }
176
+ // Detect drop
177
+ const dropMatch = content.match(/delete\s+\w+\["(\w+)"\]/);
178
+ if (dropMatch) {
179
+ transforms.push(`drop(${dropMatch[1]})`);
180
+ }
181
+ return { source, target, transforms };
182
+ }
183
+ function parseSettings(filePath) {
184
+ if (!fs.existsSync(filePath))
185
+ return null;
186
+ try {
187
+ const content = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
188
+ const graft = content.graft || {};
189
+ const budget = graft.budget?.total || 50000;
190
+ const routing = {};
191
+ if (graft.model_routing?.overrides) {
192
+ for (const [agent, model] of Object.entries(graft.model_routing.overrides)) {
193
+ routing[agent] = shortModel(model);
194
+ }
195
+ }
196
+ return { graphBudget: budget, modelRouting: routing };
197
+ }
198
+ catch {
199
+ return null;
200
+ }
201
+ }
202
+ function parseOrchestration(dir) {
203
+ const steps = [];
204
+ const parallelGroups = [];
205
+ // Try orchestration.md first, then CLAUDE.md
206
+ let content = '';
207
+ const orchPath = path.join(dir, '.claude', 'orchestration.md');
208
+ const claudePath = path.join(dir, '.claude', 'CLAUDE.md');
209
+ if (fs.existsSync(orchPath)) {
210
+ content = fs.readFileSync(orchPath, 'utf-8');
211
+ }
212
+ else if (fs.existsSync(claudePath)) {
213
+ content = fs.readFileSync(claudePath, 'utf-8');
214
+ }
215
+ if (!content)
216
+ return { steps, parallelGroups };
217
+ // Parse steps
218
+ const stepRegex = /### Step \d+:\s*(.+)/g;
219
+ let sm;
220
+ while ((sm = stepRegex.exec(content)) !== null) {
221
+ const stepLine = sm[1];
222
+ if (stepLine.includes('[parallel]')) {
223
+ const names = stepLine.replace('[parallel]', '').trim().split(/,\s*/);
224
+ parallelGroups.push(names);
225
+ steps.push(`parallel:${names.join(',')}`);
226
+ }
227
+ else if (stepLine.includes('[sequential]')) {
228
+ const name = stepLine.replace('[sequential]', '').trim();
229
+ steps.push(name);
230
+ }
231
+ else if (stepLine.includes('[foreach')) {
232
+ steps.push(stepLine.trim());
233
+ }
234
+ else {
235
+ // Fallback: extract first word
236
+ const name = stepLine.split(/\s/)[0];
237
+ if (name)
238
+ steps.push(name);
239
+ }
240
+ }
241
+ return { steps, parallelGroups };
242
+ }
243
+ // ── .gft generation ──────────────────────────────────────
244
+ function formatBudget(tokens) {
245
+ if (tokens >= 1000 && tokens % 1000 === 0)
246
+ return `${tokens / 1000}k`;
247
+ return `${tokens}`;
248
+ }
249
+ export function importHarness(dir) {
250
+ const claudeDir = path.join(dir, '.claude');
251
+ const agentsDir = path.join(claudeDir, 'agents');
252
+ const hooksDir = path.join(claudeDir, 'hooks');
253
+ const settingsPath = path.join(claudeDir, 'settings.json');
254
+ // 1. Parse agents
255
+ const agents = [];
256
+ if (fs.existsSync(agentsDir)) {
257
+ for (const file of fs.readdirSync(agentsDir)) {
258
+ if (!file.endsWith('.md'))
259
+ continue;
260
+ const agent = parseAgent(path.join(agentsDir, file));
261
+ if (agent)
262
+ agents.push(agent);
263
+ }
264
+ }
265
+ // 2. Parse hooks → edges
266
+ const edges = [];
267
+ if (fs.existsSync(hooksDir)) {
268
+ for (const file of fs.readdirSync(hooksDir)) {
269
+ if (!file.endsWith('.js'))
270
+ continue;
271
+ const edge = parseHook(path.join(hooksDir, file));
272
+ if (edge)
273
+ edges.push(edge);
274
+ }
275
+ }
276
+ // 3. Parse settings
277
+ const settings = parseSettings(settingsPath);
278
+ // Apply model from settings routing
279
+ if (settings) {
280
+ for (const agent of agents) {
281
+ const override = settings.modelRouting[agent.name.toLowerCase()];
282
+ if (override)
283
+ agent.model = override;
284
+ }
285
+ }
286
+ // 4. Parse orchestration for graph flow
287
+ const flow = parseOrchestration(dir);
288
+ // 5. Collect context names (reads that don't match any produces)
289
+ const producesNames = new Set(agents.map(a => a.producesName));
290
+ const contextNames = new Set();
291
+ for (const agent of agents) {
292
+ for (const read of agent.reads) {
293
+ if (!producesNames.has(read)) {
294
+ contextNames.add(read);
295
+ }
296
+ }
297
+ }
298
+ // 6. Generate .gft
299
+ const lines = [];
300
+ lines.push(`// Imported from ${path.basename(dir)}/.claude/ by graft import`);
301
+ lines.push('');
302
+ // Contexts (best-effort — we don't know the fields)
303
+ for (const ctx of contextNames) {
304
+ lines.push(`context ${ctx}(max_tokens: 2k) {`);
305
+ lines.push(` // TODO: add fields`);
306
+ lines.push(`}`);
307
+ lines.push('');
308
+ }
309
+ // Nodes
310
+ for (const agent of agents) {
311
+ const budget = `${formatBudget(agent.inputBudget)}/${formatBudget(agent.outputBudget)}`;
312
+ lines.push(`node ${agent.name}(model: ${agent.model}, budget: ${budget}) {`);
313
+ if (agent.reads.length > 0) {
314
+ lines.push(` reads: [${agent.reads.join(', ')}]`);
315
+ }
316
+ lines.push(` produces ${agent.producesName} {`);
317
+ for (const field of agent.producesFields) {
318
+ lines.push(` ${field.name}: ${field.type}`);
319
+ }
320
+ if (agent.producesFields.length === 0) {
321
+ lines.push(` // TODO: add fields`);
322
+ }
323
+ lines.push(` }`);
324
+ lines.push(`}`);
325
+ lines.push('');
326
+ }
327
+ // Edges
328
+ for (const edge of edges) {
329
+ let line = `edge ${edge.source} -> ${edge.target}`;
330
+ for (const t of edge.transforms) {
331
+ line += ` | ${t}`;
332
+ }
333
+ lines.push(line);
334
+ }
335
+ if (edges.length > 0)
336
+ lines.push('');
337
+ // Graph
338
+ const graphBudget = settings?.graphBudget || 50000;
339
+ const graphName = path.basename(dir).replace(/[^a-zA-Z0-9]/g, '') || 'Pipeline';
340
+ const capGraphName = graphName.charAt(0).toUpperCase() + graphName.slice(1);
341
+ // Determine input/output
342
+ const inputCtx = contextNames.size > 0 ? [...contextNames][0] : 'Input';
343
+ const lastAgent = agents.length > 0 ? agents[agents.length - 1] : null;
344
+ const outputName = lastAgent?.producesName || 'Output';
345
+ lines.push(`graph ${capGraphName}(input: ${inputCtx}, output: ${outputName}, budget: ${formatBudget(graphBudget)}) {`);
346
+ // Use orchestration flow if available, otherwise infer from edges
347
+ if (flow.steps.length > 0) {
348
+ const flowParts = [];
349
+ for (const step of flow.steps) {
350
+ if (step.startsWith('parallel:')) {
351
+ const names = step.replace('parallel:', '').split(',');
352
+ flowParts.push(`parallel { ${names.join(' ')} }`);
353
+ }
354
+ else {
355
+ flowParts.push(step);
356
+ }
357
+ }
358
+ lines.push(` ${flowParts.join(' -> ')} -> done`);
359
+ }
360
+ else {
361
+ // Infer sequential from agents list
362
+ const names = agents.map(a => a.name);
363
+ lines.push(` ${names.join(' -> ')} -> done`);
364
+ }
365
+ lines.push(`}`);
366
+ lines.push('');
367
+ return lines.join('\n');
368
+ }
package/dist/index.js CHANGED
@@ -187,17 +187,14 @@ graph ${safeName}(input: Input, output: Output, budget: 10k) {
187
187
  fs.mkdirSync(claudeDir, { recursive: true });
188
188
  const { buildSystemPrompt } = await import('./generator.js');
189
189
  const gftSpec = buildSystemPrompt();
190
- // 1. Write .gft spec to a separate file (never overwritten by compile)
191
- const specPath = path.join(claudeDir, 'graft-spec.md');
192
- const specContent = `# Graft — .gft Language Reference
193
-
194
- > Auto-generated by \`graft init\`. This file is the .gft syntax reference
195
- > that Claude Code reads to understand the Graft language.
196
- > Do NOT delete this file — \`graft compile\` does not touch it.
197
-
198
- ## Graft — Multi-Agent Pipelines
190
+ // Write .gft spec directly into CLAUDE.md (Claude Code only auto-reads CLAUDE.md)
191
+ // graft compile outputs to orchestration.md, so it never overwrites this.
192
+ const claudeMdPath = path.join(claudeDir, 'CLAUDE.md');
193
+ const existingClaudeMd = fs.existsSync(claudeMdPath) ? fs.readFileSync(claudeMdPath, 'utf-8') : '';
194
+ const graftSection = `## Graft Multi-Agent Pipelines
199
195
 
200
196
  This project uses **Graft** (.gft) for defining multi-agent pipelines.
197
+ **Do NOT manually edit \`.claude/orchestration.md\`, \`.claude/agents/\`, \`.claude/hooks/\`, or \`.claude/settings.json\`** — these are generated by \`graft compile\`.
201
198
 
202
199
  When the user asks to create, modify, or manage pipelines:
203
200
  1. Write or edit \`.gft\` files using the syntax below
@@ -222,23 +219,17 @@ graft watch <file.gft> # Watch and recompile on changes
222
219
  2. Validates output against the .gft schema (types, ranges, empty fields)
223
220
  3. Suggests .gft modifications if quality issues are found
224
221
 
225
- ${gftSpec}
226
- `;
227
- fs.writeFileSync(specPath, specContent);
228
- // 2. Add Graft reference to CLAUDE.md (short pointer, not the full spec)
229
- const claudeMdPath = path.join(claudeDir, 'CLAUDE.md');
230
- const existingClaudeMd = fs.existsSync(claudeMdPath) ? fs.readFileSync(claudeMdPath, 'utf-8') : '';
231
- const graftReference = `## Graft
232
-
233
- This project uses Graft for multi-agent pipelines. Read \`.claude/graft-spec.md\` for the full .gft syntax reference. Run \`graft compile <file.gft>\` to generate harness files.`;
234
- if (existingClaudeMd && existingClaudeMd.includes('graft-spec.md')) {
235
- console.log(` .claude/CLAUDE.md already references Graft — skipped`);
222
+ ${gftSpec}`;
223
+ if (existingClaudeMd && existingClaudeMd.includes('graft compile')) {
224
+ console.log(` .claude/CLAUDE.md already contains Graft config — skipped`);
236
225
  }
237
226
  else if (existingClaudeMd) {
238
- fs.writeFileSync(claudeMdPath, existingClaudeMd.trimEnd() + '\n\n' + graftReference + '\n');
227
+ // Existing project: append Graft section to existing CLAUDE.md
228
+ fs.writeFileSync(claudeMdPath, existingClaudeMd.trimEnd() + '\n\n' + graftSection.trim() + '\n');
239
229
  }
240
230
  else {
241
- fs.writeFileSync(claudeMdPath, `# ${safeName}\n\n` + graftReference + '\n');
231
+ // New project: create CLAUDE.md with Graft section
232
+ fs.writeFileSync(claudeMdPath, `# ${safeName}\n\n` + graftSection);
242
233
  }
243
234
  if (isExisting) {
244
235
  console.log(`\nGraft added to current project.`);
@@ -378,6 +369,42 @@ program
378
369
  }
379
370
  console.log(lines.join('\n'));
380
371
  });
372
+ program
373
+ .command('import')
374
+ .description('Import existing .claude/ harness structure into a .gft file')
375
+ .argument('[dir]', 'project directory (default: current directory)', '.')
376
+ .option('-o, --output <file>', 'output .gft file path')
377
+ .action(async (dir, opts) => {
378
+ const resolved = path.resolve(dir);
379
+ const claudeDir = path.join(resolved, '.claude');
380
+ if (!fs.existsSync(claudeDir)) {
381
+ console.error(`Error: no .claude/ directory found in ${resolved}`);
382
+ process.exit(1);
383
+ }
384
+ const agentsDir = path.join(claudeDir, 'agents');
385
+ if (!fs.existsSync(agentsDir) || fs.readdirSync(agentsDir).filter(f => f.endsWith('.md')).length === 0) {
386
+ console.error(`Error: no agent definitions found in .claude/agents/`);
387
+ process.exit(1);
388
+ }
389
+ const { importHarness } = await import('./importer.js');
390
+ const gft = importHarness(resolved);
391
+ const outFile = opts.output || path.join(resolved, 'pipeline.gft');
392
+ if (fs.existsSync(outFile)) {
393
+ console.error(`Error: ${path.relative('.', outFile)} already exists. Use -o to specify a different output file.`);
394
+ process.exit(1);
395
+ }
396
+ fs.writeFileSync(outFile, gft);
397
+ console.log(`\n✓ Imported ${path.relative('.', outFile)}`);
398
+ // Count what was imported
399
+ const agentCount = fs.readdirSync(agentsDir).filter(f => f.endsWith('.md')).length;
400
+ const hooksDir = path.join(claudeDir, 'hooks');
401
+ const hookCount = fs.existsSync(hooksDir) ? fs.readdirSync(hooksDir).filter(f => f.endsWith('.js')).length : 0;
402
+ console.log(` ${agentCount} agents, ${hookCount} edges imported`);
403
+ console.log(`\nNext steps:`);
404
+ console.log(` 1. Review and edit ${path.relative('.', outFile)} (fill in TODO fields)`);
405
+ console.log(` 2. graft check ${path.relative('.', outFile)}`);
406
+ console.log(` 3. graft compile ${path.relative('.', outFile)}`);
407
+ });
381
408
  program
382
409
  .command('fmt')
383
410
  .description('Format .gft source file')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jsleekr/graft",
3
- "version": "6.1.0",
3
+ "version": "6.2.0",
4
4
  "description": "Graft compiler — compile .gft graph DSL to Claude Code harness structures",
5
5
  "type": "module",
6
6
  "license": "MIT",