Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Git history - not needed in Docker and causes lefthook to run during yarn install
.git

# Local environment and secrets
.env
.env.*.local
.env.local
certs/
*.pem
*.key

# Development tooling
.idea/
.vscode/
.claude/
*.log
.DS_Store

# Test artefacts
test-results/
playwright-report/
coverage/
.nyc_output/
e2e-tests/

# Turborepo cache
.turbo/

# Build artefacts (rebuilt inside Docker)
dist/
build/
*.tsbuildinfo

# Docs
docs/
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,11 @@ libs/postgres-prisma/generated/

# Exception: Utility scripts that are source JS
!e2e-tests/run-with-credentials.js
!scripts/install-hooks.js

# Exception: Hand-written ambient type declarations
!**/global.d.ts
!types/**/*.d.ts

# Lefthook local overrides
.lefthook-local.yml
4 changes: 4 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ yarn test:coverage # Generate coverage report
yarn lint:fix # Run Biome linter
yarn format # Format code with Biome

# Git Hooks (installed automatically via postinstall)
# Pre-commit hook runs Biome --write on all staged files and re-stages fixes.
# To skip the hook for a single commit: LEFTHOOK=0 git commit ...

Comment on lines +18 to +21

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Update documentation to match actual hook scope.

Line 19 states "all staged files", but the hook targets only TypeScript files (**/*.{ts,tsx} per review.md). Update to "TypeScript/TSX files" for accuracy. Also consider clarifying that Biome handles lint/format only, not type errors.

# Database Operations
yarn db:migrate # Apply migrations
yarn db:migrate:dev # Auto apply migrations, add new migrations if necessary
Expand Down
101 changes: 101 additions & 0 deletions docs/tickets/563/plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# #563 Technical Plan: Pre-commit Hook for Lint and Type Checking

## Technical Approach

Install `lefthook` as the git hooks manager and configure a pre-commit hook that:
1. Runs Biome in write mode on staged files to auto-fix lint and formatting issues, then re-stages the fixed files
2. Runs a TypeScript type check across all workspaces to catch type errors that Biome cannot fix

### Why lefthook

- Fast: runs commands in parallel by default
- YAML-based configuration - no JavaScript required
- No `postinstall` side-effect scripts of its own; we control installation explicitly
- Works cleanly with Yarn 4 PnP/node_modules setups
- Supports `glob` filtering so the Biome step only runs when relevant files are staged
- Actively maintained and widely adopted in monorepo setups

### Alternative considered: husky

Husky requires a `prepare` script and shell scripts per hook file. It adds more boilerplate and its shell-script approach is harder to maintain than a single YAML file. Lefthook is a better fit here.

---

## Implementation Details

### 1. Add lefthook dev dependency

Add to root `package.json` devDependencies:

```json
"lefthook": "1.11.14"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Plan specifies incorrect lefthook version.

The plan documents version 1.11.14, but package.json installs 2.1.9. Update the plan to match the actual dependency version to avoid confusion.

```

Pin to a specific version per the project's pinned-dependency convention.

### 2. Update postinstall script

The existing `postinstall` in root `package.json` currently runs `yarn db:generate`. Update it to also install the git hooks:

```json
"postinstall": "yarn db:generate && lefthook install"
```
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

This ensures every developer gets the hooks installed automatically after `yarn install`.

### 3. Create lefthook.yml at repo root

```yaml
pre-commit:
parallel: false
commands:
biome-check:
glob: "*.{ts,tsx,js,jsx}"
run: npx @biomejs/biome check --write {staged_files}
stage_fixed: true
tsc:
run: yarn tsc --noEmit --project tsconfig.json
```

Key configuration choices:

- `parallel: false`: Biome must run and re-stage files before the TypeScript check runs. Running them in parallel would risk tsc seeing the pre-fix state.
- `glob`: limits the Biome step to JS/TS file types only; commits touching only `.yml`, `.md`, `.json` etc. skip it entirely.
- `stage_fixed: true`: lefthook automatically re-stages any files that Biome modified. This replaces the need for a manual `git add` step.
- `tsc`: runs a project-wide type check. TypeScript errors cannot be auto-fixed; if tsc exits non-zero the commit is blocked and the developer sees the error output.

### 4. Root tsconfig.json scope

The `tsc --noEmit` command references the root `tsconfig.json`. Confirm it has `references` or `include` patterns that cover all workspaces. If not, a composite project reference setup may be needed - but this is likely already in place given the existing turbo type-check pipeline.

---

## Error Handling and Edge Cases

| Scenario | Behaviour |
|---|---|
| Biome fixes one or more files | Files are auto-staged by lefthook (`stage_fixed: true`); commit proceeds |
| Biome finds an issue it cannot auto-fix | Biome exits non-zero; commit is blocked with Biome's error output |
| TypeScript error exists | `tsc` exits non-zero; commit is blocked with the TS error output |
| No `.ts/.tsx/.js/.jsx` files staged | `biome-check` step is skipped; `tsc` still runs |
| Merge commit | lefthook skips all hooks during `git merge` by default |
| Rebase | lefthook skips hooks during interactive rebase by default |
| Developer has not run `yarn install` | Hooks are not installed; no protection. Mitigated by the `postinstall` script running on every `yarn install` |

---

## Acceptance Criteria Mapping

| Requirement | Implementation |
|---|---|
| Automatically fix any lint issue on commit | Biome `--write` auto-fixes lint and formatting on staged files |
| Automatically fix any TypeScript issue on commit | **Not fully achievable**: TypeScript type errors cannot be auto-fixed by tooling. The hook runs `tsc --noEmit` and blocks the commit if errors exist, forcing the developer to fix them manually before the commit lands. |
| Per-commit hook | Pre-commit hook via lefthook |

---

## Open Questions / Clarifications Needed

**TypeScript errors cannot be silently auto-fixed.** The ticket says "automatically fix any typescript ... issue" but tsc only reports errors - it does not transform code to resolve them. The plan above blocks the commit on TS errors rather than warning and allowing it through. This is the safer default for a shared codebase.

If the intent was only to auto-fix style/formatting issues (which Biome handles) and merely surface TS errors without blocking, the `tsc` command can be changed to `run: yarn tsc --noEmit --project tsconfig.json || true`. Clarification from the ticket author is recommended before implementing.
123 changes: 123 additions & 0 deletions docs/tickets/563/review.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Code Review: Issue #563 (Re-review)

## Summary

All four issues flagged in the previous review have been resolved: the glob pattern now uses `**/*.{ts,tsx}` to match files in subdirectories, `--reset-hooks-path` has been removed, `lefthook install` is now guarded against running in CI via a `node -e` inline check, and `parallel: false` is now present at the correct level in the YAML structure.

One pre-existing open issue from the previous review remains unaddressed (the `tsc` step was planned but not implemented). One new minor issue has been introduced: CLAUDE.md describes the hook as targeting "JS/TS files" but the glob is now `**/*.{ts,tsx}` only. Neither of these block merging.

The hook is correctly wired up, the pre-commit file is installed at `.git/hooks/pre-commit`, and the implementation is clean and minimal.

---

## CRITICAL Issues

None.

---

## HIGH PRIORITY Issues

None.

---

## SUGGESTIONS

### 1. CLAUDE.md description does not match the actual glob

**File:** `/Users/kian.kwa/IdeaProjects/cath-service/CLAUDE.md`, line 19

**Observation:** The comment reads:
```
# Pre-commit hook runs Biome --write on staged JS/TS files and re-stages fixes.
```

The `lefthook.yml` glob is `**/*.{ts,tsx}`, which covers TypeScript files only. The previous review's suggestion was to remove `.js`/`.jsx` from the glob because `biome.json` excludes `*.js` anyway — that suggestion was correctly acted on. However, the CLAUDE.md description was not updated to match. It should say "TS/TSX files" or simply "TypeScript files".

This is a documentation inaccuracy that will mislead developers who try to understand what triggers the hook.

---

### 2. `tsc --noEmit` step from the plan remains absent and undocumented as a known gap

**File:** `/Users/kian.kwa/IdeaProjects/cath-service/lefthook.yml`

**Observation:** This was flagged in the previous review and remains unchanged. The plan (`docs/tickets/563/plan.md`) included a `tsc` step as a second command. The tasks checklist (`docs/tickets/563/tasks.md`) never listed this step and still records `lefthook install --reset-hooks-path` as the intended postinstall command, meaning the tasks file was not updated to reflect the changes made in this cycle either.

The ticket requirement is "automatically fix any typescript or lint issue". Biome handles the lint/format half. TypeScript type errors are not checked at commit time, which means the requirement is only partially met. This is an acceptable tradeoff if the team is relying on CI for type checking, but that decision should be documented somewhere (either as a note in the plan or as a comment in `lefthook.yml`).

---

### 3. Redundant `lefthook install` on developer machines

**File:** `/Users/kian.kwa/IdeaProjects/cath-service/package.json`, line 11

**Observation:** When a developer runs `yarn install`, two separate calls to `lefthook install` occur:

1. The `lefthook` npm package's own `scripts.postinstall` field (`"postinstall": "node postinstall.js"`) is executed by Yarn when it installs the `lefthook` package. That script checks for CI and, on non-CI machines, calls `lefthook install -f`.
2. Immediately afterwards, the root `package.json` `postinstall` script runs and also calls `lefthook install` (guarded by the same CI check).

Both calls install the same hook, so the result is correct. The install operation is idempotent and fast, so this is not harmful. It is, however, unnecessary duplication. The lefthook package's built-in postinstall is designed specifically to handle automatic installation — the explicit call in root `package.json` may not be needed at all on developer machines.

This is worth being aware of, but does not require a fix before merging.

---

### 4. `tasks.md` still describes the old (removed) postinstall command

**File:** `/Users/kian.kwa/IdeaProjects/cath-service/docs/tickets/563/tasks.md`, line 6

**Observation:** The tasks checklist records:
```
- [x] Update `postinstall` script in root `package.json` to append `&& lefthook install --reset-hooks-path` after `yarn db:generate`
```

The `--reset-hooks-path` flag was correctly removed from the final implementation in response to the previous review. The tasks file was not updated to reflect that change. This leaves the ticket documentation inconsistent with the code.

---

## Positive Feedback

- The glob fix (`**/*.{ts,tsx}`) correctly addresses the root cause from the previous review. Lefthook uses the `gobwas/glob` library where `**` matches across directory separators, so the pattern will now correctly filter staged files in `apps/` and `libs/` subdirectories.
- `--reset-hooks-path` has been cleanly removed with no residual references in `lefthook.yml` or `package.json`. The removal is correct.
- The CI guard (`node -e "process.env.CI || require('child_process').execSync('lefthook install', {stdio:'inherit'})"`) is functionally correct. The root `package.json` has no `"type": "module"` field, so `require()` is available in the inline script. The short-circuit `||` pattern correctly skips the execSync when `CI` is set to any truthy value.
- `parallel: false` is now present at the correct level (under `pre-commit:`, not under `commands:`), which is the right YAML structure.
- `.lefthook-local.yml` has been added to `.gitignore`, addressing the suggestion from the previous review.
- `yarn biome check --write` continues to use the workspace-installed Biome binary rather than `npx`, ensuring version consistency with CI.
- `stage_fixed: true` remains correctly configured, ensuring Biome-modified files are automatically re-staged.
- The pre-commit hook is confirmed installed at `.git/hooks/pre-commit` and contains the correct lefthook shell wrapper with `LEFTHOOK=0` escape hatch support.

---

## Test Coverage Assessment

- **Manual testing:** The four previous issues are resolved, so a manual test with a staged `.ts` file in `apps/` or `libs/` should now produce the expected behaviour (Biome fixes and re-stages the file). The test marked complete in `tasks.md` should be re-run to confirm against the corrected glob.
- **Automated tests:** Not applicable for git hook infrastructure.

---

## Acceptance Criteria Verification

- [x] Pre-commit hook installed automatically via postinstall: Confirmed. Hook file present at `.git/hooks/pre-commit`.
- [x] Biome auto-fixes lint/format on staged TS files: Glob is now `**/*.{ts,tsx}` and `stage_fixed: true` is set. Functionally correct.
- [x] Fixed files are re-staged automatically: `stage_fixed: true` correctly configured.
- [x] Hook only runs on .ts/.tsx files (skips other types): Glob `**/*.{ts,tsx}` correctly scopes the command. `.js` files excluded as per `biome.json`.
- [x] Hook skips in CI environments: `node -e "process.env.CI || ..."` guard correctly prevents `lefthook install` from running in CI.
- [x] CLAUDE.md documents the hook and escape hatch: Documents the hook and `LEFTHOOK=0` escape hatch. Minor inaccuracy in "JS/TS" wording (see suggestion 1).

---

## Next Steps

1. Update CLAUDE.md line 19 to say "TypeScript files" instead of "JS/TS files" to match the actual glob — minor but worth fixing for accuracy.
2. Decide whether the `tsc --noEmit` step is in or out of scope and add a note to `lefthook.yml` or `plan.md` documenting the decision. The requirement is partially unmet without it.
3. Update `tasks.md` to remove the stale `--reset-hooks-path` reference.

---

## Overall Assessment

APPROVED

All four blocking issues from the previous review cycle have been correctly addressed. The remaining items are minor documentation inaccuracies and a pre-existing gap (no `tsc` step) that does not break the implemented functionality. The hook infrastructure is correctly installed and will function as intended on developer machines.
10 changes: 10 additions & 0 deletions docs/tickets/563/tasks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# #563 Implementation Tasks

## Implementation Tasks

- [x] Add `lefthook` dev dependency to root `package.json` (pinned version)
- [x] Update `postinstall` script in root `package.json` to run `lefthook install` (CI-guarded) after `yarn db:generate`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove stale --reset-hooks-path reference.

The implementation removed this flag (per review.md), but tasks.md still records it. Update to match the actual node -e "process.env.CI || ..." guard.

- [x] Create `lefthook.yml` at repo root with pre-commit hook configuration (biome-check)
- [x] Run `yarn install` to install lefthook and trigger hook installation
- [x] Test hook by staging a file with a lint issue and committing - verify Biome auto-fixes and re-stages it
- [x] Update `CLAUDE.md` with a note about the pre-commit hook under Core Development Commands or a new Git Hooks section
17 changes: 17 additions & 0 deletions docs/tickets/563/ticket.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# #563: Fix any typescript and lint issue when commit code into branch

**State:** OPEN
**Assignees:** KianKwa
**Author:** junaidiqbalmoj
**Labels:** None
**Created:** 2026-05-11T10:59:30Z
**Updated:** 2026-06-29T08:24:17Z

## Description

We need to make sure that when a developers commit a code, it should automatically fix any typescript or lint issue in the code. You need to create per-commit hook for it.

## Comments

### Comment by junaidiqbalmoj on 2026-05-26T12:24:01Z
@SPEC
6 changes: 6 additions & 0 deletions lefthook.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pre-commit:
parallel: false
commands:
biome-check:
run: yarn biome check --write --no-errors-on-unmatched {staged_files}
stage_fixed: true
Comment on lines +1 to +6

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if glob is present in lefthook.yml
cat -n lefthook.yml

Repository: hmcts/cath-service

Length of output: 332


🌐 Web query:

Lefthook command glob staged_files default behaviour no glob file filtering documentation

💡 Result:

In Lefthook, the default behavior for file filtering when no glob is explicitly defined is to process all relevant files based on the hook type (e.g., all staged files for pre-commit hooks) [1][2][3]. When you define a glob or exclude filter, Lefthook applies it to the file list before executing your command [3][4]. The specific mechanics are as follows: 1. Automatic Filtering: If you use a file template in your run command (such as {staged_files}) or provide a custom files command, Lefthook uses your specified glob and exclude patterns to filter that list [1][5]. 2. Implicit Filtering without Templates: If you specify a glob or exclude filter but do not include a file template (like {staged_files}) in your run command, Lefthook will still automatically check the relevant file set—{staged_files} for pre-commit or {push_files} for pre-push [1][4]. 3. Command Skipping: In this scenario, if the filtering process results in no files remaining (e.g., no staged files match your glob pattern), Lefthook will automatically skip the execution of that command entirely [1][6][4]. By default, Lefthook uses the gobwas/glob library for pattern matching [1][7]. A key detail to note is that the `` pattern in this library matches one or more directories deep by default; to match files at the top level and nested directories simultaneously, you must either provide separate patterns or enable glob_matcher: doublestar in your configuration [1][7].

Citations:


Add the glob filter back — without it, this hook will run biome check --write against every staged file, not just TS/TSX files.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you ask AI to compare this hook with existing CaTH? https://github.com/hmcts/pip-frontend/blob/master/lefthook.yml.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"libs/list-types/*"
],
"scripts": {
"postinstall": "yarn db:generate",
"postinstall": "yarn db:generate && node scripts/install-hooks.js",
"test": "turbo test",
"test:force": "turbo test --force",
"test:coverage": "turbo test -- --coverage",
Expand Down Expand Up @@ -54,6 +54,7 @@
"@vitest/ui": "4.1.9",
"concurrently": "10.0.3",
"happy-dom": "^20.0.5",
"lefthook": "2.1.9",
"supertest": "7.2.2",
"tsx": "4.22.4",
"turbo": "2.9.18",
Expand Down
7 changes: 7 additions & 0 deletions scripts/install-hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const { execSync } = require("node:child_process");
const { existsSync } = require("node:fs");

// Skip in CI environments and Docker builds (no .git directory)
if (!process.env.CI && existsSync(".git")) {
execSync("lefthook install", { stdio: "inherit" });
}
Loading
Loading