@codapult/cli 0.17.2 → 0.18.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.
@@ -1,5 +1,5 @@
1
1
  import { execSync } from 'node:child_process';
2
- import { findProjectRoot } from '../utils/project.js';
2
+ import { checkProjectRoot } from '../utils/project.js';
3
3
  import { heading, success, fail, warn, info, dim, confirm, label } from '../utils/ui.js';
4
4
  const UPSTREAM_REMOTE = 'codapult-upstream';
5
5
  const UPSTREAM_URL = 'https://github.com/codapult/codapult.git';
@@ -73,11 +73,7 @@ function classifyConflicts(cwd) {
73
73
  return { safe, caution, core };
74
74
  }
75
75
  export async function updateCommand(version, options) {
76
- const root = findProjectRoot();
77
- if (!root) {
78
- fail('Not inside a Codapult project.');
79
- process.exit(1);
80
- }
76
+ const root = checkProjectRoot('exit');
81
77
  ensureUpstreamRemote(root);
82
78
  fetchUpstream(root);
83
79
  const tags = getAvailableTags(root);
package/dist/index.js CHANGED
@@ -11,13 +11,15 @@ import { generatePageCommand, generateApiCommand, generateActionCommand, generat
11
11
  import { dbPushCommand, dbGenerateCommand, dbSeedCommand, dbStudioCommand, dbStatusCommand, dbLiveDiffCommand, dbSchemaDiffCommand, } from './commands/db.js';
12
12
  import { envCheckCommand, envSyncCommand } from './commands/env.js';
13
13
  import { mcpContractCheckCommand, mcpDoctorCommand, mcpUpdateCommand } from './commands/mcp.js';
14
+ import { guardCheckCommand, guardAuditCommand, guardInitCommand, guardAnalyzeCommand, guardProposeCommand, guardInstallAgentCommand, guardDoctorCommand, guardHistoryCommand, guardHistoryDiffCommand, guardVerifyCommand, guardReviewCommand, guardRulesApproveCommand, guardContractsApproveCommand, guardContractsRejectCommand, guardBaselineCommand, } from './commands/guard.js';
14
15
  import { deployVercelCommand, deployDockerCommand, deployStatusCommand, } from './commands/deploy.js';
15
16
  import { ENV_EXAMPLE_FILE_NAME, ENV_FILE_NAME } from './utils/project-env.js';
17
+ import { config } from './utils/config.js';
16
18
  const require = createRequire(import.meta.url);
17
19
  const packageJson = require('../package.json');
18
20
  const program = new Command()
19
- .name('codapult')
20
- .description('Codapult CLI — manage your SaaS project')
21
+ .name(config.commandName)
22
+ .description(`${config.projectName} CLI — manage your SaaS project`)
21
23
  .version(packageJson.version)
22
24
  .configureHelp({
23
25
  styleTitle: (str) => pc.bold(pc.cyan(str)),
@@ -37,7 +39,7 @@ program
37
39
  .action(setupCommand);
38
40
  program
39
41
  .command('update [version]')
40
- .description('update from upstream Codapult releases')
42
+ .description(`update from upstream ${config.projectName} releases`)
41
43
  .option('--dry-run', 'show what would change without applying')
42
44
  .option('--list', 'list available versions')
43
45
  .action(updateCommand);
@@ -46,7 +48,7 @@ withNoEnvFileOption(program.command('config').description('show current project
46
48
  const plugins = program
47
49
  .commandsGroup('Plugins')
48
50
  .command('plugins')
49
- .description('manage Codapult plugins');
51
+ .description(`manage ${config.projectName} plugins`);
50
52
  withNoEnvFileOption(plugins
51
53
  .command('add <name>')
52
54
  .description('install a plugin (local or remote)')
@@ -91,6 +93,110 @@ db.command('schema-diff')
91
93
  .description('compare SQLite and PostgreSQL schema files')
92
94
  .action(dbSchemaDiffCommand);
93
95
  const env = program.command('env').description('environment variable management');
96
+ const guard = program
97
+ .commandsGroup('Architecture')
98
+ .command('guard')
99
+ .description('protect project architecture from new violations');
100
+ guard
101
+ .command('init')
102
+ .description('create local Guard rules and baseline')
103
+ .option('--force', 'replace an existing Guard baseline and generated memory')
104
+ .action(guardInitCommand);
105
+ guard
106
+ .command('analyze')
107
+ .description('analyze project structure, dependencies, AST, and conventions')
108
+ .action(guardAnalyzeCommand);
109
+ guard
110
+ .command('propose')
111
+ .description('generate evidence-based rule and contract proposals for an AI agent')
112
+ .option('--json', 'print a machine-readable proposal packet')
113
+ .action(guardProposeCommand);
114
+ guard
115
+ .command('install-agent [target]')
116
+ .description('install or update the Guard instruction block for an AI agent')
117
+ .option('--json', 'emit machine-readable JSON')
118
+ .action(guardInstallAgentCommand);
119
+ guard
120
+ .command('doctor')
121
+ .description('diagnose Guard artifacts and configuration')
122
+ .option('--json', 'print a machine-readable report')
123
+ .action(guardDoctorCommand);
124
+ guard
125
+ .command('history')
126
+ .description('list persisted Guard project snapshots')
127
+ .action(guardHistoryCommand);
128
+ guard
129
+ .command('history-diff <from> <to>')
130
+ .description('compare two Guard project snapshots')
131
+ .option('--json', 'print a machine-readable report')
132
+ .action(guardHistoryDiffCommand);
133
+ guard
134
+ .command('check')
135
+ .description('check architecture rules against the project')
136
+ .option('--changed', 'check only files changed from HEAD')
137
+ .option('--json', 'print a machine-readable report')
138
+ .option('--sarif', 'print a SARIF report for CI code-scanning integrations')
139
+ .action(guardCheckCommand);
140
+ guard
141
+ .command('audit')
142
+ .description('run a full Guard audit, including baseline findings')
143
+ .option('--json', 'print a machine-readable report')
144
+ .action(guardAuditCommand);
145
+ guard
146
+ .command('verify')
147
+ .description('verify checks, build, and architecture regressions')
148
+ .option('--checks <list>', 'comma-separated: lint,typecheck,test,build')
149
+ .option('--tools <mode>', 'external tools: auto, on, or off', 'auto')
150
+ .option('--strict', 'fail when an explicitly requested check or adapter is not configured')
151
+ .option('--no-project-checks', 'skip project lint/typecheck/test/build checks')
152
+ .option('--requirement <file>', 'read acceptance criteria from a UTF-8 text file')
153
+ .option('--changed', 'check architecture only in changed and untracked files')
154
+ .option('--json', 'print a machine-readable report')
155
+ .action(guardVerifyCommand);
156
+ guard
157
+ .command('review')
158
+ .description('prepare a semantic review packet for an AI agent')
159
+ .option('--max-diff-chars <number>', 'limit diff size in the packet', '120000')
160
+ .option('--base <ref>', 'review the PR diff from a base ref, for example origin/main')
161
+ .option('--requirement <file>', 'read acceptance criteria from a UTF-8 text file')
162
+ .action(guardReviewCommand);
163
+ const guardRules = guard.command('rules').description('manage discovered Guard rules');
164
+ guardRules
165
+ .command('approve [ids]')
166
+ .description('activate proposed rules by comma-separated ID')
167
+ .option('--all', 'activate all proposed rules')
168
+ .action(guardRulesApproveCommand);
169
+ const guardContracts = guard.command('contracts').description('manage project Guard contracts');
170
+ guardContracts
171
+ .command('approve [ids]')
172
+ .description('activate proposed contracts by comma-separated ID')
173
+ .option('--all', 'activate all proposed contracts')
174
+ .action(guardContractsApproveCommand);
175
+ guardContracts
176
+ .command('reject [ids]')
177
+ .description('reject proposed contracts by comma-separated ID')
178
+ .option('--all', 'reject all proposed contracts')
179
+ .action(guardContractsRejectCommand);
180
+ const guardBaseline = guard.command('baseline').description('manage suppressed Guard findings');
181
+ guardBaseline
182
+ .command('list')
183
+ .description('list baseline fingerprints')
184
+ .option('--json', 'print a machine-readable report')
185
+ .action((options) => guardBaselineCommand('list', undefined, options));
186
+ guardBaseline
187
+ .command('accept [ids]')
188
+ .description('accept findings into the baseline by fingerprint')
189
+ .option('--all', 'accept all current findings')
190
+ .option('--reason <text>', 'record why the findings are accepted')
191
+ .option('--json', 'print a machine-readable report')
192
+ .action((ids, options) => guardBaselineCommand('accept', ids, options));
193
+ guardBaseline
194
+ .command('remove [ids]')
195
+ .description('remove fingerprints from the baseline')
196
+ .option('--all', 'remove all current findings')
197
+ .option('--reason <text>', 'record why the findings are removed')
198
+ .option('--json', 'print a machine-readable report')
199
+ .action((ids, options) => guardBaselineCommand('remove', ids, options));
94
200
  withNoEnvFileOption(env.command('check').description(`validate env vars against ${ENV_EXAMPLE_FILE_NAME}`)).action(envCheckCommand);
95
201
  withNoEnvFileOption(env.command('sync').description(`add missing variables from ${ENV_EXAMPLE_FILE_NAME}`)).action(envSyncCommand);
96
202
  const deploy = program.command('deploy').description('deployment helpers');
@@ -106,7 +212,7 @@ const mcp = program
106
212
  .description('manage the project MCP configuration');
107
213
  mcp
108
214
  .command('update [version]')
109
- .description('pin the Codapult MCP server to a version (defaults to the latest npm version)')
215
+ .description(`pin the ${config.projectName} MCP server to a version (defaults to the latest npm version)`)
110
216
  .option('--dry-run', 'show the update without writing .cursor/mcp.json')
111
217
  .action(mcpUpdateCommand);
112
218
  mcp
@@ -1,14 +1,8 @@
1
1
  import { existsSync, readdirSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
- import { findProjectRoot, readProjectFile } from '../utils/project.js';
3
+ import { checkProjectRoot, readProjectFile } from '../utils/project.js';
4
4
  import { ENV_EXAMPLE_FILE_NAME, loadProjectEnv } from '../utils/project-env.js';
5
5
  import { getAdapters } from '../utils/env-config.js';
6
- function getRoot() {
7
- const root = findProjectRoot();
8
- if (!root)
9
- throw new Error('Not inside a Codapult project');
10
- return root;
11
- }
12
6
  function getSchemaPath(root) {
13
7
  const provider = getAdapters(loadProjectEnv(root).content).database;
14
8
  return provider === 'postgres' ? 'src/lib/db/schema-pg.ts' : 'src/lib/db/schema.ts';
@@ -19,7 +13,7 @@ export function registerResources(server) {
19
13
  description: 'Active Drizzle ORM schema selected by DB_PROVIDER — all tables, columns, types, and relations',
20
14
  mimeType: 'text/plain',
21
15
  }, () => {
22
- const root = getRoot();
16
+ const root = checkProjectRoot('throw');
23
17
  const content = readProjectFile(root, getSchemaPath(root)) ?? 'Schema file not found';
24
18
  return { contents: [{ uri: 'codapult://schema', text: content, mimeType: 'text/plain' }] };
25
19
  });
@@ -28,7 +22,8 @@ export function registerResources(server) {
28
22
  description: `Application config (src/config/app.ts) — brand and company. AI runtime settings, feature toggles, and auth methods live in src/config/env.ts — see codapult://config/env.`,
29
23
  mimeType: 'text/plain',
30
24
  }, () => {
31
- const content = readProjectFile(getRoot(), 'src/config/app.ts') ?? 'Config file not found';
25
+ const root = checkProjectRoot('throw');
26
+ const content = readProjectFile(root, 'src/config/app.ts') ?? 'Config file not found';
32
27
  return {
33
28
  contents: [{ uri: 'codapult://config/app', text: content, mimeType: 'text/plain' }],
34
29
  };
@@ -38,7 +33,8 @@ export function registerResources(server) {
38
33
  description: `Typed env access (src/config/env.ts) — feature toggles (env.features), auth methods (env.auth), provider selection (db.provider, payments.provider, storage.provider, jobs.provider), and checkout resolution. This is the source of truth for which modules are enabled — see also codapult://env-example or codapult_project_status.`,
39
34
  mimeType: 'text/plain',
40
35
  }, () => {
41
- const content = readProjectFile(getRoot(), 'src/config/env.ts') ?? 'Config file not found';
36
+ const root = checkProjectRoot('throw');
37
+ const content = readProjectFile(root, 'src/config/env.ts') ?? 'Config file not found';
42
38
  return {
43
39
  contents: [{ uri: 'codapult://config/env', text: content, mimeType: 'text/plain' }],
44
40
  };
@@ -48,7 +44,8 @@ export function registerResources(server) {
48
44
  description: 'AI agent guide — project structure, patterns, conventions, and rules',
49
45
  mimeType: 'text/markdown',
50
46
  }, () => {
51
- const content = readProjectFile(getRoot(), 'AGENTS.md') ?? 'AGENTS.md not found';
47
+ const root = checkProjectRoot('throw');
48
+ const content = readProjectFile(root, 'AGENTS.md') ?? 'AGENTS.md not found';
52
49
  return { contents: [{ uri: 'codapult://agents', text: content, mimeType: 'text/markdown' }] };
53
50
  });
54
51
  server.registerResource('codapult_env_example', 'codapult://env-example', {
@@ -56,7 +53,8 @@ export function registerResources(server) {
56
53
  description: 'Environment variable template with descriptions and defaults',
57
54
  mimeType: 'text/plain',
58
55
  }, () => {
59
- const content = readProjectFile(getRoot(), ENV_EXAMPLE_FILE_NAME) ?? `${ENV_EXAMPLE_FILE_NAME} not found`;
56
+ const root = checkProjectRoot('throw');
57
+ const content = readProjectFile(root, ENV_EXAMPLE_FILE_NAME) ?? `${ENV_EXAMPLE_FILE_NAME} not found`;
60
58
  return {
61
59
  contents: [{ uri: 'codapult://env-example', text: content, mimeType: 'text/plain' }],
62
60
  };
@@ -66,7 +64,8 @@ export function registerResources(server) {
66
64
  description: 'All Zod validation schemas (src/lib/validation.ts)',
67
65
  mimeType: 'text/plain',
68
66
  }, () => {
69
- const content = readProjectFile(getRoot(), 'src/lib/validation.ts') ?? 'validation.ts not found';
67
+ const root = checkProjectRoot('throw');
68
+ const content = readProjectFile(root, 'src/lib/validation.ts') ?? 'validation.ts not found';
70
69
  return {
71
70
  contents: [{ uri: 'codapult://validation', text: content, mimeType: 'text/plain' }],
72
71
  };
@@ -76,7 +75,8 @@ export function registerResources(server) {
76
75
  description: 'Dashboard & admin sidebar items (src/config/navigation.ts)',
77
76
  mimeType: 'text/plain',
78
77
  }, () => {
79
- const content = readProjectFile(getRoot(), 'src/config/navigation.ts') ?? 'navigation.ts not found';
78
+ const root = checkProjectRoot('throw');
79
+ const content = readProjectFile(root, 'src/config/navigation.ts') ?? 'navigation.ts not found';
80
80
  return {
81
81
  contents: [{ uri: 'codapult://config/navigation', text: content, mimeType: 'text/plain' }],
82
82
  };
@@ -86,7 +86,7 @@ export function registerResources(server) {
86
86
  description: 'All non-test TypeScript configuration files from src/config, including marketing and navigation configuration',
87
87
  mimeType: 'application/json',
88
88
  }, () => {
89
- const root = getRoot();
89
+ const root = checkProjectRoot('throw');
90
90
  const configDir = resolve(root, 'src/config');
91
91
  const files = existsSync(configDir)
92
92
  ? readdirSync(configDir)
@@ -9,6 +9,9 @@ import { registerGenerateTools } from './tools/generate.js';
9
9
  import { registerDeployTools } from './tools/deploy.js';
10
10
  import { registerPrompts } from './prompts.js';
11
11
  import { registerResources } from './resources.js';
12
+ import { registerGuardTools } from '@codapult/guard/mcp';
13
+ import { registerGuardPrompts } from '@codapult/guard/mcp/prompts';
14
+ import { registerGuardResources } from '@codapult/guard/mcp/resources';
12
15
  const require = createRequire(import.meta.url);
13
16
  const packageJson = require('../../package.json');
14
17
  const server = new McpServer({
@@ -23,5 +26,8 @@ registerGenerateTools(server);
23
26
  registerDeployTools(server);
24
27
  registerPrompts(server);
25
28
  registerResources(server);
29
+ registerGuardTools(server);
30
+ registerGuardPrompts(server);
31
+ registerGuardResources(server);
26
32
  const transport = new StdioServerTransport();
27
33
  await server.connect(transport);
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readdirSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { z } from 'zod';
4
- import { findProjectRoot, readProjectFile } from '../../utils/project.js';
4
+ import { checkProjectRoot, readProjectFile } from '../../utils/project.js';
5
5
  import { getProjectEnvOptions, loadProjectEnv } from '../../utils/project-env.js';
6
6
  import { getAdapters } from '../../utils/env-config.js';
7
7
  import { envSourceSchema } from './schemas.js';
@@ -10,12 +10,6 @@ import { previewMigration } from '../../utils/db-diff.js';
10
10
  import { parseDatabaseSchema } from '../../utils/schema-parser.js';
11
11
  import { compareSchemaFiles } from '../../utils/schema-parity.js';
12
12
  import { diffSchemaWithLiveDatabase, inspectLiveDatabase } from '../../utils/live-db-diff.js';
13
- function getRoot() {
14
- const root = findProjectRoot();
15
- if (!root)
16
- throw new Error('Not inside a Codapult project');
17
- return root;
18
- }
19
13
  function getDatabaseContext(root, envSource) {
20
14
  const envContent = loadProjectEnv(root, getProjectEnvOptions(envSource)).content;
21
15
  const provider = getAdapters(envContent).database;
@@ -33,7 +27,7 @@ export function registerDbTools(server) {
33
27
  dry_run: z.boolean().default(false).describe('Preview without changing files'),
34
28
  },
35
29
  }, ({ dry_run }) => {
36
- const root = getRoot();
30
+ const root = checkProjectRoot('throw');
37
31
  const { provider } = getDatabaseContext(root);
38
32
  if (dry_run) {
39
33
  const preview = previewMigration(root, provider, getDatabaseContext(root).schemaPath);
@@ -51,7 +45,7 @@ export function registerDbTools(server) {
51
45
  description: 'Generate the pending SQL migration in a temporary directory without changing project files. Compares source schema with local migration history, not the live database.',
52
46
  inputSchema: {},
53
47
  }, () => {
54
- const root = getRoot();
48
+ const root = checkProjectRoot('throw');
55
49
  const { provider, schemaPath } = getDatabaseContext(root);
56
50
  const preview = previewMigration(root, provider, schemaPath);
57
51
  return {
@@ -66,7 +60,7 @@ export function registerDbTools(server) {
66
60
  dry_run: z.boolean().default(false).describe('Preview without changing the database'),
67
61
  },
68
62
  }, ({ dry_run }) => {
69
- const root = getRoot();
63
+ const root = checkProjectRoot('throw');
70
64
  const { provider } = getDatabaseContext(root);
71
65
  if (dry_run) {
72
66
  return {
@@ -99,14 +93,15 @@ export function registerDbTools(server) {
99
93
  ],
100
94
  };
101
95
  }
102
- return commandResponse(runProjectCommand('pnpm db:seed', getRoot()));
96
+ const root = checkProjectRoot('throw');
97
+ return commandResponse(runProjectCommand('pnpm db:seed', root));
103
98
  });
104
99
  server.registerTool('codapult_db_get_tables', {
105
100
  title: 'Get Database Tables',
106
101
  description: 'List all tables in the database schema with column counts',
107
102
  inputSchema: {},
108
103
  }, () => {
109
- const root = getRoot();
104
+ const root = checkProjectRoot('throw');
110
105
  const { provider, schemaPath } = getDatabaseContext(root);
111
106
  const content = readProjectFile(root, schemaPath);
112
107
  if (!content)
@@ -136,7 +131,7 @@ export function registerDbTools(server) {
136
131
  table: z.string().describe('Table name (e.g. "user", "subscription")'),
137
132
  },
138
133
  }, ({ table }) => {
139
- const root = getRoot();
134
+ const root = checkProjectRoot('throw');
140
135
  const { provider, schemaPath } = getDatabaseContext(root);
141
136
  const content = readProjectFile(root, schemaPath);
142
137
  if (!content)
@@ -171,7 +166,7 @@ export function registerDbTools(server) {
171
166
  env_source: envSourceSchema.optional(),
172
167
  },
173
168
  }, ({ env_source }) => {
174
- const root = getRoot();
169
+ const root = checkProjectRoot('throw');
175
170
  const envContent = loadProjectEnv(root, getProjectEnvOptions(env_source)).content;
176
171
  const provider = getAdapters(envContent).database;
177
172
  const schemaPath = provider === 'postgres' ? 'src/lib/db/schema-pg.ts' : 'src/lib/db/schema.ts';
@@ -204,7 +199,7 @@ export function registerDbTools(server) {
204
199
  env_source: envSourceSchema.optional(),
205
200
  },
206
201
  }, ({ env_source }) => {
207
- const root = getRoot();
202
+ const root = checkProjectRoot('throw');
208
203
  const { provider, schemaPath } = getDatabaseContext(root, env_source);
209
204
  const schema = parseSchema(readProjectFile(root, schemaPath) ?? '');
210
205
  try {
@@ -244,7 +239,7 @@ export function registerDbTools(server) {
244
239
  description: 'Compare SQLite and PostgreSQL schema files and report missing tables, columns, and type differences',
245
240
  inputSchema: {},
246
241
  }, () => {
247
- const root = getRoot();
242
+ const root = checkProjectRoot('throw');
248
243
  const sqlitePath = 'src/lib/db/schema.ts';
249
244
  const postgresPath = 'src/lib/db/schema-pg.ts';
250
245
  const report = compareSchemaFiles(parseSchema(readProjectFile(root, sqlitePath) ?? ''), parseSchema(readProjectFile(root, postgresPath) ?? ''));
@@ -3,13 +3,13 @@ import { ENV_FILE_NAME } from '../../utils/project-env.js';
3
3
  vi.mock('node:fs');
4
4
  vi.mock('node:child_process');
5
5
  vi.mock('../../utils/project.js', () => ({
6
- findProjectRoot: vi.fn(),
6
+ checkProjectRoot: vi.fn(),
7
7
  readProjectFile: vi.fn(),
8
8
  }));
9
9
  const { existsSync, readdirSync } = await import('node:fs');
10
- const { findProjectRoot, readProjectFile } = await import('../../utils/project.js');
10
+ const { checkProjectRoot, readProjectFile } = await import('../../utils/project.js');
11
11
  const { registerDbTools } = await import('./db.js');
12
- const mockedFindRoot = vi.mocked(findProjectRoot);
12
+ const mockedFindRoot = vi.mocked(checkProjectRoot);
13
13
  const mockedReadProject = vi.mocked(readProjectFile);
14
14
  const mockedExists = vi.mocked(existsSync);
15
15
  const mockedReaddir = vi.mocked(readdirSync);
@@ -1,20 +1,14 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
- import { findProjectRoot } from '../../utils/project.js';
3
+ import { checkProjectRoot } from '../../utils/project.js';
4
4
  import { ENV_FILE_NAME } from '../../utils/project-env.js';
5
- function getRoot() {
6
- const root = findProjectRoot();
7
- if (!root)
8
- throw new Error('Not inside a Codapult project');
9
- return root;
10
- }
11
5
  export function registerDeployTools(server) {
12
6
  server.registerTool('codapult_deploy_status', {
13
7
  title: 'Deploy Readiness',
14
8
  description: 'Check deployment readiness: Dockerfile, vercel.json, Helm, Terraform, Pulumi, standalone output, Node engine',
15
9
  inputSchema: {},
16
10
  }, () => {
17
- const root = getRoot();
11
+ const root = checkProjectRoot('throw');
18
12
  const checks = [
19
13
  { name: 'Dockerfile', path: 'Dockerfile' },
20
14
  { name: 'docker-compose.yml', path: 'docker-compose.yml' },
@@ -1,16 +1,10 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { z } from 'zod';
4
- import { findProjectRoot, readProjectFile } from '../../utils/project.js';
4
+ import { checkProjectRoot, readProjectFile } from '../../utils/project.js';
5
5
  import { ENV_EXAMPLE_FILE_NAME, ENV_FILE_NAME, getProjectEnvOptions, loadProjectEnv, } from '../../utils/project-env.js';
6
6
  import { findProviderIssues, getAdapters, getAuthMethods, getFeatures, getOauthProviders, readEnv, } from '../../utils/env-config.js';
7
7
  import { envSourceSchema } from './schemas.js';
8
- function getRoot() {
9
- const root = findProjectRoot();
10
- if (!root)
11
- throw new Error('Not inside a Codapult project');
12
- return root;
13
- }
14
8
  export function parseEnvFile(content) {
15
9
  const entries = [];
16
10
  let lastComment = '';
@@ -61,7 +55,7 @@ export function registerEnvTools(server) {
61
55
  description: `Validate ${ENV_FILE_NAME} against ${ENV_EXAMPLE_FILE_NAME} without exposing secret values`,
62
56
  inputSchema: { env_source: envSourceSchema.optional() },
63
57
  }, ({ env_source }) => {
64
- const root = getRoot();
58
+ const root = checkProjectRoot('throw');
65
59
  const example = parseEnvFile(readProjectFile(root, ENV_EXAMPLE_FILE_NAME) ?? '');
66
60
  const local = parseEnvFile(loadProjectEnv(root, getProjectEnvOptions(env_source)).content);
67
61
  const localKeys = new Set(local.map((entry) => entry.key));
@@ -102,7 +96,7 @@ export function registerEnvTools(server) {
102
96
  .describe('Preview missing variables without writing the file'),
103
97
  },
104
98
  }, ({ dry_run }) => {
105
- const root = getRoot();
99
+ const root = checkProjectRoot('throw');
106
100
  const exampleContent = readProjectFile(root, ENV_EXAMPLE_FILE_NAME);
107
101
  if (!exampleContent) {
108
102
  return {
@@ -140,7 +134,7 @@ export function registerEnvTools(server) {
140
134
  description: `Get all environment variables from ${ENV_EXAMPLE_FILE_NAME} with descriptions and default values`,
141
135
  inputSchema: {},
142
136
  }, () => {
143
- const root = getRoot();
137
+ const root = checkProjectRoot('throw');
144
138
  const content = readProjectFile(root, ENV_EXAMPLE_FILE_NAME);
145
139
  if (!content)
146
140
  return {
@@ -161,7 +155,7 @@ export function registerEnvTools(server) {
161
155
  env_source: envSourceSchema.optional(),
162
156
  },
163
157
  }, ({ show_secrets, env_source }) => {
164
- const root = getRoot();
158
+ const root = checkProjectRoot('throw');
165
159
  const env = loadProjectEnv(root, getProjectEnvOptions(env_source));
166
160
  const localContent = env.content;
167
161
  if (!localContent && env.source === 'file')
@@ -218,7 +212,7 @@ export function registerEnvTools(server) {
218
212
  isError: true,
219
213
  };
220
214
  }
221
- const root = getRoot();
215
+ const root = checkProjectRoot('throw');
222
216
  if (env_source === 'process') {
223
217
  return {
224
218
  content: [
@@ -2,20 +2,20 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
2
  import { ENV_EXAMPLE_FILE_NAME, ENV_FILE_NAME } from '../../utils/project-env.js';
3
3
  vi.mock('node:fs');
4
4
  vi.mock('../../utils/project.js', () => ({
5
- findProjectRoot: vi.fn(),
5
+ checkProjectRoot: vi.fn(),
6
6
  readProjectFile: vi.fn(),
7
7
  }));
8
8
  const { existsSync, readFileSync, writeFileSync } = await import('node:fs');
9
- const { findProjectRoot, readProjectFile } = await import('../../utils/project.js');
9
+ const { checkProjectRoot, readProjectFile } = await import('../../utils/project.js');
10
10
  const { registerEnvTools } = await import('./env.js');
11
- const mockedFindRoot = vi.mocked(findProjectRoot);
11
+ const mockedCheckRoot = vi.mocked(checkProjectRoot);
12
12
  const mockedReadProject = vi.mocked(readProjectFile);
13
13
  const mockedExists = vi.mocked(existsSync);
14
14
  const mockedRead = vi.mocked(readFileSync);
15
15
  const mockedWrite = vi.mocked(writeFileSync);
16
16
  beforeEach(() => {
17
17
  vi.resetAllMocks();
18
- mockedFindRoot.mockReturnValue('/project');
18
+ mockedCheckRoot.mockReturnValue('/project');
19
19
  });
20
20
  function createMockServer() {
21
21
  const tools = [];
@@ -1,14 +1,8 @@
1
1
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
2
  import { resolve, dirname } from 'node:path';
3
3
  import { z } from 'zod';
4
- import { findProjectRoot } from '../../utils/project.js';
4
+ import { checkProjectRoot } from '../../utils/project.js';
5
5
  import { validateGeneratedName } from '../../utils/validation.js';
6
- function getRoot() {
7
- const root = findProjectRoot();
8
- if (!root)
9
- throw new Error('Not inside a Codapult project');
10
- return root;
11
- }
12
6
  function toKebab(name) {
13
7
  return name
14
8
  .replace(/([a-z])([A-Z])/g, '$1-$2')
@@ -42,20 +36,21 @@ export function registerGenerateTools(server) {
42
36
  },
43
37
  }, ({ name, dry_run }) => {
44
38
  validateGeneratedName(name);
45
- const root = getRoot();
39
+ const root = checkProjectRoot('throw');
46
40
  const kebab = toKebab(name);
47
41
  const pascal = toPascal(name);
48
42
  const title = pascal.replace(/([A-Z])/g, ' $1').trim();
49
43
  const path = `src/app/(dashboard)/dashboard/${kebab}/page.tsx`;
50
- if (dry_run)
44
+ if (dry_run) {
51
45
  return {
52
46
  content: [
53
47
  {
54
48
  type: 'text',
55
- text: JSON.stringify({ dryRun: true, path, wouldCreate: !existsSync(resolve(getRoot(), path)) }, null, 2),
49
+ text: JSON.stringify({ dryRun: true, path, wouldCreate: !existsSync(resolve(root, path)) }, null, 2),
56
50
  },
57
51
  ],
58
52
  };
53
+ }
59
54
  const page = `import { getAppSession } from '@/lib/auth';\nimport { redirect } from 'next/navigation';\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';\n\nexport const metadata = {\n title: '${title} — Codapult',\n};\n\nexport default async function ${pascal}Page() {\n const session = await getAppSession();\n if (!session) redirect('/sign-in');\n\n return (\n <div className="space-y-6">\n <div>\n <h1 className="text-3xl font-bold tracking-tight">${title}</h1>\n <p className="text-muted-foreground">Manage your ${kebab} settings</p>\n </div>\n\n <Card>\n <CardHeader>\n <CardTitle>${title}</CardTitle>\n <CardDescription>Your ${kebab} content goes here</CardDescription>\n </CardHeader>\n <CardContent>\n <p className="text-muted-foreground">Start building your ${kebab} page.</p>\n </CardContent>\n </Card>\n </div>\n );\n}\n`;
60
55
  const result = writeIfNew(resolve(root, path), page);
61
56
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
@@ -69,7 +64,7 @@ export function registerGenerateTools(server) {
69
64
  },
70
65
  }, ({ name, dry_run }) => {
71
66
  validateGeneratedName(name);
72
- const root = getRoot();
67
+ const root = checkProjectRoot('throw');
73
68
  const kebab = toKebab(name);
74
69
  const camel = toCamel(name);
75
70
  const schemaName = `${camel}Schema`;
@@ -79,7 +74,7 @@ export function registerGenerateTools(server) {
79
74
  content: [
80
75
  {
81
76
  type: 'text',
82
- text: JSON.stringify({ dryRun: true, path, wouldCreate: !existsSync(resolve(getRoot(), path)) }, null, 2),
77
+ text: JSON.stringify({ dryRun: true, path, wouldCreate: !existsSync(resolve(root, path)) }, null, 2),
83
78
  },
84
79
  ],
85
80
  };
@@ -96,7 +91,7 @@ export function registerGenerateTools(server) {
96
91
  },
97
92
  }, ({ name, dry_run }) => {
98
93
  validateGeneratedName(name);
99
- const root = getRoot();
94
+ const root = checkProjectRoot('throw');
100
95
  const kebab = toKebab(name);
101
96
  const camel = toCamel(name);
102
97
  const schemaName = `${camel}Schema`;
@@ -106,7 +101,7 @@ export function registerGenerateTools(server) {
106
101
  content: [
107
102
  {
108
103
  type: 'text',
109
- text: JSON.stringify({ dryRun: true, path, wouldCreate: !existsSync(resolve(getRoot(), path)) }, null, 2),
104
+ text: JSON.stringify({ dryRun: true, path, wouldCreate: !existsSync(resolve(root, path)) }, null, 2),
110
105
  },
111
106
  ],
112
107
  };
@@ -123,7 +118,7 @@ export function registerGenerateTools(server) {
123
118
  },
124
119
  }, ({ name, dry_run }) => {
125
120
  validateGeneratedName(name);
126
- const root = getRoot();
121
+ const root = checkProjectRoot('throw');
127
122
  const kebab = toKebab(name);
128
123
  const camel = toCamel(name);
129
124
  const pascal = toPascal(name);