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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .github/copilot-instructions-bloated.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Instructions for Copilot

Please always be helpful and provide complete answers. When writing code, please use best practices and follow clean code principles. Always add comments to explain what the code does. Use meaningful variable names. Follow the DRY principle. Write unit tests when applicable. Use TypeScript for all new files. Follow our team's coding standards. Be thorough in your explanations.

When working on this project, please note that we use:
- React 18 with TypeScript
- Node.js 20 for the backend
- Tailwind CSS for styling
- Jest for testing with React Testing Library for component tests
- ESLint with our custom config
- Prettier for formatting
- PostgreSQL for the database
- Express for the API server

When writing tests for this project, please make sure that you follow our testing conventions. We use Jest as our testing framework and we prefer to use the React Testing Library for component tests. Tests should be placed in a __tests__ directory next to the source file they're testing. Please make sure to include both happy path and error cases.

When working on API endpoints, please follow RESTful conventions. Use plural nouns for resource names. Use proper HTTP status codes. Always include error handling. Make sure to validate input data. Use middleware for authentication. Document any new endpoints.

Please always use functional components in React. Use hooks for state management. Keep components small and focused. Extract reusable logic into custom hooks. Use TypeScript interfaces for all props. Prefer named exports over default exports.

When writing code, please ensure that:
1. All functions have proper TypeScript types
2. Error messages are user-friendly
3. Sensitive data is never logged
4. Database queries use parameterized inputs
5. API responses follow our standard envelope format
6. Authentication is checked on all protected routes
4 changes: 4 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Stack: Node.js 20, TypeScript 5.4, Express, PostgreSQL.
Style: ESM modules, strict TypeScript, no `any` types.
Error handling: Use Result pattern, never throw in business logic.
Tests: Jest + RTL. Co-locate in __tests__/. Cover happy path + error cases.
26 changes: 26 additions & 0 deletions .github/copilot-setup-steps.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Copilot Setup Steps
on: workflow_dispatch

jobs:
copilot-setup:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
cache: "npm"

- name: Install dependencies
run: npm ci

Comment on lines +16 to +18
- name: Build project
run: npm run build

- name: Verify TypeScript
run: npx tsc --noEmit

- name: Run tests
run: npm test
36 changes: 36 additions & 0 deletions .github/prompts/api-design.prompt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
description: "Use when designing or reviewing API endpoints"
---

# API Design Standards

## URL Patterns
- Use plural nouns: /users, /orders
- Nest for relationships: /users/{id}/orders
- Use query params for filtering: /users?role=admin

## Request/Response
- Always use JSON
- Wrap responses: { data: T, meta: {...} }
- Use HTTP status codes correctly
- Include request-id header

## Versioning
- URL prefix: /api/v1/
- Never break backwards compatibility in same version

## Error Format
```json
{
"error": {
"code": "VALIDATION_FAILED",
"message": "Human-readable message",
"details": [{ "field": "email", "issue": "invalid format" }]
}
}
```

## Authentication
- Bearer token in Authorization header
- 401 for missing/invalid token
- 403 for insufficient permissions
31 changes: 31 additions & 0 deletions .github/prompts/deploy-checklist.prompt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
description: "Use when preparing or reviewing a deployment"
---

# Deploy Checklist

## Pre-Deploy
- [ ] All tests pass on CI
- [ ] No TypeScript errors (`tsc --noEmit`)
- [ ] Database migrations reviewed and tested
- [ ] Environment variables documented for new features
- [ ] API docs updated for new/changed endpoints

## Deploy Process
1. Merge PR to `main`
2. CI builds and runs full test suite
3. Docker image built and pushed to registry
4. Staging auto-deploys from `main`
5. Smoke test staging (health check + critical paths)
6. Production deploy via GitHub Actions workflow dispatch

## Post-Deploy
- [ ] Monitor error rates for 15 minutes
- [ ] Check key metrics dashboard
- [ ] Verify new feature works in production
- [ ] Update status page if needed

## Rollback
- Revert commit on `main` triggers auto-rollback
- Database: only additive migrations (never drop columns in same release)
- Feature flags: disable flag immediately if issues detected
35 changes: 35 additions & 0 deletions .github/prompts/testing.prompt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
---
description: "Use when writing or reviewing tests"
---

# Testing Standards

## Framework
- Jest for unit/integration tests
- React Testing Library for components
- Supertest for API endpoint tests

## File Placement
- Co-locate: `src/services/__tests__/userService.test.ts`
- Name: `{module}.test.ts`
Comment on lines +12 to +14

## Coverage Requirements
- Happy path (expected inputs → expected outputs)
- Error cases (invalid input, missing data, network failures)
- Edge cases (empty arrays, null values, boundary values)

## Patterns
- Arrange / Act / Assert structure
- One assertion concept per test
- Mock external dependencies only (DB, APIs)
- Never mock the module under test
- Use factories for test data: `createUser({ overrides })`

## Naming
```typescript
describe('filterActiveUsers', () => {
it('returns only users where isActive is true', () => { ... });
it('returns empty array when no users are active', () => { ... });
it('sorts by lastLoginAt descending', () => { ... });
});
```
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules/
dist/
build/
*.js.map
.env
.env.local
6 changes: 6 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"recommendations": [
"GitHub.copilot",
"GitHub.copilot-chat"
]
}
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"typescript.preferences.importModuleSpecifier": "relative"
}
69 changes: 67 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,67 @@
# token-optimization-demo
I am used to demo token optimization strategies
# Token Optimization Demos

Companion repository for the YouTube video: **"The 5 Rules of Token Optimization Every Developer MUST Know (GitHub Copilot)"**

📺 Watch the video: [YouTube Link]

## What's In This Repo

This repo is a sample TypeScript/Node.js project specifically structured to demonstrate token optimization techniques for GitHub Copilot. Use it to follow along with the video or as a template for your own projects.

### Demo Files

| File | Used In | Purpose |
|------|---------|---------|
| `.github/copilot-instructions.md` | Rule 1 & 2 | The optimized (lean) instructions file |
| `.github/copilot-instructions-bloated.md` | Rule 1 | The "before" bloated version for comparison |
| `.github/prompts/api-design.prompt.md` | Rule 2 | On-demand API design prompt file |
| `.github/prompts/testing.prompt.md` | Rule 2 | On-demand testing prompt file |
| `.github/prompts/deploy-checklist.prompt.md` | Rule 2 | On-demand deploy prompt file |
| `.github/copilot-setup-steps.yml` | Rule 5 | Coding agent setup file |
| `src/services/userService.ts` | Rule 4 | Contains `filterActiveUsersByLastLogin` |
| `src/models/user.ts` | Rule 4 | User type definition |
| `docs/content-exclusion-patterns.md` | Rule 5 | Starter list of exclusion patterns |
| `docs/caveman-instructions-examples.md` | Rule 4 | Before/after instruction compression examples |

### Project Structure

```
.github/
├── copilot-instructions.md ← Optimized (lean) - ALWAYS LOADED
├── copilot-instructions-bloated.md ← "Before" version for demo comparison
├── copilot-setup-steps.yml ← Coding agent setup
└── prompts/
├── api-design.prompt.md ← On-demand: API guidelines
├── testing.prompt.md ← On-demand: Testing standards
└── deploy-checklist.prompt.md ← On-demand: Deploy process
src/
├── models/
│ └── user.ts ← User interface
├── services/
│ └── userService.ts ← filterActiveUsersByLastLogin demo
├── utils/
│ └── helpers.ts ← Utility functions
└── __tests__/
└── userService.test.ts ← Co-located test example
docs/
├── content-exclusion-patterns.md ← Copy-paste exclusion patterns
└── caveman-instructions-examples.md ← Before/after compression guide
```

## How To Use

1. **Clone this repo** and open in VS Code
2. **Follow along with the video** — each Rule section references specific files
3. **Copy what you need** — the instruction files, prompt files, and patterns are designed to be adapted for your projects

## The 5 Rules

1. **Treat Context Like a Budget** — Every token costs. Be intentional.
2. **Load On-Demand, Not Always-On** — Keep instructions lean, details in prompt files.
3. **Right-Size Your Model** — Lightweight models for simple, premium for complex.
4. **Be Precise, Not Polite** — Caveman style. No filler. Slash commands.
5. **Clean Your Context** — /clear between tasks. Close tabs. Exclude noise.

## License

MIT — use these patterns in your own projects!
126 changes: 126 additions & 0 deletions docs/caveman-instructions-examples.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# Caveman-Style Instruction Compression

## The Principle

Write instructions in compressed, article-free, fragment style.
Drop: articles (a, an, the), filler words (just, really, basically, please), pleasantries, hedging.
Fragments OK. Short synonyms. Code unchanged.

---

## Examples: Before & After

### Example 1: General Instructions

**❌ BEFORE (~150 tokens):**
```markdown
# Instructions for Copilot

Please always be helpful and provide complete answers. When writing code,
please use best practices and follow clean code principles. Always add
comments to explain what the code does. Use meaningful variable names.
Follow the DRY principle. Write unit tests when applicable. Use TypeScript
for all new files. Follow our team's coding standards. Be thorough in
your explanations.

When working on this project, please note that we use:
- React 18 with TypeScript
- Tailwind CSS for styling
- Jest for testing
- ESLint with our custom config
- Prettier for formatting
```

**✅ AFTER (~40 tokens):**
```markdown
Stack: React 18, TypeScript, Tailwind, Jest, ESLint.
Style: Functional components, named exports, error boundaries at route level.
Tests: Co-locate with source. Use Testing Library. Mock external deps only.
```

**Savings: ~73% fewer tokens on EVERY request**

---

### Example 2: Testing Instructions

**❌ BEFORE (~70 tokens):**
```markdown
When writing tests for this project, please make sure that you follow our
testing conventions. We use Jest as our testing framework and we prefer to
use the React Testing Library for component tests. Tests should be placed
in a __tests__ directory next to the source file they're testing. Please
make sure to include both happy path and error cases.
```

**✅ AFTER (~15 tokens):**
```markdown
Tests: Jest + RTL. Co-locate in __tests__/. Cover happy path + error cases.
```

**Savings: ~78% fewer tokens on EVERY request**

---

### Example 3: API Standards

**❌ BEFORE (~90 tokens):**
```markdown
When working on API endpoints, please follow RESTful conventions. Use plural
nouns for resource names. Use proper HTTP status codes. Always include error
handling. Make sure to validate input data. Use middleware for authentication.
Document any new endpoints. Wrap all responses in our standard envelope format
with data and meta fields.
```

**✅ AFTER (~25 tokens):**
```markdown
API: RESTful, plural nouns, proper HTTP codes.
Errors: { error: { code, message, details[] } }
Responses: { data: T, meta: { timestamp, requestId } }
Auth: Bearer token middleware on protected routes.
```

**Savings: ~72% fewer tokens on EVERY request**

---

### Example 4: Project Context

**❌ BEFORE (~110 tokens):**
```markdown
This is a task management web application built with React and Node.js.
We use MongoDB as our database. The frontend is in the /src directory
and the backend API server is in the /server directory. We follow a
microservices architecture with separate services for authentication,
task management, and notifications. Each service communicates via REST APIs.
The project uses Docker for containerization and GitHub Actions for CI/CD.
```

**✅ AFTER (~40 tokens):**
```markdown
Task management app. React frontend (src/), Node.js API (server/).
DB: MongoDB. Architecture: microservices (auth, tasks, notifications) via REST.
Infra: Docker, GitHub Actions CI/CD.
```

**Savings: ~64% fewer tokens on EVERY request**

---

## The Math

If your instructions file saves 100 tokens per request, and you make 30 requests/day:
- **Daily savings:** 3,000 tokens
- **Monthly savings:** ~90,000 tokens
- **For a 10-person team:** ~900,000 tokens/month

At premium model rates, that's real money saved — and your context window has more room for actual code.

## Rules of Thumb

1. If the model already knows it (SOLID, clean code, be helpful) — delete it
2. If it's in package.json or tsconfig (framework versions, settings) — don't repeat it
3. If it only applies to some files — move it to a prompt file, not instructions
4. If it's longer than 3 lines for one concept — compress it
5. Read it aloud: if it sounds like an email, rewrite it as a telegram
Loading