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 209 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):**
@@ -77,12 +90,6 @@ cd client && npm run test:watch
- Export pure functions (validators, formatters, etc.) for direct testing
- Run `npm test` in both `server/` and `client/` before committing
**Doc drift check:**
```bash
node scripts/doc-drift.js
```
Scans `CLAUDE.md` and `PRD.md` for verifiable code references (file paths, API routes, component names) and cross-checks each against the filesystem and source tree. Prints a PASS/FAIL report with doc name and line number. Exits non-zero on any failure — suitable for CI gating.
## Application Structure
The default route `/` renders the paycheck-centric main view (`client/src/pages/PaycheckView.jsx`). It shows the current month's two paychecks side-by-side with bills, paid status, one-time expenses, and remaining balance. Month navigation (prev/next) fetches data via `GET /api/paychecks?year=&month=`.

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"

View File

@@ -1,203 +0,0 @@
#!/usr/bin/env node
/**
* doc-drift.js — detects documentation drift by cross-checking verifiable
* code references in CLAUDE.md and PRD.md against the filesystem and source tree.
*
* Usage: node scripts/doc-drift.js
* Exits non-zero if any drift is found.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const ROOT = path.resolve(__dirname, '..');
const DOCS = ['CLAUDE.md', 'PRD.md'].map(f => path.join(ROOT, f));
// ── Result tracking ──────────────────────────────────────────────────────────
const results = [];
function record(doc, line, kind, ref, pass, reason) {
results.push({ doc: path.basename(doc), line, kind, ref, pass, reason });
}
// ── Extraction helpers ───────────────────────────────────────────────────────
/** Extract all backtick spans from a line (may be multiple). */
function backtickSpans(line) {
const spans = [];
const re = /`([^`]+)`/g;
let m;
while ((m = re.exec(line)) !== null) spans.push(m[1]);
return spans;
}
/** Return true if a span looks like a file/dir path we can verify. */
function isFilePath(span) {
// Must contain a slash and start with a recognisable project prefix.
return (
/[/\\]/.test(span) &&
/^(client|server|db|scripts|docker-compose)/.test(span) &&
// Exclude shell commands, URLs, SQL snippets, etc.
!/\s/.test(span) &&
!span.includes('=') &&
!span.startsWith('http')
);
}
/** Return true if a span looks like a component/page reference (*.jsx). */
function isJsxRef(span) {
return /\w+\.jsx$/.test(span) && !/[/]/.test(span); // bare name, no path
}
/** Extract HTTP API route patterns like `GET /api/paychecks`. */
function extractApiRoutes(line) {
const routes = [];
const re = /\b(GET|POST|PUT|DELETE|PATCH)\s+(\/api\/[^\s,`'")\]]+)/g;
let m;
while ((m = re.exec(line)) !== null) routes.push({ method: m[1], path: m[2] });
return routes;
}
// ── Verification helpers ─────────────────────────────────────────────────────
function fileExists(relPath) {
return fs.existsSync(path.join(ROOT, relPath));
}
/**
* For API routes: grep server/src/routes/ for the route path string.
* We look for the path fragment (everything after /api) as a string literal.
*/
function apiRouteExists(routePath) {
// Strip query-string placeholders like ?year=&month=
const clean = routePath.replace(/\?.*$/, '').replace(/:id/g, ':id');
// Build a grep-friendly pattern: look for the path minus leading /api
const fragment = clean.replace(/^\/api/, '');
try {
const out = execSync(
`grep -rE --include="*.js" -l "${clean}|${fragment}" "${path.join(ROOT, 'server/src/routes')}"`,
{ stdio: ['pipe', 'pipe', 'pipe'] }
).toString().trim();
return out.length > 0;
} catch {
return false;
}
}
/**
* For bare *.jsx component names: check that a file with that name exists
* somewhere under client/src/.
*/
function jsxComponentExists(name) {
try {
const out = execSync(
`find "${path.join(ROOT, 'client/src')}" -name "${name}" -type f`,
{ stdio: ['pipe', 'pipe', 'pipe'] }
).toString().trim();
return out.length > 0;
} catch {
return false;
}
}
// ── Main ─────────────────────────────────────────────────────────────────────
for (const docPath of DOCS) {
if (!fs.existsSync(docPath)) {
console.error(`WARN: doc not found: ${docPath}`);
continue;
}
const lines = fs.readFileSync(docPath, 'utf8').split('\n');
lines.forEach((rawLine, idx) => {
const lineNo = idx + 1;
// 1. Backtick file paths
for (const span of backtickSpans(rawLine)) {
if (isFilePath(span)) {
const exists = fileExists(span);
record(
docPath,
lineNo,
'file-path',
span,
exists,
exists ? 'found on filesystem' : `not found: ${span}`
);
continue;
}
if (isJsxRef(span)) {
const exists = jsxComponentExists(span);
record(
docPath,
lineNo,
'component',
span,
exists,
exists ? 'found under client/src' : `no file named ${span} in client/src`
);
}
}
// 2. API routes (inside or outside backticks)
for (const { method, path: routePath } of extractApiRoutes(rawLine)) {
const ref = `${method} ${routePath}`;
const exists = apiRouteExists(routePath);
record(
docPath,
lineNo,
'api-route',
ref,
exists,
exists ? 'found in server/src/routes' : `route not found in server/src/routes`
);
}
});
}
// ── Report ───────────────────────────────────────────────────────────────────
const padDoc = Math.max(...results.map(r => r.doc.length), 9);
const padKind = Math.max(...results.map(r => r.kind.length), 9);
const padRef = Math.min(60, Math.max(...results.map(r => r.ref.length), 10));
const header = [
'STATUS'.padEnd(6),
'DOC'.padEnd(padDoc),
'LINE'.padStart(4),
'KIND'.padEnd(padKind),
'REFERENCE',
].join(' ');
console.log('\n' + header);
console.log('─'.repeat(header.length + 10));
let failures = 0;
for (const r of results) {
const status = r.pass ? 'PASS' : 'FAIL';
const ref = r.ref.length > padRef ? r.ref.slice(0, padRef - 1) + '…' : r.ref;
const line = [
(r.pass ? '\x1b[32m' : '\x1b[31m') + status.padEnd(6) + '\x1b[0m',
r.doc.padEnd(padDoc),
String(r.line).padStart(4),
r.kind.padEnd(padKind),
ref,
].join(' ');
console.log(line);
if (!r.pass) {
console.log(` \x1b[33m↳ ${r.reason}\x1b[0m`);
failures++;
}
}
console.log('─'.repeat(header.length + 10));
console.log(`\n${results.length} references checked — ${failures} failure(s)\n`);
process.exit(failures > 0 ? 1 : 0);

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