cartotree 0.2.0 → 0.2.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/src/ai.js CHANGED
@@ -1,113 +1,113 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const { shouldIgnore } = require('./ignore');
4
- const { parseExports } = require('./exports');
5
-
6
- const AI_FORMAT_HEADER = '# cartotree fmt: name{desc}[children]<exports>';
7
-
8
- function getFolderDescription(dirPath) {
9
- const folderMd = path.join(dirPath, '.folder.md');
10
- const readmeMd = path.join(dirPath, 'README.md');
11
-
12
- if (fs.existsSync(folderMd)) {
13
- return fs.readFileSync(folderMd, 'utf-8').trim().split('\n')[0].replace(/^#\s*/, '');
14
- }
15
- if (fs.existsSync(readmeMd)) {
16
- const first = fs.readFileSync(readmeMd, 'utf-8').trim().split('\n')[0].replace(/^#\s*/, '');
17
- if (first.length < 80) return first;
18
- }
19
- return null;
20
- }
21
-
22
- function buildAINode(entryPath, name, opts, isDir, currentDepth = 0) {
23
- if (isDir) {
24
- let entries;
25
- try {
26
- entries = fs.readdirSync(entryPath, { withFileTypes: true });
27
- } catch {
28
- return `${name}[!]`;
29
- }
30
-
31
- const filtered = entries
32
- .filter(e => !shouldIgnore(e.name, opts.exclude))
33
- .sort((a, b) => {
34
- if (a.isDirectory() && !b.isDirectory()) return -1;
35
- if (!a.isDirectory() && b.isDirectory()) return 1;
36
- return a.name.localeCompare(b.name);
37
- });
38
-
39
- const desc = getFolderDescription(entryPath);
40
- const descPart = desc ? `{${desc}}` : '';
41
-
42
- if (filtered.length === 0) return `${name}${descPart}[]`;
43
-
44
- if (currentDepth >= opts.depth) {
45
- const names = filtered.map(e => e.name + (e.isDirectory() ? '/' : '')).join(',');
46
- return `${name}${descPart}[${names}]`;
47
- }
48
-
49
- const children = filtered.map(e => {
50
- const fullPath = path.join(entryPath, e.name);
51
- return buildAINode(fullPath, e.name, opts, e.isDirectory(), currentDepth + 1);
52
- });
53
-
54
- return `${name}${descPart}[${children.join(',')}]`;
55
- } else {
56
- const exports = opts.showExports ? parseExports(entryPath) : null;
57
- const exportPart = exports && exports.length > 0
58
- ? `<${exports.slice(0, 4).join(',')}${exports.length > 4 ? `+${exports.length - 4}` : ''}>`
59
- : '';
60
- return `${name}${exportPart}`;
61
- }
62
- }
63
-
64
- function buildJSONNode(entryPath, opts, currentDepth = 0) {
65
- let entries;
66
- try {
67
- entries = fs.readdirSync(entryPath, { withFileTypes: true });
68
- } catch {
69
- return null;
70
- }
71
-
72
- const filtered = entries
73
- .filter(e => !shouldIgnore(e.name, opts.exclude))
74
- .sort((a, b) => {
75
- if (a.isDirectory() && !b.isDirectory()) return -1;
76
- if (!a.isDirectory() && b.isDirectory()) return 1;
77
- return a.name.localeCompare(b.name);
78
- });
79
-
80
- const result = {};
81
-
82
- const desc = getFolderDescription(entryPath);
83
- if (desc) result['_desc'] = desc;
84
-
85
- filtered.forEach(entry => {
86
- const fullPath = path.join(entryPath, entry.name);
87
-
88
- if (entry.isDirectory()) {
89
- result[entry.name] = currentDepth < opts.depth
90
- ? buildJSONNode(fullPath, opts, currentDepth + 1)
91
- : {};
92
- } else {
93
- const exports = parseExports(fullPath);
94
- result[entry.name] = exports ?? null;
95
- }
96
- });
97
-
98
- return result;
99
- }
100
-
101
- function generateAI(rootPath, opts) {
102
- const rootName = path.basename(rootPath);
103
- const node = buildAINode(rootPath, rootName, opts, true);
104
- return `${AI_FORMAT_HEADER}\n${node}`;
105
- }
106
-
107
- function generateJSON(rootPath, opts) {
108
- const rootName = path.basename(rootPath);
109
- const tree = buildJSONNode(rootPath, opts);
110
- return JSON.stringify({ [rootName]: tree }, null, 2);
111
- }
112
-
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { shouldIgnore } = require('./ignore');
4
+ const { parseExports } = require('./exports');
5
+
6
+ const AI_FORMAT_HEADER = '# cartotree fmt: name{desc}[children]<exports>';
7
+
8
+ function getFolderDescription(dirPath) {
9
+ const folderMd = path.join(dirPath, '.folder.md');
10
+ const readmeMd = path.join(dirPath, 'README.md');
11
+
12
+ if (fs.existsSync(folderMd)) {
13
+ return fs.readFileSync(folderMd, 'utf-8').trim().split('\n')[0].replace(/^#\s*/, '');
14
+ }
15
+ if (fs.existsSync(readmeMd)) {
16
+ const first = fs.readFileSync(readmeMd, 'utf-8').trim().split('\n')[0].replace(/^#\s*/, '');
17
+ if (first.length < 80) return first;
18
+ }
19
+ return null;
20
+ }
21
+
22
+ function buildAINode(entryPath, name, opts, isDir, currentDepth = 0) {
23
+ if (isDir) {
24
+ let entries;
25
+ try {
26
+ entries = fs.readdirSync(entryPath, { withFileTypes: true });
27
+ } catch {
28
+ return `${name}[!]`;
29
+ }
30
+
31
+ const filtered = entries
32
+ .filter(e => !shouldIgnore(e.name, opts.exclude))
33
+ .sort((a, b) => {
34
+ if (a.isDirectory() && !b.isDirectory()) return -1;
35
+ if (!a.isDirectory() && b.isDirectory()) return 1;
36
+ return a.name.localeCompare(b.name);
37
+ });
38
+
39
+ const desc = getFolderDescription(entryPath);
40
+ const descPart = desc ? `{${desc}}` : '';
41
+
42
+ if (filtered.length === 0) return `${name}${descPart}[]`;
43
+
44
+ if (currentDepth >= opts.depth) {
45
+ const names = filtered.map(e => e.name + (e.isDirectory() ? '/' : '')).join(',');
46
+ return `${name}${descPart}[${names}]`;
47
+ }
48
+
49
+ const children = filtered.map(e => {
50
+ const fullPath = path.join(entryPath, e.name);
51
+ return buildAINode(fullPath, e.name, opts, e.isDirectory(), currentDepth + 1);
52
+ });
53
+
54
+ return `${name}${descPart}[${children.join(',')}]`;
55
+ } else {
56
+ const exports = opts.showExports ? parseExports(entryPath) : null;
57
+ const exportPart = exports && exports.length > 0
58
+ ? `<${exports.slice(0, 4).join(',')}${exports.length > 4 ? `+${exports.length - 4}` : ''}>`
59
+ : '';
60
+ return `${name}${exportPart}`;
61
+ }
62
+ }
63
+
64
+ function buildJSONNode(entryPath, opts, currentDepth = 0) {
65
+ let entries;
66
+ try {
67
+ entries = fs.readdirSync(entryPath, { withFileTypes: true });
68
+ } catch {
69
+ return null;
70
+ }
71
+
72
+ const filtered = entries
73
+ .filter(e => !shouldIgnore(e.name, opts.exclude))
74
+ .sort((a, b) => {
75
+ if (a.isDirectory() && !b.isDirectory()) return -1;
76
+ if (!a.isDirectory() && b.isDirectory()) return 1;
77
+ return a.name.localeCompare(b.name);
78
+ });
79
+
80
+ const result = {};
81
+
82
+ const desc = getFolderDescription(entryPath);
83
+ if (desc) result['_desc'] = desc;
84
+
85
+ filtered.forEach(entry => {
86
+ const fullPath = path.join(entryPath, entry.name);
87
+
88
+ if (entry.isDirectory()) {
89
+ result[entry.name] = currentDepth < opts.depth
90
+ ? buildJSONNode(fullPath, opts, currentDepth + 1)
91
+ : {};
92
+ } else {
93
+ const exports = parseExports(fullPath);
94
+ result[entry.name] = exports ?? null;
95
+ }
96
+ });
97
+
98
+ return result;
99
+ }
100
+
101
+ function generateAI(rootPath, opts) {
102
+ const rootName = path.basename(rootPath);
103
+ const node = buildAINode(rootPath, rootName, opts, true);
104
+ return `${AI_FORMAT_HEADER}\n${node}`;
105
+ }
106
+
107
+ function generateJSON(rootPath, opts) {
108
+ const rootName = path.basename(rootPath);
109
+ const tree = buildJSONNode(rootPath, opts);
110
+ return JSON.stringify({ [rootName]: tree }, null, 2);
111
+ }
112
+
113
113
  module.exports = { generateAI, generateJSON };
@@ -1,46 +1,46 @@
1
- /**
2
- * Disk cache for atlas indexes so repeated agent calls are fast.
3
- * Key = git HEAD + working-tree changes + options. Stored with v8.serialize (keeps Map objects).
4
- */
5
- const fs = require('fs');
6
- const path = require('path');
7
- const v8 = require('v8');
8
- const crypto = require('crypto');
9
- const { execSync } = require('child_process');
10
-
11
- function repoState(root) {
12
- try {
13
- const head = execSync('git rev-parse HEAD', { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
14
- const dirty = execSync('git status --porcelain --untracked-files=normal', { cwd: root, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 1 << 26 }).toString();
15
- return head + '\n' + dirty.split('\n').filter(l => !l.includes('.cartotree/')).join('\n');
16
- } catch {
17
- return null; // not a git repo -> no caching
18
- }
19
- }
20
-
21
- function cached(root, name, opts, build) {
22
- if (process.env.CARTOTREE_NO_CACHE) return build();
23
- const state = repoState(root);
24
- if (state === null) return build();
25
- const key = crypto.createHash('sha1')
26
- .update(name + '\n' + JSON.stringify(opts) + '\n' + (process.env.CARTOTREE_HISTORY_SKIP || '') + '\n' + state)
27
- .digest('hex').slice(0, 16);
28
- const dir = path.join(root, '.cartotree', 'cache');
29
- const file = path.join(dir, `${name}-${key}.bin`);
30
- if (fs.existsSync(file)) {
31
- try {
32
- return v8.deserialize(fs.readFileSync(file));
33
- } catch { /* corrupted cache -> rebuild */ }
34
- }
35
- const value = build();
36
- try {
37
- fs.mkdirSync(dir, { recursive: true });
38
- const gi = path.join(root, '.cartotree', '.gitignore');
39
- if (!fs.existsSync(gi)) fs.writeFileSync(gi, 'cache/\n');
40
- for (const old of fs.readdirSync(dir)) if (old.startsWith(name + '-') && old !== path.basename(file)) fs.unlinkSync(path.join(dir, old));
41
- fs.writeFileSync(file, v8.serialize(value));
42
- } catch { /* read-only repo: just skip caching */ }
43
- return value;
44
- }
45
-
46
- module.exports = { cached };
1
+ /**
2
+ * Disk cache for atlas indexes so repeated agent calls are fast.
3
+ * Key = git HEAD + working-tree changes + options. Stored with v8.serialize (keeps Map objects).
4
+ */
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const v8 = require('v8');
8
+ const crypto = require('crypto');
9
+ const { execSync } = require('child_process');
10
+
11
+ function repoState(root) {
12
+ try {
13
+ const head = execSync('git rev-parse HEAD', { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
14
+ const dirty = execSync('git status --porcelain --untracked-files=normal', { cwd: root, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 1 << 26 }).toString();
15
+ return head + '\n' + dirty.split('\n').filter(l => !l.includes('.cartotree/')).join('\n');
16
+ } catch {
17
+ return null; // not a git repo -> no caching
18
+ }
19
+ }
20
+
21
+ function cached(root, name, opts, build) {
22
+ if (process.env.CARTOTREE_NO_CACHE) return build();
23
+ const state = repoState(root);
24
+ if (state === null) return build();
25
+ const key = crypto.createHash('sha1')
26
+ .update(name + '\n' + JSON.stringify(opts) + '\n' + (process.env.CARTOTREE_HISTORY_SKIP || '') + '\n' + state)
27
+ .digest('hex').slice(0, 16);
28
+ const dir = path.join(root, '.cartotree', 'cache');
29
+ const file = path.join(dir, `${name}-${key}.bin`);
30
+ if (fs.existsSync(file)) {
31
+ try {
32
+ return v8.deserialize(fs.readFileSync(file));
33
+ } catch { /* corrupted cache -> rebuild */ }
34
+ }
35
+ const value = build();
36
+ try {
37
+ fs.mkdirSync(dir, { recursive: true });
38
+ const gi = path.join(root, '.cartotree', '.gitignore');
39
+ if (!fs.existsSync(gi)) fs.writeFileSync(gi, 'cache/\n');
40
+ for (const old of fs.readdirSync(dir)) if (old.startsWith(name + '-') && old !== path.basename(file)) fs.unlinkSync(path.join(dir, old));
41
+ fs.writeFileSync(file, v8.serialize(value));
42
+ } catch { /* read-only repo: just skip caching */ }
43
+ return value;
44
+ }
45
+
46
+ module.exports = { cached };
@@ -1,56 +1,56 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const { execSync } = require('child_process');
4
-
5
- const SRC_RE = /\.(ts|tsx|js|jsx|mjs|cjs)$/;
6
- const SKIP_RE = /(^|\/)(node_modules|dist|build|coverage|\.next|out)\//;
7
- const TEST_RE = /(\.test\.|\.spec\.|__tests__\/|(^|\/)tests?\/|fixtures\/|\.d\.ts$)/;
8
-
9
- function isGitRepo(root) {
10
- try {
11
- execSync('git rev-parse --is-inside-work-tree', { cwd: root, stdio: 'ignore' });
12
- return true;
13
- } catch {
14
- return false;
15
- }
16
- }
17
-
18
- function walk(root, dir = '', out = []) {
19
- let entries;
20
- try {
21
- entries = fs.readdirSync(path.join(root, dir), { withFileTypes: true });
22
- } catch {
23
- return out;
24
- }
25
- for (const e of entries) {
26
- if (e.name.startsWith('.') && e.isDirectory()) continue;
27
- const rel = dir ? `${dir}/${e.name}` : e.name;
28
- if (e.isDirectory()) {
29
- if (!SKIP_RE.test(rel + '/')) walk(root, rel, out);
30
- } else {
31
- out.push(rel);
32
- }
33
- }
34
- return out;
35
- }
36
-
37
- /** Source files (relative paths), tests excluded unless includeTests. */
38
- function listSourceFiles(root, { includeTests = false } = {}) {
39
- let files;
40
- if (isGitRepo(root)) {
41
- files = execSync('git ls-files', { cwd: root, maxBuffer: 1 << 28 }).toString().split('\n').filter(Boolean);
42
- } else {
43
- files = walk(root);
44
- }
45
- return files.filter(f => SRC_RE.test(f) && !SKIP_RE.test(f) && (includeTests || !TEST_RE.test(f)));
46
- }
47
-
48
- function readSafe(root, rel, max = 200000) {
49
- try {
50
- return fs.readFileSync(path.join(root, rel), 'utf-8').slice(0, max);
51
- } catch {
52
- return '';
53
- }
54
- }
55
-
56
- module.exports = { listSourceFiles, readSafe, isGitRepo, SRC_RE, TEST_RE };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { execSync } = require('child_process');
4
+
5
+ const SRC_RE = /\.(ts|tsx|js|jsx|mjs|cjs)$/;
6
+ const SKIP_RE = /(^|\/)(node_modules|dist|build|coverage|\.next|out)\//;
7
+ const TEST_RE = /(\.test\.|\.spec\.|__tests__\/|(^|\/)tests?\/|fixtures\/|\.d\.ts$)/;
8
+
9
+ function isGitRepo(root) {
10
+ try {
11
+ execSync('git rev-parse --is-inside-work-tree', { cwd: root, stdio: 'ignore' });
12
+ return true;
13
+ } catch {
14
+ return false;
15
+ }
16
+ }
17
+
18
+ function walk(root, dir = '', out = []) {
19
+ let entries;
20
+ try {
21
+ entries = fs.readdirSync(path.join(root, dir), { withFileTypes: true });
22
+ } catch {
23
+ return out;
24
+ }
25
+ for (const e of entries) {
26
+ if (e.name.startsWith('.') && e.isDirectory()) continue;
27
+ const rel = dir ? `${dir}/${e.name}` : e.name;
28
+ if (e.isDirectory()) {
29
+ if (!SKIP_RE.test(rel + '/')) walk(root, rel, out);
30
+ } else {
31
+ out.push(rel);
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /** Source files (relative paths), tests excluded unless includeTests. */
38
+ function listSourceFiles(root, { includeTests = false } = {}) {
39
+ let files;
40
+ if (isGitRepo(root)) {
41
+ files = execSync('git ls-files', { cwd: root, maxBuffer: 1 << 28 }).toString().split('\n').filter(Boolean);
42
+ } else {
43
+ files = walk(root);
44
+ }
45
+ return files.filter(f => SRC_RE.test(f) && !SKIP_RE.test(f) && (includeTests || !TEST_RE.test(f)));
46
+ }
47
+
48
+ function readSafe(root, rel, max = 200000) {
49
+ try {
50
+ return fs.readFileSync(path.join(root, rel), 'utf-8').slice(0, max);
51
+ } catch {
52
+ return '';
53
+ }
54
+ }
55
+
56
+ module.exports = { listSourceFiles, readSafe, isGitRepo, SRC_RE, TEST_RE };
package/src/atlas/git.js CHANGED
@@ -1,65 +1,65 @@
1
- const { execSync } = require('child_process');
2
- const { isGitRepo } = require('./files');
3
-
4
- /**
5
- * Read recent commit history once.
6
- * @returns {{commits: {hash:string, date:string, subject:string, files:string[]}[]}}
7
- */
8
- function readHistoryRaw(root, { limit = 3000, skip = parseInt(process.env.CARTOTREE_HISTORY_SKIP || '0'), maxFilesPerCommit = 25 } = {}) {
9
- if (!isGitRepo(root)) return { commits: [] };
10
- let raw;
11
- try {
12
- raw = execSync(
13
- `git log -n ${limit} --skip=${skip} --no-merges --name-only --date=short --pretty=format:@@%h%x09%ad%x09%s`,
14
- { cwd: root, maxBuffer: 1 << 28 }
15
- ).toString();
16
- } catch {
17
- return { commits: [] };
18
- }
19
- const commits = [];
20
- for (const block of raw.split('@@').slice(1)) {
21
- const lines = block.split('\n').filter(Boolean);
22
- const [hash, date, ...subj] = lines[0].split('\t');
23
- const files = lines.slice(1);
24
- if (files.length && files.length <= maxFilesPerCommit) commits.push({ hash, date, subject: subj.join('\t'), files });
25
- }
26
- return { commits };
27
- }
28
-
29
- function readHistory(root, opts = {}) {
30
- const { cached } = require('./cache');
31
- return cached(root, 'history', opts, () => readHistoryRaw(root, opts));
32
- }
33
-
34
- /** How often each file changed (heat). */
35
- function heatMap(history) {
36
- const heat = new Map();
37
- for (const c of history.commits) for (const f of c.files) heat.set(f, (heat.get(f) || 0) + 1);
38
- return heat;
39
- }
40
-
41
- /** Files that usually change together with `file`. */
42
- function coChanges(history, file, top = 5) {
43
- const counts = new Map();
44
- let total = 0;
45
- for (const c of history.commits) {
46
- if (!c.files.includes(file)) continue;
47
- total++;
48
- for (const f of c.files) if (f !== file) counts.set(f, (counts.get(f) || 0) + 1);
49
- }
50
- return {
51
- total,
52
- files: [...counts.entries()]
53
- .sort((a, b) => b[1] - a[1])
54
- .slice(0, top)
55
- .map(([f, n]) => ({ file: f, together: n, ratio: +(n / total).toFixed(2) })),
56
- };
57
- }
58
-
59
- /** Recent commits touching a file. */
60
- function recentChanges(history, file, top = 3) {
61
- return history.commits.filter(c => c.files.includes(file)).slice(0, top)
62
- .map(({ hash, date, subject }) => ({ hash, date, subject }));
63
- }
64
-
65
- module.exports = { readHistory, heatMap, coChanges, recentChanges };
1
+ const { execSync } = require('child_process');
2
+ const { isGitRepo } = require('./files');
3
+
4
+ /**
5
+ * Read recent commit history once.
6
+ * @returns {{commits: {hash:string, date:string, subject:string, files:string[]}[]}}
7
+ */
8
+ function readHistoryRaw(root, { limit = 3000, skip = parseInt(process.env.CARTOTREE_HISTORY_SKIP || '0'), maxFilesPerCommit = 25 } = {}) {
9
+ if (!isGitRepo(root)) return { commits: [] };
10
+ let raw;
11
+ try {
12
+ raw = execSync(
13
+ `git log -n ${limit} --skip=${skip} --no-merges --name-only --date=short --pretty=format:@@%h%x09%ad%x09%s`,
14
+ { cwd: root, maxBuffer: 1 << 28 }
15
+ ).toString();
16
+ } catch {
17
+ return { commits: [] };
18
+ }
19
+ const commits = [];
20
+ for (const block of raw.split('@@').slice(1)) {
21
+ const lines = block.split('\n').filter(Boolean);
22
+ const [hash, date, ...subj] = lines[0].split('\t');
23
+ const files = lines.slice(1);
24
+ if (files.length && files.length <= maxFilesPerCommit) commits.push({ hash, date, subject: subj.join('\t'), files });
25
+ }
26
+ return { commits };
27
+ }
28
+
29
+ function readHistory(root, opts = {}) {
30
+ const { cached } = require('./cache');
31
+ return cached(root, 'history', opts, () => readHistoryRaw(root, opts));
32
+ }
33
+
34
+ /** How often each file changed (heat). */
35
+ function heatMap(history) {
36
+ const heat = new Map();
37
+ for (const c of history.commits) for (const f of c.files) heat.set(f, (heat.get(f) || 0) + 1);
38
+ return heat;
39
+ }
40
+
41
+ /** Files that usually change together with `file`. */
42
+ function coChanges(history, file, top = 5) {
43
+ const counts = new Map();
44
+ let total = 0;
45
+ for (const c of history.commits) {
46
+ if (!c.files.includes(file)) continue;
47
+ total++;
48
+ for (const f of c.files) if (f !== file) counts.set(f, (counts.get(f) || 0) + 1);
49
+ }
50
+ return {
51
+ total,
52
+ files: [...counts.entries()]
53
+ .sort((a, b) => b[1] - a[1])
54
+ .slice(0, top)
55
+ .map(([f, n]) => ({ file: f, together: n, ratio: +(n / total).toFixed(2) })),
56
+ };
57
+ }
58
+
59
+ /** Recent commits touching a file. */
60
+ function recentChanges(history, file, top = 3) {
61
+ return history.commits.filter(c => c.files.includes(file)).slice(0, top)
62
+ .map(({ hash, date, subject }) => ({ hash, date, subject }));
63
+ }
64
+
65
+ module.exports = { readHistory, heatMap, coChanges, recentChanges };