@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
package/package.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
2
  "name": "@agentic-sdlc-kit/cli",
3
- "version": "0.9.1",
3
+ "version": "1.1.0",
4
4
  "description": "The `kit` executable: user-facing entry point for the Agentic SDLC Kit.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/shubhamtaywade82/agentic-sdlc-kit.git",
8
+ "directory": "packages/cli"
9
+ },
5
10
  "license": "MIT",
6
11
  "type": "module",
7
12
  "main": "./dist/index.js",
@@ -20,12 +25,13 @@
20
25
  "src"
21
26
  ],
22
27
  "dependencies": {
23
- "@agentic-sdlc-kit/contracts": "0.9.1",
24
- "@agentic-sdlc-kit/core": "0.9.1"
28
+ "@agentic-sdlc-kit/contracts": "1.1.0",
29
+ "@agentic-sdlc-kit/core": "1.1.0",
30
+ "@modelcontextprotocol/sdk": "^1.32.2"
25
31
  },
26
32
  "devDependencies": {
27
- "@agentic-sdlc-kit/testing": "0.9.1",
28
- "@types/node": "^20.14.0",
33
+ "@agentic-sdlc-kit/testing": "1.1.0",
34
+ "@types/node": "^26.6.11",
29
35
  "typescript": "^5.5.0",
30
36
  "vitest": "^2.0.0"
31
37
  },
@@ -339,3 +339,42 @@ describe('cancellation and resumable state', () => {
339
339
  if (!again.ok) expect(again.error.message).toContain('already completed');
340
340
  });
341
341
  });
342
+
343
+ describe('PR3: the next attempt is told why the gate rejected the last one (item 1)', () => {
344
+ // A check that fails to compile, not at an assertion: the Red gate rejects it.
345
+ const COMPILE_ERROR_CHECK = [
346
+ "console.error(\"src/TASK-001.ts:1:1 - error TS2304: Cannot find name 'missing'.\");",
347
+ 'process.exit(1);',
348
+ '',
349
+ ].join('\n');
350
+
351
+ it('carries the classified rejection into the next execution', async () => {
352
+ const fixture = await buildOrchestrationFixture();
353
+ const instructions: string[] = [];
354
+ const provider = new MockAgentProvider({
355
+ performWork: async (request) => {
356
+ instructions.push(request.instructions);
357
+ if (instructions.length === 1) {
358
+ await fs.writeFile(path.join(request.workspace.rootPath, 'check.js'), COMPILE_ERROR_CHECK);
359
+ }
360
+ },
361
+ });
362
+ const gateway = gatewayFor(fixture, provider);
363
+ const run = () =>
364
+ runFeatureOrchestration({
365
+ projectRoot: fixture.root,
366
+ featureId: fixture.featureId,
367
+ gateway,
368
+ providerId: 'mock',
369
+ });
370
+
371
+ await run();
372
+ await run();
373
+
374
+ expect(instructions).toHaveLength(2);
375
+ expect(instructions[0]).not.toMatch(/Previous attempt/);
376
+ expect(instructions[1]).toMatch(
377
+ /Previous attempt 1 of 3 was rejected by the evidence gate \(classification: compilation\)/,
378
+ );
379
+ }, 60_000);
380
+ });
@@ -41,11 +41,14 @@ import {
41
41
  type AgentExecutionRequest,
42
42
  type AgentPolicySnapshot,
43
43
  type ExecutionWorkspace,
44
+ type RecoveryHint,
44
45
  type Result,
45
46
  type VerificationReport,
46
47
  } from '@agentic-sdlc-kit/contracts';
47
48
  import {
49
+ assessRecovery,
48
50
  finalizeFeatureRun,
51
+ formatRecoveryInstruction,
49
52
  getFeatureRunState,
50
53
  kitStateRoot,
51
54
  loadPlan,
@@ -243,6 +246,7 @@ function buildInstructions(
243
246
  task: NonNullable<ReturnType<WorktreeContext['taskDefs']['get']>>,
244
247
  ctx: WorktreeContext,
245
248
  workspace: ExecutionWorkspace,
249
+ recovery: RecoveryHint | null,
246
250
  ): string {
247
251
  const command = task.verificationCommand.join(' ');
248
252
  const header =
@@ -257,6 +261,7 @@ function buildInstructions(
257
261
  : `The verification command MUST PASS.`;
258
262
  return [
259
263
  header,
264
+ ...(recovery !== null ? [formatRecoveryInstruction(recovery)] : []),
260
265
  `Task: ${task.description}`,
261
266
  `Acceptance criteria:\n${task.acceptanceCriteria.map((c) => `- ${c}`).join('\n')}`,
262
267
  task.likelyFiles.length > 0 ? `Likely files: ${task.likelyFiles.join(', ')}` : '',
@@ -464,6 +469,7 @@ export async function runFeatureOrchestration(
464
469
  taskDef,
465
470
  ctx,
466
471
  state.workspace,
472
+ assessRecovery(task).hint,
467
473
  ),
468
474
  context: {
469
475
  specificationRef: ctx.specPath,
@@ -111,7 +111,7 @@ describe.skipIf(!available)('claude-code real-provider smoke (acceptance: PR4)',
111
111
  const flat = args.join(' ');
112
112
  expect(flat).not.toContain('bypassPermissions');
113
113
  expect(flat).not.toContain('--dangerously-skip-permissions');
114
- expect(flat).toContain(`Write(${workspaceRoot}/**)`);
114
+ expect(flat).toContain(`Edit(${workspaceRoot}/**)`);
115
115
 
116
116
  const provider = new ClaudeCodeProvider({ projectRoot: projectRoot!, cliPath: CLAUDE_BIN });
117
117
  const handle = await provider.start(req, new AbortController().signal);
@@ -54,9 +54,9 @@ describe('deriveClaudeCodePermissionConfig (ADR-0020 §2 generated representatio
54
54
  const cfg = configFor(['repository.read', 'repository.write'], {
55
55
  writablePaths: ['/ws/run-001', '/ws/shared'],
56
56
  });
57
- expect(cfg.allowedTools).toContain('Write(/ws/run-001/**)');
57
+ expect(cfg.allowedTools).not.toContain('Write(/ws/run-001/**)');
58
58
  expect(cfg.allowedTools).toContain('Edit(/ws/run-001/**)');
59
- expect(cfg.allowedTools).toContain('Write(/ws/shared/**)');
59
+ expect(cfg.allowedTools).toContain('Edit(/ws/shared/**)');
60
60
  // NO unscoped file mutation: an absolute-scope rule per path only.
61
61
  expect(cfg.allowedTools).not.toContain('Write');
62
62
  expect(cfg.allowedTools).not.toContain('Edit');
@@ -162,9 +162,9 @@ describe('argv carries the generated representation, never a bypass', () => {
162
162
  expect(joined).toContain('-p');
163
163
  expect(joined).toContain('--output-format stream-json');
164
164
  expect(joined).toContain('--verbose');
165
- expect(joined).toContain('--permission-mode default');
165
+ expect(joined).toContain('--permission-mode acceptEdits');
166
166
  expect(joined).toContain('--allowedTools');
167
- expect(joined).toContain('Write(/ws/run-001/**)');
167
+ expect(joined).toContain('Edit(/ws/run-001/**)');
168
168
  expect(joined).toContain('Bash(pnpm test:*)');
169
169
  expect(joined).toContain('--max-turns 40');
170
170
  expect(joined).not.toContain('bypassPermissions');
@@ -102,6 +102,10 @@ const BASH_RULES: readonly BashRule[] = [
102
102
 
103
103
  /** Capabilities that map to non-Bash Claude Code tools. */
104
104
  const READ_TOOLS: readonly string[] = ['Read', 'Grep', 'Glob', 'LS'];
105
+ // Claude Code 2.1.x matches file permissions only through Edit(path) rules, and an Edit rule covers every
106
+ // file-editing tool. A Write(path) rule is ignored and reported as unmatched, so it is never emitted.
107
+ const EDIT_RULE_TOOLS: readonly string[] = ['Edit'];
108
+ /** Every tool that edits files: a call to any of them needs repository.write, whatever rule allowed it. */
105
109
  const WRITE_TOOLS: readonly string[] = ['Write', 'Edit', 'NotebookEdit'];
106
110
  const NETWORK_TOOLS: readonly string[] = ['WebFetch', 'WebSearch'];
107
111
 
@@ -138,7 +142,7 @@ export function deriveClaudeCodePermissionConfig(
138
142
 
139
143
  // repository.write -> file mutation tools, SCOPED to writablePaths
140
144
  if (has(granted, 'repository.write')) {
141
- for (const tool of WRITE_TOOLS) {
145
+ for (const tool of EDIT_RULE_TOOLS) {
142
146
  for (const target of permissions.writablePaths) {
143
147
  allowed.push(`${tool}(${target}/**)`);
144
148
  }
@@ -167,7 +171,9 @@ export function deriveClaudeCodePermissionConfig(
167
171
  // 'default': headless sessions cannot prompt, so anything outside the
168
172
  // allowlist is denied by Claude Code itself — which is exactly the
169
173
  // fail-closed behavior the policy wants. Never bypassPermissions.
170
- permissionMode: 'default',
174
+ // A non-interactive run refuses edits under `default` even with an Edit rule granted. `acceptEdits`
175
+ // lets the granted Edit rules decide, and those rules are already scoped to the writable paths.
176
+ permissionMode: granted.includes('repository.write') ? 'acceptEdits' : 'default',
171
177
  maxTurns: budget.maxToolCalls > 0 ? budget.maxToolCalls : undefined,
172
178
  };
173
179
  }
@@ -177,9 +177,9 @@ describe('ClaudeCodeProvider — happy path', () => {
177
177
  expect(captured?.argv[3]).toBe('stream-json');
178
178
  expect(captured?.argv).toContain('--verbose');
179
179
  expect(captured?.argv).toContain('--permission-mode');
180
- expect(captured?.argv).toContain('default');
180
+ expect(captured?.argv).toContain('acceptEdits');
181
181
  const flat = captured?.argv.join(' ') ?? '';
182
- expect(flat).toContain(`Write(${workspaceRoot}/**)`);
182
+ expect(flat).toContain(`Edit(${workspaceRoot}/**)`);
183
183
  expect(flat).toContain('Bash(pnpm test:*)');
184
184
  expect(captured?.argv).toContain('--max-turns');
185
185
  expect(captured?.argv).toContain('40');
@@ -0,0 +1,160 @@
1
+ // packages/cli/src/application/agent-tools/dispatch.test.ts
2
+ //
3
+ // The typed tool surface a host calls instead of shelling out (item 4). Every
4
+ // tool validates its input against a strict contract schema before it runs,
5
+ // returns a result rather than throwing, and never accepts a command: a phase
6
+ // runs the verification command the plan declares, nothing else.
7
+ import { promises as fs } from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { afterEach, describe, expect, it } from 'vitest';
11
+ import { AGENT_TOOL_NAMES } from '@agentic-sdlc-kit/contracts';
12
+ import { callAgentTool } from './dispatch.js';
13
+
14
+ const dirs: string[] = [];
15
+
16
+ async function emptyProject(): Promise<string> {
17
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'kit-agent-tools-'));
18
+ dirs.push(dir);
19
+ return dir;
20
+ }
21
+
22
+ afterEach(async () => {
23
+ for (const dir of dirs.splice(0)) await fs.rm(dir, { recursive: true, force: true });
24
+ });
25
+
26
+ describe('agent tool surface', () => {
27
+ it('exposes exactly the three protocol tools', () => {
28
+ expect([...AGENT_TOOL_NAMES]).toEqual([
29
+ 'kit_next',
30
+ 'kit_phase',
31
+ 'kit_status',
32
+ 'kit_rules_resolve',
33
+ 'kit_rules_evaluate',
34
+ 'kit_project_context',
35
+ 'kit_rules_explain',
36
+ 'kit_adr_search',
37
+ 'kit_patterns_search',
38
+ 'kit_verification_status',
39
+ 'kit_learning_record',
40
+ ]);
41
+ });
42
+
43
+ it('refuses an unknown tool name', async () => {
44
+ const root = await emptyProject();
45
+ const res = await callAgentTool('kit_shell', { command: 'rm -rf /' }, { projectRoot: root });
46
+ expect(res.ok).toBe(false);
47
+ });
48
+
49
+ it('refuses a phase request that smuggles in a command', async () => {
50
+ const root = await emptyProject();
51
+ const res = await callAgentTool(
52
+ 'kit_phase',
53
+ { featureId: 'FEATURE-001', taskId: 'TASK-001', phase: 'red', command: 'rm -rf /' },
54
+ { projectRoot: root },
55
+ );
56
+ expect(res.ok).toBe(false);
57
+ if (!res.ok) expect(res.error).toMatch(/command/);
58
+ });
59
+
60
+ it('refuses a phase outside red, green and refactor', async () => {
61
+ const root = await emptyProject();
62
+ const res = await callAgentTool(
63
+ 'kit_phase',
64
+ { featureId: 'FEATURE-001', taskId: 'TASK-001', phase: 'completed' },
65
+ { projectRoot: root },
66
+ );
67
+ expect(res.ok).toBe(false);
68
+ });
69
+
70
+ it('answers kit_next with the protocol action, and never throws on odd input', async () => {
71
+ const root = await emptyProject();
72
+ const next = await callAgentTool('kit_next', { featureId: 'FEATURE-001' }, { projectRoot: root });
73
+ expect(next.ok).toBe(true);
74
+ if (next.ok) expect(next.value).toMatchObject({ requiredAction: 'feature.start' });
75
+
76
+ for (const bad of [null, 'text', 42, []]) {
77
+ const res = await callAgentTool('kit_next', bad, { projectRoot: root });
78
+ expect(res.ok).toBe(false);
79
+ }
80
+ });
81
+
82
+ it('reports a missing run as a failed result, not an exception', async () => {
83
+ const root = await emptyProject();
84
+ const status = await callAgentTool('kit_status', { featureId: 'FEATURE-404' }, { projectRoot: root });
85
+ expect(status.ok).toBe(false);
86
+ const phase = await callAgentTool(
87
+ 'kit_phase',
88
+ { featureId: 'FEATURE-404', taskId: 'TASK-001', phase: 'red' },
89
+ { projectRoot: root },
90
+ );
91
+ expect(phase.ok).toBe(false);
92
+ });
93
+ });
94
+
95
+ describe('constitution tools (ADR-0023, read-only)', () => {
96
+ it('kit_rules_resolve rejects unknown keys (no commands in tool input)', async () => {
97
+ const res = await callAgentTool(
98
+ 'kit_rules_resolve',
99
+ { files: ['a.ts'], command: ['rm', '-rf', '/'] },
100
+ { projectRoot: '/nonexistent-kit-root' },
101
+ );
102
+ expect(res.ok).toBe(false);
103
+ });
104
+
105
+ it('kit_rules_resolve requires at least one file', async () => {
106
+ const res = await callAgentTool('kit_rules_resolve', { files: [] }, { projectRoot: '/nonexistent-kit-root' });
107
+ expect(res.ok).toBe(false);
108
+ });
109
+
110
+ it('kit_rules_evaluate reports an absent constitution as an explicit passing state', async () => {
111
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'kit-dispatch-rules-'));
112
+ try {
113
+ const res = await callAgentTool('kit_rules_evaluate', {}, { projectRoot: root });
114
+ expect(res).toEqual({
115
+ ok: true,
116
+ value: { rulesDirPresent: false, results: [], gate: 'passed' },
117
+ });
118
+ } finally {
119
+ await fs.rm(root, { recursive: true, force: true });
120
+ }
121
+ });
122
+ });
123
+
124
+ describe('context tools (read-only)', () => {
125
+ it('kit_adr_search finds decision records by title', async () => {
126
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'kit-dispatch-adr-'));
127
+ try {
128
+ await fs.mkdir(path.join(root, 'docs', 'adr'), { recursive: true });
129
+ await fs.writeFile(path.join(root, 'docs', 'adr', 'ADR-0007-use-postgres.md'), '# ADR-0007: Use PostgreSQL\n');
130
+ const res = await callAgentTool('kit_adr_search', { query: 'postgres' }, { projectRoot: root });
131
+ expect(res.ok && res.value).toEqual({
132
+ decisions: [{ id: 'ADR-0007', title: 'Use PostgreSQL', path: 'docs/adr/ADR-0007-use-postgres.md' }],
133
+ });
134
+ } finally {
135
+ await fs.rm(root, { recursive: true, force: true });
136
+ }
137
+ });
138
+
139
+ it('kit_verification_status reports null when nothing was recorded', async () => {
140
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'kit-dispatch-verify-'));
141
+ try {
142
+ expect(await callAgentTool('kit_verification_status', {}, { projectRoot: root })).toEqual({
143
+ ok: true,
144
+ value: { report: null },
145
+ });
146
+ } finally {
147
+ await fs.rm(root, { recursive: true, force: true });
148
+ }
149
+ });
150
+
151
+ it('kit_project_context rejects unknown keys (no commands in tool input)', async () => {
152
+ const res = await callAgentTool('kit_project_context', { files: [], command: ['rm'] }, { projectRoot: '/x' });
153
+ expect(res.ok).toBe(false);
154
+ });
155
+
156
+ it('kit_rules_explain rejects a malformed rule id before touching the filesystem', async () => {
157
+ const res = await callAgentTool('kit_rules_explain', { ruleId: '../../etc' }, { projectRoot: '/x' });
158
+ expect(res.ok).toBe(false);
159
+ });
160
+ });
@@ -0,0 +1,227 @@
1
+ // packages/cli/src/application/agent-tools/dispatch.ts
2
+ //
3
+ // Dispatches one typed agent tool call (item 4) to the core workflow APIs.
4
+ // Every call is validated against its contract schema first. Every outcome is
5
+ // a result, never an exception, so a host can act on any answer.
6
+
7
+ import {
8
+ AGENT_TOOL_NAMES,
9
+ KitNextInputSchema,
10
+ KitPhaseInputSchema,
11
+ KitProjectContextInputSchema,
12
+ KitRulesEvaluateInputSchema,
13
+ KitRulesExplainInputSchema,
14
+ KitRulesResolveInputSchema,
15
+ KitSearchInputSchema,
16
+ KitStatusInputSchema,
17
+ KitLearningRecordInputSchema,
18
+ KitVerificationStatusInputSchema,
19
+ type AgentToolName,
20
+ } from '@agentic-sdlc-kit/contracts';
21
+ import {
22
+ computeNextAction,
23
+ evaluateConstitution,
24
+ explainRule,
25
+ getFeatureRunState,
26
+ appendLearningEvent,
27
+ listDecisionRecords,
28
+ listRepoFiles,
29
+ loadPatterns,
30
+ loadRules,
31
+ profileStacks,
32
+ projectContext,
33
+ readLastVerify,
34
+ recordNextOffer,
35
+ resolveRules,
36
+ runTddPhase,
37
+ } from '@agentic-sdlc-kit/core';
38
+
39
+ import { constitutionAdapters } from '../rule-adapters/index.js';
40
+
41
+ const SEARCH_LIMIT = 25;
42
+
43
+ function matches(query: string | undefined, fields: readonly string[]): boolean {
44
+ if (query === undefined || query.trim() === '') return true;
45
+ const needle = query.toLowerCase();
46
+ return fields.some((f) => f.toLowerCase().includes(needle));
47
+ }
48
+
49
+ export type AgentToolResult =
50
+ | { readonly ok: true; readonly value: unknown }
51
+ | { readonly ok: false; readonly error: string };
52
+
53
+ export interface AgentToolContext {
54
+ readonly projectRoot: string;
55
+ }
56
+
57
+ // The host calling a tool is an agent. The kit records it as such.
58
+ const ACTOR = { kind: 'agent' } as const;
59
+
60
+ function fail(error: string): AgentToolResult {
61
+ return { ok: false, error };
62
+ }
63
+
64
+ function messageOf(err: unknown): string {
65
+ return err instanceof Error ? err.message : String(err);
66
+ }
67
+
68
+ async function kitNext(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
69
+ const parsed = KitNextInputSchema.safeParse(input);
70
+ if (!parsed.success) return fail(`invalid input for kit_next: ${parsed.error.message}`);
71
+ const res = await computeNextAction({ projectRoot: ctx.projectRoot, featureId: parsed.data.featureId });
72
+ if (!res.ok) return fail(res.error.message);
73
+ await recordNextOffer(ctx.projectRoot, res.value);
74
+ return { ok: true, value: res.value };
75
+ }
76
+
77
+ async function kitPhase(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
78
+ const parsed = KitPhaseInputSchema.safeParse(input);
79
+ if (!parsed.success) return fail(`invalid input for kit_phase: ${parsed.error.message}`);
80
+ const { featureId, taskId, phase } = parsed.data;
81
+ const res = await runTddPhase({ featureId, projectRoot: ctx.projectRoot, taskId, phase, actor: ACTOR });
82
+ if (!res.ok) return fail(res.error.message);
83
+ return { ok: true, value: { featureId, taskId, phase, phaseNow: res.value.tasks[taskId]?.phase ?? null } };
84
+ }
85
+
86
+ async function kitStatus(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
87
+ const parsed = KitStatusInputSchema.safeParse(input);
88
+ if (!parsed.success) return fail(`invalid input for kit_status: ${parsed.error.message}`);
89
+ const res = await getFeatureRunState(ctx.projectRoot, parsed.data.featureId);
90
+ if (!res.ok) return fail(res.error.message);
91
+ const tasks = Object.values(res.value.tasks).map((t) => ({
92
+ taskId: t.taskId,
93
+ phase: t.phase,
94
+ attempts: t.records.length,
95
+ }));
96
+ return { ok: true, value: { featureId: parsed.data.featureId, tasks } };
97
+ }
98
+
99
+ async function kitRulesResolve(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
100
+ const parsed = KitRulesResolveInputSchema.safeParse(input);
101
+ if (!parsed.success) return fail(`invalid input for kit_rules_resolve: ${parsed.error.message}`);
102
+ const loaded = await loadRules(ctx.projectRoot);
103
+ if (!loaded.ok) return fail(loaded.error.message);
104
+ const stacks = parsed.data.stacks ?? (await profileStacks(ctx.projectRoot));
105
+ const resolved = resolveRules(loaded.value.rules.map((l) => l.rule), { files: parsed.data.files, stacks });
106
+ if (!resolved.ok) return fail(resolved.error.message);
107
+ return {
108
+ ok: true,
109
+ value: {
110
+ rules: resolved.value.map((r) => ({
111
+ ruleId: r.rule.id,
112
+ title: r.rule.title,
113
+ statement: r.rule.statement,
114
+ mode: r.rule.mode,
115
+ matchedFiles: r.matchedFiles,
116
+ })),
117
+ },
118
+ };
119
+ }
120
+
121
+ async function kitRulesEvaluate(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
122
+ const parsed = KitRulesEvaluateInputSchema.safeParse(input);
123
+ if (!parsed.success) return fail(`invalid input for kit_rules_evaluate: ${parsed.error.message}`);
124
+ const stacks = parsed.data.stacks ?? (await profileStacks(ctx.projectRoot));
125
+ let files = parsed.data.files;
126
+ if (files === undefined) {
127
+ const listed = await listRepoFiles(ctx.projectRoot);
128
+ if (!listed.ok) return fail(listed.error.message);
129
+ files = listed.value;
130
+ }
131
+ const evaluation = await evaluateConstitution({
132
+ projectRoot: ctx.projectRoot,
133
+ stacks,
134
+ files,
135
+ adapters: constitutionAdapters(),
136
+ });
137
+ if (!evaluation.ok) return fail(evaluation.error.message);
138
+ return { ok: true, value: evaluation.value };
139
+ }
140
+
141
+ async function kitProjectContext(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
142
+ const parsed = KitProjectContextInputSchema.safeParse(input);
143
+ if (!parsed.success) return fail(`invalid input for kit_project_context: ${parsed.error.message}`);
144
+ const res = await projectContext(ctx.projectRoot, { ...parsed.data, adapters: constitutionAdapters() });
145
+ return res.ok ? { ok: true, value: res.value } : fail(res.error.message);
146
+ }
147
+
148
+ async function kitRulesExplain(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
149
+ const parsed = KitRulesExplainInputSchema.safeParse(input);
150
+ if (!parsed.success) return fail(`invalid input for kit_rules_explain: ${parsed.error.message}`);
151
+ const res = await explainRule(ctx.projectRoot, parsed.data.ruleId);
152
+ return res.ok ? { ok: true, value: res.value } : fail(res.error.message);
153
+ }
154
+
155
+ async function kitAdrSearch(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
156
+ const parsed = KitSearchInputSchema.safeParse(input);
157
+ if (!parsed.success) return fail(`invalid input for kit_adr_search: ${parsed.error.message}`);
158
+ const records = await listDecisionRecords(ctx.projectRoot);
159
+ const hits = records
160
+ .filter((r) => matches(parsed.data.query, [r.id, r.title]))
161
+ .slice(0, SEARCH_LIMIT);
162
+ return { ok: true, value: { decisions: hits } };
163
+ }
164
+
165
+ async function kitPatternsSearch(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
166
+ const parsed = KitSearchInputSchema.safeParse(input);
167
+ if (!parsed.success) return fail(`invalid input for kit_patterns_search: ${parsed.error.message}`);
168
+ const loaded = await loadPatterns(ctx.projectRoot);
169
+ if (!loaded.ok) return fail(loaded.error.message);
170
+ const hits = loaded.value
171
+ .filter((p) => matches(parsed.data.query, [p.id, p.name, p.problem]))
172
+ .slice(0, SEARCH_LIMIT)
173
+ .map((p) => ({ id: p.id, name: p.name, problem: p.problem, whenToUse: p.whenToUse }));
174
+ return { ok: true, value: { patterns: hits } };
175
+ }
176
+
177
+ async function kitLearningRecord(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
178
+ const parsed = KitLearningRecordInputSchema.safeParse(input);
179
+ if (!parsed.success) return fail(`invalid input for kit_learning_record: ${parsed.error.message}`);
180
+ const res = await appendLearningEvent(ctx.projectRoot, parsed.data);
181
+ return res.ok ? { ok: true, value: { recorded: res.value.id } } : fail(res.error.message);
182
+ }
183
+
184
+ async function kitVerificationStatus(input: unknown, ctx: AgentToolContext): Promise<AgentToolResult> {
185
+ const parsed = KitVerificationStatusInputSchema.safeParse(input);
186
+ if (!parsed.success) return fail(`invalid input for kit_verification_status: ${parsed.error.message}`);
187
+ const res = await readLastVerify(ctx.projectRoot);
188
+ return res.ok ? { ok: true, value: { report: res.value } } : fail(res.error.message);
189
+ }
190
+
191
+ export async function callAgentTool(
192
+ name: unknown,
193
+ input: unknown,
194
+ ctx: AgentToolContext,
195
+ ): Promise<AgentToolResult> {
196
+ try {
197
+ if (typeof name !== 'string' || !(AGENT_TOOL_NAMES as readonly string[]).includes(name)) {
198
+ return fail(`unknown tool '${String(name)}'`);
199
+ }
200
+ switch (name as AgentToolName) {
201
+ case 'kit_next':
202
+ return await kitNext(input, ctx);
203
+ case 'kit_phase':
204
+ return await kitPhase(input, ctx);
205
+ case 'kit_status':
206
+ return await kitStatus(input, ctx);
207
+ case 'kit_rules_resolve':
208
+ return await kitRulesResolve(input, ctx);
209
+ case 'kit_rules_evaluate':
210
+ return await kitRulesEvaluate(input, ctx);
211
+ case 'kit_project_context':
212
+ return await kitProjectContext(input, ctx);
213
+ case 'kit_rules_explain':
214
+ return await kitRulesExplain(input, ctx);
215
+ case 'kit_adr_search':
216
+ return await kitAdrSearch(input, ctx);
217
+ case 'kit_patterns_search':
218
+ return await kitPatternsSearch(input, ctx);
219
+ case 'kit_verification_status':
220
+ return await kitVerificationStatus(input, ctx);
221
+ case 'kit_learning_record':
222
+ return await kitLearningRecord(input, ctx);
223
+ }
224
+ } catch (err) {
225
+ return fail(messageOf(err));
226
+ }
227
+ }
@@ -0,0 +1,86 @@
1
+ // packages/cli/src/application/agent-tools/mcp-server.test.ts
2
+ //
3
+ // The typed tool surface served over the Model Context Protocol (item 4). The
4
+ // tests run a real MCP client against the server over the SDK's in-memory
5
+ // transport, so they exercise the protocol path a host uses, not just the
6
+ // dispatcher underneath it.
7
+ import { promises as fs } from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { afterEach, describe, expect, it } from 'vitest';
11
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
12
+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
13
+ import { createAgentToolServer } from './mcp-server.js';
14
+
15
+ const dirs: string[] = [];
16
+
17
+ afterEach(async () => {
18
+ for (const dir of dirs.splice(0)) await fs.rm(dir, { recursive: true, force: true });
19
+ });
20
+
21
+ async function connectedClient(): Promise<Client> {
22
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'kit-mcp-'));
23
+ dirs.push(root);
24
+ const server = createAgentToolServer({ projectRoot: root });
25
+ const [serverSide, clientSide] = InMemoryTransport.createLinkedPair();
26
+ await server.connect(serverSide);
27
+ const client = new Client({ name: 'kit-mcp-test', version: '0.0.0' });
28
+ await client.connect(clientSide);
29
+ return client;
30
+ }
31
+
32
+ function textOf(result: unknown): string {
33
+ const content = (result as { content?: Array<{ type: string; text?: string }> }).content ?? [];
34
+ return content.map((c) => c.text ?? '').join('');
35
+ }
36
+
37
+ describe('agent tool MCP server', () => {
38
+ it('lists the three protocol tools, each with a strict input schema', async () => {
39
+ const client = await connectedClient();
40
+ const { tools } = await client.listTools();
41
+ expect(tools.map((t) => t.name).sort()).toEqual([
42
+ 'kit_adr_search',
43
+ 'kit_learning_record',
44
+ 'kit_next',
45
+ 'kit_patterns_search',
46
+ 'kit_phase',
47
+ 'kit_project_context',
48
+ 'kit_rules_evaluate',
49
+ 'kit_rules_explain',
50
+ 'kit_rules_resolve',
51
+ 'kit_status',
52
+ 'kit_verification_status',
53
+ ]);
54
+ const phase = tools.find((t) => t.name === 'kit_phase');
55
+ expect(phase?.inputSchema.additionalProperties).toBe(false);
56
+ });
57
+
58
+ it('answers kit_next with the protocol action over the wire', async () => {
59
+ const client = await connectedClient();
60
+ const result = await client.callTool({ name: 'kit_next', arguments: { featureId: 'FEATURE-001' } });
61
+ expect(result.isError).toBeFalsy();
62
+ expect(JSON.parse(textOf(result))).toMatchObject({ requiredAction: 'feature.start' });
63
+ });
64
+
65
+ it('refuses a kit_phase call that carries a command, and runs nothing', async () => {
66
+ const client = await connectedClient();
67
+ const outcome = await client
68
+ .callTool({
69
+ name: 'kit_phase',
70
+ arguments: { featureId: 'FEATURE-001', taskId: 'TASK-001', phase: 'red', command: 'rm -rf /' },
71
+ })
72
+ .then(
73
+ (r) => (r.isError ? 'error' : 'ok'),
74
+ () => 'error',
75
+ );
76
+ expect(outcome).toBe('error');
77
+ });
78
+
79
+ it('reports a missing run as a tool error, not a success', async () => {
80
+ const client = await connectedClient();
81
+ const outcome = await client
82
+ .callTool({ name: 'kit_status', arguments: { featureId: 'FEATURE-404' } })
83
+ .then((r) => (r.isError ? 'error' : 'ok'), () => 'error');
84
+ expect(outcome).toBe('error');
85
+ });
86
+ });