@agentic-sdlc-kit/cli 0.9.1 → 1.0.1

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 (144) 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/feature.test.ts +36 -4
  126. package/src/commands/feature.ts +71 -8
  127. package/src/commands/index.ts +8 -0
  128. package/src/commands/install.ts +7 -4
  129. package/src/commands/knowledge.test.ts +39 -0
  130. package/src/commands/knowledge.ts +63 -0
  131. package/src/commands/learning.test.ts +104 -0
  132. package/src/commands/learning.ts +134 -0
  133. package/src/commands/mcp.ts +30 -0
  134. package/src/commands/next.ts +3 -1
  135. package/src/commands/onboard.test.ts +83 -0
  136. package/src/commands/onboard.ts +146 -0
  137. package/src/commands/routing.test.ts +64 -0
  138. package/src/commands/routing.ts +107 -0
  139. package/src/commands/rules-format.ts +22 -0
  140. package/src/commands/rules.test.ts +153 -0
  141. package/src/commands/rules.ts +286 -0
  142. package/src/commands/verify.test.ts +115 -0
  143. package/src/commands/verify.ts +95 -7
  144. package/src/commands/version.test.ts +9 -0
@@ -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
+ }
@@ -0,0 +1,153 @@
1
+ // packages/cli/src/commands/rules.test.ts
2
+ import { execFile } from 'node:child_process';
3
+ import { promises as fs } from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
8
+ import { rulesCommand } from './rules.js';
9
+ import type { CommandContext } from './types.js';
10
+
11
+ const run = promisify(execFile);
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
+ // A rule over a single file, and a source file that breaks it.
20
+ const RULE = `schemaVersion: 1
21
+ id: ARCH-CORE-001
22
+ title: t
23
+ statement: s
24
+ rationale: r
25
+ scope:
26
+ paths:
27
+ - "packages/core/src/**/*.ts"
28
+ status: active
29
+ mode: blocking
30
+ check:
31
+ kind: import-boundary
32
+ from: "@agentic-sdlc-kit/"
33
+ allow:
34
+ - "@agentic-sdlc-kit/contracts"
35
+ source: declared
36
+ confidence: 1
37
+ owner: architecture
38
+ `;
39
+ const BAD_SOURCE = await fs.readFile(
40
+ new URL('../../../core/src/constitution/fixtures/core-imports-cli.txt', import.meta.url),
41
+ 'utf8',
42
+ );
43
+
44
+ let root: string;
45
+ beforeEach(async () => {
46
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'kit-cli-rules-'));
47
+ await fs.mkdir(path.join(root, '.ai-kit', 'constitution', 'rules'), { recursive: true });
48
+ await fs.writeFile(path.join(root, '.ai-kit', 'constitution', 'rules', 'ARCH-CORE-001.yml'), RULE);
49
+ await fs.mkdir(path.join(root, 'packages', 'core', 'src'), { recursive: true });
50
+ await fs.writeFile(path.join(root, 'packages', 'core', 'src', 'a.ts'), BAD_SOURCE);
51
+ });
52
+ afterEach(async () => {
53
+ await fs.rm(root, { recursive: true, force: true });
54
+ });
55
+
56
+ describe('kit rules', () => {
57
+ it('prints help and exits 2 with no subcommand', async () => {
58
+ const c = ctx([], root);
59
+ expect((await rulesCommand.run(c)).exitCode).toBe(2);
60
+ expect(c.out.join('')).toContain('Usage: kit rules');
61
+ });
62
+
63
+ it('list shows loaded rules', async () => {
64
+ const c = ctx(['list'], root);
65
+ expect((await rulesCommand.run(c)).exitCode).toBe(0);
66
+ expect(c.out.join('')).toContain('ARCH-CORE-001');
67
+ });
68
+
69
+ it('evaluate exits 1 and names the file and line when the gate fails', async () => {
70
+ const c = ctx(['evaluate'], root);
71
+ expect((await rulesCommand.run(c)).exitCode).toBe(1);
72
+ const text = c.out.join('');
73
+ expect(text).toContain('Gate: FAILED');
74
+ expect(text).toContain('packages/core/src/a.ts:1');
75
+ });
76
+
77
+ it('evaluate --json emits the evaluation', async () => {
78
+ const c = ctx(['evaluate', '--json'], root);
79
+ await rulesCommand.run(c);
80
+ expect(JSON.parse(c.out.join('')).gate).toBe('failed');
81
+ });
82
+
83
+ it('resolve lists rules applying to the given files', async () => {
84
+ const c = ctx(['resolve', '--files', 'packages/core/src/a.ts'], root);
85
+ expect((await rulesCommand.run(c)).exitCode).toBe(0);
86
+ expect(c.out.join('')).toContain('ARCH-CORE-001: 1 file(s)');
87
+ });
88
+
89
+ it('baseline without --accept previews and writes nothing', async () => {
90
+ const c = ctx(['baseline'], root);
91
+ expect((await rulesCommand.run(c)).exitCode).toBe(0);
92
+ expect(c.out.join('')).toContain('Baseline diff: 1 added, 0 removed, 0 changed');
93
+ await expect(fs.access(path.join(root, '.ai-kit', 'constitution', 'baseline.json'))).rejects.toThrow();
94
+ });
95
+
96
+ it('baseline --accept refuses without a git revision', async () => {
97
+ const c = ctx(['baseline', '--accept'], root);
98
+ expect((await rulesCommand.run(c)).exitCode).toBe(1);
99
+ expect(c.err.join('')).toContain('git revision is required');
100
+ });
101
+
102
+ it('baseline --accept writes the baseline at the current git revision, and evaluate then passes', async () => {
103
+ const git = (args: string[]) => run('git', args, { cwd: root });
104
+ await git(['init', '-q']);
105
+ await git(['-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-q', '--allow-empty', '-m', 'init']);
106
+
107
+ const accept = ctx(['baseline', '--accept'], root);
108
+ expect((await rulesCommand.run(accept)).exitCode).toBe(0);
109
+ const written = JSON.parse(
110
+ await fs.readFile(path.join(root, '.ai-kit', 'constitution', 'baseline.json'), 'utf8'),
111
+ );
112
+ expect(written.revision).toMatch(/^[0-9a-f]{40}$/);
113
+ expect(written.entries).toHaveLength(1);
114
+
115
+ const evaluate = ctx(['evaluate'], root);
116
+ expect((await rulesCommand.run(evaluate)).exitCode).toBe(0);
117
+ expect(evaluate.out.join('')).toContain('1 baselined');
118
+ });
119
+
120
+ it('rejects an unknown subcommand with exit 2', async () => {
121
+ expect((await rulesCommand.run(ctx(['frobnicate'], root))).exitCode).toBe(2);
122
+ });
123
+
124
+ it('explain prints the rule and its applicability', async () => {
125
+ const c = ctx(['explain', 'ARCH-CORE-001'], root);
126
+ expect((await rulesCommand.run(c)).exitCode).toBe(0);
127
+ const text = c.out.join('');
128
+ expect(text).toContain('ARCH-CORE-001 active blocking import-boundary');
129
+ expect(text).toContain('applies to: 1 file(s)');
130
+ expect(text).toContain('introduced: none (no committed history)');
131
+ });
132
+
133
+ it('explain --json emits a contract-valid explanation', async () => {
134
+ const c = ctx(['explain', 'ARCH-CORE-001', '--json'], root);
135
+ expect((await rulesCommand.run(c)).exitCode).toBe(0);
136
+ const parsed = JSON.parse(c.out.join(''));
137
+ expect(parsed.ruleId).toBe('ARCH-CORE-001');
138
+ expect(parsed.matchedFiles).toBe(1);
139
+ });
140
+
141
+ it('explain without an id is a usage error (exit 2)', async () => {
142
+ expect((await rulesCommand.run(ctx(['explain'], root))).exitCode).toBe(2);
143
+ });
144
+
145
+ it('baseline --json emits a contract-valid diff and writes nothing without --accept', async () => {
146
+ const c = ctx(['baseline', '--json'], root);
147
+ expect((await rulesCommand.run(c)).exitCode).toBe(0);
148
+ const parsed = JSON.parse(c.out.join(''));
149
+ expect(parsed.added).toHaveLength(1);
150
+ expect(parsed.accepted).toBe(false);
151
+ await expect(fs.access(path.join(root, '.ai-kit', 'constitution', 'baseline.json'))).rejects.toThrow();
152
+ });
153
+ });
@@ -0,0 +1,286 @@
1
+ // packages/cli/src/commands/rules.ts
2
+ //
3
+ // `kit rules list|resolve|evaluate|baseline [--json]` (ADR-0023 M1).
4
+ //
5
+ // list Loaded rules, status and mode.
6
+ // resolve [--files a,b] Rules that apply to the files (default: all).
7
+ // [--stack s,t] Stacks (default: from .ai-kit/project.yml).
8
+ // evaluate Evaluate every applicable rule. Exit 1 on a
9
+ // failed or blocked gate.
10
+ // baseline [--accept] Preview the violations a baseline would accept.
11
+ // Writes .ai-kit/constitution/baseline.json only
12
+ // with --accept, at the current git revision.
13
+
14
+ import path from 'node:path';
15
+ import { execFile } from 'node:child_process';
16
+ import { promisify } from 'node:util';
17
+ import {
18
+ diffBaseline,
19
+ evaluateConstitution,
20
+ draftBaselineEntries,
21
+ explainRule,
22
+ listRepoFiles,
23
+ loadBaseline,
24
+ loadRules,
25
+ profileStacks,
26
+ resolveRules,
27
+ writeBaseline,
28
+ type ConstitutionEvaluation,
29
+ } from '@agentic-sdlc-kit/core';
30
+ import {
31
+ BaselineDiffSchema,
32
+ RuleExplanationSchema,
33
+ type Baseline,
34
+ type BaselineDiff,
35
+ type Result,
36
+ type RuleExplanation,
37
+ } from '@agentic-sdlc-kit/contracts';
38
+ import type { Command, CommandContext, CommandResult } from './types.js';
39
+ import { formatRuleResultLine, formatViolationLines } from './rules-format.js';
40
+ import { constitutionAdapters } from '../application/rule-adapters/index.js';
41
+
42
+ const execFileAsync = promisify(execFile);
43
+
44
+ function flagValue(argv: readonly string[], name: string): string | undefined {
45
+ const i = argv.indexOf(name);
46
+ return i >= 0 ? argv[i + 1] : undefined;
47
+ }
48
+
49
+ function csv(value: string | undefined): string[] | undefined {
50
+ return value === undefined ? undefined : value.split(',').map((s) => s.trim()).filter(Boolean);
51
+ }
52
+
53
+ async function allRepoFiles(root: string): Promise<readonly string[] | null> {
54
+ const listed = await listRepoFiles(root);
55
+ return listed.ok ? listed.value : null;
56
+ }
57
+
58
+ async function gitHead(root: string): Promise<Result<string>> {
59
+ try {
60
+ const { stdout } = await execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: root });
61
+ const sha = stdout.trim();
62
+ if (!/^[0-9a-f]{40}$/.test(sha)) throw new Error(`unexpected HEAD: ${sha}`);
63
+ return { ok: true, value: sha };
64
+ } catch (cause) {
65
+ return {
66
+ ok: false,
67
+ error: { code: 'INTERNAL', message: 'a git revision is required to write a baseline (git rev-parse HEAD failed)', cause },
68
+ };
69
+ }
70
+ }
71
+
72
+ function fail(ctx: CommandContext, message: string, exitCode = 1): CommandResult {
73
+ ctx.stderr(`kit rules: ${message}\n`);
74
+ return { exitCode, message };
75
+ }
76
+
77
+ async function runList(ctx: CommandContext, root: string): Promise<CommandResult> {
78
+ const loaded = await loadRules(root);
79
+ if (!loaded.ok) return fail(ctx, loaded.error.message);
80
+ if (!loaded.value.rulesDirPresent) {
81
+ ctx.stdout('No constitution found at .ai-kit/constitution/rules.\n');
82
+ return { exitCode: 0 };
83
+ }
84
+ const rules = loaded.value.rules.map((l) => l.rule);
85
+ if (ctx.argv.includes('--json')) {
86
+ ctx.stdout(`${JSON.stringify(rules, null, 2)}\n`);
87
+ } else {
88
+ for (const r of rules) ctx.stdout(`${r.id.padEnd(30)} ${r.status.padEnd(10)} ${r.mode.padEnd(9)} ${r.check.kind}\n`);
89
+ }
90
+ return { exitCode: 0 };
91
+ }
92
+
93
+ async function runResolve(ctx: CommandContext, root: string): Promise<CommandResult> {
94
+ const loaded = await loadRules(root);
95
+ if (!loaded.ok) return fail(ctx, loaded.error.message);
96
+ const explicitFiles = csv(flagValue(ctx.argv, '--files'));
97
+ const files: readonly string[] | null = explicitFiles ?? (await allRepoFiles(root));
98
+ if (files === null) return fail(ctx, 'cannot enumerate repository files');
99
+ const explicitStacks = csv(flagValue(ctx.argv, '--stack'));
100
+ const stacks: readonly string[] = explicitStacks ?? (await profileStacks(root));
101
+ const resolved = resolveRules(loaded.value.rules.map((l) => l.rule), { files, stacks });
102
+ if (!resolved.ok) return fail(ctx, resolved.error.message);
103
+ if (ctx.argv.includes('--json')) {
104
+ ctx.stdout(
105
+ `${JSON.stringify(resolved.value.map((r) => ({ ruleId: r.rule.id, matchedFiles: r.matchedFiles })), null, 2)}\n`,
106
+ );
107
+ } else {
108
+ for (const r of resolved.value) ctx.stdout(`${r.rule.id}: ${r.matchedFiles.length} file(s)\n`);
109
+ if (resolved.value.length === 0) ctx.stdout('No rules apply.\n');
110
+ }
111
+ return { exitCode: 0 };
112
+ }
113
+
114
+ function printEvaluation(ctx: CommandContext, evaluation: ConstitutionEvaluation, json: boolean): void {
115
+ if (json) {
116
+ ctx.stdout(`${JSON.stringify(evaluation, null, 2)}\n`);
117
+ return;
118
+ }
119
+ ctx.stdout(`Gate: ${evaluation.gate.toUpperCase()}\n`);
120
+ for (const r of evaluation.results) {
121
+ ctx.stdout(`${formatRuleResultLine(r)}\n`);
122
+ for (const line of formatViolationLines(r)) ctx.stdout(`${line}\n`);
123
+ }
124
+ if (evaluation.results.length === 0) ctx.stdout(' (no applicable rules)\n');
125
+ }
126
+
127
+ async function runEvaluate(ctx: CommandContext, root: string): Promise<CommandResult> {
128
+ const stacks = csv(flagValue(ctx.argv, '--stack')) ?? (await profileStacks(root));
129
+ const evaluation = await evaluateConstitution({ projectRoot: root, stacks, adapters: constitutionAdapters() });
130
+ if (!evaluation.ok) return fail(ctx, evaluation.error.message);
131
+ printEvaluation(ctx, evaluation.value, ctx.argv.includes('--json'));
132
+ return { exitCode: evaluation.value.gate === 'passed' ? 0 : 1 };
133
+ }
134
+
135
+ function diffLines(diff: Pick<BaselineDiff, 'added' | 'removed' | 'changed'>): string[] {
136
+ const entry = (e: { ruleId: string; path: string; count: number }): string =>
137
+ `${e.ruleId} ${e.path} x${e.count}`;
138
+ const lines: string[] = [];
139
+ if (diff.added.length > 0) {
140
+ lines.push('Added (loosens the gate; requires --accept):');
141
+ lines.push(...diff.added.map((e) => ` + ${entry(e)}`));
142
+ }
143
+ if (diff.removed.length > 0) {
144
+ lines.push('Removed (tightens the gate):');
145
+ lines.push(...diff.removed.map((e) => ` - ${entry(e)}`));
146
+ }
147
+ if (diff.changed.length > 0) {
148
+ lines.push('Changed:');
149
+ lines.push(...diff.changed.map((c) => ` ~ ${c.after.ruleId} ${c.after.path} x${c.before.count} -> x${c.after.count}`));
150
+ }
151
+ return lines;
152
+ }
153
+
154
+ async function runBaseline(ctx: CommandContext, root: string): Promise<CommandResult> {
155
+ const stacks = csv(flagValue(ctx.argv, '--stack')) ?? (await profileStacks(root));
156
+ const evaluation = await evaluateConstitution({ projectRoot: root, stacks, ignoreBaseline: true, adapters: constitutionAdapters() });
157
+ if (!evaluation.ok) return fail(ctx, evaluation.error.message);
158
+ const proposed = draftBaselineEntries(evaluation.value.results);
159
+ const current = await loadBaseline(root);
160
+ if (!current.ok) return fail(ctx, current.error.message);
161
+ const diff = diffBaseline(current.value.entries, proposed);
162
+ const changes = diff.added.length + diff.removed.length + diff.changed.length;
163
+ const accept = ctx.argv.includes('--accept') && changes > 0;
164
+ const unbaselinable = evaluation.value.results.filter((r) => r.outcome !== 'violations' && r.outcome !== 'passed');
165
+
166
+ if (ctx.argv.includes('--json')) {
167
+ const payload: BaselineDiff = BaselineDiffSchema.parse({
168
+ schemaVersion: 1,
169
+ added: diff.added,
170
+ removed: diff.removed,
171
+ changed: diff.changed,
172
+ accepted: false,
173
+ });
174
+ ctx.stdout(`${JSON.stringify({ ...payload, accepted: accept })}\n`);
175
+ }
176
+ if (!accept) {
177
+ if (!ctx.argv.includes('--json')) {
178
+ const header = changes === 0
179
+ ? 'Baseline already matches the current violations. Nothing to accept.'
180
+ : `Baseline diff: ${diff.added.length} added, ${diff.removed.length} removed, ${diff.changed.length} changed. Re-run with --accept to write it.`;
181
+ ctx.stdout(`${header}\n`);
182
+ for (const line of diffLines(diff)) ctx.stdout(`${line}\n`);
183
+ for (const r of unbaselinable) ctx.stdout(` cannot baseline: ${formatRuleResultLine(r).trim()}\n`);
184
+ }
185
+ return { exitCode: 0 };
186
+ }
187
+
188
+ const head = await gitHead(root);
189
+ if (!head.ok) return fail(ctx, head.error.message);
190
+ const baseline: Baseline = { schemaVersion: 1, capturedAt: new Date().toISOString(), revision: head.value, entries: proposed };
191
+ const written = await writeBaseline(root, baseline);
192
+ if (!written.ok) return fail(ctx, written.error.message);
193
+ if (!ctx.argv.includes('--json')) {
194
+ ctx.stdout(`Wrote ${proposed.length} entr${proposed.length === 1 ? 'y' : 'ies'} to ${path.relative(root, written.value)}\n`);
195
+ }
196
+ return { exitCode: 0 };
197
+ }
198
+
199
+ /** Non-flag arguments, skipping the value that follows --stack or --files. */
200
+ function positionalArgs(argv: readonly string[]): string[] {
201
+ const out: string[] = [];
202
+ for (let i = 0; i < argv.length; i += 1) {
203
+ const arg = argv[i] ?? '';
204
+ if (arg === '--stack' || arg === '--files') {
205
+ i += 1;
206
+ } else if (!arg.startsWith('-')) {
207
+ out.push(arg);
208
+ }
209
+ }
210
+ return out;
211
+ }
212
+
213
+ function explanationLines(e: RuleExplanation): string[] {
214
+ const commit = (c: { sha: string; author: string; date: string; subject: string } | null): string =>
215
+ c === null ? 'none (no committed history)' : `${c.sha.slice(0, 12)} ${c.date.slice(0, 10)} ${c.author}: ${c.subject}`;
216
+ const r = e.rule;
217
+ const scope = [`paths ${r.scope.paths.join(', ')}`];
218
+ if (r.scope.exclude.length > 0) scope.push(`exclude ${r.scope.exclude.join(', ')}`);
219
+ if (r.scope.stacks.length > 0) scope.push(`stacks ${r.scope.stacks.join(', ')}`);
220
+ return [
221
+ `${r.id} ${r.status} ${r.mode} ${r.check.kind}`,
222
+ ` title: ${r.title}`,
223
+ ` statement: ${r.statement}`,
224
+ ` rationale: ${r.rationale}`,
225
+ ` scope: ${scope.join('; ')}`,
226
+ ` owner: ${r.owner} source: ${r.source}`,
227
+ ...(r.origin ? [` origin: ${r.origin.path}${r.origin.line ? `:${r.origin.line}` : ''} (kit onboard)`] : []),
228
+ ` file: ${e.file}`,
229
+ ` introduced: ${commit(e.introducedIn)}`,
230
+ ` last change: ${commit(e.lastChangedIn)}`,
231
+ ` applies to: ${e.matchedFiles} file(s) in the repository`,
232
+ ];
233
+ }
234
+
235
+ async function runExplain(ctx: CommandContext, root: string): Promise<CommandResult> {
236
+ const id = positionalArgs(ctx.argv)[1];
237
+ if (id === undefined) return fail(ctx, 'usage: kit rules explain <RULE-ID> [--json]', 2);
238
+ const res = await explainRule(root, id);
239
+ if (!res.ok) return fail(ctx, res.error.message);
240
+ const payload = RuleExplanationSchema.parse(res.value);
241
+ if (ctx.argv.includes('--json')) {
242
+ ctx.stdout(`${JSON.stringify(payload, null, 2)}\n`);
243
+ } else {
244
+ for (const line of explanationLines(payload)) ctx.stdout(`${line}\n`);
245
+ }
246
+ return { exitCode: 0 };
247
+ }
248
+
249
+ const HELP = `Usage: kit rules <list|resolve|evaluate|baseline> [options]
250
+
251
+ list Show loaded engineering rules.
252
+ resolve [--files a,b] Show rules that apply to the files (default: all repo files).
253
+ [--stack s,t] Stacks (default: from .ai-kit/project.yml).
254
+ evaluate [--json] Evaluate applicable rules. Exit 1 when the gate fails or is blocked.
255
+ explain <RULE-ID> Show a rule, where it came from in git history, and what it applies to.
256
+ baseline [--accept] Show the baseline diff; --accept writes baseline.json (git revision required).
257
+
258
+ Rules live in .ai-kit/constitution/rules/*.yml (ADR-0023).
259
+ `;
260
+
261
+ export const rulesCommand: Command = {
262
+ name: 'rules',
263
+ summary: 'List, explain, resolve, evaluate, and baseline engineering rules (ADR-0023).',
264
+ async run(ctx: CommandContext): Promise<CommandResult> {
265
+ const sub = ctx.argv.find((a) => !a.startsWith('-'));
266
+ if (ctx.argv.includes('--help') || ctx.argv.includes('-h') || sub === undefined) {
267
+ ctx.stdout(HELP);
268
+ return { exitCode: sub === undefined && !ctx.argv.includes('--help') ? 2 : 0 };
269
+ }
270
+ const root = path.resolve(ctx.cwd);
271
+ switch (sub) {
272
+ case 'list':
273
+ return runList(ctx, root);
274
+ case 'resolve':
275
+ return runResolve(ctx, root);
276
+ case 'evaluate':
277
+ return runEvaluate(ctx, root);
278
+ case 'baseline':
279
+ return runBaseline(ctx, root);
280
+ case 'explain':
281
+ return runExplain(ctx, root);
282
+ default:
283
+ return fail(ctx, `unknown subcommand "${sub}"\n${HELP}`, 2);
284
+ }
285
+ },
286
+ };