Initial commit

This commit is contained in:
Zzzz
2026-04-27 18:40:30 +08:00
commit 2120774b05
112 changed files with 12308 additions and 0 deletions
@@ -0,0 +1,141 @@
# Database Guidelines
> MySQL data and DAO conventions for the library-management system.
---
## Overview
MySQL is the project data layer. DAO classes perform CRUD and query operations
against MySQL. Application source and schema files are not present yet, so table
and class names here are illustrative conventions for future implementation.
---
## Core Tables
Use primary keys for every table and foreign keys for cross-entity integrity.
Illustrative table names:
- `books`: book information, inventory count/status, category reference.
- `book_categories`: category names and descriptions.
- `readers`: reader profiles, borrowing eligibility, contact information.
- `borrow_records`: book-reader borrowing, return, renew, and overdue data.
- `administrators`: administrator/librarian login and profile data.
- `roles`: administrator, librarian, reader, and future role definitions.
- `permissions`: permission definitions for protected actions.
- `role_permissions`: role-to-permission mapping.
- `system_logs`: key operation logs, backup events, and exception traces.
When schema files are introduced, record the actual path, DDL style, and exact
table names here.
---
## DAO Responsibilities
- DAOs own database CRUD and query details.
- Use parameterized SQL or prepared-statement style access; never concatenate
raw request parameters into SQL.
- Keep transaction boundaries in the service layer for workflows that span
multiple DAO calls, such as borrow/return operations that also update
inventory status.
- Return entities or small query result objects to services, not HTML or
servlet response objects.
- Keep MySQL connection details in a shared configuration/helper once one
exists, for example `JdbcUtil` plus `db.properties`.
---
## Query Guidance
- Book search must support combined lookup by title, author, category, and ID.
- Statistics queries should cover borrowing rankings, inventory reports, and
overdue reports.
- Borrowing records should preserve enough dates/status fields for borrow,
return, renew, overdue calculation, and automatic collection status updates.
- Permission queries should support role-based checks for administrator,
librarian, and reader workflows.
---
## Integrity Constraints
- `books.category_id` should reference `book_categories`.
- `borrow_records.book_id` should reference `books`.
- `borrow_records.reader_id` should reference `readers`.
- Administrator-role and role-permission mapping tables should use foreign keys
to preserve authorization integrity.
- Prefer explicit status columns/enums for inventory and borrowing states, then
document the chosen values once code exists.
## Scenario: Login And Permission Scaffold Schema
### 1. Scope / Trigger
- Trigger: the initial Java Web scaffold introduced a concrete MySQL schema and
login contract.
- Schema path: `src/main/resources/db/schema.sql`.
- Example configuration path: `src/main/resources/db.properties.example`.
### 2. Signatures
- DAO signature: `UserDao.findActiveByUsername(String username)`.
- Service signature: `AuthService.authenticate(String username, String password)`.
- Permission signature: `AuthService.hasPermission(AuthenticatedUser user, Permission permission)`.
- Login tables: `roles`, `permissions`, `role_permissions`, `users`, and
`system_logs`.
### 3. Contracts
- `users.username`: unique login identifier submitted by `LoginServlet`.
- `users.password_hash`: PBKDF2 hash in
`pbkdf2_sha256$iterations$saltBase64$hashBase64` format.
- `users.role_code`: foreign key to `roles.code`; supported scaffold values
are `administrator`, `librarian`, and `reader`.
- Session state stores an `AuthenticatedUser` snapshot, role code, and
permission-code set. It must not store raw passwords or DAO result objects
with password hashes.
### 4. Validation & Error Matrix
- Missing username or password -> request returns to login JSP with
`Username and password are required.`
- Unknown user, inactive user, or hash mismatch -> request returns to login JSP
with `Invalid username or password.`
- Missing `db.properties`, JDBC failure, or unsupported role code -> request
returns a generic service-unavailable message and logs server-side details.
- Authenticated user missing a required permission -> HTTP 403 and
`WEB-INF/jsp/auth/unauthorized.jsp`.
### 5. Good/Base/Bad Cases
- Good: `admin` resolves to `administrator`, receives all scaffold
permissions, and can access `/admin/home`.
- Base: `reader` resolves to `reader`, can access `/reader/home`, and cannot
access `/admin/home`.
- Bad: a JSP reads SQL or password hashes directly from the database. Keep that
logic in DAO/service code.
### 6. Tests Required
- Compile service/DAO/entity/util classes with `javac` when Maven is
unavailable.
- Run `PermissionPolicyCheck` or equivalent assertions for administrator,
librarian, and reader permissions.
- When Maven/Tomcat dependencies are installed, run `mvn test` or
`mvn clean package` to compile Servlet and JSP integration.
### 7. Wrong vs Correct
#### Wrong
```java
// JSP or Servlet opens JDBC and checks passwords directly.
```
#### Correct
```text
login.jsp -> LoginServlet -> AuthService -> UserDao -> users/roles tables
```
@@ -0,0 +1,73 @@
# Directory Structure
> Backend directory organization for the JSP + Servlet + MySQL application.
---
## Overview
Future backend code should follow the established B/S layered architecture.
There is no application source tree yet; the paths and package names below are
illustrative conventions to use when creating the first application code.
---
## Suggested Layout
```text
src/main/java/com/mzh/library/
controller/ Servlet controllers such as BookServlet
service/ Service interfaces such as BookService
service/impl/ Business implementations such as BookServiceImpl
dao/ DAO interfaces such as BookDao
dao/impl/ MySQL DAO implementations such as BookDaoImpl
entity/ JavaBeans/entities such as Book, Reader, BorrowRecord
filter/ Authentication, authorization, encoding filters
util/ Shared utilities such as JdbcUtil or DateUtil
src/main/resources/
db.properties MySQL connection configuration when introduced
src/main/webapp/
WEB-INF/web.xml Servlet/filter mappings when annotations are not used
```
Use the package root consistently once the first code is created. If a
different root package is chosen in IDEA, update this spec in the same change.
---
## Layer Responsibilities
- `controller`: Servlet classes dispatch requests, validate parameters, call
services, choose JSP forwards or redirects, and return results.
- `service`: Business workflows including book warehousing/intake, borrowing,
returning, renewals, inventory status updates, overdue statistics, and
permission checks.
- `dao`: CRUD and query access to MySQL. DAOs should not perform presentation
rendering or multi-step business workflows.
- `entity`: Plain data objects representing books, categories, readers,
borrowing records, administrators, roles/permissions, and system logs.
- `filter`: Cross-cutting web concerns such as login checks, role guards, and
request encoding.
- `util`: Small shared helpers only after searching for existing helpers first.
---
## Naming Conventions
- Servlet controllers use names such as `BookServlet`, `ReaderServlet`,
`BorrowServlet`, and `LoginServlet`.
- Service interfaces and implementations use names such as `BookService` and
`BookServiceImpl`.
- DAO interfaces and implementations use names such as `BookDao` and
`BookDaoImpl`.
- Entity names should be singular Java nouns such as `Book`, `BookCategory`,
`Reader`, `BorrowRecord`, `Administrator`, `RolePermission`, and
`SystemLog`.
---
## Boundaries
Do not put SQL in JSPs or Servlets. Do not put HTML generation in DAOs or
services. Keep permission checks in filters/services and keep request parameter
parsing in controllers.
+54
View File
@@ -0,0 +1,54 @@
# Error Handling
> Backend error handling conventions for Servlet, service, DAO, and MySQL code.
---
## Overview
Servlet controllers are responsible for parameter validation and safe result
return. Services report business failures such as ineligible readers,
unavailable inventory, failed permission checks, and overdue-rule violations.
DAOs report database failures without leaking SQL details to JSP pages.
---
## Controller Behavior
- Validate required parameters, numeric IDs, dates, and operation names before
calling services.
- On validation failure, return to the relevant JSP with field-level messages
or redirect with a short flash-style message.
- Do not print stack traces or database details into JSP output.
- Use forwards for rendering request-scoped form errors and redirects after
successful mutating operations to avoid duplicate submissions.
---
## Service Behavior
- Centralize business rule failures in the service layer: permission denied,
reader not eligible to borrow, book not available, renewal rejected, overdue
status conflicts, and inventory update failures.
- Keep transaction rollback decisions close to multi-step workflows such as
borrow, return, renew, and book intake.
- Return clear success/failure results or throw project-specific exceptions
once the application defines an exception model.
---
## DAO Behavior
- Wrap low-level SQL/MySQL exceptions with enough context for logs, but do not
expose credentials, raw SQL with user values, or stack traces to users.
- Close JDBC resources reliably using the project helper or language construct
chosen by the first implementation.
- Let services decide whether a DAO failure should abort a transaction or map
to a user-facing message.
---
## User-Facing Results
Use concise messages suitable for JSP rendering. For protected operations,
prefer generic denial messages over exposing permission internals.
+77
View File
@@ -0,0 +1,77 @@
# Backend Development Guidelines
> Backend conventions for the JSP + Servlet + MySQL library-management system.
---
## Overview
The developer has established the backend architecture as a B/S Java web
application using JSP + Servlet, MySQL, Tomcat, and IDEA. Application source
code does not exist in this workspace yet, so package names, class names, and
table names below are illustrative project conventions for future code rather
than references to existing files.
Use a layered design:
```
JSP/CSS presentation -> Servlet controller -> Service/business -> DAO -> MySQL
```
Controllers handle request dispatch, parameter validation, and result return.
Services handle business workflows and permission checks. DAOs perform database
CRUD. MySQL stores books, categories, readers, borrowing records,
administrators, roles/permissions, and system logs.
---
## Guidelines Index
| Guide | Description | Status |
|-------|-------------|--------|
| [Directory Structure](./directory-structure.md) | Servlet, service, DAO, entity, and config organization | Project decision documented |
| [Database Guidelines](./database-guidelines.md) | MySQL tables, DAO CRUD, keys, and transactions | Project decision documented |
| [Error Handling](./error-handling.md) | Servlet validation, service failures, and safe responses | Project decision documented |
| [Quality Guidelines](./quality-guidelines.md) | Layer boundaries and review constraints | Project decision documented |
| [Logging Guidelines](./logging-guidelines.md) | System logs, key operations, and exception tracing | Project decision documented |
---
## Pre-Development Checklist
Before backend implementation, read:
- `.trellis/spec/backend/directory-structure.md`
- `.trellis/spec/backend/database-guidelines.md`
- `.trellis/spec/backend/error-handling.md`
- `.trellis/spec/backend/logging-guidelines.md`
- `.trellis/spec/backend/quality-guidelines.md`
- `.trellis/tasks/00-bootstrap-guidelines/research/project-requirements.md`
---
## Core Backend Modules
- Login and permission management for administrator, librarian, and reader
roles.
- Book information management for create, update, delete, category maintenance,
and inventory status.
- Reader information management for profiles, borrowing eligibility, and
contact information.
- Borrowing and return management for borrow, return, renew, overdue handling,
and automatic collection status updates.
- Book search and statistics for combined title, author, category, and ID
search, borrowing rankings, inventory reports, and overdue reports.
- System maintenance and logs for key operation logs, data backup support, and
exception tracing.
## Evidence
- `.trellis/tasks/00-bootstrap-guidelines/research/repo-scan.md` records that
no application source code exists yet.
- `.trellis/tasks/00-bootstrap-guidelines/research/project-requirements.md`
records the developer-provided stack, architecture, modules, and data model.
---
**Language**: All documentation should be written in **English**.
@@ -0,0 +1,53 @@
# Logging Guidelines
> Logging and system-log conventions for the library-management backend.
---
## Overview
The project requires system maintenance/log support for key operation logs, data
backup support, and exception tracing. MySQL should include a system log table,
illustratively `system_logs`, for durable audit and troubleshooting records.
---
## What to Log
Record key operations that affect security, data integrity, or inventory:
- Login success/failure and logout for administrator, librarian, and reader
roles when applicable.
- Permission changes, role changes, and denied protected operations.
- Book create, update, delete, category maintenance, and warehousing/intake.
- Borrow, return, renew, overdue handling, and automatic inventory status
updates.
- Reader profile, eligibility, and contact information changes.
- Data backup events and restore-related maintenance actions.
- Unhandled exceptions and failed database operations with safe context.
---
## System Log Fields
When the schema is introduced, `system_logs` should preserve enough information
to trace actions without exposing sensitive data. Useful fields include an ID,
operator ID, operator role, operation type, target entity/table, target ID,
result status, message, timestamp, and request IP when available.
---
## Sensitive Data
Do not log passwords, raw credentials, full request bodies, database connection
strings, or unnecessary personal data. Prefer IDs and operation summaries over
large before/after payloads.
---
## Exception Tracing
Server logs may contain technical stack traces for developers. User-facing JSP
pages should receive concise messages. Durable system logs should record the
operation, actor, failure category, and correlation details needed to locate
the server-side exception.
@@ -0,0 +1,58 @@
# Quality Guidelines
> Backend quality constraints for the JSP + Servlet + MySQL application.
---
## Overview
No application source code exists yet, but the developer has established the
backend stack and layered design. Future backend work should preserve those
decisions and update these specs with real file paths once code exists.
---
## Required Patterns
- Keep strict layer boundaries: Servlet -> Service -> DAO -> MySQL.
- Use JSP/CSS only for presentation; JSPs must not contain SQL or business
workflow logic.
- Validate request parameters in Servlet controllers before calling services.
- Enforce permission checks in filters/services for administrator, librarian,
and reader roles.
- Keep inventory status updates inside service workflows so borrow, return,
renew, overdue handling, and book intake remain consistent.
- Use primary keys and foreign keys for core entity relationships.
- Record key operations and exceptions according to the logging spec.
---
## Forbidden Patterns
- Do not introduce React, Vue, SPA routing, ORM conventions, or non-Servlet
backend frameworks unless the developer explicitly changes the stack.
- Do not place SQL in JSP files or directly in presentation helpers.
- Do not put business workflows in DAO classes.
- Do not rely on client-side validation as the only validation for protected
operations.
- Do not expose stack traces, raw SQL errors, or sensitive personal data to end
users.
---
## Checks And Testing
When Java source exists, document and run the actual compile/test commands for
the chosen IDEA/Tomcat project structure. Until then, documentation-only
changes should run Trellis validation, Python compile checks for Trellis
scripts when relevant, and placeholder scans for scaffold markers.
---
## Review Checklist
- Does the change preserve JSP + Servlet + MySQL + Tomcat assumptions?
- Are Servlet, service, DAO, and JSP responsibilities separated?
- Are book, category, reader, borrowing, administrator, permission, and log
data flows covered where relevant?
- Are role permissions and operation logs handled for protected workflows?
@@ -0,0 +1,52 @@
# Component Guidelines
> JSP fragment, form, table, and reusable UI conventions.
---
## Overview
This project uses JSP-based presentation, not a component framework. Treat JSP
includes, fragments, tag files, form layouts, tables, and shared CSS classes as
the reusable UI units.
---
## JSP Includes And Fragments
- Use shared fragments for repeated layout pieces such as header, navigation,
sidebar, footer, pagination, and message banners.
- Prefer `.jspf` includes or JSP tag files once the project chooses one
pattern; document the actual paths after implementation.
- Keep fragments presentation-focused. They should not open database
connections or call DAOs.
---
## Forms
- Forms should post to Servlet controller endpoints, not directly to DAOs or
JSP-only handlers.
- Render validation messages from request attributes set by controllers.
- Preserve user-entered values on validation failure where practical.
- Use clear labels, required-field indicators, and server-side validation for
book, reader, borrowing, login, and permission forms.
---
## Tables And Reports
- Use consistent table patterns for book lists, reader lists, borrowing
records, rankings, inventory reports, overdue reports, and system logs.
- Include stable empty states and pagination or filtering controls when lists
can grow.
- Keep search forms aligned with supported filters: title, author, category,
and book ID.
---
## Styling
Implement JSP/CSS pages to faithfully restore the approved image design. Prefer
semantic class names tied to page structure or reusable UI roles. Avoid adding a
frontend component framework unless explicitly introduced later.
@@ -0,0 +1,52 @@
# Directory Structure
> JSP page and static asset organization for the presentation layer.
---
## Overview
Future frontend code should be JSP/CSS rendered by the Servlet/Tomcat
application. There is no application source tree yet; the paths below are
illustrative conventions for the first implementation.
---
## Suggested Layout
```text
src/main/webapp/
WEB-INF/jsp/
common/ Shared JSP fragments such as header.jspf
auth/ Login and permission pages
books/ Book list, form, detail, category pages
readers/ Reader list, form, detail pages
borrowing/ Borrow, return, renew, overdue pages
statistics/ Search, ranking, inventory, overdue reports
maintenance/ System logs, backup, exception trace pages
static/
css/ Page and shared styles
js/ Small page scripts when needed
images/ Designed/generated UI images and static assets
```
JSPs that should not be accessed directly belong under `WEB-INF/jsp/` and are
rendered through Servlet forwards. Public static files belong under `static/`.
---
## Page Naming
Use module-oriented JSP names such as `books/list.jsp`, `books/form.jsp`,
`readers/detail.jsp`, `borrowing/overdue.jsp`, and
`maintenance/system-logs.jsp`. Match Servlet dispatch paths once controllers
exist.
---
## Static Assets
Keep CSS in `static/css/`, small browser scripts in `static/js/`, and
image-first design references or exported assets in `static/images/` once the
application tree exists. Do not create React/Vue component directories or SPA
asset conventions unless the stack changes.
+31
View File
@@ -0,0 +1,31 @@
# Hook Guidelines
> Hook conventions for this frontend.
---
## Decision
There are no React, Vue, or hook-based frontend conventions in this project.
The established frontend approach is JSP/CSS rendered by Servlets on Tomcat.
Do not introduce React hooks, Vue composables, SPA lifecycle hooks, client-side
state hooks, or hook-style data fetching unless the developer explicitly changes
the stack later.
---
## JSP Alternative
For reusable presentation behavior, use JSP includes/fragments, tag files if
introduced, request attributes, session attributes for authenticated identity,
and small page scripts only when server-rendered JSP cannot handle the
interaction cleanly.
---
## Future Updates
If a JavaScript framework is explicitly introduced later, replace this file
with concrete conventions from the new source code and update the frontend
index status at the same time.
+57
View File
@@ -0,0 +1,57 @@
# Frontend Development Guidelines
> Frontend conventions for the JSP/CSS presentation layer.
---
## Overview
The developer has established a JSP-based presentation layer served by a
Servlet/Tomcat application. Frontend work should use JSP, JSP includes or
fragments, CSS, static images, and small page scripts when needed. Do not assume
React, Vue, frontend hooks, SPA state libraries, or TypeScript conventions
unless the developer explicitly introduces them later.
The frontend workflow is image-first: UI should be designed or generated as
images first, then JSP/CSS pages should restore the design faithfully.
---
## Guidelines Index
| Guide | Description | Status |
|-------|-------------|--------|
| [Directory Structure](./directory-structure.md) | JSP pages, includes, and static assets | Project decision documented |
| [Component Guidelines](./component-guidelines.md) | JSP fragments, forms, tables, and reusable UI | Project decision documented |
| [Hook Guidelines](./hook-guidelines.md) | No React/Vue hook conventions unless introduced later | Project decision documented |
| [State Management](./state-management.md) | Server-rendered request/session/form state | Project decision documented |
| [Quality Guidelines](./quality-guidelines.md) | Image-to-JSP restoration and UI checks | Project decision documented |
| [Type Safety](./type-safety.md) | JSP/Servlet validation and JavaBean display contracts | Project decision documented |
---
## Pre-Development Checklist
Before frontend implementation, read:
- `.trellis/spec/frontend/directory-structure.md`
- `.trellis/spec/frontend/component-guidelines.md`
- `.trellis/spec/frontend/hook-guidelines.md`
- `.trellis/spec/frontend/state-management.md`
- `.trellis/spec/frontend/type-safety.md`
- `.trellis/spec/frontend/quality-guidelines.md`
- `.trellis/tasks/00-bootstrap-guidelines/research/project-requirements.md`
---
## Evidence
- `.trellis/tasks/00-bootstrap-guidelines/research/repo-scan.md` records that
no application source code exists yet.
- `.trellis/tasks/00-bootstrap-guidelines/research/project-requirements.md`
records the developer-provided JSP presentation approach and image-to-JSP
workflow.
---
**Language**: All documentation should be written in **English**.
@@ -0,0 +1,60 @@
# Quality Guidelines
> Frontend quality constraints for JSP/CSS pages.
---
## Overview
Frontend work should implement JSP/CSS pages that match the approved
image-first design and preserve the Servlet/JSP layered architecture.
---
## Image-To-JSP Workflow
1. Design or generate the UI as images first.
2. Use the approved image as the visual reference for JSP/CSS implementation.
3. Restore layout, spacing, typography, color, table density, and form states
faithfully in JSP/CSS.
4. Preserve the image assets or references in the application assets area once
the source tree exists.
5. Compare the implemented page against the source image before considering UI
work complete.
---
## Required Patterns
- JSP pages focus on display and user interaction.
- Forms submit to Servlet controllers and render server-provided validation
messages.
- Tables and reports support scanning for books, readers, borrowing records,
rankings, inventory, overdue data, and system logs.
- Navigation should reflect role permissions for administrator, librarian, and
reader users.
- Keep CSS and small scripts in static assets rather than inline unless there
is a local reason.
---
## Forbidden Patterns
- Do not introduce React, Vue, SPA routing, hook/state conventions, or
TypeScript tooling without an explicit stack change.
- Do not implement UI only from text descriptions when an approved image
reference exists.
- Do not put SQL, DAO calls, or business workflows in JSP pages.
- Do not rely only on browser validation for protected workflows.
---
## Review Checklist
- Does the JSP/CSS page visibly match the approved image design?
- Are forms, tables, empty states, errors, and permission-specific navigation
handled?
- Are JSPs rendered through Servlet controllers where access control or page
data is required?
- Are accessibility basics preserved with labels, headings, focus order, and
readable contrast?
@@ -0,0 +1,42 @@
# State Management
> State conventions for server-rendered JSP pages.
---
## Overview
This project does not use React/Vue state libraries or SPA stores. State should
flow through the Servlet/JSP request cycle unless a future explicit decision
changes the frontend architecture.
---
## State Categories
- Request attributes: page data, validation errors, form echoes, table rows,
reports, and short result messages for a single render.
- Session attributes: authenticated user identity, role, permission summary,
and short-lived flash-style messages when redirects are used.
- Database state: books, categories, readers, borrowing records,
administrators, permissions, and logs stored in MySQL through services/DAOs.
- Form state: submitted by browser forms to Servlets and re-rendered from
validated request attributes on failure.
---
## Rules
- Keep business state in MySQL, not hidden fields or long-lived browser state.
- Keep permission decisions server-side.
- Use redirects after successful mutations such as create/update/delete,
borrow, return, renew, and permission changes.
- Do not add Redux, Pinia, client caches, or SPA routing state unless the
developer explicitly introduces that stack later.
---
## Page Scripts
Small JavaScript can improve interaction, such as confirm dialogs or local form
helpers, but server-side validation and service-layer rules remain mandatory.
+42
View File
@@ -0,0 +1,42 @@
# Type Safety
> Display and validation contracts for JSP/Servlet frontend work.
---
## Overview
The frontend is JSP/CSS, not TypeScript. Type safety comes from Java entities,
Servlet parameter parsing, service contracts, DAO results, and careful JSP
rendering.
---
## JSP Data Contracts
- Servlets should set clearly named request attributes before forwarding to
JSPs, such as `books`, `reader`, `borrowRecords`, `errors`, and `message`.
- JSP pages should render JavaBean/entity properties through JSP EL or JSTL
rather than embedding business Java code.
- Keep attribute names stable between Servlet controllers and JSP pages; update
both sides together when a contract changes.
---
## Validation
- Parse and validate IDs, dates, enum/status values, and required strings in
Servlet controllers before calling services.
- Services should re-check business rules such as borrowing eligibility,
inventory availability, overdue status, and permission access.
- JSP pages should display validation messages but should not be the only place
validation occurs.
---
## Forbidden Patterns
- Do not claim TypeScript, generated API types, React prop types, or Vue type
conventions exist unless the stack changes.
- Do not use JSP scriptlets for business logic.
- Do not let JSP pages infer database schema details directly.
@@ -0,0 +1,105 @@
# Code Reuse Thinking Guide
> **Purpose**: Stop and think before creating new code - does it already exist?
---
## The Problem
**Duplicated code is the #1 source of inconsistency bugs.**
When you copy-paste or rewrite existing logic:
- Bug fixes don't propagate
- Behavior diverges over time
- Codebase becomes harder to understand
---
## Before Writing New Code
### Step 1: Search First
```bash
# Search for similar function names
grep -r "functionName" .
# Search for similar logic
grep -r "keyword" .
```
### Step 2: Ask These Questions
| Question | If Yes... |
|----------|-----------|
| Does a similar function exist? | Use or extend it |
| Is this pattern used elsewhere? | Follow the existing pattern |
| Could this be a shared utility? | Create it in the right place |
| Am I copying code from another file? | **STOP** - extract to shared |
---
## Common Duplication Patterns
### Pattern 1: Copy-Paste Functions
**Bad**: Copying a validation function to another file
**Good**: Extract to shared utilities, import where needed
### Pattern 2: Similar Components
**Bad**: Creating a new component that's 80% similar to existing
**Good**: Extend existing component with props/variants
### Pattern 3: Repeated Constants
**Bad**: Defining the same constant in multiple files
**Good**: Single source of truth, import everywhere
---
## When to Abstract
**Abstract when**:
- Same code appears 3+ times
- Logic is complex enough to have bugs
- Multiple people might need this
**Don't abstract when**:
- Only used once
- Trivial one-liner
- Abstraction would be more complex than duplication
---
## After Batch Modifications
When you've made similar changes to multiple files:
1. **Review**: Did you catch all instances?
2. **Search**: Run grep to find any missed
3. **Consider**: Should this be abstracted?
---
## Gotcha: Asymmetric Mechanisms Producing Same Output
**Problem**: When two different mechanisms must produce the same file set (e.g., recursive directory copy for init vs. manual `files.set()` for update), structural changes (renaming, moving, adding subdirectories) only propagate through the automatic mechanism. The manual one silently drifts.
**Symptom**: Init works perfectly, but update creates files at wrong paths or misses files entirely.
**Prevention checklist**:
- [ ] When migrating directory structures, search for ALL code paths that reference the old structure
- [ ] If one path is auto-derived (glob/copy) and another is manually listed, the manual one needs updating
- [ ] Add a regression test that compares outputs from both mechanisms
---
## Checklist Before Commit
- [ ] Searched for existing similar code
- [ ] No copy-pasted logic that should be shared
- [ ] Constants defined in one place
- [ ] Similar patterns follow same structure
@@ -0,0 +1,94 @@
# Cross-Layer Thinking Guide
> **Purpose**: Think through data flow across layers before implementing.
---
## The Problem
**Most bugs happen at layer boundaries**, not within layers.
Common cross-layer bugs:
- API returns format A, frontend expects format B
- Database stores X, service transforms to Y, but loses data
- Multiple layers implement the same logic differently
---
## Before Implementing Cross-Layer Features
### Step 1: Map the Data Flow
Draw out how data moves:
```
Source → Transform → Store → Retrieve → Transform → Display
```
For each arrow, ask:
- What format is the data in?
- What could go wrong?
- Who is responsible for validation?
### Step 2: Identify Boundaries
| Boundary | Common Issues |
|----------|---------------|
| API ↔ Service | Type mismatches, missing fields |
| Service ↔ Database | Format conversions, null handling |
| Backend ↔ Frontend | Serialization, date formats |
| Component ↔ Component | Props shape changes |
### Step 3: Define Contracts
For each boundary:
- What is the exact input format?
- What is the exact output format?
- What errors can occur?
---
## Common Cross-Layer Mistakes
### Mistake 1: Implicit Format Assumptions
**Bad**: Assuming date format without checking
**Good**: Explicit format conversion at boundaries
### Mistake 2: Scattered Validation
**Bad**: Validating the same thing in multiple layers
**Good**: Validate once at the entry point
### Mistake 3: Leaky Abstractions
**Bad**: Component knows about database schema
**Good**: Each layer only knows its neighbors
---
## Checklist for Cross-Layer Features
Before implementation:
- [ ] Mapped the complete data flow
- [ ] Identified all layer boundaries
- [ ] Defined format at each boundary
- [ ] Decided where validation happens
After implementation:
- [ ] Tested with edge cases (null, empty, invalid)
- [ ] Verified error handling at each boundary
- [ ] Checked data survives round-trip
---
## When to Create Flow Documentation
Create detailed flow docs when:
- Feature spans 3+ layers
- Multiple teams are involved
- Data format is complex
- Feature has caused bugs before
+79
View File
@@ -0,0 +1,79 @@
# Thinking Guides
> **Purpose**: Expand your thinking to catch things you might not have considered.
---
## Why Thinking Guides?
**Most bugs and tech debt come from "didn't think of that"**, not from lack of skill:
- Didn't think about what happens at layer boundaries → cross-layer bugs
- Didn't think about code patterns repeating → duplicated code everywhere
- Didn't think about edge cases → runtime errors
- Didn't think about future maintainers → unreadable code
These guides help you **ask the right questions before coding**.
---
## Available Guides
| Guide | Purpose | When to Use |
|-------|---------|-------------|
| [Code Reuse Thinking Guide](./code-reuse-thinking-guide.md) | Identify patterns and reduce duplication | When you notice repeated patterns |
| [Cross-Layer Thinking Guide](./cross-layer-thinking-guide.md) | Think through data flow across layers | Features spanning multiple layers |
---
## Quick Reference: Thinking Triggers
### When to Think About Cross-Layer Issues
- [ ] Feature touches 3+ layers (API, Service, Component, Database)
- [ ] Data format changes between layers
- [ ] Multiple consumers need the same data
- [ ] You're not sure where to put some logic
→ Read [Cross-Layer Thinking Guide](./cross-layer-thinking-guide.md)
### When to Think About Code Reuse
- [ ] You're writing similar code to something that exists
- [ ] You see the same pattern repeated 3+ times
- [ ] You're adding a new field to multiple places
- [ ] **You're modifying any constant or config**
- [ ] **You're creating a new utility/helper function** ← Search first!
→ Read [Code Reuse Thinking Guide](./code-reuse-thinking-guide.md)
---
## Pre-Modification Rule (CRITICAL)
> **Before changing ANY value, ALWAYS search first!**
```bash
# Search for the value you're about to change
grep -r "value_to_change" .
```
This single habit prevents most "forgot to update X" bugs.
---
## How to Use This Directory
1. **Before coding**: Skim the relevant thinking guide
2. **During coding**: If something feels repetitive or complex, check the guides
3. **After bugs**: Add new insights to the relevant guide (learn from mistakes)
---
## Contributing
Found a new "didn't think of that" moment? Add it to the relevant guide.
---
**Core Principle**: 30 minutes of thinking saves 3 hours of debugging.