@agentic-sdlc-kit/cli 0.9.1 → 1.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 (149) hide show
  1. package/dist/application/agent/orchestrator.d.ts.map +1 -1
  2. package/dist/application/agent/orchestrator.js +4 -3
  3. package/dist/application/agent/orchestrator.js.map +1 -1
  4. package/dist/application/agent/providers/claude-code/permission-config.d.ts.map +1 -1
  5. package/dist/application/agent/providers/claude-code/permission-config.js +8 -2
  6. package/dist/application/agent/providers/claude-code/permission-config.js.map +1 -1
  7. package/dist/application/agent-tools/dispatch.d.ts +12 -0
  8. package/dist/application/agent-tools/dispatch.d.ts.map +1 -0
  9. package/dist/application/agent-tools/dispatch.js +189 -0
  10. package/dist/application/agent-tools/dispatch.js.map +1 -0
  11. package/dist/application/agent-tools/mcp-server.d.ts +10 -0
  12. package/dist/application/agent-tools/mcp-server.d.ts.map +1 -0
  13. package/dist/application/agent-tools/mcp-server.js +100 -0
  14. package/dist/application/agent-tools/mcp-server.js.map +1 -0
  15. package/dist/application/bench/harness.d.ts +5 -0
  16. package/dist/application/bench/harness.d.ts.map +1 -0
  17. package/dist/application/bench/harness.js +82 -0
  18. package/dist/application/bench/harness.js.map +1 -0
  19. package/dist/application/dispatcher.d.ts.map +1 -1
  20. package/dist/application/dispatcher.js +24 -0
  21. package/dist/application/dispatcher.js.map +1 -1
  22. package/dist/application/rule-adapters/ast-grep.d.ts +3 -0
  23. package/dist/application/rule-adapters/ast-grep.d.ts.map +1 -0
  24. package/dist/application/rule-adapters/ast-grep.js +112 -0
  25. package/dist/application/rule-adapters/ast-grep.js.map +1 -0
  26. package/dist/application/rule-adapters/index.d.ts +3 -0
  27. package/dist/application/rule-adapters/index.d.ts.map +1 -0
  28. package/dist/application/rule-adapters/index.js +15 -0
  29. package/dist/application/rule-adapters/index.js.map +1 -0
  30. package/dist/application/rule-adapters/linter.d.ts +31 -0
  31. package/dist/application/rule-adapters/linter.d.ts.map +1 -0
  32. package/dist/application/rule-adapters/linter.js +242 -0
  33. package/dist/application/rule-adapters/linter.js.map +1 -0
  34. package/dist/application/rule-adapters/process.d.ts +10 -0
  35. package/dist/application/rule-adapters/process.d.ts.map +1 -0
  36. package/dist/application/rule-adapters/process.js +38 -0
  37. package/dist/application/rule-adapters/process.js.map +1 -0
  38. package/dist/application/version.d.ts +1 -1
  39. package/dist/application/version.d.ts.map +1 -1
  40. package/dist/application/version.js +7 -4
  41. package/dist/application/version.js.map +1 -1
  42. package/dist/commands/bench.d.ts +3 -0
  43. package/dist/commands/bench.d.ts.map +1 -0
  44. package/dist/commands/bench.js +75 -0
  45. package/dist/commands/bench.js.map +1 -0
  46. package/dist/commands/context.d.ts +3 -0
  47. package/dist/commands/context.d.ts.map +1 -0
  48. package/dist/commands/context.js +56 -0
  49. package/dist/commands/context.js.map +1 -0
  50. package/dist/commands/doctor.d.ts.map +1 -1
  51. package/dist/commands/doctor.js +38 -0
  52. package/dist/commands/doctor.js.map +1 -1
  53. package/dist/commands/feature.d.ts.map +1 -1
  54. package/dist/commands/feature.js +48 -6
  55. package/dist/commands/feature.js.map +1 -1
  56. package/dist/commands/index.d.ts +8 -0
  57. package/dist/commands/index.d.ts.map +1 -1
  58. package/dist/commands/index.js +8 -0
  59. package/dist/commands/index.js.map +1 -1
  60. package/dist/commands/install.d.ts.map +1 -1
  61. package/dist/commands/install.js +7 -4
  62. package/dist/commands/install.js.map +1 -1
  63. package/dist/commands/knowledge.d.ts +3 -0
  64. package/dist/commands/knowledge.d.ts.map +1 -0
  65. package/dist/commands/knowledge.js +59 -0
  66. package/dist/commands/knowledge.js.map +1 -0
  67. package/dist/commands/learning.d.ts +3 -0
  68. package/dist/commands/learning.d.ts.map +1 -0
  69. package/dist/commands/learning.js +126 -0
  70. package/dist/commands/learning.js.map +1 -0
  71. package/dist/commands/mcp.d.ts +3 -0
  72. package/dist/commands/mcp.d.ts.map +1 -0
  73. package/dist/commands/mcp.js +26 -0
  74. package/dist/commands/mcp.js.map +1 -0
  75. package/dist/commands/next.d.ts.map +1 -1
  76. package/dist/commands/next.js +3 -1
  77. package/dist/commands/next.js.map +1 -1
  78. package/dist/commands/onboard.d.ts +5 -0
  79. package/dist/commands/onboard.d.ts.map +1 -0
  80. package/dist/commands/onboard.js +137 -0
  81. package/dist/commands/onboard.js.map +1 -0
  82. package/dist/commands/routing.d.ts +3 -0
  83. package/dist/commands/routing.d.ts.map +1 -0
  84. package/dist/commands/routing.js +107 -0
  85. package/dist/commands/routing.js.map +1 -0
  86. package/dist/commands/rules-format.d.ts +4 -0
  87. package/dist/commands/rules-format.d.ts.map +1 -0
  88. package/dist/commands/rules-format.js +16 -0
  89. package/dist/commands/rules-format.js.map +1 -0
  90. package/dist/commands/rules.d.ts +3 -0
  91. package/dist/commands/rules.d.ts.map +1 -0
  92. package/dist/commands/rules.js +270 -0
  93. package/dist/commands/rules.js.map +1 -0
  94. package/dist/commands/verify.d.ts.map +1 -1
  95. package/dist/commands/verify.js +78 -6
  96. package/dist/commands/verify.js.map +1 -1
  97. package/package.json +11 -5
  98. package/src/application/agent/orchestrator.test.ts +39 -0
  99. package/src/application/agent/orchestrator.ts +6 -0
  100. package/src/application/agent/providers/claude-code/claude-code-smoke.test.ts +1 -1
  101. package/src/application/agent/providers/claude-code/permission-config.test.ts +4 -4
  102. package/src/application/agent/providers/claude-code/permission-config.ts +8 -2
  103. package/src/application/agent/providers/claude-code/provider.test.ts +2 -2
  104. package/src/application/agent-tools/dispatch.test.ts +160 -0
  105. package/src/application/agent-tools/dispatch.ts +227 -0
  106. package/src/application/agent-tools/mcp-server.test.ts +86 -0
  107. package/src/application/agent-tools/mcp-server.ts +126 -0
  108. package/src/application/bench/harness.ts +95 -0
  109. package/src/application/dispatcher.test.ts +4 -3
  110. package/src/application/dispatcher.ts +16 -0
  111. package/src/application/rule-adapters/adapters.test.ts +224 -0
  112. package/src/application/rule-adapters/ast-grep.ts +126 -0
  113. package/src/application/rule-adapters/index.ts +16 -0
  114. package/src/application/rule-adapters/linter-paths.test.ts +95 -0
  115. package/src/application/rule-adapters/linter.ts +263 -0
  116. package/src/application/rule-adapters/process.ts +48 -0
  117. package/src/application/version.ts +9 -4
  118. package/src/commands/bench.test.ts +136 -0
  119. package/src/commands/bench.ts +74 -0
  120. package/src/commands/context.test.ts +47 -0
  121. package/src/commands/context.ts +59 -0
  122. package/src/commands/doctor-isolation.test.ts +76 -0
  123. package/src/commands/doctor.test.ts +2 -1
  124. package/src/commands/doctor.ts +36 -0
  125. package/src/commands/evolve.test.ts +153 -0
  126. package/src/commands/feature.test.ts +36 -4
  127. package/src/commands/feature.ts +71 -8
  128. package/src/commands/index.ts +8 -0
  129. package/src/commands/install.ts +7 -4
  130. package/src/commands/journal.test.ts +150 -0
  131. package/src/commands/knowledge.test.ts +39 -0
  132. package/src/commands/knowledge.ts +63 -0
  133. package/src/commands/learning.test.ts +104 -0
  134. package/src/commands/learning.ts +134 -0
  135. package/src/commands/mcp.ts +30 -0
  136. package/src/commands/memory.test.ts +146 -0
  137. package/src/commands/next.ts +3 -1
  138. package/src/commands/onboard.test.ts +83 -0
  139. package/src/commands/onboard.ts +146 -0
  140. package/src/commands/optimize.test.ts +53 -0
  141. package/src/commands/refactor.test.ts +57 -0
  142. package/src/commands/routing.test.ts +64 -0
  143. package/src/commands/routing.ts +107 -0
  144. package/src/commands/rules-format.ts +22 -0
  145. package/src/commands/rules.test.ts +153 -0
  146. package/src/commands/rules.ts +286 -0
  147. package/src/commands/verify.test.ts +115 -0
  148. package/src/commands/verify.ts +95 -7
  149. package/src/commands/version.test.ts +9 -0
@@ -18,7 +18,7 @@
18
18
  // guess.
19
19
 
20
20
  import path from 'node:path';
21
- import { computeNextAction, listFeatureRunStates } from '@agentic-sdlc-kit/core';
21
+ import { computeNextAction, listFeatureRunStates, recordNextOffer } from '@agentic-sdlc-kit/core';
22
22
  import type { NextAction } from '@agentic-sdlc-kit/contracts';
23
23
  import type { Command, CommandContext, CommandResult } from './types.js';
24
24
 
@@ -69,6 +69,8 @@ export const nextCommand: Command = {
69
69
  const res = await computeNextAction({ projectRoot: root, featureId });
70
70
  if (!res.ok) return fail(ctx, res.error.message);
71
71
  const action = res.value;
72
+ // Trace only: a failed record must not block the protocol answer.
73
+ await recordNextOffer(root, action);
72
74
 
73
75
  if (isJson) {
74
76
  ctx.stdout(JSON.stringify(action, null, 2) + '\n');
@@ -0,0 +1,83 @@
1
+ // packages/cli/src/commands/onboard.test.ts
2
+ import { promises as fs } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
6
+ import { execFile } from 'node:child_process';
7
+ import { promisify } from 'node:util';
8
+ import { onboardCommand } from './onboard.js';
9
+
10
+ const execFileAsync = promisify(execFile);
11
+ import type { CommandContext } from './types.js';
12
+
13
+ function ctx(argv: string[], cwd: string): CommandContext & { out: string[]; err: string[] } {
14
+ const out: string[] = [];
15
+ const err: string[] = [];
16
+ return { argv, cwd, stdout: (s) => void out.push(s), stderr: (s) => void err.push(s), out, err };
17
+ }
18
+
19
+ let root: string;
20
+ beforeEach(async () => {
21
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'kit-cli-onboard-'));
22
+ await fs.writeFile(path.join(root, 'AGENTS.md'), '- Never commit secrets.\n');
23
+ });
24
+ afterEach(async () => {
25
+ await fs.rm(root, { recursive: true, force: true });
26
+ });
27
+
28
+ describe('kit onboard', () => {
29
+ it('without --dry-run refuses outside git and writes nothing', async () => {
30
+ const c = ctx([], root);
31
+ expect((await onboardCommand.run(c)).exitCode).toBe(1);
32
+ expect(c.err.join('')).toContain('git revision');
33
+ await expect(fs.access(path.join(root, '.ai-kit'))).rejects.toThrow();
34
+ });
35
+
36
+ it('without --dry-run inside git adds proposed rules and a baseline', async () => {
37
+ await execFileAsync('git', ['init', '-q'], { cwd: root });
38
+ await execFileAsync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', 'add', '-A'], { cwd: root });
39
+ await execFileAsync(
40
+ 'git',
41
+ ['-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-q', '--allow-empty', '-m', 'init'],
42
+ { cwd: root },
43
+ );
44
+ const c = ctx([], root);
45
+ expect((await onboardCommand.run(c)).exitCode).toBe(0);
46
+ const text = c.out.join('');
47
+ expect(text).toContain('proposed rules added');
48
+ expect(text).toContain('Rules written: ONB-AGENT-001');
49
+ const rule = await fs.readFile(path.join(root, '.ai-kit', 'constitution', 'rules', 'ONB-AGENT-001.yml'), 'utf8');
50
+ expect(rule).toContain('mode: off');
51
+ expect(rule).toContain('status: proposed');
52
+ await expect(fs.access(path.join(root, '.ai-kit', 'constitution', 'baseline.json'))).resolves.toBeUndefined();
53
+ });
54
+
55
+ it('--dry-run prints the report and states that nothing was written', async () => {
56
+ const c = ctx(['--dry-run'], root);
57
+ expect((await onboardCommand.run(c)).exitCode).toBe(0);
58
+ const text = c.out.join('');
59
+ expect(text).toContain('Onboarding dry run: nothing was written.');
60
+ expect(text).toContain('Never commit secrets.');
61
+ expect(text).toContain('Files written: 0');
62
+ });
63
+
64
+ it('--dry-run --json emits a report with filesWritten 0', async () => {
65
+ const c = ctx(['--dry-run', '--json'], root);
66
+ expect((await onboardCommand.run(c)).exitCode).toBe(0);
67
+ const parsed = JSON.parse(c.out.join(''));
68
+ expect(parsed.filesWritten).toBe(0);
69
+ expect(parsed.candidates[0].statement).toBe('Never commit secrets.');
70
+ });
71
+
72
+ it('leaves the repository unchanged', async () => {
73
+ const before = await fs.readdir(root);
74
+ await onboardCommand.run(ctx(['--dry-run'], root));
75
+ expect(await fs.readdir(root)).toEqual(before);
76
+ });
77
+
78
+ it('shows help', async () => {
79
+ const c = ctx(['--help'], root);
80
+ expect((await onboardCommand.run(c)).exitCode).toBe(0);
81
+ expect(c.out.join('')).toContain('Usage: kit onboard');
82
+ });
83
+ });
@@ -0,0 +1,146 @@
1
+ // packages/cli/src/commands/onboard.ts
2
+ //
3
+ // `kit onboard [path] [--dry-run] [--json]` (ADR-0023 §7).
4
+ // Reports the standards a repository already declares (--dry-run writes
5
+ // nothing). Without --dry-run it adds proposed rules under .ai-kit/constitution
6
+ // and records the baseline at the current git revision. It never overwrites.
7
+
8
+ import path from 'node:path';
9
+ import { runOnboardDryRun, writeOnboardProposals } from '@agentic-sdlc-kit/core';
10
+ import type { OnboardReport, OnboardWriteResult } from '@agentic-sdlc-kit/contracts';
11
+ import { constitutionAdapters } from '../application/rule-adapters/index.js';
12
+ import type { Command, CommandContext, CommandResult } from './types.js';
13
+
14
+ const HELP = `Usage: kit onboard [path] [--dry-run] [--json]
15
+
16
+ --dry-run Report the standards this repository already declares. Writes nothing.
17
+ (default) Add proposed rules to .ai-kit/constitution/rules and, if none exists,
18
+ write the baseline pinned to the current git revision. Existing
19
+ rules and baseline are never overwritten. Requires a git commit.
20
+ --json Emit the result as JSON.
21
+
22
+ Proposed rules are status "proposed" and mode "off": they affect nothing until
23
+ a person reviews them and changes their mode.
24
+ `;
25
+
26
+ function renderWriteResult(result: OnboardWriteResult): string {
27
+ const list = (ids: readonly string[]): string => (ids.length > 0 ? ids.join(', ') : 'none');
28
+ return [
29
+ 'Onboarding write: proposed rules added under .ai-kit/constitution/rules.',
30
+ `Revision: ${result.revision}`,
31
+ `Rules written: ${list(result.rulesWritten)}`,
32
+ `Already proposed: ${list(result.rulesAlreadyProposed)}`,
33
+ `Stale proposals: ${list(result.staleProposals)}`,
34
+ `Baseline: ${result.baseline.status} (${result.baseline.entries} accepted entr${result.baseline.entries === 1 ? 'y' : 'ies'})`,
35
+ '',
36
+ 'Review the proposed rules, then change their mode (shadow, advisory or blocking) to enforce them.',
37
+ '',
38
+ ].join('\n');
39
+ }
40
+
41
+ function list(values: readonly string[]): string {
42
+ return values.length > 0 ? values.join(', ') : 'none detected';
43
+ }
44
+
45
+ function renderSources(report: OnboardReport): string[] {
46
+ if (report.sources.length === 0) return [' none found'];
47
+ return report.sources.map((s) => {
48
+ const state = s.parsed ? 'parsed' : 'not parsed';
49
+ const note = s.note ? ` — ${s.note}` : '';
50
+ return ` ${s.kind.padEnd(18)} ${s.path.padEnd(30)} ${state}${note}`;
51
+ });
52
+ }
53
+
54
+ function renderCandidates(report: OnboardReport): string[] {
55
+ if (report.candidates.length === 0) return [' none'];
56
+ return report.candidates.map((c) => {
57
+ const at = c.source.line !== undefined ? `:${c.source.line}` : '';
58
+ return ` [${c.kind}] ${c.source.path}${at} ${c.statement}`;
59
+ });
60
+ }
61
+
62
+ function renderDecisions(report: OnboardReport): string[] {
63
+ if (report.decisions.length === 0) return [' none found'];
64
+ return report.decisions.map((d) => ` ${d.id} ${d.title} (${d.path})`);
65
+ }
66
+
67
+ function renderConflicts(report: OnboardReport): string[] {
68
+ if (report.conflicts.length === 0) return [' none'];
69
+ return report.conflicts.map((c) => ` [${c.kind}] ${c.paths.join(', ')} ${c.detail}`);
70
+ }
71
+
72
+ function renderMissingTools(report: OnboardReport): string[] {
73
+ if (report.missingTools.length === 0) return [' none'];
74
+ return report.missingTools.map((t) => ` ${t.tool} (named in ${t.declaredIn})`);
75
+ }
76
+
77
+ function renderNotes(report: OnboardReport): string[] {
78
+ return report.notes.map((n) => ` ${n.severity}: ${n.message}`);
79
+ }
80
+
81
+ export function renderOnboardReport(report: OnboardReport): string {
82
+ return [
83
+ 'Onboarding dry run: nothing was written.',
84
+ `Revision: ${report.revision ?? 'not a git repository'}`,
85
+ `Stacks: ${list(report.stacks)}`,
86
+ `Package managers: ${list(report.packageManagers)}`,
87
+ `Test frameworks: ${list(report.testFrameworks)}`,
88
+ `CI: ${report.hasCi ? 'yes' : 'no'}`,
89
+ '',
90
+ 'Declared sources:',
91
+ ...renderSources(report),
92
+ '',
93
+ `Candidate standards (proposed, not enforced): ${report.candidates.length}`,
94
+ ...renderCandidates(report),
95
+ '',
96
+ `Decision records: ${report.decisions.length}`,
97
+ ...renderDecisions(report),
98
+ '',
99
+ `Declaration conflicts: ${report.conflicts.length}`,
100
+ ...renderConflicts(report),
101
+ '',
102
+ 'Tools named in configuration but not installed (depends on this machine):',
103
+ ...renderMissingTools(report),
104
+ '',
105
+ 'Notes:',
106
+ ...(report.notes.length > 0 ? renderNotes(report) : [' none']),
107
+ '',
108
+ `Files written: ${report.filesWritten}`,
109
+ '',
110
+ ].join('\n');
111
+ }
112
+
113
+ async function runDryRun(ctx: CommandContext, target: string, json: boolean): Promise<CommandResult> {
114
+ const result = await runOnboardDryRun(target);
115
+ if (!result.ok) {
116
+ ctx.stderr(`kit onboard: ${result.error.message}\n`);
117
+ return { exitCode: 1, message: result.error.message };
118
+ }
119
+ ctx.stdout(json ? `${JSON.stringify(result.value, null, 2)}\n` : renderOnboardReport(result.value));
120
+ return { exitCode: 0 };
121
+ }
122
+
123
+ async function runWrite(ctx: CommandContext, target: string, json: boolean): Promise<CommandResult> {
124
+ const result = await writeOnboardProposals(target, { adapters: constitutionAdapters() });
125
+ if (!result.ok) {
126
+ ctx.stderr(`kit onboard: ${result.error.message}\n`);
127
+ return { exitCode: 1, message: result.error.message };
128
+ }
129
+ ctx.stdout(json ? `${JSON.stringify(result.value, null, 2)}\n` : renderWriteResult(result.value));
130
+ return { exitCode: 0 };
131
+ }
132
+
133
+ export const onboardCommand: Command = {
134
+ name: 'onboard',
135
+ summary: 'Report declared standards (--dry-run) or add proposed rules and a baseline.',
136
+ async run(ctx: CommandContext): Promise<CommandResult> {
137
+ if (ctx.argv.includes('--help') || ctx.argv.includes('-h')) {
138
+ ctx.stdout(HELP);
139
+ return { exitCode: 0 };
140
+ }
141
+ const target = path.resolve(ctx.cwd, ctx.argv.find((a) => !a.startsWith('-')) ?? '.');
142
+ const json = ctx.argv.includes('--json');
143
+ if (ctx.argv.includes('--dry-run')) return runDryRun(ctx, target, json);
144
+ return runWrite(ctx, target, json);
145
+ },
146
+ };
@@ -0,0 +1,53 @@
1
+ // packages/cli/src/commands/optimize.test.ts
2
+ //
3
+ // CLI-layer tests for `kit optimize`: the informational surface of the
4
+ // M9 optimization workflow — exit code, baseline invariant, and the
5
+ // guidance content the host workflow expects.
6
+ import { describe, expect, it } from 'vitest';
7
+ import { optimizeCommand } from './optimize.js';
8
+ import type { CommandContext } from './types.js';
9
+
10
+ const makeCtx = (argv: string[], cwd = '/'): CommandContext & { out: string[]; err: string[] } => {
11
+ const out: string[] = [];
12
+ const err: string[] = [];
13
+ return {
14
+ argv,
15
+ cwd,
16
+ stdout: (s) => void out.push(s),
17
+ stderr: (s) => void err.push(s),
18
+ out,
19
+ err,
20
+ };
21
+ };
22
+
23
+ describe('kit optimize', () => {
24
+ it('exits 0 and prints the workflow guidance', () => {
25
+ const ctx = makeCtx([]);
26
+ const result = optimizeCommand.run(ctx);
27
+ expect(result.exitCode).toBe(0);
28
+ const text = ctx.out.join('');
29
+ expect(text).toContain('kit optimize — Performance optimization workflow');
30
+ expect(text).toContain('Expected lifecycle:');
31
+ expect(text).toContain('baseline');
32
+ });
33
+
34
+ it('states the baseline measurement invariant', () => {
35
+ const ctx = makeCtx([]);
36
+ optimizeCommand.run(ctx);
37
+ const text = ctx.out.join('');
38
+ expect(text).toContain('performance optimization requires baseline');
39
+ expect(text).toContain('without an established baseline');
40
+ });
41
+
42
+ it('declares its release status honestly', () => {
43
+ const ctx = makeCtx([]);
44
+ optimizeCommand.run(ctx);
45
+ expect(ctx.out.join('')).toContain('Status: declared in 0.6.0');
46
+ });
47
+
48
+ it('never writes to stderr', () => {
49
+ const ctx = makeCtx([]);
50
+ optimizeCommand.run(ctx);
51
+ expect(ctx.err.join('')).toBe('');
52
+ });
53
+ });
@@ -0,0 +1,57 @@
1
+ // packages/cli/src/commands/refactor.test.ts
2
+ //
3
+ // CLI-layer tests for `kit refactor`: the informational surface of the
4
+ // M9 refactoring workflow — exit code, lifecycle description, and the
5
+ // behavioral-preservation constraints.
6
+ import { describe, expect, it } from 'vitest';
7
+ import { refactorCommand } from './refactor.js';
8
+ import type { CommandContext } from './types.js';
9
+
10
+ const makeCtx = (argv: string[], cwd = '/'): CommandContext & { out: string[]; err: string[] } => {
11
+ const out: string[] = [];
12
+ const err: string[] = [];
13
+ return {
14
+ argv,
15
+ cwd,
16
+ stdout: (s) => void out.push(s),
17
+ stderr: (s) => void err.push(s),
18
+ out,
19
+ err,
20
+ };
21
+ };
22
+
23
+ describe('kit refactor', () => {
24
+ it('exits 0 and prints the workflow guidance', () => {
25
+ const ctx = makeCtx([]);
26
+ const result = refactorCommand.run(ctx);
27
+ expect(result.exitCode).toBe(0);
28
+ const text = ctx.out.join('');
29
+ expect(text).toContain('kit refactor — Refactoring workflow');
30
+ expect(text).toContain('driven by your AI assistant');
31
+ expect(text).toContain('/kit:refactor <target module and goal>');
32
+ });
33
+
34
+ it('lists the M9 lifecycle stages', () => {
35
+ const ctx = makeCtx([]);
36
+ refactorCommand.run(ctx);
37
+ const text = ctx.out.join('');
38
+ expect(text).toContain('characterization-tests');
39
+ expect(text).toContain('incremental-refactor');
40
+ expect(text).toContain('regression-testing');
41
+ });
42
+
43
+ it('states the behavior-preservation constraints', () => {
44
+ const ctx = makeCtx([]);
45
+ refactorCommand.run(ctx);
46
+ const text = ctx.out.join('');
47
+ expect(text).toContain('Preserve observable behavior');
48
+ expect(text).toContain('Establish baseline tests before structural changes');
49
+ expect(text).toContain('Do not use a design pattern simply because it exists');
50
+ });
51
+
52
+ it('never writes to stderr', () => {
53
+ const ctx = makeCtx([]);
54
+ refactorCommand.run(ctx);
55
+ expect(ctx.err.join('')).toBe('');
56
+ });
57
+ });
@@ -0,0 +1,64 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
5
+ import { routingCommand } from './routing.js';
6
+ import type { CommandContext } from './types.js';
7
+
8
+ function ctx(argv: string[], cwd: string): CommandContext & { out: string[]; err: string[] } {
9
+ const out: string[] = [];
10
+ const err: string[] = [];
11
+ return { argv, cwd, stdout: (s) => void out.push(s), stderr: (s) => void err.push(s), out, err };
12
+ }
13
+
14
+ const observation = (i: number, verdict: 'passed' | 'failed') => ({
15
+ schemaVersion: 1,
16
+ id: `obs-${i}`,
17
+ occurredAt: '2026-11-28T10:00:00.000Z',
18
+ taskType: 'feature',
19
+ model: 'model-a',
20
+ effort: 'low',
21
+ verdict,
22
+ tokensIn: 100,
23
+ tokensOut: 50,
24
+ costUnits: 1,
25
+ latencyMs: 900,
26
+ });
27
+
28
+ let root: string;
29
+ beforeEach(async () => {
30
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'kit-cli-routing-'));
31
+ });
32
+ afterEach(async () => {
33
+ await fs.rm(root, { recursive: true, force: true });
34
+ });
35
+
36
+ describe('kit routing', () => {
37
+ it('refuses an observation with free text and records nothing', async () => {
38
+ const file = path.join(root, 'bad.json');
39
+ await fs.writeFile(file, JSON.stringify({ ...observation(1, 'passed'), prompt: 'secret' }));
40
+ const c = ctx(['observe', '--file', file], root);
41
+ expect((await routingCommand.run(c)).exitCode).toBe(1);
42
+ expect(c.err.join('')).toContain('no free text');
43
+ });
44
+
45
+ it('table marks sparse cells and eligible ones, read-only', async () => {
46
+ const file = path.join(root, 'o.json');
47
+ for (let i = 0; i < 3; i += 1) {
48
+ await fs.writeFile(file, JSON.stringify(observation(i, 'passed')));
49
+ expect((await routingCommand.run(ctx(['observe', '--file', file], root))).exitCode).toBe(0);
50
+ }
51
+ const t = ctx(['table', '--min-samples', '3'], root);
52
+ await routingCommand.run(t);
53
+ expect(t.out.join('')).toContain('eligible');
54
+ const sparse = ctx(['table', '--min-samples', '10'], root);
55
+ await routingCommand.run(sparse);
56
+ expect(sparse.out.join('')).toContain('sparse (<10)');
57
+ });
58
+
59
+ it('an empty table says so', async () => {
60
+ const c = ctx(['table'], root);
61
+ await routingCommand.run(c);
62
+ expect(c.out.join('')).toContain('No routing observations yet');
63
+ });
64
+ });
@@ -0,0 +1,107 @@
1
+ // packages/cli/src/commands/routing.ts
2
+ //
3
+ // `kit routing observe --file <obs.json>` and `kit routing table [--task T] [--min-samples N]`
4
+ // (roadmap Phase 7, #48). Observations are validated and appended under the gitignored state
5
+ // directory. The table is read-only: it shows every cell, and marks the ones that clear the minimum
6
+ // sample as eligible. Nothing here changes which model runs.
7
+
8
+ import { promises as fs } from 'node:fs';
9
+ import path from 'node:path';
10
+ import { aggregateObservations, DEFAULT_MIN_SAMPLES, kitStateRoot } from '@agentic-sdlc-kit/core';
11
+ import { MeasuredRoutingObservationSchema, type MeasuredRoutingObservation } from '@agentic-sdlc-kit/contracts';
12
+ import type { Command, CommandContext, CommandResult } from './types.js';
13
+
14
+ const HELP = `Usage: kit routing <observe|table>
15
+
16
+ observe --file <obs.json> Validate and append one routing observation.
17
+ table [--task T] [--min-samples N] [--json] Show observed cells. Read-only: routing changes nothing.
18
+ `;
19
+
20
+ function flag(argv: readonly string[], name: string): string | undefined {
21
+ const i = argv.indexOf(name);
22
+ return i >= 0 ? argv[i + 1] : undefined;
23
+ }
24
+
25
+ function storeFile(root: string): string {
26
+ return path.join(kitStateRoot(root), 'state', 'routing', 'observations.jsonl');
27
+ }
28
+
29
+ async function readAll(root: string): Promise<{ ok: true; value: MeasuredRoutingObservation[] } | { ok: false; error: string }> {
30
+ let text: string;
31
+ try {
32
+ text = await fs.readFile(storeFile(root), 'utf8');
33
+ } catch (cause) {
34
+ if ((cause as { code?: string }).code === 'ENOENT') return { ok: true, value: [] };
35
+ return { ok: false, error: `cannot read routing observations: ${cause instanceof Error ? cause.message : String(cause)}` };
36
+ }
37
+ const out: MeasuredRoutingObservation[] = [];
38
+ const lines = text.split('\n');
39
+ for (let i = 0; i < lines.length; i += 1) {
40
+ const line = lines[i] ?? '';
41
+ if (line.trim() === '') continue;
42
+ const parsed = MeasuredRoutingObservationSchema.safeParse(JSON.parse(line));
43
+ if (!parsed.success) return { ok: false, error: `routing observation line ${i + 1} failed validation` };
44
+ out.push(parsed.data);
45
+ }
46
+ return { ok: true, value: out };
47
+ }
48
+
49
+ async function observe(ctx: CommandContext, root: string): Promise<CommandResult> {
50
+ const file = flag(ctx.argv, '--file');
51
+ if (file === undefined) return fail(ctx, 'observe needs --file <obs.json>', 2);
52
+ let input: unknown;
53
+ try {
54
+ input = JSON.parse(await fs.readFile(path.resolve(ctx.cwd, file), 'utf8'));
55
+ } catch (cause) {
56
+ return fail(ctx, `cannot read ${file} as JSON: ${cause instanceof Error ? cause.message : String(cause)}`);
57
+ }
58
+ const parsed = MeasuredRoutingObservationSchema.safeParse(input);
59
+ if (!parsed.success) return fail(ctx, 'observation failed validation (no free text is accepted)');
60
+ await fs.mkdir(path.dirname(storeFile(root)), { recursive: true });
61
+ await fs.appendFile(storeFile(root), `${JSON.stringify(parsed.data)}\n`, 'utf8');
62
+ ctx.stdout(`recorded ${parsed.data.id}\n`);
63
+ return { exitCode: 0 };
64
+ }
65
+
66
+ async function table(ctx: CommandContext, root: string): Promise<CommandResult> {
67
+ const read = await readAll(root);
68
+ if (!read.ok) return fail(ctx, read.error);
69
+ const minSamples = Number(flag(ctx.argv, '--min-samples') ?? DEFAULT_MIN_SAMPLES);
70
+ const task = flag(ctx.argv, '--task');
71
+ const cells = aggregateObservations(read.value).filter((c) => task === undefined || c.taskType === task);
72
+ const rows = cells.map((c) => ({ ...c, eligible: c.n >= minSamples }));
73
+ if (ctx.argv.includes('--json')) {
74
+ ctx.stdout(`${JSON.stringify({ minSamples, cells: rows }, null, 2)}\n`);
75
+ return { exitCode: 0 };
76
+ }
77
+ if (rows.length === 0) ctx.stdout('No routing observations yet.\n');
78
+ for (const c of rows) {
79
+ const rate = `${(c.successRate * 100).toFixed(1)}%`;
80
+ const interval = `${(c.interval95.low * 100).toFixed(1)}%–${(c.interval95.high * 100).toFixed(1)}%`;
81
+ ctx.stdout(
82
+ `${c.taskType.padEnd(9)} ${c.model.padEnd(22)} ${c.effort.padEnd(7)} n=${String(c.n).padEnd(4)} success ${rate} (95% ${interval}) cost ${c.medianCostUnits} ${c.eligible ? 'eligible' : `sparse (<${minSamples})`}\n`,
83
+ );
84
+ }
85
+ return { exitCode: 0 };
86
+ }
87
+
88
+ function fail(ctx: CommandContext, message: string, exitCode = 1): CommandResult {
89
+ ctx.stderr(`kit routing: ${message}\n`);
90
+ return { exitCode, message };
91
+ }
92
+
93
+ export const routingCommand: Command = {
94
+ name: 'routing',
95
+ summary: 'Record model-routing observations and show the measured table (roadmap Phase 7).',
96
+ async run(ctx: CommandContext): Promise<CommandResult> {
97
+ const sub = ctx.argv.find((a) => !a.startsWith('-'));
98
+ if (ctx.argv.includes('--help') || ctx.argv.includes('-h') || sub === undefined) {
99
+ ctx.stdout(HELP);
100
+ return { exitCode: sub === undefined && !ctx.argv.includes('--help') ? 2 : 0 };
101
+ }
102
+ const root = path.resolve(ctx.cwd);
103
+ if (sub === 'observe') return observe(ctx, root);
104
+ if (sub === 'table') return table(ctx, root);
105
+ return fail(ctx, `unknown subcommand "${sub}"\n${HELP}`, 2);
106
+ },
107
+ };
@@ -0,0 +1,22 @@
1
+ // packages/cli/src/commands/rules-format.ts
2
+ //
3
+ // Human-readable lines for rule results (ADR-0023). Shared by `kit verify`
4
+ // and `kit rules` so both report the same facts the same way.
5
+
6
+ import type { RuleResult } from '@agentic-sdlc-kit/contracts';
7
+
8
+ export function formatRuleResultLine(result: RuleResult): string {
9
+ const head = ` - ${result.ruleId.padEnd(28)} ${result.mode.padEnd(9)} ${result.outcome.toUpperCase()}`;
10
+ const counts =
11
+ result.violations.length > 0 || result.baselined > 0
12
+ ? ` (${result.violations.length} new, ${result.baselined} baselined)`
13
+ : '';
14
+ const detail = result.detail ? ` — ${result.detail}` : '';
15
+ return `${head}${counts}${detail}`;
16
+ }
17
+
18
+ export function formatViolationLines(result: RuleResult): string[] {
19
+ return result.violations.map(
20
+ (v) => ` ${v.path}:${v.line ?? '?'} ${v.message}`,
21
+ );
22
+ }