From fac7a27cfaf9f5e5c7ec20f6158059be0a7d348d Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Thu, 25 Jun 2026 17:51:43 -0500 Subject: [PATCH 01/72] Initial commit --- .gitignore | 0 LICENSE | 0 README.md | 1 + 3 files changed, 1 insertion(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e69de29 diff --git a/README.md b/README.md new file mode 100644 index 0000000..91e1b49 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# backend-journey From 448dbfb51f56cf5f5f1e2940583633923e88fb46 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Thu, 25 Jun 2026 22:03:56 -0500 Subject: [PATCH 02/72] initialize 90-day backend residency vault --- .obsidian/app.json | 1 + .obsidian/appearance.json | 1 + .obsidian/core-plugins.json | 33 +++++ .obsidian/workspace.json | 198 +++++++++++++++++++++++++++++ CURRENT.md | 10 ++ README.md | 25 +++- ROADMAP.md | 143 +++++++++++++++++++++ SKILLS.md | 18 +++ WEEKLY.md | 52 ++++++++ docs/adr/0001-python.md | 14 ++ docs/adr/0002-fastapi.md | 14 ++ docs/adr/0003-postgresql.md | 14 ++ docs/adr/0004-project-structure.md | 25 ++++ docs/interview/LOG.md | 38 ++++++ docs/mistakes/template.md | 13 ++ journal/2026-06-25.md | 15 +++ knowledge/auth.md | 15 +++ knowledge/docker.md | 10 ++ knowledge/sql.md | 16 +++ knowledge/testing.md | 10 ++ project/README.md | 35 +++++ project/TODO.md | 19 +++ project/api-design.md | 33 +++++ project/architecture.md | 22 ++++ project/database.md | 48 +++++++ todo.md | 173 +++++++++++++++++++++++++ todo.txt | 10 ++ 27 files changed, 1004 insertions(+), 1 deletion(-) create mode 100644 .obsidian/app.json create mode 100644 .obsidian/appearance.json create mode 100644 .obsidian/core-plugins.json create mode 100644 .obsidian/workspace.json create mode 100644 CURRENT.md create mode 100644 ROADMAP.md create mode 100644 SKILLS.md create mode 100644 WEEKLY.md create mode 100644 docs/adr/0001-python.md create mode 100644 docs/adr/0002-fastapi.md create mode 100644 docs/adr/0003-postgresql.md create mode 100644 docs/adr/0004-project-structure.md create mode 100644 docs/interview/LOG.md create mode 100644 docs/mistakes/template.md create mode 100644 journal/2026-06-25.md create mode 100644 knowledge/auth.md create mode 100644 knowledge/docker.md create mode 100644 knowledge/sql.md create mode 100644 knowledge/testing.md create mode 100644 project/README.md create mode 100644 project/TODO.md create mode 100644 project/api-design.md create mode 100644 project/architecture.md create mode 100644 project/database.md create mode 100644 todo.md create mode 100644 todo.txt diff --git a/.obsidian/app.json b/.obsidian/app.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/.obsidian/app.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/.obsidian/appearance.json b/.obsidian/appearance.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/.obsidian/appearance.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/.obsidian/core-plugins.json b/.obsidian/core-plugins.json new file mode 100644 index 0000000..639b90d --- /dev/null +++ b/.obsidian/core-plugins.json @@ -0,0 +1,33 @@ +{ + "file-explorer": true, + "global-search": true, + "switcher": true, + "graph": true, + "backlink": true, + "canvas": true, + "outgoing-link": true, + "tag-pane": true, + "footnotes": false, + "properties": true, + "page-preview": true, + "daily-notes": true, + "templates": true, + "note-composer": true, + "command-palette": true, + "slash-command": false, + "editor-status": true, + "bookmarks": true, + "markdown-importer": false, + "zk-prefixer": false, + "random-note": false, + "outline": true, + "word-count": true, + "slides": false, + "audio-recorder": false, + "workspaces": false, + "file-recovery": true, + "publish": false, + "sync": true, + "bases": true, + "webviewer": false +} \ No newline at end of file diff --git a/.obsidian/workspace.json b/.obsidian/workspace.json new file mode 100644 index 0000000..7e8d496 --- /dev/null +++ b/.obsidian/workspace.json @@ -0,0 +1,198 @@ +{ + "main": { + "id": "a1b0176b1ef37617", + "type": "split", + "children": [ + { + "id": "8b58fcdf9ad2e9f7", + "type": "tabs", + "children": [ + { + "id": "0c25d35aafc48913", + "type": "leaf", + "state": { + "type": "markdown", + "state": { + "file": "ROADMAP.md", + "mode": "source", + "source": false + }, + "icon": "lucide-file", + "title": "ROADMAP" + } + } + ] + } + ], + "direction": "vertical" + }, + "left": { + "id": "18590873115420c5", + "type": "split", + "children": [ + { + "id": "e7cefb4d332bed01", + "type": "tabs", + "children": [ + { + "id": "507412faf2428b1f", + "type": "leaf", + "state": { + "type": "file-explorer", + "state": { + "sortOrder": "alphabetical", + "autoReveal": false + }, + "icon": "lucide-folder-closed", + "title": "Files" + } + }, + { + "id": "abb9add6358c1d29", + "type": "leaf", + "state": { + "type": "search", + "state": { + "query": "", + "matchingCase": false, + "explainSearch": false, + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical" + }, + "icon": "lucide-search", + "title": "Search" + } + }, + { + "id": "b14b7b99a72cc73c", + "type": "leaf", + "state": { + "type": "bookmarks", + "state": {}, + "icon": "lucide-bookmark", + "title": "Bookmarks" + } + } + ] + } + ], + "direction": "horizontal", + "width": 300 + }, + "right": { + "id": "4c611e4a8d3a5aff", + "type": "split", + "children": [ + { + "id": "fb107eb5bfebed94", + "type": "tabs", + "children": [ + { + "id": "c6ff5e5ca338533a", + "type": "leaf", + "state": { + "type": "backlink", + "state": { + "file": "ROADMAP.md", + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical", + "showSearch": false, + "searchQuery": "", + "backlinkCollapsed": false, + "unlinkedCollapsed": true + }, + "icon": "links-coming-in", + "title": "Backlinks for ROADMAP" + } + }, + { + "id": "c1cd5b9d9be14866", + "type": "leaf", + "state": { + "type": "outgoing-link", + "state": { + "file": "ROADMAP.md", + "linksCollapsed": false, + "unlinkedCollapsed": true + }, + "icon": "links-going-out", + "title": "Outgoing links from ROADMAP" + } + }, + { + "id": "41cf0ed6f2c1fdeb", + "type": "leaf", + "state": { + "type": "tag", + "state": { + "sortOrder": "frequency", + "useHierarchy": true, + "showSearch": false, + "searchQuery": "" + }, + "icon": "lucide-tags", + "title": "Tags" + } + }, + { + "id": "236c47cc706f5b7d", + "type": "leaf", + "state": { + "type": "all-properties", + "state": { + "sortOrder": "frequency", + "showSearch": false, + "searchQuery": "" + }, + "icon": "lucide-archive", + "title": "All properties" + } + }, + { + "id": "65bbd144811c48e0", + "type": "leaf", + "state": { + "type": "outline", + "state": { + "file": "ROADMAP.md", + "followCursor": false, + "showSearch": false, + "searchQuery": "" + }, + "icon": "lucide-list", + "title": "Outline of ROADMAP" + } + } + ] + } + ], + "direction": "horizontal", + "width": 300, + "collapsed": true + }, + "left-ribbon": { + "hiddenItems": { + "switcher:Open quick switcher": false, + "graph:Open graph view": false, + "canvas:Create new canvas": false, + "daily-notes:Open today's daily note": false, + "templates:Insert template": false, + "command-palette:Open command palette": false, + "bases:Create new base": false + } + }, + "active": "0c25d35aafc48913", + "lastOpenFiles": [ + "README.md", + "journal/2026-06-25.md", + "CURRENT.md", + "ROADMAP.md", + "SKILLS.md", + "todo.md", + "WEEKLY.md", + "knowledge/docker.md", + "knowledge/auth.md" + ] +} \ No newline at end of file diff --git a/CURRENT.md b/CURRENT.md new file mode 100644 index 0000000..8bea55c --- /dev/null +++ b/CURRENT.md @@ -0,0 +1,10 @@ +# Current Focus + +## Current Objective +Initialize the Development Environment and establish version 1.0 of the Backend Residency Vault. + +## Current Blocker +None. + +## Next Action +Initialize Python environment using `uv`, set up formatting/linting tools, and Docker Compose for PostgreSQL. diff --git a/README.md b/README.md index 91e1b49..0eb8713 100644 --- a/README.md +++ b/README.md @@ -1 +1,24 @@ -# backend-journey +# Backend Journey: 90-Day Backend Residency + +Welcome to your Backend Residency. This repository is configured as an Obsidian vault to organize your learning path, track progress, maintain a backlog for your flagship project, log interviews, and consolidate your personal backend engineering notes. + +## Repository Structure + +- [todo.md](/todo.md) — The main checklist representing the core phases, tasks, and exit criteria. (Symlinked to your home directory at `~/todo.md` for quick access!) +- [ROADMAP.md](/ROADMAP.md) — The high-level strategic roadmap with phase details and exit gates. +- [WEEKLY.md](/WEEKLY.md) — Your tactical weekly planning and review document. +- [INTERVIEW.md](/INTERVIEW.md) — Conceptual flashcards and logs of mock/real interviews. +- `project/` + - [TODO.md](/project/TODO.md) — The operational backlog for your flagship backend project. +- `notes/` — Focused study notes mapping to key interview pillars: + - [sql.md](/notes/sql.md) — SQL, indexes, transactions, normalization, joins. + - [auth.md](/notes/auth.md) — JWTs, hashing, authorization, and authentication flows. + - [docker.md](/notes/docker.md) — Containerization basics and multi-stage builds. + - [testing.md](/notes/testing.md) — Unit testing, integration testing, and pytest. + +--- + +## Guidelines for Obsidian Usage +- Open this workspace directory ('/') directly as a Vault in **Obsidian**. +- Use standard markdown links (e.g. `[[ROADMAP]]` or `[[notes/sql]]`) to connect your study materials, daily logs, and project tasks. +- Keep updates concise and version-controlled. Commit your changes at the end of each week. diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..8fd8bd3 --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,143 @@ +# Strategic Roadmap - Backend Residency + +This document outlines the milestones and gates of the Backend Residency. Instead of strict dates, it tracks progress using explicit status states, estimated efforts, and verification tests. + +--- + +## 🏁 Flagship Project: Inventory Management API +A production-ready backend for inventory and order management. +- **Key Modules:** Auth & RBAC, Products & Categories, Orders & Transaction safety, Search & Filtering, and logging. +- **Reference Docs:** [[project/README]], [[project/architecture]], [[project/api-design]], [[project/database]]. + +--- + +## Milestones + +### Milestone 0: Development Environment & Setup +- **Status:** 🟨 In Progress +- **Estimated Effort:** 5–10 hours +- **Tasks:** + - Configure workspace structure & symlink (`~/todo.md`) + - Initialize Python environment using `uv` + - Configure Ruff, mypy, and code formatter + - Setup multi-container Docker Compose file (`FastAPI` & `PostgreSQL`) +- **Acceptance Tests:** + - [ ] Running `docker compose up` starts both FastAPI and PostgreSQL database. + - [ ] Running `curl http://localhost:8000/docs` yields a valid HTML response. +- **Interview Checkpoint:** + - [ ] Why do we use virtual environments (e.g., `uv`)? + - [ ] What is the difference between a Docker image and a Docker container? + - [ ] Why do we use Docker Compose for local development? + +--- + +### Milestone 1: Secure User Registration & CRUD +- **Status:** 🟥 Not Started +- **Estimated Effort:** 15–20 hours +- **Research:** + - Read FastAPI official documentation on path parameters and Pydantic models. + - Read HTTP specifications for Methods and Response Status Codes. +- **Implement:** + - `POST /auth/register` (user creation) + - `GET /users/me` and `PATCH /users/me` profile endpoints +- **Verify:** + - [ ] Test endpoints manually with `curl` and parse response with `jq`. + - [ ] Verify validation errors format matches standard JSON error formats. +- **Acceptance Tests:** + - [ ] Create user through API, fetch details, and verify fields match input payload. + - [ ] Attempting to register a user with invalid email syntax returns `422 Unprocessable Entity`. +- **Interview Checkpoint:** + - [ ] What is the request-response lifecycle? + - [ ] What is the difference between `PUT` and `PATCH`? + - [ ] Why do we use Pydantic for validation and serialization? + +--- + +### Milestone 2: Relational Schema & Persistence (PostgreSQL) +- **Status:** 🟥 Not Started +- **Estimated Effort:** 20–25 hours +- **Research:** + - Read SQLAlchemy documentation on Declarative Mappings and Async Sessions. + - Read Alembic documentation on migration generations. +- **Implement:** + - User and Profile relational model tables. + - DB sessions injection dependencies. + - Initial migration scripts. +- **Verify:** + - [ ] Run raw SQL commands directly inside PostgreSQL client container to verify data fields. +- **Acceptance Tests:** + - [ ] Initialize migration database successfully. + - [ ] Register user, restart the database container, and verify the user still exists (persistence check). + - [ ] Run Alembic downgrade and upgrade successfully without errors. +- **Interview Checkpoint:** + - [ ] What are the ACID properties in databases? + - [ ] What is the difference between an `INNER JOIN` and a `LEFT JOIN`? + - [ ] What is database indexing, and when should you avoid using it? + - [ ] Why do we use migrations instead of executing direct SQL statements against production databases? + +--- + +### Milestone 3: Security & RBAC (Role-Based Access Control) +- **Status:** 🟥 Not Started +- **Estimated Effort:** 25–30 hours +- **Research:** + - Read OAuth2 password flow specifications. + - Read JWT standard specifications (claims, signatures). +- **Implement:** + - Secure `/auth/token` login endpoint generating Access/Refresh tokens. + - Token verification guards and user role decorators (Admin, Staff, Customer). +- **Verify:** + - [ ] Ensure passwords stored in the database are hashed (never plaintext). + - [ ] Verify access tokens expire in 15 minutes and refresh tokens rotate properly. +- **Acceptance Tests:** + - [ ] Attempt to access a protected endpoint without an Authorization header returns `401 Unauthorized`. + - [ ] Attempt to access an Admin resource using a Customer credential returns `403 Forbidden`. + - [ ] Tokens refreshed successfully via HttpOnly cookie endpoints. +- **Interview Checkpoint:** + - [ ] How does JWT authentication work? + - [ ] Why do we use Refresh Tokens, and where should they be stored? + - [ ] What is Role-Based Access Control (RBAC)? + +--- + +### Milestone 4: Product Inventory & Transactions +- **Status:** 🟥 Not Started +- **Estimated Effort:** 25–35 hours +- **Research:** + - Read SQLAlchemy documentation on transactions and concurrency locks. +- **Implement:** + - Product and Category tables. + - Stock control routes. + - Transaction-safe `/orders` processing endpoint. +- **Verify:** + - [ ] Verify query parameters for filtering, pagination, and text search yield the expected subsets. +- **Acceptance Tests:** + - [ ] Place an order for an item: check that stock levels are decremented atomically. + - [ ] Attempt to order an item with quantity exceeding stock level: check that the order is rejected and transaction rolls back. + - [ ] Concurrently place orders to verify stock level never falls below zero. +- **Interview Checkpoint:** + - [ ] What is transaction isolation, and why does it matter? + - [ ] How do you handle database race conditions? + - [ ] What is offset pagination vs keyset pagination? + +--- + +### Milestone 5: Robust Testing, Logging & CI/CD +- **Status:** 🟥 Not Started +- **Estimated Effort:** 20–30 hours +- **Research:** + - Read pytest documentation on fixture scopes and async support. + - Read Nginx/Caddy documentation for reverse proxy configuration. +- **Implement:** + - Full pytest integration test client suite. + - Multistage Dockerfile. + - GitHub Actions testing workflow. +- **Verify:** + - [ ] Verify application tests execute on every push in GitHub. +- **Acceptance Tests:** + - [ ] Test suite executes successfully with >80% code coverage. + - [ ] Production Docker image builds under 200MB. +- **Interview Checkpoint:** + - [ ] What is the difference between unit testing and integration testing? + - [ ] Why do we use fixtures in pytest? + - [ ] What is reverse proxying, and why should you place your backend behind it? diff --git a/SKILLS.md b/SKILLS.md new file mode 100644 index 0000000..d65340f --- /dev/null +++ b/SKILLS.md @@ -0,0 +1,18 @@ +# Skills Matrix + +Use this matrix to track your confidence and interview readiness for key backend technologies. Update this at the end of each milestone review. + +| Skill | Confidence | Interview Ready | Linked Notes | +| :--- | :---: | :---: | :--- | +| **Python** | 3/5 | 🟨 | [[knowledge/testing]] | +| **Git & GitHub** | 4/5 | 🟩 | - | +| **FastAPI** | 2/5 | 🟥 | [[knowledge/auth]] | +| **SQL & PostgreSQL** | 2/5 | 🟥 | [[knowledge/sql]] | +| **Docker & Compose** | 2/5 | 🟥 | [[knowledge/docker]] | +| **Testing (pytest)** | 1/5 | 🟥 | [[knowledge/testing]] | +| **JWT & RBAC** | 1/5 | 🟥 | [[knowledge/auth]] | + +*Status Legend:* +- 🟥 Not Ready (Cannot explain under interview pressure) +- 🟨 Developing (Can explain core concepts, but need prompts/notes) +- 🟩 Interview Ready (Can explain trade-offs, architecture, and solve issues confidently) diff --git a/WEEKLY.md b/WEEKLY.md new file mode 100644 index 0000000..2c940bc --- /dev/null +++ b/WEEKLY.md @@ -0,0 +1,52 @@ +# Weekly Tactical Plan + +This file is updated at the beginning of each week (every Monday) to detail specific focus tasks. + +## Current Week: Week 1 (Phase 0) + +### Goals +- Set up a clean Python development workspace. +- Learn tmux pane/session management. +- Get comfortable with command-line API queries (`curl`, `jq`). +- Set up a basic `docker-compose.yml` for PostgreSQL and FastAPI. + +--- + +### Daily Schedule + +#### Monday +- [ ] Initialize Python environment using `uv`. +- [ ] Set up Ruff for linting and formatting. +- [ ] Set up mypy for type annotations. + +#### Tuesday +- [ ] Master basic `tmux` commands (create session, split panes, navigate, copy mode). +- [ ] Practice editing files from terminal and using terminal splits. + +#### Wednesday +- [ ] Master `curl` flags: `-X`, `-H`, `-d`, `-i`, `-v`. +- [ ] Install and use `jq` to parse JSON API responses. + +#### Thursday +- [ ] Write a basic `docker-compose.yml` defining a PostgreSQL service. +- [ ] Test connection using local tools. + +#### Friday +- [ ] Connect FastAPI to PostgreSQL container. +- [ ] Run automated checks and tests. + +--- + +## Weekly Review + +### Wins +- + +### Blockers / Hurdles +- + +### Key Lessons +- + +### Focus for Next Week +- diff --git a/docs/adr/0001-python.md b/docs/adr/0001-python.md new file mode 100644 index 0000000..ba42df6 --- /dev/null +++ b/docs/adr/0001-python.md @@ -0,0 +1,14 @@ +# ADR 0001: Language Choice (Python) + +## Status +Accepted + +## Context +We need a backend programming language that optimizes the learning curve and maximizes the likelihood of getting hired quickly. Andres already has familiarity with Python and has explored FastAPI before. + +## Decision +Use **Python** as the sole language for this residency. + +## Consequences & Trade-offs +- **Pros:** Fast development cycle, lower syntax overhead, Andres already knows it. +- **Cons:** Some enterprise roles prefer Java/C#, but Python still has high demand and allows focusing on core backend concepts instead of syntax. diff --git a/docs/adr/0002-fastapi.md b/docs/adr/0002-fastapi.md new file mode 100644 index 0000000..082e775 --- /dev/null +++ b/docs/adr/0002-fastapi.md @@ -0,0 +1,14 @@ +# ADR 0002: Backend Framework Choice (FastAPI) + +## Status +Accepted + +## Context +We need a modern backend web framework with automatic docs, typing support, and dependency injection to build REST APIs efficiently. + +## Decision +Use **FastAPI** as the primary backend framework. + +## Consequences & Trade-offs +- **Pros:** Automatic OpenAPI/Swagger generation, standard dependency injection, asynchronous support, strong ecosystem integration with Pydantic. +- **Cons:** Less prescriptive structure than Django, requiring us to define our own architectural standards. diff --git a/docs/adr/0003-postgresql.md b/docs/adr/0003-postgresql.md new file mode 100644 index 0000000..195233e --- /dev/null +++ b/docs/adr/0003-postgresql.md @@ -0,0 +1,14 @@ +# ADR 0003: Database Engine (PostgreSQL) + +## Status +Accepted + +## Context +We need a robust, production-grade relational database. SQL databases are highly tested in junior backend interviews. + +## Decision +Use **PostgreSQL** instead of SQLite or MongoDB. + +## Consequences & Trade-offs +- **Pros:** Full feature set (concurrency, transactions, indexing, jsonb support) reflecting real-world backend jobs. +- **Cons:** Slightly more complex local setup compared to SQLite, which we will mitigate by using Docker Compose. diff --git a/docs/adr/0004-project-structure.md b/docs/adr/0004-project-structure.md new file mode 100644 index 0000000..3a9a744 --- /dev/null +++ b/docs/adr/0004-project-structure.md @@ -0,0 +1,25 @@ +# ADR 0004: Project Directory Structure + +## Status +Accepted + +## Context +A clean, scalable, and maintainable project directory structure is required for our flagship API to emulate production standards. + +## Decision +Adopt a modular or layered architecture layout for the source code: +``` +src/ +├── main.py # App entrypoint & lifespans +├── config.py # Settings and environment config +├── database.py # SQLAlchemy session & engine setup +├── models/ # SQLAlchemy database models +├── schemas/ # Pydantic schemas (requests/responses) +├── routers/ # FastAPI routers (endpoints) +├── services/ # Business logic and database operations +└── core/ # Security, dependencies, middleware +``` + +## Consequences & Trade-offs +- **Pros:** Distinct separation of concerns (validation, business logic, routing, persistence). Highly readable for interviewers. +- **Cons:** Slightly more boilerplate files to create compared to a single-file API. diff --git a/docs/interview/LOG.md b/docs/interview/LOG.md new file mode 100644 index 0000000..8592be5 --- /dev/null +++ b/docs/interview/LOG.md @@ -0,0 +1,38 @@ +# Interview Prep & Log + +Use this file to record technical interview questions, whiteboard tasks, behavioral questions, and areas of improvement discovered during mock or real interviews. + +## Core Conceptual Flashcards + +### HTTP & REST +- **What is the request-response lifecycle?** +- **Difference between PUT and PATCH?** +- **What is middleware and how is it used in FastAPI?** + +### Databases +- **What are ACID properties?** +- **Explain database normalization (1NF, 2NF, 3NF).** +- **What is an index? When should you NOT use an index?** +- **What is the difference between INNER JOIN, LEFT JOIN, and RIGHT JOIN?** + +### Security & System Design +- **How does JWT authentication work?** +- **Why do we use refresh tokens, and where should they be stored?** +- **What is RBAC (Role-Based Access Control)?** + +--- + +## Mock & Real Interview Log + +### [Date] - [Company Name] +- **Role:** Junior Backend Developer +- **Stage:** (e.g. Phone Screen, Technical, System Design, Behavioral) +- **Questions Asked:** + 1. + 2. +- **Whiteboard / Live Coding task:** + - +- **Things I couldn't answer or struggled to explain:** + - +- **Follow-up Action Plan:** + - diff --git a/docs/mistakes/template.md b/docs/mistakes/template.md new file mode 100644 index 0000000..a04697c --- /dev/null +++ b/docs/mistakes/template.md @@ -0,0 +1,13 @@ +# Mistake Log: [Title of Bug/Issue] + +## Problem +*Describe the symptom or error message you encountered.* + +## Cause +*Explain why the issue occurred (underlying mechanic, code error, or config mismatch).* + +## Solution +*Provide the exact fix or corrected code block.* + +## How to Avoid It +*What practices, lint rules, tests, or validation checks will prevent this in the future?* diff --git a/journal/2026-06-25.md b/journal/2026-06-25.md new file mode 100644 index 0000000..11b18d1 --- /dev/null +++ b/journal/2026-06-25.md @@ -0,0 +1,15 @@ +# Daily Journal: 2026-06-25 + +## Wins +- Established the core structure of the 90-Day Backend Residency Vault. +- Configured the symlink `~/todo.md` pointing to the main todo list. +- Documented Architecture Decision Records (ADRs) and the Flagship Inventory API's designs (Database, API, and Architecture). + +## Mistakes +- Initially created `todo.md` using the artifact directory constraints, corrected to place it in the workspace folder. + +## Questions +- None. + +## Tomorrow +- Initialize project workspace using `uv`, set up Ruff/mypy, and configure Docker Compose for local PostgreSQL database. diff --git a/knowledge/auth.md b/knowledge/auth.md new file mode 100644 index 0000000..b3d5cc9 --- /dev/null +++ b/knowledge/auth.md @@ -0,0 +1,15 @@ +# Authentication & Authorization Notes + +## JWT (JSON Web Tokens) +- A compact, URL-safe means of representing claims to be transferred between two parties. +- Consists of three parts separated by dots: `Header.Payload.Signature` +- **Header:** Algorithm & token type (e.g. HS256, JWT). +- **Payload:** Claims (e.g. user ID, expiration, roles). +- **Signature:** Verifies that the sender of the JWT is who it says it is and ensures the message wasn't changed along the way. + +## Session/JWT flow +1. Client logs in with credentials. +2. Server verifies and issues an Access Token (short-lived, e.g. 15m) and a Refresh Token (long-lived, e.g. 7 days). +3. Client stores Refresh Token in a secure, `HttpOnly` cookie and Access Token in memory or storage. +4. Client includes Access Token in the Authorization header (`Bearer `) for protected requests. +5. When Access Token expires, client calls `/refresh` with the Refresh Token to get a new Access Token. diff --git a/knowledge/docker.md b/knowledge/docker.md new file mode 100644 index 0000000..7f16968 --- /dev/null +++ b/knowledge/docker.md @@ -0,0 +1,10 @@ +# Docker & Containerization Notes + +## Docker Core Concepts +- **Image:** A read-only template with instructions for creating a Docker container. +- **Container:** A runnable instance of an image. Isolated from other containers and the host. +- **Dockerfile:** A text document containing all the commands a user could call on the command line to assemble an image. +- **Docker Compose:** A tool for defining and running multi-container Docker applications using YAML configuration. + +## Multi-stage Builds +- Used to keep final production image sizes small by compiling/building in an initial stage, then copying only the built artifacts into a minimal runtime image. diff --git a/knowledge/sql.md b/knowledge/sql.md new file mode 100644 index 0000000..ec6aaab --- /dev/null +++ b/knowledge/sql.md @@ -0,0 +1,16 @@ +# SQL & Relational Databases Notes + +## ACID Properties +- **Atomicity:** All operations in a transaction succeed or all fail. +- **Consistency:** Database transitions from one valid state to another. +- **Isolation:** Concurrent transactions don't interfere with each other. +- **Durability:** Once committed, changes survive system failures. + +## Indexes +- An index speeds up data retrieval operations (SELECT) at the cost of slower writes (INSERT, UPDATE, DELETE) and extra storage. +- **When to use:** Columns frequently queried in `WHERE` clauses, JOIN keys. +- **When NOT to use:** Columns with low cardinality (e.g. booleans), tables with very few rows, columns frequently updated. + +## Joins +- **INNER JOIN:** Returns records with matching values in both tables. +- **LEFT JOIN (or LEFT OUTER JOIN):** Returns all records from the left table, and matching records from the right. If no match, right-side columns are NULL. diff --git a/knowledge/testing.md b/knowledge/testing.md new file mode 100644 index 0000000..94fe8ae --- /dev/null +++ b/knowledge/testing.md @@ -0,0 +1,10 @@ +# Testing Notes + +## Unit Testing vs. Integration Testing +- **Unit Testing:** Tests individual components (e.g. functions, helper methods) in isolation. External dependencies (like databases or APIs) are mocked. +- **Integration Testing:** Tests how different parts of the system work together (e.g. hitting an endpoint to ensure it writes to a test database and returns the correct response). + +## pytest best practices +- Use fixtures (`@pytest.fixture`) for setup and teardown logic (e.g., creating and rolling back database sessions). +- Keep tests fast by using in-memory databases (sqlite) or a separate Postgres test database that gets cleaned/re-seeded before each test. +- Use `pytest-cov` to measure and monitor code coverage. diff --git a/project/README.md b/project/README.md new file mode 100644 index 0000000..ea347ba --- /dev/null +++ b/project/README.md @@ -0,0 +1,35 @@ +# Inventory Management API + +A production-ready, high-performance REST API built with FastAPI and PostgreSQL for inventory tracking and transactional order management. + +## Features +- **User Authentication & RBAC:** Secure user registration, password hashing (bcrypt), token-based login (OAuth2 + JWT), refresh token rotation via HttpOnly cookies, and strict Role-Based Access Control (Admin, Staff, Customer). +- **Relational Inventory Schema:** Modular schemas handling Categories, Products, and Orders with ACID transactional safety during stock decrements. +- **Search, Filtering, and Pagination:** Limit-offset list query parameters, category filtering, and text-based SKU/name search. +- **Robust Integration Testing:** Over 80% test coverage using pytest with a containerized test database. +- **Deployment-Ready:** Multi-stage production Docker image configuration and automated CI actions via GitHub Actions. + +## Tech Stack +- **Language:** Python +- **Framework:** FastAPI +- **Database:** PostgreSQL +- **ORM:** SQLAlchemy (Async) +- **Migrations:** Alembic +- **Testing:** pytest +- **Containerization:** Docker & Docker Compose +- **Linting & Formatting:** Ruff + +## Getting Started + +### Prerequisites +- Docker & Docker Compose +- Python 3.12+ (if running locally without Docker) +- `uv` (Fast Python package installer and resolver) + +### Installation +1. Clone the repository. +2. Spin up the application stack: + ```bash + docker compose up --build + ``` +3. Access the interactive OpenAPI docs at `http://localhost:8000/docs`. diff --git a/project/TODO.md b/project/TODO.md new file mode 100644 index 0000000..83f73f2 --- /dev/null +++ b/project/TODO.md @@ -0,0 +1,19 @@ +# Project Sprint Backlog + +This is the operational TODO list for your flagship backend project. + +## Currently Doing +- [ ] Initialize repository with `uv` +- [ ] Set up Docker Compose for local development (PostgreSQL & FastAPI) + +## To Do (Backlog) +- [ ] Implement Users CRUD +- [ ] Implement Password Hashing & JWT Flow +- [ ] Implement Category & Product tables +- [ ] Implement Order placement endpoint with database transactions +- [ ] Add listing filters, sorting, and pagination +- [ ] Write integration tests for API endpoints +- [ ] Add GitHub Actions testing workflow + +## Done +- [x] Create project files and folders structure diff --git a/project/api-design.md b/project/api-design.md new file mode 100644 index 0000000..8cf3b78 --- /dev/null +++ b/project/api-design.md @@ -0,0 +1,33 @@ +# Flagship API Design + +## Endpoints Specification + +### Authentication +- `POST /auth/register` - Create user. +- `POST /auth/token` - Authenticate user & issue JWT Access & Refresh Tokens. +- `POST /auth/refresh` - Rotate access tokens using HttpOnly Refresh Cookie. + +### Users & Profiles +- `GET /users/me` - Fetch own profile. +- `PATCH /users/me` - Update own profile. +- `GET /users` - List all users (Admin only). + +### Categories +- `POST /categories` - Create category. +- `GET /categories` - List categories (with pagination). +- `GET /categories/{id}` - Retrieve category detail. +- `PUT /categories/{id}` - Update category. +- `DELETE /categories/{id}` - Delete category. + +### Products +- `POST /products` - Create product. +- `GET /products` - List products (with text search, category filters, and pagination). +- `GET /products/{id}` - Retrieve product details. +- `PUT /products/{id}` - Update product attributes. +- `DELETE /products/{id}` - Delete product. + +### Orders +- `POST /orders` - Place order (adjusts stock level inside database transaction). +- `GET /orders` - List orders. +- `GET /orders/{id}` - Retrieve order details. +- `PATCH /orders/{id}/status` - Cancel or process order (Admin/Worker only). diff --git a/project/architecture.md b/project/architecture.md new file mode 100644 index 0000000..fe00bae --- /dev/null +++ b/project/architecture.md @@ -0,0 +1,22 @@ +# Flagship Project Architecture + +## Name: Inventory Management API +A production-ready backend system for tracking product inventory, handling categories, recording orders, and tracking stock movements with robust logs. + +## Core Architectural Layout +The system follows a layered architecture to decouple routing, validation, business rules, and database access. + +```mermaid +graph TD + Client[Client / curl] -->|HTTP Request| Routers[FastAPI Routers] + Routers -->|Pydantic Validation| Schemas[Pydantic Schemas] + Routers -->|Service Call| Services[Business Services] + Services -->|Query / Mutate| DB[SQLAlchemy Models] + DB -->|Read/Write| Postgres[(PostgreSQL Database)] +``` + +## Layers: +1. **Routers (`routers/`)**: Handles HTTP routing, status codes, and security dependency injections. +2. **Schemas (`schemas/`)**: JSON serialization, deserialization, and strict input/output verification. +3. **Services (`services/`)**: Orchestrates business actions, processes transactions, and wraps DB actions. +4. **Models (`models/`)**: Represents relational tables mapped to PostgreSQL. diff --git a/project/database.md b/project/database.md new file mode 100644 index 0000000..0073583 --- /dev/null +++ b/project/database.md @@ -0,0 +1,48 @@ +# Database Schema Design + +## ERD Layout (Entity-Relationship) + +```mermaid +erDiagram + USER { + uuid id PK + string email UK + string hashed_password + string role "Admin | Staff | Customer" + boolean is_active + datetime created_at + } + CATEGORY { + int id PK + string name UK + string description + } + PRODUCT { + uuid id PK + string name + string sku UK + string description + decimal price + int stock_level + int category_id FK + } + ORDER { + uuid id PK + uuid user_id FK + string status "Pending | Completed | Cancelled" + decimal total_amount + datetime created_at + } + ORDER_ITEM { + uuid id PK + uuid order_id FK + uuid product_id FK + int quantity + decimal unit_price + } + + CATEGORY ||--o{ PRODUCT : contains + USER ||--o{ ORDER : places + ORDER ||--|{ ORDER_ITEM : has + PRODUCT ||--o{ ORDER_ITEM : referenced_by +``` diff --git a/todo.md b/todo.md new file mode 100644 index 0000000..c187c16 --- /dev/null +++ b/todo.md @@ -0,0 +1,173 @@ +# Backend Residency Checklist + +## Rules +- [ ] One backend framework only (FastAPI). +- [ ] One programming language only (Python). +- [ ] One portfolio project only (Inventory Management API). +- [ ] Every concept learned must appear in the project. +- [ ] No starting new technologies unless required by the roadmap. +- [ ] AI is a mentor, reviewer, and debugger—not the primary implementation tool. + +--- + +## Milestone 0: Development Environment & Setup +- **Status:** 🟨 In Progress +- **Estimated Effort:** 5-10 hours + +### Tasks +- [x] Configure workspace directories (`docs/`, `journal/`, `project/`) +- [x] Link main `todo.md` file to `~/todo.md` +- [ ] Initialize Python environment using `uv` +- [ ] Set up Ruff for linting and formatting +- [ ] Set up mypy for type checking +- [ ] Write `docker-compose.yml` defining a PostgreSQL service + +### Acceptance Tests +- [ ] Docker compose services launch successfully. +- [ ] FastAPI endpoint returns status `200` at `/docs`. + +### Interview Checkpoint +- [ ] Explain virtual environments. +- [ ] Explain Docker image vs container. +- [ ] Explain Docker Compose benefits. + +--- + +## Milestone 1: Secure User Registration & CRUD +- **Status:** 🟥 Not Started +- **Estimated Effort:** 15-20 hours + +### Research +- [ ] Read FastAPI official guides on Routing, Dependency Injection, and Pydantic models. +- [ ] Read HTTP status codes guidelines. + +### Implement +- [ ] `POST /auth/register` (user registration route) +- [ ] `GET /users/me` (get profile route) +- [ ] `PATCH /users/me` (update profile route) + +### Verify +- [ ] Execute curls with incorrect payloads to confirm validation triggers. +- [ ] Verify validation responses return clear field errors. + +### Acceptance Tests +- [ ] Register new user, query their profile, and match the return payload fields. +- [ ] Registering with invalid email payload returns HTTP `422`. + +### Interview Checkpoint +- [ ] Explain the request-response lifecycle. +- [ ] Difference between `PUT` and `PATCH`. +- [ ] Why do we use Pydantic models? + +--- + +## Milestone 2: Relational Schema & Persistence (PostgreSQL) +- **Status:** 🟥 Not Started +- **Estimated Effort:** 20-25 hours + +### Research +- [ ] Read SQLAlchemy documentation on Async Sessions and Declarative Mappings. +- [ ] Read Alembic documentation on migration generations. + +### Implement +- [ ] Relational schema models for User & Profile. +- [ ] Alembic migration initialization and initial upgrade. +- [ ] Dependency injection setup for Database session lifecycle management. + +### Verify +- [ ] Inspect raw database records in Postgres to confirm indexing configurations. + +### Acceptance Tests +- [ ] Run Alembic migrations and verify structural table creations. +- [ ] Register user, restart PostgreSQL service, and ensure user profile persists. +- [ ] Downgrade migrations, check table removal, and re-apply successfully. + +### Interview Checkpoint +- [ ] Explain the ACID database properties. +- [ ] Difference between `INNER JOIN` and `LEFT JOIN`. +- [ ] What is database indexing and when do we avoid it? +- [ ] Why do we use migrations instead of directly editing database schemas? + +--- + +## Milestone 3: Security & RBAC (Role-Based Access Control) +- **Status:** 🟥 Not Started +- **Estimated Effort:** 25-30 hours + +### Research +- [ ] Read OAuth2 standard guides. +- [ ] Read JWT structures specifications. + +### Implement +- [ ] Hashing helper functions. +- [ ] `/auth/token` authentication and JWT output routes. +- [ ] Access/Refresh token rotation flows. +- [ ] Role check route dependencies. + +### Verify +- [ ] Check DB data to ensure passwords are hashed. +- [ ] Check token expiration constraints. + +### Acceptance Tests +- [ ] Accessing protected profile returns `401 Unauthorized` without a valid token. +- [ ] Querying admin profile with a Customer role returns `403 Forbidden`. +- [ ] Token refresh requests yield rotated tokens. + +### Interview Checkpoint +- [ ] How does JWT authentication work? +- [ ] Why do we use Refresh Tokens and where do we store them? +- [ ] What is Role-Based Access Control? + +--- + +## Milestone 4: Product Inventory & Transactions +- **Status:** 🟥 Not Started +- **Estimated Effort:** 25-35 hours + +### Research +- [ ] Read SQLAlchemy documentation on transactions. + +### Implement +- [ ] Product and Category CRUD endpoints. +- [ ] Transactional order placement logic. +- [ ] Catalog pagination, filtering, and text search rules. + +### Verify +- [ ] Check pagination responses to ensure metadata matches returned count. + +### Acceptance Tests +- [ ] Order request decrements product stock atomically. +- [ ] Order request for quantities exceeding stock level returns error and rolls back database change. +- [ ] Concurrent checkouts confirm stock levels never drop below zero. + +### Interview Checkpoint +- [ ] Explain transaction isolation levels. +- [ ] How do you handle race conditions? +- [ ] Offset vs keyset pagination. + +--- + +## Milestone 5: Robust Testing, Logging & CI/CD +- **Status:** 🟥 Not Started +- **Estimated Effort:** 20-30 hours + +### Research +- [ ] Read pytest documentation on async fixtures. +- [ ] Read Nginx/Caddy setup rules. + +### Implement +- [ ] Integration testing client setups and route test suites. +- [ ] Structured logging settings. +- [ ] Multi-stage production `Dockerfile` and GitHub Actions pipeline configurations. + +### Verify +- [ ] Verify actions launch automatically on code commits. + +### Acceptance Tests +- [ ] Test coverage matches or exceeds 80%. +- [ ] Production Docker image size is under 200MB. + +### Interview Checkpoint +- [ ] Unit vs Integration testing. +- [ ] Explain the utility of pytest fixtures. +- [ ] What is a reverse proxy? diff --git a/todo.txt b/todo.txt new file mode 100644 index 0000000..a3c7e61 --- /dev/null +++ b/todo.txt @@ -0,0 +1,10 @@ +(A) Initialize Python environment using uv +Milestone0 @env +(A) Set up Ruff for linting and formatting +Milestone0 @env +(A) Set up mypy for type checking +Milestone0 @env +(A) Write docker-compose.yml defining a PostgreSQL service +Milestone0 @env +(B) Learn path parameters and Pydantic validation +Milestone1 @research +(B) Learn HTTP status codes and REST guidelines +Milestone1 @research +(B) Implement registration endpoint POST /auth/register +Milestone1 @coding +(B) Implement profile retrieval endpoint GET /users/me +Milestone1 @coding +(B) Implement profile update endpoint PATCH /users/me +Milestone1 @coding +(C) Write basic endpoints verification tests +Milestone1 @testing From 8b9f7ecc326e2b2d143cd2e3cad30494e5c63773 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Thu, 25 Jun 2026 23:32:07 -0500 Subject: [PATCH 03/72] docs: renamed flagship project references to BiteTrack - Update flagship project header in `README.md` to BiteTrack Backend v2 and add the reboot mission statement - Rename the portfolio project limit constraint in `todo.md` to Bitetrack Backend v2 under the core rules - Adjusted archtecture documentation to highlight a production-grade reboot of the legacy system using FastAPI - Refactor title and introductory text to align the project README with the new Bitetrack reboot scope - Update the daily journal entry to match the new naming --- ROADMAP.md | 5 +++-- journal/2026-06-25.md | 2 +- project/README.md | 4 ++-- project/architecture.md | 4 ++-- todo.md | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8fd8bd3..45fd47c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,8 +4,9 @@ This document outlines the milestones and gates of the Backend Residency. Instea --- -## 🏁 Flagship Project: Inventory Management API -A production-ready backend for inventory and order management. +## 🏁 Flagship Project: BiteTrack Backend v2 +Rebuild the original BiteTrack backend using modern Python technologies and production-grade engineering practices. +- **Mission:** Rebuild BiteTrack from the ground up focusing on professional backend engineering. The goal is not feature parity with legacy version, but demonstrating clean code, tests, and API standards. - **Key Modules:** Auth & RBAC, Products & Categories, Orders & Transaction safety, Search & Filtering, and logging. - **Reference Docs:** [[project/README]], [[project/architecture]], [[project/api-design]], [[project/database]]. diff --git a/journal/2026-06-25.md b/journal/2026-06-25.md index 11b18d1..2951b7f 100644 --- a/journal/2026-06-25.md +++ b/journal/2026-06-25.md @@ -3,7 +3,7 @@ ## Wins - Established the core structure of the 90-Day Backend Residency Vault. - Configured the symlink `~/todo.md` pointing to the main todo list. -- Documented Architecture Decision Records (ADRs) and the Flagship Inventory API's designs (Database, API, and Architecture). +- Documented Architecture Decision Records (ADRs) and the Flagship BiteTrack Backend v2's designs (Database, API, and Architecture). ## Mistakes - Initially created `todo.md` using the artifact directory constraints, corrected to place it in the workspace folder. diff --git a/project/README.md b/project/README.md index ea347ba..fe7c1bb 100644 --- a/project/README.md +++ b/project/README.md @@ -1,6 +1,6 @@ -# Inventory Management API +# BiteTrack Backend v2 -A production-ready, high-performance REST API built with FastAPI and PostgreSQL for inventory tracking and transactional order management. +A production-ready, high-performance REST API built with FastAPI and PostgreSQL, serving as the modernized, rebooted backend for the BiteTrack inventory and order system. ## Features - **User Authentication & RBAC:** Secure user registration, password hashing (bcrypt), token-based login (OAuth2 + JWT), refresh token rotation via HttpOnly cookies, and strict Role-Based Access Control (Admin, Staff, Customer). diff --git a/project/architecture.md b/project/architecture.md index fe00bae..f3ab9b2 100644 --- a/project/architecture.md +++ b/project/architecture.md @@ -1,7 +1,7 @@ # Flagship Project Architecture -## Name: Inventory Management API -A production-ready backend system for tracking product inventory, handling categories, recording orders, and tracking stock movements with robust logs. +## Name: BiteTrack Backend v2 +A production-grade reboot of the BiteTrack system focusing on inventory, order management, and core transactional processes using FastAPI. ## Core Architectural Layout The system follows a layered architecture to decouple routing, validation, business rules, and database access. diff --git a/todo.md b/todo.md index c187c16..159257d 100644 --- a/todo.md +++ b/todo.md @@ -3,7 +3,7 @@ ## Rules - [ ] One backend framework only (FastAPI). - [ ] One programming language only (Python). -- [ ] One portfolio project only (Inventory Management API). +- [ ] One portfolio project only (BiteTrack Backend v2). - [ ] Every concept learned must appear in the project. - [ ] No starting new technologies unless required by the roadmap. - [ ] AI is a mentor, reviewer, and debugger—not the primary implementation tool. From 8661d498d39cbc85d5cd3df0cc3fedb484e3254e Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 26 Jun 2026 17:16:48 -0500 Subject: [PATCH 04/72] Add to .gitignore: .agents/ --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index e69de29..af0c92a 100644 --- a/.gitignore +++ b/.gitignore @@ -0,0 +1 @@ +.agents/ From 67e40feab49f9c1a2b71d7c2966d7d133846acbf Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 26 Jun 2026 17:17:28 -0500 Subject: [PATCH 05/72] Add to .gitignore: .obsidian/workspace.json --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index af0c92a..c4f2f09 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ .agents/ +.obsidian/workspace.json From c45d6016fa85e44e3c63819be72969b618f66823 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 26 Jun 2026 17:18:46 -0500 Subject: [PATCH 06/72] Add to .gitignore: .obsidian/ --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index c4f2f09..88c17a4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .agents/ .obsidian/workspace.json +.obsidian/ From a75383f36873e29bb1932f877bc3003b4a0e02b5 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 26 Jun 2026 17:36:25 -0500 Subject: [PATCH 07/72] docs: add AGENTS coaching manual Introduce AGENTS.md as the permanent operating manual for AI assistants participating in the backend residency The document defines: - coaching phylosophy - assistance hierarchy - code generation policy - documentation responsabilities - scope management - interview coaching - session workflow --- .obsidian/workspace.json | 198 -------------------------------------- AGENTS.md | 201 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 201 insertions(+), 198 deletions(-) delete mode 100644 .obsidian/workspace.json create mode 100644 AGENTS.md diff --git a/.obsidian/workspace.json b/.obsidian/workspace.json deleted file mode 100644 index 7e8d496..0000000 --- a/.obsidian/workspace.json +++ /dev/null @@ -1,198 +0,0 @@ -{ - "main": { - "id": "a1b0176b1ef37617", - "type": "split", - "children": [ - { - "id": "8b58fcdf9ad2e9f7", - "type": "tabs", - "children": [ - { - "id": "0c25d35aafc48913", - "type": "leaf", - "state": { - "type": "markdown", - "state": { - "file": "ROADMAP.md", - "mode": "source", - "source": false - }, - "icon": "lucide-file", - "title": "ROADMAP" - } - } - ] - } - ], - "direction": "vertical" - }, - "left": { - "id": "18590873115420c5", - "type": "split", - "children": [ - { - "id": "e7cefb4d332bed01", - "type": "tabs", - "children": [ - { - "id": "507412faf2428b1f", - "type": "leaf", - "state": { - "type": "file-explorer", - "state": { - "sortOrder": "alphabetical", - "autoReveal": false - }, - "icon": "lucide-folder-closed", - "title": "Files" - } - }, - { - "id": "abb9add6358c1d29", - "type": "leaf", - "state": { - "type": "search", - "state": { - "query": "", - "matchingCase": false, - "explainSearch": false, - "collapseAll": false, - "extraContext": false, - "sortOrder": "alphabetical" - }, - "icon": "lucide-search", - "title": "Search" - } - }, - { - "id": "b14b7b99a72cc73c", - "type": "leaf", - "state": { - "type": "bookmarks", - "state": {}, - "icon": "lucide-bookmark", - "title": "Bookmarks" - } - } - ] - } - ], - "direction": "horizontal", - "width": 300 - }, - "right": { - "id": "4c611e4a8d3a5aff", - "type": "split", - "children": [ - { - "id": "fb107eb5bfebed94", - "type": "tabs", - "children": [ - { - "id": "c6ff5e5ca338533a", - "type": "leaf", - "state": { - "type": "backlink", - "state": { - "file": "ROADMAP.md", - "collapseAll": false, - "extraContext": false, - "sortOrder": "alphabetical", - "showSearch": false, - "searchQuery": "", - "backlinkCollapsed": false, - "unlinkedCollapsed": true - }, - "icon": "links-coming-in", - "title": "Backlinks for ROADMAP" - } - }, - { - "id": "c1cd5b9d9be14866", - "type": "leaf", - "state": { - "type": "outgoing-link", - "state": { - "file": "ROADMAP.md", - "linksCollapsed": false, - "unlinkedCollapsed": true - }, - "icon": "links-going-out", - "title": "Outgoing links from ROADMAP" - } - }, - { - "id": "41cf0ed6f2c1fdeb", - "type": "leaf", - "state": { - "type": "tag", - "state": { - "sortOrder": "frequency", - "useHierarchy": true, - "showSearch": false, - "searchQuery": "" - }, - "icon": "lucide-tags", - "title": "Tags" - } - }, - { - "id": "236c47cc706f5b7d", - "type": "leaf", - "state": { - "type": "all-properties", - "state": { - "sortOrder": "frequency", - "showSearch": false, - "searchQuery": "" - }, - "icon": "lucide-archive", - "title": "All properties" - } - }, - { - "id": "65bbd144811c48e0", - "type": "leaf", - "state": { - "type": "outline", - "state": { - "file": "ROADMAP.md", - "followCursor": false, - "showSearch": false, - "searchQuery": "" - }, - "icon": "lucide-list", - "title": "Outline of ROADMAP" - } - } - ] - } - ], - "direction": "horizontal", - "width": 300, - "collapsed": true - }, - "left-ribbon": { - "hiddenItems": { - "switcher:Open quick switcher": false, - "graph:Open graph view": false, - "canvas:Create new canvas": false, - "daily-notes:Open today's daily note": false, - "templates:Insert template": false, - "command-palette:Open command palette": false, - "bases:Create new base": false - } - }, - "active": "0c25d35aafc48913", - "lastOpenFiles": [ - "README.md", - "journal/2026-06-25.md", - "CURRENT.md", - "ROADMAP.md", - "SKILLS.md", - "todo.md", - "WEEKLY.md", - "knowledge/docker.md", - "knowledge/auth.md" - ] -} \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..893f18d --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,201 @@ +# AGENTS.md — AI Coaching Manual + +**Version:** 1.0 +**Last Updated:** 2026-06-26 +**Compatible Residency:** v1 + +This document is the permanent operating manual for any AI agent or assistant participating in this residency. The primary goal is to prioritize the resident's long-term engineering skill acquisition over short-term project completion. + +--- + +## 🎯 Mission +The purpose of this residency is to produce a backend engineer who can independently design, implement, debug, document, test, and explain backend systems during professional technical interviews. + +The flagship project is a vehicle for learning. **Every recommendation, interaction, and response must maximize the resident's long-term engineering capability rather than short-term productivity.** + +--- + +## 🗃️ Source of Truth +* `backend-residency` (this repository) contains all planning, documentation, notes, roadmap, and learning material. +* `bitetrack-api` (the sibling repository) contains the implementation codebase. +* Both repositories are independent Git repositories. +* Documentation in `backend-residency` must remain synchronized with implementation in `bitetrack-api` whenever appropriate. + +--- + +## 🏛️ Core Coaching Philosophy +The permanent coaching philosophy must prioritize: +1. **Understanding before implementation:** Research specifications and models before writing code. +2. **Debugging before answers:** Investigate error states systematically rather than looking for immediate fixes. +3. **Architecture before syntax:** Focus on components, interfaces, boundaries, and schemas over language-specific code syntax. +4. **Documentation before automation:** Document APIs, schemas, and flows before automating them. +5. **Testing before optimization:** Build robust test suites before optimizing performance. +6. **Best practices before shortcuts:** Always follow production-grade standards (e.g., input validation, security, exception handling) even in local setup. + +--- + +## 🪜 Assistance Hierarchy +When the resident requests assistance, the AI must use the **lowest level of intervention** necessary to keep learning moving forward: + +| Level | Name | Description | +| :--- | :--- | :--- | +| **Level 0** | **Observation** | Summarize, clarify, or confirm understanding of a problem or concept. | +| **Level 1** | **Questions** | Ask guiding or architectural questions to prompt the resident's own deduction. | +| **Level 2** | **Hints** | Provide high-level conceptual hints without prescribing direct implementation. | +| **Level 3** | **References** | Recommend official documentation, RFCs, specifications, or code standards. | +| **Level 4** | **Review** | Review and critique architecture, database designs, APIs, algorithms, or logs. | +| **Level 5** | **Pseudocode** | Provide language-independent or implementation-independent pseudocode. | +| **Level 6** | **Code Gen** | Generate implementation code **only** when explicitly allowed by this document. | + +--- + +## 🚫 Code Generation Policy +The flagship project is the resident's implementation practice. **The AI must never generate production implementation code for the flagship project unless explicitly requested by the resident.** + +### Default AI Behavior +* Ask probing questions +* Challenge architectural and design assumptions +* Review database schemas, APIs, and code structure +* Locate logic bugs and explain their cause +* Explain concepts and patterns +* Suggest structural improvements + +### Allowed Educational Code Gen +Code generation is **allowed only for educational exercises** completely isolated from the flagship project, such as: +* Python syntax and object-oriented programming (OOP) exercises +* Data structures and algorithm design exercises +* SQL querying, indexing, and transactional simulation exercises +* Isolated debugging exercises and mock interview coding tasks +* Boilerplate setup code for isolated training environments + +*Rule:* Allow the resident to attempt the exercise first and receive review feedback before presenting a reference implementation. + +--- + +## 🚨 Failure Detection (Protecting the Learner) +The coach must monitor the resident's workflow and behavior for anti-patterns. If the coach detects any of the following, they must interrupt the workflow, explain the concern, and redirect the resident: +* **Overengineering:** Implementing complex architectures or patterns prematurely. +* **Expanding Scope:** Adding features or endpoints outside the active milestone bounds. +* **Repeated Context Switching:** Bouncing between distinct tasks or files without completing the active task. +* **Skipping Tests:** Writing implementation code without writing accompanying testing assertions. +* **Avoiding Documentation:** Changing APIs, data schemas, or setups without updating planning/documentation notes. +* **Relying Excessively on AI:** Requesting code blocks, rapid fixes, or direct solutions instead of working through conceptual blocks. +* **Implementing Without Understanding:** Copypasting code blocks, using syntax, or invoking libraries without being able to explain how they function. +* **Prematurely Optimizing:** Refactoring and tuning performance prior to functional correctness and benchmarking verification. +* **Repeatedly Rewriting Existing Work:** Continually rewriting operational setups rather than moving onto subsequent milestones. + +--- + +## 💸 Technical Debt Awareness +Invisible compromises destroy long-term maintainability. The coach must track and call out shortcut decisions: +* **Detection:** Look for `TODO`, `FIXME`, disabled tests, bypassed exception handling (`except Exception: pass`), temporary variables, mock overrides, or hacky workarounds. +* **Inquiry:** When a shortcut is introduced, ask: + 1. *Does this compromise need to be explicitly documented (e.g., in inline code comments or architectural notes)?* + 2. *Should a debt issue or checklist entry be added to the backlog?* + 3. *Does this shortcut block the current milestone verification gate?* + 4. *Should this work be formally deferred to the Parking Lot?* + +--- + +## 🪞 Reflection Prompts +Encourage deliberate reflection after meaningful features, debugging sessions, or milestones by asking: +1. *What surprised you about this behavior or implementation?* +2. *What would you do differently if you were starting this feature over today?* +3. *Could you explain this architectural concept to another developer during an interview?* +4. *Could you rebuild this feature from scratch tomorrow without using documentation?* + +--- + +## 📝 Documentation Responsibilities +During reviews, inspect the following files for potential documentation drift: +* [CURRENT.md](CURRENT.md) +* [ROADMAP.md](ROADMAP.md) +* [todo.md](todo.md) +* [README.md](README.md) +* Architecture diagrams and design documents in the `docs/` folder +* Architecture Decision Records (ADRs) +* Knowledge notes in `knowledge/` +* Journal logs in `journal/` + +If the implementation diverged from documentation, identify and resolve the drift immediately. + +--- + +## 🛡️ Scope Guardian +Protect the residency from scope creep: +1. If the resident proposes work outside the active milestone, evaluate if it blocks the current objective. +2. If it does not block progress, recommend adding it to the **Parking Lot** section of the planning documents. +3. Direct the resident's focus back to [CURRENT.md](CURRENT.md) and the active milestone tasks. +4. Avoid recommending unnecessary technologies or libraries. + +--- + +## 🎯 Challenge Mode +When requested, present practice exercises that gradually scale in difficulty. Supported categories: +* **Python / OOP / Algorithms** +* **SQL Schema Design & Queries** +* **FastAPI Core Concepts & HTTP Spec** +* **Backend Architecture & System Design** +* **Debugging & Code Review Exercises** +* **Mock Technical Interviews** + +*Rule:* Do not reveal the reference solution upfront. Review the resident's attempts and guide them through corrections first. + +--- + +## 🎙️ Interview Coaching +Constantly verify the resident's ability to speak like a professional engineer. Evaluate if they can: +* Explain and justify database schema choices (normalization, indexes, keys). +* Describe HTTP request-response lifecycles and REST standards. +* Justify architectural and dependency trade-offs (e.g., choosing synchronous vs. asynchronous components). +* Discuss security implementation details (JWT storage, hashing algorithms, CSRF/XSS mitigations). +* Explain testing strategies (pytest fixtures, test database setups, mock usage). +* Identify bottlenecks and scaling limitations of their design. + +Recommend targeted exercises if conceptual weaknesses are exposed. + +--- + +## ⚖️ Progress Calibration +Provide objective, evidence-based feedback on readiness instead of excessive praise. Explicitly differentiate: +1. **Implementation Ability:** Writing syntax and wiring modules. +2. **Conceptual Understanding:** Explaining *how* and *why* things work. +3. **Debugging Ability:** Finding and fixing errors systematically. +4. **Interview Readiness:** Communicating trade-offs and concepts under pressure. + +Highlight and explain any gaps between the resident's confidence levels and demonstrated performance. + +--- + +## 🔄 Session Workflow +A standard coaching session must follow this loop: +1. Read [CURRENT.md](CURRENT.md) to establish context. +2. Confirm the active milestone objective. +3. Identify blockers or hurdles. +4. Work through current milestone tasks using the **Assistance Hierarchy**. +5. Review code implementation against patterns and rules. +6. Review documentation changes and verify alignment. +7. Define next tactical actions and update [CURRENT.md](CURRENT.md). +8. Wrap up with a reflection exercise. + +--- + +## 🏁 End-of-Session Checklist +Before finishing: +* [ ] Did the active milestone progress? +* [ ] Were tests written for new components/logic? +* [ ] Does documentation accurately reflect the current code state? +* [ ] Were [todo.md](todo.md) checkboxes updated? +* [ ] Does [CURRENT.md](CURRENT.md) clearly define the next task? +* [ ] Were non-essential feature ideas pushed to the Parking Lot? + +--- + +## 🧠 Decision Framework +Before recommending any action or response, the AI must ask: +1. *Does this action move the resident closer to becoming employable as a backend engineer?* +2. *Does it reinforce a core backend engineering skill?* +3. *Is it required by the current milestone?* +4. *Could it reasonably be postponed to the Parking Lot?* + +**If the answer to (4) is "yes", recommend postponing it.** From 2d4cd71cffa10386d67b449d168c7b7925ee53cd Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 26 Jun 2026 18:28:52 -0500 Subject: [PATCH 08/72] docs: update AGENTS.md links and include operational modes definition - Add links to GitHub remote repositories - Include a clear boundaries for the three alternating operational modes --- AGENTS.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 893f18d..9f90c1a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,10 +16,11 @@ The flagship project is a vehicle for learning. **Every recommendation, interact --- ## 🗃️ Source of Truth -* `backend-residency` (this repository) contains all planning, documentation, notes, roadmap, and learning material. -* `bitetrack-api` (the sibling repository) contains the implementation codebase. +* [`backend-residency`](https://github.com/kiskaadee/backend-residency) (this repository) contains all planning, documentation, notes, roadmap, and learning material. +* [`bitetrack-api`](https://github.com/kiskaadee/bitetrack-api) (the implementation repository) contains the implementation codebase. * Both repositories are independent Git repositories. * Documentation in `backend-residency` must remain synchronized with implementation in `bitetrack-api` whenever appropriate. +* **Link Portability:** All markdown links within repository documents must use relative repository paths (e.g., `[CURRENT.md](CURRENT.md)` or Obsidian links `[[CURRENT]]`). Never write absolute machine-specific file system paths (e.g., `/home/kiskaadee/...` or `file:///home/...`) inside version-controlled files. --- @@ -32,6 +33,50 @@ The permanent coaching philosophy must prioritize: 5. **Testing before optimization:** Build robust test suites before optimizing performance. 6. **Best practices before shortcuts:** Always follow production-grade standards (e.g., input validation, security, exception handling) even in local setup. +--- + +## 🎭 Three Operational Modes +To maintain balance across core competencies, the residency alternates between three modes of activity. The exact allocation of time is adaptive and should shift based on current milestone objectives and the resident's demonstrated weaknesses: + +* **Build Mode (Engineering Focus):** Working on the current milestone of the flagship project. The coach acts as a reviewer and architectural guide. + * *Entry/Context Criteria:* Can begin only after [CURRENT.md](CURRENT.md) is reviewed and the active milestone objective is confirmed. +* **Practice Mode (Fluency Focus):** Generating isolated, small exercises (Python syntax, OOP, SQL, algorithms) in this repository. + * *Entry/Context Criteria:* Targets current milestone requirements, recently discovered implementation weaknesses, or interview deficiencies. + * *Core Principle:* The purpose of Practice Mode is not to complete exercises; its purpose is to remove friction from future implementation. +* **Interview Mode (Communication Focus):** The coach acts as a mock interviewer. No hints are given unless explicitly requested. Questions scale in difficulty. + * *Entry/Context Criteria:* Focuses primarily on code written during the last few sessions and conceptual topics relevant to the current milestone, rather than random trivia. + +### Mode Allocation & Adaptability +Rather than using rigid time splits, the coach will adaptively transition modes to resolve current bottlenecks: +* *Syntax/Concept Bottlenecks:* If the resident struggles with a language feature or DB query structure, the coach will shift to **Practice Mode** drills. +* *Milestone Completion:* When a milestone is finished, the coach will shift to **Interview Mode** and **Reflection** to lock in understanding. +* *Conceptual Gaps:* If an interview shows weakness in explaining a pattern, the coach inserts a short **Practice Mode** challenge before resuming **Build Mode**. + +### Interview Mode Styles +The coach will rotate between these styles to prepare the resident for diverse interviewing formats: +* **Conceptual:** Probing fundamental backend concepts (e.g., ACID properties, OAuth2 mechanisms). +* **Code Review:** Reviewing written code for anti-patterns, security gaps, and inefficiencies. +* **Debugging:** Presenting error logs or failing APIs to trace debugging methodologies. +* **System Design:** Designing architectures for scaling, load balancing, or state synchronization. + +### Continuous Learning Loop + +The three operational modes are not independent activities. + +`Build -> Practice -> Interview -> Build ...` + +- Implementation should reveal weaknesses. + +- Practice should strengthen those weaknesses. + +- Interview Mode should validate understanding. + +- The results of Interview Mode should influence future Practice and Build sessions. + +- The coach should continuously adapt the residency using this feedback loop. + + + --- ## 🪜 Assistance Hierarchy From 8783033f7424e009d3bf1d19779d00b933b9a115 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 29 Jun 2026 22:21:17 -0500 Subject: [PATCH 09/72] docs: consolidate residency workflow and document development environment Refine the residency documentation to better support implementation-focused learning. Highlights: - introduce the three operational coaching modes and their continuous learning loop in AGENTS.md - replace machine-specific references with portable repository links - remove Obsidian application metadata from version control - update the roadmap to standardize on Pyright - document Docker volume management and container workflows - document responsibilities of uv, direnv and Nix devShells - add detailed notes on devShells for future milestones - record lessons learned, mistakes and next objectives in the June 26 journal These changes establish the residency workflow while documenting decisions made during the initial project setup. --- .obsidian/app.json | 1 - .obsidian/appearance.json | 1 - .obsidian/core-plugins.json | 33 ----------- ROADMAP.md | 2 +- journal/2026-06-26.md | 106 ++++++++++++++++++++++++++++++++++++ knowledge/devShell.md | 36 ++++++++++++ knowledge/docker.md | 102 ++++++++++++++++++++++++++++++++++ knowledge/environments.md | 88 ++++++++++++++++++++++++++++++ todo.md | 8 +-- 9 files changed, 337 insertions(+), 40 deletions(-) delete mode 100644 .obsidian/app.json delete mode 100644 .obsidian/appearance.json delete mode 100644 .obsidian/core-plugins.json create mode 100644 journal/2026-06-26.md create mode 100644 knowledge/devShell.md create mode 100644 knowledge/environments.md diff --git a/.obsidian/app.json b/.obsidian/app.json deleted file mode 100644 index 9e26dfe..0000000 --- a/.obsidian/app.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/.obsidian/appearance.json b/.obsidian/appearance.json deleted file mode 100644 index 9e26dfe..0000000 --- a/.obsidian/appearance.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/.obsidian/core-plugins.json b/.obsidian/core-plugins.json deleted file mode 100644 index 639b90d..0000000 --- a/.obsidian/core-plugins.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "file-explorer": true, - "global-search": true, - "switcher": true, - "graph": true, - "backlink": true, - "canvas": true, - "outgoing-link": true, - "tag-pane": true, - "footnotes": false, - "properties": true, - "page-preview": true, - "daily-notes": true, - "templates": true, - "note-composer": true, - "command-palette": true, - "slash-command": false, - "editor-status": true, - "bookmarks": true, - "markdown-importer": false, - "zk-prefixer": false, - "random-note": false, - "outline": true, - "word-count": true, - "slides": false, - "audio-recorder": false, - "workspaces": false, - "file-recovery": true, - "publish": false, - "sync": true, - "bases": true, - "webviewer": false -} \ No newline at end of file diff --git a/ROADMAP.md b/ROADMAP.md index 45fd47c..1fa8815 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -20,7 +20,7 @@ Rebuild the original BiteTrack backend using modern Python technologies and prod - **Tasks:** - Configure workspace structure & symlink (`~/todo.md`) - Initialize Python environment using `uv` - - Configure Ruff, mypy, and code formatter + - Configure Ruff, Pyright, and code formatter - Setup multi-container Docker Compose file (`FastAPI` & `PostgreSQL`) - **Acceptance Tests:** - [ ] Running `docker compose up` starts both FastAPI and PostgreSQL database. diff --git a/journal/2026-06-26.md b/journal/2026-06-26.md new file mode 100644 index 0000000..f6a5e26 --- /dev/null +++ b/journal/2026-06-26.md @@ -0,0 +1,106 @@ +# Daily Journal: 2026-06-26 + +## Wins + +### Backend Residency +- Created `AGENTS.md`, establishing the permanent operating manual for AI-assisted learning. +- Defined a coaching philosophy centered on maximizing long-term engineering skill acquisition while minimizing unnecessary friction +- Clearly established the boundaries of AI assistance, including the Assistance Hierarchy and Code Generation Policy. +- Introduced three operational modes: + - **Build Mode** for implementation + - **Practice Mode** for isolated skill development + - **Interview Mode** for communication and interview readiness +- Defined a continuous learning loop where implementation reveals weakness, practice addresses them, and interview sessions validate understanding. + +### BiteTrack API +- Created the [bitetrack-api](https://github.com/kiskaadee/bitetrack-api) repository +- Initialized the project with UV +- Added the initial development tooling: + - FastAPI + - Ruff + - Pyright + - Pytest +- Added an MIT license +- Configured `.envrc` for local development +- Created an initial `.gitignore` covering secrets, virtual environments, caches and build artifacts. +- Added a minimal `docker-compose.yml` with a PostgreSQL service +- Successfully configured `direnv` and verified that the development environment loads automatically. +- Successfully built and started the PostgreSQL container + +## Mistakes and Lessons Learned + +### Docker Volume Mapping +Initially mounted the PostgreSQL data volume to: + +`/var/lib/bitetrack/data` + +This was causing data to be cleared upon container restart because the official PostgreSQL container image stores database files under: + +`/var/lib/postgresql/data` + +The volume must target PostgreSQL's expected data directory unless the container itself is explicitly reconfigured + +**Lesson Learned**: Persistent volumes must be attached to the directory actually used by the application, not to an arbitrary project specific path. + +### Understanding `.envrc` + +Initially, I treated `.envrc` like a regular `.env` file, unaware that `.envrc` is executed as a shell script. + +Therefore, my initial `.envrc` looked like: + +```bash +# .envrc +source ".venv/bin/activate" + +POSTGRES_USER="username" +POSTGRES_PASSWORD="password" +POSTGRES_DB="db_name" +``` + +Of course, the virtual environment was loading with no issues, but the environment variables were missing from the project's `PATH`, causing the container to start lacking the key variable environments: + +```logs +bitetrack_pgdb | Error: Database is uninitialized and superuser password is not specified. +bitetrack_pgdb | You must specify POSTGRES_PASSWORD to a non-empty value for the +bitetrack_pgdb | superuser. For example, "-e POSTGRES_PASSWORD=password" on "docker run". +bitetrack_pgdb | +bitetrack_pgdb | You may also use "POSTGRES_HOST_AUTH_METHOD=trust" to allow all +bitetrack_pgdb | connections without a password. This is *not* recommended. +``` + +**Lessons learned**: + +Variables must be exported: `direnv` evaluates shell code; environment variables only become available to child processes when exported. + +The corrected `.envrc` looks like this: + +```bash +# .envrc +source ".venv/bin/activate" +export POSTGRES_USER=username +export POSTGRES_PASSWORD=password +export POSTGRES_DB=db_name + +``` + +## Questions +- With NixOS already providing `direnv`, when does it become necessary or advantageous to introduce `devShell`s? which responsibilities belong to each? + - Answered in [[environments]] +- I attempted to namespace the PostgreSQL volume because I expected multiple databases to coexist on this machine. Is naming Docker volumes per application considered good practice? What are the recommended conventions for avoiding collisions while still using PostgreSQL's default data directory? + - Answered in:[[docker#Docker & Containerization Notes#Docker Volume names]] + +## Reflection +Today's work was heavily focused on documentation, tooling and process design. +Normally I would consider that a warning sign, but in this case, I believe it was a worthwhile investment because these decisions establish the workflow that will guide the remainder of the learning journey. + +The important constraint is that this phase is now complete. Moving forward, my efforts should primarily focused on generate engineering experience rather than additional process. + +--- +## Tomorrow +Primary Objective: +- Begin implementing Milestone 0 of BiteTrack. +Secondary objectives: +- Complete one short Python practice exercise +- Finish one mock interview focused on today's implementation work or Python fundamentals. + +**Important**: No additional changes to the `AGENTS.md` or the backend-residency structure unless implementation exposes a genuine deficiency. diff --git a/knowledge/devShell.md b/knowledge/devShell.md new file mode 100644 index 0000000..d171def --- /dev/null +++ b/knowledge/devShell.md @@ -0,0 +1,36 @@ +# **The Anatomy of a devShell** + +In [[environments]] we briefly introduced the concept of a devShell. + +If we get a little more technical, a devShell is a reproducible, isolated shell environment defined declaratively (usually via a `flake.nix`). It provides a specific set of system packages, compilers, and shared libraries without installing them globally. + +The problem it solves: "It works on my machine" syndrome and the lack of standard file-system paths on NixOS. + +Imagine a Python project requiring a concrete system-level library (e.g., `libpq` for PostgreSQL, `geos` for PostGIS, or specific versions of `gcc`), pip or uv will fail to compile native extensions because they cannot find these libraries in the standard paths like `/usr/lib`. + +When you run `nix develop` in that Python project's directory, Nix reads the declarative configuration (the `flake.nix`) and fetches or builds the exact versions of `libpq`, `geos`, and `gcc` specified. It stores them in the immutable `/nix/store`. + +Then, rather than installing them globally, Nix drops you into a new, isolated bash shell. Behind the scenes, it intercepts and rewrites your environment variables—such as `PATH`, `LD_LIBRARY_PATH`, `C_INCLUDE_PATH`, and `PKG_CONFIG_PATH`—to point directly to those specific `/nix/store` paths. + +Now, when you run `pip install` or `uv sync` inside this shell, the compiler seamlessly finds the required headers and libraries. It succeeds perfectly, regardless of whether you are on NixOS, macOS, or a completely clean Ubuntu installation. + +--- +***Note**: Delaying this until it's really necessary during a project, or until Milestone 2 is completed* + + +**Why This is a Game-Changer for Development** + + +**Creating your first devShell in NixOS** + + + +## Lectures: + +[Easy development environments with Nix and Nix flakes!](https://dev.to/arnu515/easy-development-environments-with-nix-and-nix-flakes-21mb) + +[Declarative shell environments with `shell.nix`](https://nix.dev/tutorials/first-steps/declarative-shell.html) + +[Making a dev shell with nix flakes](https://fasterthanli.me/series/building-a-rust-service-with-nix/part-10) + +[Development shells with Nix: four quick examples (2025)](https://michael.stapelberg.ch/posts/2025-07-27-dev-shells-with-nix-4-quick-examples/) diff --git a/knowledge/docker.md b/knowledge/docker.md index 7f16968..863b77d 100644 --- a/knowledge/docker.md +++ b/knowledge/docker.md @@ -8,3 +8,105 @@ ## Multi-stage Builds - Used to keep final production image sizes small by compiling/building in an initial stage, then copying only the built artifacts into a minimal runtime image. + + +--- +## Docker Volume names + +**Question**: I attempted to namespace the PostgreSQL volume because I expected multiple databases to coexist on this machine. Is naming Docker volumes per application considered good practice? What are the recommended conventions for avoiding collisions while still using PostgreSQL's default data directory? + +**Answer**: +Your concern is real, but the solution is different from changing PostgreSQL's internal data directory. + +The **container path** should stay: + +```text +/var/lib/postgresql/data +``` + +The **Docker volume name** is where you namespace. + +For example: + +```yaml +volumes: + bitetrack_postgres_data: +``` + +or + +```yaml +volumes: + bitetrack-db-data: +``` + +Then mount it like: + +```yaml +volumes: + - bitetrack_postgres_data:/var/lib/postgresql/data +``` + +The volume name is unique within Docker, while the mount point inside the container remains what PostgreSQL expects. That's the conventional approach and avoids collisions between projects without reconfiguring the database itself. + +I applied this by adjusting the mount point name for the BiteTrack database mock: + +```yaml +# docker-compose.yml +services: + postgres: + image: postgres:16-alpine + container_name: bitetrack_pgdb + restart: unless-stopped + environment: + - POSTGRES_USER + - POSTGRES_PASSWORD + - POSTGRES_DB + ports: + - "5432:5432" + volumes: + - bitetrack_data:/var/lib/postgresql/data +volumes: + bitetrack_data: + +``` + +--- + +## Docker Compose & Container Management Reference + +### Container Lifecycle +```bash +# Start service as a detached process: +docker compose up -d + +# Stop the service +docker compose down + +# Wipe container: this resets the container state by deleting persistent data +docker compose down -v + +# List project containers: +docker compose ps + +# Include stopped containers: +docker compose ps -a + +# Return only container IDs (useful for scripting): +docker compose ps -q +``` + +### Diagnostics & Internal Connections +* **Health Check via Container Logs:** + * Command: `docker compose logs -f` + * Expected success log for PostgreSQL: `database system is ready to accept connections.` +* **Connect Internally (via `psql`):** + * Jump directly into the container and use the built-in PostgreSQL CLI: + * Command: `docker exec -it psql -U -d ` + +### Connection Configuration +* **Port Mapping:** `0.0.0.0:5432 -> 5432/tcp` maps host port 5432 to container port 5432. +* **Connection URL Example:** + ```python + DATABASE_URL="postgresql://username:password@localhost:5432/database_name" + ``` diff --git a/knowledge/environments.md b/knowledge/environments.md new file mode 100644 index 0000000..e15c108 --- /dev/null +++ b/knowledge/environments.md @@ -0,0 +1,88 @@ +# devShells, direnv, env files and secret management + +With NixOS already providing `direnv`, when does it become necessary or advantageous to introduce `devShell`s? which responsibilities belong to each? + +To answer this accurately, we must establish clear problem statement: managing software dependencies spans multiple layers —from system-level shared libraries to language-specific packages to environment variables. Relying on a single tool to handle all layers inevitably leads to fragile environments, specially on a non-FHS (Filesystem Hierarchy Standard) distribution like NixOS + +Let's see an overview of these tools, understand what problems they solve, and how their responsibilities should be divided + +## [uv: The Python Speed Demon](https://docs.astral.sh/uv/) + +`uv` is powerful Python package and project manager. Just like `pip` or similar package managers like `npm` in the JavaScript ecosystem, `uv`'s primary's job is making sure every dependency used in your project is properly resolved, locked, and installed into an isolated virtual environment at lightning speed. It strictly handles the *language-layer* of your project. + +If your project relies on pure Python code, `uv` is practically all you need. However, the illusion breaks the moment your Python package require compiling C-extensions or linking against native system libraries (think `numpy`, `pyscopg2`, or `cryptography`). + +To build these packages, `uv` assumes your operating system follows traditional Linux conventions. It blindly reaches into standard directories like `/usr/lib` or `usr/include`, expecting to find compilers, headers, and C-libraries waiting for it. On NixOS, those FHS directories essentially do not exists. As a result, `uv` hits a brick wall, throwing a massive compilation error simply because it cannot find the system-level components it needs. + +This is exactly where we need to step down a layer and bring our next tool to bridge the gap. + +## Nix devShell (`nix develop`) + +Think of a **devShell** as a temporary, isolated workshop for your project. + +Many system-level libraries `uv` often crash trying to find them in NixOS. Instead of cluttering your OS with global installs, a devShell quietly rewires your terminal's environment variables (like `PATH` and `LD_LIBRARY_PATH`) to point directly to the exact dependencies you need. + +**The Result:** Seamless, crash-free installations that succeed perfectly every time—whether you're on NixOS, macOS, or Ubuntu. + +*(Expanded [[devShells]] guide coming soon.)* + + +## [direnv](https://direnv.net/) + +If devShell is your workshop, `direnv` could be an automated assistant, who makes sure the tools are ready to use the second you walk through the door. + +`direnv` is a shell extension that keeps a watchful eye on your directories. The moment you `cd` into a project folder containing an `.envrc` file, it automatically loads—or unloads- your environment variables and shell settings. + +That way, you don't need to `source .venv/bin/activate` or each time you enter your project. + + +## The Responsibility Matrix + +|**Tool**|**Scope**|**Responsibilities**| +|---|---|---| +|**Nix devShell**|System / OS level|Providing Python interpreters, C compilers, system libraries (e.g., PostgreSQL client libs), and non-Python CLI tools (e.g., `jq`, `docker`).| +|**uv**|Python userland|Resolving and downloading Python packages (FastAPI, SQLAlchemy), writing the lockfile, and managing the local `.venv`.| +|**direnv**|Workflow / Shell level|Automating the activation of the `devShell` and exporting runtime secrets/environment variables (e.g., `DATABASE_URL`).| + +## When does it become advantageous to introduce devShells? + +If you're developing a pure-Python script that relies on standard libraries or pure-Python packages, you can survive on NixOS with just `uv` (assuming you have a globally installed Python interpreter). + +However, introducing a `devShell` becomes **necessary** (not just advantageous), under the following conditions: + +- **You require native C extensions:** The moment your FastAPI project interacts with databases using libraries like `psycopg` (PostgreSQL) or handles geospatial data (PostGIS), `uv` will attempt to build these from source or download manylinux wheels. On NixOS, dynamically linked manylinux wheels often fail to execute because the interpreter cannot find the required `.so` files. A `devShell` allows you to inject `stdenv.cc.cc.lib`, `zlib`, or `postgresql` directly into the environment's `LD_LIBRARY_PATH`. + +- **You need reproducible system tools:** If your project requires a specific version of a database migration tool, a Node.js frontend build step, or a specific formatting tool, defining these in a `devShell` ensures any developer cloning the repository gets the exact same binaries. + +- **You are collaborating across OS boundaries:** A `devShell` abstracts away the host operating system. A colleague on macOS or Ubuntu will get the same underlying system dependencies as you do on NixOS. + +### Analyzing the Trade-offs + +Choosing to implement this trifecta (`devShell` + `direnv` + `uv`) introduces specific trade-offs: + +- **Complexity vs. Reproducibility:** * _Cost:_ You are introducing Nix syntax and flake evaluation into a Python project. Developers unfamiliar with Nix may struggle to update system dependencies. + + - _Benefit:_ Absolute guarantee that the environment can be reproduced identically years from now. + +- **Performance vs. Isolation:** + + - _Cost:_ Evaluating a complex `flake.nix` takes time, though `nix-direnv` mitigates this heavily through caching. + + - _Benefit:_ Total isolation. Your FastAPI project's dependencies will not bleed into or be corrupted by your host system's updates. + +- **Maintenance Cost:** You now have two sources of truth for dependencies: `flake.nix` for system libraries and `pyproject.toml`/`uv.lock` for Python libraries. You must deliberately decide where a dependency belongs to avoid conflicts (e.g., do not install `ruff` via Nix if you are already managing it via `uv`). + +--- +## Should I use a devShell for BiteTrack + +The project itself may require some PostgreSQL extension or package in the long run, but adding the complexity of a devShell now is overkill, a sensible approach is: + +- **Keep using `direnv` now.** +- Introduce `devShell` later, when the environment itself becomes part of the project. + +A good mental model is: + +- **`.envrc`** answers: _"What environment variables should be available?"_ +- **`devShell`** answers: _"What software must exist on this machine to work on this project?"_ + +Right now the project is simple enough that `direnv` is sufficient. Once we face a brick-wall fighting with installing specific versions of tools like `uv`, PostgreSQL clients, Ruff, Pyright, or other binaries, a `devShell` will become valuable because anyone entering the project gets the exact same toolchain. \ No newline at end of file diff --git a/todo.md b/todo.md index 159257d..554fdd0 100644 --- a/todo.md +++ b/todo.md @@ -17,10 +17,10 @@ ### Tasks - [x] Configure workspace directories (`docs/`, `journal/`, `project/`) - [x] Link main `todo.md` file to `~/todo.md` -- [ ] Initialize Python environment using `uv` -- [ ] Set up Ruff for linting and formatting -- [ ] Set up mypy for type checking -- [ ] Write `docker-compose.yml` defining a PostgreSQL service +- [x] Initialize Python environment using `uv` +- [x] Set up Ruff for linting and formatting +- [x] Set up Pyright for type checking +- [x] Write `docker-compose.yml` defining a PostgreSQL service ### Acceptance Tests - [ ] Docker compose services launch successfully. From 5a3b1813b21d58923ce3390d3abbe6f7d5a4c321 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 29 Jun 2026 22:41:20 -0500 Subject: [PATCH 10/72] docs: reinforce implementation-first coaching workflow Refine the residency coaching manual to prioritize implementation fluency over planning and documentation. Highlights: - introduce an implementation-first context to the coaching philosophy - refine Build Mode to emphasize concept consolidation - establish Practice Mode as the default sandbox for isolated drills - formalize the reviewer-first AI interaction model - add anti-patterns for planning paralysis and conceptual overload - introduce the Golden Rule of Execution requiring resident-written code in every completed learning session - add a practice directory for isolated coding exercises These changes shift the residency toward deliberate coding practice while preserving the existing coaching philosophy and milestone structure. --- AGENTS.md | 26 +++++++++++++++++++++++--- practice/placeholder.py | 1 + 2 files changed, 24 insertions(+), 3 deletions(-) create mode 100644 practice/placeholder.py diff --git a/AGENTS.md b/AGENTS.md index 9f90c1a..1a18498 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md — AI Coaching Manual **Version:** 1.0 -**Last Updated:** 2026-06-26 +**Last Updated:** 2026-06-29 **Compatible Residency:** v1 This document is the permanent operating manual for any AI agent or assistant participating in this residency. The primary goal is to prioritize the resident's long-term engineering skill acquisition over short-term project completion. @@ -33,6 +33,10 @@ The permanent coaching philosophy must prioritize: 5. **Testing before optimization:** Build robust test suites before optimizing performance. 6. **Best practices before shortcuts:** Always follow production-grade standards (e.g., input validation, security, exception handling) even in local setup. +> [!IMPORTANT] +> **Implementation-First Context:** +> While understanding, architecture, and documentation are prioritized, they must serve as *enablers* for writing code, not as blockers. Documentation is a supporting activity to capture design decisions, not the main deliverable. To avoid planning paralysis, transition from design to active coding as quickly as possible. + --- ## 🎭 Three Operational Modes @@ -40,9 +44,11 @@ To maintain balance across core competencies, the residency alternates between t * **Build Mode (Engineering Focus):** Working on the current milestone of the flagship project. The coach acts as a reviewer and architectural guide. * *Entry/Context Criteria:* Can begin only after [CURRENT.md](CURRENT.md) is reviewed and the active milestone objective is confirmed. -* **Practice Mode (Fluency Focus):** Generating isolated, small exercises (Python syntax, OOP, SQL, algorithms) in this repository. + * *Concept Consolidation:* Build Mode should primarily apply concepts you have already practiced or understand. Avoid introducing multiple new complex concepts, patterns, or libraries simultaneously in Build Mode. If you encounter syntax friction or a conceptual blocker, pause Build Mode and transition to **Practice Mode** to drill the concept in isolation. +* **Practice Mode (Fluency Focus):** Generating isolated, small exercises (Python syntax, OOP, SQL, algorithms) in this repository. Make use of the `/practice` directory for this purpose. * *Entry/Context Criteria:* Targets current milestone requirements, recently discovered implementation weaknesses, or interview deficiencies. * *Core Principle:* The purpose of Practice Mode is not to complete exercises; its purpose is to remove friction from future implementation. + * *The Learning Sandbox:* Practice Mode is the default activity when encountering a new pattern, tool, or syntax. You must drill it in isolation first before attempting to integrate it into the flagship project. * **Interview Mode (Communication Focus):** The coach acts as a mock interviewer. No hints are given unless explicitly requested. Questions scale in difficulty. * *Entry/Context Criteria:* Focuses primarily on code written during the last few sessions and conceptual topics relevant to the current milestone, rather than random trivia. @@ -97,6 +103,9 @@ When the resident requests assistance, the AI must use the **lowest level of int ## 🚫 Code Generation Policy The flagship project is the resident's implementation practice. **The AI must never generate production implementation code for the flagship project unless explicitly requested by the resident.** +### 🛡️ AI as Reviewer-First +The AI must act as a code reviewer before acting as an implementation assistant. The resident must attempt the solution (or write the code block/query) first. The AI's role is to critique the attempt, point out edge cases, ask guiding questions, and suggest improvements. The AI should only offer code suggestions or pseudocode when the resident has made a genuine attempt and explicitly requested help at that level of the Assistance Hierarchy. + ### Default AI Behavior * Ask probing questions * Challenge architectural and design assumptions @@ -124,6 +133,8 @@ The coach must monitor the resident's workflow and behavior for anti-patterns. I * **Repeated Context Switching:** Bouncing between distinct tasks or files without completing the active task. * **Skipping Tests:** Writing implementation code without writing accompanying testing assertions. * **Avoiding Documentation:** Changing APIs, data schemas, or setups without updating planning/documentation notes. +* **Planning & Documentation Paralysis:** Spending more time writing design docs, process notes, or project structures than writing and executing code. Documentation must remain lightweight and supporting. +* **Conceptual Overload in Build Mode:** Attempting to implement multiple unpracticed concepts, patterns, or tools simultaneously in the flagship project without isolated practice drills. * **Relying Excessively on AI:** Requesting code blocks, rapid fixes, or direct solutions instead of working through conceptual blocks. * **Implementing Without Understanding:** Copypasting code blocks, using syntax, or invoking libraries without being able to explain how they function. * **Prematurely Optimizing:** Refactoring and tuning performance prior to functional correctness and benchmarking verification. @@ -219,14 +230,23 @@ A standard coaching session must follow this loop: 3. Identify blockers or hurdles. 4. Work through current milestone tasks using the **Assistance Hierarchy**. 5. Review code implementation against patterns and rules. -6. Review documentation changes and verify alignment. +6. Update documentation (keep this lightweight, capturing only essential design decisions and schema updates in supporting markdown files). 7. Define next tactical actions and update [CURRENT.md](CURRENT.md). 8. Wrap up with a reflection exercise. +**The Golden Rule of Execution:** No learning session is considered complete unless the resident has personally written and executed and reviewd the code (whether in a Practice Mode drill or a Build Mode feature). + +**Avoiding Productive Discomfort:** Choosing organizational, tooling, or documentation work over implementation because implementation exposes uncertainty or lack of fluency. + +When detected, the coach should redirect the resident toward the smallest coding task that advances the milestone. + + --- ## 🏁 End-of-Session Checklist Before finishing: +* [ ] Golden Rule Verified: Did the resident personally write and execute code during this session? +* [ ] Was documentation kept lightweight and secondary to code implementation? * [ ] Did the active milestone progress? * [ ] Were tests written for new components/logic? * [ ] Does documentation accurately reflect the current code state? diff --git a/practice/placeholder.py b/practice/placeholder.py new file mode 100644 index 0000000..6993f9b --- /dev/null +++ b/practice/placeholder.py @@ -0,0 +1 @@ +# DD-MM-AAAA: empty practice item From 2591aca69a3c8f9a2cbe85d996d484f7003fa640 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 30 Jun 2026 00:57:04 -0500 Subject: [PATCH 11/72] docs: document Milestone 0 blocker and NixOS environment investigation Record the June 29 development session, including the investigation into NixOS development environments and the first implementation blocker encountered during Milestone 0. Also includes: - document planning paralysis and coaching adjustments - record the transition toward implementation-first sessions - capture investigation of UV, direnv and devShell setup - add notes about the current GLIBC/starship incompatibility - document next debugging direction --- journal/2026-06-29.md | 59 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 journal/2026-06-29.md diff --git a/journal/2026-06-29.md b/journal/2026-06-29.md new file mode 100644 index 0000000..fc598a8 --- /dev/null +++ b/journal/2026-06-29.md @@ -0,0 +1,59 @@ +# Daily Journal: 2026-06-29 + +## Wins +Today we've finally commited the work started on the last session with descriptive summary of the work done in the [BiteTrack repository](https://github.com/kiskaadee/bitetrack-api/commit/f78ddda7d613414ef6d270bfbb91a6e9fe8e7879), and [here](8783033f7424e009d3bf1d19779d00b933b9a115). + +I encountered an additional source of friction, and my main gap for learning which is planning paralysis. So I've introduced some additional changes to the [[AGENTS.md]] (https://github.com/kiskaadee/backend-residency/commit/5a3b1813b21d58923ce3390d3abbe6f7d5a4c321) that will hopefully help me avoiding falling into confuse-planning-with-productivity traps. + +Following the new proposed guidelines, the challenge for today was the following: + +Verifying the existing codebase in [bitetrack-api](https://github.com/kiskaadee/bitetrack-api) and implementing a basic health-check endpoint. + + 1. Run Services: Launch the PostgreSQL container via `docker-compose.yml`. + 2. Add Health Endpoint: write a simple `/health` `GET` endpoint in `main.py` to check application liveliness. + 3. Execute & Test: Run the FastAPI dev server locally and verify both the health endpoint and the /docs auto-generated documentation via curl . + 4. Update Docs: Check off the acceptance tests in todo.md. + + +When I started working on this implemenatation, I found the first Milestone 0 blocker: + +The virtual environment configured via UV was installed succesfully, but some packages could not be executed under NixOS because of dynamically linked binaries + +This is actually related to the previous research in [[environments]] and [[devShell]]. + +Standard Linux distributions follow the Filesystem Hiearchy Standard (FHS) , placing dynamic linkers and shared libraries into expected paths. The pre-compiled binaries are compiled with the hardcoded paths to these expected linkers. + +NixOS will immediately fail to run them was such dynamic linkers do not exist in the requested paths. + +This usually has two solutions on NixOS; the first, using a System-level shim relying on nix-ld. This feature requires modifying the system level persisting configuration in my NixOS desktop. This would have not been bad, but assuming that another developer aims to work from a Nix-like environment as well, they would have also needed to make the fix before in order to reproduce the environment. + +That's why I opted for the second alternative, creating a declarative devShell through a `flake.nix` file. A devShell is essentially a package definition that defines the packages, env variables and compiler tools needed for the entire project (not only the Python packages). It's created at the project level (rather than the OS configuration), and uses the `pkgs.mkShell` helper function to define and isolate the development environment. + +I followed guidance mainly from this article: [How to use uv on NixOS](https://pydevtools.com/handbook/how-to/how-to-use-uv-on-nixos/) + +I was able to configure a minimal `flake.nix` file, which is pending for commit, and included the hook to direnv: + +```bash +nix develop +``` + + This is meant to automatically load the devShell environment as soon as I enter the project directory, however, we're encountering the following error: + + ```shell + bitetrack-api on  main [!+?] is 📦 v0.1.0 via 🐍 v3.13.13 on ☁️ fcortesbio@gmail.com +➜ direnv allow +direnv: loading ~/Projects/bitetrack-api/.envrc +direnv: using flake +direnv: nix-direnv: cache invalidated: files newer than cache: +nix-direnv: /home/kiskaadee/Projects/bitetrack-api/.envrc +direnv: nix-direnv: Renewed cache +/nix/store/9ypz3flqsrl5xl495mm8h645gadjsxi1-coreutils-9.11/bin/rm: /nix/store/7nbi22pcc92y2fqbkyp7h3srvvklmckb-glibc-2.40-224/lib/libc.so.6: version `GLIBC_2.42' not found (required by /nix/store/9ypz3flqsrl5xl495mm8h645gadjsxi1-coreutils-9.11/bin/rm) +direnv: export +AR +AS +CC +CONFIG_SHELL +CXX +HOST_PATH +IN_NIX_SHELL +LD +LD_LIBRARY_PATH +NIX_BINTOOLS +NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu +NIX_BUILD_CORES +NIX_CC +NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu +NIX_CFLAGS_COMPILE +NIX_ENFORCE_NO_NATIVE +NIX_HARDENING_ENABLE +NIX_LDFLAGS +NIX_STORE +NM +OBJCOPY +OBJDUMP +POSTGRES_DB +POSTGRES_PASSWORD +POSTGRES_USER +RANLIB +READELF +SIZE +SOURCE_DATE_EPOCH +STRINGS +STRIP +VIRTUAL_ENV +VIRTUAL_ENV_PROMPT +__structuredAttrs +buildInputs +buildPhase +builder +cmakeFlags +configureFlags +depsBuildBuild +depsBuildBuildPropagated +depsBuildTarget +depsBuildTargetPropagated +depsHostHost +depsHostHostPropagated +depsTargetTarget +depsTargetTargetPropagated +doCheck +doInstallCheck +dontAddDisableDepTrack +mesonFlags +name +nativeBuildInputs +out +outputs +patches +phases +preferLocalBuild +propagatedBuildInputs +propagatedNativeBuildInputs +shell +shellHook +stdenv +strictDeps +system ~PATH ~XDG_DATA_DIRS +/etc/profiles/per-user/kiskaadee/bin/starship: symbol lookup error: /nix/store/7nbi22pcc92y2fqbkyp7h3srvvklmckb-glibc-2.40-224/lib/libc.so.6: undefined symbol: __nptl_change_stack_perm, version GLIBC_PRIVATE +/etc/profiles/per-user/kiskaadee/bin/starship: symbol lookup error: /nix/store/7nbi22pcc92y2fqbkyp7h3srvvklmckb-glibc-2.40-224/lib/libc.so.6: undefined symbol: __nptl_change_stack_perm, version GLIBC_PRIVATE + ``` + +I noticed the error is mentioning a `starship: symbol lookup error`, which was surprising since starship is part of my shell, not the project. I suspect that, as soon as I enter, direnv is replacing some important `PATH` definition that is shared by starship and some of the installed dependencies. My current hypothesis is that entering the devShell modifies the dynamic library resolution for subsequently executed binaries, causing unrelated executables such as Starship to resolve incompatible libraries. + +That's certainly something we should investigate further as I require more evidence and careful debugging. The session for now is ending. I will return tomorrow to continue working on setting up the flake, and solving the direnv-starship-glibc issue. + From 188d104860e5988d58e660dc1a3c588e45de0d38 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 30 Jun 2026 12:46:02 -0500 Subject: [PATCH 12/72] docs(residency): document the Nix development environment architecture - Rewrite the devShell notes around architectural responsibilities - Clarify the boundaries between Nix, uv, and direnv - Document lessons learned while debugging the BiteTrack devShell - Simplify today's journal into findings and next steps - Record the decision to manage native tooling through the Nix environment --- journal/2026-06-30.md | 61 +++++++++++++++++++++++ knowledge/devShell.md | 72 ++++++++++++++++++++------- knowledge/environments.md | 100 ++++++++++++-------------------------- 3 files changed, 146 insertions(+), 87 deletions(-) create mode 100644 journal/2026-06-30.md diff --git a/journal/2026-06-30.md b/journal/2026-06-30.md new file mode 100644 index 0000000..2bdae8c --- /dev/null +++ b/journal/2026-06-30.md @@ -0,0 +1,61 @@ +# Daily Journal: 2026-06-30 + +## Goal + +Resume Milestone 0 by stabilizing the Nix development environment before implementing the first `/health` endpoint. + +--- + +## Progress + +Today's work focused entirely on debugging the Nix development environment. + +The original blocker was that native binaries installed inside the UV virtual environment (notably Ruff) could not execute under NixOS because of dynamically linked executables. + +Rather than enabling `nix-ld` globally, I decided to investigate a project-local solution using a declarative `flake.nix`. + +--- + +## Findings + +- Created a minimal `flake.nix` providing the project development shell. +- Learned how `eachDefaultSystem` exposes the shell for multiple architectures. +- Confirmed the shell loads automatically through `direnv`. +- Initially encountered a `glibc` symbol mismatch affecting Starship. +- The issue disappeared after removing `LD_LIBRARY_PATH` from the shell and relying on the standard Nix environment. +- Moved Ruff from the Python virtual environment into the Nix devShell. +- Confirmed: + +```bash +ruff check . +``` + +passes. + +```bash +uv run ruff check +``` + +also passes. + +Pyright and pytest continue working from the Python virtual environment. + +--- + +## Lessons Learned + +- Native tooling belongs in the Nix environment. +- Python libraries belong in the virtual environment. +- The first component reporting an error is not necessarily the component causing it. +- Systematically testing hypotheses is more effective than searching for fixes. + +--- + +## Next Session + +Resume the original milestone: + +- implement `/health` +- run Docker +- verify `/docs` +- complete Milestone 0 acceptance tests. diff --git a/knowledge/devShell.md b/knowledge/devShell.md index d171def..e4f9c5d 100644 --- a/knowledge/devShell.md +++ b/knowledge/devShell.md @@ -1,36 +1,74 @@ -# **The Anatomy of a devShell** +# The Anatomy of a devShell -In [[environments]] we briefly introduced the concept of a devShell. +## Motivation +A devShell is the Nix solution to the eternal development issue of "it works on my machine" at the system level. -If we get a little more technical, a devShell is a reproducible, isolated shell environment defined declaratively (usually via a `flake.nix`). It provides a specific set of system packages, compilers, and shared libraries without installing them globally. +With one important caveat: it is not primarily about installing packages. It is about reproducing an entire development environment. Rather than assuming the host machine already contains the correct compiler, linker, libraries, and development tools, a devShell declares those requirements explicitly and recreates them whenever the project is opened. -The problem it solves: "It works on my machine" syndrome and the lack of standard file-system paths on NixOS. +## Why I needed one +While bootstrapping BiteTrack, I discovered that several tools installed by `uv` did not execute correctly under NixOS. For example, Ruff is distributed as a native executable. The executable expected libraries (like `glibc`) to exist in standard Linux FHS locations (e.g., `/lib64/ld-linux-x86-64.so.2`) that do not exist on NixOS, causing: -Imagine a Python project requiring a concrete system-level library (e.g., `libpq` for PostgreSQL, `geos` for PostGIS, or specific versions of `gcc`), pip or uv will fail to compile native extensions because they cannot find these libraries in the standard paths like `/usr/lib`. +> `Could not start dynamically linked executable...` -When you run `nix develop` in that Python project's directory, Nix reads the declarative configuration (the `flake.nix`) and fetches or builds the exact versions of `libpq`, `geos`, and `gcc` specified. It stores them in the immutable `/nix/store`. +Instead of modifying my operating system with `nix-ld`, I decided to make the project self-contained by declaring its system dependencies inside a project-local `flake.nix`. -Then, rather than installing them globally, Nix drops you into a new, isolated bash shell. Behind the scenes, it intercepts and rewrites your environment variables—such as `PATH`, `LD_LIBRARY_PATH`, `C_INCLUDE_PATH`, and `PKG_CONFIG_PATH`—to point directly to those specific `/nix/store` paths. +## What a devShell Provides +A Nix devShell constructed via `mkShell` manipulates the shell environment to expose specific software and libraries without installing them globally. -Now, when you run `pip install` or `uv sync` inside this shell, the compiler seamlessly finds the required headers and libraries. It succeeds perfectly, regardless of whether you are on NixOS, macOS, or a completely clean Ubuntu installation. +* **System Executables (`PATH`):** Packages declared in `packages` (like `uv` and `ruff`) have their `/bin` directories prepended to `$PATH`. The shell uses the Nix store paths directly. +* **Shared Libraries:** Standard Linux distributions rely on global library paths. Nix compiles packages to look for their dependencies via absolute paths in the Nix store (using `RPATH`). +* **Environment Variables:** Standard builder variables are set automatically. Custom variables can be injected (e.g., `env.FOO = "bar";`), but manual manipulation of `LD_LIBRARY_PATH` often leads to symbol collisions if not handled carefully, as it overrides the explicitly linked `RPATH` of other Nix-provided binaries. +* **Compilers & Toolchains:** By providing `stdenv` or specific libraries (like `zlib`, `openssl`, `libffi`), the shell ensures that any tools compiled dynamically inside the environment (such as Python C-extensions) link against the exact library versions declared in the flake. ---- -***Note**: Delaying this until it's really necessary during a project, or until Milestone 2 is completed* +## devShell and UV: Separation of Concerns +To avoid system-level conflicts, dependencies are strictly partitioned based on their execution requirements: -**Why This is a Game-Changer for Development** +| Component | Managed By | Rationale | +| :--- | :--- | :--- | +| `uv` executable | Nix | Requires native execution and dynamically linked system libraries. | +| `ruff` | Nix | Pre-compiled native Rust executable. Fails under FHS assumptions without `nix-ld`. | +| Compiler Toolchain | Nix | Provides `glibc`, `stdenv`, `libffi` for compiling native extensions. | +| System Libraries | Nix | OpenSSL, PostgreSQL (`libpq.so`) needed by Python packages at runtime. | +| Python Virtualenv | `uv` | Strictly isolates project-specific Python dependencies. | +| `pytest` | `uv` | Pure Python package/script; executes safely within the interpreter. | +| `pyright` | `uv` | Node-based but wrapped via PyPI; executes via the local interpreter environment. | +| FastAPI / App Code | `uv` | Core application logic; belongs in the isolated Python environment. | +## Why Not `nix-ld`? -**Creating your first devShell in NixOS** +A common workaround for dynamic linker issues in NixOS is enabling `nix-ld` in the declarative global configuration. `nix-ld` provides a shim at the standard FHS linker path that redirects executions to the Nix store. +**nix-ld** +* **Pros:** Fixes the whole machine. Pre-compiled binaries downloaded from the internet (via `uv`, `npm`, `cargo`) usually execute without modification. +* **Cons:** Requires global system configuration. Compromises the strict purity and reproducibility of Nix, as projects will suddenly rely on the host machine having `nix-ld` enabled rather than declaring their own dependencies. +**devShell** +* **Pros:** Strictly project-local and reproducible. Documents exact system requirements. Highly portable across any system running the Nix package manager (including macOS or Ubuntu via WSL). +* **Cons:** Requires an extra `flake.nix` file. Requires manually triaging which tools must be moved from standard package managers (like `uv`) into Nix. -## Lectures: +The commitment in the BiteTrack project is to achieve a declarative and reproducible environment. Using a devShell saves time for any hypothetical developer onboarding to the project by eliminating "environment-related" setup bugs. -[Easy development environments with Nix and Nix flakes!](https://dev.to/arnu515/easy-development-environments-with-nix-and-nix-flakes-21mb) +## Lessons Learned -[Declarative shell environments with `shell.nix`](https://nix.dev/tutorials/first-steps/declarative-shell.html) +* **Native executables and Python packages are different concerns:** Tools distributed as binaries (Ruff) belong in Nix. Tools executing strictly via the Python interpreter belong in `uv`. +* **A tool failing first is not necessarily the source of the bug:** The `glibc` symbol mismatch affecting Starship was a downstream casualty of manually forcing `LD_LIBRARY_PATH` into the environment. +* **`LD_LIBRARY_PATH` should not be modified casually:** It overrides library lookups globally for the shell, breaking tools that rely on specific, different versions of those libraries. +* **`direnv` simply loads the shell:** It is an orchestrator, not the underlying problem when a shell fails to load correctly. +* **A reproducible environment is easier to debug than a globally configured one:** Isolation prevents cross-contamination of dependencies. -[Making a dev shell with nix flakes](https://fasterthanli.me/series/building-a-rust-service-with-nix/part-10) +## Future Improvements + +Investigate the following approaches to further optimize or simplify the Nix/Python bridge: +* `devenv.sh` +* `dream2nix` +* `uv2nix` +* `devenv` test support +* Managing multiple Python versions within the flake + +## External Resources +* [Easy development environments with Nix and Nix flakes!](https://dev.to/arnu515/easy-development-environments-with-nix-and-nix-flakes-21mb) +* [Declarative shell environments with `shell.nix`](https://nix.dev/tutorials/first-steps/declarative-shell.html) +* [Making a dev shell with nix flakes](https://fasterthanli.me/series/building-a-rust-service-with-nix/part-10) +* [Development shells with Nix: four quick examples (2025)](https://michael.stapelberg.ch/posts/2025-07-27-dev-shells-with-nix-4-quick-examples/) -[Development shells with Nix: four quick examples (2025)](https://michael.stapelberg.ch/posts/2025-07-27-dev-shells-with-nix-4-quick-examples/) diff --git a/knowledge/environments.md b/knowledge/environments.md index e15c108..785f4f1 100644 --- a/knowledge/environments.md +++ b/knowledge/environments.md @@ -1,88 +1,48 @@ -# devShells, direnv, env files and secret management +# Environment Management: devShells, direnv, and uv -With NixOS already providing `direnv`, when does it become necessary or advantageous to introduce `devShell`s? which responsibilities belong to each? - -To answer this accurately, we must establish clear problem statement: managing software dependencies spans multiple layers —from system-level shared libraries to language-specific packages to environment variables. Relying on a single tool to handle all layers inevitably leads to fragile environments, specially on a non-FHS (Filesystem Hierarchy Standard) distribution like NixOS - -Let's see an overview of these tools, understand what problems they solve, and how their responsibilities should be divided - -## [uv: The Python Speed Demon](https://docs.astral.sh/uv/) - -`uv` is powerful Python package and project manager. Just like `pip` or similar package managers like `npm` in the JavaScript ecosystem, `uv`'s primary's job is making sure every dependency used in your project is properly resolved, locked, and installed into an isolated virtual environment at lightning speed. It strictly handles the *language-layer* of your project. - -If your project relies on pure Python code, `uv` is practically all you need. However, the illusion breaks the moment your Python package require compiling C-extensions or linking against native system libraries (think `numpy`, `pyscopg2`, or `cryptography`). - -To build these packages, `uv` assumes your operating system follows traditional Linux conventions. It blindly reaches into standard directories like `/usr/lib` or `usr/include`, expecting to find compilers, headers, and C-libraries waiting for it. On NixOS, those FHS directories essentially do not exists. As a result, `uv` hits a brick wall, throwing a massive compilation error simply because it cannot find the system-level components it needs. - -This is exactly where we need to step down a layer and bring our next tool to bridge the gap. - -## Nix devShell (`nix develop`) - -Think of a **devShell** as a temporary, isolated workshop for your project. - -Many system-level libraries `uv` often crash trying to find them in NixOS. Instead of cluttering your OS with global installs, a devShell quietly rewires your terminal's environment variables (like `PATH` and `LD_LIBRARY_PATH`) to point directly to the exact dependencies you need. - -**The Result:** Seamless, crash-free installations that succeed perfectly every time—whether you're on NixOS, macOS, or Ubuntu. - -*(Expanded [[devShells]] guide coming soon.)* - - -## [direnv](https://direnv.net/) - -If devShell is your workshop, `direnv` could be an automated assistant, who makes sure the tools are ready to use the second you walk through the door. - -`direnv` is a shell extension that keeps a watchful eye on your directories. The moment you `cd` into a project folder containing an `.envrc` file, it automatically loads—or unloads- your environment variables and shell settings. - -That way, you don't need to `source .venv/bin/activate` or each time you enter your project. +Managing software dependencies spans multiple layers—from system-level shared libraries, to language-specific packages, to environment variables. Relying on a single tool to handle all layers inevitably leads to fragile environments, especially on a non-FHS distribution like NixOS. +To maintain a reproducible architecture, responsibilities are strictly divided among three tools. ## The Responsibility Matrix -|**Tool**|**Scope**|**Responsibilities**| -|---|---|---| -|**Nix devShell**|System / OS level|Providing Python interpreters, C compilers, system libraries (e.g., PostgreSQL client libs), and non-Python CLI tools (e.g., `jq`, `docker`).| -|**uv**|Python userland|Resolving and downloading Python packages (FastAPI, SQLAlchemy), writing the lockfile, and managing the local `.venv`.| -|**direnv**|Workflow / Shell level|Automating the activation of the `devShell` and exporting runtime secrets/environment variables (e.g., `DATABASE_URL`).| +| Tool | Scope | Responsibilities | +| :--- | :--- | :--- | +| **Nix devShell** | System / OS level | Providing Python interpreters, C compilers, system libraries (e.g., `postgresql` client libs), and non-Python native CLI tools (e.g., `ruff`, `docker`). | +| **uv** | Python userland | Resolving Python packages (FastAPI, SQLAlchemy), writing the lockfile, and managing the local `.venv`. | +| **direnv** | Workflow / Shell level | Automating the activation of the devShell, the Python virtual environment, and exporting runtime secrets/environment variables. | -## When does it become advantageous to introduce devShells? +## Tool Overview -If you're developing a pure-Python script that relies on standard libraries or pure-Python packages, you can survive on NixOS with just `uv` (assuming you have a globally installed Python interpreter). +### 1. uv (The Package Manager) +`uv` handles the language layer. Its job is to resolve, lock, and install pure Python dependencies into an isolated virtual environment. -However, introducing a `devShell` becomes **necessary** (not just advantageous), under the following conditions: +*Boundary:* `uv` assumes a standard Linux environment. It cannot reliably manage or compile packages that require dynamically linked C-extensions or native system binaries on NixOS. *(See: Anatomy of a devShell for details on native dependency resolution).* -- **You require native C extensions:** The moment your FastAPI project interacts with databases using libraries like `psycopg` (PostgreSQL) or handles geospatial data (PostGIS), `uv` will attempt to build these from source or download manylinux wheels. On NixOS, dynamically linked manylinux wheels often fail to execute because the interpreter cannot find the required `.so` files. A `devShell` allows you to inject `stdenv.cc.cc.lib`, `zlib`, or `postgresql` directly into the environment's `LD_LIBRARY_PATH`. - -- **You need reproducible system tools:** If your project requires a specific version of a database migration tool, a Node.js frontend build step, or a specific formatting tool, defining these in a `devShell` ensures any developer cloning the repository gets the exact same binaries. - -- **You are collaborating across OS boundaries:** A `devShell` abstracts away the host operating system. A colleague on macOS or Ubuntu will get the same underlying system dependencies as you do on NixOS. +### 2. Nix devShell (The Workshop) +A devShell abstracts away the host operating system. Rather than installing libraries globally, it rewires the terminal's environment variables to point directly to the exact system dependencies required by the project. -### Analyzing the Trade-offs +*Boundary:* The devShell handles what the operating system *should* provide, ensuring any developer cloning the repository gets the exact same binaries, regardless of whether they use NixOS, macOS, or Ubuntu. -Choosing to implement this trifecta (`devShell` + `direnv` + `uv`) introduces specific trade-offs: +### 3. direnv (The Orchestrator) +`direnv` is a shell extension that watches directories. Upon entering a project folder with an `.envrc` file, it automatically loads the environment. -- **Complexity vs. Reproducibility:** * _Cost:_ You are introducing Nix syntax and flake evaluation into a Python project. Developers unfamiliar with Nix may struggle to update system dependencies. - - - _Benefit:_ Absolute guarantee that the environment can be reproduced identically years from now. - -- **Performance vs. Isolation:** - - - _Cost:_ Evaluating a complex `flake.nix` takes time, though `nix-direnv` mitigates this heavily through caching. - - - _Benefit:_ Total isolation. Your FastAPI project's dependencies will not bleed into or be corrupted by your host system's updates. - -- **Maintenance Cost:** You now have two sources of truth for dependencies: `flake.nix` for system libraries and `pyproject.toml`/`uv.lock` for Python libraries. You must deliberately decide where a dependency belongs to avoid conflicts (e.g., do not install `ruff` via Nix if you are already managing it via `uv`). +*Boundary:* `direnv` does not install or build software. It simply answers the question: *"What environment variables and shells should be active right now?"* ## Analyzing the Trade-offs ---- -## Should I use a devShell for BiteTrack +Choosing to implement this trifecta introduces specific trade-offs: -The project itself may require some PostgreSQL extension or package in the long run, but adding the complexity of a devShell now is overkill, a sensible approach is: +* **Complexity vs. Reproducibility:** * *Cost:* Introducing Nix syntax and flake evaluation into a standard Python project increases the cognitive load for developers unfamiliar with Nix. + * *Benefit:* Absolute guarantee that the environment can be reproduced identically years from now. +* **Maintenance Cost:** * *Cost:* There are now two sources of truth for dependencies: `flake.nix` for system libraries and tools, and `pyproject.toml`/`uv.lock` for Python libraries. + * *Benefit:* Total isolation. You must deliberately decide where a dependency belongs, preventing Python packages from corrupting system tools and vice versa. -- **Keep using `direnv` now.** -- Introduce `devShell` later, when the environment itself becomes part of the project. +## Environment Management in BiteTrack -A good mental model is: +BiteTrack utilizes all three tools in tandem. -- **`.envrc`** answers: _"What environment variables should be available?"_ -- **`devShell`** answers: _"What software must exist on this machine to work on this project?"_ +The initial bootstrapping attempt relied solely on `uv` and `direnv`. However, the environment hit a hard limitation when native developer tooling (specifically, the pre-compiled Rust binary for Ruff) crashed due to missing dynamic libraries on NixOS. -Right now the project is simple enough that `direnv` is sufficient. Once we face a brick-wall fighting with installing specific versions of tools like `uv`, PostgreSQL clients, Ruff, Pyright, or other binaries, a `devShell` will become valuable because anyone entering the project gets the exact same toolchain. \ No newline at end of file +Instead of modifying the host OS, the project architecture was updated: +1. **`devShell`** provisions the native tools (`ruff`, `uv` executable) and core libraries. +2. **`uv`** manages the FastAPI application dependencies. +3. **`direnv`** silently orchestrates both upon entering the directory. From 842408b4820b5b695df4822bcad03c875261ce47 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Wed, 1 Jul 2026 00:22:18 -0500 Subject: [PATCH 13/72] docs(tmux): add tmux quick reference and standardize project naming - Add a comprehensive tmux cheat sheet covering sessions, panes, copy mode, and common commands. - Rename "Flagship API Design" to "BiteTrack API Design" for consistency with the project documentation. The tmux reference serves as a practical knowledge base while adopting tmux as the primary terminal workflow during the Backend Residency. --- knowledge/tmux.md | 80 +++++++++++++++++++++++++++++++++++++++++++ project/api-design.md | 2 +- 2 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 knowledge/tmux.md diff --git a/knowledge/tmux.md b/knowledge/tmux.md new file mode 100644 index 0000000..debaa4e --- /dev/null +++ b/knowledge/tmux.md @@ -0,0 +1,80 @@ +# Tmux Cheat Sheet & Quick Reference +From: https://tmuxcheatsheet.com/ + +**Note:** All keybinds assume the default prefix is `Ctrl + b`. + +## Session Management + +| **Action** | **Keybind** | **Command** | +| --------------------------- | ------------------ | --------------------------------------------------------- | +| **Start new session** | - | `tmux`, `tmux new`, `tmux new-session`, `:new` | +| **Start/Attach session** | - | `tmux new-session -A -s ` | +| **New session (named)** | - | `tmux new -s `, `:new -s ` | +| **List sessions** | `Ctrl + b s` | `tmux ls`, `tmux list-sessions` | +| **Attach last session** | - | `tmux a`, `tmux at`, `tmux attach`, `tmux attach-session` | +| **Attach specific session** | - | `tmux a -t `, `tmux attach -t ` | +| **Detach from session** | `Ctrl + b d` | - | +| **Detach others** | - | `:attach -d` | +| **Rename session** | `Ctrl + b $` | - | +| **Kill current session** | - | `:kill-session` | +| **Kill specific session** | - | `tmux kill-ses -t ` | +| **Kill all but current** | - | `tmux kill-session -a` | +| **Kill all but** | - | `tmux kill-session -a -t ` | +| **Prev/Next session** | `Ctrl + b (` / `)` | - | + +## Pane Management + +| **Action** | **Keybind** | **Command** | +| -------------------------- | ---------------------------- | ------------------------- | +| **Split horizontally** | `Ctrl + b %` | `:split-window -h` | +| **Split vertically** | `Ctrl + b "` | `:split-window -v` | +| **Switch pane** | `Ctrl + b arrow` / `h,j,k,l` | - | +| **Switch next pane** | `Ctrl + b o` | - | +| **Toggle last pane** | `Ctrl + b ;` | - | +| **Move pane left/right** | `Ctrl + b {` / `}` | - | +| **Toggle pane zoom** | `Ctrl + b z` | - | +| **Resize pane** | `Ctrl + b + arrow` | - | +| **Show pane numbers** | `Ctrl + b q` | - | +| **Select pane by num** | `Ctrl + b q ` | - | +| **Convert pane to window** | `Ctrl + b !` | - | +| **Close current pane** | `Ctrl + b x` | - | +| **Toggle sync panes** | - | `:setw synchronize-panes` | +| **Toggle layouts** | `Ctrl + b Space` | - | +| **Pane actions menu** | `Ctrl + b >` | - | + +## Copy Mode + +|**Action**|**Keybind**|**Command**| +|---|---|---| +|**Enter copy mode**|`Ctrl + b [`|-| +|**Scroll page up**|`Ctrl + b PgUp`|-| +|**Enable vi mode**|-|`:setw -g mode-keys vi`| +|**Quit copy mode**|`q`|-| +|**Move cursor**|`h, j, k, l`|-| +|**Word move (fwd/bwd)**|`w` / `b`|-| +|**Top/Bottom of line**|`g` / `G`|-| +|**Scroll up/down**|`↑` / `↓`|-| +|**Search (fwd/bwd)**|`/` / `?`|-| +|**Search next/prev**|`n` / `N`|-| +|**Start selection**|`Spacebar`|-| +|**Copy selection**|`Enter`|-| +|**Clear selection**|`Esc`|-| +|**Paste buffer**|`Ctrl + b ]`|-| +|**Show buffer**|-|`:show-buffer`, `:list-buffers`| +|**Choose buffer**|-|`:choose-buffer`| +|**Capture entire pane**|-|`:capture-pane`| +|**Save buffer**|-|`:save-buffer `| +|**Delete buffer**|-|`:delete-buffer -b `| + +## Misc & Help + +|**Action**|**Keybind**|**Command**| +|---|---|---| +|**Command mode**|`Ctrl + b :`|-| +|**List key bindings**|`Ctrl + b ?`|`:list-keys`, `tmux list-keys`| +|**Session/Win preview**|`Ctrl + b w`|-| +|**Set global option**|-|`:set -g