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
8 changed files with 1497 additions and 251 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):**

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"

View File

@@ -1,251 +0,0 @@
#!/usr/bin/env node
/**
* metrics-coverage.js — Static analysis script for metrics/logging instrumentation coverage.
*
* Scans all Express route files in server/src/routes/*.js and app.js to measure
* how many route handlers contain logging calls (console.error/console.warn/console.log).
*
* Usage:
* node scripts/metrics-coverage.js # JSON output (default)
* node scripts/metrics-coverage.js --format=text # Human-readable table
*
* Sample output (captured 2026-03-20):
* {
* "files": [
* { "file": "actuals.js", "total": 5, "logged": 5, "unlogged": 0, "coverage": 100 },
* { "file": "bills.js", "total": 6, "logged": 6, "unlogged": 0, "coverage": 100 },
* { "file": "config.js", "total": 2, "logged": 2, "unlogged": 0, "coverage": 100 },
* { "file": "financing.js", "total": 6, "logged": 6, "unlogged": 0, "coverage": 100 },
* { "file": "health.js", "total": 1, "logged": 0, "unlogged": 1, "coverage": 0 },
* { "file": "one-time-expenses.js", "total": 3, "logged": 3, "unlogged": 0, "coverage": 100 },
* { "file": "paychecks.js", "total": 6, "logged": 6, "unlogged": 0, "coverage": 100 },
* { "file": "summary.js", "total": 2, "logged": 2, "unlogged": 0, "coverage": 100 }
* ],
* "app": {
* "has_request_timing_middleware": false,
* "has_error_handling_middleware": false,
* "middleware_count": 11
* },
* "aggregate": {
* "total_handlers": 31,
* "logged_handlers": 30,
* "unlogged_handlers": 1,
* "coverage_pct": 96.77
* }
* }
*/
'use strict';
const fs = require('fs');
const path = require('path');
const ROUTES_DIR = path.resolve(__dirname, '../server/src/routes');
const APP_FILE = path.resolve(__dirname, '../server/src/app.js');
// Regex patterns for route handler definitions.
// Matches: router.get/post/put/patch/delete( and app.get/post/put/patch/delete(
const ROUTE_DEF_RE = /\b(?:router|app)\.(get|post|put|patch|delete)\s*\(/g;
// Logging call patterns
const LOG_RE = /\bconsole\.(error|warn|log)\s*\(/;
/**
* Extract individual route handler bodies from source.
* Strategy: find each route definition, then walk forward counting
* braces to find the closing of the outermost async/function callback.
*/
function extractHandlerBodies(src) {
const handlers = [];
let match;
ROUTE_DEF_RE.lastIndex = 0;
while ((match = ROUTE_DEF_RE.exec(src)) !== null) {
const startIdx = match.index;
// Find the opening paren of the route call
const parenOpen = src.indexOf('(', startIdx);
if (parenOpen === -1) continue;
// Walk from the paren open, tracking paren depth to find the matching close.
// The handler callback body will be inside the outer parens.
let depth = 0;
let bodyStart = -1;
let bodyEnd = -1;
let inString = false;
let stringChar = '';
let i = parenOpen;
while (i < src.length) {
const ch = src[i];
// Basic string tracking (skip contents of string literals)
if (!inString && (ch === '"' || ch === "'" || ch === '`')) {
inString = true;
stringChar = ch;
i++;
continue;
}
if (inString) {
if (ch === '\\') { i += 2; continue; } // skip escape
if (ch === stringChar) inString = false;
i++;
continue;
}
if (ch === '(') {
depth++;
if (depth === 1) {
// This is the opening of the route call args
}
} else if (ch === ')') {
depth--;
if (depth === 0) {
bodyEnd = i;
break;
}
} else if (ch === '{' && depth >= 1 && bodyStart === -1) {
// First brace inside the outer parens — start of the handler body
bodyStart = i;
}
i++;
}
if (bodyStart !== -1 && bodyEnd !== -1) {
handlers.push(src.slice(bodyStart, bodyEnd));
}
}
return handlers;
}
/**
* Analyse a single route file.
*/
function analyseRouteFile(filePath) {
const src = fs.readFileSync(filePath, 'utf8');
const handlers = extractHandlerBodies(src);
const logged = handlers.filter(body => LOG_RE.test(body));
return {
file: path.basename(filePath),
total: handlers.length,
logged: logged.length,
unlogged: handlers.length - logged.length,
coverage: handlers.length === 0
? null
: Math.round((logged.length / handlers.length) * 10000) / 100,
};
}
/**
* Analyse app.js for middleware-level instrumentation.
*/
function analyseApp(filePath) {
const src = fs.readFileSync(filePath, 'utf8');
// Request timing: morgan, custom middleware checking req.method, Date.now() at top-level use()
const hasRequestTiming =
/\brequire\s*\(\s*['"]morgan['"]\s*\)/.test(src) ||
/app\.use\s*\(.*Date\.now\(\)/.test(src) ||
/app\.use\s*\(.*req,\s*res,\s*next/.test(src) && /Date\.now|performance\.now/.test(src);
// Error handling middleware: app.use((err, req, res, next) => ...)
const hasErrorHandling = /app\.use\s*\(\s*(?:\S+\s*,\s*)?\(\s*err\s*,/.test(src);
// Count top-level app.use() calls (middleware registrations)
const middlewareMatches = src.match(/app\.use\s*\(/g) || [];
return {
has_request_timing_middleware: hasRequestTiming,
has_error_handling_middleware: hasErrorHandling,
middleware_count: middlewareMatches.length,
};
}
function run() {
const format = process.argv.includes('--format=text') ? 'text' : 'json';
// Analyse all route files
const routeFiles = fs.readdirSync(ROUTES_DIR)
.filter(f => f.endsWith('.js'))
.sort();
const fileResults = routeFiles.map(f =>
analyseRouteFile(path.join(ROUTES_DIR, f))
);
// Aggregate
const totalHandlers = fileResults.reduce((s, r) => s + r.total, 0);
const loggedHandlers = fileResults.reduce((s, r) => s + r.logged, 0);
const aggregate = {
total_handlers: totalHandlers,
logged_handlers: loggedHandlers,
unlogged_handlers: totalHandlers - loggedHandlers,
coverage_pct: totalHandlers === 0
? null
: Math.round((loggedHandlers / totalHandlers) * 10000) / 100,
};
const appInfo = analyseApp(APP_FILE);
const result = {
files: fileResults,
app: appInfo,
aggregate,
};
if (format === 'json') {
console.log(JSON.stringify(result, null, 2));
return;
}
// Text table
const COL_FILE = 28;
const COL_TOTAL = 7;
const COL_LOGGED = 8;
const COL_COVER = 10;
const pad = (s, n) => String(s).padEnd(n);
const lpad = (s, n) => String(s).padStart(n);
const hr = '-'.repeat(COL_FILE + COL_TOTAL + COL_LOGGED + COL_COVER + 6);
console.log('\nMetrics Instrumentation Coverage\n');
console.log(
pad('Route File', COL_FILE) +
lpad('Handlers', COL_TOTAL) +
lpad('Logged', COL_LOGGED) +
lpad('Coverage', COL_COVER)
);
console.log(hr);
for (const r of fileResults) {
const cov = r.coverage === null ? 'N/A' : `${r.coverage}%`;
console.log(
pad(r.file, COL_FILE) +
lpad(r.total, COL_TOTAL) +
lpad(r.logged, COL_LOGGED) +
lpad(cov, COL_COVER)
);
}
console.log(hr);
const aggCov = aggregate.coverage_pct === null ? 'N/A' : `${aggregate.coverage_pct}%`;
console.log(
pad('TOTAL', COL_FILE) +
lpad(aggregate.total_handlers, COL_TOTAL) +
lpad(aggregate.logged_handlers, COL_LOGGED) +
lpad(aggCov, COL_COVER)
);
console.log('\napp.js middleware:');
console.log(` Request timing middleware : ${appInfo.has_request_timing_middleware}`);
console.log(` Error handling middleware : ${appInfo.has_error_handling_middleware}`);
console.log(` app.use() call count : ${appInfo.middleware_count}`);
console.log('');
}
run();

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"
}
}