@codapult/cli 0.18.1 → 0.19.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 (34) hide show
  1. package/README.md +49 -18
  2. package/package.json +12 -5
  3. package/dist/commands/generate.test.d.ts +0 -1
  4. package/dist/commands/generate.test.js +0 -127
  5. package/dist/mcp/tools/db.test.d.ts +0 -1
  6. package/dist/mcp/tools/db.test.js +0 -221
  7. package/dist/mcp/tools/env.test.d.ts +0 -1
  8. package/dist/mcp/tools/env.test.js +0 -156
  9. package/dist/mcp/tools/project.test.d.ts +0 -1
  10. package/dist/mcp/tools/project.test.js +0 -188
  11. package/dist/utils/config-report.test.d.ts +0 -1
  12. package/dist/utils/config-report.test.js +0 -18
  13. package/dist/utils/env-compatibility.test.d.ts +0 -1
  14. package/dist/utils/env-compatibility.test.js +0 -23
  15. package/dist/utils/env-schema-parser.test.d.ts +0 -1
  16. package/dist/utils/env-schema-parser.test.js +0 -11
  17. package/dist/utils/git.test.d.ts +0 -1
  18. package/dist/utils/git.test.js +0 -77
  19. package/dist/utils/health-render.test.d.ts +0 -1
  20. package/dist/utils/health-render.test.js +0 -18
  21. package/dist/utils/live-db-diff.test.d.ts +0 -1
  22. package/dist/utils/live-db-diff.test.js +0 -29
  23. package/dist/utils/manifest.test.d.ts +0 -1
  24. package/dist/utils/manifest.test.js +0 -107
  25. package/dist/utils/patchers.test.d.ts +0 -1
  26. package/dist/utils/patchers.test.js +0 -647
  27. package/dist/utils/project-env.test.d.ts +0 -1
  28. package/dist/utils/project-env.test.js +0 -47
  29. package/dist/utils/project.test.d.ts +0 -1
  30. package/dist/utils/project.test.js +0 -123
  31. package/dist/utils/schema-parity.test.d.ts +0 -1
  32. package/dist/utils/schema-parity.test.js +0 -27
  33. package/dist/utils/schema-parser.test.d.ts +0 -1
  34. package/dist/utils/schema-parser.test.js +0 -59
package/README.md CHANGED
@@ -1,8 +1,27 @@
1
1
  # @codapult/cli
2
2
 
3
+ [![CI](https://github.com/codapult/codapult-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/codapult/codapult-cli/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/@codapult/cli?logo=npm)](https://www.npmjs.com/package/@codapult/cli)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+ [![Node.js >=20.19](https://img.shields.io/badge/node-%3E%3D20.19-339933.svg?logo=node.js&logoColor=white)](package.json)
7
+
3
8
  CLI tool for managing [Codapult](https://codapult.dev) SaaS projects, with the universal
4
9
  `@codapult/guard` architecture guard built in for AI-assisted development.
5
10
 
11
+ `@codapult/cli` is the open-source Codapult integration layer: a CLI and MCP server for
12
+ Codapult-based SaaS projects. It combines project setup, updates, plugins, database and
13
+ deployment tooling with the standalone Guard engine.
14
+
15
+ For a non-Codapult JavaScript or TypeScript project, install
16
+ [`@codapult/guard`](https://github.com/codapult/codapult-guard) directly. The CLI does not make
17
+ Guard universal by adding Codapult assumptions to it; it connects the Codapult-specific tools to
18
+ the same published Guard package through a thin adapter.
19
+
20
+ | Package | Use it when |
21
+ | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
22
+ | [`@codapult/guard`](https://github.com/codapult/codapult-guard) | You need architecture guardrails, project memory, MCP, and AI-agent verification in any JS/TS project. |
23
+ | `@codapult/cli` | You are building a Codapult SaaS and also need setup, plugins, database, environment, and deployment workflows. |
24
+
6
25
  ## Installation
7
26
 
8
27
  This is the maintained CLI package used by Codapult projects. Buyers normally invoke the published package through `npx` or the generated MCP configuration; they do not clone or build this repository. The CLI also powers Codapult MCP, exposing project-aware tools, resources, and prompt templates to compatible AI coding clients. The development and release sections below are for Codapult maintainers.
@@ -85,6 +104,7 @@ tests, SAST, or a general PR-review service.
85
104
  - `codapult guard check --changed` — check new architecture violations
86
105
  - `codapult guard audit` — inspect the complete current state, including baseline findings
87
106
  - `codapult guard review` — prepare a bounded diff and project-context packet for an AI reviewer
107
+ - `codapult guard impact <files...>` — explain dependencies, transitive dependents, capabilities, and relevant contracts
88
108
  - `codapult guard verify` — run Guard verification and configured project checks
89
109
  - `codapult guard doctor` — diagnose missing or invalid Guard artifacts
90
110
  - `codapult guard rules ...` — approve proposed rules
@@ -99,8 +119,11 @@ pnpm exec codapult-guard init
99
119
  ```
100
120
 
101
121
  The Codapult CLI adapter and the standalone Guard package share the same implementation; Guard
102
- logic is not duplicated in this repository. See the [Guard documentation](https://github.com/codapult/codapult-guard/tree/main/docs)
103
- for the full lifecycle, contracts, AI-agent workflow, MCP tools, and CI example.
122
+ logic is not duplicated in this repository. This section documents only the Codapult-specific
123
+ entrypoints. The standalone [Guard README](https://github.com/codapult/codapult-guard) and
124
+ [Guard documentation](https://github.com/codapult/codapult-guard/tree/main/docs) are the source of
125
+ truth for the complete lifecycle, contracts, impact analysis, AI-agent workflow, MCP tools, CI,
126
+ and current Guard capabilities.
104
127
 
105
128
  ### AI Integration
106
129
 
@@ -180,18 +203,18 @@ The CLI includes an MCP (Model Context Protocol) server with 39 tools, 12 resour
180
203
 
181
204
  #### Architecture Guard
182
205
 
183
- | Tool | Description |
184
- | -------------------------------- | ---------------------------------------------------------------------- |
185
- | `codapult_guard_init` | Discover the project and create Guard state and an initial baseline. |
186
- | `codapult_guard_context` | Return project architecture context for an AI agent. |
187
- | `codapult_guard_propose` | Generate evidence-based rule and contract proposals. |
188
- | `codapult_guard_proposal_decide` | Approve or reject proposed Guard policy. |
189
- | `codapult_guard_check` | Check active Guard policy against the project or changed files. |
190
- | `codapult_guard_audit` | Run a complete Guard scan, including baseline-suppressed findings. |
191
- | `codapult_guard_review` | Prepare a bounded semantic-review packet from the current diff. |
192
- | `codapult_guard_verify` | Run Guard, project checks, adapters, and contract verification. |
193
- | `codapult_guard_impact` | Analyze affected modules and architecture impact paths. |
194
- | `codapult_guard_explain` | Explain Guard findings and project-specific architectural constraints. |
206
+ | Tool | Description |
207
+ | -------------------------------- | ---------------------------------------------------------------------------------------------------- |
208
+ | `codapult_guard_init` | Discover the project and create Guard state and an initial baseline. |
209
+ | `codapult_guard_context` | Return project architecture context for an AI agent. |
210
+ | `codapult_guard_propose` | Generate evidence-based rule and contract proposals. |
211
+ | `codapult_guard_proposal_decide` | Approve or reject proposed Guard policy. |
212
+ | `codapult_guard_check` | Check active Guard policy against the project or changed files. |
213
+ | `codapult_guard_audit` | Run a complete Guard scan, including baseline-suppressed findings. |
214
+ | `codapult_guard_review` | Prepare a bounded semantic-review packet from the current diff. |
215
+ | `codapult_guard_verify` | Run Guard, project checks, adapters, and contract verification. |
216
+ | `codapult_guard_impact` | Analyze dependencies, transitive dependents, capabilities, contracts, and architecture impact paths. |
217
+ | `codapult_guard_explain` | Explain Guard findings and project-specific architectural constraints. |
195
218
 
196
219
  Mutating MCP tools support `dry_run` where applicable. The tool returns the planned operations without writing project files, changing environment files, running migrations, or applying database changes. `codapult_env_read` masks sensitive values by default; `show_secrets: true` is optional and returns a security warning.
197
220
 
@@ -233,6 +256,9 @@ pnpm lint # lint
233
256
  pnpm typecheck # type-check without emitting
234
257
  ```
235
258
 
259
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the public repository workflow and
260
+ [SECURITY.md](SECURITY.md) for vulnerability reporting and safe CLI usage.
261
+
236
262
  ## Releasing
237
263
 
238
264
  Releases are managed with [release-it](https://github.com/release-it/release-it). The workflow:
@@ -241,9 +267,9 @@ Releases are managed with [release-it](https://github.com/release-it/release-it)
241
267
 
242
268
  ```shell
243
269
  pnpm run release # interactive — prompts for version bump type
244
- pnpm run release -- patch # non-interactive patch bump (0.1.0 → 0.1.1)
245
- pnpm run release -- minor # minor bump (0.1.0 → 0.2.0)
246
- pnpm run release -- major # major bump (0.1.0 → 1.0.0)
270
+ pnpm run release -- patch # non-interactive patch bump (0.18.1 → 0.18.2)
271
+ pnpm run release -- minor # minor bump (0.18.1 → 0.19.0)
272
+ pnpm run release -- major # major bump (0.18.1 → 1.0.0)
247
273
  ```
248
274
 
249
275
  2. `release-it` will automatically:
@@ -253,8 +279,11 @@ pnpm run release -- major # major bump (0.1.0 → 1.0.0)
253
279
  - Commit the changes (`chore: release v<version>`)
254
280
  - Create a Git tag (`v<version>`)
255
281
  - Push the commit and tag to `origin`
282
+ - Create a published GitHub Release for the tag
256
283
 
257
- 3. The `v*` tag push triggers the **Publish** GitHub Actions workflow, which builds and publishes the package to npm.
284
+ 3. The published GitHub Release triggers `.github/workflows/release.yml`, which checks out the
285
+ exact tag, validates the package, and publishes it to npm. GitHub Release is the reviewed
286
+ release record; npm remains the distribution channel.
258
287
 
259
288
  ### Dry run
260
289
 
@@ -267,6 +296,8 @@ pnpm run release -- --dry-run
267
296
  ### Prerequisites
268
297
 
269
298
  - npm [trusted publishing](https://docs.npmjs.com/trusted-publishers) must be configured for the `@codapult/cli` package on npmjs.com.
299
+ - The npm trusted publisher must point to this repository's `.github/workflows/release.yml` workflow
300
+ and allow direct `npm publish`.
270
301
  - Before publishing a CLI release, the standalone `codapult-guard` package must be available on npm and the CLI dependency must use its published version rather than the pre-release workspace `file:` dependency.
271
302
  - Commit messages should follow [Conventional Commits](https://www.conventionalcommits.org/) for meaningful changelogs (e.g. `feat:`, `fix:`, `chore:`).
272
303
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@codapult/cli",
3
- "version": "0.18.1",
4
- "description": "Codapult CLI — manage, update, and diagnose your Codapult SaaS project",
3
+ "version": "0.19.1",
4
+ "description": "Open-source CLI and MCP server for Codapult SaaS projects, with architecture guardrails for AI-assisted development",
5
5
  "license": "MIT",
6
6
  "packageManager": "pnpm@11.22.0+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621",
7
7
  "engines": {
@@ -15,7 +15,8 @@
15
15
  "dist"
16
16
  ],
17
17
  "scripts": {
18
- "build": "tsc",
18
+ "clean": "node scripts/clean-dist.mjs",
19
+ "build": "pnpm clean && tsc -p tsconfig.build.json",
19
20
  "dev": "tsc --watch",
20
21
  "lint": "eslint .",
21
22
  "lint:fix": "eslint --fix .",
@@ -26,7 +27,7 @@
26
27
  "test:coverage": "vitest run --coverage",
27
28
  "test:watch": "vitest",
28
29
  "typecheck": "tsc --noEmit",
29
- "prepublishOnly": "tsc",
30
+ "prepublishOnly": "tsc -p tsconfig.build.json",
30
31
  "release": "release-it"
31
32
  },
32
33
  "keywords": [
@@ -34,7 +35,13 @@
34
35
  "saas",
35
36
  "boilerplate",
36
37
  "cli",
37
- "nextjs"
38
+ "nextjs",
39
+ "mcp",
40
+ "ai-agents",
41
+ "architecture",
42
+ "guardrails",
43
+ "drizzle",
44
+ "deployment"
38
45
  ],
39
46
  "homepage": "https://codapult.dev",
40
47
  "repository": {
@@ -1 +0,0 @@
1
- export {};
@@ -1,127 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- vi.mock('node:fs');
3
- vi.mock('../utils/project.js', async (importOriginal) => ({
4
- findProjectRoot: vi.fn(),
5
- checkProjectRoot: vi.fn((await importOriginal()).checkProjectRoot),
6
- }));
7
- vi.mock('../utils/ui.js', () => ({
8
- heading: vi.fn(),
9
- success: vi.fn(),
10
- fail: vi.fn(),
11
- info: vi.fn(),
12
- dim: vi.fn(),
13
- }));
14
- const { existsSync, writeFileSync, mkdirSync } = await import('node:fs');
15
- const { checkProjectRoot, findProjectRoot } = await import('../utils/project.js');
16
- const { generatePageCommand, generateApiCommand, generateActionCommand, generatePluginCommand } = await import('./generate.js');
17
- const mockedFindRoot = vi.mocked(findProjectRoot);
18
- const mockedCheckRoot = vi.mocked(checkProjectRoot);
19
- const mockedExists = vi.mocked(existsSync);
20
- const mockedWrite = vi.mocked(writeFileSync);
21
- const mockedMkdir = vi.mocked(mkdirSync);
22
- beforeEach(() => {
23
- vi.resetAllMocks();
24
- vi.spyOn(process, 'exit').mockImplementation(() => {
25
- throw new Error('process.exit');
26
- });
27
- });
28
- describe('generatePageCommand', () => {
29
- it('generates a dashboard page file with correct naming', () => {
30
- mockedCheckRoot.mockReturnValue('/project');
31
- mockedExists.mockReturnValue(false);
32
- generatePageCommand('userSettings');
33
- expect(mockedMkdir).toHaveBeenCalled();
34
- expect(mockedWrite).toHaveBeenCalledTimes(1);
35
- const [path, content] = mockedWrite.mock.calls[0];
36
- expect(path).toContain('user-settings/page.tsx');
37
- expect(content).toContain('UserSettingsPage');
38
- expect(content).toContain("title: 'User Settings — Codapult'");
39
- expect(content).toContain('getAppSession');
40
- });
41
- it('converts camelCase to kebab-case in path', () => {
42
- mockedCheckRoot.mockReturnValue('/project');
43
- mockedExists.mockReturnValue(false);
44
- generatePageCommand('myDashboard');
45
- const [path] = mockedWrite.mock.calls[0];
46
- expect(path).toContain('my-dashboard/page.tsx');
47
- });
48
- it('does not overwrite existing page', () => {
49
- mockedCheckRoot.mockReturnValue('/project');
50
- mockedExists.mockReturnValue(true);
51
- generatePageCommand('analytics');
52
- expect(mockedWrite).not.toHaveBeenCalled();
53
- });
54
- it('exits when not in a Codapult project', () => {
55
- mockedFindRoot.mockReturnValue(undefined);
56
- expect(() => generatePageCommand('test')).toThrow('process.exit');
57
- expect(process.exit).toHaveBeenCalledWith(1);
58
- });
59
- });
60
- describe('generateApiCommand', () => {
61
- it('generates an API route with auth and rate limiting', () => {
62
- mockedCheckRoot.mockReturnValue('/project');
63
- mockedExists.mockReturnValue(false);
64
- generateApiCommand('webhooks');
65
- const [path, content] = mockedWrite.mock.calls[0];
66
- expect(path).toContain('api/webhooks/route.ts');
67
- expect(content).toContain('getAppSession');
68
- expect(content).toContain('checkRateLimit');
69
- expect(content).toContain('webhooksSchema');
70
- expect(content).toContain('export async function GET()');
71
- expect(content).toContain('export async function POST(req: Request)');
72
- });
73
- it('converts multi-word names to kebab-case', () => {
74
- mockedCheckRoot.mockReturnValue('/project');
75
- mockedExists.mockReturnValue(false);
76
- generateApiCommand('userBilling');
77
- const [path, content] = mockedWrite.mock.calls[0];
78
- expect(path).toContain('api/user-billing/route.ts');
79
- expect(content).toContain('userBillingSchema');
80
- });
81
- });
82
- describe('generateActionCommand', () => {
83
- it('generates a server action file', () => {
84
- mockedCheckRoot.mockReturnValue('/project');
85
- mockedExists.mockReturnValue(false);
86
- generateActionCommand('updateProfile');
87
- const [path, content] = mockedWrite.mock.calls[0];
88
- expect(path).toContain('actions/update-profile.ts');
89
- expect(content).toContain("'use server'");
90
- expect(content).toContain('updateProfileSchema');
91
- expect(content).toContain('updateProfileAction');
92
- expect(content).toContain('getAppSession');
93
- expect(content).toContain('checkRateLimit');
94
- expect(content).toContain("revalidatePath('/dashboard/update-profile')");
95
- });
96
- });
97
- describe('generatePluginCommand', () => {
98
- it('scaffolds a complete plugin directory', () => {
99
- mockedCheckRoot.mockReturnValue('/project');
100
- mockedExists.mockReturnValue(false);
101
- generatePluginCommand('my-widget');
102
- // package.json, tsconfig.json, src/index.ts, codapult-plugin.json, .gitignore, README.md
103
- expect(mockedWrite).toHaveBeenCalledTimes(6);
104
- expect(mockedMkdir).toHaveBeenCalled();
105
- const writtenPaths = mockedWrite.mock.calls.map(([p]) => p);
106
- expect(writtenPaths.some((p) => p.includes('package.json'))).toBe(true);
107
- expect(writtenPaths.some((p) => p.includes('src/index.ts'))).toBe(true);
108
- expect(writtenPaths.some((p) => p.includes('codapult-plugin.json'))).toBe(true);
109
- });
110
- it('generates correct plugin name references', () => {
111
- mockedCheckRoot.mockReturnValue('/project');
112
- mockedExists.mockReturnValue(false);
113
- generatePluginCommand('dataSync');
114
- const indexWrite = mockedWrite.mock.calls.find(([p]) => p.includes('src/index.ts'));
115
- expect(indexWrite).toBeDefined();
116
- const content = indexWrite[1];
117
- expect(content).toContain('dataSyncPlugin');
118
- expect(content).toContain("name: 'data-sync'");
119
- expect(content).toContain("label: 'DataSync'");
120
- });
121
- it('exits when target directory already exists', () => {
122
- mockedCheckRoot.mockReturnValue('/project');
123
- mockedExists.mockReturnValue(true);
124
- expect(() => generatePluginCommand('existing')).toThrow('process.exit');
125
- expect(process.exit).toHaveBeenCalledWith(1);
126
- });
127
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,221 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { ENV_FILE_NAME } from '../../utils/project-env.js';
3
- vi.mock('node:fs');
4
- vi.mock('node:child_process');
5
- vi.mock('../../utils/project.js', () => ({
6
- checkProjectRoot: vi.fn(),
7
- readProjectFile: vi.fn(),
8
- }));
9
- const { existsSync, readdirSync } = await import('node:fs');
10
- const { checkProjectRoot, readProjectFile } = await import('../../utils/project.js');
11
- const { registerDbTools } = await import('./db.js');
12
- const mockedFindRoot = vi.mocked(checkProjectRoot);
13
- const mockedReadProject = vi.mocked(readProjectFile);
14
- const mockedExists = vi.mocked(existsSync);
15
- const mockedReaddir = vi.mocked(readdirSync);
16
- beforeEach(() => {
17
- vi.resetAllMocks();
18
- mockedFindRoot.mockReturnValue('/project');
19
- });
20
- function createMockServer() {
21
- const tools = [];
22
- const registerTool = vi.fn((name, _opts, handler) => {
23
- tools.push({ name, handler });
24
- });
25
- return { registerTool, tools };
26
- }
27
- describe('registerDbTools', () => {
28
- it('registers database inspection and mutation tools', () => {
29
- const server = createMockServer();
30
- registerDbTools(server);
31
- expect(server.tools).toHaveLength(9);
32
- expect(server.tools.map((t) => t.name)).toEqual([
33
- 'codapult_db_generate',
34
- 'codapult_db_migration_diff',
35
- 'codapult_db_push',
36
- 'codapult_db_seed',
37
- 'codapult_db_get_tables',
38
- 'codapult_db_get_table_info',
39
- 'codapult_db_status',
40
- 'codapult_db_live_diff',
41
- 'codapult_db_schema_diff',
42
- ]);
43
- });
44
- describe('codapult_db_get_tables', () => {
45
- it('parses schema and returns table summary', () => {
46
- const server = createMockServer();
47
- registerDbTools(server);
48
- const schema = `
49
- import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';
50
-
51
- export const user = sqliteTable('user', {
52
- id: text('id').primaryKey(),
53
- name: text('name').notNull(),
54
- age: integer('age'),
55
- });
56
-
57
- export const post = sqliteTable('post', {
58
- id: text('id').primaryKey(),
59
- title: text('title').notNull(),
60
- userId: text('user_id').references(() => user.id),
61
- });
62
- `;
63
- mockedReadProject.mockReturnValue(schema);
64
- const handler = server.tools.find((t) => t.name === 'codapult_db_get_tables').handler;
65
- const result = handler({});
66
- const parsed = JSON.parse(result.content[0].text);
67
- expect(parsed.provider).toBe('turso');
68
- expect(parsed.schemaPath).toBe('src/lib/db/schema.ts');
69
- expect(parsed.tables).toHaveLength(2);
70
- expect(parsed.tables[0].name).toBe('user');
71
- expect(parsed.tables[0].columns).toBe(3);
72
- expect(parsed.tables[1].name).toBe('post');
73
- expect(parsed.tables[1].columns).toBe(3);
74
- });
75
- it('returns error when schema file not found', () => {
76
- const server = createMockServer();
77
- registerDbTools(server);
78
- mockedReadProject.mockReturnValue(undefined);
79
- const handler = server.tools.find((t) => t.name === 'codapult_db_get_tables').handler;
80
- const result = handler({});
81
- expect(result.isError).toBe(true);
82
- expect(result.content[0].text).toContain('not found');
83
- });
84
- });
85
- describe('codapult_db_get_table_info', () => {
86
- it('returns detailed info for a specific table', () => {
87
- const server = createMockServer();
88
- registerDbTools(server);
89
- const schema = `
90
- export const user = sqliteTable('user', {
91
- id: text('id').primaryKey(),
92
- email: text('email').notNull().unique(),
93
- createdAt: integer('created_at').$defaultFn(() => new Date()),
94
- });
95
- `;
96
- mockedReadProject.mockReturnValue(schema);
97
- const handler = server.tools.find((t) => t.name === 'codapult_db_get_table_info').handler;
98
- const result = handler({ table: 'user' });
99
- const parsed = JSON.parse(result.content[0].text);
100
- expect(parsed.name).toBe('user');
101
- expect(parsed.columns).toHaveLength(3);
102
- const idCol = parsed.columns.find((c) => c.name === 'id');
103
- expect(idCol.type).toBe('text');
104
- expect(idCol.constraints).toContain('PRIMARY KEY');
105
- const emailCol = parsed.columns.find((c) => c.name === 'email');
106
- expect(emailCol.constraints).toContain('NOT NULL');
107
- expect(emailCol.constraints).toContain('UNIQUE');
108
- const createdAtCol = parsed.columns.find((c) => c.name === 'createdAt');
109
- expect(createdAtCol.constraints).toContain('DEFAULT');
110
- });
111
- it('returns error for non-existent table', () => {
112
- const server = createMockServer();
113
- registerDbTools(server);
114
- const schema = `export const user = sqliteTable('user', { id: text('id') });`;
115
- mockedReadProject.mockReturnValue(schema);
116
- const handler = server.tools.find((t) => t.name === 'codapult_db_get_table_info').handler;
117
- const result = handler({ table: 'nonexistent' });
118
- expect(result.isError).toBe(true);
119
- expect(result.content[0].text).toContain('not found');
120
- expect(result.content[0].text).toContain('user');
121
- });
122
- });
123
- describe('codapult_db_status', () => {
124
- it('returns provider, table count, and migration counts', () => {
125
- const server = createMockServer();
126
- registerDbTools(server);
127
- const envContent = 'DB_PROVIDER=turso\nOTHER=val';
128
- const schema = `export const user = sqliteTable('user', { id: text('id') });`;
129
- mockedReadProject.mockImplementation((_root, path) => {
130
- if (path === ENV_FILE_NAME)
131
- return envContent;
132
- if (path === 'src/lib/db/schema.ts')
133
- return schema;
134
- return undefined;
135
- });
136
- mockedExists.mockReturnValue(true);
137
- mockedReaddir.mockReturnValue(['0001.sql', '0002.sql', 'meta']);
138
- const handler = server.tools.find((t) => t.name === 'codapult_db_status').handler;
139
- const result = handler({});
140
- const parsed = JSON.parse(result.content[0].text);
141
- expect(parsed.provider).toBe('turso');
142
- expect(parsed.tableCount).toBe(1);
143
- expect(parsed.sqliteMigrations).toBe(2);
144
- });
145
- it('defaults provider to turso when not set', () => {
146
- const server = createMockServer();
147
- registerDbTools(server);
148
- mockedReadProject.mockImplementation((_root, path) => {
149
- if (path === ENV_FILE_NAME)
150
- return '';
151
- if (path === 'src/lib/db/schema.ts')
152
- return '';
153
- return undefined;
154
- });
155
- mockedExists.mockReturnValue(false);
156
- const handler = server.tools.find((t) => t.name === 'codapult_db_status').handler;
157
- const result = handler({});
158
- const parsed = JSON.parse(result.content[0].text);
159
- expect(parsed.provider).toBe('turso');
160
- });
161
- it('can read provider from process env', () => {
162
- const server = createMockServer();
163
- registerDbTools(server);
164
- vi.stubEnv('DB_PROVIDER', 'postgres');
165
- mockedReadProject.mockImplementation((_root, path) => {
166
- if (path === 'src/lib/db/schema.ts')
167
- return '';
168
- return undefined;
169
- });
170
- mockedExists.mockReturnValue(false);
171
- const handler = server.tools.find((t) => t.name === 'codapult_db_status').handler;
172
- const result = handler({ env_source: 'process' });
173
- const parsed = JSON.parse(result.content[0].text);
174
- expect(parsed.provider).toBe('postgres');
175
- });
176
- });
177
- describe('codapult_db_schema_diff', () => {
178
- it('returns an ok parity report for matching schemas', () => {
179
- const server = createMockServer();
180
- registerDbTools(server);
181
- const sqlite = `export const user = sqliteTable('user', { id: text('id') });`;
182
- const postgres = `export const user = pgTable('user', { id: text('id') });`;
183
- mockedReadProject.mockImplementation((_root, path) => {
184
- if (path === 'src/lib/db/schema.ts')
185
- return sqlite;
186
- if (path === 'src/lib/db/schema-pg.ts')
187
- return postgres;
188
- return undefined;
189
- });
190
- const handler = server.tools.find((t) => t.name === 'codapult_db_schema_diff').handler;
191
- const result = handler({});
192
- const parsed = JSON.parse(result.content[0].text);
193
- expect(result.isError).toBe(false);
194
- expect(parsed.status).toBe('ok');
195
- expect(parsed.identical).toBe(true);
196
- expect(parsed.differences).toEqual([]);
197
- });
198
- it('returns an error result for missing tables', () => {
199
- const server = createMockServer();
200
- registerDbTools(server);
201
- mockedReadProject.mockImplementation((_root, path) => {
202
- if (path === 'src/lib/db/schema.ts') {
203
- return `export const user = sqliteTable('user', { id: text('id') });`;
204
- }
205
- if (path === 'src/lib/db/schema-pg.ts') {
206
- return `export const post = pgTable('post', { id: text('id') });`;
207
- }
208
- return undefined;
209
- });
210
- const handler = server.tools.find((t) => t.name === 'codapult_db_schema_diff').handler;
211
- const result = handler({});
212
- const parsed = JSON.parse(result.content[0].text);
213
- expect(result.isError).toBe(true);
214
- expect(parsed.status).toBe('fail');
215
- expect(parsed.differences.map((difference) => difference.issue)).toEqual([
216
- 'missing_in_postgres',
217
- 'missing_in_sqlite',
218
- ]);
219
- });
220
- });
221
- });
@@ -1 +0,0 @@
1
- export {};