coaiajs 0.1.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.
Files changed (162) hide show
  1. package/CLAUDE.md +56 -0
  2. package/KINSHIP.md +63 -0
  3. package/README.md +148 -0
  4. package/articles/academic/creative-orientation-vs-problem-solving.md +177 -0
  5. package/articles/academic/jsonl-knowledge-graphs-agent-memory.md +142 -0
  6. package/articles/academic/langfuse-observability-llm-pipelines.md +144 -0
  7. package/articles/academic/medicine-wheel-software-architecture.md +163 -0
  8. package/articles/academic/mmot-autonomous-agents.md +156 -0
  9. package/articles/academic/model-context-protocol-interagent.md +161 -0
  10. package/articles/academic/pde-prompt-decomposition.md +186 -0
  11. package/articles/academic/structural-tension-in-ai-agents.md +134 -0
  12. package/articles/reviews/mcp-protocol-design-review.md +170 -0
  13. package/articles/reviews/observability-ai-systems-review.md +176 -0
  14. package/articles/reviews/prompt-engineering-decomposition-review.md +184 -0
  15. package/articles/surveys/agent-orchestration-survey.md +186 -0
  16. package/articles/surveys/knowledge-graph-storage-survey.md +204 -0
  17. package/articles/surveys/structural-tension-methodology-survey.md +154 -0
  18. package/articles/technical/aws-sdk-v3-polly.md +270 -0
  19. package/articles/technical/commander-cli-framework.md +262 -0
  20. package/articles/technical/dotenv-config-patterns.md +360 -0
  21. package/articles/technical/ioredis-vs-redis.md +142 -0
  22. package/articles/technical/langfuse-js-sdk-vs-rest.md +191 -0
  23. package/articles/technical/mcp-sdk-typescript.md +291 -0
  24. package/articles/technical/octokit-github-api.md +293 -0
  25. package/articles/technical/openai-sdk-modern.md +231 -0
  26. package/articles/technical/yaml-parsing-node.md +266 -0
  27. package/articles/technical/zod-runtime-validation.md +212 -0
  28. package/dist/mcp/config.d.ts +14 -0
  29. package/dist/mcp/config.js +185 -0
  30. package/dist/mcp/server.d.ts +3 -0
  31. package/dist/mcp/server.js +324 -0
  32. package/dist/mcp/tools/coaiapy-tools.d.ts +8 -0
  33. package/dist/mcp/tools/coaiapy-tools.js +326 -0
  34. package/dist/mcp/tools/index.d.ts +3 -0
  35. package/dist/mcp/tools/index.js +3 -0
  36. package/dist/src/audio.d.ts +12 -0
  37. package/dist/src/audio.js +57 -0
  38. package/dist/src/cli-helpers.d.ts +9 -0
  39. package/dist/src/cli-helpers.js +78 -0
  40. package/dist/src/cli.d.ts +3 -0
  41. package/dist/src/cli.js +1086 -0
  42. package/dist/src/config.d.ts +15 -0
  43. package/dist/src/config.js +145 -0
  44. package/dist/src/environment.d.ts +44 -0
  45. package/dist/src/environment.js +146 -0
  46. package/dist/src/github.d.ts +47 -0
  47. package/dist/src/github.js +79 -0
  48. package/dist/src/langfuse/client.d.ts +30 -0
  49. package/dist/src/langfuse/client.js +75 -0
  50. package/dist/src/langfuse/comments.d.ts +16 -0
  51. package/dist/src/langfuse/comments.js +36 -0
  52. package/dist/src/langfuse/datasets.d.ts +19 -0
  53. package/dist/src/langfuse/datasets.js +140 -0
  54. package/dist/src/langfuse/index.d.ts +13 -0
  55. package/dist/src/langfuse/index.js +10 -0
  56. package/dist/src/langfuse/media.d.ts +11 -0
  57. package/dist/src/langfuse/media.js +167 -0
  58. package/dist/src/langfuse/observations.d.ts +18 -0
  59. package/dist/src/langfuse/observations.js +113 -0
  60. package/dist/src/langfuse/prompts.d.ts +14 -0
  61. package/dist/src/langfuse/prompts.js +127 -0
  62. package/dist/src/langfuse/scores.d.ts +54 -0
  63. package/dist/src/langfuse/scores.js +366 -0
  64. package/dist/src/langfuse/traces.d.ts +29 -0
  65. package/dist/src/langfuse/traces.js +225 -0
  66. package/dist/src/llm.d.ts +23 -0
  67. package/dist/src/llm.js +76 -0
  68. package/dist/src/narrative/graph-manager.d.ts +106 -0
  69. package/dist/src/narrative/graph-manager.js +915 -0
  70. package/dist/src/narrative/index.d.ts +9 -0
  71. package/dist/src/narrative/index.js +7 -0
  72. package/dist/src/narrative/markdown-export.d.ts +21 -0
  73. package/dist/src/narrative/markdown-export.js +383 -0
  74. package/dist/src/narrative/tool-definitions.d.ts +21 -0
  75. package/dist/src/narrative/tool-definitions.js +588 -0
  76. package/dist/src/narrative/tool-handlers.d.ts +11 -0
  77. package/dist/src/narrative/tool-handlers.js +462 -0
  78. package/dist/src/narrative/types.d.ts +2 -0
  79. package/dist/src/narrative/types.js +2 -0
  80. package/dist/src/narrative/validation.d.ts +29 -0
  81. package/dist/src/narrative/validation.js +144 -0
  82. package/dist/src/pde/index.d.ts +8 -0
  83. package/dist/src/pde/index.js +8 -0
  84. package/dist/src/pde/mcp-handlers.d.ts +7 -0
  85. package/dist/src/pde/mcp-handlers.js +300 -0
  86. package/dist/src/pde/mcp-tools.d.ts +15 -0
  87. package/dist/src/pde/mcp-tools.js +191 -0
  88. package/dist/src/pde/session-manager.d.ts +32 -0
  89. package/dist/src/pde/session-manager.js +205 -0
  90. package/dist/src/pde/stc-mapper.d.ts +26 -0
  91. package/dist/src/pde/stc-mapper.js +234 -0
  92. package/dist/src/pipeline/index.d.ts +2 -0
  93. package/dist/src/pipeline/index.js +3 -0
  94. package/dist/src/pipeline/template-engine.d.ts +20 -0
  95. package/dist/src/pipeline/template-engine.js +361 -0
  96. package/dist/src/planning/index.d.ts +7 -0
  97. package/dist/src/planning/index.js +7 -0
  98. package/dist/src/planning/mcp-handlers.d.ts +7 -0
  99. package/dist/src/planning/mcp-handlers.js +310 -0
  100. package/dist/src/planning/mcp-tools.d.ts +15 -0
  101. package/dist/src/planning/mcp-tools.js +145 -0
  102. package/dist/src/planning/plan-parser.d.ts +35 -0
  103. package/dist/src/planning/plan-parser.js +506 -0
  104. package/dist/src/redis.d.ts +21 -0
  105. package/dist/src/redis.js +78 -0
  106. package/dist/src/types.d.ts +244 -0
  107. package/dist/src/types.js +8 -0
  108. package/mcp/config.ts +196 -0
  109. package/mcp/server.ts +402 -0
  110. package/mcp/tools/coaiapy-tools.ts +364 -0
  111. package/mcp/tools/index.ts +4 -0
  112. package/package.json +52 -0
  113. package/rispecs/00-coaiajs-platform.spec.md +102 -0
  114. package/rispecs/01-core-config.spec.md +89 -0
  115. package/rispecs/02-redis-module.spec.md +62 -0
  116. package/rispecs/03-langfuse-module.spec.md +101 -0
  117. package/rispecs/04-narrative-engine.spec.md +185 -0
  118. package/rispecs/05-pde-engine.spec.md +112 -0
  119. package/rispecs/06-planning-engine.spec.md +128 -0
  120. package/rispecs/07-pipeline-templates.spec.md +97 -0
  121. package/rispecs/08-cli-interface.spec.md +134 -0
  122. package/rispecs/09-mcp-server.spec.md +140 -0
  123. package/rispecs/10-audio-module.spec.md +63 -0
  124. package/rispecs/KINSHIP.md +56 -0
  125. package/rispecs/README.md +100 -0
  126. package/src/audio.ts +76 -0
  127. package/src/cli-helpers.ts +86 -0
  128. package/src/cli.ts +1223 -0
  129. package/src/config.ts +172 -0
  130. package/src/environment.ts +171 -0
  131. package/src/github.ts +143 -0
  132. package/src/langfuse/client.ts +105 -0
  133. package/src/langfuse/comments.ts +52 -0
  134. package/src/langfuse/datasets.ts +178 -0
  135. package/src/langfuse/index.ts +33 -0
  136. package/src/langfuse/media.ts +193 -0
  137. package/src/langfuse/observations.ts +131 -0
  138. package/src/langfuse/prompts.ts +157 -0
  139. package/src/langfuse/scores.ts +456 -0
  140. package/src/langfuse/traces.ts +276 -0
  141. package/src/llm.ts +106 -0
  142. package/src/narrative/graph-manager.ts +1358 -0
  143. package/src/narrative/index.ts +32 -0
  144. package/src/narrative/markdown-export.ts +535 -0
  145. package/src/narrative/tool-definitions.ts +635 -0
  146. package/src/narrative/tool-handlers.ts +528 -0
  147. package/src/narrative/types.ts +9 -0
  148. package/src/narrative/validation.ts +179 -0
  149. package/src/pde/index.ts +8 -0
  150. package/src/pde/mcp-handlers.ts +359 -0
  151. package/src/pde/mcp-tools.ts +201 -0
  152. package/src/pde/session-manager.ts +248 -0
  153. package/src/pde/stc-mapper.ts +298 -0
  154. package/src/pipeline/index.ts +7 -0
  155. package/src/pipeline/template-engine.ts +398 -0
  156. package/src/planning/index.ts +13 -0
  157. package/src/planning/mcp-handlers.ts +369 -0
  158. package/src/planning/mcp-tools.ts +155 -0
  159. package/src/planning/plan-parser.ts +587 -0
  160. package/src/redis.ts +97 -0
  161. package/src/types.ts +280 -0
  162. package/tsconfig.json +26 -0
package/src/cli.ts ADDED
@@ -0,0 +1,1223 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import chalk from 'chalk';
4
+ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
5
+ import { resolve } from 'node:path';
6
+
7
+ import { tash, fetch as redisFetch, keys as redisKeys, disconnect as redisDisconnect } from './redis.js';
8
+ import { readConfig, getConfig } from './config.js';
9
+ import { llm as llmCall, transcribeAudio, abstractProcess } from './llm.js';
10
+ import { listIssues, getIssue } from './github.js';
11
+ import { createEnvironment, findEnvironment } from './environment.js';
12
+ import {
13
+ formatTable, formatJson, formatError, formatSuccess,
14
+ truncate, formatDate, formatProgress, setColorEnabled,
15
+ } from './cli-helpers.js';
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Types
19
+ // ---------------------------------------------------------------------------
20
+
21
+ interface GlobalOpts {
22
+ env?: string;
23
+ memoryPath?: string;
24
+ color: boolean;
25
+ json: boolean;
26
+ }
27
+
28
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
29
+ type AnyModule = Record<string, (...args: any[]) => any>;
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Helpers
33
+ // ---------------------------------------------------------------------------
34
+
35
+ async function loadModule(name: string): Promise<AnyModule> {
36
+ const paths: Record<string, string> = {
37
+ langfuse: './langfuse/index.js',
38
+ narrative: './narrative/index.js',
39
+ pde: './pde/index.js',
40
+ planning: './planning/index.js',
41
+ pipeline: './pipeline/index.js',
42
+ };
43
+ const p = paths[name];
44
+ if (!p) throw new Error(`Unknown module: ${name}`);
45
+ try {
46
+ return (await import(p)) as AnyModule;
47
+ } catch {
48
+ throw new Error(`Module '${name}' is not yet implemented. Expected at ${p}`);
49
+ }
50
+ }
51
+
52
+ async function callModule(moduleName: string, funcName: string, ...args: unknown[]): Promise<unknown> {
53
+ const mod = await loadModule(moduleName);
54
+ const fn = mod[funcName];
55
+ if (typeof fn !== 'function') {
56
+ throw new Error(`${moduleName}.${funcName} is not available`);
57
+ }
58
+ return fn(...args);
59
+ }
60
+
61
+ function globals(cmd: Command): GlobalOpts {
62
+ return cmd.optsWithGlobals() as GlobalOpts;
63
+ }
64
+
65
+ function output(data: unknown, cmd: Command): void {
66
+ if (globals(cmd).json) {
67
+ console.log(formatJson(data));
68
+ } else if (typeof data === 'string') {
69
+ console.log(data);
70
+ } else {
71
+ console.log(formatJson(data));
72
+ }
73
+ }
74
+
75
+ async function readStdin(): Promise<string> {
76
+ if (process.stdin.isTTY) return '';
77
+ const chunks: string[] = [];
78
+ for await (const chunk of process.stdin) {
79
+ chunks.push(String(chunk));
80
+ }
81
+ return chunks.join('');
82
+ }
83
+
84
+ function resolveText(
85
+ positional: string | undefined,
86
+ opts: { file?: string },
87
+ ): string | undefined {
88
+ if (opts.file) return readFileSync(resolve(opts.file), 'utf-8');
89
+ return positional;
90
+ }
91
+
92
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
93
+ function actionHandler(
94
+ fn: (...args: any[]) => Promise<void>,
95
+ ): (...args: any[]) => Promise<void> {
96
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
+ return async (...args: any[]) => {
98
+ try {
99
+ await fn(...args);
100
+ } catch (err) {
101
+ console.error(formatError(err instanceof Error ? err.message : String(err)));
102
+ process.exit(1);
103
+ }
104
+ };
105
+ }
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // Root commands
109
+ // ---------------------------------------------------------------------------
110
+
111
+ function registerRootCommands(program: Command): void {
112
+ // ── tash ─────────────────────────────────────────────────────────────
113
+ program
114
+ .command('tash')
115
+ .alias('m')
116
+ .description('Store a key-value pair in Redis')
117
+ .argument('<key>', 'Redis key')
118
+ .argument('[value]', 'Value to store')
119
+ .option('--file <path>', 'Read value from file')
120
+ .option('--ttl <seconds>', 'Time to live in seconds', parseInt)
121
+ .option('--verbose', 'Verbose output')
122
+ .action(
123
+ actionHandler(async (key: string, value: string | undefined, opts: { file?: string; ttl?: number; verbose?: boolean }, cmd: Command) => {
124
+ const val = resolveText(value, opts);
125
+ if (!val) {
126
+ console.error(formatError('Value required — provide as argument or with --file'));
127
+ process.exit(1);
128
+ }
129
+ await tash(key, val, opts.ttl);
130
+ if (opts.verbose) {
131
+ console.log(formatSuccess(`Stored ${key} (${val.length} bytes${opts.ttl ? `, ttl=${opts.ttl}s` : ''})`));
132
+ } else {
133
+ console.log(formatSuccess(`Stored ${key}`));
134
+ }
135
+ }),
136
+ );
137
+
138
+ // ── fetch ────────────────────────────────────────────────────────────
139
+ program
140
+ .command('fetch')
141
+ .description('Get a value from Redis')
142
+ .argument('<key>', 'Redis key')
143
+ .option('--output <path>', 'Write result to file')
144
+ .option('--verbose', 'Verbose output')
145
+ .action(
146
+ actionHandler(async (key: string, opts: { output?: string; verbose?: boolean }, cmd: Command) => {
147
+ const result = await redisFetch(key);
148
+ if (result === null) {
149
+ console.error(formatError(`Key not found: ${key}`));
150
+ process.exit(1);
151
+ }
152
+ if (opts.output) {
153
+ writeFileSync(resolve(opts.output), result);
154
+ console.log(formatSuccess(`Written to ${opts.output}`));
155
+ } else {
156
+ output(result, cmd);
157
+ }
158
+ }),
159
+ );
160
+
161
+ // ── transcribe ───────────────────────────────────────────────────────
162
+ program
163
+ .command('transcribe')
164
+ .alias('t')
165
+ .description('Transcribe audio via Whisper')
166
+ .argument('<file>', 'Audio file path')
167
+ .option('--output <path>', 'Write transcript to file')
168
+ .action(
169
+ actionHandler(async (file: string, opts: { output?: string }, cmd: Command) => {
170
+ const result = await transcribeAudio(resolve(file));
171
+ if (opts.output) {
172
+ writeFileSync(resolve(opts.output), result);
173
+ console.log(formatSuccess(`Transcript written to ${opts.output}`));
174
+ } else {
175
+ output(result, cmd);
176
+ }
177
+ }),
178
+ );
179
+
180
+ // ── summarize ────────────────────────────────────────────────────────
181
+ program
182
+ .command('summarize')
183
+ .alias('s')
184
+ .description('Summarize text')
185
+ .argument('[text]', 'Text to summarize')
186
+ .option('--output <path>', 'Write summary to file')
187
+ .option('--file <path>', 'Read text from file')
188
+ .action(
189
+ actionHandler(async (text: string | undefined, opts: { output?: string; file?: string }, cmd: Command) => {
190
+ let input = resolveText(text, opts);
191
+ if (!input) input = await readStdin();
192
+ if (!input) {
193
+ console.error(formatError('Text required — provide as argument, --file, or pipe via stdin'));
194
+ process.exit(1);
195
+ }
196
+ const result = await abstractProcess('summarize', input);
197
+ if (opts.output) {
198
+ writeFileSync(resolve(opts.output), result);
199
+ console.log(formatSuccess(`Summary written to ${opts.output}`));
200
+ } else {
201
+ output(result, cmd);
202
+ }
203
+ }),
204
+ );
205
+
206
+ // ── p (process) ──────────────────────────────────────────────────────
207
+ program
208
+ .command('p')
209
+ .description('Process text with a custom tag')
210
+ .argument('<tag>', 'Processing tag')
211
+ .argument('[text]', 'Text to process')
212
+ .option('--output <path>', 'Write result to file')
213
+ .option('--file <path>', 'Read text from file')
214
+ .action(
215
+ actionHandler(async (tag: string, text: string | undefined, opts: { output?: string; file?: string }, cmd: Command) => {
216
+ let input = resolveText(text, opts);
217
+ if (!input) input = await readStdin();
218
+ if (!input) {
219
+ console.error(formatError('Text required — provide as argument, --file, or pipe via stdin'));
220
+ process.exit(1);
221
+ }
222
+ const result = await abstractProcess(tag, input);
223
+ if (opts.output) {
224
+ writeFileSync(resolve(opts.output), result);
225
+ console.log(formatSuccess(`Result written to ${opts.output}`));
226
+ } else {
227
+ output(result, cmd);
228
+ }
229
+ }),
230
+ );
231
+
232
+ // ── init ─────────────────────────────────────────────────────────────
233
+ program
234
+ .command('init')
235
+ .description('Create a sample coaia.json config')
236
+ .action(
237
+ actionHandler(async () => {
238
+ const target = resolve('coaia.json');
239
+ if (existsSync(target)) {
240
+ console.error(formatError('coaia.json already exists'));
241
+ process.exit(1);
242
+ }
243
+ const sample = {
244
+ redis: { url: 'redis://localhost:6379' },
245
+ langfuse: { publicKey: '', secretKey: '', baseUrl: 'https://cloud.langfuse.com' },
246
+ openai: { apiKey: '', model: 'gpt-4o-mini' },
247
+ github: { token: '' },
248
+ };
249
+ writeFileSync(target, JSON.stringify(sample, null, 2) + '\n');
250
+ console.log(formatSuccess('Created coaia.json'));
251
+ }),
252
+ );
253
+
254
+ // ── llm ──────────────────────────────────────────────────────────────
255
+ program
256
+ .command('llm')
257
+ .description('Make a raw LLM call')
258
+ .argument('<user>', 'User message')
259
+ .argument('[system]', 'System message')
260
+ .option('--temperature <n>', 'Temperature (0-2)', parseFloat)
261
+ .action(
262
+ actionHandler(async (user: string, system: string | undefined, opts: { temperature?: number }, cmd: Command) => {
263
+ const result = await llmCall(user, system, opts.temperature);
264
+ output(result, cmd);
265
+ }),
266
+ );
267
+ }
268
+
269
+ // ---------------------------------------------------------------------------
270
+ // Fuse (Langfuse) commands
271
+ // ---------------------------------------------------------------------------
272
+
273
+ function registerFuseCommands(program: Command): void {
274
+ const fuse = program
275
+ .command('fuse')
276
+ .description('Langfuse operations');
277
+
278
+ // ── comments ─────────────────────────────────────────────────────────
279
+ const comments = fuse.command('comments').description('Comment operations');
280
+
281
+ comments
282
+ .command('list')
283
+ .description('List comments')
284
+ .option('--trace-id <id>', 'Filter by trace ID')
285
+ .option('--page <n>', 'Page number', parseInt)
286
+ .option('--limit <n>', 'Results per page', parseInt)
287
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
288
+ const result = await callModule('langfuse', 'listComments', opts);
289
+ output(result, cmd);
290
+ }));
291
+
292
+ comments
293
+ .command('post')
294
+ .description('Post a comment')
295
+ .option('--trace-id <id>', 'Trace ID')
296
+ .option('--content <text>', 'Comment content')
297
+ .option('--author <name>', 'Author name')
298
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
299
+ const result = await callModule('langfuse', 'postComment', opts);
300
+ output(result, cmd);
301
+ }));
302
+
303
+ // ── prompts ──────────────────────────────────────────────────────────
304
+ const prompts = fuse.command('prompts').description('Prompt management');
305
+
306
+ prompts
307
+ .command('list')
308
+ .description('List prompts')
309
+ .option('--page <n>', 'Page number', parseInt)
310
+ .option('--limit <n>', 'Results per page', parseInt)
311
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
312
+ const result = await callModule('langfuse', 'listPrompts', opts);
313
+ output(result, cmd);
314
+ }));
315
+
316
+ prompts
317
+ .command('get')
318
+ .description('Get a prompt')
319
+ .argument('<name>', 'Prompt name')
320
+ .option('--version <n>', 'Prompt version', parseInt)
321
+ .action(actionHandler(async (name: string, opts: Record<string, unknown>, cmd: Command) => {
322
+ const result = await callModule('langfuse', 'getPrompt', name, opts);
323
+ output(result, cmd);
324
+ }));
325
+
326
+ prompts
327
+ .command('create')
328
+ .description('Create a prompt')
329
+ .option('--name <name>', 'Prompt name')
330
+ .option('--prompt <text>', 'Prompt text')
331
+ .option('--model <model>', 'Model name')
332
+ .option('--config <json>', 'Config JSON')
333
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
334
+ const result = await callModule('langfuse', 'createPrompt', opts);
335
+ output(result, cmd);
336
+ }));
337
+
338
+ // ── datasets ─────────────────────────────────────────────────────────
339
+ const datasets = fuse.command('datasets').description('Dataset management');
340
+
341
+ datasets
342
+ .command('list')
343
+ .description('List datasets')
344
+ .option('--page <n>', 'Page number', parseInt)
345
+ .option('--limit <n>', 'Results per page', parseInt)
346
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
347
+ const result = await callModule('langfuse', 'listDatasets', opts);
348
+ output(result, cmd);
349
+ }));
350
+
351
+ datasets
352
+ .command('get')
353
+ .description('Get a dataset')
354
+ .argument('<name>', 'Dataset name')
355
+ .action(actionHandler(async (name: string, opts: Record<string, unknown>, cmd: Command) => {
356
+ const result = await callModule('langfuse', 'getDataset', name);
357
+ output(result, cmd);
358
+ }));
359
+
360
+ datasets
361
+ .command('create')
362
+ .description('Create a dataset')
363
+ .option('--name <name>', 'Dataset name')
364
+ .option('--description <text>', 'Description')
365
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
366
+ const result = await callModule('langfuse', 'createDataset', opts);
367
+ output(result, cmd);
368
+ }));
369
+
370
+ // ── sessions ─────────────────────────────────────────────────────────
371
+ const sessions = fuse.command('sessions').description('Session management');
372
+
373
+ sessions
374
+ .command('create')
375
+ .description('Create a session')
376
+ .option('--id <id>', 'Session ID')
377
+ .option('--project-id <id>', 'Project ID')
378
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
379
+ const result = await callModule('langfuse', 'createSession', opts);
380
+ output(result, cmd);
381
+ }));
382
+
383
+ sessions
384
+ .command('addnode')
385
+ .description('Add a node to a session')
386
+ .option('--session-id <id>', 'Session ID')
387
+ .option('--trace-id <id>', 'Trace ID')
388
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
389
+ const result = await callModule('langfuse', 'addSessionNode', opts);
390
+ output(result, cmd);
391
+ }));
392
+
393
+ sessions
394
+ .command('view')
395
+ .description('View a session')
396
+ .argument('<sessionId>', 'Session ID')
397
+ .action(actionHandler(async (sessionId: string, opts: Record<string, unknown>, cmd: Command) => {
398
+ const result = await callModule('langfuse', 'viewSession', sessionId);
399
+ output(result, cmd);
400
+ }));
401
+
402
+ // ── scores ───────────────────────────────────────────────────────────
403
+ const scores = fuse.command('scores').alias('sc').description('Score management');
404
+
405
+ scores
406
+ .command('create')
407
+ .description('Create a score')
408
+ .option('--name <name>', 'Score name')
409
+ .option('--trace-id <id>', 'Trace ID')
410
+ .option('--observation-id <id>', 'Observation ID')
411
+ .option('--value <n>', 'Score value', parseFloat)
412
+ .option('--data-type <type>', 'Data type (NUMERIC|CATEGORICAL|BOOLEAN)')
413
+ .option('--comment <text>', 'Comment')
414
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
415
+ const result = await callModule('langfuse', 'createScore', opts);
416
+ output(result, cmd);
417
+ }));
418
+
419
+ scores
420
+ .command('apply')
421
+ .description('Apply a score config')
422
+ .option('--config <name>', 'Score config name')
423
+ .option('--trace-id <id>', 'Trace ID')
424
+ .option('--value <n>', 'Score value', parseFloat)
425
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
426
+ const result = await callModule('langfuse', 'applyScore', opts);
427
+ output(result, cmd);
428
+ }));
429
+
430
+ scores
431
+ .command('list')
432
+ .description('List scores')
433
+ .option('--trace-id <id>', 'Filter by trace ID')
434
+ .option('--name <name>', 'Filter by name')
435
+ .option('--page <n>', 'Page number', parseInt)
436
+ .option('--limit <n>', 'Results per page', parseInt)
437
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
438
+ const result = await callModule('langfuse', 'listScores', opts);
439
+ output(result, cmd);
440
+ }));
441
+
442
+ // ── score-configs ────────────────────────────────────────────────────
443
+ const scc = fuse.command('score-configs').alias('scc').description('Score config management');
444
+
445
+ scc
446
+ .command('list')
447
+ .description('List score configs')
448
+ .option('--page <n>', 'Page number', parseInt)
449
+ .option('--limit <n>', 'Results per page', parseInt)
450
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
451
+ const result = await callModule('langfuse', 'listScoreConfigs', opts);
452
+ output(result, cmd);
453
+ }));
454
+
455
+ scc
456
+ .command('get')
457
+ .description('Get a score config')
458
+ .argument('<name>', 'Config name')
459
+ .action(actionHandler(async (name: string, opts: Record<string, unknown>, cmd: Command) => {
460
+ const result = await callModule('langfuse', 'getScoreConfig', name);
461
+ output(result, cmd);
462
+ }));
463
+
464
+ scc
465
+ .command('create')
466
+ .description('Create a score config')
467
+ .option('--name <name>', 'Config name')
468
+ .option('--data-type <type>', 'NUMERIC | CATEGORICAL | BOOLEAN')
469
+ .option('--description <text>', 'Description')
470
+ .option('--min <n>', 'Min value (NUMERIC)', parseFloat)
471
+ .option('--max <n>', 'Max value (NUMERIC)', parseFloat)
472
+ .option('--categories <json>', 'Categories JSON (CATEGORICAL)')
473
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
474
+ const result = await callModule('langfuse', 'createScoreConfig', opts);
475
+ output(result, cmd);
476
+ }));
477
+
478
+ scc
479
+ .command('export')
480
+ .description('Export score configs')
481
+ .option('--output <path>', 'Output file path')
482
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
483
+ const result = await callModule('langfuse', 'exportScoreConfigs', opts);
484
+ output(result, cmd);
485
+ }));
486
+
487
+ scc
488
+ .command('import')
489
+ .description('Import score configs')
490
+ .argument('<path>', 'Config file path')
491
+ .action(actionHandler(async (path: string, opts: Record<string, unknown>, cmd: Command) => {
492
+ const result = await callModule('langfuse', 'importScoreConfigs', resolve(path));
493
+ output(result, cmd);
494
+ }));
495
+
496
+ scc
497
+ .command('presets')
498
+ .description('List available presets')
499
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
500
+ const result = await callModule('langfuse', 'listScoreConfigPresets');
501
+ output(result, cmd);
502
+ }));
503
+
504
+ scc
505
+ .command('apply')
506
+ .description('Apply a preset')
507
+ .argument('<preset>', 'Preset name')
508
+ .action(actionHandler(async (preset: string, opts: Record<string, unknown>, cmd: Command) => {
509
+ const result = await callModule('langfuse', 'applyScoreConfigPreset', preset);
510
+ output(result, cmd);
511
+ }));
512
+
513
+ scc
514
+ .command('available')
515
+ .description('Show available score types')
516
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
517
+ const result = await callModule('langfuse', 'availableScoreTypes');
518
+ output(result, cmd);
519
+ }));
520
+
521
+ scc
522
+ .command('show')
523
+ .description('Show a score config in detail')
524
+ .argument('<name>', 'Config name')
525
+ .action(actionHandler(async (name: string, opts: Record<string, unknown>, cmd: Command) => {
526
+ const result = await callModule('langfuse', 'showScoreConfig', name);
527
+ output(result, cmd);
528
+ }));
529
+
530
+ // ── traces ───────────────────────────────────────────────────────────
531
+ const traces = fuse.command('traces').description('Trace operations');
532
+
533
+ traces
534
+ .command('create')
535
+ .description('Create a trace')
536
+ .option('--name <name>', 'Trace name')
537
+ .option('--session-id <id>', 'Session ID')
538
+ .option('--input <json>', 'Input JSON')
539
+ .option('--metadata <json>', 'Metadata JSON')
540
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
541
+ const result = await callModule('langfuse', 'createTrace', opts);
542
+ output(result, cmd);
543
+ }));
544
+
545
+ traces
546
+ .command('add-observation')
547
+ .description('Add an observation to a trace')
548
+ .option('--trace-id <id>', 'Trace ID')
549
+ .option('--name <name>', 'Observation name')
550
+ .option('--type <type>', 'Type: generation | span | event')
551
+ .option('--input <json>', 'Input JSON')
552
+ .option('--output <json>', 'Output JSON')
553
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
554
+ const result = await callModule('langfuse', 'addObservation', opts);
555
+ output(result, cmd);
556
+ }));
557
+
558
+ traces
559
+ .command('add-observations')
560
+ .description('Add multiple observations from a file')
561
+ .option('--trace-id <id>', 'Trace ID')
562
+ .option('--file <path>', 'JSON file with observations')
563
+ .action(actionHandler(async (opts: { traceId?: string; file?: string }, cmd: Command) => {
564
+ let data: unknown = opts;
565
+ if (opts.file) {
566
+ const raw = readFileSync(resolve(opts.file), 'utf-8');
567
+ data = { traceId: opts.traceId, observations: JSON.parse(raw) };
568
+ }
569
+ const result = await callModule('langfuse', 'addObservations', data);
570
+ output(result, cmd);
571
+ }));
572
+
573
+ traces
574
+ .command('patch-output')
575
+ .description('Patch trace output')
576
+ .option('--trace-id <id>', 'Trace ID')
577
+ .option('--output <json>', 'Output JSON')
578
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
579
+ const result = await callModule('langfuse', 'patchTraceOutput', opts);
580
+ output(result, cmd);
581
+ }));
582
+
583
+ traces
584
+ .command('session-view')
585
+ .description('View traces by session')
586
+ .argument('<sessionId>', 'Session ID')
587
+ .action(actionHandler(async (sessionId: string, opts: Record<string, unknown>, cmd: Command) => {
588
+ const result = await callModule('langfuse', 'sessionView', sessionId);
589
+ output(result, cmd);
590
+ }));
591
+
592
+ traces
593
+ .command('trace-view')
594
+ .description('View a specific trace')
595
+ .argument('<traceId>', 'Trace ID')
596
+ .action(actionHandler(async (traceId: string, opts: Record<string, unknown>, cmd: Command) => {
597
+ const result = await callModule('langfuse', 'traceView', traceId);
598
+ output(result, cmd);
599
+ }));
600
+
601
+ traces
602
+ .command('get-observation')
603
+ .description('Get an observation')
604
+ .argument('<observationId>', 'Observation ID')
605
+ .action(actionHandler(async (observationId: string, opts: Record<string, unknown>, cmd: Command) => {
606
+ const result = await callModule('langfuse', 'getObservation', observationId);
607
+ output(result, cmd);
608
+ }));
609
+
610
+ // ── projects ─────────────────────────────────────────────────────────
611
+ fuse
612
+ .command('projects')
613
+ .description('List projects')
614
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
615
+ const result = await callModule('langfuse', 'listProjects');
616
+ output(result, cmd);
617
+ }));
618
+
619
+ // ── media ────────────────────────────────────────────────────────────
620
+ const media = fuse.command('media').description('Media operations');
621
+
622
+ media
623
+ .command('upload')
624
+ .description('Upload a media file')
625
+ .argument('<file>', 'File path')
626
+ .option('--trace-id <id>', 'Associate with trace')
627
+ .action(actionHandler(async (file: string, opts: Record<string, unknown>, cmd: Command) => {
628
+ const result = await callModule('langfuse', 'uploadMedia', resolve(file), opts);
629
+ output(result, cmd);
630
+ }));
631
+
632
+ media
633
+ .command('get')
634
+ .description('Get media details')
635
+ .argument('<mediaId>', 'Media ID')
636
+ .action(actionHandler(async (mediaId: string, opts: Record<string, unknown>, cmd: Command) => {
637
+ const result = await callModule('langfuse', 'getMedia', mediaId);
638
+ output(result, cmd);
639
+ }));
640
+
641
+ // ── dataset-items ────────────────────────────────────────────────────
642
+ const datasetItems = fuse.command('dataset-items').description('Dataset item operations');
643
+
644
+ datasetItems
645
+ .command('create')
646
+ .description('Create a dataset item')
647
+ .option('--dataset <name>', 'Dataset name')
648
+ .option('--input <json>', 'Input JSON')
649
+ .option('--expected <json>', 'Expected output JSON')
650
+ .option('--metadata <json>', 'Metadata JSON')
651
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
652
+ const result = await callModule('langfuse', 'createDatasetItem', opts);
653
+ output(result, cmd);
654
+ }));
655
+ }
656
+
657
+ // ---------------------------------------------------------------------------
658
+ // Pipeline commands
659
+ // ---------------------------------------------------------------------------
660
+
661
+ function registerPipelineCommands(program: Command): void {
662
+ const pipeline = program
663
+ .command('pipeline')
664
+ .description('Pipeline template operations');
665
+
666
+ pipeline
667
+ .command('list')
668
+ .description('List pipeline templates')
669
+ .option('--path <dir>', 'Templates directory')
670
+ .option('--json', 'JSON output')
671
+ .action(actionHandler(async (opts: { path?: string; json?: boolean }, cmd: Command) => {
672
+ const result = await callModule('pipeline', 'listTemplates', opts);
673
+ output(result, cmd);
674
+ }));
675
+
676
+ pipeline
677
+ .command('show')
678
+ .description('Show a pipeline template')
679
+ .argument('<name>', 'Template name')
680
+ .option('--preview', 'Preview rendered template')
681
+ .action(actionHandler(async (name: string, opts: { preview?: boolean }, cmd: Command) => {
682
+ const result = await callModule('pipeline', 'showTemplate', name, opts);
683
+ output(result, cmd);
684
+ }));
685
+
686
+ pipeline
687
+ .command('create')
688
+ .description('Create a run from template')
689
+ .argument('<name>', 'Template name')
690
+ .option(
691
+ '--var <pair>',
692
+ 'Template variable (KEY=value), repeatable',
693
+ (val: string, list: string[]) => { list.push(val); return list; },
694
+ [] as string[],
695
+ )
696
+ .option('--trace-id <id>', 'Trace ID')
697
+ .option('--session-id <id>', 'Session ID')
698
+ .option('--dry-run', 'Preview without executing')
699
+ .action(actionHandler(async (name: string, opts: { var: string[]; traceId?: string; sessionId?: string; dryRun?: boolean }, cmd: Command) => {
700
+ const vars: Record<string, string> = {};
701
+ for (const pair of opts.var) {
702
+ const eq = pair.indexOf('=');
703
+ if (eq === -1) { console.error(formatError(`Invalid --var format: ${pair} (expected KEY=value)`)); process.exit(1); }
704
+ vars[pair.slice(0, eq)] = pair.slice(eq + 1);
705
+ }
706
+ const result = await callModule('pipeline', 'createFromTemplate', name, {
707
+ variables: vars,
708
+ traceId: opts.traceId,
709
+ sessionId: opts.sessionId,
710
+ dryRun: opts.dryRun,
711
+ });
712
+ output(result, cmd);
713
+ }));
714
+
715
+ pipeline
716
+ .command('init')
717
+ .description('Create a new pipeline template')
718
+ .argument('<name>', 'Template name')
719
+ .action(actionHandler(async (name: string, opts: Record<string, unknown>, cmd: Command) => {
720
+ const result = await callModule('pipeline', 'initTemplate', name);
721
+ output(result, cmd);
722
+ }));
723
+ }
724
+
725
+ // ---------------------------------------------------------------------------
726
+ // Environment commands
727
+ // ---------------------------------------------------------------------------
728
+
729
+ function registerEnvCommands(program: Command): void {
730
+ const env = program
731
+ .command('env')
732
+ .description('Environment variable management');
733
+
734
+ env
735
+ .command('init')
736
+ .description('Initialize environment file')
737
+ .action(actionHandler(async () => {
738
+ const mgr = createEnvironment();
739
+ mgr.init();
740
+ console.log(formatSuccess(`Initialized ${mgr.getFilePath()}`));
741
+ }));
742
+
743
+ env
744
+ .command('list')
745
+ .description('List environment variables')
746
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
747
+ const mgr = findEnvironment();
748
+ const vars = mgr.list();
749
+ if (globals(cmd).json) {
750
+ console.log(formatJson(vars));
751
+ } else {
752
+ const entries = Object.entries(vars);
753
+ if (entries.length === 0) {
754
+ console.log('(no variables set)');
755
+ } else {
756
+ console.log(formatTable(
757
+ ['Key', 'Value'],
758
+ entries.map(([k, v]) => [k, truncate(v, 60)]),
759
+ ));
760
+ }
761
+ }
762
+ }));
763
+
764
+ env
765
+ .command('source')
766
+ .description('Load env vars into process')
767
+ .action(actionHandler(async () => {
768
+ const mgr = findEnvironment();
769
+ mgr.source();
770
+ console.log(formatSuccess('Environment loaded'));
771
+ }));
772
+
773
+ env
774
+ .command('set')
775
+ .description('Set an environment variable')
776
+ .argument('<key>', 'Variable name')
777
+ .argument('<value>', 'Variable value')
778
+ .action(actionHandler(async (key: string, value: string) => {
779
+ const mgr = findEnvironment();
780
+ mgr.set(key, value);
781
+ console.log(formatSuccess(`Set ${key}`));
782
+ }));
783
+
784
+ env
785
+ .command('get')
786
+ .description('Get an environment variable')
787
+ .argument('<key>', 'Variable name')
788
+ .action(actionHandler(async (key: string, opts: Record<string, unknown>, cmd: Command) => {
789
+ const mgr = findEnvironment();
790
+ const value = mgr.get(key);
791
+ if (value === undefined) {
792
+ console.error(formatError(`Variable not set: ${key}`));
793
+ process.exit(1);
794
+ }
795
+ output(value, cmd);
796
+ }));
797
+
798
+ env
799
+ .command('unset')
800
+ .description('Remove an environment variable')
801
+ .argument('<key>', 'Variable name')
802
+ .action(actionHandler(async (key: string) => {
803
+ const mgr = findEnvironment();
804
+ mgr.unset(key);
805
+ console.log(formatSuccess(`Unset ${key}`));
806
+ }));
807
+
808
+ env
809
+ .command('clear')
810
+ .description('Remove environment file')
811
+ .action(actionHandler(async () => {
812
+ const mgr = findEnvironment();
813
+ mgr.clear();
814
+ console.log(formatSuccess('Environment cleared'));
815
+ }));
816
+
817
+ env
818
+ .command('save')
819
+ .description('Save current context')
820
+ .action(actionHandler(async () => {
821
+ const mgr = findEnvironment();
822
+ mgr.save();
823
+ console.log(formatSuccess(`Saved to ${mgr.getFilePath()}`));
824
+ }));
825
+ }
826
+
827
+ // ---------------------------------------------------------------------------
828
+ // GitHub commands
829
+ // ---------------------------------------------------------------------------
830
+
831
+ function registerGhCommands(program: Command): void {
832
+ const gh = program
833
+ .command('gh')
834
+ .description('GitHub operations');
835
+
836
+ const issues = gh.command('issues').description('Issue operations');
837
+
838
+ issues
839
+ .command('list')
840
+ .description('List issues')
841
+ .requiredOption('--owner <owner>', 'Repository owner')
842
+ .requiredOption('--repo <repo>', 'Repository name')
843
+ .option('--state <state>', 'Filter: open | closed | all', 'open')
844
+ .option('--labels <labels>', 'Comma-separated labels')
845
+ .option('--per-page <n>', 'Results per page', parseInt)
846
+ .action(actionHandler(async (opts: { owner: string; repo: string; state?: string; labels?: string; perPage?: number }, cmd: Command) => {
847
+ const result = await listIssues(opts.owner, opts.repo, {
848
+ state: opts.state as 'open' | 'closed' | 'all' | undefined,
849
+ labels: opts.labels,
850
+ per_page: opts.perPage,
851
+ });
852
+ if (globals(cmd).json) {
853
+ console.log(formatJson(result));
854
+ } else {
855
+ console.log(formatTable(
856
+ ['#', 'State', 'Title', 'Labels', 'Updated'],
857
+ result.map(i => [
858
+ String(i.number),
859
+ i.state,
860
+ truncate(i.title, 50),
861
+ i.labels.map(l => l.name).join(', '),
862
+ formatDate(i.updated_at),
863
+ ]),
864
+ ));
865
+ }
866
+ }));
867
+
868
+ issues
869
+ .command('get')
870
+ .description('Get an issue (owner/repo#123 or number with --owner/--repo)')
871
+ .argument('<spec>', 'Issue spec: owner/repo#123 or issue number')
872
+ .option('--owner <owner>', 'Repository owner')
873
+ .option('--repo <repo>', 'Repository name')
874
+ .action(actionHandler(async (spec: string, opts: { owner?: string; repo?: string }, cmd: Command) => {
875
+ let owner = opts.owner;
876
+ let repo = opts.repo;
877
+ let num: number;
878
+
879
+ const match = spec.match(/^([^/]+)\/([^#]+)#(\d+)$/);
880
+ if (match) {
881
+ owner = match[1];
882
+ repo = match[2];
883
+ num = parseInt(match[3]!, 10);
884
+ } else {
885
+ num = parseInt(spec, 10);
886
+ if (isNaN(num) || !owner || !repo) {
887
+ console.error(formatError('Provide owner/repo#number or a number with --owner and --repo'));
888
+ process.exit(1);
889
+ }
890
+ }
891
+
892
+ const issue = await getIssue(owner!, repo!, num);
893
+ if (globals(cmd).json) {
894
+ console.log(formatJson(issue));
895
+ } else {
896
+ console.log([
897
+ `${chalk.bold(`#${issue.number}`)} ${issue.title}`,
898
+ `State: ${issue.state} Author: ${issue.user?.login ?? '?'}`,
899
+ `Labels: ${issue.labels.map(l => l.name).join(', ') || '(none)'}`,
900
+ `URL: ${issue.html_url}`,
901
+ '',
902
+ issue.body ?? '(no body)',
903
+ ].join('\n'));
904
+ }
905
+ }));
906
+ }
907
+
908
+ // ---------------------------------------------------------------------------
909
+ // Narrative commands
910
+ // ---------------------------------------------------------------------------
911
+
912
+ function registerNarrativeCommands(program: Command): void {
913
+ const narr = program
914
+ .command('narrative')
915
+ .alias('n')
916
+ .description('Structural tension narrative operations');
917
+
918
+ narr
919
+ .command('list')
920
+ .alias('ls')
921
+ .description('List active charts')
922
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
923
+ const result = await callModule('narrative', 'listCharts', globals(cmd));
924
+ output(result, cmd);
925
+ }));
926
+
927
+ narr
928
+ .command('view')
929
+ .alias('v')
930
+ .description('View chart details')
931
+ .argument('<chartId>', 'Chart ID')
932
+ .action(actionHandler(async (chartId: string, opts: Record<string, unknown>, cmd: Command) => {
933
+ const result = await callModule('narrative', 'viewChart', chartId, globals(cmd));
934
+ output(result, cmd);
935
+ }));
936
+
937
+ narr
938
+ .command('current')
939
+ .alias('cur')
940
+ .description('Show or set the current chart')
941
+ .argument('[chartId]', 'Chart ID to set as current')
942
+ .action(actionHandler(async (chartId: string | undefined, opts: Record<string, unknown>, cmd: Command) => {
943
+ if (chartId) {
944
+ await callModule('narrative', 'setCurrentChart', chartId);
945
+ console.log(formatSuccess(`Current chart set to ${chartId}`));
946
+ } else {
947
+ const result = await callModule('narrative', 'getCurrentChart');
948
+ output(result, cmd);
949
+ }
950
+ }));
951
+
952
+ narr
953
+ .command('update')
954
+ .alias('up')
955
+ .description('Update a chart')
956
+ .argument('<chartId>', 'Chart ID')
957
+ .option('--desired-outcome <text>', 'New desired outcome')
958
+ .option('--current-reality <text>', 'New current reality observation')
959
+ .action(actionHandler(async (chartId: string, opts: { desiredOutcome?: string; currentReality?: string }, cmd: Command) => {
960
+ const result = await callModule('narrative', 'updateChart', chartId, opts);
961
+ output(result, cmd);
962
+ }));
963
+
964
+ narr
965
+ .command('add-action')
966
+ .alias('aa')
967
+ .description('Add an action step to a chart')
968
+ .argument('<chartId>', 'Chart ID')
969
+ .option('--title <text>', 'Action step title')
970
+ .option('--current-reality <text>', 'Current reality for this step')
971
+ .option('--due <date>', 'Due date (ISO)')
972
+ .action(actionHandler(async (chartId: string, opts: { title?: string; currentReality?: string; due?: string }, cmd: Command) => {
973
+ const result = await callModule('narrative', 'addAction', chartId, opts);
974
+ output(result, cmd);
975
+ }));
976
+
977
+ narr
978
+ .command('add-obs')
979
+ .alias('ao')
980
+ .description('Add an observation to a chart')
981
+ .argument('<chartId>', 'Chart ID')
982
+ .argument('[text...]', 'Observation text')
983
+ .action(actionHandler(async (chartId: string, text: string[], opts: Record<string, unknown>, cmd: Command) => {
984
+ const observation = text.join(' ');
985
+ if (!observation) {
986
+ console.error(formatError('Observation text required'));
987
+ process.exit(1);
988
+ }
989
+ const result = await callModule('narrative', 'addObservation', chartId, observation);
990
+ output(result, cmd);
991
+ }));
992
+
993
+ narr
994
+ .command('complete')
995
+ .alias('done')
996
+ .description('Mark an action step complete')
997
+ .argument('<actionName>', 'Action step name')
998
+ .action(actionHandler(async (actionName: string, opts: Record<string, unknown>, cmd: Command) => {
999
+ const result = await callModule('narrative', 'completeAction', actionName);
1000
+ if (typeof result === 'string') console.log(formatSuccess(result));
1001
+ else output(result, cmd);
1002
+ }));
1003
+
1004
+ narr
1005
+ .command('export')
1006
+ .alias('exp')
1007
+ .description('Export a chart to markdown')
1008
+ .argument('<chartId>', 'Chart ID')
1009
+ .option('--output <path>', 'Output file path')
1010
+ .action(actionHandler(async (chartId: string, opts: { output?: string }, cmd: Command) => {
1011
+ const result = await callModule('narrative', 'exportChart', chartId) as string;
1012
+ if (opts.output) {
1013
+ writeFileSync(resolve(opts.output), result);
1014
+ console.log(formatSuccess(`Exported to ${opts.output}`));
1015
+ } else {
1016
+ console.log(result);
1017
+ }
1018
+ }));
1019
+
1020
+ narr
1021
+ .command('export-all')
1022
+ .description('Export all charts to markdown')
1023
+ .option('--output <dir>', 'Output directory')
1024
+ .action(actionHandler(async (opts: { output?: string }, cmd: Command) => {
1025
+ const result = await callModule('narrative', 'exportAllCharts', opts);
1026
+ output(result, cmd);
1027
+ }));
1028
+
1029
+ narr
1030
+ .command('stats')
1031
+ .alias('st')
1032
+ .description('Show chart statistics')
1033
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
1034
+ const result = await callModule('narrative', 'getStats', globals(cmd));
1035
+ output(result, cmd);
1036
+ }));
1037
+
1038
+ narr
1039
+ .command('progress')
1040
+ .alias('pg')
1041
+ .description('Progress report for a chart')
1042
+ .argument('<chartId>', 'Chart ID')
1043
+ .action(actionHandler(async (chartId: string, opts: Record<string, unknown>, cmd: Command) => {
1044
+ const result = await callModule('narrative', 'getProgress', chartId) as {
1045
+ completed: number; total: number; chartId: string;
1046
+ } | unknown;
1047
+ if (globals(cmd).json) {
1048
+ console.log(formatJson(result));
1049
+ } else if (
1050
+ result &&
1051
+ typeof result === 'object' &&
1052
+ 'completed' in result &&
1053
+ 'total' in result
1054
+ ) {
1055
+ const r = result as { completed: number; total: number; chartId: string };
1056
+ console.log(`${chalk.bold(r.chartId)} ${formatProgress(r.completed, r.total)}`);
1057
+ } else {
1058
+ output(result, cmd);
1059
+ }
1060
+ }));
1061
+
1062
+ narr
1063
+ .command('mmot')
1064
+ .description('Run MMOT evaluation on a chart')
1065
+ .argument('<chartId>', 'Chart ID')
1066
+ .option('--assessment <text>', 'Assessment text')
1067
+ .option('--direction <dir>', 'Direction: South | East | West | North')
1068
+ .action(actionHandler(async (chartId: string, opts: { assessment?: string; direction?: string }, cmd: Command) => {
1069
+ const result = await callModule('narrative', 'performMmot', chartId, opts);
1070
+ output(result, cmd);
1071
+ }));
1072
+
1073
+ narr
1074
+ .command('set-date')
1075
+ .alias('sd')
1076
+ .description('Set due date on a chart')
1077
+ .argument('<chartId>', 'Chart ID')
1078
+ .argument('<date>', 'Due date (ISO)')
1079
+ .action(actionHandler(async (chartId: string, date: string, opts: Record<string, unknown>, cmd: Command) => {
1080
+ const result = await callModule('narrative', 'setDueDate', chartId, date);
1081
+ if (typeof result === 'string') console.log(formatSuccess(result));
1082
+ else output(result, cmd);
1083
+ }));
1084
+ }
1085
+
1086
+ // ---------------------------------------------------------------------------
1087
+ // PDE commands
1088
+ // ---------------------------------------------------------------------------
1089
+
1090
+ function registerPdeCommands(program: Command): void {
1091
+ const pde = program
1092
+ .command('pde')
1093
+ .description('Prompt Decomposition Engine');
1094
+
1095
+ pde
1096
+ .command('import')
1097
+ .description('Import a PDE decomposition into narrative')
1098
+ .argument('<pdeId>', 'Decomposition ID')
1099
+ .action(actionHandler(async (pdeId: string, opts: Record<string, unknown>, cmd: Command) => {
1100
+ const result = await callModule('pde', 'importDecomposition', pdeId);
1101
+ output(result, cmd);
1102
+ }));
1103
+
1104
+ pde
1105
+ .command('list')
1106
+ .description('List decompositions')
1107
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
1108
+ const result = await callModule('pde', 'listDecompositions');
1109
+ output(result, cmd);
1110
+ }));
1111
+
1112
+ pde
1113
+ .command('sessions')
1114
+ .description('List PDE sessions')
1115
+ .action(actionHandler(async (opts: Record<string, unknown>, cmd: Command) => {
1116
+ const result = await callModule('pde', 'listSessions');
1117
+ output(result, cmd);
1118
+ }));
1119
+
1120
+ pde
1121
+ .command('show')
1122
+ .description('Show session details')
1123
+ .argument('<sessionId>', 'Session ID')
1124
+ .action(actionHandler(async (sessionId: string, opts: Record<string, unknown>, cmd: Command) => {
1125
+ const result = await callModule('pde', 'showSession', sessionId);
1126
+ output(result, cmd);
1127
+ }));
1128
+ }
1129
+
1130
+ // ---------------------------------------------------------------------------
1131
+ // Planning commands
1132
+ // ---------------------------------------------------------------------------
1133
+
1134
+ function registerPlanCommands(program: Command): void {
1135
+ const plan = program
1136
+ .command('plan')
1137
+ .description('Structural tension plan operations');
1138
+
1139
+ plan
1140
+ .command('parse')
1141
+ .description('Parse a plan file structurally')
1142
+ .argument('<planPath>', 'Path to plan file')
1143
+ .action(actionHandler(async (planPath: string, opts: Record<string, unknown>, cmd: Command) => {
1144
+ const result = await callModule('planning', 'parsePlan', resolve(planPath));
1145
+ output(result, cmd);
1146
+ }));
1147
+
1148
+ plan
1149
+ .command('convert')
1150
+ .description('Convert a plan to a structural tension chart')
1151
+ .argument('<planPath>', 'Path to plan file')
1152
+ .action(actionHandler(async (planPath: string, opts: Record<string, unknown>, cmd: Command) => {
1153
+ const result = await callModule('planning', 'convertToChart', resolve(planPath));
1154
+ output(result, cmd);
1155
+ }));
1156
+
1157
+ plan
1158
+ .command('sync-to-chart')
1159
+ .description('Sync a plan file into charts')
1160
+ .argument('<planPath>', 'Path to plan file')
1161
+ .argument('<chartsPath>', 'Path to charts JSONL')
1162
+ .action(actionHandler(async (planPath: string, chartsPath: string, opts: Record<string, unknown>, cmd: Command) => {
1163
+ const result = await callModule('planning', 'syncToChart', resolve(planPath), resolve(chartsPath));
1164
+ output(result, cmd);
1165
+ }));
1166
+
1167
+ plan
1168
+ .command('sync-to-plan')
1169
+ .description('Sync chart data back to a plan file')
1170
+ .argument('<chartsPath>', 'Path to charts JSONL')
1171
+ .argument('<planPath>', 'Path to plan file')
1172
+ .action(actionHandler(async (chartsPath: string, planPath: string, opts: Record<string, unknown>, cmd: Command) => {
1173
+ const result = await callModule('planning', 'syncToPlan', resolve(chartsPath), resolve(planPath));
1174
+ output(result, cmd);
1175
+ }));
1176
+ }
1177
+
1178
+ // ---------------------------------------------------------------------------
1179
+ // Main
1180
+ // ---------------------------------------------------------------------------
1181
+
1182
+ async function main(): Promise<void> {
1183
+ const program = new Command();
1184
+
1185
+ program
1186
+ .name('coaia')
1187
+ .version('0.1.0', '-V, --version')
1188
+ .description('CoAIA unified CLI — structural tension, narrative, and DevOps tooling')
1189
+ .option('--env <path>', 'Load environment file')
1190
+ .option('-M, --memory-path <path>', 'JSONL memory file path')
1191
+ .option('--no-color', 'Disable colors')
1192
+ .option('--json', 'JSON output', false);
1193
+
1194
+ program.hook('preAction', (_thisCmd, actionCmd) => {
1195
+ const opts = actionCmd.optsWithGlobals();
1196
+ if (opts.color === false) {
1197
+ setColorEnabled(false);
1198
+ }
1199
+ if (opts.env) {
1200
+ readConfig(opts.env as string);
1201
+ }
1202
+ });
1203
+
1204
+ registerRootCommands(program);
1205
+ registerFuseCommands(program);
1206
+ registerPipelineCommands(program);
1207
+ registerEnvCommands(program);
1208
+ registerGhCommands(program);
1209
+ registerNarrativeCommands(program);
1210
+ registerPdeCommands(program);
1211
+ registerPlanCommands(program);
1212
+
1213
+ program.hook('postAction', async () => {
1214
+ try { await redisDisconnect(); } catch { /* client may not have been initialized */ }
1215
+ });
1216
+
1217
+ await program.parseAsync(process.argv);
1218
+ }
1219
+
1220
+ main().catch((err: unknown) => {
1221
+ console.error(formatError(err instanceof Error ? err.message : String(err)));
1222
+ process.exit(1);
1223
+ });