sourcebook 0.1.0 → 0.4.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 CHANGED
@@ -1,21 +1,65 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 maroond
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.
1
+ Business Source License 1.1
2
+
3
+ Licensor: maroond labs
4
+
5
+ Licensed Work: sourcebook
6
+ The Licensed Work is (c) 2026 maroond labs
7
+
8
+ Additional Use Grant: You may make production use of the Licensed Work,
9
+ provided your use does not include offering the
10
+ Licensed Work to third parties as a commercial
11
+ code analysis or context generation service.
12
+
13
+ Change Date: 2030-03-25
14
+
15
+ Change License: MIT
16
+
17
+ For information about alternative licensing arrangements, contact
18
+ roy@maroond.ai.
19
+
20
+ Notice
21
+
22
+ Business Source License 1.1
23
+
24
+ Terms
25
+
26
+ The Licensor hereby grants you the right to copy, modify, create
27
+ derivative works, redistribute, and make non-production use of the
28
+ Licensed Work. The Licensor may make an Additional Use Grant, above,
29
+ permitting limited production use.
30
+
31
+ Effective on the Change Date, or the fourth anniversary of the first
32
+ publicly available distribution of a specific version of the Licensed
33
+ Work, whichever comes first, the Licensor hereby grants you rights
34
+ under the terms of the Change License, and the rights granted in the
35
+ paragraph above terminate.
36
+
37
+ If your use of the Licensed Work does not comply with the requirements
38
+ currently in effect as described in this License, you must purchase a
39
+ commercial license from the Licensor, its affiliated entities, or
40
+ authorized resellers, or you must refrain from using the Licensed Work.
41
+
42
+ All copies of the original and modified Licensed Work, and derivative
43
+ works of the Licensed Work, are subject to this License. This License
44
+ applies separately for each version of the Licensed Work and the
45
+ Change Date may vary for each version of the Licensed Work released by
46
+ Licensor.
47
+
48
+ You must conspicuously display this License on each original or
49
+ modified copy of the Licensed Work. If you receive the Licensed Work
50
+ in original or modified form from a third party, the terms and
51
+ conditions set forth in this License apply to your use of that work.
52
+
53
+ Any use of the Licensed Work in violation of this License will
54
+ automatically terminate your rights under this License for the current
55
+ and all other versions of the Licensed Work.
56
+
57
+ This License does not grant you any right in any trademark or logo of
58
+ Licensor or its affiliates (provided that you may use a trademark or
59
+ logo of Licensor as expressly required by this License).
60
+
61
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS
62
+ PROVIDED ON AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES
63
+ AND CONDITIONS, EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION)
64
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
65
+ NON-INFRINGEMENT, AND TITLE.
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
+ <p align="center">
2
+ <img src="logo.png" alt="sourcebook" width="120" />
3
+ </p>
4
+
1
5
  # sourcebook
2
6
 
3
7
  Generate AI context files from your codebase's actual conventions. Not what agents already know — what they keep missing.
@@ -23,10 +27,11 @@ sourcebook inverts the typical approach: instead of dumping everything, it extra
23
27
  ## What It Finds
24
28
 
25
29
  - **Import graph + PageRank** — ranks files by structural importance, identifies hub files with the widest blast radius
26
- - **Git history forensics** — reverted commits (literal "don't do this" signals), co-change coupling (invisible dependencies), rapid re-edits (code that was hard to get right)
27
- - **Convention detection** — naming patterns, export style, import organization, barrel exports, path aliases
28
- - **Framework detection** — Next.js, Expo, Supabase, Tailwind, Express, TypeScript configs
30
+ - **Git history forensics** — reverted commits ("don't do this" signals), co-change coupling (invisible dependencies), rapid re-edits (code that was hard to get right), anti-patterns from abandoned approaches
31
+ - **Convention detection** — naming patterns, export style, import organization, barrel exports, path aliases, type hint usage, error handling style
32
+ - **Framework detection** — Next.js, Expo, Supabase, Tailwind, Express, TypeScript, Django, FastAPI, Flask, Go (Gin, Echo, Fiber)
29
33
  - **Context-rot-aware formatting** — critical constraints at the top, reference info in the middle, action prompts at the bottom (optimized for LLM attention patterns)
34
+ - **Smart budget enforcement** — when context exceeds your token budget, drops low-priority sections first (keeps critical constraints always)
30
35
 
31
36
  ## Quick Start
32
37
 
@@ -34,54 +39,104 @@ sourcebook inverts the typical approach: instead of dumping everything, it extra
34
39
  # Generate CLAUDE.md for your project
35
40
  npx sourcebook init
36
41
 
37
- # Specify output format
42
+ # Generate for a specific tool
38
43
  npx sourcebook init --format claude # CLAUDE.md (default)
39
44
  npx sourcebook init --format cursor # .cursor/rules/sourcebook.mdc + .cursorrules
40
45
  npx sourcebook init --format copilot # .github/copilot-instructions.md
41
46
  npx sourcebook init --format all # All of the above
47
+
48
+ # Re-analyze while preserving your manual edits
49
+ npx sourcebook update
50
+
51
+ # See what changed since last generation (exit code 1 = changes found)
52
+ npx sourcebook diff
53
+
54
+ # Limit output to a token budget (drops low-priority sections first)
55
+ npx sourcebook init --budget 1000
56
+ ```
57
+
58
+ ## Commands
59
+
60
+ | Command | What it does |
61
+ |---------|-------------|
62
+ | `sourcebook init` | Analyze codebase and generate context files |
63
+ | `sourcebook update` | Re-analyze while preserving sections you added manually |
64
+ | `sourcebook diff` | Show what would change without writing files (exit code 1 if changes found — useful for CI) |
65
+
66
+ ### Options
67
+
68
+ | Flag | Description | Default |
69
+ |------|-------------|---------|
70
+ | `-d, --dir <path>` | Target directory | `.` |
71
+ | `-f, --format <formats>` | Output formats: `claude`, `cursor`, `copilot`, `all` | `claude` |
72
+ | `--budget <tokens>` | Max token budget for output | `4000` |
73
+ | `--dry-run` | Preview findings without writing files | — |
74
+
75
+ ## Language Support
76
+
77
+ | Language | Framework Detection | Convention Detection | Import Graph | Git Analysis |
78
+ |----------|:------------------:|:-------------------:|:------------:|:------------:|
79
+ | TypeScript/JavaScript | Next.js, Expo, Vite, React, Express, Tailwind, Supabase | Barrel exports, path aliases, export style, error handling | Full | Full |
80
+ | Python | Django, FastAPI, Flask, pytest | Type hints, `__init__.py` barrels | Full | Full |
81
+ | Go | Gin, Echo, Fiber | Module path, cmd/pkg/internal layout, error wrapping, interfaces | Full | Full |
82
+
83
+ ## GitHub Action
84
+
85
+ Auto-update context files on every merge:
86
+
87
+ ```yaml
88
+ # .github/workflows/sourcebook.yml
89
+ name: Update context files
90
+ on:
91
+ push:
92
+ branches: [main]
93
+
94
+ jobs:
95
+ sourcebook:
96
+ runs-on: ubuntu-latest
97
+ steps:
98
+ - uses: actions/checkout@v4
99
+ - uses: maroondlabs/sourcebook@main
100
+ with:
101
+ format: all
42
102
  ```
43
103
 
44
104
  ## Example Output
45
105
 
46
- Running `npx sourcebook init` on a real Expo + Supabase project (3,467 files):
106
+ Running on [cal.com](https://github.com/calcom/cal.com) (10,456 files):
47
107
 
48
108
  ```
49
- sourcebook v0.1.0
50
-
51
- Scanning project...
52
- Detected: Expo, Supabase, TypeScript, EAS Build
53
- Files: 3,467 across 847 directories
54
- Build: npx expo start | eas build
55
-
56
- Analyzing import graph...
57
- Hub files: ThemeContext.tsx (684 importers), brain-api.ts (42 importers)
58
- Circular: brain-api.ts ↔ chat.ts
59
- Orphans: 23 potentially dead files
60
-
61
- Mining git history (287 commits)...
62
- Reverts: 2 found
63
- Co-change coupling: useTodayBrain.ts ↔ brain-api.ts (89% correlation)
64
- Rapid edits: profile.tsx (18 edits in one week)
65
- Active areas: src/ (265 changes in 30 days)
66
-
67
- Detecting conventions...
68
- Barrel exports: 35 index files
69
- Path aliases: @/ prefix
70
- Named exports preferred (25:6 ratio)
71
- Conventional Commits: yes
72
-
73
- Generated: CLAUDE.md (15 findings, 1.2K tokens)
74
- Done in 2.8s
109
+ sourcebook
110
+ Extracting repo truths...
111
+
112
+ Scanned project structure
113
+ 10,456 files, 3 frameworks detected
114
+ Extracted 11 findings
115
+
116
+ Core modules: types.ts imported by 183 files — widest blast radius
117
+ Circular deps: bookingScenario.ts getMockRequestData.ts
118
+ ● Co-change: auth/provider.ts ↔ middleware/session.ts (88% correlation)
119
+ ● Dead code: 1,907 orphan files detected
120
+ ● Conventions: named exports preferred (26:2 ratio)
121
+ Barrel exports: 40 index.ts re-export files
122
+ ● Commit style: Conventional Commits (feat/fix/docs)
123
+
124
+ Wrote CLAUDE.md
125
+ Wrote .cursor/rules/sourcebook.mdc
126
+ ✓ Wrote .github/copilot-instructions.md
127
+
128
+ Done in 3.1s
75
129
  ```
76
130
 
77
131
  ## How It Works
78
132
 
79
- sourcebook runs four analysis passes, all deterministic and local — no LLM, no API keys, no network calls:
133
+ sourcebook runs five analysis passes, all deterministic and local — no LLM, no API keys, no network calls:
80
134
 
81
135
  1. **Static analysis** — framework detection, build commands, project structure, environment variables
82
136
  2. **Import graph** — builds a directed graph of all imports, runs PageRank to find the most structurally important files
83
- 3. **Git forensics** — mines commit history for reverts, co-change patterns, churn hotspots, and development velocity
84
- 4. **Convention inference** — samples source files to detect naming, import, export, and error handling patterns
137
+ 3. **Git forensics** — mines commit history for reverts, anti-patterns, co-change coupling, churn hotspots, and abandoned approaches
138
+ 4. **Convention inference** — samples source files to detect naming, import, export, error handling, and type annotation patterns
139
+ 5. **Budget enforcement** — if output exceeds your token budget, intelligently drops low-priority sections (supplementary findings first, critical constraints never)
85
140
 
86
141
  Then applies a **discoverability filter**: for every finding, asks "can an agent figure this out by reading the code?" If yes, drops it. Only non-discoverable information makes it to the output.
87
142
 
@@ -89,14 +144,19 @@ Output is formatted for **context-rot resistance** — critical constraints go a
89
144
 
90
145
  ## Roadmap
91
146
 
92
- - [x] `.cursor/rules/sourcebook.mdc` + legacy `.cursorrules` output format
93
- - [x] `.github/copilot-instructions.md` output format
94
- - [ ] `sourcebook update` — re-analyze while preserving manual edits
95
- - [ ] `--budget <tokens>`PageRank-based prioritization within a token limit
147
+ - [x] `.cursor/rules/sourcebook.mdc` + legacy `.cursorrules` output
148
+ - [x] `.github/copilot-instructions.md` output
149
+ - [x] `sourcebook update` — re-analyze while preserving manual edits
150
+ - [x] `sourcebook diff`show what changed (CI-friendly exit codes)
151
+ - [x] `--budget <tokens>` — smart PageRank-based prioritization
152
+ - [x] Anti-pattern detection from reverted commits and deleted files
153
+ - [x] Python support (Django, FastAPI, Flask, pytest)
154
+ - [x] Go support (Gin, Echo, Fiber, module layout)
155
+ - [x] GitHub Action for CI
96
156
  - [ ] Framework knowledge packs (community-contributed)
97
157
  - [ ] Tree-sitter AST parsing for deeper convention detection
98
- - [ ] GitHub Action for CI (auto-update context on merge)
99
158
  - [ ] `sourcebook serve` — MCP server mode
159
+ - [ ] Hosted dashboard with context quality scores
100
160
 
101
161
  ## Research Foundation
102
162
 
@@ -108,4 +168,4 @@ Built on findings from:
108
168
 
109
169
  ## License
110
170
 
111
- MIT
171
+ BSL-1.1 — source-available, free to use, cannot be offered as a hosted service. Converts to MIT on 2030-03-25. See [LICENSE](./LICENSE) for details.
@@ -0,0 +1,25 @@
1
+ export interface LicenseInfo {
2
+ valid: boolean;
3
+ tier: "free" | "pro" | "team";
4
+ email?: string;
5
+ expiresAt?: string;
6
+ }
7
+ /**
8
+ * Check if the user has a valid Pro or Team license.
9
+ * License keys are stored in ~/.sourcebook/license.key
10
+ *
11
+ * Flow:
12
+ * 1. Read key from disk
13
+ * 2. Validate against API (with 5s timeout)
14
+ * 3. Cache validation result for 24h to avoid hitting API every run
15
+ */
16
+ export declare function checkLicense(): Promise<LicenseInfo>;
17
+ /**
18
+ * Save a license key to disk.
19
+ */
20
+ export declare function saveLicenseKey(key: string): void;
21
+ /**
22
+ * Gate a feature behind Pro license.
23
+ * Prints upgrade message and exits if not licensed.
24
+ */
25
+ export declare function requirePro(feature: string): Promise<void>;
@@ -0,0 +1,130 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import chalk from "chalk";
5
+ const LICENSE_DIR = path.join(os.homedir(), ".sourcebook");
6
+ const LICENSE_FILE = path.join(LICENSE_DIR, "license.key");
7
+ const VALIDATION_ENDPOINT = "https://sourcebook.run/api/validate";
8
+ /**
9
+ * Check if the user has a valid Pro or Team license.
10
+ * License keys are stored in ~/.sourcebook/license.key
11
+ *
12
+ * Flow:
13
+ * 1. Read key from disk
14
+ * 2. Validate against API (with 5s timeout)
15
+ * 3. Cache validation result for 24h to avoid hitting API every run
16
+ */
17
+ export async function checkLicense() {
18
+ const key = readLicenseKey();
19
+ if (!key) {
20
+ return { valid: false, tier: "free" };
21
+ }
22
+ // Check cache first (avoid hitting API every run)
23
+ const cached = readCache();
24
+ if (cached && cached.key === key && !isCacheExpired(cached.timestamp)) {
25
+ return cached.info;
26
+ }
27
+ // Validate against API
28
+ try {
29
+ const controller = new AbortController();
30
+ const timeout = setTimeout(() => controller.abort(), 5000);
31
+ const response = await fetch(VALIDATION_ENDPOINT, {
32
+ method: "POST",
33
+ headers: { "Content-Type": "application/json" },
34
+ body: JSON.stringify({ key }),
35
+ signal: controller.signal,
36
+ });
37
+ clearTimeout(timeout);
38
+ if (response.ok) {
39
+ const data = await response.json();
40
+ writeCache(key, data);
41
+ return data;
42
+ }
43
+ }
44
+ catch {
45
+ // Network error or timeout — fall back to cache or offline validation
46
+ if (cached && cached.key === key) {
47
+ return cached.info;
48
+ }
49
+ // Offline grace: if key looks valid (format check), allow Pro for 7 days
50
+ if (isValidKeyFormat(key)) {
51
+ return { valid: true, tier: "pro" };
52
+ }
53
+ }
54
+ return { valid: false, tier: "free" };
55
+ }
56
+ /**
57
+ * Save a license key to disk.
58
+ */
59
+ export function saveLicenseKey(key) {
60
+ if (!fs.existsSync(LICENSE_DIR)) {
61
+ fs.mkdirSync(LICENSE_DIR, { recursive: true });
62
+ }
63
+ fs.writeFileSync(LICENSE_FILE, key.trim(), "utf-8");
64
+ }
65
+ /**
66
+ * Read the license key from disk.
67
+ */
68
+ function readLicenseKey() {
69
+ try {
70
+ const key = fs.readFileSync(LICENSE_FILE, "utf-8").trim();
71
+ return key || null;
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ }
77
+ /**
78
+ * License key format: sb_pro_<32 hex chars> or sb_team_<32 hex chars>
79
+ */
80
+ function isValidKeyFormat(key) {
81
+ return /^sb_(pro|team)_[a-f0-9]{32}$/.test(key);
82
+ }
83
+ const CACHE_FILE = path.join(LICENSE_DIR, ".cache.json");
84
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
85
+ function readCache() {
86
+ try {
87
+ const data = JSON.parse(fs.readFileSync(CACHE_FILE, "utf-8"));
88
+ return data;
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ }
94
+ function writeCache(key, info) {
95
+ if (!fs.existsSync(LICENSE_DIR)) {
96
+ fs.mkdirSync(LICENSE_DIR, { recursive: true });
97
+ }
98
+ const entry = { key, info, timestamp: Date.now() };
99
+ fs.writeFileSync(CACHE_FILE, JSON.stringify(entry), "utf-8");
100
+ }
101
+ function isCacheExpired(timestamp) {
102
+ return Date.now() - timestamp > CACHE_TTL_MS;
103
+ }
104
+ // --- Gate ---
105
+ /**
106
+ * Gate a feature behind Pro license.
107
+ * Prints upgrade message and exits if not licensed.
108
+ */
109
+ export async function requirePro(feature) {
110
+ const license = await checkLicense();
111
+ if (license.tier === "pro" || license.tier === "team") {
112
+ return; // Licensed, proceed
113
+ }
114
+ console.log("");
115
+ console.log(chalk.yellow("⚡") +
116
+ chalk.bold(` ${feature} requires sourcebook Pro`));
117
+ console.log("");
118
+ console.log(chalk.dim(" sourcebook Pro includes:"));
119
+ console.log(chalk.dim(" · sourcebook update (preserve manual edits)"));
120
+ console.log(chalk.dim(" · sourcebook serve (MCP server mode)"));
121
+ console.log(chalk.dim(" · sourcebook watch (auto-regenerate on changes)"));
122
+ console.log(chalk.dim(" · Web demo (shareable analysis links)"));
123
+ console.log(chalk.dim(" · Priority language support"));
124
+ console.log("");
125
+ console.log(` ${chalk.bold("$19/mo")} → ${chalk.underline("https://sourcebook.run/pro")}`);
126
+ console.log("");
127
+ console.log(chalk.dim(" Already have a key? Run: sourcebook activate <key>"));
128
+ console.log("");
129
+ process.exit(0);
130
+ }
package/dist/cli.js CHANGED
@@ -1,17 +1,38 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from "commander";
3
3
  import { init } from "./commands/init.js";
4
+ import { update } from "./commands/update.js";
5
+ import { diff } from "./commands/diff.js";
6
+ import { activate } from "./commands/activate.js";
4
7
  const program = new Command();
5
8
  program
6
9
  .name("sourcebook")
7
10
  .description("Extract the conventions, constraints, and architectural truths your AI coding agents keep missing.")
8
- .version("0.1.0");
11
+ .version("0.3.0");
9
12
  program
10
13
  .command("init")
11
14
  .description("Analyze a codebase and generate agent context files")
12
15
  .option("-d, --dir <path>", "Target directory to analyze", ".")
13
- .option("-f, --format <formats>", "Output formats (claude,cursor,copilot,agents,json)", "claude")
16
+ .option("-f, --format <formats>", "Output formats (claude,cursor,copilot,all)", "claude")
14
17
  .option("--budget <tokens>", "Max token budget for generated context", "4000")
15
18
  .option("--dry-run", "Preview findings without writing files")
16
19
  .action(init);
20
+ program
21
+ .command("update")
22
+ .description("Re-analyze and update context files while preserving manual edits")
23
+ .option("-d, --dir <path>", "Target directory to analyze", ".")
24
+ .option("-f, --format <formats>", "Output formats (claude,cursor,copilot,all)", "claude")
25
+ .option("--budget <tokens>", "Max token budget for generated context", "4000")
26
+ .action(update);
27
+ program
28
+ .command("diff")
29
+ .description("Show what would change if context files were regenerated")
30
+ .option("-d, --dir <path>", "Target directory to analyze", ".")
31
+ .option("-f, --format <formats>", "Output format to diff (claude,cursor,copilot)", "claude")
32
+ .option("--budget <tokens>", "Max token budget for generated context", "4000")
33
+ .action(diff);
34
+ program
35
+ .command("activate <key>")
36
+ .description("Activate a Pro or Team license key")
37
+ .action(activate);
17
38
  program.parse();
@@ -0,0 +1 @@
1
+ export declare function activate(key: string): Promise<void>;
@@ -0,0 +1,38 @@
1
+ import chalk from "chalk";
2
+ import { saveLicenseKey, checkLicense } from "../auth/license.js";
3
+ export async function activate(key) {
4
+ if (!key || key.trim().length === 0) {
5
+ console.log(chalk.red("\nNo license key provided."));
6
+ console.log(chalk.dim("Usage: sourcebook activate <key>"));
7
+ console.log(chalk.dim("Get a key at https://sourcebook.run/pro\n"));
8
+ process.exit(1);
9
+ }
10
+ console.log(chalk.bold("\nsourcebook activate"));
11
+ console.log(chalk.dim("Validating license key...\n"));
12
+ // Save key first
13
+ saveLicenseKey(key);
14
+ // Validate it
15
+ const license = await checkLicense();
16
+ if (license.tier === "pro" || license.tier === "team") {
17
+ console.log(chalk.green("✓") +
18
+ chalk.bold(` License activated — ${license.tier} tier`));
19
+ if (license.email) {
20
+ console.log(chalk.dim(` Licensed to: ${license.email}`));
21
+ }
22
+ if (license.expiresAt) {
23
+ console.log(chalk.dim(` Expires: ${license.expiresAt}`));
24
+ }
25
+ console.log("");
26
+ console.log(chalk.dim(" You now have access to:"));
27
+ console.log(chalk.dim(" · sourcebook update"));
28
+ console.log(chalk.dim(" · sourcebook serve"));
29
+ console.log(chalk.dim(" · sourcebook watch"));
30
+ console.log("");
31
+ }
32
+ else {
33
+ console.log(chalk.yellow("⚠") +
34
+ " License key saved but could not be validated.");
35
+ console.log(chalk.dim(" This may be a network issue. The key will be re-validated on next use."));
36
+ console.log(chalk.dim(" If the problem persists, contact roy@maroond.ai\n"));
37
+ }
38
+ }
@@ -0,0 +1,12 @@
1
+ interface DiffOptions {
2
+ dir: string;
3
+ format: string;
4
+ budget: string;
5
+ }
6
+ /**
7
+ * Show what would change if sourcebook regenerated the context files.
8
+ * Does not write any files — pure comparison.
9
+ * Exit code: 0 if no changes, 1 if changes found (useful for CI).
10
+ */
11
+ export declare function diff(options: DiffOptions): Promise<void>;
12
+ export {};
@@ -0,0 +1,97 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import chalk from "chalk";
4
+ import { scanProject } from "../scanner/index.js";
5
+ import { generateClaude } from "../generators/claude.js";
6
+ import { generateCursor } from "../generators/cursor.js";
7
+ import { generateCopilot } from "../generators/copilot.js";
8
+ /**
9
+ * Show what would change if sourcebook regenerated the context files.
10
+ * Does not write any files — pure comparison.
11
+ * Exit code: 0 if no changes, 1 if changes found (useful for CI).
12
+ */
13
+ export async function diff(options) {
14
+ const targetDir = path.resolve(options.dir);
15
+ const format = options.format.split(",")[0].trim(); // diff one format at a time
16
+ const budget = parseInt(options.budget, 10);
17
+ console.log(chalk.bold("\nsourcebook diff"));
18
+ console.log(chalk.dim("Comparing current context with fresh analysis...\n"));
19
+ const scan = await scanProject(targetDir);
20
+ const formatMap = {
21
+ claude: {
22
+ generator: () => generateClaude(scan, budget),
23
+ file: "CLAUDE.md",
24
+ },
25
+ cursor: {
26
+ generator: () => generateCursor(scan, budget),
27
+ file: ".cursor/rules/sourcebook.mdc",
28
+ },
29
+ copilot: {
30
+ generator: () => generateCopilot(scan, budget),
31
+ file: ".github/copilot-instructions.md",
32
+ },
33
+ };
34
+ const config = formatMap[format];
35
+ if (!config) {
36
+ console.log(chalk.yellow(`⚠ Format "${format}" not supported for diff`));
37
+ process.exit(1);
38
+ }
39
+ const filePath = path.join(targetDir, config.file);
40
+ let existing;
41
+ try {
42
+ existing = fs.readFileSync(filePath, "utf-8");
43
+ }
44
+ catch {
45
+ console.log(chalk.yellow(`⚠ ${config.file} does not exist yet. Run \`sourcebook init\` first.`));
46
+ process.exit(1);
47
+ }
48
+ const fresh = config.generator();
49
+ if (existing.trim() === fresh.trim()) {
50
+ console.log(chalk.green("✓") + ` ${config.file} is up to date. No changes needed.\n`);
51
+ process.exit(0);
52
+ }
53
+ // Line-by-line diff
54
+ const existingLines = existing.split("\n");
55
+ const freshLines = fresh.split("\n");
56
+ let hasChanges = false;
57
+ console.log(chalk.bold(` ${config.file}\n`));
58
+ // Simple diff: show removed and added lines
59
+ const maxLen = Math.max(existingLines.length, freshLines.length);
60
+ // Build sets for quick lookup
61
+ const existingSet = new Set(existingLines.map((l) => l.trim()).filter(Boolean));
62
+ const freshSet = new Set(freshLines.map((l) => l.trim()).filter(Boolean));
63
+ // Lines only in existing (removed)
64
+ const removed = existingLines.filter((l) => l.trim() && !freshSet.has(l.trim()));
65
+ // Lines only in fresh (added)
66
+ const added = freshLines.filter((l) => l.trim() && !existingSet.has(l.trim()));
67
+ if (removed.length > 0) {
68
+ hasChanges = true;
69
+ console.log(chalk.red(" Removed:"));
70
+ for (const line of removed.slice(0, 20)) {
71
+ console.log(chalk.red(` - ${line}`));
72
+ }
73
+ if (removed.length > 20) {
74
+ console.log(chalk.dim(` ... and ${removed.length - 20} more`));
75
+ }
76
+ console.log("");
77
+ }
78
+ if (added.length > 0) {
79
+ hasChanges = true;
80
+ console.log(chalk.green(" Added:"));
81
+ for (const line of added.slice(0, 20)) {
82
+ console.log(chalk.green(` + ${line}`));
83
+ }
84
+ if (added.length > 20) {
85
+ console.log(chalk.dim(` ... and ${added.length - 20} more`));
86
+ }
87
+ console.log("");
88
+ }
89
+ if (hasChanges) {
90
+ console.log(chalk.dim(" Run `sourcebook update` to apply these changes while preserving your edits.\n"));
91
+ process.exit(1);
92
+ }
93
+ else {
94
+ console.log(chalk.green("✓") + " No meaningful changes detected.\n");
95
+ process.exit(0);
96
+ }
97
+ }
@@ -4,6 +4,7 @@ import { scanProject } from "../scanner/index.js";
4
4
  import { generateClaude } from "../generators/claude.js";
5
5
  import { generateCursor, generateCursorLegacy } from "../generators/cursor.js";
6
6
  import { generateCopilot } from "../generators/copilot.js";
7
+ import { generateAgents } from "../generators/agents.js";
7
8
  import { writeOutput } from "../utils/output.js";
8
9
  export async function init(options) {
9
10
  const targetDir = path.resolve(options.dir);
@@ -67,6 +68,12 @@ export async function init(options) {
67
68
  console.log(chalk.green("✓") + " Wrote .github/copilot-instructions.md");
68
69
  break;
69
70
  }
71
+ case "agents": {
72
+ const agentsContent = generateAgents(scan, budget);
73
+ await writeOutput(targetDir, "AGENTS.md", agentsContent);
74
+ console.log(chalk.green("✓") + " Wrote AGENTS.md");
75
+ break;
76
+ }
70
77
  case "all": {
71
78
  const claudeAll = generateClaude(scan, budget);
72
79
  await writeOutput(targetDir, "CLAUDE.md", claudeAll);
@@ -80,6 +87,9 @@ export async function init(options) {
80
87
  const copilotAll = generateCopilot(scan, budget);
81
88
  await writeOutput(targetDir, ".github/copilot-instructions.md", copilotAll);
82
89
  console.log(chalk.green("✓") + " Wrote .github/copilot-instructions.md");
90
+ const agentsAll = generateAgents(scan, budget);
91
+ await writeOutput(targetDir, "AGENTS.md", agentsAll);
92
+ console.log(chalk.green("✓") + " Wrote AGENTS.md");
83
93
  break;
84
94
  }
85
95
  default: