@directive-run/cli 0.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,681 @@
1
+ 'use strict';
2
+
3
+ var knowledge = require('@directive-run/knowledge');
4
+ var fs = require('fs');
5
+ var path = require('path');
6
+ var pc = require('picocolors');
7
+
8
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
+
10
+ var pc__default = /*#__PURE__*/_interopDefault(pc);
11
+
12
+ // src/lib/knowledge.ts
13
+
14
+ // src/templates/claude.ts
15
+ function generateClaudeRules() {
16
+ const corePatterns = knowledge.getKnowledge("core-patterns");
17
+ const antiPatterns = knowledge.getKnowledge("anti-patterns");
18
+ const naming = knowledge.getKnowledge("naming");
19
+ const schemaTypes = knowledge.getKnowledge("schema-types");
20
+ return `# Directive \u2014 Complete AI Coding Rules
21
+
22
+ > Constraint-driven runtime for TypeScript. Declare requirements, let the runtime resolve them.
23
+ > https://directive.run | \`npm install @directive-run/core\`
24
+ > Full reference with examples: https://directive.run/llms.txt
25
+
26
+ ## Core Patterns
27
+
28
+ ${corePatterns}
29
+
30
+ ---
31
+
32
+ ## Anti-Patterns (All 36)
33
+
34
+ ${antiPatterns}
35
+
36
+ ### AI Package Anti-Patterns (21-36)
37
+
38
+ | # | WRONG | CORRECT |
39
+ |---|-------|---------|
40
+ | 21 | TS types for factsSchema: \`{ confidence: number }\` | Use \`{ confidence: t.number() }\` |
41
+ | 22 | \`facts.cache.push(item)\` in orchestrator | \`facts.cache = [...facts.cache, item]\` |
42
+ | 23 | Returning data from orchestrator \`resolve\` | Resolvers return \`void\` \u2014 mutate \`context.facts\` |
43
+ | 24 | Forgetting \`orchestrator.start()\` multi-agent | Single: implicit. Multi: must call \`start()\` |
44
+ | 25 | Catching \`Error\` not \`GuardrailError\` | \`GuardrailError\` has \`.guardrailName\`, \`.errorCode\` |
45
+ | 26 | \`from '@directive-run/ai'\` for adapters | Subpath: \`from '@directive-run/ai/openai'\` |
46
+ | 27 | Assuming \`{ input_tokens }\` structure | Normalized: \`{ inputTokens, outputTokens }\` |
47
+ | 28 | Same CircuitBreaker across agents | Create separate instances per dependency |
48
+ | 29 | \`budgetWarningThreshold: 1.5\` | Must be 0-1 (percentage) |
49
+ | 30 | \`race\` minSuccess > agents.length | Must be \`1 \u2264 minSuccess \u2264 agents.length\` |
50
+ | 31 | Async summarizer with autoManage: true | Use \`autoManage: false\` for sync control |
51
+ | 32 | Side effects in reflect \`evaluator\` | Evaluator must be pure |
52
+ | 33 | Task calling \`runSingleAgent\` | Tasks can't call agents \u2014 separate node |
53
+ | 34 | Task expecting object input | Input is always \`string\` \u2014 \`JSON.parse(input)\` |
54
+ | 35 | Task ID same as agent ID | IDs share namespace \u2014 distinct names |
55
+ | 36 | \`from '@directive-run/ai/mcp'\` | \`from '@directive-run/ai'\` (main export) |
56
+
57
+ ---
58
+
59
+ ## Naming Conventions
60
+
61
+ ${naming}
62
+
63
+ ---
64
+
65
+ ## Schema Type Builders
66
+
67
+ ${schemaTypes}
68
+
69
+ ---
70
+
71
+ ## Multi-Module Quick Reference
72
+
73
+ \`\`\`typescript
74
+ // Two modules with cross-module dependency
75
+ const authSchema = { facts: { token: t.string(), isAuth: t.boolean() } };
76
+ const authModule = createModule("auth", { schema: authSchema, /* ... */ });
77
+
78
+ const cartModule = createModule("cart", {
79
+ schema: { facts: { items: t.array<CartItem>() } },
80
+ crossModuleDeps: { auth: authSchema }, // Declare dependency
81
+ constraints: {
82
+ checkout: {
83
+ when: (facts) => facts.self.items.length > 0 && facts.auth.isAuth, // facts.self.* for own, facts.auth.* for cross
84
+ require: () => ({ type: "CHECKOUT" }),
85
+ },
86
+ },
87
+ // ...
88
+ });
89
+
90
+ const system = createSystem({ modules: { auth: authModule, cart: cartModule } });
91
+ // Access: system.facts.auth.token, system.events.cart.addItem({...})
92
+ \`\`\`
93
+
94
+ Key rules:
95
+ - \`facts.self.*\` for own module facts in constraints/resolvers
96
+ - \`facts.otherModule.*\` for cross-module reads
97
+ - \`crossModuleDeps\` must declare consumed schemas
98
+ - \`system.events.moduleName.eventName(payload)\` for namespaced events
99
+ - The \`::\` separator is internal \u2014 always use dot notation
100
+
101
+ ---
102
+
103
+ ## Constraints
104
+
105
+ - \`when(facts)\` \u2192 boolean. When true, requirement is emitted.
106
+ - \`require(facts)\` \u2192 \`{ type: "TYPE", ...data }\` object (never string literal)
107
+ - \`priority: number\` \u2014 higher evaluated first
108
+ - \`after: ["constraintName"]\` \u2014 ordering within same priority
109
+ - Async: \`async: true\` + \`deps: ['factName']\` (deps REQUIRED for async)
110
+ - Constraints DECLARE needs, resolvers FULFILL them \u2014 decoupled.
111
+
112
+ ---
113
+
114
+ ## Resolvers
115
+
116
+ - \`resolve(req, context)\` \u2014 async, returns \`void\`. Mutate \`context.facts.*\`.
117
+ - \`requirement: "TYPE"\` \u2014 which type this handles
118
+ - \`key: (req) => string\` \u2014 deduplication key
119
+ - \`retry: { attempts: 3, backoff: "exponential", initialDelay: 100 }\`
120
+ - \`batch: { maxSize: 10, windowMs: 50 }\` for N+1 prevention
121
+ - Always \`await system.settle()\` after start to wait for resolution
122
+
123
+ ---
124
+
125
+ ## System API
126
+
127
+ - \`system.facts.fieldName\` \u2014 read/write facts
128
+ - \`system.derive.derivationName\` \u2014 read derived values
129
+ - \`system.events.eventName(payload)\` \u2014 dispatch events
130
+ - \`system.subscribe(listener)\` \u2014 subscribe to all changes
131
+ - \`system.read(key)\` \u2014 read fact or derivation by string key
132
+ - \`system.inspect()\` \u2014 full state snapshot
133
+ - \`system.settle()\` \u2014 wait for async operations
134
+ - \`system.start()\` / \`system.stop()\` / \`system.destroy()\`
135
+
136
+ ---
137
+
138
+ ## React (\`@directive-run/react\`)
139
+
140
+ \`\`\`typescript
141
+ import { useSelector, useEvent } from "@directive-run/react";
142
+
143
+ const count = useSelector(system, (s) => s.facts.count);
144
+ const events = useEvent(system);
145
+ // onClick={() => events.increment()}
146
+ \`\`\`
147
+
148
+ **NO** \`useDirective()\` hook. Use \`useSelector\` + \`useEvent\`.
149
+
150
+ ---
151
+
152
+ ## Plugins (\`@directive-run/core/plugins\`)
153
+
154
+ \`devtoolsPlugin()\`, \`loggingPlugin()\`, \`persistencePlugin(config)\`,
155
+ \`createCircuitBreaker(config)\`, \`createObservability(config)\`
156
+
157
+ ---
158
+
159
+ ## AI Package (\`@directive-run/ai\`)
160
+
161
+ ### Single-Agent Orchestrator
162
+
163
+ \`\`\`typescript
164
+ import { createAgentOrchestrator, t } from '@directive-run/ai';
165
+ import { createAnthropicRunner } from '@directive-run/ai/anthropic';
166
+
167
+ const orchestrator = createAgentOrchestrator({
168
+ runner: createAnthropicRunner({ apiKey }),
169
+ factsSchema: { result: t.string(), confidence: t.number() },
170
+ init: (facts) => { facts.result = ""; facts.confidence = 0; },
171
+ maxTokenBudget: 100000,
172
+ budgetWarningThreshold: 0.8,
173
+ guardrails: { input: [...], output: [...] },
174
+ memory: createAgentMemory({ strategy: createSlidingWindowStrategy({ maxMessages: 30 }) }),
175
+ debug: true,
176
+ });
177
+
178
+ const result = await orchestrator.run(agent, "analyze this");
179
+ \`\`\`
180
+
181
+ ### Multi-Agent
182
+
183
+ \`\`\`typescript
184
+ import { createMultiAgentOrchestrator, parallel, sequential, dag } from '@directive-run/ai';
185
+
186
+ const orch = createMultiAgentOrchestrator({
187
+ agents: { researcher: agentA, writer: agentB },
188
+ patterns: {
189
+ pipeline: sequential(["researcher", "writer"]),
190
+ brainstorm: parallel(["researcher", "writer"], mergeResults),
191
+ workflow: dag([
192
+ { id: "research", handler: "researcher" },
193
+ { id: "write", handler: "writer", dependencies: ["research"] },
194
+ ]),
195
+ },
196
+ runner,
197
+ });
198
+ orch.start(); // Required for multi-agent!
199
+ \`\`\`
200
+
201
+ 8 patterns: \`parallel\`, \`sequential\`, \`supervisor\`, \`dag\`, \`reflect\`, \`race\`, \`debate\`, \`goal\`
202
+
203
+ ### Adapter Imports (Subpath!)
204
+
205
+ \`\`\`typescript
206
+ import { createAnthropicRunner } from '@directive-run/ai/anthropic';
207
+ import { createOpenAIRunner } from '@directive-run/ai/openai';
208
+ import { createOllamaRunner } from '@directive-run/ai/ollama';
209
+ import { createGeminiRunner } from '@directive-run/ai/gemini';
210
+ \`\`\`
211
+
212
+ ### Guardrails
213
+
214
+ \`createPIIGuardrail\`, \`createModerationGuardrail\`, \`createRateLimitGuardrail\`,
215
+ \`createToolGuardrail\`, \`createOutputSchemaGuardrail\`, \`createLengthGuardrail\`,
216
+ \`createContentFilterGuardrail\`
217
+
218
+ \`GuardrailResult: { passed: boolean, reason?: string, transformed?: unknown }\`
219
+
220
+ ### Memory
221
+
222
+ \`createAgentMemory({ strategy, summarizer?, autoManage? })\`
223
+ Strategies: \`createSlidingWindowStrategy\`, \`createTokenBasedStrategy\`, \`createHybridStrategy\`
224
+ Summarizers: \`createTruncationSummarizer\`, \`createKeyPointsSummarizer\`, \`createLLMSummarizer(runner)\`
225
+
226
+ ### Streaming
227
+
228
+ \`\`\`typescript
229
+ const streamResult = orchestrator.runStream(agent, "analyze");
230
+ for await (const chunk of streamResult.stream) {
231
+ switch (chunk.type) {
232
+ case "token": process.stdout.write(chunk.data); break;
233
+ case "done": console.log("Tokens:", chunk.totalTokens); break;
234
+ case "error": console.error(chunk.error); break;
235
+ }
236
+ }
237
+ \`\`\`
238
+
239
+ Backpressure: \`"buffer"\` (default), \`"block"\`, \`"drop"\`
240
+ `;
241
+ }
242
+
243
+ // src/templates/cursor.ts
244
+ function generateCursorRules() {
245
+ return `# Directive \u2014 AI Coding Rules
246
+
247
+ > Constraint-driven runtime for TypeScript. \`npm install @directive-run/core\`
248
+ > Full reference: https://directive.run/llms.txt
249
+
250
+ ## Schema Shape (CRITICAL)
251
+
252
+ \`\`\`typescript
253
+ import { createModule, createSystem, t } from "@directive-run/core";
254
+
255
+ const myModule = createModule("name", {
256
+ schema: {
257
+ facts: { count: t.number(), items: t.array<string>() },
258
+ derivations: { total: "number" },
259
+ events: { increment: "void", addItem: "string" },
260
+ requirements: { FETCH_DATA: { url: "string" } },
261
+ },
262
+ init: (facts) => { facts.count = 0; facts.items = []; },
263
+ derive: {
264
+ total: (facts) => facts.items.length + facts.count,
265
+ },
266
+ events: {
267
+ increment: (facts) => { facts.count += 1; },
268
+ addItem: (facts, item) => { facts.items = [...facts.items, item]; },
269
+ },
270
+ constraints: {
271
+ fetchWhenReady: {
272
+ when: (facts) => facts.count > 0 && facts.items.length === 0,
273
+ require: (facts) => ({ type: "FETCH_DATA", url: "/api/items" }),
274
+ },
275
+ },
276
+ resolvers: {
277
+ fetchData: {
278
+ requirement: "FETCH_DATA",
279
+ resolve: async (req, context) => {
280
+ const data = await fetch(req.url).then(r => r.json());
281
+ context.facts.items = data;
282
+ },
283
+ },
284
+ },
285
+ });
286
+
287
+ const system = createSystem({ module: myModule });
288
+ await system.settle();
289
+ \`\`\`
290
+
291
+ ## Top 10 Anti-Patterns
292
+
293
+ | # | WRONG | CORRECT |
294
+ |---|-------|---------|
295
+ | 1 | \`facts.profile as ResourceState<Profile>\` | Remove cast \u2014 schema provides types |
296
+ | 2 | \`{ phase: t.string() }\` flat schema | \`schema: { facts: { phase: t.string() } }\` |
297
+ | 3 | \`facts.items\` in multi-module | \`facts.self.items\` |
298
+ | 4 | \`t.map()\`, \`t.set()\`, \`t.promise()\` | Don't exist. Use \`t.object<Map<K,V>>()\` |
299
+ | 5 | \`(req, ctx)\` in resolver | \`(req, context)\` \u2014 never abbreviate |
300
+ | 6 | \`createModule("n", { phase: t.string() })\` | Must wrap: \`schema: { facts: { ... } }\` |
301
+ | 7 | \`system.dispatch('login', {...})\` | \`system.events.login({...})\` |
302
+ | 8 | \`facts.items.push(item)\` | \`facts.items = [...facts.items, item]\` |
303
+ | 9 | \`useDirective(system)\` | \`useSelector(system, s => s.facts.count)\` |
304
+ | 10 | \`facts['auth::status']\` | \`facts.auth.status\` dot notation |
305
+
306
+ ## Naming
307
+
308
+ - \`req\` = requirement (not request). Parameter: \`(req, context)\`
309
+ - \`derive\` / derivations \u2014 never "computed" or "selectors"
310
+ - Resolvers return \`void\` \u2014 mutate \`context.facts\` instead
311
+ - Always use braces for returns: \`if (x) { return y; }\`
312
+ - Multi-module: \`facts.self.fieldName\` for own module facts
313
+ - Events: \`system.events.eventName(payload)\` \u2014 not \`system.dispatch()\`
314
+ - Import from main: \`import { createModule } from '@directive-run/core'\`
315
+
316
+ ## Schema Types That Exist
317
+
318
+ \`t.string<T>()\`, \`t.number()\`, \`t.boolean()\`, \`t.array<T>()\`, \`t.object<T>()\`,
319
+ \`t.enum("a","b")\`, \`t.literal(value)\`, \`t.nullable(inner)\`, \`t.optional(inner)\`, \`t.union(...)\`
320
+
321
+ Chainable: \`.default()\`, \`.validate()\`, \`.transform()\`, \`.brand<>()\`, \`.refine()\`
322
+
323
+ **DO NOT USE** (hallucinations): \`t.map()\`, \`t.set()\`, \`t.date()\`, \`t.tuple()\`, \`t.record()\`, \`t.promise()\`, \`t.any()\`
324
+
325
+ ## Key Pattern: Constraint \u2192 Requirement \u2192 Resolver
326
+
327
+ When the user wants "do X when Y": create THREE things:
328
+ 1. **Constraint**: \`when: (facts) => Y_condition\` \u2192 \`require: { type: "DO_X" }\`
329
+ 2. **Resolver**: handles "DO_X", calls API, sets \`context.facts\`
330
+ 3. They are **decoupled**. Constraint declares need, resolver fulfills it.
331
+ `;
332
+ }
333
+
334
+ // src/templates/copilot.ts
335
+ function generateCopilotRules() {
336
+ const base = generateCursorRules();
337
+ const extraAntiPatterns = `
338
+ ## Anti-Patterns 11-20
339
+
340
+ | # | WRONG | CORRECT |
341
+ |---|-------|---------|
342
+ | 11 | \`module("name").schema({...}).build()\` | Prefer \`createModule("name", {...})\` object syntax |
343
+ | 12 | Returning data from \`resolve\` | Resolvers return \`void\` \u2014 mutate \`context.facts\` |
344
+ | 13 | Async logic in \`init\` | \`init\` is synchronous, facts assignment only |
345
+ | 14 | \`await system.start()\` without settle | Add \`await system.settle()\` after start |
346
+ | 15 | Missing \`crossModuleDeps\` | Declare \`crossModuleDeps: { auth: authSchema }\` |
347
+ | 16 | \`require: "TYPE"\` string literal | \`require: { type: "TYPE" }\` object form |
348
+ | 17 | Passthrough derivation \`(f) => f.count\` | Remove \u2014 read fact directly |
349
+ | 18 | \`from '@directive-run/core/module'\` | \`from '@directive-run/core'\` (main export) |
350
+ | 19 | \`async when()\` without \`deps\` | Add \`deps: ['factName']\` for async constraints |
351
+ | 20 | No error boundary on resolver | Use try-catch or module error boundary config |
352
+ `;
353
+ const multiModule = `
354
+ ## Multi-Module
355
+
356
+ \`\`\`typescript
357
+ const system = createSystem({
358
+ modules: { auth: authModule, cart: cartModule },
359
+ });
360
+
361
+ // Access: system.facts.auth.token, system.events.cart.addItem({...})
362
+ // In constraints/resolvers: use facts.self.* for own module
363
+ // Declare deps: crossModuleDeps: { auth: authSchema }
364
+ \`\`\`
365
+ `;
366
+ const aiBasics = `
367
+ ## AI Package Basics (\`@directive-run/ai\`)
368
+
369
+ \`\`\`typescript
370
+ import { createAgentOrchestrator, t } from '@directive-run/ai';
371
+ import { createAnthropicRunner } from '@directive-run/ai/anthropic'; // Subpath import!
372
+
373
+ const orchestrator = createAgentOrchestrator({
374
+ runner: createAnthropicRunner({ apiKey: process.env.ANTHROPIC_API_KEY }),
375
+ factsSchema: { result: t.string(), confidence: t.number() }, // Use t.*() !
376
+ init: (facts) => { facts.result = ""; facts.confidence = 0; },
377
+ });
378
+
379
+ const result = await orchestrator.run(agent, "analyze this");
380
+ \`\`\`
381
+
382
+ **AI Anti-Patterns:**
383
+ - Use \`t.number()\` not \`number\` for factsSchema
384
+ - Subpath imports: \`from '@directive-run/ai/anthropic'\` not \`from '@directive-run/ai'\`
385
+ - Token usage normalized: \`{ inputTokens, outputTokens }\` (not provider-specific)
386
+ - \`facts.cache = [...facts.cache, item]\` not \`facts.cache.push(item)\`
387
+ `;
388
+ return base + extraAntiPatterns + multiModule + aiBasics;
389
+ }
390
+
391
+ // src/templates/cline.ts
392
+ function generateClineRules() {
393
+ return generateCopilotRules();
394
+ }
395
+
396
+ // src/templates/llms-txt.ts
397
+ function generateLlmsTxt() {
398
+ const knowledge$1 = knowledge.getAllKnowledge();
399
+ const examples = knowledge.getAllExamples();
400
+ const coreOrder = [
401
+ "core-patterns",
402
+ "anti-patterns",
403
+ "naming",
404
+ "multi-module",
405
+ "constraints",
406
+ "resolvers",
407
+ "error-boundaries",
408
+ "testing",
409
+ "time-travel",
410
+ "schema-types",
411
+ "system-api",
412
+ "react-adapter",
413
+ "plugins"
414
+ ];
415
+ const aiOrder = [
416
+ "ai-orchestrator",
417
+ "ai-multi-agent",
418
+ "ai-tasks",
419
+ "ai-agents-streaming",
420
+ "ai-guardrails-memory",
421
+ "ai-adapters",
422
+ "ai-budget-resilience",
423
+ "ai-mcp-rag",
424
+ "ai-communication",
425
+ "ai-debug-observability",
426
+ "ai-security",
427
+ "ai-testing-evals"
428
+ ];
429
+ const exampleOrder = [
430
+ "counter",
431
+ "auth-flow",
432
+ "shopping-cart",
433
+ "error-boundaries",
434
+ "ai-orchestrator",
435
+ "fraud-analysis",
436
+ "ai-checkpoint"
437
+ ];
438
+ const sections = [
439
+ "# Directive \u2014 Complete AI Reference (llms.txt)",
440
+ "",
441
+ "> Constraint-driven runtime for TypeScript.",
442
+ "> Declare requirements. Let the runtime resolve them.",
443
+ "> https://directive.run",
444
+ "",
445
+ "## Core API (@directive-run/core)",
446
+ ""
447
+ ];
448
+ for (const name of coreOrder) {
449
+ const content = knowledge$1.get(name);
450
+ if (content) {
451
+ sections.push(content, "", "---", "");
452
+ }
453
+ }
454
+ sections.push("## AI Package (@directive-run/ai)", "");
455
+ for (const name of aiOrder) {
456
+ const content = knowledge$1.get(name);
457
+ if (content) {
458
+ sections.push(content, "", "---", "");
459
+ }
460
+ }
461
+ const apiSkeleton = knowledge$1.get("api-skeleton");
462
+ if (apiSkeleton) {
463
+ sections.push("## API Reference (Auto-Generated)", "", apiSkeleton, "");
464
+ }
465
+ sections.push("## Complete Examples", "");
466
+ for (const name of exampleOrder) {
467
+ const content = examples.get(name);
468
+ if (content) {
469
+ sections.push(
470
+ `### ${name}`,
471
+ "",
472
+ "```typescript",
473
+ content,
474
+ "```",
475
+ ""
476
+ );
477
+ }
478
+ }
479
+ return sections.join("\n");
480
+ }
481
+
482
+ // src/templates/windsurf.ts
483
+ function generateWindsurfRules() {
484
+ return generateCopilotRules();
485
+ }
486
+
487
+ // src/templates/index.ts
488
+ var generators = {
489
+ cursor: generateCursorRules,
490
+ claude: generateClaudeRules,
491
+ copilot: generateCopilotRules,
492
+ windsurf: generateWindsurfRules,
493
+ cline: generateClineRules
494
+ };
495
+ function getTemplate(toolId) {
496
+ const generator = generators[toolId];
497
+ if (!generator) {
498
+ throw new Error(`No template for tool: ${toolId}`);
499
+ }
500
+ return generator();
501
+ }
502
+ var TOOL_SIGNALS = [
503
+ {
504
+ id: "cursor",
505
+ name: "Cursor",
506
+ signals: [".cursor", ".cursorrules"],
507
+ outputPath: ".cursorrules"
508
+ },
509
+ {
510
+ id: "claude",
511
+ name: "Claude Code",
512
+ signals: [".claude"],
513
+ outputPath: ".claude/CLAUDE.md"
514
+ },
515
+ {
516
+ id: "copilot",
517
+ name: "GitHub Copilot",
518
+ signals: [".github"],
519
+ outputPath: ".github/copilot-instructions.md"
520
+ },
521
+ {
522
+ id: "windsurf",
523
+ name: "Windsurf",
524
+ signals: [".windsurfrules"],
525
+ outputPath: ".windsurfrules"
526
+ },
527
+ {
528
+ id: "cline",
529
+ name: "Cline",
530
+ signals: [".clinerules"],
531
+ outputPath: ".clinerules"
532
+ }
533
+ ];
534
+ function detectTools(rootDir) {
535
+ const detected = [];
536
+ for (const tool of TOOL_SIGNALS) {
537
+ const hasSignal = tool.signals.some(
538
+ (signal) => fs.existsSync(path.join(rootDir, signal))
539
+ );
540
+ if (hasSignal) {
541
+ detected.push({
542
+ name: tool.name,
543
+ id: tool.id,
544
+ outputPath: path.join(rootDir, tool.outputPath)
545
+ });
546
+ }
547
+ }
548
+ return detected;
549
+ }
550
+ var MONOREPO_SIGNALS = [
551
+ { file: "pnpm-workspace.yaml", tool: "pnpm" },
552
+ { file: "turbo.json", tool: "turbo" }
553
+ ];
554
+ function detectMonorepo(startDir) {
555
+ let dir = path.resolve(startDir);
556
+ while (dir !== path.dirname(dir)) {
557
+ for (const signal of MONOREPO_SIGNALS) {
558
+ if (fs.existsSync(path.join(dir, signal.file))) {
559
+ return { isMonorepo: true, rootDir: dir, tool: signal.tool };
560
+ }
561
+ }
562
+ const pkgPath = path.join(dir, "package.json");
563
+ if (fs.existsSync(pkgPath)) {
564
+ try {
565
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
566
+ if (pkg.workspaces) {
567
+ const tool = fs.existsSync(path.join(dir, "yarn.lock")) ? "yarn" : "npm";
568
+ return { isMonorepo: true, rootDir: dir, tool };
569
+ }
570
+ } catch {
571
+ }
572
+ }
573
+ dir = path.dirname(dir);
574
+ }
575
+ return { isMonorepo: false, rootDir: startDir };
576
+ }
577
+
578
+ // src/lib/constants.ts
579
+ var CLI_NAME = "directive";
580
+ var PACKAGE_NAME = "@directive-run/cli";
581
+ var SECTION_START = "<!-- directive:start -->";
582
+ var SECTION_END = "<!-- directive:end -->";
583
+
584
+ // src/lib/merge.ts
585
+ function mergeSection(existingContent, newSection) {
586
+ const startIdx = existingContent.indexOf(SECTION_START);
587
+ const endIdx = existingContent.indexOf(SECTION_END);
588
+ const wrapped = `${SECTION_START}
589
+ ${newSection}
590
+ ${SECTION_END}`;
591
+ if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
592
+ return existingContent.slice(0, startIdx) + wrapped + existingContent.slice(endIdx + SECTION_END.length);
593
+ }
594
+ const separator = existingContent.endsWith("\n") ? "\n" : "\n\n";
595
+ return existingContent + separator + wrapped + "\n";
596
+ }
597
+ function hasDirectiveSection(content) {
598
+ return content.includes(SECTION_START) && content.includes(SECTION_END);
599
+ }
600
+ async function loadSystem(filePath) {
601
+ const resolved = path.resolve(filePath);
602
+ if (!fs.existsSync(resolved)) {
603
+ throw new Error(`File not found: ${resolved}`);
604
+ }
605
+ try {
606
+ const mod = await import(resolved);
607
+ if (mod.default && isSystem(mod.default)) {
608
+ return mod.default;
609
+ }
610
+ if (mod.system && isSystem(mod.system)) {
611
+ return mod.system;
612
+ }
613
+ for (const key of Object.keys(mod)) {
614
+ if (isSystem(mod[key])) {
615
+ return mod[key];
616
+ }
617
+ }
618
+ throw new Error(
619
+ `No Directive system found in ${pc__default.default.dim(filePath)}
620
+ Export a system as default or named "system":
621
+
622
+ ${pc__default.default.cyan("export default")} createSystem({ module: myModule });
623
+ ${pc__default.default.cyan("export const system")} = createSystem({ module: myModule });`
624
+ );
625
+ } catch (err) {
626
+ if (err instanceof Error && err.message.includes("No Directive system")) {
627
+ throw err;
628
+ }
629
+ throw new Error(
630
+ `Failed to load ${pc__default.default.dim(filePath)}: ${err instanceof Error ? err.message : String(err)}
631
+
632
+ Make sure the file is valid TypeScript and tsx is installed:
633
+ ${pc__default.default.cyan("npm install -D tsx")}`
634
+ );
635
+ }
636
+ }
637
+ function isSystem(obj) {
638
+ if (typeof obj !== "object" || obj === null) {
639
+ return false;
640
+ }
641
+ const sys = obj;
642
+ return typeof sys.inspect === "function" && typeof sys.start === "function" && typeof sys.stop === "function" && "facts" in sys;
643
+ }
644
+
645
+ Object.defineProperty(exports, "getAllExamples", {
646
+ enumerable: true,
647
+ get: function () { return knowledge.getAllExamples; }
648
+ });
649
+ Object.defineProperty(exports, "getAllKnowledge", {
650
+ enumerable: true,
651
+ get: function () { return knowledge.getAllKnowledge; }
652
+ });
653
+ Object.defineProperty(exports, "getExample", {
654
+ enumerable: true,
655
+ get: function () { return knowledge.getExample; }
656
+ });
657
+ Object.defineProperty(exports, "getExampleFiles", {
658
+ enumerable: true,
659
+ get: function () { return knowledge.getExampleFiles; }
660
+ });
661
+ Object.defineProperty(exports, "getKnowledge", {
662
+ enumerable: true,
663
+ get: function () { return knowledge.getKnowledge; }
664
+ });
665
+ Object.defineProperty(exports, "getKnowledgeFiles", {
666
+ enumerable: true,
667
+ get: function () { return knowledge.getKnowledgeFiles; }
668
+ });
669
+ exports.CLI_NAME = CLI_NAME;
670
+ exports.PACKAGE_NAME = PACKAGE_NAME;
671
+ exports.SECTION_END = SECTION_END;
672
+ exports.SECTION_START = SECTION_START;
673
+ exports.detectMonorepo = detectMonorepo;
674
+ exports.detectTools = detectTools;
675
+ exports.generateLlmsTxt = generateLlmsTxt;
676
+ exports.getTemplate = getTemplate;
677
+ exports.hasDirectiveSection = hasDirectiveSection;
678
+ exports.loadSystem = loadSystem;
679
+ exports.mergeSection = mergeSection;
680
+ //# sourceMappingURL=index.cjs.map
681
+ //# sourceMappingURL=index.cjs.map