@specverse/engines 6.53.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 (84) 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/controllers/templates/fastify/routes-generator.js +29 -10
  16. package/dist/libs/instance-factories/services/templates/_shared/step-matching.js +11 -0
  17. package/dist/libs/instance-factories/services/templates/mongodb-native/step-conventions.js +39 -19
  18. package/dist/libs/instance-factories/services/templates/postgres-native/step-conventions.js +35 -18
  19. package/dist/libs/instance-factories/services/templates/prisma/ai-behaviors-generator.js +16 -11
  20. package/dist/libs/instance-factories/services/templates/prisma/controller-generator.js +1 -1
  21. package/dist/libs/instance-factories/services/templates/prisma/step-conventions.js +34 -12
  22. package/dist/libs/instance-factories/services/templates/shared-patterns.js +5 -5
  23. package/dist/realize/index.d.ts.map +1 -1
  24. package/dist/realize/index.js +91 -10
  25. package/dist/realize/index.js.map +1 -1
  26. package/dist/realize/per-action-recovery.d.ts +74 -0
  27. package/dist/realize/per-action-recovery.d.ts.map +1 -0
  28. package/dist/realize/per-action-recovery.js +255 -0
  29. package/dist/realize/per-action-recovery.js.map +1 -0
  30. package/dist/realize/per-owner-emit.d.ts +6 -0
  31. package/dist/realize/per-owner-emit.d.ts.map +1 -1
  32. package/dist/realize/per-owner-emit.js +22 -6
  33. package/dist/realize/per-owner-emit.js.map +1 -1
  34. package/dist/realize/per-owner-runner.d.ts +23 -2
  35. package/dist/realize/per-owner-runner.d.ts.map +1 -1
  36. package/dist/realize/per-owner-runner.js +91 -46
  37. package/dist/realize/per-owner-runner.js.map +1 -1
  38. package/dist/realize/post-emit-verify/diagnostics.d.ts +107 -0
  39. package/dist/realize/post-emit-verify/diagnostics.d.ts.map +1 -0
  40. package/dist/realize/post-emit-verify/diagnostics.js +148 -0
  41. package/dist/realize/post-emit-verify/diagnostics.js.map +1 -0
  42. package/dist/realize/post-emit-verify/feedback-runner.d.ts +41 -1
  43. package/dist/realize/post-emit-verify/feedback-runner.d.ts.map +1 -1
  44. package/dist/realize/post-emit-verify/feedback-runner.js +62 -6
  45. package/dist/realize/post-emit-verify/feedback-runner.js.map +1 -1
  46. package/dist/realize/post-emit-verify/index.d.ts +4 -2
  47. package/dist/realize/post-emit-verify/index.d.ts.map +1 -1
  48. package/dist/realize/post-emit-verify/index.js +3 -1
  49. package/dist/realize/post-emit-verify/index.js.map +1 -1
  50. package/dist/realize/post-emit-verify/reemit.d.ts +22 -1
  51. package/dist/realize/post-emit-verify/reemit.d.ts.map +1 -1
  52. package/dist/realize/post-emit-verify/reemit.js +20 -18
  53. package/dist/realize/post-emit-verify/reemit.js.map +1 -1
  54. package/dist/realize/post-emit-verify/types.d.ts +49 -0
  55. package/dist/realize/post-emit-verify/types.d.ts.map +1 -1
  56. package/dist/realize/post-emit-verify/verifier-manifest.d.ts.map +1 -1
  57. package/dist/realize/post-emit-verify/verifier-manifest.js +2 -0
  58. package/dist/realize/post-emit-verify/verifier-manifest.js.map +1 -1
  59. package/dist/realize/post-emit-verify/verifiers/stub-completeness.d.ts +127 -0
  60. package/dist/realize/post-emit-verify/verifiers/stub-completeness.d.ts.map +1 -0
  61. package/dist/realize/post-emit-verify/verifiers/stub-completeness.js +423 -0
  62. package/dist/realize/post-emit-verify/verifiers/stub-completeness.js.map +1 -0
  63. package/dist/realize/realize-context-snapshot.d.ts +70 -0
  64. package/dist/realize/realize-context-snapshot.d.ts.map +1 -0
  65. package/dist/realize/realize-context-snapshot.js +96 -0
  66. package/dist/realize/realize-context-snapshot.js.map +1 -0
  67. package/dist/realize/structural-validator.d.ts +36 -2
  68. package/dist/realize/structural-validator.d.ts.map +1 -1
  69. package/dist/realize/structural-validator.js +50 -7
  70. package/dist/realize/structural-validator.js.map +1 -1
  71. package/libs/instance-factories/controllers/templates/fastify/routes-generator.ts +49 -15
  72. package/libs/instance-factories/services/templates/_shared/step-matching.ts +43 -0
  73. package/libs/instance-factories/services/templates/mongodb-native/step-conventions.ts +39 -19
  74. package/libs/instance-factories/services/templates/postgres-native/step-conventions.ts +35 -18
  75. package/libs/instance-factories/services/templates/prisma/__tests__/step-conventions-create.test.ts +184 -0
  76. package/libs/instance-factories/services/templates/prisma/ai-behaviors-generator.ts +34 -5
  77. package/libs/instance-factories/services/templates/prisma/controller-generator.ts +6 -1
  78. package/libs/instance-factories/services/templates/prisma/step-conventions.ts +34 -12
  79. package/libs/instance-factories/services/templates/shared-patterns.ts +20 -10
  80. package/package.json +1 -1
  81. package/libs/instance-factories/services/templates/_shared/step-matching.d.ts +0 -39
  82. package/libs/instance-factories/services/templates/_shared/step-matching.d.ts.map +0 -1
  83. package/libs/instance-factories/services/templates/_shared/step-matching.js +0 -90
  84. package/libs/instance-factories/services/templates/_shared/step-matching.js.map +0 -1
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Stub-completeness verifier — detects placeholder/stub bodies in
3
+ * emitted `.ai.ts` files and reports them as VerifyErrors so the
4
+ * existing feedback runner re-emits real bodies.
5
+ *
6
+ * Why this exists:
7
+ * The tsc verifier catches code that DOESN'T COMPILE. It says nothing
8
+ * about code that compiles but ships no behavior — the dominant
9
+ * failure mode for smaller/open LLMs on per-owner emit:
10
+ * - Engine γ-stubs (LLM declined → fallback placeholder file)
11
+ * - LLM-emitted throw stubs ("not implemented", "TODO: ...")
12
+ * - LLM-emitted trivial returns (`return null as any`)
13
+ *
14
+ * Empirical at 2026-05-13:
15
+ * - idle-meta Ollama: 58% real-LLM fill, 80 tsc errors → 0 tsc
16
+ * errors looks clean but 42% of bodies are stubs.
17
+ * - idle-meta MarrBox: 69% real-LLM fill, 40 → ? tsc errors,
18
+ * 31% bodies still stubs.
19
+ *
20
+ * Reporting stubs as VerifyErrors lets the feedback runner re-emit
21
+ * them with a targeted prompt. The existing rollback machinery
22
+ * prevents regressions if the LLM can't do better.
23
+ *
24
+ * Design:
25
+ * - Regex-only — no TS compiler API import. The `.ai.ts` files have
26
+ * a narrow shape: top-level `export async function NAME(...):
27
+ * Promise<X> { ... }` declarations. Brace-balanced extraction with
28
+ * a single line scanner is enough.
29
+ * - Conservative: ONLY flags single-statement bodies that match
30
+ * stub patterns. A real function body with a stub-shaped throw
31
+ * inside a conditional is NOT flagged.
32
+ * - Severity `warning` not `error` — these don't break the build,
33
+ * but the feedback runner counts them as errors-to-fix.
34
+ *
35
+ * Initial release: `enabledByDefault: false` — opt in via
36
+ * `SPECVERSE_REALIZE_POST_VERIFY_ENABLE=stub-completeness`. Once the
37
+ * empirical hit-rate is measured we flip default-on.
38
+ */
39
+ import type { PostEmitVerifier } from '../types.js';
40
+ /** Stub error codes — surfaced to the feedback prompt as the verifier
41
+ * code; the LLM doesn't see them directly but they appear in the
42
+ * audit sidecar + logs. */
43
+ export declare const STUB_CODES: {
44
+ readonly GAMMA_FALLBACK: "STUB001";
45
+ readonly LLM_THROW: "STUB002";
46
+ readonly TRIVIAL_RETURN: "STUB003";
47
+ readonly EMPTY_BODY: "STUB004";
48
+ readonly MISPLACED_BRACE: "STUB005";
49
+ };
50
+ /**
51
+ * Find every top-level `export async function NAME(...): Promise<X> {`
52
+ * declaration in a file and return its name + body + start-line.
53
+ *
54
+ * Brace counting handles nested blocks and template-literal expression
55
+ * holes. We don't try to parse strings/regexes/comments precisely; the
56
+ * narrow shape of `.ai.ts` files makes this safe in practice (each
57
+ * function is independent and bodies don't contain `}` in odd places
58
+ * at the start of a line at depth 0).
59
+ */
60
+ interface ExtractedFunction {
61
+ name: string;
62
+ body: string;
63
+ /** 1-based line number of the `export async function` declaration. */
64
+ declLine: number;
65
+ /** 1-based line number of the first body line (after the opening `{`). */
66
+ bodyStartLine: number;
67
+ /** 1-based line number of the closing `}` that ends the body. */
68
+ endLine: number;
69
+ }
70
+ export declare function extractAsyncFunctions(source: string): ExtractedFunction[];
71
+ /**
72
+ * Strip line + block comments and blank lines, then trim.
73
+ * Used to normalize bodies before stub-pattern matching.
74
+ */
75
+ export declare function stripCommentsAndBlanks(body: string): string;
76
+ export interface StubMatch {
77
+ kind: 'gamma-fallback' | 'llm-throw' | 'trivial-return' | 'empty' | 'misplaced-brace';
78
+ code: string;
79
+ /** For 'misplaced-brace': a sample of the orphan code that follows
80
+ * the misplaced `}`. Surfaced to the LLM in the reemit prompt so it
81
+ * knows exactly which lines were displaced. */
82
+ orphanPreview?: string;
83
+ }
84
+ /**
85
+ * Detect the "misplaced `}`" emission pattern surfaced by marrbox on
86
+ * `GameConditionController.loadGameData` (2026-05-14). When the LLM
87
+ * emits a stray `}` right after the [PRE-BAKED] comment block, the
88
+ * brace-walker (correctly) treats it as the function's end. The
89
+ * function body classifies as `empty`, but the steps that were meant
90
+ * to be inside the body are now orphan top-level code:
91
+ *
92
+ * export async function loadGameData(_input: any): Promise<any> {
93
+ * // [PRE-BAKED] Step 1: ...
94
+ * // TODO: ...
95
+ * } ← misplaced
96
+ * // [WRITE] Step 2: ... ← orphan
97
+ * const v3BaseUrl = ...; ← orphan
98
+ * return { ... }; ← orphan, tsc TS1108
99
+ *
100
+ * The plain STUB004 message ("empty body") gives the LLM no clue why
101
+ * its previous emission was wrong; the reemit typically repeats the
102
+ * same mistake. STUB005's message names the specific shape so the
103
+ * LLM can correct the brace placement.
104
+ *
105
+ * Heuristic: between `fn.endLine + 1` and `nextDeclLine - 1` (or EOF
106
+ * if no next function), strip comments + blanks; if any non-trivial
107
+ * line remains AND we see at least one of:
108
+ * - `// [WRITE]` or `// [PRE-BAKED]` marker (these belong INSIDE
109
+ * function bodies; their presence at top level is diagnostic)
110
+ * - a top-level `return` statement (illegal TS — TS1108)
111
+ * - a top-level `const`/`let`/`var` declaration that isn't followed
112
+ * by `export`/`function` (i.e. not a module-level binding)
113
+ * → it's misplaced-brace orphan code.
114
+ *
115
+ * Returns a preview of the first ~5 orphan lines, or `null` if not
116
+ * misplaced-brace.
117
+ */
118
+ export declare function detectMisplacedBrace(source: string, fn: ExtractedFunction, nextDeclLine: number | null): string | null;
119
+ /**
120
+ * Classify a function body as a stub (or not). Conservative: requires
121
+ * the body to be a single-statement match to avoid false positives on
122
+ * real bodies that happen to contain a throw deep inside a conditional.
123
+ */
124
+ export declare function classifyBody(body: string): StubMatch | null;
125
+ export declare const STUB_COMPLETENESS_VERIFIER: PostEmitVerifier;
126
+ export {};
127
+ //# sourceMappingURL=stub-completeness.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stub-completeness.d.ts","sourceRoot":"","sources":["../../../../src/realize/post-emit-verify/verifiers/stub-completeness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAIH,OAAO,KAAK,EACV,gBAAgB,EAIjB,MAAM,aAAa,CAAC;AAErB;;4BAE4B;AAC5B,eAAO,MAAM,UAAU;;;;;;CAMb,CAAC;AAQX;;;;;;;;;GASG;AACH,UAAU,iBAAiB;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,sEAAsE;IACtE,QAAQ,EAAE,MAAM,CAAC;IACjB,0EAA0E;IAC1E,aAAa,EAAE,MAAM,CAAC;IACtB,iEAAiE;IACjE,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,iBAAiB,EAAE,CAwFzE;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQ3D;AAaD,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,gBAAgB,GAAG,WAAW,GAAG,gBAAgB,GAAG,OAAO,GAAG,iBAAiB,CAAC;IACtF,IAAI,EAAE,MAAM,CAAC;IACb;;oDAEgD;IAChD,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,iBAAiB,EACrB,YAAY,EAAE,MAAM,GAAG,IAAI,GAC1B,MAAM,GAAG,IAAI,CA8Df;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAwB3D;AAsDD,eAAO,MAAM,0BAA0B,EAAE,gBAuFxC,CAAC"}
@@ -0,0 +1,423 @@
1
+ /**
2
+ * Stub-completeness verifier — detects placeholder/stub bodies in
3
+ * emitted `.ai.ts` files and reports them as VerifyErrors so the
4
+ * existing feedback runner re-emits real bodies.
5
+ *
6
+ * Why this exists:
7
+ * The tsc verifier catches code that DOESN'T COMPILE. It says nothing
8
+ * about code that compiles but ships no behavior — the dominant
9
+ * failure mode for smaller/open LLMs on per-owner emit:
10
+ * - Engine γ-stubs (LLM declined → fallback placeholder file)
11
+ * - LLM-emitted throw stubs ("not implemented", "TODO: ...")
12
+ * - LLM-emitted trivial returns (`return null as any`)
13
+ *
14
+ * Empirical at 2026-05-13:
15
+ * - idle-meta Ollama: 58% real-LLM fill, 80 tsc errors → 0 tsc
16
+ * errors looks clean but 42% of bodies are stubs.
17
+ * - idle-meta MarrBox: 69% real-LLM fill, 40 → ? tsc errors,
18
+ * 31% bodies still stubs.
19
+ *
20
+ * Reporting stubs as VerifyErrors lets the feedback runner re-emit
21
+ * them with a targeted prompt. The existing rollback machinery
22
+ * prevents regressions if the LLM can't do better.
23
+ *
24
+ * Design:
25
+ * - Regex-only — no TS compiler API import. The `.ai.ts` files have
26
+ * a narrow shape: top-level `export async function NAME(...):
27
+ * Promise<X> { ... }` declarations. Brace-balanced extraction with
28
+ * a single line scanner is enough.
29
+ * - Conservative: ONLY flags single-statement bodies that match
30
+ * stub patterns. A real function body with a stub-shaped throw
31
+ * inside a conditional is NOT flagged.
32
+ * - Severity `warning` not `error` — these don't break the build,
33
+ * but the feedback runner counts them as errors-to-fix.
34
+ *
35
+ * Initial release: `enabledByDefault: false` — opt in via
36
+ * `SPECVERSE_REALIZE_POST_VERIFY_ENABLE=stub-completeness`. Once the
37
+ * empirical hit-rate is measured we flip default-on.
38
+ */
39
+ import { existsSync, readdirSync, readFileSync, statSync } from 'fs';
40
+ import { join, relative } from 'path';
41
+ /** Stub error codes — surfaced to the feedback prompt as the verifier
42
+ * code; the LLM doesn't see them directly but they appear in the
43
+ * audit sidecar + logs. */
44
+ export const STUB_CODES = {
45
+ GAMMA_FALLBACK: 'STUB001', // engine wrote the placeholder file
46
+ LLM_THROW: 'STUB002', // LLM emitted "throw not implemented"
47
+ TRIVIAL_RETURN: 'STUB003', // LLM emitted `return null|undefined|{}|[]`
48
+ EMPTY_BODY: 'STUB004', // body is whitespace/comments only
49
+ MISPLACED_BRACE: 'STUB005', // empty body + orphan top-level code follows
50
+ };
51
+ /** Resolve the behaviors directory tsc + this verifier scan. */
52
+ function resolveBehaviorsDir(ctx) {
53
+ const sub = ctx.subpath ?? 'backend';
54
+ return join(ctx.outputDir, sub, 'src', 'behaviors');
55
+ }
56
+ export function extractAsyncFunctions(source) {
57
+ const lines = source.split('\n');
58
+ const out = [];
59
+ // Pattern: line starts (after optional `export ` + `async `) with
60
+ // `async function NAME(`. We accept `export async function` (the
61
+ // canonical case) plus the alternate `async function NAME(...){...}`
62
+ // followed by `export { NAME as ... }` re-export form used for
63
+ // reserved-word action names in the engine γ-fallback file.
64
+ const declRe = /^(export\s+)?async\s+function\s+(\w+)\s*\(/;
65
+ for (let i = 0; i < lines.length; i++) {
66
+ const line = lines[i];
67
+ const m = declRe.exec(line);
68
+ if (!m)
69
+ continue;
70
+ const name = m[2];
71
+ // Walk forward to find the first `{` that opens the body. Skip
72
+ // anything inside the parameter list / return-type annotation.
73
+ let openIdx = -1;
74
+ let parenDepth = 0;
75
+ let lineCursor = i;
76
+ let colCursor = m.index + m[0].length; // just past `(`
77
+ // We've consumed up to the `(` of params; start at depth 1.
78
+ parenDepth = 1;
79
+ scanHeader: while (lineCursor < lines.length) {
80
+ const s = lines[lineCursor];
81
+ while (colCursor < s.length) {
82
+ const ch = s[colCursor];
83
+ if (parenDepth > 0) {
84
+ if (ch === '(')
85
+ parenDepth++;
86
+ else if (ch === ')')
87
+ parenDepth--;
88
+ }
89
+ else {
90
+ // After params closed: look for `{`.
91
+ if (ch === '{') {
92
+ openIdx = colCursor;
93
+ break scanHeader;
94
+ }
95
+ }
96
+ colCursor++;
97
+ }
98
+ lineCursor++;
99
+ colCursor = 0;
100
+ }
101
+ if (openIdx === -1)
102
+ continue;
103
+ // Now brace-count forward from just past `{` until we hit the
104
+ // matching `}`.
105
+ let depth = 1;
106
+ let bodyStartLineIdx = lineCursor;
107
+ let bodyStartColIdx = openIdx + 1;
108
+ let endLineIdx = -1;
109
+ let endColIdx = -1;
110
+ walkBody: for (let li = lineCursor; li < lines.length; li++) {
111
+ const s = lines[li];
112
+ const startCol = li === lineCursor ? openIdx + 1 : 0;
113
+ for (let ci = startCol; ci < s.length; ci++) {
114
+ const ch = s[ci];
115
+ if (ch === '{')
116
+ depth++;
117
+ else if (ch === '}') {
118
+ depth--;
119
+ if (depth === 0) {
120
+ endLineIdx = li;
121
+ endColIdx = ci;
122
+ break walkBody;
123
+ }
124
+ }
125
+ }
126
+ }
127
+ if (endLineIdx === -1)
128
+ continue; // unbalanced; bail on this fn
129
+ // Slice the body content (exclusive of the outer braces).
130
+ let body;
131
+ if (bodyStartLineIdx === endLineIdx) {
132
+ body = lines[bodyStartLineIdx].slice(bodyStartColIdx, endColIdx);
133
+ }
134
+ else {
135
+ const first = lines[bodyStartLineIdx].slice(bodyStartColIdx);
136
+ const middle = lines.slice(bodyStartLineIdx + 1, endLineIdx).join('\n');
137
+ const last = lines[endLineIdx].slice(0, endColIdx);
138
+ body = [first, middle, last].filter((x) => x !== '').join('\n');
139
+ }
140
+ out.push({
141
+ name,
142
+ body,
143
+ declLine: i + 1,
144
+ bodyStartLine: bodyStartLineIdx + 1,
145
+ endLine: endLineIdx + 1,
146
+ });
147
+ // Skip past the end so we don't re-scan content inside the body.
148
+ i = endLineIdx;
149
+ }
150
+ return out;
151
+ }
152
+ /**
153
+ * Strip line + block comments and blank lines, then trim.
154
+ * Used to normalize bodies before stub-pattern matching.
155
+ */
156
+ export function stripCommentsAndBlanks(body) {
157
+ // Block comments first (greedy, multi-line capable).
158
+ let s = body.replace(/\/\*[\s\S]*?\*\//g, '');
159
+ // Line comments.
160
+ s = s.replace(/(^|\n)\s*\/\/[^\n]*/g, (_, p1) => p1 ?? '');
161
+ // Collapse multiple newlines + trim.
162
+ s = s.split('\n').map((l) => l.trimEnd()).filter((l) => l.trim() !== '').join('\n').trim();
163
+ return s;
164
+ }
165
+ // γ-fallback engine placeholders. Two producers:
166
+ // - per-owner-runner.renderFallbackPlaceholderFile → "(per-owner emit fell back)"
167
+ // - per-action-recovery.renderActionGammaStub → "(per-action recovery fell back)"
168
+ // Both are ENGINE placeholders (STUB001, auto-reemit-eligible), NOT the
169
+ // LLM's own "not implemented" throw (STUB002, surface-spec-gap).
170
+ const GAMMA_FALLBACK_RE = /^throw new Error\s*\(\s*["'`].*?not implemented \((?:per-owner emit|per-action recovery) fell back\).*?["'`]\s*\)\s*;?$/s;
171
+ const LLM_THROW_RE = /^throw new Error\s*\(\s*["'`][^"'`]*\b(not\s+implement\w*|not\s+yet|todo|placeholder|stub|requires|fallback|missing|unimplement\w*)\b[^"'`]*["'`]\s*\)\s*;?$/is;
172
+ const TRIVIAL_RETURN_RE = /^return\s+(?:null|undefined|\{\s*\}|\[\s*\])(\s+as\s+\w+)?\s*;?$/s;
173
+ /**
174
+ * Detect the "misplaced `}`" emission pattern surfaced by marrbox on
175
+ * `GameConditionController.loadGameData` (2026-05-14). When the LLM
176
+ * emits a stray `}` right after the [PRE-BAKED] comment block, the
177
+ * brace-walker (correctly) treats it as the function's end. The
178
+ * function body classifies as `empty`, but the steps that were meant
179
+ * to be inside the body are now orphan top-level code:
180
+ *
181
+ * export async function loadGameData(_input: any): Promise<any> {
182
+ * // [PRE-BAKED] Step 1: ...
183
+ * // TODO: ...
184
+ * } ← misplaced
185
+ * // [WRITE] Step 2: ... ← orphan
186
+ * const v3BaseUrl = ...; ← orphan
187
+ * return { ... }; ← orphan, tsc TS1108
188
+ *
189
+ * The plain STUB004 message ("empty body") gives the LLM no clue why
190
+ * its previous emission was wrong; the reemit typically repeats the
191
+ * same mistake. STUB005's message names the specific shape so the
192
+ * LLM can correct the brace placement.
193
+ *
194
+ * Heuristic: between `fn.endLine + 1` and `nextDeclLine - 1` (or EOF
195
+ * if no next function), strip comments + blanks; if any non-trivial
196
+ * line remains AND we see at least one of:
197
+ * - `// [WRITE]` or `// [PRE-BAKED]` marker (these belong INSIDE
198
+ * function bodies; their presence at top level is diagnostic)
199
+ * - a top-level `return` statement (illegal TS — TS1108)
200
+ * - a top-level `const`/`let`/`var` declaration that isn't followed
201
+ * by `export`/`function` (i.e. not a module-level binding)
202
+ * → it's misplaced-brace orphan code.
203
+ *
204
+ * Returns a preview of the first ~5 orphan lines, or `null` if not
205
+ * misplaced-brace.
206
+ */
207
+ export function detectMisplacedBrace(source, fn, nextDeclLine) {
208
+ const lines = source.split('\n');
209
+ const startIdx = fn.endLine; // 1-based endLine → 0-based first line after = endLine
210
+ const stopIdx = nextDeclLine !== null ? nextDeclLine - 1 : lines.length;
211
+ if (startIdx >= stopIdx)
212
+ return null;
213
+ const range = lines.slice(startIdx, stopIdx);
214
+ // Look for diagnostic markers.
215
+ let hasInsideMarker = false;
216
+ let hasOrphanStatement = false;
217
+ const orphanLines = [];
218
+ for (const raw of range) {
219
+ const trimmed = raw.trim();
220
+ if (trimmed === '')
221
+ continue;
222
+ // Markers that should only appear INSIDE function bodies.
223
+ if (/^\/\/\s*\[(WRITE|PRE-BAKED|PRE_BAKED)\]/.test(trimmed)) {
224
+ hasInsideMarker = true;
225
+ if (orphanLines.length < 5)
226
+ orphanLines.push(trimmed);
227
+ continue;
228
+ }
229
+ // Module-level legal tokens (skip — not orphan).
230
+ if (/^(import|export|function|async\s+function|class|interface|type|enum|declare|\/\/|\/\*|\*)/.test(trimmed)) {
231
+ continue;
232
+ }
233
+ if (trimmed.startsWith('*/') || trimmed.startsWith('*'))
234
+ continue;
235
+ if (trimmed === '}' || trimmed === '};' || trimmed === ');' || trimmed === '})' || trimmed === '});') {
236
+ // Stray closers from orphan bodies. Diagnostic, but not by themselves.
237
+ if (orphanLines.length < 5)
238
+ orphanLines.push(trimmed);
239
+ continue;
240
+ }
241
+ // Statement-level keywords / patterns that are illegal at module top.
242
+ if (/^(return|await|if\s*\(|for\s*\(|while\s*\(|switch\s*\(|throw\s|break|continue)/.test(trimmed)) {
243
+ hasOrphanStatement = true;
244
+ if (orphanLines.length < 5)
245
+ orphanLines.push(trimmed);
246
+ continue;
247
+ }
248
+ // Bare `const`/`let`/`var` could be legal module-level, but in the
249
+ // body of an .ai.ts file (which only contains function declarations)
250
+ // they are diagnostic. Treat as orphan in conjunction with other
251
+ // signals — not on their own.
252
+ if (/^(const|let|var)\s/.test(trimmed)) {
253
+ if (orphanLines.length < 5)
254
+ orphanLines.push(trimmed);
255
+ continue;
256
+ }
257
+ // Identifier-followed-by-call (e.g. `gameDataResponse.edges.forEach`)
258
+ // is also a statement-level pattern, diagnostic when paired with
259
+ // markers above.
260
+ if (/^[A-Za-z_$][\w$]*[.[(]/.test(trimmed)) {
261
+ if (orphanLines.length < 5)
262
+ orphanLines.push(trimmed);
263
+ continue;
264
+ }
265
+ }
266
+ if (!hasInsideMarker && !hasOrphanStatement)
267
+ return null;
268
+ return orphanLines.join('\n');
269
+ }
270
+ /**
271
+ * Classify a function body as a stub (or not). Conservative: requires
272
+ * the body to be a single-statement match to avoid false positives on
273
+ * real bodies that happen to contain a throw deep inside a conditional.
274
+ */
275
+ export function classifyBody(body) {
276
+ const stripped = stripCommentsAndBlanks(body);
277
+ if (stripped === '') {
278
+ return { kind: 'empty', code: STUB_CODES.EMPTY_BODY };
279
+ }
280
+ // Single-statement check: count semicolons + ensure no control-flow
281
+ // keywords at the top level. We don't try to detect every multi-
282
+ // statement function; instead, we use the simplest signal — if the
283
+ // stripped body matches a single-statement stub regex end-to-end,
284
+ // it's a stub.
285
+ if (GAMMA_FALLBACK_RE.test(stripped)) {
286
+ return { kind: 'gamma-fallback', code: STUB_CODES.GAMMA_FALLBACK };
287
+ }
288
+ if (LLM_THROW_RE.test(stripped)) {
289
+ return { kind: 'llm-throw', code: STUB_CODES.LLM_THROW };
290
+ }
291
+ if (TRIVIAL_RETURN_RE.test(stripped)) {
292
+ return { kind: 'trivial-return', code: STUB_CODES.TRIVIAL_RETURN };
293
+ }
294
+ return null;
295
+ }
296
+ /** Render a feedback-prompt-friendly message for a stub match. */
297
+ function messageFor(kind, fnName, orphanPreview) {
298
+ switch (kind) {
299
+ case 'gamma-fallback':
300
+ return (`Function '${fnName}' is a γ-stub placeholder (per-owner emit fell back). ` +
301
+ `Emit a real implementation per the [PRE-BAKED] action contract in the spec.`);
302
+ case 'llm-throw':
303
+ return (`Function '${fnName}' has a placeholder body that throws 'not implemented' ` +
304
+ `(or similar). Emit a real implementation per the [PRE-BAKED] action contract.`);
305
+ case 'trivial-return':
306
+ return (`Function '${fnName}' returns a trivial placeholder (null/undefined/{}). ` +
307
+ `Emit a real implementation per the [PRE-BAKED] action contract.`);
308
+ case 'empty':
309
+ return (`Function '${fnName}' has an empty body. ` +
310
+ `Emit a real implementation per the [PRE-BAKED] action contract.`);
311
+ case 'misplaced-brace': {
312
+ const preview = orphanPreview ? `\nOrphan code sample:\n${orphanPreview}` : '';
313
+ return (`Function '${fnName}' has an empty body AND top-level code follows the ` +
314
+ `closing '}'. This is a misplaced-brace bug: the '}' that closes the function ` +
315
+ `was emitted right after the [PRE-BAKED] / [WRITE] step comments, leaving the ` +
316
+ `actual step bodies as illegal top-level statements (tsc TS1108). Fix: place ` +
317
+ `the closing '}' AFTER the last step body — not between the step comments and ` +
318
+ `their implementations.${preview}`);
319
+ }
320
+ }
321
+ }
322
+ /** Recursively list `*.ai.ts` files under a directory. Defensive — the
323
+ * behaviors dir is normally flat but engines may add subdirs later. */
324
+ function listAiTsFiles(dir) {
325
+ if (!existsSync(dir))
326
+ return [];
327
+ const out = [];
328
+ for (const name of readdirSync(dir)) {
329
+ const p = join(dir, name);
330
+ let st;
331
+ try {
332
+ st = statSync(p);
333
+ }
334
+ catch {
335
+ continue;
336
+ }
337
+ if (st.isDirectory())
338
+ out.push(...listAiTsFiles(p));
339
+ else if (st.isFile() && p.endsWith('.ai.ts'))
340
+ out.push(p);
341
+ }
342
+ return out;
343
+ }
344
+ export const STUB_COMPLETENESS_VERIFIER = {
345
+ id: 'stub-completeness',
346
+ name: 'Stub Body Completeness',
347
+ // Default-on as of engines 6.56.0 (Phase 2 of
348
+ // 2026-05-13-VERIFIER-DIAGNOSTIC-TREATMENT-SPLIT). Safe to flip
349
+ // because the feedback runner's defaultTreatmentSelector routes
350
+ // STUB002 to surface-spec-gap (no reemit), preventing the cross-
351
+ // file regressions measured at engines 6.54.0 on idle-meta.
352
+ // STUB001/003/004 still auto-reemit (high-success on γ-fallback
353
+ // recovery, measured at engines 6.54.0 on nestjs-billing: 7/7 fixed).
354
+ enabledByDefault: true,
355
+ applies: (ctx) => {
356
+ if (ctx.targetLanguage && ctx.targetLanguage !== 'typescript')
357
+ return false;
358
+ const dir = resolveBehaviorsDir(ctx);
359
+ return existsSync(dir) && listAiTsFiles(dir).length > 0;
360
+ },
361
+ verify: async (ctx) => {
362
+ const start = Date.now();
363
+ const dir = resolveBehaviorsDir(ctx);
364
+ const files = listAiTsFiles(dir);
365
+ const errors = [];
366
+ const notes = [];
367
+ let totalFunctions = 0;
368
+ let totalStubs = 0;
369
+ for (const absFile of files) {
370
+ let source;
371
+ try {
372
+ source = readFileSync(absFile, 'utf8');
373
+ }
374
+ catch (e) {
375
+ notes.push(`could not read ${absFile}: ${e?.message ?? String(e)}`);
376
+ continue;
377
+ }
378
+ const fns = extractAsyncFunctions(source);
379
+ totalFunctions += fns.length;
380
+ for (let fnIdx = 0; fnIdx < fns.length; fnIdx++) {
381
+ const fn = fns[fnIdx];
382
+ const match = classifyBody(fn.body);
383
+ if (!match)
384
+ continue;
385
+ // Promote 'empty' to 'misplaced-brace' when orphan top-level
386
+ // code follows the (apparent) closing `}`. Same severity, same
387
+ // treatment routing — only the message text changes, so the
388
+ // LLM gets a richer diagnostic on reemit.
389
+ let resolvedKind = match.kind;
390
+ let resolvedCode = match.code;
391
+ let orphanPreview;
392
+ if (match.kind === 'empty') {
393
+ const nextDeclLine = fnIdx + 1 < fns.length ? fns[fnIdx + 1].declLine : null;
394
+ const preview = detectMisplacedBrace(source, fn, nextDeclLine);
395
+ if (preview !== null) {
396
+ resolvedKind = 'misplaced-brace';
397
+ resolvedCode = STUB_CODES.MISPLACED_BRACE;
398
+ orphanPreview = preview;
399
+ }
400
+ }
401
+ totalStubs++;
402
+ errors.push({
403
+ file: relative(ctx.outputDir, absFile),
404
+ line: fn.declLine,
405
+ col: 1,
406
+ severity: 'warning',
407
+ code: resolvedCode,
408
+ message: messageFor(resolvedKind, fn.name, orphanPreview),
409
+ });
410
+ }
411
+ }
412
+ notes.push(`scanned ${files.length} .ai.ts file(s), ${totalFunctions} function(s); ` +
413
+ `flagged ${totalStubs} stub(s)`);
414
+ return {
415
+ verifierId: 'stub-completeness',
416
+ durationMs: Date.now() - start,
417
+ ok: true,
418
+ errors,
419
+ notes,
420
+ };
421
+ },
422
+ };
423
+ //# sourceMappingURL=stub-completeness.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stub-completeness.js","sourceRoot":"","sources":["../../../../src/realize/post-emit-verify/verifiers/stub-completeness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACrE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AAQtC;;4BAE4B;AAC5B,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,cAAc,EAAE,SAAS,EAAG,oCAAoC;IAChE,SAAS,EAAE,SAAS,EAAQ,sCAAsC;IAClE,cAAc,EAAE,SAAS,EAAG,4CAA4C;IACxE,UAAU,EAAE,SAAS,EAAO,mCAAmC;IAC/D,eAAe,EAAE,SAAS,EAAE,6CAA6C;CACjE,CAAC;AAEX,gEAAgE;AAChE,SAAS,mBAAmB,CAAC,GAAkB;IAC7C,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,IAAI,SAAS,CAAC;IACrC,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,GAAG,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;AACtD,CAAC;AAuBD,MAAM,UAAU,qBAAqB,CAAC,MAAc;IAClD,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACjC,MAAM,GAAG,GAAwB,EAAE,CAAC;IACpC,kEAAkE;IAClE,iEAAiE;IACjE,qEAAqE;IACrE,+DAA+D;IAC/D,4DAA4D;IAC5D,MAAM,MAAM,GAAG,4CAA4C,CAAC;IAE5D,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,E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QAAQ,EAAE,SAAS;oBACnB,IAAI,EAAE,YAAY;oBAClB,OAAO,EAAE,UAAU,CAAC,YAAY,EAAE,EAAE,CAAC,IAAI,EAAE,aAAa,CAAC;iBAC1D,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,KAAK,CAAC,IAAI,CACR,WAAW,KAAK,CAAC,MAAM,oBAAoB,cAAc,gBAAgB;YACzE,WAAW,UAAU,UAAU,CAChC,CAAC;QAEF,OAAO;YACL,UAAU,EAAE,mBAAmB;YAC/B,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK;YAC9B,EAAE,EAAE,IAAI;YACR,MAAM;YACN,KAAK;SACN,CAAC;IACJ,CAAC;CACF,CAAC"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Per-owner realize-context snapshot.
3
+ *
4
+ * Phase 3 of 2026-05-13-VERIFIER-DIAGNOSTIC-TREATMENT-SPLIT.
5
+ *
6
+ * The per-owner emit prompt has TARGET RUNTIME, [PRE-BAKED] step bullets,
7
+ * cross-service operation signatures, available capabilities, library
8
+ * whitelist — everything the LLM needs to emit a real action body. The
9
+ * post-emit feedback runner's `buildLlmReemit` historically had NONE of
10
+ * this; the reemit prompt provided only the previous bad output + the
11
+ * verifier errors.
12
+ *
13
+ * Empirical consequence: sonnet still bridged the gap via inference;
14
+ * smaller models (Ollama qwen3-coder:30b, MarrBox) drifted further from
15
+ * the realize-emit skill's contract, introducing cross-file tsc
16
+ * regressions when asked to fix STUB002 stubs (measured 2026-05-13 at
17
+ * engines 6.54.0 on idle-meta).
18
+ *
19
+ * Phase 3 closes the gap by SNAPSHOTTING the per-owner context to disk
20
+ * at emit time and READING it at reemit time. The snapshot lives at
21
+ * `<outputDir>/.realize-context/<OwnerName>.md` and contains a compact
22
+ * markdown blob — directly embeddable in the reemit user prompt.
23
+ *
24
+ * Decoupling: the snapshot writer (called from per-owner-runner)
25
+ * doesn't know about reemit; the snapshot loader (called from reemit
26
+ * factory) doesn't know about per-owner-emit. They share only the
27
+ * file layout convention.
28
+ */
29
+ /** Input data for snapshotting an owner's realize context. Mirrors the
30
+ * subset of PerOwnerEmitRequest that's directly useful for fixing
31
+ * bodies — TARGET RUNTIME + per-action [PRE-BAKED] scaffolding +
32
+ * cross-service signatures + available capabilities. */
33
+ export interface OwnerRealizeContext {
34
+ ownerName: string;
35
+ /** e.g. "Node.js (backend)" — short, structurally useful for choosing
36
+ * imports + identifying forbidden APIs. */
37
+ targetRuntime: string;
38
+ /** The full per-action scaffolding rendered by `buildPerActionScaffolding`
39
+ * — already formatted with `[PRE-BAKED] "<step>" → <snippet>` blocks
40
+ * and `[WRITE] "<step>"` markers. Reusing the same render keeps the
41
+ * reemit prompt aligned with the original per-owner prompt. */
42
+ perActionScaffolding: string;
43
+ /** AVAILABLE SPEC SURFACE — signatures of cross-service operations.
44
+ * Empty-fallback formatted by the per-owner-runner. */
45
+ availableSpecSurface: string;
46
+ /** AVAILABLE CAPABILITIES — clients / repos the LLM may call. */
47
+ availableCapabilities: string;
48
+ /** AVAILABLE CLIENTS — generated client classes the LLM may instantiate. */
49
+ availableClients: string;
50
+ }
51
+ /**
52
+ * Render the context as a compact markdown blob suitable for direct
53
+ * embedding in the reemit prompt body. Mirrors the section headings
54
+ * used in the per-owner-emit prompt template so the LLM sees the same
55
+ * structural cues.
56
+ */
57
+ export declare function formatContextSnapshot(ctx: OwnerRealizeContext): string;
58
+ /**
59
+ * Persist a context snapshot to disk. Best-effort — caller should
60
+ * never crash on snapshot failure (the reemit prompt degrades to the
61
+ * pre-Phase-3 behavior cleanly).
62
+ */
63
+ export declare function writeContextSnapshot(outputDir: string, ctx: OwnerRealizeContext): void;
64
+ /**
65
+ * Load a previously-written snapshot. Returns the raw markdown blob,
66
+ * or `null` if no snapshot exists for the owner. Callers (the reemit
67
+ * factory) include the blob in the prompt body when present.
68
+ */
69
+ export declare function loadContextSnapshot(outputDir: string, ownerName: string): string | null;
70
+ //# sourceMappingURL=realize-context-snapshot.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"realize-context-snapshot.d.ts","sourceRoot":"","sources":["../../src/realize/realize-context-snapshot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAOH;;;yDAGyD;AACzD,MAAM,WAAW,mBAAmB;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB;gDAC4C;IAC5C,aAAa,EAAE,MAAM,CAAC;IACtB;;;oEAGgE;IAChE,oBAAoB,EAAE,MAAM,CAAC;IAC7B;4DACwD;IACxD,oBAAoB,EAAE,MAAM,CAAC;IAC7B,iEAAiE;IACjE,qBAAqB,EAAE,MAAM,CAAC;IAC9B,4EAA4E;IAC5E,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,mBAAmB,GAAG,MAAM,CAmBtE;AAQD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,mBAAmB,GACvB,IAAI,CASN;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB,MAAM,GAAG,IAAI,CAQf"}