Skip to content

Commit 3873564

Browse files
bwlclaude
andcommitted
Upgrade TLDR to v0.2 with NDJSON format and add --tldr=all flag
TLDR v0.1 → v0.2 Migration: - Replace ASCII KEY:value format with NDJSON (newline-delimited JSON) - Add tool delimiter (--- tool: forest ---) and metadata headers - Implement Forest's condensed keymap (12 keys vs 38 stdlib, 60% reduction) - Command-level: cmd, p, in, out, fx, fl, ex, rel - Flag-level: n, t, d, desc - Update type system: STR→str, BOOL→bool, INT→int, FLOAT→float, etc. - Transform all 31 command definitions to v0.2 abbreviated format - Convert side effects to namespaced: db:write, compute:embedding, etc. - Update emitTldrAndExit signature: (data, jsonMode) → (data, version) New --tldr=all Feature: - Add formatAllCommandsTldr() to output entire CLI surface in one call - Enable zero-shot CLI discovery for AI agents (31 commands in single response) - Format: tool delimiter + metadata header + 31 JSON objects (one per line) - Non-breaking: preserves existing 'forest --tldr' behavior Benefits: - 60% token reduction from condensed keymap - Single API call discovers full CLI capability - Valid NDJSON for easy parsing - Self-documenting with embedded keymap Testing: - forest --tldr outputs global index ✓ - forest capture --tldr outputs single command ✓ - forest --tldr=all outputs 33 lines (delimiter + header + 31 commands) ✓ - All JSON lines parse correctly ✓ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 06a6659 commit 3873564

131 files changed

Lines changed: 559010 additions & 431 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.claude/agents/api-tester.md

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
---
2+
name: api-tester
3+
description: Use this agent when the user has just implemented or modified API endpoints and needs comprehensive endpoint testing. Trigger when you see phrases like 'test the endpoints', 'verify the API', 'check if the routes work', 'test the new endpoints I added', or after completing implementation of REST endpoints, server routes, or API features. Also use proactively after you've helped implement new endpoints or modified existing routes to suggest testing before the user commits changes.\n\nExamples:\n\n<example>\nContext: User just implemented new /nodes CRUD endpoints.\nuser: "I just added the /nodes endpoints with GET, POST, PUT, and DELETE. Can you test them?"\nassistant: "I'll use the api-tester agent to run comprehensive tests on your new /nodes endpoints."\n<commentary>The user explicitly requested endpoint testing after implementation, which is the primary use case for api-tester.</commentary>\n</example>\n\n<example>\nContext: User modified edge management routes to add new query parameters.\nuser: "I updated the /edges endpoint to support filtering by status and score range. Please verify it works."\nassistant: "Let me launch the api-tester agent to verify your updated /edges endpoint with the new filtering parameters."\n<commentary>User wants verification of modified routes with new functionality - perfect for api-tester.</commentary>\n</example>\n\n<example>\nContext: Assistant just helped implement pagination on /tags endpoint.\nuser: "Thanks for adding pagination!"\nassistant: "You're welcome! Let me use the api-tester agent to verify the pagination parameters work correctly on the /tags endpoint before you commit this change."\n<commentary>Proactive testing suggestion after implementation is complete - api-tester should verify the new feature works.</commentary>\n</example>\n\n<example>\nContext: User asks to test error handling.\nuser: "Can you test if the API properly returns 404 for missing nodes?"\nassistant: "I'll use the api-tester agent to test error cases including 404 responses for missing resources."\n<commentary>Testing specific error scenarios is part of comprehensive endpoint testing.</commentary>\n</example>
4+
tools: Bash, Read, Grep
5+
model: haiku
6+
color: orange
7+
---
8+
9+
You are an expert API testing specialist with deep knowledge of REST API design, HTTP protocols, and comprehensive endpoint validation. Your role is to execute thorough, systematic tests of API endpoints and provide concise, actionable test reports.
10+
11+
## Your Responsibilities
12+
13+
1. **Comprehensive Endpoint Testing**: For each endpoint, you will:
14+
- Test all HTTP methods (GET, POST, PUT, DELETE, PATCH as applicable)
15+
- Verify successful responses return correct status codes (200, 201, 204)
16+
- Test error cases (400, 404, 422, 500) with invalid inputs
17+
- Validate response formats match expected schemas (JSON structure, field types)
18+
- Check pagination parameters (limit, offset, page, cursor as applicable)
19+
- Test query parameters and filters
20+
- Verify request/response headers
21+
- Measure and note response times
22+
23+
2. **Systematic Test Execution**: You will:
24+
- Use curl commands via the Bash tool to make HTTP requests
25+
- Parse JSON responses to validate structure and data
26+
- Test edge cases: empty results, boundary values, missing parameters
27+
- Verify data persistence (create → read → update → read → delete flows)
28+
- Test related endpoints together (e.g., create node, then link it, then query the link)
29+
30+
3. **Intelligent Test Coverage**: Based on the endpoint type, adapt your tests:
31+
- **CRUD endpoints**: Full lifecycle testing (Create, Read, Update, Delete)
32+
- **List endpoints**: Empty state, single item, multiple items, pagination, filtering
33+
- **Search endpoints**: Query variations, no results, partial matches
34+
- **Batch operations**: Single vs multiple items, partial failures
35+
36+
4. **Concise Reporting**: After testing, provide a structured summary:
37+
- **Test Summary**: Total tests run, passed count, failed count
38+
- **Failures**: List any failed tests with brief error descriptions
39+
- **Performance**: Note any unusually slow responses (>1s)
40+
- **Recommendations**: Suggest fixes for failures or improvements
41+
- **DO NOT**: Include verbose curl output or full JSON responses unless explaining a failure
42+
43+
## Test Execution Guidelines
44+
45+
- **Server Discovery**: First check if a server is running (typically localhost:3000 or similar). Use Read tool to check project files for server config if needed.
46+
- **Test Data**: Create minimal test data needed for validation, clean up after tests when possible
47+
- **Error Handling**: Gracefully handle connection failures, timeouts, and unexpected responses
48+
- **Context Efficiency**: Keep test execution details internal, only surface actionable results
49+
- **Use jq**: Pipe curl output through jq for JSON validation and field extraction when available
50+
51+
## Example Test Flow
52+
53+
For a hypothetical `/api/nodes` endpoint:
54+
```bash
55+
# 1. Test GET all (empty state)
56+
curl -s http://localhost:3000/api/nodes | jq '.data | length'
57+
58+
# 2. Test POST create
59+
curl -s -X POST http://localhost:3000/api/nodes -H "Content-Type: application/json" -d '{"title":"Test","body":"Body"}' | jq '.id'
60+
61+
# 3. Test GET single (with created ID)
62+
curl -s http://localhost:3000/api/nodes/{id} | jq '.title'
63+
64+
# 4. Test error case (404)
65+
curl -s -w "\n%{http_code}" http://localhost:3000/api/nodes/nonexistent
66+
67+
# 5. Test pagination
68+
curl -s "http://localhost:3000/api/nodes?limit=10&offset=0" | jq '.data | length'
69+
```
70+
71+
## Output Format
72+
73+
Your final response should follow this structure:
74+
75+
```
76+
=== API Test Results ===
77+
78+
**Endpoints Tested**: /api/nodes, /api/edges
79+
**Total Tests**: 24
80+
**Passed**: 22
81+
**Failed**: 2
82+
83+
**Failures**:
84+
- GET /api/nodes?invalidParam=x: Expected 400, got 200 (invalid params not validated)
85+
- DELETE /api/edges/{id}: 500 error (foreign key constraint not handled)
86+
87+
**Performance**:
88+
- Most responses < 100ms
89+
- GET /api/search taking 1.2s (consider indexing)
90+
91+
**Recommendations**:
92+
1. Add query parameter validation to return 400 for unknown params
93+
2. Handle edge deletion constraints with proper cascade or error message
94+
3. Add database index on search fields
95+
96+
**Test Coverage**: CRUD operations, pagination, filtering, error cases
97+
```
98+
99+
## Decision Framework
100+
101+
- If server isn't running, report this immediately and suggest starting it
102+
- If endpoints are undocumented, make reasonable assumptions based on REST conventions
103+
- If a test fails, try to diagnose the root cause (validation, data, server error)
104+
- If you encounter unexpected behavior, include it in recommendations
105+
- If all tests pass, still provide the summary with performance notes
106+
107+
You work efficiently and autonomously. You don't ask for permission to run tests - you execute them systematically and report results. You are thorough but concise, ensuring the user gets actionable insights without context pollution.

.claude/settings.local.json

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"permissions": {
3+
"allow": [
4+
"Bash(forest:*)",
5+
"WebSearch",
6+
"Bash(curl -s http://localhost:3000/api/v1/health)",
7+
"Bash(curl -s \"http://localhost:3000/api/v1/nodes?limit=5\")",
8+
"WebFetch(domain:platform.openai.com)",
9+
"WebFetch(domain:raw.githubusercontent.com)"
10+
],
11+
"deny": [],
12+
"ask": []
13+
}
14+
}

AGENTS.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Repository Guidelines
2+
3+
## Project Structure & Module Organization
4+
- `src/index.ts` stitches together the CLI, orchestrating capture, explore, and linking commands.
5+
- `src/lib/` contains focused modules: `db.ts` wraps sql.js persistence, `graph.ts` builds graphology structures, `scoring.ts` maintains suggestion heuristics, and `text.ts` handles tokenization and tagging.
6+
- `dist/` is generated output from TypeScript; rebuild instead of editing files here.
7+
- `docs/` hosts design notes such as `cli-surface-proposal.md`; keep long-form discussions and ADR-style writeups here.
8+
- `forest.db` is a sample database for local smoke tests; feel free to reset it when experimenting.
9+
10+
## Build, Test, and Development Commands
11+
- `npm run build` compiles TypeScript to `dist/` with the repo tsconfig.
12+
- `npm run dev` executes the CLI through `tsx`, ideal for iterating on commands without compiling.
13+
- `npm run lint` runs `tsc --noEmit` for type safety; treat failures as blockers.
14+
- `npm start` runs the compiled CLI (`node dist/index.js`); use it when verifying release artifacts.
15+
16+
## Coding Style & Naming Conventions
17+
- Follow the existing 2-space indentation, single quotes, and trailing commas where they clarify multi-line structures.
18+
- Favor small, pure functions; keep modules under `src/lib/` single-purpose and export named functions instead of default exports.
19+
- Use lowerCamelCase for variables/functions, PascalCase for types, and kebab-case for new file names.
20+
21+
## Testing Guidelines
22+
- There is no automated test suite yet; for new features, add targeted TypeScript tests alongside the code (e.g., `src/lib/__tests__/graph.spec.ts`) using `tsx` or `ts-node`.
23+
- Cover edge cases around scoring thresholds, tag extraction, and graph linking; include fixtures under a nearby `fixtures/` folder if needed.
24+
- Run `npm run dev -- capture --body "example"` against a fresh `forest.db` to perform smoke tests before submitting.
25+
26+
## Commit & Pull Request Guidelines
27+
- Write concise, imperative commit subjects (e.g., “Add capture preview summary”), mirroring the existing history.
28+
- Group related changes per commit and mention the affected module path in the body when context helps reviewers.
29+
- In pull requests, link related issues, summarize behavior changes, note manual test commands, and include CLI output snippets or screenshots when UI-facing functionality changes.

Camper/PRODUCT_STRATEGY.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Camper Product Strategy
2+
3+
**READ THIS FIRST**: GPT-5 generated a comprehensive product strategy report for Camper.
4+
5+
## How to Access
6+
7+
```bash
8+
forest node read e860b1c3
9+
```
10+
11+
Or view in Forest's knowledge base as node `e860b1c3`.
12+
13+
## Report Summary
14+
15+
**Title**: "What Humans Actually Want: A Human-First Product Strategy for Camper (Built on Forest)"
16+
17+
**Generated**: 2025-10-21
18+
**Cost**: $0.02 (GPT-5 high reasoning)
19+
**Length**: ~2,424 words
20+
21+
## Key Insights
22+
23+
### Core Principle
24+
> "Build the Practice, Not the Graph. The graph is the engine; the practice is the product."
25+
26+
### Strategic Focus Areas
27+
28+
1. **Three-Second Capture** - Every primary action <2 seconds
29+
2. **Review Mode Over Dashboards** - Calm triage, not information overload
30+
3. **Editor-First Experience** - People live in the editor
31+
4. **Human-in-the-Loop Intelligence** - Forest proposes, humans decide
32+
5. **Rhythmic Workflows** - Daily, weekly, monthly patterns
33+
34+
### What NOT to Build
35+
36+
- ❌ Heavy PM suite (Gantt charts, sprints)
37+
- ❌ Real-time collaboration as core feature
38+
- ❌ Notion-like database engine
39+
- ❌ Flashy graph dashboard
40+
- ❌ Auto-rewriting notes without confirmation
41+
42+
### The Camper Advantage
43+
44+
Forest handles graph intelligence (embeddings, auto-linking, scoring). This frees Camper to focus entirely on human workflows that competitors can't match because they conflate the graph layer with the interface layer.
45+
46+
## Three-Phase Roadmap
47+
48+
**Phase 1 (0-3mo)**: Quick capture, daily notes, Review Mode v1, editor experience
49+
**Phase 2 (3-6mo)**: Tasks, meeting briefings, context panel, AI-assisted extraction
50+
**Phase 3 (6-9mo)**: Automations, integrations (Readwise/Omnivore), lightweight sharing
51+
52+
## Success Metrics
53+
54+
- Time-to-capture < 2 seconds
55+
- Triage throughput (inbox zero in ~12 minutes)
56+
- Retrieval success within 10 seconds
57+
- **Forest proposal acceptance rate** (trust indicator)
58+
- 4-week retention
59+
60+
## Read the Full Report
61+
62+
The full report covers:
63+
- User psychology and friction points
64+
- Daily/weekly/monthly workflow patterns
65+
- The capture problem (lessons from Readwise, Omnivore)
66+
- Cozy features that build trust
67+
- Editor integration insights
68+
- Triage workflow design
69+
- Task management (PKM vs. dedicated managers)
70+
- Collaboration boundaries
71+
- Concrete UX examples
72+
73+
```bash
74+
forest node read e860b1c3
75+
```
76+
77+
---
78+
79+
**Note**: This report was generated using `forest write` with a detailed prompt about Forest/Camper architecture and user needs. It represents GPT-5's synthesis of PKM best practices, user behavior patterns, and strategic opportunities given our clean separation of concerns.

FEATURE_CHECKLIST.md

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
# Feature Development Checklist
2+
3+
Use this checklist when adding new features to Forest to ensure CLI/API parity.
4+
5+
## Pre-Implementation
6+
7+
- [ ] Define feature requirements clearly
8+
- [ ] Identify where the feature should be accessible (CLI only, API only, or both?)
9+
- [ ] Design the core function signature and return types
10+
- [ ] Plan error cases and validation
11+
12+
## Implementation Order
13+
14+
### 1. Core Business Logic
15+
- [ ] Create or update function in `src/core/*.ts`
16+
- [ ] Function is pure (no I/O formatting, no HTTP/CLI dependencies)
17+
- [ ] Returns typed data structures
18+
- [ ] Handles all business validation
19+
- [ ] Includes comprehensive error handling
20+
- [ ] Well-documented with JSDoc comments
21+
22+
### 2. REST API (if applicable)
23+
- [ ] Create or update route in `src/server/routes/*.ts`
24+
- [ ] Calls core function (no business logic duplication)
25+
- [ ] Parses and validates query parameters/request body
26+
- [ ] Uses helper functions from `src/server/utils/helpers.ts`
27+
- [ ] Returns standard envelope format via `createSuccessResponse()`
28+
- [ ] Handles errors with `ForestError` classes
29+
- [ ] Sets appropriate HTTP status codes
30+
- [ ] Includes Swagger/OpenAPI documentation tags
31+
- [ ] Register route in `src/server/index.ts`
32+
- [ ] Import route module
33+
- [ ] Add `.use()` call to app
34+
- [ ] Add tag to Swagger documentation config
35+
36+
### 3. CLI Command (if applicable)
37+
- [ ] Create or update command in `src/cli/commands/*.ts`
38+
- [ ] Calls core function (no business logic duplication)
39+
- [ ] Parses command-line arguments and flags
40+
- [ ] Provides human-readable text output (default)
41+
- [ ] Provides machine-readable JSON output (with `--json` flag)
42+
- [ ] Uses utilities from `src/cli/shared/utils.ts`
43+
- [ ] Handles errors with `handleError()`
44+
- [ ] Register command in `src/cli/index.ts`
45+
- [ ] Import command factory
46+
- [ ] Call `cli.command(createYourCommand(clerc))`
47+
48+
### 4. Documentation
49+
- [ ] Update `CLAUDE.md`
50+
- [ ] Add command to command structure list (if new command)
51+
- [ ] Document any new patterns or utilities
52+
- [ ] Update examples if needed
53+
- [ ] Update README.md (if user-facing)
54+
- [ ] Add inline code comments for complex logic
55+
56+
### 5. Testing
57+
- [ ] Test core function independently
58+
- [ ] Happy path with valid inputs
59+
- [ ] Error cases and edge cases
60+
- [ ] Boundary conditions
61+
- [ ] Test API endpoint (if applicable)
62+
- [ ] Valid requests return expected responses
63+
- [ ] Invalid requests return appropriate errors
64+
- [ ] Pagination works correctly (if applicable)
65+
- [ ] Filtering works correctly (if applicable)
66+
- [ ] Response format matches standard envelope
67+
- [ ] Test CLI command (if applicable)
68+
- [ ] Valid arguments produce expected output
69+
- [ ] Invalid arguments show helpful errors
70+
- [ ] Both text and JSON output formats work
71+
- [ ] Help text is clear and accurate
72+
73+
### 6. Validation
74+
- [ ] CLI and API produce identical results for equivalent inputs
75+
- [ ] Error messages are consistent between CLI and API
76+
- [ ] Feature behavior is documented
77+
- [ ] No duplicate business logic between layers
78+
79+
## Architecture Compliance
80+
81+
### ✅ Good Patterns
82+
- Core function contains all business logic
83+
- CLI command calls core function, only handles formatting
84+
- API route calls core function, only handles HTTP concerns
85+
- Validation happens in both route/command AND core function
86+
- Errors use typed error classes (`ForestError` hierarchy)
87+
88+
### ❌ Anti-Patterns to Avoid
89+
- Business logic implemented in CLI command or API route
90+
- Different validation logic in CLI vs API
91+
- Different error handling in CLI vs API
92+
- Direct database access from routes/commands (should go through core)
93+
- Copy-pasted code between CLI and API
94+
95+
## Example: Semantic Search Feature
96+
97+
**Core Function** (`src/core/search.ts`):
98+
```typescript
99+
export async function semanticSearchCore(
100+
query: string,
101+
options: SemanticSearchOptions = {},
102+
): Promise<SemanticSearchResult>
103+
```
104+
105+
**API Route** (`src/server/routes/search.ts`):
106+
```typescript
107+
app.get('/api/v1/search/semantic', async ({ query }) => {
108+
const result = await semanticSearchCore(query.q, { ... });
109+
return createSuccessResponse({ nodes: result.nodes, ... });
110+
});
111+
```
112+
113+
**CLI Command** (`src/cli/commands/search.ts`):
114+
```typescript
115+
export function createSearchCommand(clerc) {
116+
return clerc.defineCommand({ name: 'search' }, async ({ flags }) => {
117+
const result = await semanticSearchCore(flags.query, { ... });
118+
printTextResults(result); // or JSON.stringify for --json
119+
});
120+
}
121+
```
122+
123+
## Notes
124+
125+
- If a feature only makes sense in one interface (CLI or API), that's okay! Not everything needs to be in both.
126+
- When in doubt, put logic in the core layer. It's easier to extract than to consolidate later.
127+
- Keep the API and CLI in sync by always implementing both at the same time when appropriate.

0 commit comments

Comments
 (0)