codebook-strategy 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 codebook-strategy contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # codebook-strategy
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Scaffold a structured context system for LLM-assisted development.** Give your AI the *right* context, not *all* the context.
4
+
5
+ ```bash
6
+ npx codebook-strategy init
7
+ ```
8
+
9
+ Then tell your coding assistant:
10
+
11
+ > **"Implement the book strategy"**
12
+
13
+ It scans your codebase once and writes a compact "book" that it reads on every future session — instead of re-crawling every file.
14
+
15
+ ---
16
+
17
+ ## The problem
18
+
19
+ LLM coding assistants waste tokens. Ask one to fix a bug and it often reads dozens of files just to rebuild an understanding of your project it threw away when the last session ended. That is slow, expensive, and the context it gathers is mostly noise for the task at hand.
20
+
21
+ ## The solution
22
+
23
+ A **book**: four kinds of file that live in your repo and give the assistant a map it can read cheaply, loading deep detail only for the feature it's actually touching.
24
+
25
+ ```
26
+ book/
27
+ PREFACE.md always read — project-wide patterns
28
+ INDEX.md always read — every feature and its status
29
+ CONNECTIONS.md always read — how features depend on each other
30
+ chapters/
31
+ <feature>.md read on demand — deep context + key files for one feature
32
+ ```
33
+
34
+ The three top-level files are small and always loaded. Chapters are detailed but only read when relevant. The assistant goes:
35
+
36
+ **preface → index → connections → the one or two chapters that matter → the actual source files those chapters point to.**
37
+
38
+ ### The four files
39
+
40
+ - **PREFACE.md** — Cross-cutting patterns that apply everywhere: tech stack, auth, error handling, logging, API and database conventions, testing. Chapters only note where they *deviate* from the preface.
41
+ - **INDEX.md** — A table of every feature/module: name, status, last updated, one-liner. This is how the assistant decides which chapters to open.
42
+ - **CONNECTIONS.md** — Topic-level relationships between features (`auth/tenant → billing/invoices`). This is the blast-radius map: what else might break if you change something.
43
+ - **chapters/** — One file per feature. Architecture, key files, known issues, recent changes, and a "don't bother reading" list of dead code and fixtures.
44
+
45
+ ## The three protocols
46
+
47
+ The strategy is enforced by instructions injected into your assistant's config file (`CLAUDE.md`, `.cursorrules`, or `AGENTS.md`):
48
+
49
+ 1. **Reading order** — Always preface → index → connections → relevant chapters → source. Never crawl the whole codebase.
50
+ 2. **Mismatch protocol** — If the book and the code disagree, *stop* and surface both to you. A stale book gets updated; wrong code might be the actual bug.
51
+ 3. **Checkpoint protocol** — If a feature or topic isn't in the book, the assistant asks whether to document it after resolving your request — so the book grows as you work.
52
+
53
+ ## How the book matures
54
+
55
+ It starts as structure and becomes knowledge. `init` lays down empty templates. The bootstrap pass fills them from your current codebase. From then on, every time the assistant touches an undocumented corner, the checkpoint protocol nudges it to write that corner down. Over weeks the book accumulates the hard-won context that normally lives only in senior engineers' heads.
56
+
57
+ ## Commands
58
+
59
+ ### `init`
60
+
61
+ ```bash
62
+ npx codebook-strategy init [--force]
63
+ ```
64
+
65
+ - Confirms you're in a project (looks for `package.json`, `.git`, or `src/`).
66
+ - Detects your LLM tooling and injects the strategy into the right config file:
67
+ - `CLAUDE.md` / `.claude/` → **Claude Code**
68
+ - `.cursorrules` / `.cursor/` → **Cursor**
69
+ - `AGENTS.md` → **Amp / Warp**
70
+ - none detected → creates all three
71
+ - Scaffolds `book/` with `PREFACE.md`, `INDEX.md`, `CONNECTIONS.md`, and `chapters/`.
72
+ - Existing config files are **appended to**, never overwritten. Existing book files are left untouched unless you pass `--force`.
73
+
74
+ ### `status`
75
+
76
+ ```bash
77
+ npx codebook-strategy status
78
+ ```
79
+
80
+ Shows which book files exist, when each was last modified, how many chapters there are, and warns if `INDEX.md` lists a chapter that has no file.
81
+
82
+ ### `validate`
83
+
84
+ ```bash
85
+ npx codebook-strategy validate
86
+ ```
87
+
88
+ Checks the book for consistency:
89
+
90
+ - every chapter file has an `INDEX.md` entry, and vice versa
91
+ - `CONNECTIONS.md` only references chapters that exist
92
+
93
+ Prints a warning for each mismatch and exits non-zero if any are found, so it fits in CI.
94
+
95
+ ## Works with
96
+
97
+ Claude Code, Cursor, Amp, Warp — and any LLM tool that reads a project config file. The book itself is just markdown, so any assistant you point at it can follow along.
98
+
99
+ ## Design notes
100
+
101
+ Zero dependencies. Node.js built-ins only. No build step. The whole tool is plain JavaScript you can read in a few minutes.
102
+
103
+ ## License
104
+
105
+ MIT
package/bin/cli.js ADDED
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const init = require('../src/commands/init');
5
+ const status = require('../src/commands/status');
6
+ const validate = require('../src/commands/validate');
7
+ const { red, bold, dim } = require('../src/utils/colors');
8
+
9
+ const HELP = `
10
+ ${bold('codebook-strategy')} — a structured context system for LLM-assisted development
11
+
12
+ ${bold('Usage')}
13
+ npx codebook-strategy <command> [options]
14
+
15
+ ${bold('Commands')}
16
+ init Scaffold the /book/ directory and inject strategy instructions
17
+ status Show which book files exist and their state
18
+ validate Check the book for index/chapter/connection mismatches
19
+
20
+ ${bold('Options for init')}
21
+ --force Overwrite an existing book/ directory
22
+
23
+ ${bold('After init')}
24
+ Tell your LLM: ${dim('"Implement the book strategy"')}
25
+ `;
26
+
27
+ function main(argv) {
28
+ const args = argv.slice(2);
29
+ const command = args[0];
30
+ const rest = args.slice(1);
31
+
32
+ switch (command) {
33
+ case 'init':
34
+ return init(rest);
35
+ case 'status':
36
+ return status(rest);
37
+ case 'validate':
38
+ return validate(rest);
39
+ case '-h':
40
+ case '--help':
41
+ case 'help':
42
+ case undefined:
43
+ process.stdout.write(HELP + '\n');
44
+ return 0;
45
+ default:
46
+ process.stderr.write(red(`Unknown command: ${command}`) + '\n');
47
+ process.stdout.write(HELP + '\n');
48
+ return 1;
49
+ }
50
+ }
51
+
52
+ const code = main(process.argv);
53
+ process.exit(typeof code === 'number' ? code : 0);
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "codebook-strategy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Scaffold a structured context system for LLM-assisted development. Minimize token usage by giving your AI the right context, not all the context.",
5
+ "bin": {
6
+ "codebook-strategy": "bin/cli.js"
7
+ },
8
+ "keywords": [
9
+ "llm",
10
+ "context",
11
+ "ai",
12
+ "claude",
13
+ "cursor",
14
+ "coding-assistant",
15
+ "prompt-engineering",
16
+ "developer-tools",
17
+ "codebook"
18
+ ],
19
+ "author": "Shrey Tandel",
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/shrey-tandel/codebook-strategy.git"
24
+ },
25
+ "bugs": {
26
+ "url": "https://github.com/shrey-tandel/codebook-strategy/issues"
27
+ },
28
+ "homepage": "https://github.com/shrey-tandel/codebook-strategy#readme",
29
+ "engines": {
30
+ "node": ">=16.0.0"
31
+ },
32
+ "files": [
33
+ "bin/",
34
+ "src/",
35
+ "templates/"
36
+ ]
37
+ }
@@ -0,0 +1,141 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ const { isProject, detectTargets } = require('../utils/detect-environment');
7
+ const {
8
+ exists,
9
+ ensureDir,
10
+ writeIfAbsent,
11
+ appendSection,
12
+ removeDir,
13
+ } = require('../utils/file-writer');
14
+ const { green, yellow, red, cyan, bold, dim } = require('../utils/colors');
15
+
16
+ const TEMPLATES = path.join(__dirname, '..', '..', 'templates');
17
+ // Any config file that already contains this marker is considered to already
18
+ // have the strategy injected.
19
+ const STRATEGY_MARKER = 'Codebook Strategy';
20
+
21
+ // The book files that get scaffolded, relative to the book/ directory.
22
+ const BOOK_FILES = ['PREFACE.md', 'INDEX.md', 'CONNECTIONS.md'];
23
+
24
+ function read(templatePath) {
25
+ return fs.readFileSync(path.join(TEMPLATES, templatePath), 'utf8');
26
+ }
27
+
28
+ function init(args) {
29
+ const force = args.includes('--force');
30
+ const cwd = process.cwd();
31
+
32
+ if (!isProject(cwd)) {
33
+ process.stderr.write(
34
+ red('This does not look like a project directory.') +
35
+ '\n' +
36
+ dim('Expected a package.json, .git, or src/ here. Run init from your project root.') +
37
+ '\n'
38
+ );
39
+ return 1;
40
+ }
41
+
42
+ const bookDir = path.join(cwd, 'book');
43
+
44
+ // Handle an existing book/ directory.
45
+ if (exists(bookDir)) {
46
+ if (force) {
47
+ removeDir(bookDir);
48
+ process.stdout.write(yellow('Removed existing book/ (--force).') + '\n');
49
+ } else {
50
+ process.stdout.write(
51
+ yellow('book/ already exists. ') +
52
+ dim('Re-run with --force to overwrite, or leave it as is.') +
53
+ '\n'
54
+ );
55
+ // Still run config injection below — that part is append-safe — but do
56
+ // not touch existing book files.
57
+ }
58
+ }
59
+
60
+ // --- Scaffold the book directory --------------------------------------
61
+ ensureDir(bookDir);
62
+ ensureDir(path.join(bookDir, 'chapters'));
63
+
64
+ const bookResults = [];
65
+ for (const name of BOOK_FILES) {
66
+ const result = writeIfAbsent(
67
+ path.join(bookDir, name),
68
+ read(path.join('book', name))
69
+ );
70
+ bookResults.push({ name: `book/${name}`, result });
71
+ }
72
+ // Keep the chapters directory tracked even when empty.
73
+ const keepResult = writeIfAbsent(
74
+ path.join(bookDir, 'chapters', '.gitkeep'),
75
+ ''
76
+ );
77
+ bookResults.push({ name: 'book/chapters/', result: keepResult });
78
+
79
+ // --- Inject strategy into config files --------------------------------
80
+ const { detected, targets } = detectTargets(cwd);
81
+
82
+ const configResults = [];
83
+ for (const target of targets) {
84
+ const section = read(target.template);
85
+ const filePath = path.join(cwd, target.file);
86
+ const result = appendSection(filePath, section, STRATEGY_MARKER);
87
+ configResults.push({ tool: target.tool, file: target.file, result });
88
+ }
89
+
90
+ // --- Report -----------------------------------------------------------
91
+ process.stdout.write('\n' + bold('Codebook Strategy initialized') + '\n\n');
92
+
93
+ process.stdout.write(bold('Book files') + '\n');
94
+ for (const { name, result } of bookResults) {
95
+ process.stdout.write(' ' + formatResult(result) + ' ' + name + '\n');
96
+ }
97
+
98
+ process.stdout.write('\n' + bold('Config files') + '\n');
99
+ if (detected) {
100
+ process.stdout.write(
101
+ dim(' Detected existing LLM tooling; injected into:') + '\n'
102
+ );
103
+ } else {
104
+ process.stdout.write(
105
+ dim(' No LLM tooling detected; created all three config files:') + '\n'
106
+ );
107
+ }
108
+ for (const { tool, file, result } of configResults) {
109
+ process.stdout.write(
110
+ ' ' + formatResult(result) + ' ' + file + dim(` (${tool})`) + '\n'
111
+ );
112
+ }
113
+
114
+ process.stdout.write('\n' + bold('Next steps') + '\n');
115
+ process.stdout.write(
116
+ ' 1. Open your LLM coding tool in this project.\n' +
117
+ ' 2. Tell it: ' +
118
+ cyan('"Implement the book strategy"') +
119
+ '\n' +
120
+ ' 3. It will scan the codebase and fill in the book.\n\n'
121
+ );
122
+
123
+ return 0;
124
+ }
125
+
126
+ function formatResult(result) {
127
+ switch (result) {
128
+ case 'created':
129
+ return green('created ');
130
+ case 'appended':
131
+ return green('appended');
132
+ case 'skipped':
133
+ return yellow('skipped ');
134
+ case 'present':
135
+ return yellow('present ');
136
+ default:
137
+ return dim(result);
138
+ }
139
+ }
140
+
141
+ module.exports = init;
@@ -0,0 +1,91 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ const { exists } = require('../utils/file-writer');
7
+
8
+ // List real chapter markdown files in book/chapters/, ignoring dotfiles.
9
+ function listChapters(bookDir) {
10
+ const dir = path.join(bookDir, 'chapters');
11
+ if (!exists(dir)) return [];
12
+ return fs
13
+ .readdirSync(dir)
14
+ .filter((f) => f.endsWith('.md') && !f.startsWith('.'))
15
+ .sort();
16
+ }
17
+
18
+ // Extract chapter names from the INDEX.md table.
19
+ //
20
+ // The table has the form:
21
+ // | Chapter | Status | Last Updated | One-liner |
22
+ // |---------|--------|-------------|-----------|
23
+ // | auth | active | 2026-01-01 | ... |
24
+ //
25
+ // The first column holds the chapter name. HTML-comment placeholder rows
26
+ // (the template's example row) are ignored.
27
+ function parseIndexChapters(content) {
28
+ const names = [];
29
+ const lines = content.split('\n');
30
+ for (const line of lines) {
31
+ const trimmed = line.trim();
32
+ if (!trimmed.startsWith('|')) continue;
33
+
34
+ const cells = trimmed
35
+ .split('|')
36
+ .slice(1, -1)
37
+ .map((c) => c.trim());
38
+ if (cells.length === 0) continue;
39
+
40
+ const first = cells[0];
41
+ if (!first) continue;
42
+ // Skip header and separator rows.
43
+ if (/^chapter$/i.test(first)) continue;
44
+ if (/^:?-{3,}:?$/.test(first)) continue;
45
+ // Skip placeholder/comment rows from the template.
46
+ if (first.startsWith('<!--')) continue;
47
+
48
+ names.push(first);
49
+ }
50
+ return names;
51
+ }
52
+
53
+ // Extract topic references from CONNECTIONS.md lines of the form:
54
+ // source/topic -> target/topic : reason
55
+ // source/topic <-> target/topic : reason
56
+ // (using the ASCII or unicode arrows). Lines inside HTML comments are ignored.
57
+ //
58
+ // Returns [{ chapter, topic, raw }] — one entry per side of each connection.
59
+ function parseConnectionTopics(content) {
60
+ const topics = [];
61
+ const withoutComments = content.replace(/<!--[\s\S]*?-->/g, '');
62
+ const lines = withoutComments.split('\n');
63
+
64
+ for (const line of lines) {
65
+ const trimmed = line.trim();
66
+ if (!trimmed || trimmed.startsWith('>') || trimmed.startsWith('#')) continue;
67
+ if (!/(↔|→|<->|->)/.test(trimmed)) continue;
68
+
69
+ // Drop the reason after the first colon.
70
+ const beforeReason = trimmed.split(':')[0];
71
+ const sides = beforeReason.split(/↔|→|<->|->/);
72
+ for (const side of sides) {
73
+ const ref = side.trim();
74
+ if (!ref) continue;
75
+ const [chapter, topic] = ref.split('/');
76
+ if (!chapter) continue;
77
+ topics.push({
78
+ chapter: chapter.trim(),
79
+ topic: (topic || '').trim(),
80
+ raw: ref,
81
+ });
82
+ }
83
+ }
84
+ return topics;
85
+ }
86
+
87
+ module.exports = {
88
+ listChapters,
89
+ parseIndexChapters,
90
+ parseConnectionTopics,
91
+ };
@@ -0,0 +1,88 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ const { exists } = require('../utils/file-writer');
7
+ const { green, yellow, red, dim, bold } = require('../utils/colors');
8
+ const { listChapters, parseIndexChapters } = require('./shared');
9
+
10
+ function fmtDate(d) {
11
+ // YYYY-MM-DD HH:MM, local time.
12
+ const pad = (n) => String(n).padStart(2, '0');
13
+ return (
14
+ `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ` +
15
+ `${pad(d.getHours())}:${pad(d.getMinutes())}`
16
+ );
17
+ }
18
+
19
+ function status() {
20
+ const cwd = process.cwd();
21
+ const bookDir = path.join(cwd, 'book');
22
+
23
+ if (!exists(bookDir)) {
24
+ process.stderr.write(
25
+ red('No book/ directory found.') +
26
+ '\n' +
27
+ dim('Run `npx codebook-strategy init` first.') +
28
+ '\n'
29
+ );
30
+ return 1;
31
+ }
32
+
33
+ process.stdout.write('\n' + bold('Codebook status') + '\n\n');
34
+
35
+ const coreFiles = ['PREFACE.md', 'INDEX.md', 'CONNECTIONS.md'];
36
+ process.stdout.write(bold('Core files') + '\n');
37
+ for (const name of coreFiles) {
38
+ const p = path.join(bookDir, name);
39
+ if (exists(p)) {
40
+ const stat = fs.statSync(p);
41
+ process.stdout.write(
42
+ ' ' + green('present') + ' ' + name + dim(` (modified ${fmtDate(stat.mtime)})`) + '\n'
43
+ );
44
+ } else {
45
+ process.stdout.write(' ' + red('missing') + ' ' + name + '\n');
46
+ }
47
+ }
48
+
49
+ // Chapters on disk.
50
+ const chapters = listChapters(bookDir);
51
+ process.stdout.write('\n' + bold('Chapters') + '\n');
52
+ if (chapters.length === 0) {
53
+ process.stdout.write(dim(' No chapters yet.') + '\n');
54
+ } else {
55
+ for (const ch of chapters) {
56
+ const stat = fs.statSync(path.join(bookDir, 'chapters', ch));
57
+ process.stdout.write(
58
+ ' ' + green('•') + ' ' + ch + dim(` (modified ${fmtDate(stat.mtime)})`) + '\n'
59
+ );
60
+ }
61
+ process.stdout.write(dim(` ${chapters.length} chapter(s) total.`) + '\n');
62
+ }
63
+
64
+ // Warn about index entries that have no matching chapter file.
65
+ const indexPath = path.join(bookDir, 'INDEX.md');
66
+ if (exists(indexPath)) {
67
+ const indexNames = parseIndexChapters(fs.readFileSync(indexPath, 'utf8'));
68
+ const chapterBaseNames = chapters.map((c) => c.replace(/\.md$/i, ''));
69
+ const orphans = indexNames.filter(
70
+ (n) => !chapterBaseNames.includes(n)
71
+ );
72
+ if (orphans.length > 0) {
73
+ process.stdout.write('\n' + bold('Warnings') + '\n');
74
+ for (const name of orphans) {
75
+ process.stdout.write(
76
+ ' ' +
77
+ yellow('!') +
78
+ ` INDEX.md lists "${name}" but book/chapters/${name}.md does not exist\n`
79
+ );
80
+ }
81
+ }
82
+ }
83
+
84
+ process.stdout.write('\n');
85
+ return 0;
86
+ }
87
+
88
+ module.exports = status;
@@ -0,0 +1,93 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ const { exists } = require('../utils/file-writer');
7
+ const { green, yellow, red, dim, bold } = require('../utils/colors');
8
+ const {
9
+ listChapters,
10
+ parseIndexChapters,
11
+ parseConnectionTopics,
12
+ } = require('./shared');
13
+
14
+ function validate() {
15
+ const cwd = process.cwd();
16
+ const bookDir = path.join(cwd, 'book');
17
+
18
+ if (!exists(bookDir)) {
19
+ process.stderr.write(
20
+ red('No book/ directory found.') +
21
+ '\n' +
22
+ dim('Run `npx codebook-strategy init` first.') +
23
+ '\n'
24
+ );
25
+ return 1;
26
+ }
27
+
28
+ const warnings = [];
29
+
30
+ const chapters = listChapters(bookDir);
31
+ const chapterBaseNames = chapters.map((c) => c.replace(/\.md$/i, ''));
32
+
33
+ // INDEX.md <-> chapter files
34
+ const indexPath = path.join(bookDir, 'INDEX.md');
35
+ let indexNames = [];
36
+ if (exists(indexPath)) {
37
+ indexNames = parseIndexChapters(fs.readFileSync(indexPath, 'utf8'));
38
+ } else {
39
+ warnings.push('INDEX.md is missing.');
40
+ }
41
+
42
+ for (const name of indexNames) {
43
+ if (!chapterBaseNames.includes(name)) {
44
+ warnings.push(
45
+ `INDEX.md lists "${name}" but book/chapters/${name}.md does not exist.`
46
+ );
47
+ }
48
+ }
49
+ for (const base of chapterBaseNames) {
50
+ if (!indexNames.includes(base)) {
51
+ warnings.push(
52
+ `book/chapters/${base}.md exists but is not listed in INDEX.md.`
53
+ );
54
+ }
55
+ }
56
+
57
+ // CONNECTIONS.md references chapters that exist.
58
+ const connPath = path.join(bookDir, 'CONNECTIONS.md');
59
+ if (exists(connPath)) {
60
+ const topics = parseConnectionTopics(fs.readFileSync(connPath, 'utf8'));
61
+ const known = new Set([...chapterBaseNames, ...indexNames]);
62
+ for (const topic of topics) {
63
+ if (!known.has(topic.chapter)) {
64
+ warnings.push(
65
+ `CONNECTIONS.md references chapter "${topic.chapter}" (in "${topic.raw}") ` +
66
+ `which is not a known chapter.`
67
+ );
68
+ }
69
+ }
70
+ } else {
71
+ warnings.push('CONNECTIONS.md is missing.');
72
+ }
73
+
74
+ // Report
75
+ process.stdout.write('\n' + bold('Codebook validation') + '\n\n');
76
+ if (warnings.length === 0) {
77
+ process.stdout.write(
78
+ ' ' + green('✓') + ' No problems found. The book is consistent.\n\n'
79
+ );
80
+ return 0;
81
+ }
82
+
83
+ for (const w of warnings) {
84
+ process.stdout.write(' ' + yellow('!') + ' ' + w + '\n');
85
+ }
86
+ process.stdout.write(
87
+ '\n' + dim(` ${warnings.length} warning(s).`) + '\n\n'
88
+ );
89
+ // Mismatches are warnings, not hard failures; exit non-zero so CI can catch them.
90
+ return 1;
91
+ }
92
+
93
+ module.exports = validate;
@@ -0,0 +1,26 @@
1
+ 'use strict';
2
+
3
+ // Minimal ANSI coloring. No dependencies. Disables itself when output is not a
4
+ // TTY or when NO_COLOR is set, so piped/redirected output stays clean.
5
+
6
+ const enabled =
7
+ process.env.NO_COLOR === undefined &&
8
+ process.env.TERM !== 'dumb' &&
9
+ Boolean(process.stdout && process.stdout.isTTY);
10
+
11
+ function wrap(open, close) {
12
+ return function (str) {
13
+ if (!enabled) return String(str);
14
+ return `\u001b[${open}m${str}\u001b[${close}m`;
15
+ };
16
+ }
17
+
18
+ module.exports = {
19
+ enabled,
20
+ green: wrap(32, 39),
21
+ yellow: wrap(33, 39),
22
+ red: wrap(31, 39),
23
+ cyan: wrap(36, 39),
24
+ dim: wrap(2, 22),
25
+ bold: wrap(1, 22),
26
+ };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const { exists } = require('./file-writer');
5
+
6
+ // Decide whether the current working directory looks like a real project.
7
+ function isProject(cwd) {
8
+ return (
9
+ exists(path.join(cwd, 'package.json')) ||
10
+ exists(path.join(cwd, '.git')) ||
11
+ exists(path.join(cwd, 'src'))
12
+ );
13
+ }
14
+
15
+ // Detect which LLM tool config files/directories are present.
16
+ // Returns a list of target descriptors. Each descriptor names the config file
17
+ // the strategy should be injected into and the template it comes from.
18
+ //
19
+ // If nothing is detected, all three targets are returned so the book works with
20
+ // whichever tool the developer uses.
21
+ function detectTargets(cwd) {
22
+ const claude =
23
+ exists(path.join(cwd, 'CLAUDE.md')) || exists(path.join(cwd, '.claude'));
24
+ const cursor =
25
+ exists(path.join(cwd, '.cursorrules')) || exists(path.join(cwd, '.cursor'));
26
+ const agents = exists(path.join(cwd, 'AGENTS.md'));
27
+
28
+ const all = {
29
+ claude: { tool: 'Claude Code', file: 'CLAUDE.md', template: 'CLAUDE.md' },
30
+ cursor: { tool: 'Cursor', file: '.cursorrules', template: 'cursorrules' },
31
+ agents: { tool: 'Amp/Warp', file: 'AGENTS.md', template: 'AGENTS.md' },
32
+ };
33
+
34
+ const detected = [];
35
+ if (claude) detected.push(all.claude);
36
+ if (cursor) detected.push(all.cursor);
37
+ if (agents) detected.push(all.agents);
38
+
39
+ if (detected.length > 0) {
40
+ return { detected: true, targets: detected };
41
+ }
42
+
43
+ return { detected: false, targets: [all.claude, all.cursor, all.agents] };
44
+ }
45
+
46
+ module.exports = {
47
+ isProject,
48
+ detectTargets,
49
+ };
@@ -0,0 +1,64 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ // Safe filesystem helpers. Nothing here overwrites existing content unless the
7
+ // caller explicitly opts in.
8
+
9
+ function exists(p) {
10
+ try {
11
+ fs.accessSync(p);
12
+ return true;
13
+ } catch (_) {
14
+ return false;
15
+ }
16
+ }
17
+
18
+ function ensureDir(dir) {
19
+ fs.mkdirSync(dir, { recursive: true });
20
+ }
21
+
22
+ // Write a file only if it does not already exist.
23
+ // Returns 'created' or 'skipped'.
24
+ function writeIfAbsent(filePath, content) {
25
+ if (exists(filePath)) return 'skipped';
26
+ ensureDir(path.dirname(filePath));
27
+ fs.writeFileSync(filePath, content);
28
+ return 'created';
29
+ }
30
+
31
+ // Append a section to a file, creating the file if it is absent.
32
+ // A separator is inserted before the section when the file already has content.
33
+ // Returns 'created' or 'appended'. If the section marker is already present,
34
+ // returns 'present' and writes nothing.
35
+ function appendSection(filePath, section, marker) {
36
+ if (!exists(filePath)) {
37
+ ensureDir(path.dirname(filePath));
38
+ fs.writeFileSync(filePath, section.replace(/^\n+/, ''));
39
+ return 'created';
40
+ }
41
+
42
+ const current = fs.readFileSync(filePath, 'utf8');
43
+ if (marker && current.indexOf(marker) !== -1) {
44
+ return 'present';
45
+ }
46
+
47
+ const needsNewline = current.length > 0 && !current.endsWith('\n');
48
+ const separator = `${needsNewline ? '\n' : ''}\n---\n\n`;
49
+ fs.appendFileSync(filePath, separator + section.replace(/^\n+/, ''));
50
+ return 'appended';
51
+ }
52
+
53
+ // Remove a directory and everything in it.
54
+ function removeDir(dir) {
55
+ fs.rmSync(dir, { recursive: true, force: true });
56
+ }
57
+
58
+ module.exports = {
59
+ exists,
60
+ ensureDir,
61
+ writeIfAbsent,
62
+ appendSection,
63
+ removeDir,
64
+ };
@@ -0,0 +1,64 @@
1
+ # Codebook Strategy
2
+
3
+ This project uses a structured context system called the Codebook Strategy.
4
+ DO NOT crawl the full codebase to understand the project. Follow the book.
5
+
6
+ ## Reading Order
7
+
8
+ Every session, follow this exact order:
9
+
10
+ 1. Read `/book/PREFACE.md` — project-wide patterns that apply everywhere
11
+ 2. Read `/book/INDEX.md` — understand what features exist and their status
12
+ 3. Read `/book/CONNECTIONS.md` — find related topics based on the user's question
13
+ 4. Read ONLY the relevant chapters from `/book/chapters/` — deep context + key files
14
+ 5. Read the actual source files listed in those chapters
15
+
16
+ ## How to Identify Relevant Chapters
17
+
18
+ From the user's question, identify which feature(s) are involved.
19
+ Check CONNECTIONS.md for that feature. Load any topic-to-topic connection
20
+ that is relevant to the current question. Skip connections that clearly
21
+ don't apply to the current task.
22
+
23
+ ## Mismatch Protocol
24
+
25
+ If you find a contradiction between the book and the code:
26
+
27
+ 1. STOP — do not proceed with the original task
28
+ 2. Surface both versions to the developer
29
+ 3. Ask: "Book says X, code says Y. Which is correct?"
30
+ 4. If the book is stale → update the book, then continue
31
+ 5. If the code is wrong → that might be the actual bug
32
+
33
+ ## Checkpoint Protocol
34
+
35
+ If you're working on something not covered by the book:
36
+
37
+ **Missing chapter:** "This feature isn't in the book. Should I update the index and create a chapter after resolving?"
38
+
39
+ **Missing topic:** "This topic isn't covered in the chapter. Should I update it after resolving?"
40
+
41
+ After resolving the user's question, and if they approved:
42
+ - Create or update the relevant chapter
43
+ - Update INDEX.md if a new chapter was added
44
+ - Update CONNECTIONS.md if new relationships were discovered
45
+
46
+ ## Bootstrap Command
47
+
48
+ If the user says "Implement the book strategy" or "Bootstrap the book":
49
+
50
+ 1. Scan the entire codebase
51
+ 2. Identify cross-cutting patterns → write PREFACE.md
52
+ 3. Identify features/modules → create chapters with topics, key files
53
+ 4. Populate INDEX.md with all discovered features
54
+ 5. Map dependencies between features → write CONNECTIONS.md
55
+ 6. Chapters should include: architecture, key files, known issues, recent changes
56
+ 7. Chapters should list "Don't bother reading" files (dead code, legacy, test fixtures)
57
+
58
+ ## DO NOT
59
+
60
+ - Read every file in the codebase to understand the project
61
+ - Load chapters unrelated to the user's issue
62
+ - Skip the CONNECTIONS.md check before making changes
63
+ - Silently bypass the book — if something is missing, use the checkpoint protocol
64
+ - Trust the book over the code without flagging mismatches
@@ -0,0 +1,64 @@
1
+ ## Codebook Strategy
2
+
3
+ This project uses a structured context system called the Codebook Strategy.
4
+ DO NOT crawl the full codebase to understand the project. Follow the book.
5
+
6
+ ### Reading Order
7
+
8
+ Every session, follow this exact order:
9
+
10
+ 1. Read `/book/PREFACE.md` — project-wide patterns that apply everywhere
11
+ 2. Read `/book/INDEX.md` — understand what features exist and their status
12
+ 3. Read `/book/CONNECTIONS.md` — find related topics based on the user's question
13
+ 4. Read ONLY the relevant chapters from `/book/chapters/` — deep context + key files
14
+ 5. Read the actual source files listed in those chapters
15
+
16
+ ### How to Identify Relevant Chapters
17
+
18
+ From the user's question, identify which feature(s) are involved.
19
+ Check CONNECTIONS.md for that feature. Load any topic-to-topic connection
20
+ that is relevant to the current question. Skip connections that clearly
21
+ don't apply to the current task.
22
+
23
+ ### Mismatch Protocol
24
+
25
+ If you find a contradiction between the book and the code:
26
+
27
+ 1. STOP — do not proceed with the original task
28
+ 2. Surface both versions to the developer
29
+ 3. Ask: "Book says X, code says Y. Which is correct?"
30
+ 4. If the book is stale → update the book, then continue
31
+ 5. If the code is wrong → that might be the actual bug
32
+
33
+ ### Checkpoint Protocol
34
+
35
+ If you're working on something not covered by the book:
36
+
37
+ **Missing chapter:** "This feature isn't in the book. Should I update the index and create a chapter after resolving?"
38
+
39
+ **Missing topic:** "This topic isn't covered in the chapter. Should I update it after resolving?"
40
+
41
+ After resolving the user's question, and if they approved:
42
+ - Create or update the relevant chapter
43
+ - Update INDEX.md if a new chapter was added
44
+ - Update CONNECTIONS.md if new relationships were discovered
45
+
46
+ ### Bootstrap Command
47
+
48
+ If the user says "Implement the book strategy" or "Bootstrap the book":
49
+
50
+ 1. Scan the entire codebase
51
+ 2. Identify cross-cutting patterns → write PREFACE.md
52
+ 3. Identify features/modules → create chapters with topics, key files
53
+ 4. Populate INDEX.md with all discovered features
54
+ 5. Map dependencies between features → write CONNECTIONS.md
55
+ 6. Chapters should include: architecture, key files, known issues, recent changes
56
+ 7. Chapters should list "Don't bother reading" files (dead code, legacy, test fixtures)
57
+
58
+ ### DO NOT
59
+
60
+ - Read every file in the codebase to understand the project
61
+ - Load chapters unrelated to the user's issue
62
+ - Skip the CONNECTIONS.md check before making changes
63
+ - Silently bypass the book — if something is missing, use the checkpoint protocol
64
+ - Trust the book over the code without flagging mismatches
@@ -0,0 +1,14 @@
1
+ # Connections
2
+
3
+ > This file maps relationships between features at the topic level.
4
+ > It is always loaded at the start of every session.
5
+ > Use it to identify blast radius before making changes.
6
+ >
7
+ > Format: source/topic → target/topic : reason for connection
8
+ > Use ↔ for bidirectional, → for one-way dependencies
9
+
10
+ <!-- Example:
11
+ call-ingestion/storage-schema ↔ reporting/queries : shared call_records table
12
+ call-ingestion/webhook-handling → auth/tenant-resolution : every webhook resolves tenant
13
+ call-ingestion/caching → reporting/dashboard-api : cache invalidation affects display
14
+ -->
@@ -0,0 +1,9 @@
1
+ # Index
2
+
3
+ > This file lists every feature/module in the project.
4
+ > It is always loaded at the start of every session.
5
+ > Use it to identify which chapters to read.
6
+
7
+ | Chapter | Status | Last Updated | One-liner |
8
+ |---------|--------|-------------|-----------|
9
+ | <!-- feature-name --> | <!-- active/stable/wip/not-started --> | <!-- date --> | <!-- brief description --> |
@@ -0,0 +1,37 @@
1
+ # Preface
2
+
3
+ > This file describes project-wide patterns that apply to every feature.
4
+ > It is always loaded at the start of every session.
5
+ > Chapters only document deviations from these patterns.
6
+
7
+ ## Tech Stack
8
+
9
+ <!-- What languages, frameworks, databases, and tools this project uses -->
10
+
11
+ ## Project Structure
12
+
13
+ <!-- High-level directory layout and what lives where -->
14
+
15
+ ## Authentication & Tenant Resolution
16
+
17
+ <!-- How auth works across the entire app -->
18
+
19
+ ## Error Handling
20
+
21
+ <!-- Standard error format, how exceptions are caught and logged -->
22
+
23
+ ## Logging
24
+
25
+ <!-- Logging conventions, what gets logged, log levels -->
26
+
27
+ ## API Conventions
28
+
29
+ <!-- Request/response format, naming conventions, versioning -->
30
+
31
+ ## Database Conventions
32
+
33
+ <!-- Naming, migrations, connection handling -->
34
+
35
+ ## Testing Conventions
36
+
37
+ <!-- Test framework, naming, what requires tests -->
@@ -0,0 +1,64 @@
1
+ # Codebook Strategy
2
+
3
+ This project uses a structured context system called the Codebook Strategy.
4
+ DO NOT crawl the full codebase to understand the project. Follow the book.
5
+
6
+ ## Reading Order
7
+
8
+ Every session, follow this exact order:
9
+
10
+ 1. Read `/book/PREFACE.md` — project-wide patterns that apply everywhere
11
+ 2. Read `/book/INDEX.md` — understand what features exist and their status
12
+ 3. Read `/book/CONNECTIONS.md` — find related topics based on the user's question
13
+ 4. Read ONLY the relevant chapters from `/book/chapters/` — deep context + key files
14
+ 5. Read the actual source files listed in those chapters
15
+
16
+ ## How to Identify Relevant Chapters
17
+
18
+ From the user's question, identify which feature(s) are involved.
19
+ Check CONNECTIONS.md for that feature. Load any topic-to-topic connection
20
+ that is relevant to the current question. Skip connections that clearly
21
+ don't apply to the current task.
22
+
23
+ ## Mismatch Protocol
24
+
25
+ If you find a contradiction between the book and the code:
26
+
27
+ 1. STOP — do not proceed with the original task
28
+ 2. Surface both versions to the developer
29
+ 3. Ask: "Book says X, code says Y. Which is correct?"
30
+ 4. If the book is stale → update the book, then continue
31
+ 5. If the code is wrong → that might be the actual bug
32
+
33
+ ## Checkpoint Protocol
34
+
35
+ If you're working on something not covered by the book:
36
+
37
+ Missing chapter: "This feature isn't in the book. Should I update the index and create a chapter after resolving?"
38
+
39
+ Missing topic: "This topic isn't covered in the chapter. Should I update it after resolving?"
40
+
41
+ After resolving the user's question, and if they approved:
42
+ - Create or update the relevant chapter
43
+ - Update INDEX.md if a new chapter was added
44
+ - Update CONNECTIONS.md if new relationships were discovered
45
+
46
+ ## Bootstrap Command
47
+
48
+ If the user says "Implement the book strategy" or "Bootstrap the book":
49
+
50
+ 1. Scan the entire codebase
51
+ 2. Identify cross-cutting patterns → write PREFACE.md
52
+ 3. Identify features/modules → create chapters with topics, key files
53
+ 4. Populate INDEX.md with all discovered features
54
+ 5. Map dependencies between features → write CONNECTIONS.md
55
+ 6. Chapters should include: architecture, key files, known issues, recent changes
56
+ 7. Chapters should list "Don't bother reading" files (dead code, legacy, test fixtures)
57
+
58
+ ## DO NOT
59
+
60
+ - Read every file in the codebase to understand the project
61
+ - Load chapters unrelated to the user's issue
62
+ - Skip the CONNECTIONS.md check before making changes
63
+ - Silently bypass the book — if something is missing, use the checkpoint protocol
64
+ - Trust the book over the code without flagging mismatches