@specverse/engines 6.60.1 → 6.63.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 (46) hide show
  1. package/dist/ai/analyse-runner.d.ts.map +1 -1
  2. package/dist/ai/analyse-runner.js +22 -1
  3. package/dist/ai/analyse-runner.js.map +1 -1
  4. package/dist/analyse-prepass/adapters/module-functions.d.ts +25 -0
  5. package/dist/analyse-prepass/adapters/module-functions.d.ts.map +1 -1
  6. package/dist/analyse-prepass/adapters/module-functions.js +54 -0
  7. package/dist/analyse-prepass/adapters/module-functions.js.map +1 -1
  8. package/dist/analyse-prepass/backends/gitnexus.d.ts +28 -0
  9. package/dist/analyse-prepass/backends/gitnexus.d.ts.map +1 -1
  10. package/dist/analyse-prepass/backends/gitnexus.js +36 -2
  11. package/dist/analyse-prepass/backends/gitnexus.js.map +1 -1
  12. package/dist/analyse-prepass/index.d.ts.map +1 -1
  13. package/dist/analyse-prepass/index.js +17 -1
  14. package/dist/analyse-prepass/index.js.map +1 -1
  15. package/dist/libs/instance-factories/services/templates/_shared/step-matching.js +11 -0
  16. package/dist/libs/instance-factories/services/templates/mongodb-native/step-conventions.js +39 -19
  17. package/dist/libs/instance-factories/services/templates/postgres-native/step-conventions.js +35 -18
  18. package/dist/libs/instance-factories/services/templates/prisma/ai-behaviors-generator.js +7 -3
  19. package/dist/libs/instance-factories/services/templates/prisma/step-conventions.js +34 -12
  20. package/dist/libs/instance-factories/services/templates/shared-patterns.js +5 -5
  21. package/dist/realize/per-action-recovery.d.ts.map +1 -1
  22. package/dist/realize/per-action-recovery.js +6 -19
  23. package/dist/realize/per-action-recovery.js.map +1 -1
  24. package/dist/realize/per-owner-runner.d.ts.map +1 -1
  25. package/dist/realize/per-owner-runner.js +15 -28
  26. package/dist/realize/per-owner-runner.js.map +1 -1
  27. package/dist/realize/post-emit-verify/feedback-runner.d.ts +2 -1
  28. package/dist/realize/post-emit-verify/feedback-runner.d.ts.map +1 -1
  29. package/dist/realize/post-emit-verify/feedback-runner.js +2 -1
  30. package/dist/realize/post-emit-verify/feedback-runner.js.map +1 -1
  31. package/dist/realize/post-emit-verify/verifiers/stub-completeness.d.ts +43 -1
  32. package/dist/realize/post-emit-verify/verifiers/stub-completeness.d.ts.map +1 -1
  33. package/dist/realize/post-emit-verify/verifiers/stub-completeness.js +129 -4
  34. package/dist/realize/post-emit-verify/verifiers/stub-completeness.js.map +1 -1
  35. package/libs/instance-factories/services/templates/_shared/step-matching.ts +43 -0
  36. package/libs/instance-factories/services/templates/mongodb-native/step-conventions.ts +39 -19
  37. package/libs/instance-factories/services/templates/postgres-native/step-conventions.ts +35 -18
  38. package/libs/instance-factories/services/templates/prisma/__tests__/step-conventions-create.test.ts +184 -0
  39. package/libs/instance-factories/services/templates/prisma/ai-behaviors-generator.ts +16 -3
  40. package/libs/instance-factories/services/templates/prisma/step-conventions.ts +34 -12
  41. package/libs/instance-factories/services/templates/shared-patterns.ts +20 -10
  42. package/package.json +1 -1
  43. package/libs/instance-factories/services/templates/_shared/step-matching.d.ts +0 -39
  44. package/libs/instance-factories/services/templates/_shared/step-matching.d.ts.map +0 -1
  45. package/libs/instance-factories/services/templates/_shared/step-matching.js +0 -90
  46. package/libs/instance-factories/services/templates/_shared/step-matching.js.map +0 -1
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Step-conventions — `create` pattern reserved-word regression.
3
+ *
4
+ * Surfaced 2026-05-14 by the 9-cell comparison matrix: sonnet's
5
+ * idle-meta realize γ-stubbed `PlayersController.post0` with the
6
+ * precise diagnostic "pre-baked step 7 uses reserved keyword 'new' as
7
+ * a variable identifier — cannot emit coherently". The pre-baked
8
+ * snippet was:
9
+ *
10
+ * // Step 7: Create new
11
+ * const new = await prisma.new.create({ data: data });
12
+ *
13
+ * Root cause: prisma's `create` convention pattern was
14
+ * `/^create\s+(\w+).../i` — for the step "Create new Player with level 1",
15
+ * m[1] captured the adjective "new" rather than the noun "Player".
16
+ * Then toVar("new") = "new" (a JS reserved word) became both the
17
+ * variable name AND the prisma model name in the generated snippet,
18
+ * neither of which is legal/correct.
19
+ *
20
+ * mongo and pg conventions already had `(?:new\s+)?` in their create
21
+ * patterns — this was a parity gap. Fix: add the same optional group
22
+ * to prisma's create pattern. After the fix, m[1] = "Player" → snippet
23
+ * uses `prisma.player.create`.
24
+ */
25
+
26
+ import { describe, it, expect } from 'vitest';
27
+ import { STEP_CONVENTIONS } from '../step-conventions.js';
28
+ import type { StepContext } from '../step-conventions.js';
29
+
30
+ function findCreateConvention() {
31
+ const c = STEP_CONVENTIONS.find((x) => x.name === 'create');
32
+ expect(c).toBeDefined();
33
+ return c!;
34
+ }
35
+
36
+ function makeCtx(overrides: Partial<StepContext> = {}): StepContext {
37
+ return {
38
+ modelName: 'Player',
39
+ serviceName: 'PlayersController',
40
+ operationName: 'post0',
41
+ stepNum: 7,
42
+ parameterNames: [],
43
+ declaredVars: new Set<string>(),
44
+ ...overrides,
45
+ } as any;
46
+ }
47
+
48
+ describe('prisma step-convention `create` — adjective-skip + entity-name correctness', () => {
49
+ it('extracts the entity noun, not the adjective, from "Create new Player with …"', () => {
50
+ const convention = findCreateConvention();
51
+ const m = 'Create new Player with level 1, experience 0'.match(convention.pattern)!;
52
+ expect(m[1]).toBe('Player');
53
+ });
54
+
55
+ it('emits a snippet referencing `prisma.player` (not `prisma.new`) for the adjective case', () => {
56
+ const convention = findCreateConvention();
57
+ const m = 'Create new Player with level 1, experience 0'.match(convention.pattern)!;
58
+ const call = convention.generateCall(m, makeCtx())!;
59
+ expect(call).toContain('prisma.player.create');
60
+ expect(call).not.toContain('prisma.new');
61
+ expect(call).not.toContain('const new ');
62
+ });
63
+
64
+ it('still works for the no-adjective case "Create Player with …" (no regression)', () => {
65
+ const convention = findCreateConvention();
66
+ const m = 'Create Player with level 1'.match(convention.pattern)!;
67
+ expect(m[1]).toBe('Player');
68
+ const call = convention.generateCall(m, makeCtx())!;
69
+ expect(call).toContain('prisma.player.create');
70
+ });
71
+
72
+ it('uses parameter names for the data shape when provided', () => {
73
+ const convention = findCreateConvention();
74
+ const m = 'Create new Player with level 1'.match(convention.pattern)!;
75
+ const call = convention.generateCall(m, makeCtx({ parameterNames: ['userId', 'gameId'] }))!;
76
+ expect(call).toContain('{ userId, gameId }');
77
+ });
78
+
79
+ it('emits a syntactically valid `const <var> = await prisma.<var>.create(...)` shape', () => {
80
+ const convention = findCreateConvention();
81
+ const m = 'Create new Player with level 1'.match(convention.pattern)!;
82
+ const call = convention.generateCall(m, makeCtx())!;
83
+ // const <var> = await prisma.<var>.create(...);
84
+ // Variable name must NOT be a JS reserved word; both the variable
85
+ // and the prisma model reference should be the lowercased entity.
86
+ expect(call).toMatch(/const\s+player\s+=\s+await\s+prisma\.player\.create/);
87
+ });
88
+
89
+ // Wider adjective list (engines 6.60.4) — kept in sync with
90
+ // NL_LEADING_ADJECTIVES in _shared/step-matching.ts.
91
+ it.each([
92
+ ['existing', 'Create existing Player with level 1'],
93
+ ['current', 'Create current Player'],
94
+ ['the', 'Create the Player with level 1'],
95
+ ['a', 'Create a Player with level 1'],
96
+ ['an', 'Create an Order with total 100'],
97
+ ])('skips the leading adjective %s (no regression for any in the list)', (_adj, step) => {
98
+ const convention = findCreateConvention();
99
+ const m = step.match(convention.pattern)!;
100
+ // m[1] is the noun (Player/Order), never the adjective.
101
+ expect(['Player', 'Order']).toContain(m[1]);
102
+ const call = convention.generateCall(m, makeCtx())!;
103
+ expect(call).not.toMatch(/const\s+(existing|current|the|a|an)\s+=/);
104
+ expect(call).not.toMatch(/prisma\.(existing|current|the|a|an)\./);
105
+ });
106
+ });
107
+
108
+ describe('prisma step-convention `create` — reserved-word safety net', () => {
109
+ // The pattern's leading-adjective skip catches the common cases. The
110
+ // safety net catches anything that still leaks a JS reserved word as
111
+ // the entity name (an adjective not in the skip list, or a mis-parse).
112
+ // generateCall returns '' → the matcher falls through to the AI
113
+ // [WRITE] fallback instead of emitting `const class = await prisma.class...`.
114
+ it.each([
115
+ ['class', 'Create class Foo'],
116
+ ['function', 'Create function Bar'],
117
+ ['delete', 'Create delete Marker'],
118
+ ['return', 'Create return Receipt'],
119
+ ])('returns empty string when m[1] would be reserved word "%s"', (reserved, step) => {
120
+ const convention = findCreateConvention();
121
+ const m = step.match(convention.pattern);
122
+ // The pattern still matches structurally; the generateCall guard refuses.
123
+ if (m) {
124
+ expect(m[1]!.toLowerCase()).toBe(reserved);
125
+ const call = convention.generateCall(m, makeCtx());
126
+ expect(call).toBe('');
127
+ }
128
+ });
129
+
130
+ it('matches but refuses "Create new class" (post-adjective-skip the captured noun is reserved)', () => {
131
+ const convention = findCreateConvention();
132
+ const m = 'Create new class'.match(convention.pattern)!;
133
+ expect(m[1]).toBe('class');
134
+ expect(convention.generateCall(m, makeCtx())).toBe('');
135
+ });
136
+ });
137
+
138
+ describe('prisma step-conventions — extracted-input reserved-word safety (transition + call-service)', () => {
139
+ // 2026-05-15 audit of all toVar(extracted) sites. Same shape as the
140
+ // create-convention safety net above: when the captured noun lowercases
141
+ // to a TS reserved word, generateCall returns '' so the matcher falls
142
+ // through to the AI [WRITE] fallback instead of emitting illegal TS.
143
+
144
+ function findConvention(name: string) {
145
+ const c = STEP_CONVENTIONS.find((x) => x.name === name);
146
+ expect(c).toBeDefined();
147
+ return c!;
148
+ }
149
+
150
+ it.each([
151
+ ['delete', 'transition delete to active'],
152
+ ['return', 'transition return to closed'],
153
+ ['class', 'transition class to graduated'],
154
+ ])('transition: refuses reserved-word model "%s"', (_reserved, step) => {
155
+ const convention = findConvention('transition');
156
+ const m = step.match(convention.pattern)!;
157
+ expect(convention.generateCall(m, makeCtx())).toBe('');
158
+ });
159
+
160
+ it('transition: still works for a real model name (no regression)', () => {
161
+ const convention = findConvention('transition');
162
+ const m = 'transition Player to active'.match(convention.pattern)!;
163
+ const ctx = makeCtx({ declaredVars: new Set(['player']) });
164
+ const call = convention.generateCall(m, ctx)!;
165
+ expect(call).toContain('prisma.player.update');
166
+ expect(call).toContain("'active'");
167
+ });
168
+
169
+ it.each([
170
+ ['delete', 'call delete.purge'],
171
+ ['return', 'call return.process'],
172
+ ])('call-service: refuses reserved-word service name "%s"', (_reserved, step) => {
173
+ const convention = findConvention('call-service');
174
+ const m = step.match(convention.pattern)!;
175
+ expect(convention.generateCall(m, makeCtx())).toBe('');
176
+ });
177
+
178
+ it('call-service: still works for a real service name (no regression)', () => {
179
+ const convention = findConvention('call-service');
180
+ const m = 'call notificationService.send'.match(convention.pattern)!;
181
+ const call = convention.generateCall(m, makeCtx())!;
182
+ expect(call).toContain('notificationService.send');
183
+ });
184
+ });
@@ -18,6 +18,7 @@
18
18
  */
19
19
 
20
20
  import type { TemplateContext } from '@specverse/types';
21
+ import { safeFunctionName } from '@specverse/types';
21
22
  import { matchStep, type StepContext } from './step-conventions.js';
22
23
  import { validateImportWhitelist } from '@specverse/engines/ai';
23
24
  import { createHash } from 'crypto';
@@ -352,6 +353,15 @@ export async function generateAiBehaviorsFile(opts: {
352
353
  let cacheHits = 0;
353
354
  let cacheMisses = 0;
354
355
  for (const { functionName, step, operationName, parameterNames, inputs, returns, modelName } of unmatchedFunctions) {
356
+ // Reserved-word safety for the function declaration. `functionName`
357
+ // came from `toMethod(step)` in step-matching; a step text like
358
+ // "Delete" camelCases to `delete` — a JS keyword that's illegal as
359
+ // a function-declaration identifier. Suffix-rename the decl and
360
+ // append a re-export so callers (`aiBehaviors.delete(...)`) still
361
+ // resolve via the re-export's binding. Same shape as the γ-stub
362
+ // renderers in per-owner-runner + per-action-recovery.
363
+ const { name: safeName, reserved: nameReserved } = safeFunctionName(functionName);
364
+
355
365
  // Pure function signature + destructure are built AFTER the body so we
356
366
  // can match what the LLM actually references — strict tsc's
357
367
  // noUnusedLocals / noUnusedParameters fire on every input the body
@@ -484,7 +494,7 @@ export async function generateAiBehaviorsFile(opts: {
484
494
  const buildTestCode = (rawBody: string): string => {
485
495
  const { signature, destructure } = buildSignatureAndDestructure(rawBody);
486
496
  const destructureLine = destructure ? destructure + '\n' : '';
487
- return `export async function ${functionName}(${signature}): Promise<${returnType}> {\n${destructureLine}${rawBody}\n}`;
497
+ return `export async function ${safeName}(${signature}): Promise<${returnType}> {\n${destructureLine}${rawBody}\n}`;
488
498
  };
489
499
 
490
500
  // Check cache first — skip Claude if we've generated this exact step before
@@ -610,6 +620,9 @@ export async function generateAiBehaviorsFile(opts: {
610
620
  ? ` * Returns: ${returnType}\n`
611
621
  : '';
612
622
 
623
+ const reExportLine = nameReserved
624
+ ? `\nexport { ${safeName} as ${functionName} };`
625
+ : '';
613
626
  functions.push(`/**
614
627
  * ${functionName}
615
628
  *
@@ -628,7 +641,7 @@ ${inputsDoc}${returnsDoc} * Source: ${source}
628
641
  ? 'AI returned code with syntax errors — function throws at runtime. Fix or regenerate.'
629
642
  : 'STUB — Claude CLI unavailable. Install Claude Code or implement manually.'}
630
643
  */
631
- export async function ${functionName}(${(() => {
644
+ ${nameReserved ? 'async' : 'export async'} function ${safeName}(${(() => {
632
645
  const { signature: sig } = buildSignatureAndDestructure(body);
633
646
  return sig;
634
647
  })()}): Promise<${returnType}> {
@@ -636,7 +649,7 @@ ${(() => {
636
649
  const { destructure } = buildSignatureAndDestructure(body);
637
650
  return destructure ? destructure + '\n' : '';
638
651
  })()}${body}
639
- }`);
652
+ }${reExportLine}`);
640
653
  }
641
654
 
642
655
  // End the session
@@ -17,6 +17,7 @@ import {
17
17
  type SharedConvention,
18
18
  type SharedStepContext,
19
19
  } from '../_shared/step-matching.js';
20
+ import { safeEntityName } from '@specverse/types';
20
21
 
21
22
  export type StepConvention = SharedConvention<StepContext>;
22
23
 
@@ -125,13 +126,27 @@ export const STEP_CONVENTIONS: StepConvention[] = [
125
126
  },
126
127
 
127
128
  // --- Find / Lookup ---
129
+ //
130
+ // All entity-targeting patterns (find / create / update / delete) share
131
+ // two safeguards:
132
+ // 1. A pattern-level leading-adjective skip
133
+ // `(?:(?:new|existing|current|the|a|an)\s+)?` so NL phrasings like
134
+ // "Find existing Player by id" or "Create new Player with ..."
135
+ // extract the noun, not the adjective. Kept in sync with
136
+ // `NL_LEADING_ADJECTIVES` in `_shared/step-matching.ts`.
137
+ // 2. `safeEntityName(m[1])` — the reserved-word-safe primitive from
138
+ // `@specverse/types`. Returns the lowerCamel identifier, or `null`
139
+ // when the extraction would emit a TS reserved word
140
+ // (e.g. `prisma.new.create`). On null, generateCall returns `''` so
141
+ // the matcher falls through to the AI [WRITE] fallback.
128
142
  {
129
143
  name: 'find',
130
- pattern: /^find\s+(\w+)\s+by\s+(\w+)/i,
144
+ pattern: /^find\s+(?:(?:new|existing|current|the|a|an)\s+)?(\w+)\s+by\s+(\w+)/i,
131
145
  generateCall: (m, ctx) => {
132
146
  const model = m[1];
147
+ const modelVar = safeEntityName(model);
148
+ if (!modelVar) return '';
133
149
  const field = m[2];
134
- const modelVar = toVar(model);
135
150
  const params = ctx.parameterNames || [];
136
151
  const declared = ctx.declaredVars || new Set();
137
152
 
@@ -154,10 +169,11 @@ export const STEP_CONVENTIONS: StepConvention[] = [
154
169
  // --- Create ---
155
170
  {
156
171
  name: 'create',
157
- pattern: /^create\s+(\w+)(?:\s+(?:with\s+)?(.+))?/i,
172
+ pattern: /^create\s+(?:(?:new|existing|current|the|a|an)\s+)?(\w+)(?:\s+(?:with\s+)?(.+))?/i,
158
173
  generateCall: (m, ctx) => {
159
174
  const model = m[1];
160
- const modelVar = toVar(model);
175
+ const modelVar = safeEntityName(model);
176
+ if (!modelVar) return '';
161
177
  // Build data from parameter names if available
162
178
  const paramNames = ctx.parameterNames || [];
163
179
  const dataFields = paramNames.length > 0
@@ -171,12 +187,13 @@ export const STEP_CONVENTIONS: StepConvention[] = [
171
187
  // --- Update field ---
172
188
  {
173
189
  name: 'update-field',
174
- pattern: /^update\s+(\w+)\s+(\w+)\s+to\s+(.+)/i,
190
+ pattern: /^update\s+(?:(?:new|existing|current|the|a|an)\s+)?(\w+)\s+(\w+)\s+to\s+(.+)/i,
175
191
  generateCall: (m, ctx) => {
176
192
  const model = m[1];
193
+ const modelVar = safeEntityName(model);
194
+ if (!modelVar) return '';
177
195
  const field = m[2];
178
196
  const rawValue = m[3];
179
- const modelVar = toVar(model);
180
197
  const val = resolveValue(rawValue, ctx);
181
198
  return ` // Step ${ctx.stepNum}: Update ${model} ${field} to ${rawValue.trim()}
182
199
  await prisma.${modelVar}.update({
@@ -189,10 +206,11 @@ export const STEP_CONVENTIONS: StepConvention[] = [
189
206
  // --- Generic update ---
190
207
  {
191
208
  name: 'update',
192
- pattern: /^update\s+(\w+)(?:\s+(.+))?/i,
209
+ pattern: /^update\s+(?:(?:new|existing|current|the|a|an)\s+)?(\w+)(?:\s+(.+))?/i,
193
210
  generateCall: (m, ctx) => {
194
211
  const model = m[1];
195
- const modelVar = toVar(model);
212
+ const modelVar = safeEntityName(model);
213
+ if (!modelVar) return '';
196
214
  return ` // Step ${ctx.stepNum}: Update ${model}
197
215
  await prisma.${modelVar}.update({
198
216
  where: { id: ${modelVar}.id },
@@ -204,10 +222,11 @@ export const STEP_CONVENTIONS: StepConvention[] = [
204
222
  // --- Delete ---
205
223
  {
206
224
  name: 'delete',
207
- pattern: /^delete\s+(\w+)/i,
225
+ pattern: /^delete\s+(?:(?:new|existing|current|the|a|an)\s+)?(\w+)/i,
208
226
  generateCall: (m, ctx) => {
209
227
  const model = m[1];
210
- const modelVar = toVar(model);
228
+ const modelVar = safeEntityName(model);
229
+ if (!modelVar) return '';
211
230
  return ` // Step ${ctx.stepNum}: Delete ${model}
212
231
  await prisma.${modelVar}.delete({ where: { id: ${modelVar}.id } });`;
213
232
  },
@@ -220,7 +239,8 @@ export const STEP_CONVENTIONS: StepConvention[] = [
220
239
  generateCall: (m, ctx) => {
221
240
  const model = m[1];
222
241
  const state = m[2];
223
- const modelVar = toVar(model);
242
+ const modelVar = safeEntityName(model);
243
+ if (!modelVar) return '';
224
244
  return ` // Step ${ctx.stepNum}: Transition ${model} to ${state}
225
245
  if (${modelVar}.status === '${state}') throw new Error('${model} is already ${state}');
226
246
  await prisma.${modelVar}.update({
@@ -314,8 +334,10 @@ export const STEP_CONVENTIONS: StepConvention[] = [
314
334
  generateCall: (m, ctx) => {
315
335
  const service = m[1];
316
336
  const method = m[2];
337
+ const serviceVar = safeEntityName(service);
338
+ if (!serviceVar) return '';
317
339
  return ` // Step ${ctx.stepNum}: Call ${service}.${method}
318
- await ${toVar(service)}.${method}({ ${(ctx.parameterNames || []).join(', ')} });`;
340
+ await ${serviceVar}.${method}({ ${(ctx.parameterNames || []).join(', ')} });`;
319
341
  },
320
342
  },
321
343
 
@@ -1,12 +1,22 @@
1
1
  /**
2
2
  * Shared Convention Pattern Definitions
3
3
  *
4
- * The canonical list of step convention patterns. Both the Prisma factory
5
- * (code generation) and the Memory factory (runtime interpretation) use
6
- * these same patterns. Add new patterns here both targets pick them up.
4
+ * Canonical pattern list consumed by the Memory factory's runtime
5
+ * interpreter (`generateInterpreterModule` reads them to emit
6
+ * dispatch code). Prisma / Mongo / Postgres step-conventions split
7
+ * off into their own inline-regex files historically and no longer
8
+ * read from here — changes in this file primarily affect Memory.
7
9
  *
8
- * This is the "interface" of the convention system. Each factory provides
9
- * the "implementation" (generateCall or execute).
10
+ * Entity-targeting patterns (find / create / update-field / update /
11
+ * delete) carry a leading-adjective skip
12
+ * `(?:(?:new|existing|current|the|a|an)\s+)?` so an NL step like
13
+ * "Create new Player with …" extracts `Player`, not `new`. Mirrors
14
+ * `NL_LEADING_ADJECTIVES` in `_shared/step-matching.ts`. Without this,
15
+ * Memory's interpreter would call `ctx.store.create("new", data)` and
16
+ * fail at lookup; the structural cause is identical to the TS-side bug
17
+ * that `safeEntityName` (from `@specverse/types`) addresses in the
18
+ * other ORMs — only the *consequence* differs (runtime lookup failure
19
+ * here vs TS syntax error there).
10
20
  */
11
21
 
12
22
  export interface PatternDefinition {
@@ -19,13 +29,13 @@ export const CONVENTION_PATTERNS: PatternDefinition[] = [
19
29
  { name: 'validate', pattern: /^validate\s+(.+)/i, description: 'Validate input data' },
20
30
  { name: 'check-no-existing', pattern: /^check\s+(?:no\s+existing|.*has\s+no\s+existing)\s+(\w+)\s+for\s+(\w+)\s+in\s+(\w+)/i, description: 'Check no duplicate entity exists for a pair' },
21
31
  { name: 'check', pattern: /^check\s+(.+)/i, description: 'Check a condition' },
22
- { name: 'find', pattern: /^find\s+(\w+)\s+by\s+(\w+)/i, description: 'Find entity by field' },
32
+ { name: 'find', pattern: /^find\s+(?:(?:new|existing|current|the|a|an)\s+)?(\w+)\s+by\s+(\w+)/i, description: 'Find entity by field' },
23
33
  { name: 'find-all-for', pattern: /^find\s+(?:all\s+)?(\w+?)s?\s+(?:for|of|belonging\s+to)\s+(\w+)/i, description: 'Cross-model query via foreign key' },
24
34
  { name: 'count-per', pattern: /^count\s+(\w+?)s?\s+(?:per|by|for\s+each)\s+(\w+)/i, description: 'Group-by aggregation count' },
25
- { name: 'create', pattern: /^create\s+(\w+)(?:\s+record)?/i, description: 'Create a new entity' },
26
- { name: 'update-field', pattern: /^update\s+(\w+)\s+(\w+)\s+to\s+(.+)/i, description: 'Update specific field to value' },
27
- { name: 'update', pattern: /^update\s+(\w+)$/i, description: 'Update entity with params' },
28
- { name: 'delete', pattern: /^delete\s+(\w+)/i, description: 'Delete an entity' },
35
+ { name: 'create', pattern: /^create\s+(?:(?:new|existing|current|the|a|an)\s+)?(\w+)(?:\s+record)?/i, description: 'Create a new entity' },
36
+ { name: 'update-field', pattern: /^update\s+(?:(?:new|existing|current|the|a|an)\s+)?(\w+)\s+(\w+)\s+to\s+(.+)/i, description: 'Update specific field to value' },
37
+ { name: 'update', pattern: /^update\s+(?:(?:new|existing|current|the|a|an)\s+)?(\w+)$/i, description: 'Update entity with params' },
38
+ { name: 'delete', pattern: /^delete\s+(?:(?:new|existing|current|the|a|an)\s+)?(\w+)/i, description: 'Delete an entity' },
29
39
  { name: 'transition', pattern: /^transition\s+(\w+)\s+to\s+(\w+)/i, description: 'Lifecycle state transition' },
30
40
  { name: 'set', pattern: /^set\s+(\w+)\s+to\s+(.+)/i, description: 'Set a field value' },
31
41
  { name: 'increment', pattern: /^increment\s+(\w+)\s+by\s+(\w+)/i, description: 'Increment numeric field' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@specverse/engines",
3
- "version": "6.60.1",
3
+ "version": "6.63.0",
4
4
  "description": "SpecVerse toolchain — parser, inference, realize, generators, AI, registry, bundles",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1,39 +0,0 @@
1
- /**
2
- * Shared step-matching machinery — common helpers + the canonical
3
- * `matchAgainstConventions` walker that any ORM-specific step-conventions
4
- * library can compose with.
5
- *
6
- * Each ORM library (prisma, mongodb-native) exports its own
7
- * `STEP_CONVENTIONS` array of `{name, pattern, generateCall}` items
8
- * describing what code to emit for matched patterns. The matcher itself
9
- * is identical across libraries: walk the conventions in order, first
10
- * match wins; if nothing matches, compute the AI-fallback shape
11
- * (functionName + inputs + resultVar) deterministically.
12
- *
13
- * Extracted from prisma/step-conventions.ts and mongodb-native/step-conventions.ts
14
- * so future ORM libraries can drop in just the conventions array
15
- * without re-implementing matching logic. (#43K-D)
16
- */
17
- /** Camel-case a step's text into a TS identifier. Identical algorithm
18
- * across all ORM libraries — function names emitted in `aiBehaviors.<X>(...)`
19
- * calls must agree with the function declarations the AI-behaviors-generator
20
- * emits. Both sides go through this. */
21
- export declare function toMethod(words: string): string;
22
- export declare function toVar(name: string): string;
23
- export type { SharedStepContext, SharedConvention, MatchResult, MatcherFn, } from '@specverse/types';
24
- import type { SharedStepContext, SharedConvention, MatchResult } from '@specverse/types';
25
- export interface StepMatchRecord {
26
- ownerName: string;
27
- actionName: string;
28
- stepOrdinal: number;
29
- stepText: string;
30
- matched: boolean;
31
- helperMethod?: string;
32
- aiFunctionName?: string;
33
- }
34
- export declare function setStepMatchRecorder(fn: ((r: StepMatchRecord) => void) | null): void;
35
- /** Walk conventions in order. First match wins (with empty-string fallthrough).
36
- * Unmatched: compute the AI-delegate call site shape so the controller and
37
- * the AI-behaviors-generator agree on function name + inputs + resultVar. */
38
- export declare function matchAgainstConventions<C extends SharedStepContext>(step: string, ctx: C, conventions: ReadonlyArray<SharedConvention<C>>, aiArgsExpr: (inputs: string[], paramNames: string[]) => string): MatchResult;
39
- //# sourceMappingURL=step-matching.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"step-matching.d.ts","sourceRoot":"","sources":["step-matching.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH;;;wCAGwC;AACxC,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAK9C;AAED,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE1C;AAMD,YAAY,EACV,iBAAiB,EACjB,gBAAgB,EAChB,WAAW,EACX,SAAS,GACV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAWzF,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,wBAAgB,oBAAoB,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,eAAe,KAAK,IAAI,CAAC,GAAG,IAAI,GAAG,IAAI,CAEpF;AAED;;6EAE6E;AAC7E,wBAAgB,uBAAuB,CAAC,CAAC,SAAS,iBAAiB,EACjE,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,CAAC,EACN,WAAW,EAAE,aAAa,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,EAC/C,UAAU,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,MAAM,GAC7D,WAAW,CAsDb"}
@@ -1,90 +0,0 @@
1
- /**
2
- * Shared step-matching machinery — common helpers + the canonical
3
- * `matchAgainstConventions` walker that any ORM-specific step-conventions
4
- * library can compose with.
5
- *
6
- * Each ORM library (prisma, mongodb-native) exports its own
7
- * `STEP_CONVENTIONS` array of `{name, pattern, generateCall}` items
8
- * describing what code to emit for matched patterns. The matcher itself
9
- * is identical across libraries: walk the conventions in order, first
10
- * match wins; if nothing matches, compute the AI-fallback shape
11
- * (functionName + inputs + resultVar) deterministically.
12
- *
13
- * Extracted from prisma/step-conventions.ts and mongodb-native/step-conventions.ts
14
- * so future ORM libraries can drop in just the conventions array
15
- * without re-implementing matching logic. (#43K-D)
16
- */
17
- /** Camel-case a step's text into a TS identifier. Identical algorithm
18
- * across all ORM libraries — function names emitted in `aiBehaviors.<X>(...)`
19
- * calls must agree with the function declarations the AI-behaviors-generator
20
- * emits. Both sides go through this. */
21
- export function toMethod(words) {
22
- const cleaned = words.trim().replace(/[^A-Za-z0-9\s]+/g, ' ');
23
- const camel = cleaned.replace(/\s+(.)/g, (_, c) => c.toUpperCase()).replace(/^\w/, (c) => c.toLowerCase());
24
- const safe = camel.replace(/[^A-Za-z0-9_$]/g, '');
25
- return safe || 'unnamedStep';
26
- }
27
- export function toVar(name) {
28
- return name.charAt(0).toLowerCase() + name.slice(1);
29
- }
30
- let _stepRecorder = null;
31
- export function setStepMatchRecorder(fn) {
32
- _stepRecorder = fn;
33
- }
34
- /** Walk conventions in order. First match wins (with empty-string fallthrough).
35
- * Unmatched: compute the AI-delegate call site shape so the controller and
36
- * the AI-behaviors-generator agree on function name + inputs + resultVar. */
37
- export function matchAgainstConventions(step, ctx, conventions, aiArgsExpr) {
38
- let result = null;
39
- for (const convention of conventions) {
40
- const m = step.match(convention.pattern);
41
- if (m) {
42
- const call = convention.generateCall(m, ctx);
43
- if (call) {
44
- result = {
45
- matched: true,
46
- call,
47
- helperMethod: convention.generateMethod?.(m, ctx),
48
- };
49
- break;
50
- }
51
- }
52
- }
53
- if (!result) {
54
- // AI fallback shape — same across all ORMs.
55
- const functionName = toMethod(step);
56
- const declared = Array.from(ctx.declaredVars || []);
57
- const paramNames = ctx.parameterNames || [];
58
- const inputs = [...paramNames, ...declared];
59
- const resultVar = ctx.resultName || `step${ctx.stepNum}Result`;
60
- if (ctx.declaredVars)
61
- ctx.declaredVars.add(resultVar);
62
- const inputObj = aiArgsExpr(inputs, paramNames);
63
- result = {
64
- matched: false,
65
- call: ` // Step ${ctx.stepNum}: ${step} [AI-generated — pure transform]
66
- const ${resultVar} = await aiBehaviors.${functionName}(${inputObj});`,
67
- functionName,
68
- inputs,
69
- resultVar,
70
- };
71
- }
72
- // Forward-log the decision. ctx.serviceName carries the spec owner
73
- // (controller or service — the shared context uses one field for both).
74
- if (_stepRecorder) {
75
- try {
76
- _stepRecorder({
77
- ownerName: ctx.serviceName,
78
- actionName: ctx.operationName,
79
- stepOrdinal: ctx.stepNum,
80
- stepText: step,
81
- matched: result.matched,
82
- helperMethod: result.helperMethod,
83
- aiFunctionName: result.functionName,
84
- });
85
- }
86
- catch { /* recorder must never break generation */ }
87
- }
88
- return result;
89
- }
90
- //# sourceMappingURL=step-matching.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"step-matching.js","sourceRoot":"","sources":["step-matching.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH;;;wCAGwC;AACxC,MAAM,UAAU,QAAQ,CAAC,KAAa;IACpC,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,kBAAkB,EAAE,GAAG,CAAC,CAAC;IAC9D,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAA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