codemaxxing 0.1.0

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.
@@ -0,0 +1,220 @@
1
+ import { readFileSync, readdirSync, statSync } from "fs";
2
+ import { join, extname, relative } from "path";
3
+
4
+ const IGNORE_DIRS = new Set([
5
+ "node_modules", ".git", "dist", ".next", "__pycache__", ".pytest_cache",
6
+ "target", "build", "out", ".cache", ".parcel-cache", ".nuxt", ".svelte-kit",
7
+ "vendor", "venv", ".venv", "env", ".env", "coverage", ".nyc_output",
8
+ ]);
9
+
10
+ const IGNORE_FILES = new Set([
11
+ ".DS_Store", "package-lock.json", "yarn.lock", "pnpm-lock.yaml",
12
+ ]);
13
+
14
+ const MAX_FILE_SIZE = 100 * 1024;
15
+ const MAX_MAP_SIZE = 15 * 1024;
16
+
17
+ // ── Per-line regex patterns (no /g flag!) ──
18
+
19
+ interface LangPatterns {
20
+ patterns: Array<{ kind: string; regex: RegExp; format: (m: RegExpMatchArray) => string }>;
21
+ }
22
+
23
+ const LANGS: Record<string, LangPatterns> = {
24
+ javascript: {
25
+ patterns: [
26
+ { kind: "fn", regex: /^(?:export\s+)?(?:export\s+default\s+)?(?:async\s+)?function\s+(\w+)\s*\(/, format: (m) => `function ${m[1]}(...)` },
27
+ { kind: "arrow", regex: /^(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\(/, format: (m) => `const ${m[1]} = (...)` },
28
+ { kind: "cls", regex: /^(?:export\s+)?(?:export\s+default\s+)?class\s+(\w+)/, format: (m) => `class ${m[1]}` },
29
+ ],
30
+ },
31
+ typescript: {
32
+ patterns: [
33
+ { kind: "fn", regex: /^(?:export\s+)?(?:export\s+default\s+)?(?:async\s+)?function\s+(\w+)/, format: (m) => `function ${m[1]}(...)` },
34
+ { kind: "arrow", regex: /^(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\(/, format: (m) => `const ${m[1]} = (...)` },
35
+ { kind: "cls", regex: /^(?:export\s+)?(?:export\s+default\s+)?class\s+(\w+)/, format: (m) => `class ${m[1]}` },
36
+ { kind: "iface", regex: /^(?:export\s+)?interface\s+(\w+)/, format: (m) => `interface ${m[1]}` },
37
+ { kind: "type", regex: /^(?:export\s+)?type\s+(\w+)\s*[=<]/, format: (m) => `type ${m[1]}` },
38
+ { kind: "enum", regex: /^(?:export\s+)?enum\s+(\w+)/, format: (m) => `enum ${m[1]}` },
39
+ ],
40
+ },
41
+ python: {
42
+ patterns: [
43
+ { kind: "fn", regex: /^def\s+(\w+)\s*\(/, format: (m) => `def ${m[1]}(...)` },
44
+ { kind: "method", regex: /^\s{2,}def\s+(\w+)\s*\(/, format: (m) => ` def ${m[1]}(...)` },
45
+ { kind: "cls", regex: /^class\s+(\w+)/, format: (m) => `class ${m[1]}` },
46
+ ],
47
+ },
48
+ go: {
49
+ patterns: [
50
+ { kind: "fn", regex: /^func\s+(\w+)\s*\(/, format: (m) => `func ${m[1]}(...)` },
51
+ { kind: "method", regex: /^func\s+\((\w+)\s+\*?(\w+)\)\s+(\w+)\s*\(/, format: (m) => `func (${m[2]}) ${m[3]}(...)` },
52
+ { kind: "struct", regex: /^type\s+(\w+)\s+struct/, format: (m) => `type ${m[1]} struct` },
53
+ { kind: "iface", regex: /^type\s+(\w+)\s+interface/, format: (m) => `type ${m[1]} interface` },
54
+ ],
55
+ },
56
+ rust: {
57
+ patterns: [
58
+ { kind: "fn", regex: /^(?:pub\s+)?(?:async\s+)?fn\s+(\w+)/, format: (m) => `fn ${m[1]}(...)` },
59
+ { kind: "struct", regex: /^(?:pub\s+)?struct\s+(\w+)/, format: (m) => `struct ${m[1]}` },
60
+ { kind: "enum", regex: /^(?:pub\s+)?enum\s+(\w+)/, format: (m) => `enum ${m[1]}` },
61
+ { kind: "trait", regex: /^(?:pub\s+)?trait\s+(\w+)/, format: (m) => `trait ${m[1]}` },
62
+ { kind: "impl", regex: /^impl(?:<[^>]*>)?\s+(?:(\w+)\s+for\s+)?(\w+)/, format: (m) => m[1] ? `impl ${m[1]} for ${m[2]}` : `impl ${m[2]}` },
63
+ { kind: "mod", regex: /^(?:pub\s+)?mod\s+(\w+)/, format: (m) => `mod ${m[1]}` },
64
+ ],
65
+ },
66
+ };
67
+
68
+ /**
69
+ * Get language from extension
70
+ */
71
+ function getLang(ext: string): string | null {
72
+ const map: Record<string, string> = {
73
+ ".js": "javascript", ".jsx": "javascript", ".mjs": "javascript", ".cjs": "javascript",
74
+ ".ts": "typescript", ".tsx": "typescript",
75
+ ".py": "python",
76
+ ".go": "go",
77
+ ".rs": "rust",
78
+ };
79
+ return map[ext.toLowerCase()] || null;
80
+ }
81
+
82
+ /**
83
+ * Extract signatures from file content
84
+ */
85
+ function extractSignatures(content: string, lang: string): string[] {
86
+ const sigs: string[] = [];
87
+ const langDef = LANGS[lang];
88
+ if (!langDef) return sigs;
89
+
90
+ const lines = content.split("\n");
91
+ const seen = new Set<string>();
92
+
93
+ for (const line of lines) {
94
+ for (const pattern of langDef.patterns) {
95
+ const match = line.match(pattern.regex);
96
+ if (match) {
97
+ const sig = pattern.format(match);
98
+ if (!seen.has(sig)) {
99
+ seen.add(sig);
100
+ sigs.push(sig);
101
+ }
102
+ break; // Only match one pattern per line
103
+ }
104
+ }
105
+ }
106
+
107
+ return sigs;
108
+ }
109
+
110
+ /**
111
+ * Scan directory for supported files
112
+ */
113
+ function getFiles(cwd: string): string[] {
114
+ const files: string[] = [];
115
+
116
+ function walk(dir: string, depth: number) {
117
+ if (depth > 5) return;
118
+ try {
119
+ for (const entry of readdirSync(dir)) {
120
+ if (IGNORE_FILES.has(entry) || entry.startsWith(".")) continue;
121
+ if (IGNORE_DIRS.has(entry)) continue;
122
+ const full = join(dir, entry);
123
+
124
+ const stat = statSync(full);
125
+ if (stat.isDirectory()) {
126
+ walk(full, depth + 1);
127
+ } else if (stat.isFile() && stat.size < MAX_FILE_SIZE) {
128
+ if (getLang(extname(entry))) files.push(full);
129
+ }
130
+ }
131
+ } catch { /* skip */ }
132
+ }
133
+
134
+ walk(cwd, 0);
135
+ return files;
136
+ }
137
+
138
+ // ── Cache ──
139
+ let cachedMap = "";
140
+ let cachedCwd = "";
141
+ let cachedTime = 0;
142
+ const CACHE_TTL = 60_000;
143
+
144
+ /**
145
+ * Build the repo map — cached for 1 min
146
+ */
147
+ export async function buildRepoMap(cwd: string): Promise<string> {
148
+ const now = Date.now();
149
+ if (cachedMap && cachedCwd === cwd && now - cachedTime < CACHE_TTL) {
150
+ return cachedMap;
151
+ }
152
+
153
+ const files = getFiles(cwd);
154
+ const lines: string[] = [];
155
+
156
+ for (const file of files) {
157
+ const ext = extname(file);
158
+ const lang = getLang(ext);
159
+ if (!lang) continue;
160
+
161
+ try {
162
+ const content = readFileSync(file, "utf-8");
163
+ const sigs = extractSignatures(content, lang);
164
+
165
+ if (sigs.length > 0) {
166
+ const relPath = relative(cwd, file);
167
+ lines.push(`${relPath}:`);
168
+ for (const sig of sigs) {
169
+ lines.push(` ${sig}`);
170
+ }
171
+ lines.push("");
172
+
173
+ // Size guard
174
+ if (lines.join("\n").length > MAX_MAP_SIZE) {
175
+ lines.push(`... (truncated)`);
176
+ break;
177
+ }
178
+ }
179
+ } catch { /* skip */ }
180
+ }
181
+
182
+ const map = lines.length > 0 ? lines.join("\n") : "(no signatures found)";
183
+
184
+ cachedMap = map;
185
+ cachedCwd = cwd;
186
+ cachedTime = now;
187
+
188
+ return map;
189
+ }
190
+
191
+ /**
192
+ * Get cached map without rebuilding
193
+ */
194
+ export function getCachedMap(): string {
195
+ return cachedMap;
196
+ }
197
+
198
+ /**
199
+ * Clear the cache
200
+ */
201
+ export function clearMapCache(): void {
202
+ cachedMap = "";
203
+ cachedCwd = "";
204
+ cachedTime = 0;
205
+ }
206
+
207
+ /**
208
+ * Check if file is supported
209
+ */
210
+ export function isSupportedFile(filePath: string): boolean {
211
+ return !!getLang(extname(filePath).toLowerCase());
212
+ }
213
+
214
+ export function getSupportedExtensions(): string[] {
215
+ return [".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".py", ".go", ".rs"];
216
+ }
217
+
218
+ export function getLanguageForExt(ext: string): string | null {
219
+ return getLang(ext);
220
+ }
@@ -0,0 +1,222 @@
1
+ import Database from "better-sqlite3";
2
+ import { existsSync, mkdirSync } from "fs";
3
+ import { join } from "path";
4
+ import { homedir } from "os";
5
+ import type { ChatCompletionMessageParam } from "openai/resources/chat/completions";
6
+
7
+ const CONFIG_DIR = join(homedir(), ".codemaxxing");
8
+ const DB_PATH = join(CONFIG_DIR, "sessions.db");
9
+
10
+ let db: Database.Database | null = null;
11
+
12
+ /**
13
+ * Initialize the database and create tables if needed
14
+ */
15
+ function getDb(): Database.Database {
16
+ if (db) return db;
17
+
18
+ if (!existsSync(CONFIG_DIR)) {
19
+ mkdirSync(CONFIG_DIR, { recursive: true });
20
+ }
21
+
22
+ db = new Database(DB_PATH);
23
+
24
+ // Enable WAL mode for better concurrent performance
25
+ db.pragma("journal_mode = WAL");
26
+
27
+ // Create tables
28
+ db.exec(`
29
+ CREATE TABLE IF NOT EXISTS sessions (
30
+ id TEXT PRIMARY KEY,
31
+ cwd TEXT NOT NULL,
32
+ model TEXT NOT NULL,
33
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
34
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
35
+ message_count INTEGER NOT NULL DEFAULT 0,
36
+ token_estimate INTEGER NOT NULL DEFAULT 0,
37
+ summary TEXT
38
+ );
39
+
40
+ CREATE TABLE IF NOT EXISTS messages (
41
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
42
+ session_id TEXT NOT NULL,
43
+ role TEXT NOT NULL,
44
+ content TEXT,
45
+ tool_calls TEXT,
46
+ tool_call_id TEXT,
47
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
48
+ FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
49
+ );
50
+
51
+ CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id);
52
+ `);
53
+
54
+ return db;
55
+ }
56
+
57
+ /**
58
+ * Generate a short session ID (8 chars)
59
+ */
60
+ function generateId(): string {
61
+ const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
62
+ let id = "";
63
+ for (let i = 0; i < 8; i++) {
64
+ id += chars[Math.floor(Math.random() * chars.length)];
65
+ }
66
+ return id;
67
+ }
68
+
69
+ /**
70
+ * Create a new session
71
+ */
72
+ export function createSession(cwd: string, model: string): string {
73
+ const db = getDb();
74
+ const id = generateId();
75
+
76
+ db.prepare(`
77
+ INSERT INTO sessions (id, cwd, model) VALUES (?, ?, ?)
78
+ `).run(id, cwd, model);
79
+
80
+ return id;
81
+ }
82
+
83
+ /**
84
+ * Save a message to a session
85
+ */
86
+ export function saveMessage(sessionId: string, message: ChatCompletionMessageParam): void {
87
+ const db = getDb();
88
+
89
+ const content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
90
+ const toolCalls = "tool_calls" in message && message.tool_calls
91
+ ? JSON.stringify(message.tool_calls)
92
+ : null;
93
+ const toolCallId = "tool_call_id" in message ? (message as any).tool_call_id : null;
94
+
95
+ db.prepare(`
96
+ INSERT INTO messages (session_id, role, content, tool_calls, tool_call_id)
97
+ VALUES (?, ?, ?, ?, ?)
98
+ `).run(sessionId, message.role, content, toolCalls, toolCallId);
99
+
100
+ // Update session metadata
101
+ const stats = db.prepare(`
102
+ SELECT COUNT(*) as count FROM messages WHERE session_id = ?
103
+ `).get(sessionId) as { count: number };
104
+
105
+ db.prepare(`
106
+ UPDATE sessions SET updated_at = datetime('now'), message_count = ? WHERE id = ?
107
+ `).run(stats.count, sessionId);
108
+ }
109
+
110
+ /**
111
+ * Update token estimate for a session
112
+ */
113
+ export function updateTokenEstimate(sessionId: string, tokens: number): void {
114
+ const db = getDb();
115
+ db.prepare(`
116
+ UPDATE sessions SET token_estimate = ? WHERE id = ?
117
+ `).run(tokens, sessionId);
118
+ }
119
+
120
+ /**
121
+ * List recent sessions
122
+ */
123
+ export interface SessionInfo {
124
+ id: string;
125
+ cwd: string;
126
+ model: string;
127
+ created_at: string;
128
+ updated_at: string;
129
+ message_count: number;
130
+ token_estimate: number;
131
+ summary: string | null;
132
+ }
133
+
134
+ export function listSessions(limit: number = 10): SessionInfo[] {
135
+ const db = getDb();
136
+ return db.prepare(`
137
+ SELECT * FROM sessions ORDER BY updated_at DESC LIMIT ?
138
+ `).all(limit) as SessionInfo[];
139
+ }
140
+
141
+ /**
142
+ * Load all messages for a session
143
+ */
144
+ export function loadMessages(sessionId: string): ChatCompletionMessageParam[] {
145
+ const db = getDb();
146
+
147
+ const rows = db.prepare(`
148
+ SELECT role, content, tool_calls, tool_call_id FROM messages
149
+ WHERE session_id = ? ORDER BY id ASC
150
+ `).all(sessionId) as Array<{
151
+ role: string;
152
+ content: string | null;
153
+ tool_calls: string | null;
154
+ tool_call_id: string | null;
155
+ }>;
156
+
157
+ return rows.map((row) => {
158
+ const msg: any = { role: row.role, content: row.content };
159
+
160
+ if (row.tool_calls) {
161
+ try {
162
+ msg.tool_calls = JSON.parse(row.tool_calls);
163
+ } catch { /* ignore */ }
164
+ }
165
+
166
+ if (row.tool_call_id) {
167
+ msg.tool_call_id = row.tool_call_id;
168
+ }
169
+
170
+ return msg as ChatCompletionMessageParam;
171
+ });
172
+ }
173
+
174
+ /**
175
+ * Get a specific session
176
+ */
177
+ export function getSession(sessionId: string): SessionInfo | null {
178
+ const db = getDb();
179
+ return (db.prepare(`
180
+ SELECT * FROM sessions WHERE id = ?
181
+ `).get(sessionId) as SessionInfo) || null;
182
+ }
183
+
184
+ /**
185
+ * Delete a session and its messages
186
+ */
187
+ export function deleteSession(sessionId: string): boolean {
188
+ const db = getDb();
189
+ db.prepare(`DELETE FROM messages WHERE session_id = ?`).run(sessionId);
190
+ const result = db.prepare(`DELETE FROM sessions WHERE id = ?`).run(sessionId);
191
+ return result.changes > 0;
192
+ }
193
+
194
+ /**
195
+ * Update session summary (for context compression)
196
+ */
197
+ export function updateSummary(sessionId: string, summary: string): void {
198
+ const db = getDb();
199
+ db.prepare(`
200
+ UPDATE sessions SET summary = ? WHERE id = ?
201
+ `).run(summary, sessionId);
202
+ }
203
+
204
+ /**
205
+ * Get the most recent session for a given cwd
206
+ */
207
+ export function getLastSession(cwd: string): SessionInfo | null {
208
+ const db = getDb();
209
+ return (db.prepare(`
210
+ SELECT * FROM sessions WHERE cwd = ? ORDER BY updated_at DESC LIMIT 1
211
+ `).get(cwd) as SessionInfo) || null;
212
+ }
213
+
214
+ /**
215
+ * Close the database connection
216
+ */
217
+ export function closeDb(): void {
218
+ if (db) {
219
+ db.close();
220
+ db = null;
221
+ }
222
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "outDir": "dist",
7
+ "rootDir": "src",
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "declaration": true,
12
+ "resolveJsonModule": true,
13
+ "jsx": "react-jsx"
14
+ },
15
+ "include": ["src/**/*"]
16
+ }