@gurulu/cli 0.1.0 → 0.1.2

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 (54) hide show
  1. package/package.json +7 -3
  2. package/scripts/.gitkeep +0 -0
  3. package/scripts/README-gurulu-agentic-install.md +114 -0
  4. package/scripts/README-gurulu-scan.md +98 -0
  5. package/scripts/audit-cli-scopes.mjs +204 -0
  6. package/scripts/backfill-tenant-id.mjs +172 -0
  7. package/scripts/backfill-tenant-links.ts +252 -0
  8. package/scripts/backup-clickhouse.sh +27 -0
  9. package/scripts/backup-postgres.sh +19 -0
  10. package/scripts/bootstrap-runtime-schema.mjs +105 -0
  11. package/scripts/bootstrap-stripe.mjs +158 -0
  12. package/scripts/gurulu-agentic-install.lib.cjs +734 -0
  13. package/scripts/gurulu-agentic-install.mjs +343 -0
  14. package/scripts/gurulu-scan.lib.cjs +989 -0
  15. package/scripts/gurulu-scan.mjs +91 -0
  16. package/scripts/gurulu-verify-install.lib.cjs +334 -0
  17. package/scripts/gurulu-verify-install.mjs +59 -0
  18. package/scripts/init-ssl.sh +26 -0
  19. package/scripts/migrate-flow-graph-enums.sh +86 -0
  20. package/scripts/monitor-disk.sh +24 -0
  21. package/scripts/patches/astro.patch.cjs +73 -0
  22. package/scripts/patches/auto-instrument/ast-helper.cjs +332 -0
  23. package/scripts/patches/auto-instrument/astro.cjs +267 -0
  24. package/scripts/patches/auto-instrument/express.cjs +368 -0
  25. package/scripts/patches/auto-instrument/fastify.cjs +258 -0
  26. package/scripts/patches/auto-instrument/index.cjs +78 -0
  27. package/scripts/patches/auto-instrument/nestjs.cjs +282 -0
  28. package/scripts/patches/auto-instrument/nextjs-app-router.cjs +318 -0
  29. package/scripts/patches/auto-instrument/nextjs-pages.cjs +348 -0
  30. package/scripts/patches/auto-instrument/remix.cjs +164 -0
  31. package/scripts/patches/auto-instrument/singleton-helper.cjs +193 -0
  32. package/scripts/patches/auto-instrument/sveltekit.cjs +157 -0
  33. package/scripts/patches/auto-instrument/vite-react.cjs +37 -0
  34. package/scripts/patches/auto-instrument/vue.cjs +192 -0
  35. package/scripts/patches/express.patch.cjs +99 -0
  36. package/scripts/patches/fastify.patch.cjs +107 -0
  37. package/scripts/patches/index.cjs +294 -0
  38. package/scripts/patches/nestjs.patch.cjs +111 -0
  39. package/scripts/patches/nextjs-app-router.patch.cjs +95 -0
  40. package/scripts/patches/nextjs-pages.patch.cjs +96 -0
  41. package/scripts/patches/remix.patch.cjs +74 -0
  42. package/scripts/patches/sveltekit.patch.cjs +71 -0
  43. package/scripts/patches/vite-react.patch.cjs +72 -0
  44. package/scripts/patches/vue.patch.cjs +81 -0
  45. package/scripts/renew-ssl.sh +14 -0
  46. package/scripts/resolve-migration.sh +23 -0
  47. package/scripts/seed-cli-dev-keys.mjs +130 -0
  48. package/scripts/seed-test-data.mjs +391 -0
  49. package/scripts/spike-browserless.ts +65 -0
  50. package/scripts/tenant-pivot-consistency-check.mjs +205 -0
  51. package/scripts/tenant-pivot-phase-3-cleanup.lib.cjs +258 -0
  52. package/scripts/tenant-pivot-phase-3-cleanup.mjs +98 -0
  53. package/scripts/test-identity-resolution.ts +804 -0
  54. package/scripts/validate-gurulu-schemas.mjs +79 -0
@@ -0,0 +1,368 @@
1
+ // scripts/patches/auto-instrument/express.cjs — Phase 20 W1 A1.
2
+ //
3
+ // AST-based auto-instrumentation for Express route files. We walk common
4
+ // entry files + `routes/**` and search for `app.<method>('/path', handler)`
5
+ // or `router.<method>('/path', handler)` call expressions. Once we locate
6
+ // the matching call we inject `gurulu.track(...)` inside the handler body
7
+ // (last argument, arrow or function expression).
8
+ //
9
+ // Regex fallback is retained for graceful degradation on parse failure.
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+
14
+ const ast = require('./ast-helper.cjs');
15
+ const singleton = require('./singleton-helper.cjs');
16
+
17
+ const NAME = 'auto-instrument-express';
18
+ const SUPPORTED = ['express'];
19
+ const MARKER = '// @gurulu-instrumented';
20
+ const IMPORT_LINE_ESM = "import { gurulu } from '@/lib/gurulu';";
21
+ const IMPORT_LINE_CJS = "const { gurulu } = require('./lib/gurulu');";
22
+
23
+ const CANDIDATE_ENTRIES = [
24
+ 'app.js',
25
+ 'server.js',
26
+ 'index.js',
27
+ 'src/app.js',
28
+ 'src/server.js',
29
+ 'src/index.js',
30
+ 'src/app.ts',
31
+ 'src/server.ts',
32
+ 'src/index.ts',
33
+ ];
34
+
35
+ function walkRoutes(repoRoot) {
36
+ const results = [];
37
+ const dirs = ['routes', 'src/routes', 'api', 'src/api'];
38
+ for (const d of dirs) {
39
+ const abs = path.join(repoRoot, d);
40
+ if (!fs.existsSync(abs)) continue;
41
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
42
+ if (entry.isFile() && /\.(js|ts|mjs|cjs)$/.test(entry.name)) {
43
+ results.push(path.posix.join(d, entry.name));
44
+ }
45
+ }
46
+ }
47
+ return results;
48
+ }
49
+
50
+ function parseRoute(routeStr) {
51
+ if (!routeStr || typeof routeStr !== 'string') return null;
52
+ const m = routeStr.trim().match(/^([A-Z]+)\s+(\/.*)$/);
53
+ if (!m) return null;
54
+ return { method: m[1].toUpperCase(), urlPath: m[2].replace(/\/+$/, '') || '/' };
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // AST path
59
+ // ---------------------------------------------------------------------------
60
+
61
+ /**
62
+ * Find all `app.<method>('path', ..., handler)` or `router.<method>(...)`
63
+ * call expressions matching the given method + urlPath. Returns an array of
64
+ * `{ fn, body }` entries (the handler arrow/function bodies).
65
+ */
66
+ function findRouteHandlers(tree, method, urlPath) {
67
+ const t = ast.t;
68
+ const results = [];
69
+ const lowerMethod = method.toLowerCase();
70
+ ast.traverse(tree, {
71
+ CallExpression(p) {
72
+ const callee = p.node.callee;
73
+ if (!t.isMemberExpression(callee)) return;
74
+ if (!t.isIdentifier(callee.property) || callee.property.name !== lowerMethod) return;
75
+ if (!t.isIdentifier(callee.object)) return;
76
+ const obj = callee.object.name;
77
+ if (obj !== 'app' && obj !== 'router') return;
78
+ const args = p.node.arguments;
79
+ if (args.length < 2) return;
80
+ if (!t.isStringLiteral(args[0]) || args[0].value !== urlPath) return;
81
+ // The final argument should be the handler function.
82
+ const handler = args[args.length - 1];
83
+ if (
84
+ (t.isArrowFunctionExpression(handler) || t.isFunctionExpression(handler)) &&
85
+ t.isBlockStatement(handler.body)
86
+ ) {
87
+ results.push({ fn: handler, body: handler.body });
88
+ }
89
+ },
90
+ });
91
+ return results;
92
+ }
93
+
94
+ function astInstrumentFile(source, method, urlPath, events) {
95
+ const tree = ast.parseSource(source);
96
+ const handlers = findRouteHandlers(tree, method, urlPath);
97
+ if (handlers.length === 0) {
98
+ return { ok: false, reason: 'handler-not-found' };
99
+ }
100
+ const target = handlers[0];
101
+ if (ast.hasInstrumentedMarker(target.fn)) {
102
+ return {
103
+ ok: true,
104
+ after: source,
105
+ instrumented: [],
106
+ skipped: events.map((e) => ({ event: e.name, reason: 'already-instrumented' })),
107
+ changed: false,
108
+ };
109
+ }
110
+ const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
111
+ ast.injectTrackBeforeLastReturn(target.fn, target.body, stmts);
112
+ ast.ensureGuruluImport(tree);
113
+ const after = ast.generateSource(tree, source);
114
+ return {
115
+ ok: true,
116
+ after,
117
+ instrumented: events.map((e) => e.name),
118
+ skipped: [],
119
+ changed: true,
120
+ };
121
+ }
122
+
123
+ // ---------------------------------------------------------------------------
124
+ // Regex fallback
125
+ // ---------------------------------------------------------------------------
126
+
127
+ function regexFindHandlerStart(source, method, urlPath) {
128
+ const lower = method.toLowerCase();
129
+ const escapedPath = urlPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
130
+ const re = new RegExp(
131
+ `(?:app|router)\\.${lower}\\s*\\(\\s*['"\`]${escapedPath}['"\`]\\s*,`,
132
+ );
133
+ const m = re.exec(source);
134
+ if (!m) return null;
135
+ let i = m.index + m[0].length;
136
+ const tail = source.slice(i);
137
+ const arrowIdx = tail.search(/=>\s*\{/);
138
+ const funcIdx = tail.search(/function\s*[^(]*\([^)]*\)\s*\{/);
139
+ let bodyOpen = -1;
140
+ if (arrowIdx !== -1 && (funcIdx === -1 || arrowIdx < funcIdx)) {
141
+ bodyOpen = i + tail.indexOf('{', arrowIdx);
142
+ } else if (funcIdx !== -1) {
143
+ bodyOpen = i + tail.indexOf('{', funcIdx);
144
+ }
145
+ if (bodyOpen === -1) return null;
146
+ let depth = 0;
147
+ for (let j = bodyOpen; j < source.length; j++) {
148
+ const c = source[j];
149
+ if (c === '{') depth++;
150
+ else if (c === '}') {
151
+ depth--;
152
+ if (depth === 0) return { start: bodyOpen, end: j };
153
+ }
154
+ }
155
+ return null;
156
+ }
157
+
158
+ function regexFindLastResponseCall(source, start, end) {
159
+ const snippet = source.slice(start, end);
160
+ const patterns = [
161
+ /res\.status\s*\([^)]*\)\s*\.json\s*\(/g,
162
+ /res\.status\s*\([^)]*\)\s*\.send\s*\(/g,
163
+ /res\.json\s*\(/g,
164
+ /res\.send\s*\(/g,
165
+ /res\.sendStatus\s*\(/g,
166
+ /res\.end\s*\(/g,
167
+ ];
168
+ let lastIdx = -1;
169
+ for (const re of patterns) {
170
+ let m;
171
+ while ((m = re.exec(snippet)) !== null) {
172
+ if (m.index > lastIdx) lastIdx = m.index;
173
+ }
174
+ }
175
+ if (lastIdx === -1) return null;
176
+ const absoluteIdx = start + lastIdx;
177
+ let lineStart = absoluteIdx;
178
+ while (lineStart > 0 && source[lineStart - 1] !== '\n') lineStart--;
179
+ const indentMatch = source.slice(lineStart, absoluteIdx).match(/^(\s*)/);
180
+ const indent = (indentMatch && indentMatch[1]) || ' ';
181
+ return { insertAt: lineStart, indent };
182
+ }
183
+
184
+ function regexEnsureImport(source) {
185
+ if (source.includes(IMPORT_LINE_ESM) || source.includes(IMPORT_LINE_CJS)) return source;
186
+ const isCjs = /\brequire\s*\(/.test(source) && !/^import\s/m.test(source);
187
+ const line = isCjs ? IMPORT_LINE_CJS : IMPORT_LINE_ESM;
188
+ const importRegex = /^(?:import[\s\S]*?;\s*\n)+/m;
189
+ const requireRegex = /^(?:const\s[\s\S]*?require\([\s\S]*?\);\s*\n)+/m;
190
+ const m = source.match(importRegex) || source.match(requireRegex);
191
+ if (m) {
192
+ const end = m.index + m[0].length;
193
+ return source.slice(0, end) + line + '\n' + source.slice(end);
194
+ }
195
+ return line + '\n' + source;
196
+ }
197
+
198
+ function regexBuildTrackCall(eventName, indent) {
199
+ const safeName = JSON.stringify(eventName);
200
+ return `${indent}${MARKER} ${eventName}\n${indent}gurulu.track(${safeName}, {});\n`;
201
+ }
202
+
203
+ function regexInstrumentFile(before, method, urlPath, events) {
204
+ const body = regexFindHandlerStart(before, method, urlPath);
205
+ if (!body) return { ok: false, reason: 'handler-not-found' };
206
+ const snippet = before.slice(body.start, body.end);
207
+ const needed = [];
208
+ const skipped = [];
209
+ for (const e of events) {
210
+ if (snippet.includes(`${MARKER} ${e.name}`)) {
211
+ skipped.push({ event: e.name, reason: 'already-instrumented' });
212
+ } else {
213
+ needed.push(e);
214
+ }
215
+ }
216
+ if (needed.length === 0) return { ok: true, after: before, instrumented: [], skipped, changed: false };
217
+ const ret = regexFindLastResponseCall(before, body.start, body.end);
218
+ if (!ret) return { ok: false, reason: 'no-response-found' };
219
+ const block = needed.map((e) => regexBuildTrackCall(e.name, ret.indent)).join('');
220
+ let after = before.slice(0, ret.insertAt) + block + before.slice(ret.insertAt);
221
+ after = regexEnsureImport(after);
222
+ return {
223
+ ok: true,
224
+ after,
225
+ instrumented: needed.map((e) => e.name),
226
+ skipped,
227
+ changed: true,
228
+ };
229
+ }
230
+
231
+ // ---------------------------------------------------------------------------
232
+ // Glue
233
+ // ---------------------------------------------------------------------------
234
+
235
+ function resolveRouteFile(ctx, method, urlPath) {
236
+ const seen = new Set();
237
+ const candidates = [
238
+ ...CANDIDATE_ENTRIES,
239
+ ...walkRoutes(ctx.repoRoot),
240
+ ].filter((rel) => {
241
+ if (seen.has(rel)) return false;
242
+ seen.add(rel);
243
+ return fs.existsSync(path.join(ctx.repoRoot, rel));
244
+ });
245
+ for (const rel of candidates) {
246
+ const src = fs.readFileSync(path.join(ctx.repoRoot, rel), 'utf8');
247
+ // Cheap pre-filter: must contain `.${method.toLowerCase()}(`.
248
+ if (!src.includes(`.${method.toLowerCase()}(`)) continue;
249
+ try {
250
+ const tree = ast.parseSource(src);
251
+ const handlers = findRouteHandlers(tree, method, urlPath);
252
+ if (handlers.length > 0) return { relPath: rel };
253
+ } catch (_) {
254
+ // Regex check as last-ditch.
255
+ if (regexFindHandlerStart(src, method, urlPath)) return { relPath: rel };
256
+ }
257
+ }
258
+ return null;
259
+ }
260
+
261
+ function instrumentEvents(ctx, events) {
262
+ const helper = singleton.ensureSingletonHelper(ctx, 'express');
263
+ const changes = [...helper.changes];
264
+ const notes = [...helper.notes];
265
+ let eventsInstrumented = 0;
266
+ let eventsSkipped = 0;
267
+
268
+ if (helper.collision) {
269
+ return {
270
+ changes: [],
271
+ notes,
272
+ filesModified: 0,
273
+ eventsInstrumented: 0,
274
+ eventsSkipped: events ? events.length : 0,
275
+ collision: true,
276
+ };
277
+ }
278
+
279
+ const groups = new Map();
280
+ for (const e of events || []) {
281
+ const parsed = parseRoute(e && e.source && e.source.route);
282
+ if (!parsed) {
283
+ notes.push(`skip:${e && e.name}:no-source-route`);
284
+ eventsSkipped++;
285
+ continue;
286
+ }
287
+ const resolved = resolveRouteFile(ctx, parsed.method, parsed.urlPath);
288
+ if (!resolved) {
289
+ notes.push(`skip:${e.name}:route-not-found`);
290
+ eventsSkipped++;
291
+ continue;
292
+ }
293
+ const key = `${resolved.relPath}::${parsed.method}::${parsed.urlPath}`;
294
+ if (!groups.has(key)) {
295
+ groups.set(key, {
296
+ relPath: resolved.relPath,
297
+ method: parsed.method,
298
+ urlPath: parsed.urlPath,
299
+ events: [],
300
+ });
301
+ }
302
+ groups.get(key).events.push(e);
303
+ }
304
+
305
+ for (const group of groups.values()) {
306
+ const abs = path.join(ctx.repoRoot, group.relPath);
307
+ const before = fs.readFileSync(abs, 'utf8');
308
+ let res;
309
+ try {
310
+ res = astInstrumentFile(before, group.method, group.urlPath, group.events);
311
+ } catch (err) {
312
+ const msg = (err && err.message) || String(err);
313
+ // eslint-disable-next-line no-console
314
+ console.warn(`[auto-instrument] patch.fallback ${group.relPath}: ${msg}`);
315
+ notes.push(`patch.fallback:${group.relPath}:${msg}`);
316
+ res = regexInstrumentFile(before, group.method, group.urlPath, group.events);
317
+ }
318
+ if (!res.ok) {
319
+ for (const e of group.events) {
320
+ notes.push(`skip:${e.name}:${res.reason || 'instrument-failed'}`);
321
+ eventsSkipped++;
322
+ }
323
+ continue;
324
+ }
325
+ for (const s of res.skipped || []) {
326
+ notes.push(`skip:${s.event}:${s.reason}`);
327
+ eventsSkipped++;
328
+ }
329
+ if (!res.changed) continue;
330
+ // Merge with earlier staged change to the same file (AST already takes
331
+ // care of dedup-by-marker within a single call, so we just overwrite).
332
+ const existing = changes.find((c) => c.relPath === group.relPath && c.type === 'auto-instrument');
333
+ if (existing) {
334
+ existing.after = res.after;
335
+ } else {
336
+ changes.push({
337
+ relPath: group.relPath,
338
+ before,
339
+ after: res.after,
340
+ reason: `auto-instrument-${group.method}`,
341
+ type: 'auto-instrument',
342
+ });
343
+ }
344
+ eventsInstrumented += (res.instrumented || []).length;
345
+ }
346
+
347
+ const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
348
+ return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
349
+ }
350
+
351
+ function ensureSingletonHelper(ctx) {
352
+ return singleton.ensureSingletonHelper(ctx, 'express');
353
+ }
354
+
355
+ module.exports = {
356
+ name: NAME,
357
+ supportedFrameworks: SUPPORTED,
358
+ ensureSingletonHelper,
359
+ instrumentEvents,
360
+ _internals: {
361
+ parseRoute,
362
+ resolveRouteFile,
363
+ astInstrumentFile,
364
+ regexInstrumentFile,
365
+ walkRoutes,
366
+ findRouteHandlers,
367
+ },
368
+ };
@@ -0,0 +1,258 @@
1
+ // scripts/patches/auto-instrument/fastify.cjs — Phase 20 W1 A3.
2
+ //
3
+ // Fastify supports two idiomatic route registration shapes:
4
+ //
5
+ // fastify.get('/users', async (req, reply) => { ... });
6
+ // fastify.route({ method: 'GET', url: '/users', handler: async (req, reply) => { ... } });
7
+ //
8
+ // We search the usual server entry files plus `routes/**` for a matching
9
+ // registration, parse the AST, and inject `gurulu.track(...)` into the
10
+ // handler body before the last return.
11
+
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+
15
+ const ast = require('./ast-helper.cjs');
16
+ const singleton = require('./singleton-helper.cjs');
17
+
18
+ const NAME = 'auto-instrument-fastify';
19
+ const SUPPORTED = ['fastify'];
20
+
21
+ const CANDIDATE_ENTRIES = [
22
+ 'app.js',
23
+ 'server.js',
24
+ 'index.js',
25
+ 'src/app.js',
26
+ 'src/server.js',
27
+ 'src/index.js',
28
+ 'src/app.ts',
29
+ 'src/server.ts',
30
+ 'src/index.ts',
31
+ ];
32
+
33
+ function parseEventRoute(routeStr) {
34
+ if (!routeStr || typeof routeStr !== 'string') return null;
35
+ const m = routeStr.trim().match(/^([A-Z]+)\s+(\/.*)$/);
36
+ if (!m) return null;
37
+ return { method: m[1].toUpperCase(), urlPath: m[2].replace(/\/+$/, '') || '/' };
38
+ }
39
+
40
+ function walkRoutes(repoRoot) {
41
+ const results = [];
42
+ const dirs = ['routes', 'src/routes', 'plugins', 'src/plugins'];
43
+ for (const d of dirs) {
44
+ const abs = path.join(repoRoot, d);
45
+ if (!fs.existsSync(abs)) continue;
46
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
47
+ if (entry.isFile() && /\.(js|ts|mjs|cjs)$/.test(entry.name)) {
48
+ results.push(path.posix.join(d, entry.name));
49
+ }
50
+ }
51
+ }
52
+ return results;
53
+ }
54
+
55
+ function findFastifyHandlers(tree, method, urlPath) {
56
+ const t = ast.t;
57
+ const results = [];
58
+ const lowerMethod = method.toLowerCase();
59
+
60
+ ast.traverse(tree, {
61
+ CallExpression(p) {
62
+ const callee = p.node.callee;
63
+ // Shape 1: fastify.get('/users', handler) / app.get(...) — identifier may
64
+ // be any local name bound to the fastify instance.
65
+ if (t.isMemberExpression(callee) && t.isIdentifier(callee.property)) {
66
+ if (callee.property.name === lowerMethod) {
67
+ const args = p.node.arguments;
68
+ if (args.length >= 2 && t.isStringLiteral(args[0]) && args[0].value === urlPath) {
69
+ const handler = args[args.length - 1];
70
+ if (
71
+ (t.isArrowFunctionExpression(handler) || t.isFunctionExpression(handler)) &&
72
+ t.isBlockStatement(handler.body)
73
+ ) {
74
+ results.push({ fn: handler, body: handler.body });
75
+ }
76
+ }
77
+ }
78
+ // Shape 2: fastify.route({ method, url, handler })
79
+ if (callee.property.name === 'route') {
80
+ const arg0 = p.node.arguments[0];
81
+ if (t.isObjectExpression(arg0)) {
82
+ let m, u, handlerNode;
83
+ for (const prop of arg0.properties) {
84
+ if (!t.isObjectProperty(prop)) continue;
85
+ const key = t.isIdentifier(prop.key) ? prop.key.name : (t.isStringLiteral(prop.key) ? prop.key.value : null);
86
+ if (!key) continue;
87
+ if (key === 'method' && t.isStringLiteral(prop.value)) m = prop.value.value.toUpperCase();
88
+ else if (key === 'url' && t.isStringLiteral(prop.value)) u = prop.value.value;
89
+ else if (key === 'handler') handlerNode = prop.value;
90
+ }
91
+ if (m === method && u === urlPath && handlerNode) {
92
+ if (
93
+ (t.isArrowFunctionExpression(handlerNode) || t.isFunctionExpression(handlerNode)) &&
94
+ t.isBlockStatement(handlerNode.body)
95
+ ) {
96
+ results.push({ fn: handlerNode, body: handlerNode.body });
97
+ }
98
+ }
99
+ }
100
+ }
101
+ }
102
+ },
103
+ });
104
+ return results;
105
+ }
106
+
107
+ function astInstrumentFile(source, method, urlPath, events) {
108
+ const tree = ast.parseSource(source);
109
+ const handlers = findFastifyHandlers(tree, method, urlPath);
110
+ if (handlers.length === 0) return { ok: false, reason: 'handler-not-found' };
111
+ const target = handlers[0];
112
+ if (ast.hasInstrumentedMarker(target.fn)) {
113
+ return {
114
+ ok: true,
115
+ after: source,
116
+ instrumented: [],
117
+ skipped: events.map((e) => ({ event: e.name, reason: 'already-instrumented' })),
118
+ changed: false,
119
+ };
120
+ }
121
+ const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
122
+ ast.injectTrackBeforeLastReturn(target.fn, target.body, stmts);
123
+ ast.ensureGuruluImport(tree);
124
+ const after = ast.generateSource(tree, source);
125
+ return {
126
+ ok: true,
127
+ after,
128
+ instrumented: events.map((e) => e.name),
129
+ skipped: [],
130
+ changed: true,
131
+ };
132
+ }
133
+
134
+ function resolveRouteFile(ctx, method, urlPath) {
135
+ const seen = new Set();
136
+ const candidates = [
137
+ ...CANDIDATE_ENTRIES,
138
+ ...walkRoutes(ctx.repoRoot),
139
+ ].filter((rel) => {
140
+ if (seen.has(rel)) return false;
141
+ seen.add(rel);
142
+ return fs.existsSync(path.join(ctx.repoRoot, rel));
143
+ });
144
+ for (const rel of candidates) {
145
+ const src = fs.readFileSync(path.join(ctx.repoRoot, rel), 'utf8');
146
+ if (!src.includes(urlPath)) continue;
147
+ try {
148
+ const tree = ast.parseSource(src);
149
+ const h = findFastifyHandlers(tree, method, urlPath);
150
+ if (h.length > 0) return rel;
151
+ } catch (_) {
152
+ // ignore
153
+ }
154
+ }
155
+ return null;
156
+ }
157
+
158
+ function instrumentEvents(ctx, events) {
159
+ const helper = singleton.ensureSingletonHelper(ctx, 'fastify');
160
+ const changes = [...helper.changes];
161
+ const notes = [...helper.notes];
162
+ let eventsInstrumented = 0;
163
+ let eventsSkipped = 0;
164
+
165
+ if (helper.collision) {
166
+ return {
167
+ changes: [],
168
+ notes,
169
+ filesModified: 0,
170
+ eventsInstrumented: 0,
171
+ eventsSkipped: events ? events.length : 0,
172
+ collision: true,
173
+ };
174
+ }
175
+
176
+ const groups = new Map();
177
+ for (const e of events || []) {
178
+ const parsed = parseEventRoute(e && e.source && e.source.route);
179
+ if (!parsed) {
180
+ notes.push(`skip:${e && e.name}:no-source-route`);
181
+ eventsSkipped++;
182
+ continue;
183
+ }
184
+ const rel = resolveRouteFile(ctx, parsed.method, parsed.urlPath);
185
+ if (!rel) {
186
+ notes.push(`skip:${e.name}:route-not-found`);
187
+ eventsSkipped++;
188
+ continue;
189
+ }
190
+ const key = `${rel}::${parsed.method}::${parsed.urlPath}`;
191
+ if (!groups.has(key)) {
192
+ groups.set(key, { relPath: rel, method: parsed.method, urlPath: parsed.urlPath, events: [] });
193
+ }
194
+ groups.get(key).events.push(e);
195
+ }
196
+
197
+ for (const group of groups.values()) {
198
+ const abs = path.join(ctx.repoRoot, group.relPath);
199
+ const before = fs.readFileSync(abs, 'utf8');
200
+ let res;
201
+ try {
202
+ res = astInstrumentFile(before, group.method, group.urlPath, group.events);
203
+ } catch (err) {
204
+ const msg = (err && err.message) || String(err);
205
+ // eslint-disable-next-line no-console
206
+ console.warn(`[auto-instrument] patch.fallback ${group.relPath}: ${msg}`);
207
+ notes.push(`patch.fallback:${group.relPath}:${msg}`);
208
+ continue;
209
+ }
210
+ if (!res.ok) {
211
+ for (const e of group.events) {
212
+ notes.push(`skip:${e.name}:${res.reason}`);
213
+ eventsSkipped++;
214
+ }
215
+ continue;
216
+ }
217
+ for (const s of res.skipped || []) {
218
+ notes.push(`skip:${s.event}:${s.reason}`);
219
+ eventsSkipped++;
220
+ }
221
+ if (res.changed) {
222
+ const existing = changes.find((c) => c.relPath === group.relPath && c.type === 'auto-instrument');
223
+ if (existing) {
224
+ existing.after = res.after;
225
+ } else {
226
+ changes.push({
227
+ relPath: group.relPath,
228
+ before,
229
+ after: res.after,
230
+ reason: `auto-instrument-fastify`,
231
+ type: 'auto-instrument',
232
+ });
233
+ }
234
+ eventsInstrumented += (res.instrumented || []).length;
235
+ }
236
+ }
237
+
238
+ const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
239
+ return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
240
+ }
241
+
242
+ function ensureSingletonHelper(ctx) {
243
+ return singleton.ensureSingletonHelper(ctx, 'fastify');
244
+ }
245
+
246
+ module.exports = {
247
+ name: NAME,
248
+ supportedFrameworks: SUPPORTED,
249
+ ensureSingletonHelper,
250
+ instrumentEvents,
251
+ _internals: {
252
+ parseEventRoute,
253
+ walkRoutes,
254
+ findFastifyHandlers,
255
+ astInstrumentFile,
256
+ resolveRouteFile,
257
+ },
258
+ };
@@ -0,0 +1,78 @@
1
+ // scripts/patches/auto-instrument/index.cjs — Phase 18.7 B auto-instrument
2
+ // dispatcher.
3
+ //
4
+ // Maps a resolved framework name to the matching auto-instrument module and
5
+ // exposes a single `dispatch(framework, ctx, events)` entry point used by
6
+ // `scripts/gurulu-agentic-install.mjs` and `packages/cli/src/commands/
7
+ // install.ts`. Modules themselves own singleton-helper planning and regex
8
+ // instrumentation; this index is just the registry.
9
+
10
+ const nextAppRouter = require('./nextjs-app-router.cjs');
11
+ const nextPages = require('./nextjs-pages.cjs');
12
+ const express = require('./express.cjs');
13
+ const viteReact = require('./vite-react.cjs');
14
+ const nestjs = require('./nestjs.cjs');
15
+ const remix = require('./remix.cjs');
16
+ const sveltekit = require('./sveltekit.cjs');
17
+ const astro = require('./astro.cjs');
18
+ const fastify = require('./fastify.cjs');
19
+ const vue = require('./vue.cjs');
20
+ const singleton = require('./singleton-helper.cjs');
21
+
22
+ const MODULES = [
23
+ nextAppRouter,
24
+ nextPages,
25
+ express,
26
+ viteReact,
27
+ nestjs,
28
+ remix,
29
+ sveltekit,
30
+ astro,
31
+ fastify,
32
+ vue,
33
+ ];
34
+
35
+ const MODULE_BY_FRAMEWORK = {};
36
+ for (const mod of MODULES) {
37
+ for (const fw of mod.supportedFrameworks) {
38
+ MODULE_BY_FRAMEWORK[fw] = mod;
39
+ }
40
+ }
41
+ // Aliases.
42
+ MODULE_BY_FRAMEWORK['nextjs'] = nextAppRouter;
43
+ MODULE_BY_FRAMEWORK['nextjs-app'] = nextAppRouter;
44
+
45
+ function resolveModule(framework) {
46
+ if (!framework) return null;
47
+ return MODULE_BY_FRAMEWORK[framework] || null;
48
+ }
49
+
50
+ /**
51
+ * Dispatch: given a framework, context, and a list of ProposedEvents, invoke
52
+ * the matching module's `instrumentEvents()` and return its plan result. If
53
+ * no module matches, returns a no-op plan with a note describing why.
54
+ */
55
+ function dispatch(framework, ctx, events) {
56
+ const mod = resolveModule(framework);
57
+ if (!mod) {
58
+ return {
59
+ changes: [],
60
+ notes: [`auto-instrument:no-module-for-${framework || 'auto'}`],
61
+ filesModified: 0,
62
+ eventsInstrumented: 0,
63
+ eventsSkipped: events ? events.length : 0,
64
+ collision: false,
65
+ module: null,
66
+ };
67
+ }
68
+ const result = mod.instrumentEvents(ctx, events);
69
+ return { ...result, module: mod.name };
70
+ }
71
+
72
+ module.exports = {
73
+ MODULES,
74
+ MODULE_BY_FRAMEWORK,
75
+ resolveModule,
76
+ dispatch,
77
+ singleton,
78
+ };