create-tigra 4.0.1 → 4.1.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.
- package/CHANGELOG.md +27 -0
- package/README.md +17 -2
- package/bin/create-tigra.js +72 -1
- package/lib/patchers/diagnostics.patcher.js +149 -0
- package/lib/patchers/metrics.patcher.js +145 -0
- package/modules/diagnostics/diagnostics.md +65 -0
- package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
- package/modules/diagnostics/prisma/migration.sql +43 -0
- package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
- package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +107 -0
- package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
- package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
- package/modules/diagnostics/server/diagnostics.context.ts +73 -0
- package/modules/diagnostics/server/diagnostics.repo.ts +69 -0
- package/modules/diagnostics/server/diagnostics.routes.ts +17 -0
- package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
- package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
- package/modules/diagnostics/server/diagnostics.service.ts +44 -0
- package/modules/metrics/client/WebVitalsReporter.tsx +35 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +65 -0
- package/modules/metrics/client/metrics.pages.ts +5 -0
- package/modules/metrics/performance.md +56 -0
- package/modules/metrics/prisma/metric-bucket.prisma +18 -0
- package/modules/metrics/prisma/migration.sql +17 -0
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +75 -0
- package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
- package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
- package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
- package/modules/metrics/server/metrics.collector.ts +130 -0
- package/modules/metrics/server/metrics.pages.ts +3 -0
- package/modules/metrics/server/metrics.repo.ts +45 -0
- package/modules/metrics/server/metrics.routes.ts +46 -0
- package/modules/metrics/server/metrics.schemas.ts +57 -0
- package/modules/metrics/server/metrics.service.ts +100 -0
- package/package.json +1 -1
- package/template/AGENTS.md +17 -10
- package/template/client/src/app/focus-rings.policy.test.ts +88 -0
- package/template/client/src/app/globals.css +46 -0
- package/template/client/src/app/layout.tsx +5 -0
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
- package/template/client/src/components/ui/input.tsx +3 -2
- package/template/client/src/lib/input-modality.test.ts +79 -0
- package/template/client/src/lib/input-modality.ts +52 -0
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,33 @@
|
|
|
3
3
|
A generated project never changes after it is created: these notes say what new projects get. To bring an older
|
|
4
4
|
project along, port the changes you need; the guides in [docs/](docs/) cover the ones that need care.
|
|
5
5
|
|
|
6
|
+
## 4.1.0 (2026-11-10)
|
|
7
|
+
|
|
8
|
+
- Add optional performance metrics for Fastify requests, Node runtime health, named operations, and Next.js Web Vitals. The module stores five-minute aggregates in MySQL and provides a read-only admin API.
|
|
9
|
+
- Add optional error and warning tracking with sanitized diagnostic samples, an hourly MySQL view, and a read-only admin API for agent investigations.
|
|
10
|
+
- Choose either module independently in the wizard or install it later with `npx create-tigra add metrics` or `npx create-tigra add diagnostics`. Each module adds its own migration and maintenance guidance.
|
|
11
|
+
- Expand generated agent guidance on architecture and reuse. Search the relevant client or server code for the closest behavior and follow imports and callers before adding a new implementation.
|
|
12
|
+
|
|
13
|
+
- Focus rings show only for keyboard users. Radix menus and selects cancel the mouse press on their trigger and then
|
|
14
|
+
move focus by script, so Chrome treated mouse use as keyboard use and drew focus rings (for example on a menu item
|
|
15
|
+
under the pointer) until the first ordinary click. The client now keeps `<html data-input="pointer" | "keyboard">`
|
|
16
|
+
(`lib/input-modality.ts`, mounted by `components/common/InputModalityTracker.tsx` in the root layout), Tailwind's
|
|
17
|
+
`focus-visible:` variant stays off in pointer mode, and a global rule drops plain-CSS focus outlines in pointer
|
|
18
|
+
mode. Text fields still show focus for mouse users too.
|
|
19
|
+
- Keyboard focus has one quiet style everywhere: a 1px accent line on the element's own edge and a faint accent tint
|
|
20
|
+
inside, with nothing drawn outside the element (it replaces the 3px half-transparent rings). Accent-filled controls
|
|
21
|
+
(primary and destructive buttons, hand-styled `bg-primary` / `bg-destructive` links) get the edge plus a 1px
|
|
22
|
+
page-coloured line inside it, since their fill is the accent; menu items and select options keep their highlight
|
|
23
|
+
only.
|
|
24
|
+
- Text fields lose the 3px glow too: focus turns the field's own border accent, an invalid field's border is red, and a
|
|
25
|
+
focused invalid field also gets a faint red tint inside, so focus stays visible on a field with an error.
|
|
26
|
+
- To port into an older project: copy those two files, add `data-input="pointer"` to `<html>` and mount the tracker
|
|
27
|
+
in `app/layout.tsx`, copy the `@custom-variant focus-visible` line and the four focus rules at the end of
|
|
28
|
+
`app/globals.css` ("Focus rings", "Keyboard focus", "Filled controls", "Text fields"), and change any `focus:ring`
|
|
29
|
+
(for example a dialog's close button) to `focus-visible:ring`. In `components/ui/input.tsx` (and a textarea, if
|
|
30
|
+
you have one) keep only `focus-visible:border-ring` and `aria-invalid:border-destructive` from the focus and
|
|
31
|
+
invalid classes. Remove any own `:focus-visible { outline }` a menu item or option has.
|
|
32
|
+
|
|
6
33
|
## 4.0.1 (2026-10-20)
|
|
7
34
|
|
|
8
35
|
Documentation only, no code changes.
|
package/README.md
CHANGED
|
@@ -251,18 +251,33 @@ server replica each runs them too, which is safe.
|
|
|
251
251
|
|
|
252
252
|
## Adding a module later
|
|
253
253
|
|
|
254
|
-
Modules add a feature to an existing project.
|
|
254
|
+
Modules add a feature to an existing project. The creation wizard asks about
|
|
255
|
+
email verification, performance metrics, and error and warning tracking independently:
|
|
255
256
|
|
|
256
257
|
```bash
|
|
257
258
|
cd my-app # the folder that holds server/ and client/
|
|
258
259
|
npx create-tigra add email-verification
|
|
260
|
+
npx create-tigra add metrics
|
|
261
|
+
npx create-tigra add diagnostics
|
|
259
262
|
```
|
|
260
263
|
|
|
261
|
-
|
|
264
|
+
The email verification module adds the routes (`POST /auth/send-verification`, `POST /auth/verify-account`), their integration
|
|
262
265
|
tests, the client's `useVerifyAccount` / `useSendVerification` hooks and service, and sets `REQUIRE_USER_VERIFICATION=true` in `server/.env`.
|
|
263
266
|
Then set `RESEND_API_KEY` in `server/.env` and restart the server. Answering "yes" to the email question when you
|
|
264
267
|
create a project does the same. Run it on projects made with 4.x: it copies tests that use the 4.x test helpers.
|
|
265
268
|
|
|
269
|
+
The metrics module collects request and operation timings, Node runtime
|
|
270
|
+
measurements, and browser Web Vitals into five-minute MySQL buckets. Apply the
|
|
271
|
+
added Prisma migration and regenerate the Prisma client before starting the
|
|
272
|
+
server. The generated `server/docs/performance.md` explains the admin API,
|
|
273
|
+
sampling, and how to extend coverage when adding features.
|
|
274
|
+
|
|
275
|
+
The diagnostics module groups unexpected server errors and actionable warnings
|
|
276
|
+
with safe messages and source frames. Apply the additive Prisma migration and
|
|
277
|
+
regenerate the client before starting the server. The generated
|
|
278
|
+
`server/docs/diagnostics.md` gives agents copyable commands for the read-only
|
|
279
|
+
MySQL view and the admin API. Diagnostic history has no automatic expiry.
|
|
280
|
+
|
|
266
281
|
## Documentation
|
|
267
282
|
|
|
268
283
|
In every generated project:
|
package/bin/create-tigra.js
CHANGED
|
@@ -227,7 +227,7 @@ function registerAddCommand(program) {
|
|
|
227
227
|
process.exit(1);
|
|
228
228
|
}
|
|
229
229
|
|
|
230
|
-
const availableModules = ['email-verification'];
|
|
230
|
+
const availableModules = ['email-verification', 'metrics', 'diagnostics'];
|
|
231
231
|
|
|
232
232
|
if (!availableModules.includes(moduleName)) {
|
|
233
233
|
console.error(chalk.red(` Unknown module: "${moduleName}"`));
|
|
@@ -240,6 +240,39 @@ function registerAddCommand(program) {
|
|
|
240
240
|
process.exit(1);
|
|
241
241
|
}
|
|
242
242
|
|
|
243
|
+
if (moduleName === 'metrics') {
|
|
244
|
+
const spinner = ora('Adding performance metrics module...').start();
|
|
245
|
+
try {
|
|
246
|
+
const { applyMetricsModule } = await import('../lib/patchers/metrics.patcher.js');
|
|
247
|
+
const installed = await applyMetricsModule(projectDir);
|
|
248
|
+
spinner.succeed(installed ? 'Performance metrics module added!' : 'Performance metrics is already installed.');
|
|
249
|
+
if (installed) {
|
|
250
|
+
console.log(' Apply the Prisma migration and regenerate the client from server/.');
|
|
251
|
+
console.log(' See server/docs/performance.md for settings and the admin API.');
|
|
252
|
+
}
|
|
253
|
+
} catch (error) {
|
|
254
|
+
spinner.fail('Failed to add performance metrics');
|
|
255
|
+
console.error(chalk.red(`\n ${error.message}\n`));
|
|
256
|
+
process.exit(1);
|
|
257
|
+
}
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (moduleName === 'diagnostics') {
|
|
262
|
+
const spinner = ora('Adding error and warning diagnostics...').start();
|
|
263
|
+
try {
|
|
264
|
+
const { applyDiagnosticsModule } = await import('../lib/patchers/diagnostics.patcher.js');
|
|
265
|
+
const installed = await applyDiagnosticsModule(projectDir);
|
|
266
|
+
spinner.succeed(installed ? 'Diagnostics module added!' : 'Diagnostics is already installed.');
|
|
267
|
+
if (installed) console.log(' Apply the Prisma migration and regenerate the client from server/. See server/docs/diagnostics.md.');
|
|
268
|
+
} catch (error) {
|
|
269
|
+
spinner.fail('Failed to add diagnostics');
|
|
270
|
+
console.error(chalk.red(`\n ${error.message}\n`));
|
|
271
|
+
process.exit(1);
|
|
272
|
+
}
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
|
|
243
276
|
if (moduleName === 'email-verification') {
|
|
244
277
|
// Check if already applied
|
|
245
278
|
const alreadyApplied = await fs.pathExists(
|
|
@@ -362,6 +395,26 @@ async function main() {
|
|
|
362
395
|
hint: 'Users must verify email before accessing the app',
|
|
363
396
|
});
|
|
364
397
|
|
|
398
|
+
const { enableMetrics } = await ask({
|
|
399
|
+
type: 'toggle',
|
|
400
|
+
name: 'enableMetrics',
|
|
401
|
+
message: 'Enable performance metrics?',
|
|
402
|
+
initial: false,
|
|
403
|
+
active: 'Yes',
|
|
404
|
+
inactive: 'No',
|
|
405
|
+
hint: 'Collect request, runtime and browser measurements',
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
const { enableDiagnostics } = await ask({
|
|
409
|
+
type: 'toggle',
|
|
410
|
+
name: 'enableDiagnostics',
|
|
411
|
+
message: 'Enable error and warning tracking?',
|
|
412
|
+
initial: false,
|
|
413
|
+
active: 'Yes',
|
|
414
|
+
inactive: 'No',
|
|
415
|
+
hint: 'Store grouped server diagnostics for agents',
|
|
416
|
+
});
|
|
417
|
+
|
|
365
418
|
// Generate random port offset (1-200) so multiple projects don't conflict
|
|
366
419
|
const portOffset = crypto.randomInt(1, 201);
|
|
367
420
|
|
|
@@ -424,6 +477,14 @@ async function main() {
|
|
|
424
477
|
const { applyEmailVerificationModule } = await import('../lib/patchers/email-verification.patcher.js');
|
|
425
478
|
await applyEmailVerificationModule(targetDir);
|
|
426
479
|
}
|
|
480
|
+
if (enableMetrics) {
|
|
481
|
+
const { applyMetricsModule } = await import('../lib/patchers/metrics.patcher.js');
|
|
482
|
+
await applyMetricsModule(targetDir);
|
|
483
|
+
}
|
|
484
|
+
if (enableDiagnostics) {
|
|
485
|
+
const { applyDiagnosticsModule } = await import('../lib/patchers/diagnostics.patcher.js');
|
|
486
|
+
await applyDiagnosticsModule(targetDir);
|
|
487
|
+
}
|
|
427
488
|
|
|
428
489
|
spinner.succeed('Project scaffolded successfully!');
|
|
429
490
|
} catch (error) {
|
|
@@ -485,6 +546,16 @@ async function main() {
|
|
|
485
546
|
console.log(dim(' Set RESEND_API_KEY in server/.env to send emails'));
|
|
486
547
|
console.log();
|
|
487
548
|
}
|
|
549
|
+
if (enableMetrics) {
|
|
550
|
+
console.log(dim(' Performance metrics: ') + green('enabled after migration'));
|
|
551
|
+
console.log(dim(' See server/docs/performance.md for the admin API and collection settings'));
|
|
552
|
+
console.log();
|
|
553
|
+
}
|
|
554
|
+
if (enableDiagnostics) {
|
|
555
|
+
console.log(dim(' Error and warning diagnostics: ') + green('enabled after migration'));
|
|
556
|
+
console.log(dim(' See server/docs/diagnostics.md for agent read commands'));
|
|
557
|
+
console.log();
|
|
558
|
+
}
|
|
488
559
|
console.log(dim(' Tip: ') + 'npm run docker:down' + dim(' to stop infrastructure'));
|
|
489
560
|
console.log();
|
|
490
561
|
console.log(dim(' Happy coding! 🚀'));
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import fs from 'fs-extra';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
const payload = fileURLToPath(new URL('../../modules/diagnostics/', import.meta.url));
|
|
6
|
+
const moduleDir = 'server/src/modules/diagnostics';
|
|
7
|
+
const schema = 'server/prisma/schema.prisma';
|
|
8
|
+
const migrations = 'server/prisma/migrations';
|
|
9
|
+
const marker = `${moduleDir}/installation.json`;
|
|
10
|
+
const heading = '## Error and warning diagnostics';
|
|
11
|
+
const guide = 'server/docs/diagnostics.md';
|
|
12
|
+
const instruction = `${heading}\n\nWhen diagnostics is installed, use the [diagnostics guide](${guide}) to investigate error history through the read-only MySQL skill or admin API. Report observed failures separately from inferred causes. Verify automatic capture for new requests and jobs, and record handled failures or actionable warnings with stable codes and safe messages.\n`;
|
|
13
|
+
|
|
14
|
+
const transforms = {
|
|
15
|
+
'server/src/app.ts': [
|
|
16
|
+
["import { registerErrorHandler } from '@libs/error-handler.js';", "import { registerErrorHandler } from '@libs/error-handler.js';\nimport { registerDiagnostics } from '@modules/diagnostics/diagnostics.service.js';"],
|
|
17
|
+
[' const { onRoute } = options;', ' const { onRoute } = options;\n registerDiagnostics(app);'],
|
|
18
|
+
],
|
|
19
|
+
'server/src/libs/error-handler.ts': [
|
|
20
|
+
["import { logger } from '@libs/logger.js';", "import { logger } from '@libs/logger.js';\nimport { captureRequestFailure } from '@modules/diagnostics/diagnostics.context.js';"],
|
|
21
|
+
[' if (isAppError(error)) {', ' if (isAppError(error)) {\n if (error.statusCode >= 500) captureRequestFailure(error);'],
|
|
22
|
+
[" const requestId = request.id || 'unknown';", " captureRequestFailure(error);\n const requestId = request.id || 'unknown';"],
|
|
23
|
+
],
|
|
24
|
+
'server/src/jobs/schedule.ts': [
|
|
25
|
+
["import { logger } from '@libs/logger.js';", "import { logger } from '@libs/logger.js';\nimport { captureJobFailure, withDiagnosticJob } from '@modules/diagnostics/diagnostics.context.js';"],
|
|
26
|
+
[' const tick = async (): Promise<void> => {', ' const tick = (): Promise<void> => withDiagnosticJob(app, job.name, async () => {'],
|
|
27
|
+
[' } catch (error) {', ' } catch (error) {\n captureJobFailure(error);'],
|
|
28
|
+
[' };\n\n const firstRun', ' });\n\n const firstRun'],
|
|
29
|
+
],
|
|
30
|
+
'server/src/modules/admin/admin.routes.ts': [
|
|
31
|
+
["import { authenticate, authorize } from '@libs/auth.js';", "import { authenticate, authorize } from '@libs/auth.js';\nimport { registerAdminDiagnosticsRoute } from '@modules/diagnostics/diagnostics.routes.js';"],
|
|
32
|
+
[" fastify.addHook('preValidation', authorize('ADMIN'));", " fastify.addHook('preValidation', authorize('ADMIN'));\n registerAdminDiagnosticsRoute(fastify);"],
|
|
33
|
+
],
|
|
34
|
+
'server/src/__tests__/routes.integration.test.ts': [
|
|
35
|
+
['const COVERED_ELSEWHERE: Record<string, string> = {', "const COVERED_ELSEWHERE: Record<string, string> = {\n 'GET /api/v1/admin/diagnostics': 'src/modules/diagnostics/__tests__/diagnostics.integration.test.ts',"],
|
|
36
|
+
],
|
|
37
|
+
'server/src/test/integration.global-setup.ts': [
|
|
38
|
+
[' const tables = await tx.$queryRaw<{ name: string }[]>', ' // The guarded test database reset must also remove the diagnostics view.\n await tx.$executeRaw`DROP VIEW IF EXISTS diagnostic_hourly_top`;\n const tables = await tx.$queryRaw<{ name: string }[]>'],
|
|
39
|
+
],
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
function patch(file, content, edits) {
|
|
43
|
+
const newline = content.includes('\r\n') ? '\r\n' : '\n';
|
|
44
|
+
let patched = content.replaceAll('\r\n', '\n');
|
|
45
|
+
for (const [anchor, replacement] of edits) {
|
|
46
|
+
const index = patched.indexOf(anchor);
|
|
47
|
+
if (index === -1 || patched.indexOf(anchor, index + anchor.length) !== -1) {
|
|
48
|
+
throw new Error(`Cannot install diagnostics: expected one integration point in ${file}.`);
|
|
49
|
+
}
|
|
50
|
+
patched = patched.replace(anchor, replacement);
|
|
51
|
+
}
|
|
52
|
+
return patched.replaceAll('\n', newline);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function migrationName(existing) {
|
|
56
|
+
const timestamp = (date) => date.toISOString().slice(0, 19).replace(/\D/g, '');
|
|
57
|
+
const now = new Date();
|
|
58
|
+
let name = `${timestamp(now)}_diagnostics`;
|
|
59
|
+
const last = existing.at(-1);
|
|
60
|
+
if (!last || last < name) return name;
|
|
61
|
+
const date = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})_/.exec(last);
|
|
62
|
+
if (date) {
|
|
63
|
+
const [, year, month, day, hour, minute, second] = date;
|
|
64
|
+
const lastTime = Date.parse(`${year}-${month}-${day}T${hour}:${minute}:${second}Z`);
|
|
65
|
+
if (Number.isFinite(lastTime)) name = `${timestamp(new Date(lastTime + 1_000))}_diagnostics`;
|
|
66
|
+
}
|
|
67
|
+
if (last >= name) throw new Error('Cannot place the diagnostics migration after the existing migrations.');
|
|
68
|
+
return name;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function applyDiagnosticsModule(root) {
|
|
72
|
+
const at = (file) => path.join(root, file);
|
|
73
|
+
const read = (file) => fs.readFile(at(file), 'utf8');
|
|
74
|
+
const originalSchema = await read(schema);
|
|
75
|
+
const agents = await read('AGENTS.md');
|
|
76
|
+
const serverPayload = path.join(payload, 'server');
|
|
77
|
+
const sources = (await fs.readdir(serverPayload, { recursive: true, withFileTypes: true }))
|
|
78
|
+
.filter((entry) => entry.isFile())
|
|
79
|
+
.map((entry) => {
|
|
80
|
+
const source = path.join(entry.parentPath, entry.name);
|
|
81
|
+
return [source, path.join(moduleDir, path.relative(serverPayload, source))];
|
|
82
|
+
});
|
|
83
|
+
sources.push([path.join(payload, 'diagnostics.md'), guide]);
|
|
84
|
+
|
|
85
|
+
if (await fs.pathExists(at(marker))) {
|
|
86
|
+
const { migration } = await fs.readJson(at(marker));
|
|
87
|
+
const expected = typeof migration === 'string' && /^\d{14}_diagnostics$/.test(migration);
|
|
88
|
+
const installedFiles = [...sources.map(([, file]) => file), `${migrations}/${migration}/migration.sql`];
|
|
89
|
+
const integrations = await Promise.all(Object.entries(transforms).map(async ([file, edits]) => {
|
|
90
|
+
const content = (await read(file)).replaceAll('\r\n', '\n');
|
|
91
|
+
// Another module can insert lines between ours and a shared anchor.
|
|
92
|
+
return edits.every(([, replacement]) => replacement.split('\n').every((line) => content.includes(line)));
|
|
93
|
+
}));
|
|
94
|
+
if (!expected || !originalSchema.includes('model DiagnosticBucket') || !agents.includes(heading) ||
|
|
95
|
+
!integrations.every(Boolean) || !(await Promise.all(installedFiles.map((file) => fs.pathExists(at(file))))).every(Boolean)) {
|
|
96
|
+
throw new Error('The diagnostics installation is incomplete. Restore the missing integration or pre-install state.');
|
|
97
|
+
}
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const existing = (await fs.readdir(at(migrations), { withFileTypes: true }))
|
|
102
|
+
.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
103
|
+
if (!/provider\s*=\s*"mysql"/.test(originalSchema) || /DiagnosticBucket|diagnostic_buckets/.test(originalSchema) ||
|
|
104
|
+
agents.includes(heading) || await fs.pathExists(at(moduleDir)) || existing.some((name) => name.endsWith('_diagnostics'))) {
|
|
105
|
+
throw new Error('Diagnostics requires a compatible MySQL Tigra project with no partial diagnostics installation.');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Prepare the full change before writing any file. If a write fails, restore
|
|
109
|
+
// the original files in reverse order and leave the completion marker absent.
|
|
110
|
+
const migration = migrationName(existing);
|
|
111
|
+
sources.push([path.join(payload, 'prisma/migration.sql'), `${migrations}/${migration}/migration.sql`]);
|
|
112
|
+
const writes = [];
|
|
113
|
+
for (const [source, file] of sources) {
|
|
114
|
+
if (await fs.pathExists(at(file))) throw new Error(`Cannot install diagnostics: ${file} already exists.`);
|
|
115
|
+
writes.push({ file, next: await fs.readFile(source) });
|
|
116
|
+
}
|
|
117
|
+
for (const [file, edits] of Object.entries(transforms)) {
|
|
118
|
+
const original = await read(file);
|
|
119
|
+
if (original.includes('@modules/diagnostics/') || original.includes('GET /api/v1/admin/diagnostics')) {
|
|
120
|
+
throw new Error(`Cannot install over partial diagnostics integration in ${file}.`);
|
|
121
|
+
}
|
|
122
|
+
writes.push({ file, original, next: patch(file, original, edits) });
|
|
123
|
+
}
|
|
124
|
+
const model = await fs.readFile(path.join(payload, 'prisma/diagnostic-bucket.prisma'), 'utf8');
|
|
125
|
+
writes.push({ file: schema, original: originalSchema, next: `${originalSchema.trimEnd()}\n\n${model}` });
|
|
126
|
+
writes.push({ file: 'AGENTS.md', original: agents, next: `${agents.trimEnd()}\n\n${instruction}` });
|
|
127
|
+
writes.push({ file: marker, next: `${JSON.stringify({ migration }, null, 2)}\n` });
|
|
128
|
+
|
|
129
|
+
// An exclusive directory creation keeps two diagnostics installers from
|
|
130
|
+
// writing the same checkout after both complete preflight.
|
|
131
|
+
await fs.mkdir(at(moduleDir));
|
|
132
|
+
const attempted = [];
|
|
133
|
+
try {
|
|
134
|
+
for (const write of writes) {
|
|
135
|
+
attempted.push(write);
|
|
136
|
+
await fs.outputFile(at(write.file), write.next);
|
|
137
|
+
}
|
|
138
|
+
} catch (error) {
|
|
139
|
+
for (const { file, original } of attempted.reverse()) {
|
|
140
|
+
if (original === undefined) await fs.unlink(at(file)).catch((failure) => { if (failure.code !== 'ENOENT') throw failure; });
|
|
141
|
+
else await fs.writeFile(at(file), original);
|
|
142
|
+
}
|
|
143
|
+
for (const file of [`${moduleDir}/__tests__`, moduleDir, `${migrations}/${migration}`]) {
|
|
144
|
+
await fs.rmdir(at(file)).catch(() => {}); // Only empty directories created by this installer.
|
|
145
|
+
}
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import fs from 'fs-extra';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
const payload = fileURLToPath(new URL('../../modules/metrics/', import.meta.url));
|
|
6
|
+
const server = 'server/src/modules/metrics';
|
|
7
|
+
const client = 'client/src/features/metrics';
|
|
8
|
+
const schema = 'server/prisma/schema.prisma';
|
|
9
|
+
const marker = `${server}/installation.json`;
|
|
10
|
+
const migrations = 'server/prisma/migrations';
|
|
11
|
+
const coverage = 'src/modules/metrics/__tests__/metrics.integration.test.ts';
|
|
12
|
+
const instruction = [
|
|
13
|
+
'## Performance metrics',
|
|
14
|
+
'',
|
|
15
|
+
'When metrics are installed, maintain performance coverage with every feature change. Verify request and Web Vitals coverage for new routes and pages. Add named timings for meaningful dependency calls and jobs, update page groups where needed, and verify that the affected measurements reach storage and the admin API. Use stable labels free of user data.',
|
|
16
|
+
'',
|
|
17
|
+
'See the [performance guide](server/docs/performance.md) for the collection and read contracts.',
|
|
18
|
+
].join('\n');
|
|
19
|
+
|
|
20
|
+
const transforms = {
|
|
21
|
+
'server/src/app.ts': [
|
|
22
|
+
["import { env } from '@config/env.js';", `\nimport { registerMetrics } from '@modules/metrics/metrics.service.js';\nimport { webVitalsRoutes } from '@modules/metrics/metrics.routes.js';`],
|
|
23
|
+
[' const { onRoute } = options;', '\n const metrics = registerMetrics(app);'],
|
|
24
|
+
[" await app.register(adminRoutes, { prefix: '/api/v1' });", "\n await app.register(webVitalsRoutes, { prefix: '/api/v1', collector: metrics });"],
|
|
25
|
+
],
|
|
26
|
+
'server/src/modules/admin/admin.routes.ts': [
|
|
27
|
+
["import { authenticate, authorize } from '@libs/auth.js';", "\nimport { registerAdminMetricsRoute } from '@modules/metrics/metrics.routes.js';"],
|
|
28
|
+
[" fastify.addHook('preValidation', authorize('ADMIN'));", '\n registerAdminMetricsRoute(fastify);'],
|
|
29
|
+
],
|
|
30
|
+
'server/src/config/env.ts': [
|
|
31
|
+
['const envSchema = z.object({', '\n METRICS_ENABLED: envBoolean(true),'],
|
|
32
|
+
],
|
|
33
|
+
'server/src/config/rate-limit.config.ts': [
|
|
34
|
+
[" ADMIN_DEFAULT: routeLimit('ADMIN_DEFAULT', 30, '1m'),", "\n METRICS_INGESTION: routeLimit('METRICS_INGESTION', 120, '1m'),"],
|
|
35
|
+
],
|
|
36
|
+
'server/src/config/__tests__/rate-limit.config.test.ts': [
|
|
37
|
+
[' ADMIN_DEFAULT: { max: 30, timeWindow: MIN },', '\n METRICS_INGESTION: { max: 120, timeWindow: MIN },'],
|
|
38
|
+
],
|
|
39
|
+
'server/src/__tests__/routes.integration.test.ts': [
|
|
40
|
+
['const COVERED_ELSEWHERE: Record<string, string> = {', `\n 'POST /api/v1/metrics/web-vitals': '${coverage}',\n 'GET /api/v1/admin/metrics': '${coverage}',`],
|
|
41
|
+
],
|
|
42
|
+
'client/src/app/providers.tsx': [
|
|
43
|
+
["import { Toaster } from 'sonner';", "\nimport { WebVitalsReporter } from '@/features/metrics/WebVitalsReporter';"],
|
|
44
|
+
[' <Toaster position="top-right" richColors />', '\n <WebVitalsReporter />'],
|
|
45
|
+
],
|
|
46
|
+
'client/src/lib/env.ts': [
|
|
47
|
+
['const envSchema = z.object({', "\n NEXT_PUBLIC_METRICS_SAMPLE_RATE: z.preprocess((value) => value === '' ? undefined : value, z.coerce.number().min(0).max(1).default(1)),"],
|
|
48
|
+
[' const result = envSchema.safeParse({', '\n NEXT_PUBLIC_METRICS_SAMPLE_RATE: process.env.NEXT_PUBLIC_METRICS_SAMPLE_RATE,'],
|
|
49
|
+
],
|
|
50
|
+
'client/Dockerfile': [
|
|
51
|
+
['ARG NEXT_PUBLIC_API_BASE_URL', '\nARG NEXT_PUBLIC_METRICS_SAMPLE_RATE=1'],
|
|
52
|
+
['ENV NEXT_PUBLIC_API_BASE_URL=$NEXT_PUBLIC_API_BASE_URL', '\nENV NEXT_PUBLIC_METRICS_SAMPLE_RATE=$NEXT_PUBLIC_METRICS_SAMPLE_RATE'],
|
|
53
|
+
],
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
async function payloadFiles(source, target) {
|
|
57
|
+
const entries = await fs.readdir(path.join(payload, source), { withFileTypes: true });
|
|
58
|
+
return (await Promise.all(entries.map((entry) => {
|
|
59
|
+
const nextSource = `${source}/${entry.name}`;
|
|
60
|
+
const nextTarget = `${target}/${entry.name}`;
|
|
61
|
+
return entry.isDirectory() ? payloadFiles(nextSource, nextTarget) : [[nextSource, nextTarget]];
|
|
62
|
+
}))).flat();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function patchAnchor(content, file, anchor, addition) {
|
|
66
|
+
const index = content.indexOf(anchor);
|
|
67
|
+
if (index === -1 || content.indexOf(anchor, index + anchor.length) !== -1) {
|
|
68
|
+
throw new Error(`Cannot install metrics: expected one integration anchor in ${file}. Review the module guide and integrate that customization manually.`);
|
|
69
|
+
}
|
|
70
|
+
const newline = content.includes('\r\n') ? '\r\n' : '\n';
|
|
71
|
+
return content.replace(anchor, anchor + addition.replaceAll('\n', newline));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function applyMetricsModule(root) {
|
|
75
|
+
const read = (file) => fs.readFile(path.join(root, file), 'utf8');
|
|
76
|
+
const exists = (file) => fs.pathExists(path.join(root, file));
|
|
77
|
+
const copies = [
|
|
78
|
+
...await payloadFiles('server', server),
|
|
79
|
+
...await payloadFiles('client', client),
|
|
80
|
+
['performance.md', 'server/docs/performance.md'],
|
|
81
|
+
];
|
|
82
|
+
const originalSchema = await read(schema);
|
|
83
|
+
const agents = await read('AGENTS.md');
|
|
84
|
+
if (await exists(marker)) {
|
|
85
|
+
const install = JSON.parse(await read(marker));
|
|
86
|
+
const migration = typeof install.migration === 'string' && /^\d{14}_metrics$/.test(install.migration)
|
|
87
|
+
? `${migrations}/${install.migration}/migration.sql` : null;
|
|
88
|
+
if (!migration || !await exists(migration) || !originalSchema.includes('model MetricBucket') ||
|
|
89
|
+
!agents.includes('## Performance metrics') ||
|
|
90
|
+
!(await Promise.all(copies.map(([, file]) => exists(file)))).every(Boolean)) {
|
|
91
|
+
throw new Error('The metrics installation is incomplete. Restore the missing module files or restore the pre-install state.');
|
|
92
|
+
}
|
|
93
|
+
for (const [file, anchors] of Object.entries(transforms)) {
|
|
94
|
+
const content = (await read(file)).replaceAll('\r\n', '\n');
|
|
95
|
+
if (anchors.some(([, addition]) => !content.includes(addition.trim()))) {
|
|
96
|
+
throw new Error(`The metrics installation is incomplete at ${file}. Restore its metrics integration before continuing.`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
if (!/provider\s*=\s*"mysql"/.test(originalSchema) || /\bMetricBucket\b|metric_buckets/.test(originalSchema) ||
|
|
102
|
+
agents.includes('## Performance metrics') || await exists(server) || await exists(client)) {
|
|
103
|
+
throw new Error('Metrics needs a compatible MySQL Tigra project with no partial metrics installation.');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Build the entire write set first. A missing/ambiguous anchor or migration
|
|
107
|
+
// collision must not leave a customized app half patched.
|
|
108
|
+
const existingMigrations = (await fs.readdir(path.join(root, migrations), { withFileTypes: true }))
|
|
109
|
+
.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
110
|
+
const migration = `${new Date().toISOString().slice(0, 19).replace(/\D/g, '')}_metrics`;
|
|
111
|
+
if (existingMigrations.some((name) => name.endsWith('_metrics') || name >= migration)) {
|
|
112
|
+
throw new Error('Cannot place the metrics migration after the existing migrations. Check the migration history.');
|
|
113
|
+
}
|
|
114
|
+
copies.push(['prisma/migration.sql', `${migrations}/${migration}/migration.sql`]);
|
|
115
|
+
const writes = new Map();
|
|
116
|
+
for (const [source, target] of copies) {
|
|
117
|
+
if (await exists(target)) throw new Error(`Cannot install metrics: ${target} already exists.`);
|
|
118
|
+
writes.set(target, await fs.readFile(path.join(payload, source)));
|
|
119
|
+
}
|
|
120
|
+
for (const [file, anchors] of Object.entries(transforms)) {
|
|
121
|
+
let content = await read(file);
|
|
122
|
+
for (const [anchor, addition] of anchors) {
|
|
123
|
+
if (content.replaceAll('\r\n', '\n').includes(addition.trim())) {
|
|
124
|
+
throw new Error(`Cannot install metrics over an incomplete installation at ${file}.`);
|
|
125
|
+
}
|
|
126
|
+
content = patchAnchor(content, file, anchor, addition);
|
|
127
|
+
}
|
|
128
|
+
writes.set(file, content);
|
|
129
|
+
}
|
|
130
|
+
writes.set(schema, `${originalSchema.trimEnd()}\n\n${await fs.readFile(path.join(payload, 'prisma/metric-bucket.prisma'), 'utf8')}`);
|
|
131
|
+
writes.set('AGENTS.md', `${agents.trimEnd()}\n\n${instruction}\n`);
|
|
132
|
+
for (const side of ['server', 'client']) {
|
|
133
|
+
const setting = side === 'server' ? 'METRICS_ENABLED=true' : 'NEXT_PUBLIC_METRICS_SAMPLE_RATE=1';
|
|
134
|
+
for (const example of ['.env.example', '.env.example.production']) {
|
|
135
|
+
const file = `${side}/${example}`;
|
|
136
|
+
const content = await read(file);
|
|
137
|
+
if (content.includes(setting.split('=')[0])) throw new Error(`Metrics configuration already exists in ${file}.`);
|
|
138
|
+
writes.set(file, `${content.trimEnd()}\n\n# Optional performance metrics\n${setting}\n`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
for (const [file, content] of writes) await fs.outputFile(path.join(root, file), content);
|
|
142
|
+
// Only a finished installation gets a completion marker.
|
|
143
|
+
await fs.outputJson(path.join(root, marker), { migration }, { spaces: 2 });
|
|
144
|
+
return true;
|
|
145
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Investigating server errors and warnings
|
|
2
|
+
|
|
3
|
+
Start with the most recent completed UTC hour unless the user gives a range.
|
|
4
|
+
Check errors first and repeat for warnings when relevant. Use the app checkout
|
|
5
|
+
and its configured instance. Read the diagnostics through either path below.
|
|
6
|
+
Report observed counts and samples separately from what the source suggests
|
|
7
|
+
caused them. Use the recorded release to locate the matching source revision.
|
|
8
|
+
|
|
9
|
+
## Read with the shared MySQL skill
|
|
10
|
+
|
|
11
|
+
Use `seed-mysql-control` with the application's existing read-only access.
|
|
12
|
+
The example uses PowerShell. Set the checkout, instance and UTC hour for the
|
|
13
|
+
project under investigation. The hour format is `YYYY-MM-DD HH:00:00`.
|
|
14
|
+
|
|
15
|
+
```powershell
|
|
16
|
+
$tool = 'C:/Users/seed/Documents/GitHub/seed-plugins/mysql/mysql_control.py'
|
|
17
|
+
$app = 'C:/path/to/generated-app'
|
|
18
|
+
$instance = 'kotiko'
|
|
19
|
+
$hour = (Get-Date).ToUniversalTime().AddHours(-1).ToString('yyyy-MM-dd HH:00:00')
|
|
20
|
+
uv run --script $tool select $instance --repo-root $app --table diagnostic_hourly_top --columns hour_start,severity,group_rank,group_id,occurrence_count,first_seen,last_seen,source,label,code,message,frames,release --where "hour_start=$hour" --where 'severity=error' --limit 10
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Sort returned rows by `group_rank`. Use `severity=warning` for warnings. The
|
|
24
|
+
view returns at most ten groups for each exact hour and severity. Use the
|
|
25
|
+
admin API for custom intervals and for groups outside the hourly top ten.
|
|
26
|
+
|
|
27
|
+
## Read with an existing admin session
|
|
28
|
+
|
|
29
|
+
Use the project's existing admin session cookie jar. Do not print or copy the
|
|
30
|
+
cookies into diagnostic evidence. Replace the server origin and times below.
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
curl -fsS --cookie "$ADMIN_COOKIE_JAR" --get "$API_ORIGIN/api/v1/admin/diagnostics" \
|
|
34
|
+
--data-urlencode 'from=2026-07-21T12:00:00Z' \
|
|
35
|
+
--data-urlencode 'to=2026-07-21T13:00:00Z' \
|
|
36
|
+
--data-urlencode 'severity=error' --data-urlencode 'limit=10'
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`data.groups` is ranked by count, then group ID. Use `groupId` for one group
|
|
40
|
+
and `nextCursor` for more results with the same filters. `from` is inclusive,
|
|
41
|
+
`to` is exclusive, and both must identify five-minute boundaries with an
|
|
42
|
+
explicit timezone. A range can span up to seven days. Counts can change if
|
|
43
|
+
more batches arrive between requests. A valid empty range returns no groups.
|
|
44
|
+
|
|
45
|
+
Read `label`, `code`, `message`, and the first entry in `frames`. Open that
|
|
46
|
+
application-relative source file and inspect the function and line when known.
|
|
47
|
+
A null line means the stack came from compiled code without source maps. A
|
|
48
|
+
null release means the server commit was unavailable. The displayed sample and
|
|
49
|
+
release belong to the latest occurrence in the requested group and range.
|
|
50
|
+
When the commit is available locally, `git show <release>:server/<frame.file>`
|
|
51
|
+
opens the source at that release without switching branches.
|
|
52
|
+
|
|
53
|
+
## Maintain coverage
|
|
54
|
+
|
|
55
|
+
Unexpected request failures and failed recurring jobs are captured where the
|
|
56
|
+
scaffold handles them. Use `recordDiagnostic` from the diagnostics context
|
|
57
|
+
inside a request or job for a handled failure or an actionable warning. Use
|
|
58
|
+
a static operation name and add application-owned reason text to
|
|
59
|
+
`diagnosticMessages` when needed. Pass the original Error if it may be
|
|
60
|
+
rethrown. Keep all customer data and variable text out of labels and messages.
|
|
61
|
+
|
|
62
|
+
Counts persist in five-minute contributions. Writes normally flush within 15
|
|
63
|
+
seconds. Outages and shutdown can delay or drop samples after the bounded
|
|
64
|
+
buffer fills. Missing data alone does not establish that no failures occurred.
|
|
65
|
+
Diagnostics has no automatic expiry.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// An immutable contribution from one process and flush batch.
|
|
2
|
+
model DiagnosticBucket {
|
|
3
|
+
id String @id @db.Char(64)
|
|
4
|
+
bucketStart DateTime @map("bucket_start") @db.DateTime(3)
|
|
5
|
+
hourStart DateTime @map("hour_start") @db.DateTime(3)
|
|
6
|
+
groupId String @map("group_id") @db.Char(64)
|
|
7
|
+
severity String @db.VarChar(8)
|
|
8
|
+
source String @db.VarChar(12)
|
|
9
|
+
label String @db.VarChar(191)
|
|
10
|
+
code String? @db.VarChar(64)
|
|
11
|
+
message String @db.VarChar(255)
|
|
12
|
+
frames Json
|
|
13
|
+
occurrences Int @db.UnsignedInt
|
|
14
|
+
firstSeen DateTime @map("first_seen") @db.DateTime(3)
|
|
15
|
+
lastSeen DateTime @map("last_seen") @db.DateTime(3)
|
|
16
|
+
release String? @db.VarChar(64)
|
|
17
|
+
|
|
18
|
+
@@index([bucketStart, severity, groupId])
|
|
19
|
+
@@index([hourStart, severity, groupId])
|
|
20
|
+
@@index([groupId, bucketStart])
|
|
21
|
+
@@map("diagnostic_buckets")
|
|
22
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
CREATE TABLE `diagnostic_buckets` (
|
|
2
|
+
`id` CHAR(64) NOT NULL,
|
|
3
|
+
`bucket_start` DATETIME(3) NOT NULL,
|
|
4
|
+
`hour_start` DATETIME(3) NOT NULL,
|
|
5
|
+
`group_id` CHAR(64) NOT NULL,
|
|
6
|
+
`severity` VARCHAR(8) NOT NULL,
|
|
7
|
+
`source` VARCHAR(12) NOT NULL,
|
|
8
|
+
`label` VARCHAR(191) NOT NULL,
|
|
9
|
+
`code` VARCHAR(64) NULL,
|
|
10
|
+
`message` VARCHAR(255) NOT NULL,
|
|
11
|
+
`frames` JSON NOT NULL,
|
|
12
|
+
`occurrences` INTEGER UNSIGNED NOT NULL,
|
|
13
|
+
`first_seen` DATETIME(3) NOT NULL,
|
|
14
|
+
`last_seen` DATETIME(3) NOT NULL,
|
|
15
|
+
`release` VARCHAR(64) NULL,
|
|
16
|
+
INDEX `diagnostic_buckets_bucket_start_severity_group_id_idx`(`bucket_start`, `severity`, `group_id`),
|
|
17
|
+
INDEX `diagnostic_buckets_hour_start_severity_group_id_idx`(`hour_start`, `severity`, `group_id`),
|
|
18
|
+
INDEX `diagnostic_buckets_group_id_bucket_start_idx`(`group_id`, `bucket_start`),
|
|
19
|
+
PRIMARY KEY (`id`)
|
|
20
|
+
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
|
21
|
+
|
|
22
|
+
-- Both equality filters are window partition columns so MySQL can push them
|
|
23
|
+
-- down into the indexed aggregation. The sample tie breaks on immutable ID.
|
|
24
|
+
CREATE SQL SECURITY INVOKER VIEW `diagnostic_hourly_top` AS
|
|
25
|
+
WITH summaries AS (
|
|
26
|
+
SELECT hour_start, severity, group_id,
|
|
27
|
+
CAST(SUM(occurrences) AS UNSIGNED) AS occurrence_count,
|
|
28
|
+
MIN(first_seen) AS first_seen, MAX(last_seen) AS last_seen,
|
|
29
|
+
MAX(CONCAT(DATE_FORMAT(last_seen, '%Y%m%d%H%i%s%f'), id)) AS sample_position
|
|
30
|
+
FROM diagnostic_buckets
|
|
31
|
+
GROUP BY hour_start, severity, group_id
|
|
32
|
+
), ranked AS (
|
|
33
|
+
SELECT summaries.*, ROW_NUMBER() OVER (
|
|
34
|
+
PARTITION BY hour_start, severity ORDER BY occurrence_count DESC, group_id ASC
|
|
35
|
+
) AS group_rank
|
|
36
|
+
FROM summaries
|
|
37
|
+
)
|
|
38
|
+
SELECT ranked.hour_start, ranked.severity, ranked.group_rank, ranked.group_id,
|
|
39
|
+
ranked.occurrence_count, ranked.first_seen, ranked.last_seen,
|
|
40
|
+
sample.source, sample.label, sample.code, sample.message, sample.frames, sample.release
|
|
41
|
+
FROM ranked
|
|
42
|
+
JOIN diagnostic_buckets AS sample ON sample.id = RIGHT(ranked.sample_position, 64)
|
|
43
|
+
WHERE ranked.group_rank <= 10;
|