bonescript-compiler 0.3.0 → 0.4.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 (52) hide show
  1. package/dist/commands/compile.js +42 -10
  2. package/dist/commands/compile.js.map +1 -1
  3. package/dist/commands/init.d.ts +1 -1
  4. package/dist/commands/init.js +29 -2
  5. package/dist/commands/init.js.map +1 -1
  6. package/dist/emit_capability.js +61 -7
  7. package/dist/emit_capability.js.map +1 -1
  8. package/dist/emit_composition.js +37 -3
  9. package/dist/emit_composition.js.map +1 -1
  10. package/dist/emit_events.d.ts +1 -0
  11. package/dist/emit_events.js +68 -1
  12. package/dist/emit_events.js.map +1 -1
  13. package/dist/emit_full.js +33 -0
  14. package/dist/emit_full.js.map +1 -1
  15. package/dist/emit_models.d.ts +12 -0
  16. package/dist/emit_models.js +171 -0
  17. package/dist/emit_models.js.map +1 -0
  18. package/dist/emit_openapi.d.ts +9 -0
  19. package/dist/emit_openapi.js +308 -0
  20. package/dist/emit_openapi.js.map +1 -0
  21. package/dist/emit_router.js +19 -4
  22. package/dist/emit_router.js.map +1 -1
  23. package/dist/emit_tests.js +37 -0
  24. package/dist/emit_tests.js.map +1 -1
  25. package/dist/emitter.js +34 -5
  26. package/dist/emitter.js.map +1 -1
  27. package/dist/lowering.js +16 -1
  28. package/dist/lowering.js.map +1 -1
  29. package/dist/lowering_channels.d.ts +1 -1
  30. package/dist/lowering_channels.js +2 -2
  31. package/dist/lowering_channels.js.map +1 -1
  32. package/dist/typechecker.js +32 -13
  33. package/dist/typechecker.js.map +1 -1
  34. package/dist/verifier.d.ts +5 -0
  35. package/dist/verifier.js +140 -2
  36. package/dist/verifier.js.map +1 -1
  37. package/package.json +1 -1
  38. package/src/commands/compile.ts +41 -10
  39. package/src/commands/init.ts +28 -2
  40. package/src/emit_capability.ts +61 -6
  41. package/src/emit_composition.ts +36 -3
  42. package/src/emit_events.ts +70 -0
  43. package/src/emit_full.ts +36 -1
  44. package/src/emit_models.ts +176 -0
  45. package/src/emit_openapi.ts +318 -0
  46. package/src/emit_router.ts +18 -4
  47. package/src/emit_tests.ts +41 -0
  48. package/src/emitter.ts +592 -566
  49. package/src/lowering.ts +19 -1
  50. package/src/lowering_channels.ts +2 -2
  51. package/src/typechecker.ts +606 -591
  52. package/src/verifier.ts +495 -348
package/src/verifier.ts CHANGED
@@ -1,348 +1,495 @@
1
- /**
2
- * BoneScript Verifier — Stage 7 of the compilation pipeline.
3
- * Implements spec/07_IR_SPEC.md §5 (IR Validation Rules).
4
- *
5
- * Checks:
6
- * - V001: Every dependency target exists as a module
7
- * - V002: Every event source exists as a module
8
- * - V003: State machine transitions reference valid events
9
- * - V004: No circular dependencies between modules
10
- * - V005: Every method's preconditions reference accessible fields
11
- * - V006: Every effect targets a field that exists
12
- * - V007: Every model has a primary key field
13
- * - V008: Every index references fields that exist
14
- * - V009: No duplicate module ids
15
- * - V010: No duplicate event ids
16
- * - V011: Every authenticated method's module depends on auth
17
- * - V012: Resolution map is complete
18
- *
19
- * Also validates generated code:
20
- * - All TypeScript files have balanced braces
21
- * - All SQL files have valid CREATE TABLE structure
22
- * - All imports reference existing files
23
- */
24
-
25
- import * as IR from "./ir";
26
- import { EmittedFile } from "./emitter";
27
-
28
- export interface VerifyIssue {
29
- code: string;
30
- severity: "error" | "warning";
31
- message: string;
32
- location: string;
33
- }
34
-
35
- export interface VerifyResult {
36
- passed: boolean;
37
- issues: VerifyIssue[];
38
- }
39
-
40
- export class Verifier {
41
- verify(system: IR.IRSystem, files: EmittedFile[]): VerifyResult {
42
- const issues: VerifyIssue[] = [];
43
-
44
- // ─── IR Validation ─────────────────────────────────────────────────────
45
-
46
- this.checkDependencies(system, issues);
47
- this.checkDuplicateIds(system, issues);
48
- this.checkModels(system, issues);
49
- this.checkStateMachines(system, issues);
50
- this.checkCircularDeps(system, issues);
51
-
52
- // ─── Generated Code Validation ─────────────────────────────────────────
53
-
54
- this.checkTypeScriptSyntax(files, issues);
55
- this.checkSqlSyntax(files, issues);
56
- this.checkImports(files, issues);
57
-
58
- return {
59
- passed: issues.filter(i => i.severity === "error").length === 0,
60
- issues,
61
- };
62
- }
63
-
64
- // ─── V001: Dependency targets exist ──────────────────────────────────────
65
-
66
- private checkDependencies(system: IR.IRSystem, issues: VerifyIssue[]) {
67
- const moduleIds = new Set(system.modules.map(m => m.id));
68
- for (const mod of system.modules) {
69
- for (const dep of mod.dependencies) {
70
- if (!moduleIds.has(dep)) {
71
- issues.push({
72
- code: "V001",
73
- severity: "error",
74
- message: `Module '${mod.name}' depends on '${dep}' which does not exist`,
75
- location: mod.id,
76
- });
77
- }
78
- }
79
- }
80
- }
81
-
82
- // ─── V009/V010: No duplicate IDs ─────────────────────────────────────────
83
-
84
- private checkDuplicateIds(system: IR.IRSystem, issues: VerifyIssue[]) {
85
- const moduleIds = new Set<string>();
86
- for (const mod of system.modules) {
87
- if (moduleIds.has(mod.id)) {
88
- issues.push({
89
- code: "V009",
90
- severity: "error",
91
- message: `Duplicate module id: ${mod.id} (${mod.name})`,
92
- location: mod.id,
93
- });
94
- }
95
- moduleIds.add(mod.id);
96
- }
97
-
98
- const eventIds = new Set<string>();
99
- for (const ev of system.events) {
100
- if (eventIds.has(ev.id)) {
101
- issues.push({
102
- code: "V010",
103
- severity: "error",
104
- message: `Duplicate event id: ${ev.id} (${ev.name})`,
105
- location: ev.id,
106
- });
107
- }
108
- eventIds.add(ev.id);
109
- }
110
- }
111
-
112
- // ─── V007/V008: Model validation ─────────────────────────────────────────
113
-
114
- private checkModels(system: IR.IRSystem, issues: VerifyIssue[]) {
115
- for (const mod of system.modules) {
116
- for (const model of mod.models) {
117
- // V007: Primary key exists
118
- const pkField = model.fields.find(f => f.name === model.primary_key);
119
- if (!pkField) {
120
- issues.push({
121
- code: "V007",
122
- severity: "error",
123
- message: `Model '${model.name}' primary key '${model.primary_key}' not found in fields`,
124
- location: `${mod.id}.${model.name}`,
125
- });
126
- }
127
-
128
- // V008: Index fields exist
129
- const fieldNames = new Set(model.fields.map(f => f.name));
130
- for (const idx of model.indexes) {
131
- for (const field of idx.fields) {
132
- if (!fieldNames.has(field)) {
133
- issues.push({
134
- code: "V008",
135
- severity: "warning",
136
- message: `Index on '${model.name}' references non-existent field '${field}'`,
137
- location: `${mod.id}.${model.name}`,
138
- });
139
- }
140
- }
141
- }
142
- }
143
- }
144
- }
145
-
146
- // ─── V003: State machine transitions ──────────────────────────────────────
147
-
148
- private checkStateMachines(system: IR.IRSystem, issues: VerifyIssue[]) {
149
- for (const mod of system.modules) {
150
- for (const sm of mod.state_machines) {
151
- const validStates = new Set(sm.states);
152
-
153
- // Initial state must be valid
154
- if (!validStates.has(sm.initial)) {
155
- issues.push({
156
- code: "V003",
157
- severity: "error",
158
- message: `State machine '${sm.entity}' initial state '${sm.initial}' not in states list`,
159
- location: `${mod.id}.${sm.entity}`,
160
- });
161
- }
162
-
163
- // All transition targets must be valid
164
- for (const t of sm.transitions) {
165
- if (!validStates.has(t.from)) {
166
- issues.push({
167
- code: "V003",
168
- severity: "error",
169
- message: `Transition from '${t.from}' — state not declared in '${sm.entity}'`,
170
- location: `${mod.id}.${sm.entity}`,
171
- });
172
- }
173
- if (!validStates.has(t.to)) {
174
- issues.push({
175
- code: "V003",
176
- severity: "error",
177
- message: `Transition to '${t.to}' — state not declared in '${sm.entity}'`,
178
- location: `${mod.id}.${sm.entity}`,
179
- });
180
- }
181
- }
182
- }
183
- }
184
- }
185
-
186
- // ─── V004: Circular dependencies ──────────────────────────────────────────
187
-
188
- private checkCircularDeps(system: IR.IRSystem, issues: VerifyIssue[]) {
189
- const graph = new Map<string, string[]>();
190
- for (const mod of system.modules) {
191
- graph.set(mod.id, mod.dependencies);
192
- }
193
-
194
- const visited = new Set<string>();
195
- const inStack = new Set<string>();
196
-
197
- const dfs = (node: string, path: string[]): boolean => {
198
- if (inStack.has(node)) {
199
- const cycle = [...path.slice(path.indexOf(node)), node];
200
- const names = cycle.map(id => system.modules.find(m => m.id === id)?.name || id);
201
- issues.push({
202
- code: "V004",
203
- severity: "error",
204
- message: `Circular dependency: ${names.join(" → ")}`,
205
- location: node,
206
- });
207
- return true;
208
- }
209
- if (visited.has(node)) return false;
210
-
211
- visited.add(node);
212
- inStack.add(node);
213
-
214
- for (const dep of graph.get(node) || []) {
215
- if (graph.has(dep)) {
216
- dfs(dep, [...path, node]);
217
- }
218
- }
219
-
220
- inStack.delete(node);
221
- return false;
222
- };
223
-
224
- for (const [id] of graph) {
225
- if (!visited.has(id)) {
226
- dfs(id, []);
227
- }
228
- }
229
- }
230
-
231
- // ─── Generated TypeScript Validation ───────────────────────────────────────
232
-
233
- private checkTypeScriptSyntax(files: EmittedFile[], issues: VerifyIssue[]) {
234
- for (const file of files) {
235
- if (file.language !== "typescript") continue;
236
-
237
- // Check balanced braces
238
- let braceCount = 0;
239
- let parenCount = 0;
240
- let bracketCount = 0;
241
-
242
- for (const ch of file.content) {
243
- if (ch === "{") braceCount++;
244
- if (ch === "}") braceCount--;
245
- if (ch === "(") parenCount++;
246
- if (ch === ")") parenCount--;
247
- if (ch === "[") bracketCount++;
248
- if (ch === "]") bracketCount--;
249
- }
250
-
251
- if (braceCount !== 0) {
252
- issues.push({
253
- code: "GEN_TS_BRACES",
254
- severity: "error",
255
- message: `Unbalanced braces in ${file.path} (${braceCount > 0 ? "missing }" : "extra }"})`,
256
- location: file.path,
257
- });
258
- }
259
- if (parenCount !== 0) {
260
- issues.push({
261
- code: "GEN_TS_PARENS",
262
- severity: "warning",
263
- message: `Unbalanced parentheses in ${file.path}`,
264
- location: file.path,
265
- });
266
- }
267
- }
268
- }
269
-
270
- // ─── Generated SQL Validation ──────────────────────────────────────────────
271
-
272
- private checkSqlSyntax(files: EmittedFile[], issues: VerifyIssue[]) {
273
- for (const file of files) {
274
- if (file.language !== "sql") continue;
275
-
276
- // Check CREATE TABLE has matching parentheses
277
- if (file.content.includes("CREATE TABLE")) {
278
- const opens = (file.content.match(/\(/g) || []).length;
279
- const closes = (file.content.match(/\)/g) || []).length;
280
- if (opens !== closes) {
281
- issues.push({
282
- code: "GEN_SQL_PARENS",
283
- severity: "error",
284
- message: `Unbalanced parentheses in SQL: ${file.path}`,
285
- location: file.path,
286
- });
287
- }
288
- }
289
-
290
- // Check no empty CREATE TABLE
291
- if (file.content.match(/CREATE TABLE[^(]+\(\s*\)/)) {
292
- issues.push({
293
- code: "GEN_SQL_EMPTY",
294
- severity: "warning",
295
- message: `Empty CREATE TABLE in ${file.path}`,
296
- location: file.path,
297
- });
298
- }
299
- }
300
- }
301
-
302
- // ─── Import Resolution ─────────────────────────────────────────────────────
303
-
304
- private checkImports(files: EmittedFile[], issues: VerifyIssue[]) {
305
- const filePaths = new Set(files.map(f => f.path));
306
-
307
- for (const file of files) {
308
- if (file.language !== "typescript") continue;
309
-
310
- const importMatches = file.content.matchAll(/from\s+"([^"]+)"/g);
311
- for (const match of importMatches) {
312
- const importPath = match[1];
313
- // Skip node_modules imports
314
- if (!importPath.startsWith(".")) continue;
315
-
316
- // Resolve relative to file
317
- const dir = file.path.split("/").slice(0, -1).join("/");
318
- const resolved = resolvePath(dir, importPath) + ".ts";
319
-
320
- // Check if target exists in our file set
321
- if (!filePaths.has(resolved) && !filePaths.has(resolved.replace(".ts", "/index.ts"))) {
322
- // Not necessarily an error — could be importing from a parent project
323
- // Only warn for imports within src/
324
- if (importPath.startsWith("./") || importPath.startsWith("../")) {
325
- issues.push({
326
- code: "GEN_IMPORT",
327
- severity: "warning",
328
- message: `Import '${importPath}' in ${file.path} may not resolve (target: ${resolved})`,
329
- location: file.path,
330
- });
331
- }
332
- }
333
- }
334
- }
335
- }
336
- }
337
-
338
- function resolvePath(base: string, relative: string): string {
339
- const parts = base.split("/");
340
- const relParts = relative.split("/");
341
-
342
- for (const part of relParts) {
343
- if (part === "..") parts.pop();
344
- else if (part !== ".") parts.push(part);
345
- }
346
-
347
- return parts.join("/");
348
- }
1
+ /**
2
+ * BoneScript Verifier — Stage 7 of the compilation pipeline.
3
+ * Implements spec/07_IR_SPEC.md §5 (IR Validation Rules).
4
+ *
5
+ * Checks:
6
+ * - V001: Every dependency target exists as a module
7
+ * - V002: Every event source exists as a module
8
+ * - V003: State machine transitions reference valid events
9
+ * - V004: No circular dependencies between modules
10
+ * - V005: Every method's preconditions reference accessible fields
11
+ * - V006: Every effect targets a field that exists
12
+ * - V007: Every model has a primary key field
13
+ * - V008: Every index references fields that exist
14
+ * - V009: No duplicate module ids
15
+ * - V010: No duplicate event ids
16
+ * - V011: Every authenticated method's module depends on auth
17
+ * - V012: Resolution map is complete
18
+ *
19
+ * Also validates generated code:
20
+ * - All TypeScript files have balanced braces
21
+ * - All SQL files have valid CREATE TABLE structure
22
+ * - All imports reference existing files
23
+ */
24
+
25
+ import * as IR from "./ir";
26
+ import { EmittedFile } from "./emitter";
27
+
28
+ export interface VerifyIssue {
29
+ code: string;
30
+ severity: "error" | "warning";
31
+ message: string;
32
+ location: string;
33
+ }
34
+
35
+ export interface VerifyResult {
36
+ passed: boolean;
37
+ issues: VerifyIssue[];
38
+ }
39
+
40
+ export class Verifier {
41
+ verify(system: IR.IRSystem, files: EmittedFile[]): VerifyResult {
42
+ const issues: VerifyIssue[] = [];
43
+
44
+ // ─── IR Validation ────────────────────────────────────────────────────────
45
+ this.checkDependencies(system, issues);
46
+ this.checkEventSources(system, issues); // V002
47
+ this.checkDuplicateIds(system, issues);
48
+ this.checkModels(system, issues);
49
+ this.checkStateMachines(system, issues);
50
+ this.checkCircularDeps(system, issues);
51
+ this.checkPreconditions(system, issues); // V005
52
+ this.checkMethodEffects(system, issues); // V006
53
+ this.checkAuthDependencies(system, issues); // V011
54
+ this.checkResolutionMap(system, issues); // V012
55
+
56
+ // ─── Generated Code Validation ────────────────────────────────────────────
57
+ this.checkTypeScriptSyntax(files, issues);
58
+ this.checkSqlSyntax(files, issues);
59
+ this.checkImports(files, issues);
60
+
61
+ return {
62
+ passed: issues.filter(i => i.severity === "error").length === 0,
63
+ issues,
64
+ };
65
+ }
66
+
67
+ // ─── V001: Dependency targets exist ──────────────────────────────────────
68
+
69
+ private checkDependencies(system: IR.IRSystem, issues: VerifyIssue[]) {
70
+ const moduleIds = new Set(system.modules.map(m => m.id));
71
+ for (const mod of system.modules) {
72
+ for (const dep of mod.dependencies) {
73
+ if (!moduleIds.has(dep)) {
74
+ issues.push({
75
+ code: "V001",
76
+ severity: "error",
77
+ message: `Module '${mod.name}' depends on '${dep}' which does not exist`,
78
+ location: mod.id,
79
+ });
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ // ─── V009/V010: No duplicate IDs ─────────────────────────────────────────
86
+
87
+ private checkDuplicateIds(system: IR.IRSystem, issues: VerifyIssue[]) {
88
+ const moduleIds = new Set<string>();
89
+ for (const mod of system.modules) {
90
+ if (moduleIds.has(mod.id)) {
91
+ issues.push({
92
+ code: "V009",
93
+ severity: "error",
94
+ message: `Duplicate module id: ${mod.id} (${mod.name})`,
95
+ location: mod.id,
96
+ });
97
+ }
98
+ moduleIds.add(mod.id);
99
+ }
100
+
101
+ const eventIds = new Set<string>();
102
+ for (const ev of system.events) {
103
+ if (eventIds.has(ev.id)) {
104
+ issues.push({
105
+ code: "V010",
106
+ severity: "error",
107
+ message: `Duplicate event id: ${ev.id} (${ev.name})`,
108
+ location: ev.id,
109
+ });
110
+ }
111
+ eventIds.add(ev.id);
112
+ }
113
+ }
114
+
115
+ // ─── V007/V008: Model validation ─────────────────────────────────────────
116
+
117
+ private checkModels(system: IR.IRSystem, issues: VerifyIssue[]) {
118
+ for (const mod of system.modules) {
119
+ for (const model of mod.models) {
120
+ // V007: Primary key exists
121
+ const pkField = model.fields.find(f => f.name === model.primary_key);
122
+ if (!pkField) {
123
+ issues.push({
124
+ code: "V007",
125
+ severity: "error",
126
+ message: `Model '${model.name}' primary key '${model.primary_key}' not found in fields`,
127
+ location: `${mod.id}.${model.name}`,
128
+ });
129
+ }
130
+
131
+ // V008: Index fields exist
132
+ const fieldNames = new Set(model.fields.map(f => f.name));
133
+ for (const idx of model.indexes) {
134
+ for (const field of idx.fields) {
135
+ if (!fieldNames.has(field)) {
136
+ issues.push({
137
+ code: "V008",
138
+ severity: "warning",
139
+ message: `Index on '${model.name}' references non-existent field '${field}'`,
140
+ location: `${mod.id}.${model.name}`,
141
+ });
142
+ }
143
+ }
144
+ }
145
+ }
146
+ }
147
+ }
148
+
149
+ // ─── V003: State machine transitions ──────────────────────────────────────
150
+
151
+ private checkStateMachines(system: IR.IRSystem, issues: VerifyIssue[]) {
152
+ for (const mod of system.modules) {
153
+ for (const sm of mod.state_machines) {
154
+ const validStates = new Set(sm.states);
155
+
156
+ // Initial state must be valid
157
+ if (!validStates.has(sm.initial)) {
158
+ issues.push({
159
+ code: "V003",
160
+ severity: "error",
161
+ message: `State machine '${sm.entity}' initial state '${sm.initial}' not in states list`,
162
+ location: `${mod.id}.${sm.entity}`,
163
+ });
164
+ }
165
+
166
+ // All transition targets must be valid
167
+ for (const t of sm.transitions) {
168
+ if (!validStates.has(t.from)) {
169
+ issues.push({
170
+ code: "V003",
171
+ severity: "error",
172
+ message: `Transition from '${t.from}' — state not declared in '${sm.entity}'`,
173
+ location: `${mod.id}.${sm.entity}`,
174
+ });
175
+ }
176
+ if (!validStates.has(t.to)) {
177
+ issues.push({
178
+ code: "V003",
179
+ severity: "error",
180
+ message: `Transition to '${t.to}' — state not declared in '${sm.entity}'`,
181
+ location: `${mod.id}.${sm.entity}`,
182
+ });
183
+ }
184
+ }
185
+ }
186
+ }
187
+ }
188
+
189
+ // ─── V004: Circular dependencies ──────────────────────────────────────────
190
+
191
+ private checkCircularDeps(system: IR.IRSystem, issues: VerifyIssue[]) {
192
+ const graph = new Map<string, string[]>();
193
+ for (const mod of system.modules) {
194
+ graph.set(mod.id, mod.dependencies);
195
+ }
196
+
197
+ const visited = new Set<string>();
198
+ const inStack = new Set<string>();
199
+
200
+ const dfs = (node: string, path: string[]): boolean => {
201
+ if (inStack.has(node)) {
202
+ const cycle = [...path.slice(path.indexOf(node)), node];
203
+ const names = cycle.map(id => system.modules.find(m => m.id === id)?.name || id);
204
+ issues.push({
205
+ code: "V004",
206
+ severity: "error",
207
+ message: `Circular dependency: ${names.join(" → ")}`,
208
+ location: node,
209
+ });
210
+ return true;
211
+ }
212
+ if (visited.has(node)) return false;
213
+
214
+ visited.add(node);
215
+ inStack.add(node);
216
+
217
+ for (const dep of graph.get(node) || []) {
218
+ if (graph.has(dep)) {
219
+ dfs(dep, [...path, node]);
220
+ }
221
+ }
222
+
223
+ inStack.delete(node);
224
+ return false;
225
+ };
226
+
227
+ for (const [id] of graph) {
228
+ if (!visited.has(id)) {
229
+ dfs(id, []);
230
+ }
231
+ }
232
+ }
233
+
234
+ // ─── Generated TypeScript Validation ───────────────────────────────────────
235
+
236
+ private checkTypeScriptSyntax(files: EmittedFile[], issues: VerifyIssue[]) {
237
+ for (const file of files) {
238
+ if (file.language !== "typescript") continue;
239
+
240
+ // Check balanced braces
241
+ let braceCount = 0;
242
+ let parenCount = 0;
243
+ let bracketCount = 0;
244
+
245
+ for (const ch of file.content) {
246
+ if (ch === "{") braceCount++;
247
+ if (ch === "}") braceCount--;
248
+ if (ch === "(") parenCount++;
249
+ if (ch === ")") parenCount--;
250
+ if (ch === "[") bracketCount++;
251
+ if (ch === "]") bracketCount--;
252
+ }
253
+
254
+ if (braceCount !== 0) {
255
+ issues.push({
256
+ code: "GEN_TS_BRACES",
257
+ severity: "error",
258
+ message: `Unbalanced braces in ${file.path} (${braceCount > 0 ? "missing }" : "extra }"})`,
259
+ location: file.path,
260
+ });
261
+ }
262
+ if (parenCount !== 0) {
263
+ issues.push({
264
+ code: "GEN_TS_PARENS",
265
+ severity: "warning",
266
+ message: `Unbalanced parentheses in ${file.path}`,
267
+ location: file.path,
268
+ });
269
+ }
270
+ }
271
+ }
272
+
273
+ // ─── Generated SQL Validation ──────────────────────────────────────────────
274
+
275
+ private checkSqlSyntax(files: EmittedFile[], issues: VerifyIssue[]) {
276
+ for (const file of files) {
277
+ if (file.language !== "sql") continue;
278
+
279
+ // Check CREATE TABLE has matching parentheses
280
+ if (file.content.includes("CREATE TABLE")) {
281
+ const opens = (file.content.match(/\(/g) || []).length;
282
+ const closes = (file.content.match(/\)/g) || []).length;
283
+ if (opens !== closes) {
284
+ issues.push({
285
+ code: "GEN_SQL_PARENS",
286
+ severity: "error",
287
+ message: `Unbalanced parentheses in SQL: ${file.path}`,
288
+ location: file.path,
289
+ });
290
+ }
291
+ }
292
+
293
+ // Check no empty CREATE TABLE
294
+ if (file.content.match(/CREATE TABLE[^(]+\(\s*\)/)) {
295
+ issues.push({
296
+ code: "GEN_SQL_EMPTY",
297
+ severity: "warning",
298
+ message: `Empty CREATE TABLE in ${file.path}`,
299
+ location: file.path,
300
+ });
301
+ }
302
+ }
303
+ }
304
+
305
+ // ─── Import Resolution ─────────────────────────────────────────────────────
306
+
307
+ private checkImports(files: EmittedFile[], issues: VerifyIssue[]) {
308
+ const filePaths = new Set(files.map(f => f.path));
309
+
310
+ for (const file of files) {
311
+ if (file.language !== "typescript") continue;
312
+
313
+ const importMatches = file.content.matchAll(/from\s+"([^"]+)"/g);
314
+ for (const match of importMatches) {
315
+ const importPath = match[1];
316
+ // Skip node_modules imports
317
+ if (!importPath.startsWith(".")) continue;
318
+
319
+ // Resolve relative to file
320
+ const dir = file.path.split("/").slice(0, -1).join("/");
321
+ const resolved = resolvePath(dir, importPath) + ".ts";
322
+
323
+ // Check if target exists in our file set
324
+ if (!filePaths.has(resolved) && !filePaths.has(resolved.replace(".ts", "/index.ts"))) {
325
+ // Not necessarily an error — could be importing from a parent project
326
+ // Only warn for imports within src/
327
+ if (importPath.startsWith("./") || importPath.startsWith("../")) {
328
+ issues.push({
329
+ code: "GEN_IMPORT",
330
+ severity: "warning",
331
+ message: `Import '${importPath}' in ${file.path} may not resolve (target: ${resolved})`,
332
+ location: file.path,
333
+ });
334
+ }
335
+ }
336
+ }
337
+ }
338
+ }
339
+
340
+
341
+ // ─── V002: Event source exists as a module ────────────────────────────────
342
+ private checkEventSources(system: IR.IRSystem, issues: VerifyIssue[]) {
343
+ const moduleIds = new Set(system.modules.map(m => m.id));
344
+ for (const ev of system.events) {
345
+ if (ev.source && ev.source !== "unknown" && !moduleIds.has(ev.source)) {
346
+ issues.push({
347
+ code: "V002",
348
+ severity: "warning",
349
+ message: `Event '${ev.name}' source '${ev.source}' does not match any module id`,
350
+ location: ev.id,
351
+ });
352
+ }
353
+ }
354
+ }
355
+
356
+ // ─── V005: Preconditions reference accessible fields ─────────────────────
357
+ private checkPreconditions(system: IR.IRSystem, issues: VerifyIssue[]) {
358
+ // Build a map of all model field names by model name (lowercase for case-insensitive lookup)
359
+ const modelFields = new Map<string, Set<string>>();
360
+ for (const mod of system.modules) {
361
+ for (const model of mod.models) {
362
+ const fields = new Set(model.fields.map(f => f.name));
363
+ // Add ontology-entailed fields always present
364
+ fields.add("id"); fields.add("created_at"); fields.add("updated_at"); fields.add("state");
365
+ modelFields.set(model.name, fields);
366
+ modelFields.set(model.name.toLowerCase(), fields);
367
+ }
368
+ }
369
+
370
+ // Simple field-path extractor: finds "word.word" patterns in a serialized expression
371
+ const fieldPathPattern = /\b([a-zA-Z_]\w*)\.([a-zA-Z_]\w*)\b/g;
372
+
373
+ for (const mod of system.modules) {
374
+ for (const iface of mod.interfaces) {
375
+ for (const method of iface.methods) {
376
+ for (const pre of method.preconditions) {
377
+ let match: RegExpExecArray | null;
378
+ fieldPathPattern.lastIndex = 0;
379
+ while ((match = fieldPathPattern.exec(pre.expression)) !== null) {
380
+ const [, paramName, fieldName] = match;
381
+ // Skip known non-field patterns (e.g. "now()", numeric literals)
382
+ if (paramName === "now" || /^\d/.test(paramName)) continue;
383
+ // Check if the field exists in any model — warn if not found
384
+ const foundInAnyModel = [...modelFields.values()].some(f => f.has(fieldName));
385
+ if (!foundInAnyModel) {
386
+ issues.push({
387
+ code: "V005",
388
+ severity: "warning",
389
+ message: `Precondition in '${method.name}' references '${paramName}.${fieldName}' — field '${fieldName}' not found in any model`,
390
+ location: `${mod.id}.${method.name}`,
391
+ });
392
+ }
393
+ }
394
+ }
395
+ }
396
+ }
397
+ }
398
+ }
399
+
400
+ // ─── V006: Effects target fields that exist ───────────────────────────────
401
+ private checkMethodEffects(system: IR.IRSystem, issues: VerifyIssue[]) {
402
+ // Build a map of all model field names by model name
403
+ const modelFields = new Map<string, Set<string>>();
404
+ for (const mod of system.modules) {
405
+ for (const model of mod.models) {
406
+ const fields = new Set(model.fields.map(f => f.name));
407
+ modelFields.set(model.name, fields);
408
+ modelFields.set(model.name.toLowerCase(), fields);
409
+ }
410
+ }
411
+
412
+ for (const mod of system.modules) {
413
+ for (const iface of mod.interfaces) {
414
+ for (const method of iface.methods) {
415
+ for (const effect of method.effects) {
416
+ const parts = effect.target.split(".");
417
+ if (parts.length < 2) continue;
418
+ const fieldName = parts[1];
419
+ // Try to find the model — check all models for the field
420
+ // (we can't always resolve the param name to a model here without type info)
421
+ // Only error if the field name looks like a typo (not found in ANY model)
422
+ const foundInAnyModel = [...modelFields.values()].some(fields => fields.has(fieldName));
423
+ if (!foundInAnyModel && !["state", "status", "owner_id"].includes(fieldName)) {
424
+ issues.push({
425
+ code: "V006",
426
+ severity: "warning",
427
+ message: `Effect target '${effect.target}' in method '${method.name}' — field '${fieldName}' not found in any model`,
428
+ location: `${mod.id}.${method.name}`,
429
+ });
430
+ }
431
+ }
432
+ }
433
+ }
434
+ }
435
+ }
436
+
437
+ // ─── V011: Authenticated methods' modules depend on auth ─────────────────
438
+ private checkAuthDependencies(system: IR.IRSystem, issues: VerifyIssue[]) {
439
+ const authModuleIds = new Set(
440
+ system.modules
441
+ .filter(m => m.kind === "auth_service" || m.config["auth_method"])
442
+ .map(m => m.id)
443
+ );
444
+
445
+ for (const mod of system.modules) {
446
+ const hasAuthenticatedMethod = mod.interfaces.some(i =>
447
+ i.methods.some(m => m.authenticated)
448
+ );
449
+ if (!hasAuthenticatedMethod) continue;
450
+
451
+ // Module must either be an auth service itself or depend on one
452
+ const isAuthService = mod.kind === "auth_service";
453
+ const dependsOnAuth = mod.dependencies.some(dep => authModuleIds.has(dep));
454
+ const hasAuthConfig = mod.config["auth_method"] && mod.config["auth_method"] !== "none";
455
+
456
+ if (!isAuthService && !dependsOnAuth && !hasAuthConfig && authModuleIds.size > 0) {
457
+ issues.push({
458
+ code: "V011",
459
+ severity: "warning",
460
+ message: `Module '${mod.name}' has authenticated methods but does not declare an auth dependency`,
461
+ location: mod.id,
462
+ });
463
+ }
464
+ }
465
+ }
466
+
467
+ // ─── V012: Resolution map is complete ────────────────────────────────────
468
+ private checkResolutionMap(system: IR.IRSystem, issues: VerifyIssue[]) {
469
+ // Resolution map must have at least the system-level keys
470
+ const required = ["system.name", "system.version", "system.domain"];
471
+ for (const key of required) {
472
+ if (!system.resolution[key]) {
473
+ issues.push({
474
+ code: "V012",
475
+ severity: "warning",
476
+ message: `Resolution map missing required key '${key}' — run constraint solver`,
477
+ location: system.name,
478
+ });
479
+ }
480
+ }
481
+ }
482
+
483
+ }
484
+
485
+ function resolvePath(base: string, relative: string): string {
486
+ const parts = base.split("/");
487
+ const relParts = relative.split("/");
488
+
489
+ for (const part of relParts) {
490
+ if (part === "..") parts.pop();
491
+ else if (part !== ".") parts.push(part);
492
+ }
493
+
494
+ return parts.join("/");
495
+ }