@relipa/ai-flow-kit 0.0.8-beta.1 → 0.0.9-beta.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/bin/aiflow.js CHANGED
@@ -1,400 +1,409 @@
1
1
  #!/usr/bin/env node
2
-
3
- const { program } = require('commander');
4
- const chalk = require('chalk');
5
- const packageJson = require('../package.json');
6
- const initCommand = require('../scripts/init');
7
- const updateCommand = require('../scripts/update');
8
- const doctorCommand = require('../scripts/doctor');
9
- const useCommand = require('../scripts/use');
10
- const TaskDetector = require('../scripts/detect');
11
- const validateCommand = require('../scripts/validate');
12
- const memoryCommand = require('../scripts/memory');
13
- const contextCommand = require('../scripts/context');
14
- const promptCommand = require('../scripts/prompt');
15
- const removeCommand = require('../scripts/remove');
16
- const guideCommand = require('../scripts/guide');
17
- const telemetryCommand= require('../scripts/telemetry/cli');
18
- const taskCommand = require('../scripts/task');
19
- const checkpointCommand = require('../scripts/checkpoint');
20
- const { record } = require('../scripts/telemetry/record');
21
-
22
- // ── DEPRECATION WARNING ───────────────────────────────────────
23
- if (!process.env.AIFLOW_IS_AK) {
24
- console.warn(chalk.yellow('\n⚠ Warning: "aiflow" command is deprecated and will be removed in future versions.'));
25
- console.warn(chalk.yellow('Please use the shorter "ak" command instead.\n'));
26
- }
27
-
28
- program
29
- .version(packageJson.version)
30
- .description('AI Flow Kit CLI - AI-powered development workflows for teams');
31
-
32
- // ── GLOBAL TELEMETRY HOOK ────────────────────────────────────
33
- // We intercept raw argv here so we can catch --version, --help,
34
- // and invalid commands *before* Commander exits the process.
35
- // Also alias `-v` to commander's `-V` at the root only — subcommands still
36
- // keep `-v` as `--verbose`. And alias `--fw` to `--framework`.
37
- (() => {
38
- if (process.argv[2] === '-v') process.argv[2] = '-V';
39
- for (let i = 3; i < process.argv.length; i++) {
40
- if (process.argv[i] === '--fw') process.argv[i] = '--framework';
41
- }
42
- const args = process.argv.slice(2);
43
- let cmd = 'help';
44
- if (args.length > 0) {
45
- const first = args[0];
46
- if (['-V', '-v', '--version'].includes(first)) {
47
- cmd = 'version';
48
- } else if (['-h', '--help'].includes(first)) {
49
- cmd = 'help';
50
- } else if (first.startsWith('-')) {
51
- cmd = 'unknown_flag';
52
- if (args.includes('--help') || args.includes('-h')) cmd = 'help';
53
- } else if (first === 'memory') {
54
- const sec = args[1];
55
- cmd = (sec && !sec.startsWith('-')) ? `memory.${sec}` : 'memory';
56
- } else {
57
- cmd = first;
58
- if (args.includes('--help') || args.includes('-h')) {
59
- cmd = `${first}.help`;
60
- }
61
- }
62
- }
63
- // Record everything except telemetry and gate actions (gate records its own rich event)
64
- if (cmd !== 'telemetry' && !cmd.startsWith('telemetry.') && cmd !== 'gate') {
65
- record('command.invoked', { command: cmd });
66
- }
67
- })();
68
-
69
-
70
- // ── init ──────────────────────────────────────────────────────
71
- program
72
- .command('init')
73
- .alias('i')
74
- .description('Initialize AI Flow Kit in your project')
75
- .option('-f, --framework <types>', 'framework(s), comma-separated (e.g. spring-boot,reactjs)')
76
- .option('-a, --adapter <types>', 'adapter(s), comma-separated (e.g. backlog,jira)')
77
- .option('-e, --env <types>', 'AI environment(s)/tool(s), comma-separated (e.g. cursor,gemini,copilot)')
78
- .option('--with-rtk', 'force enable RTK token compression hook')
79
- .option('--no-rtk', 'skip RTK setup even if RTK is detected')
80
- .action((options) => {
81
- options.frameworks = options.framework
82
- ? options.framework.split(',').map(s => s.trim()).filter(Boolean)
83
- : [];
84
- options.adapters = options.adapter
85
- ? options.adapter.split(',').map(s => s.trim()).filter(Boolean)
86
- : [];
87
- options.aiTools = options.env
88
- ? options.env.split(',').map(s => s.trim()).filter(Boolean)
89
- : Object.keys(require('../scripts/init').AI_TOOL_FILES || {}).filter(t => t !== 'generic');
90
-
91
- record('command.invoked', { command: 'init' });
92
- initCommand(options);
93
- });
94
-
95
- // ── use ───────────────────────────────────────────────────────
96
- program
97
- .command('use [target]')
98
- .alias('u')
99
- .description('Load context from ticket, version, or file')
100
- .option('-m, --manual', 'manual context entry')
101
- .option('-f, --file <path>', 'load from file')
102
- .option('-s, --save <name>', 'save as named context')
103
- .option('-c, --coms', 'load all comments (alias for --with-comments)')
104
- .option('--with-comments', 'load all comments')
105
- .option('--cid <id>', 'load a specific comment by ID')
106
- .option('--clast <n>', 'load the last N comments', parseInt)
107
- .option('--cfrom <id>', 'load comments from ID N onward', parseInt)
108
- .option('--cto <id>', 'load comments up to ID N', parseInt)
109
- .option('-F, --fast', 'fast mode: minimal Q&A, concise requirement doc (Default)')
110
- .option('-U, --full', 'full mode: force complete analysis with Q&A (default)')
111
- .action((target, options) => {
112
- record('command.invoked', { command: 'use' });
113
- useCommand(target, options);
114
- });
115
-
116
- // ── prompt ────────────────────────────────────────────────────
117
- program
118
- .command('prompt [type]')
119
- .alias('p')
120
- .description('Generate AI prompt with context and rules')
121
- .option('-l, --list', 'list available prompt types')
122
- .option('-o, --output <file>', 'save to file')
123
- .option('-L, --lang <lang>', 'language: english (default) or vietnamese')
124
- .option('-d, --detail <level>', 'detail level: minimal | standard (default) | comprehensive')
125
- .action((type, options) => {
126
- record('command.invoked', { command: 'prompt' });
127
- promptCommand(type, options);
128
- });
129
-
130
- // ── detect ────────────────────────────────────────────────────
131
- program
132
- .command('detect [description]')
133
- .alias('d')
134
- .description('Auto-detect task type from description')
135
- .option('-v, --verbose', 'show detection details')
136
- .option('-t, --threshold <number>', 'confidence threshold (0-100)')
137
- .action((description, options) => {
138
- record('command.invoked', { command: 'detect' });
139
- const detector = new TaskDetector();
140
- const threshold = options.threshold ? parseInt(options.threshold) / 100 : 0.8;
141
- const result = detector.detect(description, threshold);
142
- console.log(chalk.cyan('\nTask Detection Results:\n'));
143
- console.log(detector.formatOutput(result, options.verbose));
144
- });
145
-
146
- // ── task ─────────────────────────────────────────────────────
147
- const taskCmd = program.command('task').alias('t').description('Manage multiple tasks — pause, switch, resume');
148
-
149
- taskCmd
150
- .command('status')
151
- .alias('st')
152
- .description('Show active task and pending tasks')
153
- .action(() => { record('command.invoked', { command: 'task.status' }); taskCommand('status'); });
154
-
155
- taskCmd
156
- .command('list')
157
- .alias('ls')
158
- .description('List all saved tasks')
159
- .action(() => { record('command.invoked', { command: 'task.list' }); taskCommand('list'); });
160
-
161
- taskCmd
162
- .command('pause')
163
- .alias('p')
164
- .description('Pause current task and save progress')
165
- .option('-n, --note <text>', 'note about why you are pausing')
166
- .action((opts) => { record('command.invoked', { command: 'task.pause' }); taskCommand('pause', { note: opts.note }); });
167
-
168
- taskCmd
169
- .command('switch <ticket-id>')
170
- .alias('sw')
171
- .description('Pause current task and switch to another')
172
- .action((ticketId) => { record('command.invoked', { command: 'task.switch' }); taskCommand('switch', { taskId: ticketId }); });
173
-
174
- taskCmd
175
- .command('resume <ticket-id>')
176
- .alias('r')
177
- .description('Resume a paused task')
178
- .action((ticketId) => { record('command.invoked', { command: 'task.resume' }); taskCommand('resume', { taskId: ticketId }); });
179
-
180
- taskCmd
181
- .command('reset <ticket-id>')
182
- .alias('rst')
183
- .description('Reset task to Gate 1 (keeps ticket context, clears gate progress)')
184
- .action((ticketId) => { record('command.invoked', { command: 'task.reset' }); taskCommand('reset', { taskId: ticketId }); });
185
-
186
- taskCmd
187
- .command('remove <ticket-id>')
188
- .alias('rm')
189
- .description('Permanently delete all saved data for a task')
190
- .action((ticketId) => { record('command.invoked', { command: 'task.remove' }); taskCommand('remove', { taskId: ticketId }); });
191
-
192
- taskCmd
193
- .command('next')
194
- .alias('n')
195
- .description('Approve current gate and prepare next session (saves state for resume)')
196
- .option('-t, --ticket <id>', 'ticket ID (defaults to active task)')
197
- .action((opts) => {
198
- record('command.invoked', { command: 'task.next' });
199
- taskCommand('next', { taskId: opts.ticket });
200
- });
201
-
202
- // ── context ───────────────────────────────────────────────────
203
- program
204
- .command('context [action]')
205
- .alias('ctx')
206
- .description('Manage task contexts (list|show|save <name>|clear)')
207
- .option('-s, --save <name>', 'save current context with name')
208
- .option('-l, --load <name>', 'load saved context by name')
209
- .option('-d, --delete <name>', 'delete saved context')
210
- .option('--clear', 'clear all saved contexts')
211
- .option('--show', 'show current context')
212
- .action((action, options) => {
213
- record('command.invoked', { command: 'context' });
214
- contextCommand(action, options);
215
- });
216
-
217
- // ── checkpoint ────────────────────────────────────────────────
218
- program
219
- .command('checkpoint')
220
- .alias('cp')
221
- .description('Record token usage checkpoint (called by AI during gate work)')
222
- .requiredOption('-g, --gate <n>', 'gate number (1–5)', parseInt)
223
- .requiredOption('-s, --step <name>', 'step name (e.g. "tests-written")')
224
- .requiredOption('-n, --tokens <n>', 'estimated token count', parseInt)
225
- .option('-t, --ticket <id>', 'ticket ID (defaults to active task)')
226
- .action((opts) => {
227
- record('command.invoked', { command: 'checkpoint' });
228
- checkpointCommand({ gate: opts.gate, step: opts.step, tokens: opts.tokens, ticket: opts.ticket });
229
- });
230
-
231
- // ── validate ──────────────────────────────────────────────────
232
- program
233
- .command('validate <file>')
234
- .alias('vl')
235
- .description('Validate output against team rules')
236
- .option('-r, --ruleset <set>', 'rule set: default | strict | lenient', 'default')
237
- .option('-v, --verbose', 'detailed report')
238
- .option('-x, --fix', 'auto-fix trailing whitespace')
239
- .action((file, options) => {
240
- record('command.invoked', { command: 'validate' });
241
- validateCommand(file, {
242
- ruleset: options.ruleset,
243
- verbose: options.verbose,
244
- fix: options.fix
245
- });
246
- });
247
-
248
- // ── memory ────────────────────────────────────────────────────
249
- // Sub-commands to avoid the ambiguous "memory <action> --save key" pattern
250
- const memCmd = program.command('memory').alias('mem').description('Manage team knowledge and memory');
251
-
252
- memCmd
253
- .command('save <key> <value>')
254
- .alias('s')
255
- .description('Save a memory entry')
256
- .action((key, value) => { record('command.invoked', { command: 'memory.save' }); memoryCommand('save', { key, value }); });
257
-
258
- memCmd
259
- .command('get <key>')
260
- .alias('g')
261
- .description('Retrieve a memory entry')
262
- .action((key) => { record('command.invoked', { command: 'memory.get' }); memoryCommand('get', { key }); });
263
-
264
- memCmd
265
- .command('list')
266
- .alias('ls')
267
- .description('List all memories')
268
- .action(() => { record('command.invoked', { command: 'memory.list' }); memoryCommand('list'); });
269
-
270
- memCmd
271
- .command('search <query>')
272
- .alias('sr')
273
- .description('Search memories by keyword')
274
- .action((query) => { record('command.invoked', { command: 'memory.search' }); memoryCommand('search', { query }); });
275
-
276
- memCmd
277
- .command('delete <key>')
278
- .alias('d')
279
- .description('Delete a memory entry')
280
- .action((key) => { record('command.invoked', { command: 'memory.delete' }); memoryCommand('delete', { key }); });
281
-
282
- memCmd
283
- .command('clear')
284
- .alias('cl')
285
- .description('Clear all memories')
286
- .action(() => { record('command.invoked', { command: 'memory.clear' }); memoryCommand('clear'); });
287
-
288
- // ── guide ─────────────────────────────────────────────────────
289
- program
290
- .command('guide')
291
- .alias('g')
292
- .description('Show quickstart guide, architecture, and command reference')
293
- .option('-f, --flow', 'show architecture & flow diagram only')
294
- .option('-c, --commands', 'show command reference only')
295
- .action((options) => {
296
- record('command.invoked', { command: 'guide' });
297
- guideCommand(options);
298
- });
299
-
300
- // ── gate (telemetry for gate workflow events) ─────────────────
301
- program
302
- .command('gate <number> <action>')
303
- .description('Log a gate workflow event (start|approved) — called by AI during gate workflow')
304
- .option('--ticket <id>', 'ticket ID')
305
- .option('--ai-tool <tool>', 'AI tool name')
306
- .action((number, action, options) => {
307
- const gateNum = parseInt(number);
308
- if (isNaN(gateNum) || gateNum < 1 || gateNum > 5) return;
309
- if (!['start', 'approved'].includes(action)) return;
310
- record(`gate.${action}`, {
311
- gate: gateNum,
312
- ticket_id: options.ticket || '',
313
- command: `gate${gateNum}.${action}`,
314
- ai_tool: options.aiTool || ''
315
- });
316
-
317
- if (action === 'approved') {
318
- console.log(chalk.cyan(`\n Gate ${gateNum} approved!`));
319
- console.log(chalk.yellow(` Pro-Tip: To avoid context pollution, it's recommended to start a fresh chat session.`));
320
- console.log(chalk.gray(` Run: aiflow task next${options.ticket ? ` --ticket ${options.ticket}` : ''} to save progress,`));
321
- console.log(chalk.gray(` then open a NEW chatbox and type "continue".\n`));
322
- }
323
- });
324
-
325
- // ── remove ────────────────────────────────────────────────────
326
- program
327
- .command('remove')
328
- .alias('rm')
329
- .description('Remove ai-flow-kit from project, a cached version, or uninstall globally')
330
- .option('--version <ver>', 'remove a specific cached version from .aiflow/versions/')
331
- .option('-g, --global', 'uninstall the global npm package (removes `aiflow` command)')
332
- .action((options) => {
333
- record('command.invoked', { command: 'remove' });
334
- removeCommand(options);
335
- });
336
-
337
- // ── update ────────────────────────────────────────────────────
338
- program
339
- .command('update')
340
- .alias('up')
341
- .description('Update to latest version')
342
- .option('-f, --force', 'force update even if already on latest')
343
- .action((options) => {
344
- record('command.invoked', { command: 'update' });
345
- updateCommand(options);
346
- });
347
-
348
- // ── sync-skills ───────────────────────────────────────────────
349
- program
350
- .command('sync-skills')
351
- .alias('sync')
352
- .description('Manually synchronize AI Instruction files with local custom skills')
353
- .action(async () => {
354
- record('command.invoked', { command: 'sync-skills' });
355
- const projectDir = process.cwd();
356
- const { setupFramework, AI_TOOL_FILES, ensureAiflowGitignored } = require('../scripts/init');
357
- const fs = require('fs-extra');
358
- const path = require('path');
359
- const chalk = require('chalk');
360
-
361
- const stateFile = path.join(projectDir, '.aiflow', 'state.json');
362
- if (!(await fs.pathExists(stateFile))) {
363
- console.log(chalk.red('Project is not initialized. Please run `aiflow init` first.'));
364
- return;
365
- }
366
-
367
- const state = await fs.readJson(stateFile);
368
- const frameworks = state.frameworks || [];
369
- const selectedTools = state.aiTools || Object.keys(AI_TOOL_FILES);
370
-
371
- console.log(chalk.cyan('⟳ Syncing AI Instruction files...'));
372
- for (const fw of frameworks) {
373
- await setupFramework(projectDir, fw, frameworks.length > 1, selectedTools);
374
- }
375
- await ensureAiflowGitignored(projectDir);
376
- console.log(chalk.green('✨ Sync completed!'));
377
- });
378
-
379
- // ── doctor ────────────────────────────────────────────────────
380
- program
381
- .command('doctor')
382
- .alias('dr')
383
- .description('Health check of AI Flow Kit setup')
384
- .option('-t, --ticket <id>', 'show token breakdown for specific ticket')
385
- .option('-v, --verbose', 'detailed output')
386
- .action((opts) => {
387
- record('command.invoked', { command: 'doctor' });
388
- doctorCommand({ ticket: opts.ticket, verbose: opts.verbose });
389
- });
390
-
391
- // ── telemetry ──────────────────────────────────────────────────
392
- program
393
- .command('telemetry [action]')
394
- .alias('tel')
395
- .description('Manage telemetry logging (enable|disable|status)')
396
- .action((action) => {
397
- telemetryCommand(action || 'status');
398
- });
399
-
400
- program.parse(process.argv);
2
+
3
+ const { program } = require('commander');
4
+ const chalk = require('chalk');
5
+ const packageJson = require('../package.json');
6
+ const initCommand = require('../scripts/init');
7
+ const updateCommand = require('../scripts/update');
8
+ const doctorCommand = require('../scripts/doctor');
9
+ const useCommand = require('../scripts/use');
10
+ const TaskDetector = require('../scripts/detect');
11
+ const validateCommand = require('../scripts/validate');
12
+ const memoryCommand = require('../scripts/memory');
13
+ const contextCommand = require('../scripts/context');
14
+ const promptCommand = require('../scripts/prompt');
15
+ const removeCommand = require('../scripts/remove');
16
+ const guideCommand = require('../scripts/guide');
17
+ const telemetryCommand= require('../scripts/telemetry/cli');
18
+ const taskCommand = require('../scripts/task');
19
+ const checkpointCommand = require('../scripts/checkpoint');
20
+ const { record } = require('../scripts/telemetry/record');
21
+ const { updateTaskGateState } = require('../scripts/task');
22
+
23
+ // ── DEPRECATION WARNING ───────────────────────────────────────
24
+ if (!process.env.AIFLOW_IS_AK) {
25
+ console.warn(chalk.yellow('\n⚠ Warning: "aiflow" command is deprecated and will be removed in future versions.'));
26
+ console.warn(chalk.yellow('Please use the shorter "ak" command instead.\n'));
27
+ }
28
+
29
+ program
30
+ .version(packageJson.version)
31
+ .description('AI Flow Kit CLI - AI-powered development workflows for teams');
32
+
33
+ // ── GLOBAL TELEMETRY HOOK ────────────────────────────────────
34
+ // We intercept raw argv here so we can catch --version, --help,
35
+ // and invalid commands *before* Commander exits the process.
36
+ // Also alias `-v` to commander's `-V` at the root only — subcommands still
37
+ // keep `-v` as `--verbose`. And alias `--fw` to `--framework`.
38
+ (() => {
39
+ if (process.argv[2] === '-v') process.argv[2] = '-V';
40
+ for (let i = 3; i < process.argv.length; i++) {
41
+ if (process.argv[i] === '--fw') process.argv[i] = '--framework';
42
+ }
43
+ const args = process.argv.slice(2);
44
+ let cmd = 'help';
45
+ if (args.length > 0) {
46
+ const first = args[0];
47
+ if (['-V', '-v', '--version'].includes(first)) {
48
+ cmd = 'version';
49
+ } else if (['-h', '--help'].includes(first)) {
50
+ cmd = 'help';
51
+ } else if (first.startsWith('-')) {
52
+ cmd = 'unknown_flag';
53
+ if (args.includes('--help') || args.includes('-h')) cmd = 'help';
54
+ } else if (first === 'memory') {
55
+ const sec = args[1];
56
+ cmd = (sec && !sec.startsWith('-')) ? `memory.${sec}` : 'memory';
57
+ } else {
58
+ cmd = first;
59
+ if (args.includes('--help') || args.includes('-h')) {
60
+ cmd = `${first}.help`;
61
+ }
62
+ }
63
+ }
64
+ // Record everything except telemetry and gate actions (gate records its own rich event)
65
+ if (cmd !== 'telemetry' && !cmd.startsWith('telemetry.') && cmd !== 'gate') {
66
+ record('command.invoked', { command: cmd });
67
+ }
68
+ })();
69
+
70
+
71
+ // ── init ──────────────────────────────────────────────────────
72
+ program
73
+ .command('init')
74
+ .alias('i')
75
+ .description('Initialize AI Flow Kit in your project')
76
+ .option('-f, --framework <types>', 'framework(s), comma-separated (e.g. spring-boot,reactjs)')
77
+ .option('-a, --adapter <types>', 'adapter(s), comma-separated (e.g. backlog,jira)')
78
+ .option('-e, --env <types>', 'AI environment(s)/tool(s), comma-separated (e.g. cursor,gemini,copilot)')
79
+ .option('--with-rtk', 'force enable RTK token compression hook')
80
+ .option('--no-rtk', 'skip RTK setup even if RTK is detected')
81
+ .action((options) => {
82
+ options.frameworks = options.framework
83
+ ? options.framework.split(',').map(s => s.trim()).filter(Boolean)
84
+ : [];
85
+ options.adapters = options.adapter
86
+ ? options.adapter.split(',').map(s => s.trim()).filter(Boolean)
87
+ : [];
88
+ options.aiTools = options.env
89
+ ? options.env.split(',').map(s => s.trim()).filter(Boolean)
90
+ : Object.keys(require('../scripts/init').AI_TOOL_FILES || {}).filter(t => t !== 'generic');
91
+
92
+ record('command.invoked', { command: 'init' });
93
+ initCommand(options);
94
+ });
95
+
96
+ // ── use ───────────────────────────────────────────────────────
97
+ program
98
+ .command('use [target]')
99
+ .alias('u')
100
+ .description('Load context from ticket, version, or file')
101
+ .option('-m, --manual', 'manual context entry')
102
+ .option('-f, --file <path>', 'load from file')
103
+ .option('-s, --save <name>', 'save as named context')
104
+ .option('-c, --coms', 'load all comments (alias for --with-comments)')
105
+ .option('--with-comments', 'load all comments')
106
+ .option('--cid <id>', 'load a specific comment by ID')
107
+ .option('--clast <n>', 'load the last N comments', parseInt)
108
+ .option('--cfrom <id>', 'load comments from ID N onward', parseInt)
109
+ .option('--cto <id>', 'load comments up to ID N', parseInt)
110
+ .option('-F, --fast', 'fast mode: minimal Q&A, concise requirement doc (Default)')
111
+ .option('-U, --full', 'full mode: force complete analysis with Q&A (default)')
112
+ .action((target, options) => {
113
+ record('command.invoked', { command: 'use' });
114
+ useCommand(target, options);
115
+ });
116
+
117
+ // ── prompt ────────────────────────────────────────────────────
118
+ program
119
+ .command('prompt [type]')
120
+ .alias('p')
121
+ .description('Generate AI prompt with context and rules')
122
+ .option('-l, --list', 'list available prompt types')
123
+ .option('-o, --output <file>', 'save to file')
124
+ .option('-L, --lang <lang>', 'language: english (default) or vietnamese')
125
+ .option('-d, --detail <level>', 'detail level: minimal | standard (default) | comprehensive')
126
+ .action((type, options) => {
127
+ record('command.invoked', { command: 'prompt' });
128
+ promptCommand(type, options);
129
+ });
130
+
131
+ // ── detect ────────────────────────────────────────────────────
132
+ program
133
+ .command('detect [description]')
134
+ .alias('d')
135
+ .description('Auto-detect task type from description')
136
+ .option('-v, --verbose', 'show detection details')
137
+ .option('-t, --threshold <number>', 'confidence threshold (0-100)')
138
+ .action((description, options) => {
139
+ record('command.invoked', { command: 'detect' });
140
+ const detector = new TaskDetector();
141
+ const threshold = options.threshold ? parseInt(options.threshold) / 100 : 0.8;
142
+ const result = detector.detect(description, threshold);
143
+ console.log(chalk.cyan('\nTask Detection Results:\n'));
144
+ console.log(detector.formatOutput(result, options.verbose));
145
+ });
146
+
147
+ // ── task ─────────────────────────────────────────────────────
148
+ const taskCmd = program.command('task').alias('t').description('Manage multiple tasks — pause, switch, resume');
149
+
150
+ taskCmd
151
+ .command('status')
152
+ .alias('st')
153
+ .description('Show active task and pending tasks')
154
+ .action(() => { record('command.invoked', { command: 'task.status' }); taskCommand('status'); });
155
+
156
+ taskCmd
157
+ .command('list')
158
+ .alias('ls')
159
+ .description('List all saved tasks')
160
+ .action(() => { record('command.invoked', { command: 'task.list' }); taskCommand('list'); });
161
+
162
+ taskCmd
163
+ .command('pause')
164
+ .alias('p')
165
+ .description('Pause current task and save progress')
166
+ .option('-n, --note <text>', 'note about why you are pausing')
167
+ .action((opts) => { record('command.invoked', { command: 'task.pause' }); taskCommand('pause', { note: opts.note }); });
168
+
169
+ taskCmd
170
+ .command('switch <ticket-id>')
171
+ .alias('sw')
172
+ .description('Pause current task and switch to another')
173
+ .action((ticketId) => { record('command.invoked', { command: 'task.switch' }); taskCommand('switch', { taskId: ticketId }); });
174
+
175
+ taskCmd
176
+ .command('resume <ticket-id>')
177
+ .alias('r')
178
+ .description('Resume a paused task')
179
+ .action((ticketId) => { record('command.invoked', { command: 'task.resume' }); taskCommand('resume', { taskId: ticketId }); });
180
+
181
+ taskCmd
182
+ .command('reset <ticket-id>')
183
+ .alias('rst')
184
+ .description('Reset task to Gate 1 (keeps ticket context, clears gate progress)')
185
+ .action((ticketId) => { record('command.invoked', { command: 'task.reset' }); taskCommand('reset', { taskId: ticketId }); });
186
+
187
+ taskCmd
188
+ .command('remove <ticket-id>')
189
+ .alias('rm')
190
+ .description('Permanently delete all saved data for a task')
191
+ .action((ticketId) => { record('command.invoked', { command: 'task.remove' }); taskCommand('remove', { taskId: ticketId }); });
192
+
193
+ taskCmd
194
+ .command('next')
195
+ .alias('n')
196
+ .description('Approve current gate and prepare next session (saves state for resume)')
197
+ .option('-t, --ticket <id>', 'ticket ID (defaults to active task)')
198
+ .action((opts) => {
199
+ record('command.invoked', { command: 'task.next' });
200
+ taskCommand('next', { taskId: opts.ticket });
201
+ });
202
+
203
+ // ── context ───────────────────────────────────────────────────
204
+ program
205
+ .command('context [action]')
206
+ .alias('ctx')
207
+ .description('Manage task contexts (list|show|save <name>|clear)')
208
+ .option('-s, --save <name>', 'save current context with name')
209
+ .option('-l, --load <name>', 'load saved context by name')
210
+ .option('-d, --delete <name>', 'delete saved context')
211
+ .option('--clear', 'clear all saved contexts')
212
+ .option('--show', 'show current context')
213
+ .action((action, options) => {
214
+ record('command.invoked', { command: 'context' });
215
+ contextCommand(action, options);
216
+ });
217
+
218
+ // ── checkpoint ────────────────────────────────────────────────
219
+ program
220
+ .command('checkpoint')
221
+ .alias('cp')
222
+ .description('Record token usage checkpoint (called by AI during gate work)')
223
+ .requiredOption('-g, --gate <n>', 'gate number (1–5)', parseInt)
224
+ .requiredOption('-s, --step <name>', 'step name (e.g. "tests-written")')
225
+ .requiredOption('-n, --tokens <n>', 'estimated token count', parseInt)
226
+ .option('-t, --ticket <id>', 'ticket ID (defaults to active task)')
227
+ .action((opts) => {
228
+ record('command.invoked', { command: 'checkpoint' });
229
+ checkpointCommand({ gate: opts.gate, step: opts.step, tokens: opts.tokens, ticket: opts.ticket });
230
+ });
231
+
232
+ // ── validate ──────────────────────────────────────────────────
233
+ program
234
+ .command('validate <file>')
235
+ .alias('vl')
236
+ .description('Validate output against team rules')
237
+ .option('-r, --ruleset <set>', 'rule set: default | strict | lenient', 'default')
238
+ .option('-v, --verbose', 'detailed report')
239
+ .option('-x, --fix', 'auto-fix trailing whitespace')
240
+ .action((file, options) => {
241
+ record('command.invoked', { command: 'validate' });
242
+ validateCommand(file, {
243
+ ruleset: options.ruleset,
244
+ verbose: options.verbose,
245
+ fix: options.fix
246
+ });
247
+ });
248
+
249
+ // ── memory ────────────────────────────────────────────────────
250
+ // Sub-commands to avoid the ambiguous "memory <action> --save key" pattern
251
+ const memCmd = program.command('memory').alias('mem').description('Manage team knowledge and memory');
252
+
253
+ memCmd
254
+ .command('save <key> <value>')
255
+ .alias('s')
256
+ .description('Save a memory entry')
257
+ .action((key, value) => { record('command.invoked', { command: 'memory.save' }); memoryCommand('save', { key, value }); });
258
+
259
+ memCmd
260
+ .command('get <key>')
261
+ .alias('g')
262
+ .description('Retrieve a memory entry')
263
+ .action((key) => { record('command.invoked', { command: 'memory.get' }); memoryCommand('get', { key }); });
264
+
265
+ memCmd
266
+ .command('list')
267
+ .alias('ls')
268
+ .description('List all memories')
269
+ .action(() => { record('command.invoked', { command: 'memory.list' }); memoryCommand('list'); });
270
+
271
+ memCmd
272
+ .command('search <query>')
273
+ .alias('sr')
274
+ .description('Search memories by keyword')
275
+ .action((query) => { record('command.invoked', { command: 'memory.search' }); memoryCommand('search', { query }); });
276
+
277
+ memCmd
278
+ .command('delete <key>')
279
+ .alias('d')
280
+ .description('Delete a memory entry')
281
+ .action((key) => { record('command.invoked', { command: 'memory.delete' }); memoryCommand('delete', { key }); });
282
+
283
+ memCmd
284
+ .command('clear')
285
+ .alias('cl')
286
+ .description('Clear all memories')
287
+ .action(() => { record('command.invoked', { command: 'memory.clear' }); memoryCommand('clear'); });
288
+
289
+ // ── guide ─────────────────────────────────────────────────────
290
+ program
291
+ .command('guide')
292
+ .alias('g')
293
+ .description('Show quickstart guide, architecture, and command reference')
294
+ .option('-f, --flow', 'show architecture & flow diagram only')
295
+ .option('-c, --commands', 'show command reference only')
296
+ .action((options) => {
297
+ record('command.invoked', { command: 'guide' });
298
+ guideCommand(options);
299
+ });
300
+
301
+ // ── gate (telemetry for gate workflow events) ─────────────────
302
+ program
303
+ .command('gate <number> <action>')
304
+ .description('Log a gate workflow event (start|approved) — called by AI during gate workflow')
305
+ .option('--ticket <id>', 'ticket ID')
306
+ .option('--ai-tool <tool>', 'AI tool name')
307
+ .action((number, action, options) => {
308
+ const gateNum = parseInt(number);
309
+ if (isNaN(gateNum) || gateNum < 1 || gateNum > 5) return;
310
+ if (!['start', 'approved'].includes(action)) return;
311
+
312
+ const ticketId = options.ticket || '';
313
+
314
+ record(`gate.${action}`, {
315
+ gate: gateNum,
316
+ ticket_id: ticketId,
317
+ command: `gate${gateNum}.${action}`,
318
+ ai_tool: options.aiTool || ''
319
+ });
320
+
321
+ // Keep task-state.json currentGate in sync (silent never blocks the AI)
322
+ if (ticketId) {
323
+ updateTaskGateState(ticketId, gateNum, action).catch(() => {});
324
+ }
325
+
326
+ if (action === 'approved') {
327
+ console.log(chalk.cyan(`\n Gate ${gateNum} approved!`));
328
+ console.log(chalk.yellow(` Pro-Tip: To avoid context pollution, it's recommended to start a fresh chat session.`));
329
+ console.log(chalk.gray(` Run: aiflow task next${ticketId ? ` --ticket ${ticketId}` : ''} to save progress,`));
330
+ console.log(chalk.gray(` then open a NEW chatbox and type "continue".\n`));
331
+ }
332
+ });
333
+
334
+ // ── remove ────────────────────────────────────────────────────
335
+ program
336
+ .command('remove')
337
+ .alias('rm')
338
+ .description('Remove ai-flow-kit from project, a cached version, or uninstall globally')
339
+ .option('--version <ver>', 'remove a specific cached version from .aiflow/versions/')
340
+ .option('-g, --global', 'uninstall the global npm package (removes `aiflow` command)')
341
+ .action((options) => {
342
+ record('command.invoked', { command: 'remove' });
343
+ removeCommand(options);
344
+ });
345
+
346
+ // ── update ────────────────────────────────────────────────────
347
+ program
348
+ .command('update')
349
+ .alias('up')
350
+ .description('Update to latest version')
351
+ .option('-f, --force', 'force update even if already on latest')
352
+ .action((options) => {
353
+ record('command.invoked', { command: 'update' });
354
+ updateCommand(options);
355
+ });
356
+
357
+ // ── sync-skills ───────────────────────────────────────────────
358
+ program
359
+ .command('sync-skills')
360
+ .alias('sync')
361
+ .description('Manually synchronize AI Instruction files with local custom skills')
362
+ .action(async () => {
363
+ record('command.invoked', { command: 'sync-skills' });
364
+ const projectDir = process.cwd();
365
+ const { setupFramework, AI_TOOL_FILES, ensureAiflowGitignored } = require('../scripts/init');
366
+ const fs = require('fs-extra');
367
+ const path = require('path');
368
+ const chalk = require('chalk');
369
+
370
+ const stateFile = path.join(projectDir, '.aiflow', 'state.json');
371
+ if (!(await fs.pathExists(stateFile))) {
372
+ console.log(chalk.red('Project is not initialized. Please run `aiflow init` first.'));
373
+ return;
374
+ }
375
+
376
+ const state = await fs.readJson(stateFile);
377
+ const frameworks = state.frameworks || [];
378
+ const selectedTools = state.aiTools || Object.keys(AI_TOOL_FILES);
379
+
380
+ console.log(chalk.cyan('⟳ Syncing AI Instruction files...'));
381
+ for (const fw of frameworks) {
382
+ await setupFramework(projectDir, fw, frameworks.length > 1, selectedTools);
383
+ }
384
+ await ensureAiflowGitignored(projectDir);
385
+ console.log(chalk.green(' Sync completed!'));
386
+ });
387
+
388
+ // ── doctor ────────────────────────────────────────────────────
389
+ program
390
+ .command('doctor')
391
+ .alias('dr')
392
+ .description('Health check of AI Flow Kit setup')
393
+ .option('-t, --ticket <id>', 'show token breakdown for specific ticket')
394
+ .option('-v, --verbose', 'detailed output')
395
+ .action((opts) => {
396
+ record('command.invoked', { command: 'doctor' });
397
+ doctorCommand({ ticket: opts.ticket, verbose: opts.verbose });
398
+ });
399
+
400
+ // ── telemetry ──────────────────────────────────────────────────
401
+ program
402
+ .command('telemetry [action]')
403
+ .alias('tel')
404
+ .description('Manage telemetry logging (enable|disable|status)')
405
+ .action((action) => {
406
+ telemetryCommand(action || 'status');
407
+ });
408
+
409
+ program.parse(process.argv);