2 Commits

Author SHA1 Message Date
758828c70a Fix test import style and document hooks in CLAUDE.md
- Replace mixed ESM/CJS import syntax in test file with consistent ESM
  imports throughout (both vitest and normalizer use import)
- Add Git Hooks section to CLAUDE.md documenting install-hooks.sh
  and the commit-msg normalizer for new contributors

Nightshift-Task: commit-normalize
Nightshift-Ref: https://github.com/marcus/nightshift
2026-03-20 02:07:30 -04:00
73e7967735 Add commit message normalizer hook and install script
- scripts/normalize-commit-msg.js: capitalizes subject, strips trailing
  period, trims whitespace, warns when subject > 72 chars
- scripts/commit-msg: shell wrapper symlinked into .git/hooks/commit-msg
- scripts/install-hooks.sh: contributor setup script (sh scripts/install-hooks.sh)
- scripts/package.json: test runner + hooks:install npm script
- scripts/__tests__/normalize-commit-msg.test.js: 15 unit tests

Nightshift-Task: commit-normalize
Nightshift-Ref: https://github.com/marcus/nightshift
2026-03-20 02:04:04 -04:00
13 changed files with 1499 additions and 205 deletions

View File

@@ -29,6 +29,19 @@ td session --new # force a new session in the same terminal context
Task state is stored in `.todos/issues.db` (SQLite).
## Git Hooks
A commit-msg hook normalizes commit messages on every commit (capitalizes subject, strips trailing period, trims whitespace, warns when subject exceeds 72 characters). The hook never blocks a commit.
**Wire hooks after cloning:**
```bash
sh scripts/install-hooks.sh
# or via npm script:
cd scripts && npm run hooks:install
```
The hook script lives at `scripts/commit-msg` and is invoked by `.git/hooks/commit-msg`. The normalizer logic is in `scripts/normalize-commit-msg.js` with unit tests in `scripts/__tests__/normalize-commit-msg.test.js` (run with `cd scripts && npm test`).
## Development
**Run production stack (Docker):**
@@ -94,16 +107,3 @@ The default route `/` renders the paycheck-centric main view (`client/src/pages/
**Financing:** `GET/POST /api/financing`, `PUT/DELETE /api/financing/:id`, `PATCH /api/financing-payments/:id/paid`. Plans track a total amount, payoff due date, and `start_date`. Payment per period is auto-calculated as `(remaining balance) / (remaining periods)`. Split plans (`assigned_paycheck = null`) divide each period's payment across both paychecks. Plans auto-close when fully paid. Financing payments are included in the paycheck remaining balance. `start_date` prevents a plan from appearing on paycheck months before it was created — both virtual previews and `generate` respect this guard.
**Migrations:** SQL files in `db/migrations/` are applied in filename order on server startup. Add new migrations as `00N_description.sql` — they run once and are tracked in the `migrations` table.
## Performance Tooling
**Timing middleware** (`server/src/middleware/timing.js`): Registered early in `app.js`. Logs every request's method, path, status code, and duration. Emits a `[SLOW]` warning for responses exceeding 200 ms.
**Benchmark script** (`scripts/perf-benchmark.js`): Hits `GET /api/paychecks`, `GET /api/financing`, and `GET /api/summary/annual` five times each and reports min/mean/max latency. Exits non-zero if any mean exceeds the threshold (default 500 ms, override via `SLOW_THRESHOLD_MS` env var). Target server URL defaults to `http://localhost:3001` (override via `BENCHMARK_URL`).
```bash
cd server && npm run perf # run against localhost:3001
BENCHMARK_URL=http://localhost:3000 npm run perf
```
**Performance indexes** (`db/migrations/005_performance_indexes.sql`): Adds indexes on `paychecks(period_year, period_month)`, `paycheck_bills(paycheck_id)`, `actuals(paycheck_id)`, `one_time_expenses(paycheck_id)`, `financing_payments(plan_id)`, and `financing_plans(active)` — applied automatically on server startup.

View File

@@ -1,7 +0,0 @@
-- Performance indexes for high-traffic query patterns
CREATE INDEX IF NOT EXISTS idx_paychecks_period ON paychecks(period_year, period_month);
CREATE INDEX IF NOT EXISTS idx_paycheck_bills_paycheck_id ON paycheck_bills(paycheck_id);
CREATE INDEX IF NOT EXISTS idx_actuals_paycheck_id ON actuals(paycheck_id);
CREATE INDEX IF NOT EXISTS idx_one_time_expenses_paycheck_id ON one_time_expenses(paycheck_id);
CREATE INDEX IF NOT EXISTS idx_financing_payments_plan_id ON financing_payments(plan_id);
CREATE INDEX IF NOT EXISTS idx_financing_plans_active ON financing_plans(active) WHERE active = true;

View File

@@ -0,0 +1,90 @@
import { describe, it, expect } from 'vitest';
import { normalizeSubject, normalizeMessage } from '../normalize-commit-msg.js';
describe('normalizeSubject', () => {
it('passes an already-valid subject unchanged', () => {
const { subject, warned } = normalizeSubject('Add feature flag support');
expect(subject).toBe('Add feature flag support');
expect(warned).toBe(false);
});
it('capitalizes the first letter', () => {
const { subject } = normalizeSubject('add feature flag support');
expect(subject).toBe('Add feature flag support');
});
it('strips a trailing period', () => {
const { subject } = normalizeSubject('Add feature flag support.');
expect(subject).toBe('Add feature flag support');
});
it('trims leading whitespace', () => {
const { subject } = normalizeSubject(' Fix the bug');
expect(subject).toBe('Fix the bug');
});
it('trims trailing whitespace', () => {
const { subject } = normalizeSubject('Fix the bug ');
expect(subject).toBe('Fix the bug');
});
it('capitalizes and strips period together', () => {
const { subject } = normalizeSubject('fix the bug.');
expect(subject).toBe('Fix the bug');
});
it('does not strip a period that is not trailing', () => {
const { subject } = normalizeSubject('Fix bug in v1.0 release');
expect(subject).toBe('Fix bug in v1.0 release');
});
it('warns when subject exceeds 72 characters', () => {
const long = 'A'.repeat(73);
const { warned } = normalizeSubject(long);
expect(warned).toBe(true);
});
it('does not warn when subject is exactly 72 characters', () => {
const exact = 'A'.repeat(72);
const { warned } = normalizeSubject(exact);
expect(warned).toBe(false);
});
it('does not warn when subject is under 72 characters', () => {
const { warned } = normalizeSubject('Short message');
expect(warned).toBe(false);
});
it('handles an empty subject gracefully', () => {
const { subject, warned } = normalizeSubject('');
expect(subject).toBe('');
expect(warned).toBe(false);
});
});
describe('normalizeMessage', () => {
it('normalizes only the subject line of a multi-line message', () => {
const input = 'fix the bug.\n\nThis is the body paragraph.';
const { message } = normalizeMessage(input);
expect(message).toBe('Fix the bug\n\nThis is the body paragraph.');
});
it('skips comment lines when finding the subject', () => {
const input = '# Comment\nfix the bug.';
const { message } = normalizeMessage(input);
expect(message).toBe('# Comment\nFix the bug');
});
it('returns warned true for long subject inside full message', () => {
const longSubject = 'x'.repeat(73);
const input = `${longSubject}\n\nBody.`;
const { warned } = normalizeMessage(input);
expect(warned).toBe(true);
});
it('preserves body lines exactly as-is', () => {
const input = 'Fix bug\n\n - detail one\n - detail two.';
const { message } = normalizeMessage(input);
expect(message).toBe('Fix bug\n\n - detail one\n - detail two.');
});
});

4
scripts/commit-msg Executable file
View File

@@ -0,0 +1,4 @@
#!/bin/sh
# Git commit-msg hook — delegates to normalize-commit-msg.js
# This file is symlinked into .git/hooks/commit-msg by scripts/install-hooks.sh
node "$(git rev-parse --show-toplevel)/scripts/normalize-commit-msg.js" "$1"

34
scripts/install-hooks.sh Executable file
View File

@@ -0,0 +1,34 @@
#!/bin/sh
# install-hooks.sh
# Installs the project's git hooks into .git/hooks/.
# Run this once after cloning: sh scripts/install-hooks.sh
set -e
REPO_ROOT="$(git rev-parse --show-toplevel)"
HOOKS_DIR="$REPO_ROOT/.git/hooks"
SCRIPTS_DIR="$REPO_ROOT/scripts"
install_hook() {
local name="$1"
local src="$SCRIPTS_DIR/$name"
local dst="$HOOKS_DIR/$name"
if [ ! -f "$src" ]; then
echo "install-hooks: source not found: $src" >&2
return 1
fi
if [ -f "$dst" ] && [ ! -L "$dst" ]; then
echo "install-hooks: warning: $dst already exists and is not a symlink — skipping"
return 0
fi
ln -sf "$src" "$dst"
chmod +x "$src"
echo "install-hooks: installed $name -> $dst"
}
install_hook "commit-msg"
echo "install-hooks: done"

95
scripts/normalize-commit-msg.js Executable file
View File

@@ -0,0 +1,95 @@
#!/usr/bin/env node
/**
* normalize-commit-msg.js
*
* Git commit-msg hook: reads the commit message file, applies normalization
* rules to the subject line, rewrites the file in place.
*
* Rules:
* 1. Trim leading/trailing whitespace from the subject line
* 2. Capitalize the first letter of the subject
* 3. Strip a trailing period from the subject
* 4. Warn (but do not block) if the subject exceeds 72 characters
*/
'use strict';
const fs = require('fs');
const MAX_SUBJECT_LEN = 72;
/**
* Normalize the subject line of a commit message.
* Returns { subject, warned } where warned is true if a length warning was emitted.
*
* @param {string} subject
* @returns {{ subject: string, warned: boolean }}
*/
function normalizeSubject(subject) {
let s = subject.trimEnd();
// Trim leading whitespace
s = s.trimStart();
// Capitalize first letter
if (s.length > 0) {
s = s[0].toUpperCase() + s.slice(1);
}
// Strip trailing period
if (s.endsWith('.')) {
s = s.slice(0, -1);
}
const warned = s.length > MAX_SUBJECT_LEN;
return { subject: s, warned };
}
/**
* Normalize a full commit message string.
* Only the subject line (first non-empty, non-comment line) is modified.
*
* @param {string} message
* @returns {{ message: string, warned: boolean }}
*/
function normalizeMessage(message) {
const lines = message.split('\n');
let warned = false;
// Find the subject line (first non-comment line)
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!line.startsWith('#')) {
const result = normalizeSubject(line);
lines[i] = result.subject;
warned = result.warned;
break;
}
}
return { message: lines.join('\n'), warned };
}
// Only run as a hook when invoked directly (not when required in tests)
if (require.main === module) {
const msgFile = process.argv[2];
if (!msgFile) {
process.stderr.write('commit-msg hook: no message file argument\n');
process.exit(1);
}
const original = fs.readFileSync(msgFile, 'utf8');
const { message, warned } = normalizeMessage(original);
if (warned) {
process.stderr.write(
`commit-msg warning: subject line exceeds ${MAX_SUBJECT_LEN} characters — consider shortening it.\n`
);
}
fs.writeFileSync(msgFile, message, 'utf8');
process.exit(0);
}
module.exports = { normalizeSubject, normalizeMessage };

1249
scripts/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

12
scripts/package.json Normal file
View File

@@ -0,0 +1,12 @@
{
"name": "budget-scripts",
"version": "1.0.0",
"scripts": {
"test": "vitest run",
"test:watch": "vitest",
"hooks:install": "sh install-hooks.sh"
},
"devDependencies": {
"vitest": "^4.1.0"
}
}

View File

@@ -1,62 +0,0 @@
#!/usr/bin/env node
'use strict';
const BASE_URL = process.env.BENCHMARK_URL || 'http://localhost:3001';
const ITERATIONS = 5;
const MEAN_THRESHOLD_MS = parseInt(process.env.SLOW_THRESHOLD_MS || '500', 10);
const ENDPOINTS = [
{ label: 'GET /api/paychecks', path: `/api/paychecks?year=${new Date().getFullYear()}&month=${new Date().getMonth() + 1}` },
{ label: 'GET /api/financing', path: '/api/financing' },
{ label: 'GET /api/summary/annual', path: `/api/summary/annual?year=${new Date().getFullYear()}` },
];
async function measureEndpoint(endpoint) {
const times = [];
for (let i = 0; i < ITERATIONS; i++) {
const start = Date.now();
const res = await fetch(`${BASE_URL}${endpoint.path}`);
const duration = Date.now() - start;
if (!res.ok) {
console.warn(` [warn] ${endpoint.label} returned HTTP ${res.status}`);
}
times.push(duration);
}
const min = Math.min(...times);
const max = Math.max(...times);
const mean = Math.round(times.reduce((a, b) => a + b, 0) / times.length);
return { min, mean, max };
}
(async () => {
console.log(`Benchmarking ${BASE_URL} (${ITERATIONS} iterations each, threshold ${MEAN_THRESHOLD_MS}ms)\n`);
let failed = false;
for (const endpoint of ENDPOINTS) {
let stats;
try {
stats = await measureEndpoint(endpoint);
} catch (err) {
console.error(` [error] ${endpoint.label}: ${err.message}`);
failed = true;
continue;
}
const flag = stats.mean >= MEAN_THRESHOLD_MS ? ' *** SLOW ***' : '';
console.log(`${endpoint.label}`);
console.log(` min=${stats.min}ms mean=${stats.mean}ms max=${stats.max}ms${flag}`);
if (stats.mean >= MEAN_THRESHOLD_MS) {
failed = true;
}
}
console.log('');
if (failed) {
console.error('FAIL: one or more endpoints exceeded the threshold or errored.');
process.exit(1);
} else {
console.log('PASS: all endpoints within threshold.');
}
})();

View File

@@ -6,8 +6,7 @@
"start": "node src/index.js",
"dev": "nodemon src/index.js",
"test": "vitest run",
"test:watch": "vitest",
"perf": "node ../scripts/perf-benchmark.js"
"test:watch": "vitest"
},
"dependencies": {
"cors": "^2.8.5",

View File

@@ -1,98 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
const timingMiddleware = require('../middleware/timing');
function makeResMock() {
const listeners = {};
return {
statusCode: 200,
on(event, cb) {
listeners[event] = cb;
},
emit(event) {
if (listeners[event]) listeners[event]();
},
};
}
describe('timingMiddleware', () => {
let consoleSpy;
let warnSpy;
beforeEach(() => {
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
consoleSpy.mockRestore();
warnSpy.mockRestore();
vi.useRealTimers();
});
it('calls next()', () => {
const req = { method: 'GET', path: '/api/health' };
const res = makeResMock();
const next = vi.fn();
timingMiddleware(req, res, next);
expect(next).toHaveBeenCalledOnce();
});
it('logs timing on response finish', () => {
const req = { method: 'GET', path: '/api/health' };
const res = makeResMock();
timingMiddleware(req, res, vi.fn());
res.emit('finish');
expect(consoleSpy).toHaveBeenCalledOnce();
const msg = consoleSpy.mock.calls[0][0];
expect(msg).toMatch(/\[timing\] GET \/api\/health 200 \d+ms/);
});
it('emits SLOW warning when duration exceeds 200ms threshold', () => {
vi.useFakeTimers();
const req = { method: 'POST', path: '/api/paychecks' };
const res = makeResMock();
timingMiddleware(req, res, vi.fn());
// Advance time past the threshold
vi.advanceTimersByTime(250);
res.emit('finish');
expect(warnSpy).toHaveBeenCalledOnce();
const msg = warnSpy.mock.calls[0][0];
expect(msg).toMatch(/\[SLOW\] POST \/api\/paychecks/);
expect(consoleSpy).not.toHaveBeenCalled();
});
it('does not emit SLOW warning for fast requests', () => {
vi.useFakeTimers();
const req = { method: 'GET', path: '/api/financing' };
const res = makeResMock();
timingMiddleware(req, res, vi.fn());
vi.advanceTimersByTime(50);
res.emit('finish');
expect(consoleSpy).toHaveBeenCalledOnce();
expect(warnSpy).not.toHaveBeenCalled();
});
it('includes status code in the log message', () => {
const req = { method: 'GET', path: '/api/bills' };
const res = makeResMock();
res.statusCode = 404;
timingMiddleware(req, res, vi.fn());
res.emit('finish');
const msg = consoleSpy.mock.calls[0][0];
expect(msg).toContain('404');
});
});

View File

@@ -9,14 +9,13 @@ const actualsRouter = require('./routes/actuals');
const oneTimeExpensesRouter = require('./routes/one-time-expenses');
const summaryRouter = require('./routes/summary');
const { router: financingRouter } = require('./routes/financing');
const timingMiddleware = require('./middleware/timing');
const app = express();
app.use(cors());
app.use(express.json());
// API routes
app.use('/api', timingMiddleware);
app.use('/api', healthRouter);
app.use('/api', configRouter);
app.use('/api', billsRouter);

View File

@@ -1,21 +0,0 @@
'use strict';
const SLOW_THRESHOLD_MS = 200;
function timingMiddleware(req, res, next) {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
const msg = `${req.method} ${req.path} ${res.statusCode} ${duration}ms`;
if (duration >= SLOW_THRESHOLD_MS) {
console.warn(`[SLOW] ${msg}`);
} else {
console.log(`[timing] ${msg}`);
}
});
next();
}
module.exports = timingMiddleware;