@yawlabs/ctxlint 0.2.2 → 0.4.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.
package/dist/index.js CHANGED
@@ -1,1279 +1,9 @@
1
1
  #!/usr/bin/env node
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
- }) : x)(function(x) {
5
- if (typeof require !== "undefined") return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
2
 
9
3
  // src/index.ts
10
- import { Command } from "commander";
11
- import ora from "ora";
12
-
13
- // src/core/scanner.ts
14
- import * as fs2 from "fs";
15
- import * as path2 from "path";
16
- import { glob } from "glob";
17
-
18
- // src/utils/fs.ts
19
- import * as fs from "fs";
20
- import * as path from "path";
21
- function loadPackageJson(projectRoot) {
22
- try {
23
- const content = fs.readFileSync(path.join(projectRoot, "package.json"), "utf-8");
24
- return JSON.parse(content);
25
- } catch {
26
- return null;
27
- }
28
- }
29
- function fileExists(filePath) {
30
- try {
31
- fs.accessSync(filePath);
32
- return true;
33
- } catch {
34
- return false;
35
- }
36
- }
37
- function isDirectory(filePath) {
38
- try {
39
- return fs.statSync(filePath).isDirectory();
40
- } catch {
41
- return false;
42
- }
43
- }
44
- function isSymlink(filePath) {
45
- try {
46
- return fs.lstatSync(filePath).isSymbolicLink();
47
- } catch {
48
- return false;
49
- }
50
- }
51
- function readSymlinkTarget(filePath) {
52
- try {
53
- return fs.readlinkSync(filePath);
54
- } catch {
55
- return void 0;
56
- }
57
- }
58
- function readFileContent(filePath) {
59
- return fs.readFileSync(filePath, "utf-8");
60
- }
61
- var IGNORED_DIRS = /* @__PURE__ */ new Set([
62
- "node_modules",
63
- ".git",
64
- "dist",
65
- "build",
66
- "vendor",
67
- ".next",
68
- ".nuxt",
69
- "coverage",
70
- "__pycache__"
71
- ]);
72
- function getAllProjectFiles(projectRoot) {
73
- const files = [];
74
- function walk(dir, depth) {
75
- if (depth > 10) return;
76
- try {
77
- const entries = fs.readdirSync(dir, { withFileTypes: true });
78
- for (const entry of entries) {
79
- if (IGNORED_DIRS.has(entry.name)) continue;
80
- const fullPath = path.join(dir, entry.name);
81
- if (entry.isDirectory()) {
82
- walk(fullPath, depth + 1);
83
- } else {
84
- files.push(path.relative(projectRoot, fullPath));
85
- }
86
- }
87
- } catch {
88
- }
89
- }
90
- walk(projectRoot, 0);
91
- return files;
92
- }
93
-
94
- // src/core/scanner.ts
95
- var CONTEXT_FILE_PATTERNS = [
96
- "CLAUDE.md",
97
- "CLAUDE.local.md",
98
- "AGENTS.md",
99
- ".cursorrules",
100
- ".cursor/rules/*.md",
101
- ".cursor/rules/*.mdc",
102
- "copilot-instructions.md",
103
- ".github/copilot-instructions.md",
104
- ".github/instructions/*.md",
105
- ".windsurfrules",
106
- ".windsurf/rules/*.md",
107
- "GEMINI.md",
108
- "JULES.md",
109
- ".clinerules",
110
- "CONVENTIONS.md",
111
- "CODEX.md",
112
- ".aiderules",
113
- ".aide/rules/*.md",
114
- ".amazonq/rules/*.md",
115
- ".goose/instructions.md"
116
- ];
117
- var IGNORED_DIRS2 = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "build", "vendor"]);
118
- async function scanForContextFiles(projectRoot) {
119
- const found = [];
120
- const seen = /* @__PURE__ */ new Set();
121
- const dirsToScan = [projectRoot];
122
- try {
123
- const entries = fs2.readdirSync(projectRoot, { withFileTypes: true });
124
- for (const entry of entries) {
125
- if (entry.isDirectory() && !IGNORED_DIRS2.has(entry.name) && !entry.name.startsWith(".")) {
126
- dirsToScan.push(path2.join(projectRoot, entry.name));
127
- }
128
- }
129
- } catch {
130
- }
131
- for (const dir of dirsToScan) {
132
- for (const pattern of CONTEXT_FILE_PATTERNS) {
133
- const matches = await glob(pattern, {
134
- cwd: dir,
135
- absolute: true,
136
- nodir: true,
137
- dot: true
138
- });
139
- for (const match of matches) {
140
- const normalized = path2.normalize(match);
141
- if (seen.has(normalized)) continue;
142
- seen.add(normalized);
143
- const relativePath = path2.relative(projectRoot, normalized);
144
- const symlink = isSymlink(normalized);
145
- const target = symlink ? readSymlinkTarget(normalized) : void 0;
146
- found.push({
147
- absolutePath: normalized,
148
- relativePath: relativePath.replace(/\\/g, "/"),
149
- isSymlink: symlink,
150
- symlinkTarget: target
151
- });
152
- }
153
- }
154
- }
155
- return found.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
156
- }
157
-
158
- // src/utils/tokens.ts
159
- import { encoding_for_model } from "tiktoken";
160
- var encoder = null;
161
- function getEncoder() {
162
- if (!encoder) {
163
- encoder = encoding_for_model("gpt-4");
164
- }
165
- return encoder;
166
- }
167
- function countTokens(text) {
168
- try {
169
- const enc = getEncoder();
170
- const tokens = enc.encode(text);
171
- return tokens.length;
172
- } catch {
173
- return Math.ceil(text.length / 4);
174
- }
175
- }
176
- function freeEncoder() {
177
- if (encoder) {
178
- encoder.free();
179
- encoder = null;
180
- }
181
- }
182
-
183
- // src/core/parser.ts
184
- var PATH_PATTERN = /(?:^|[\s`"'(])((\.{0,2}\/)?(?:[\w@.-]+\/)+[\w.*-]+(?:\.\w+)?)(?=[\s`"'),;:]|$)/gm;
185
- var PATH_EXCLUDE = /^(https?:\/\/|ftp:\/\/|mailto:|n\/a|w\/o|I\/O|i\/o|e\.g\.|N\/A|\.deb\/|\.rpm[.\/]|\.tar[.\/]|\.zip[.\/])/i;
186
- var COMMAND_PREFIXES = /^\s*[\$>]\s+(.+)$/;
187
- var COMMON_COMMANDS = /^(npm\s+run|npx|pnpm|yarn|make|cargo|go\s+(run|build|test)|python|pytest|vitest|jest|bun|deno)\b/;
188
- function parseContextFile(file) {
189
- const content = readFileContent(file.absolutePath);
190
- const lines = content.split("\n");
191
- const sections = parseSections(lines);
192
- const paths = extractPathReferences(lines, sections);
193
- const commands = extractCommandReferences(lines, sections);
194
- return {
195
- filePath: file.absolutePath,
196
- relativePath: file.relativePath,
197
- isSymlink: file.isSymlink,
198
- symlinkTarget: file.symlinkTarget,
199
- totalTokens: countTokens(content),
200
- totalLines: lines.length,
201
- content,
202
- sections,
203
- references: {
204
- paths,
205
- commands
206
- }
207
- };
208
- }
209
- function parseSections(lines) {
210
- const sections = [];
211
- for (let i = 0; i < lines.length; i++) {
212
- const match = lines[i].match(/^(#{1,6})\s+(.+)/);
213
- if (match) {
214
- if (sections.length > 0) {
215
- const prev = sections[sections.length - 1];
216
- if (prev.endLine === -1) {
217
- prev.endLine = i - 1;
218
- }
219
- }
220
- sections.push({
221
- title: match[2].trim(),
222
- startLine: i + 1,
223
- // 1-indexed
224
- endLine: -1,
225
- level: match[1].length
226
- });
227
- }
228
- }
229
- if (sections.length > 0) {
230
- const last = sections[sections.length - 1];
231
- if (last.endLine === -1) {
232
- last.endLine = lines.length;
233
- }
234
- }
235
- return sections;
236
- }
237
- function getSectionForLine(line, sections) {
238
- for (let i = sections.length - 1; i >= 0; i--) {
239
- if (line >= sections[i].startLine) {
240
- return sections[i].title;
241
- }
242
- }
243
- return void 0;
244
- }
245
- function extractPathReferences(lines, sections) {
246
- const paths = [];
247
- let inCodeBlock = false;
248
- let codeBlockLang = "";
249
- for (let i = 0; i < lines.length; i++) {
250
- const line = lines[i];
251
- if (line.trimStart().startsWith("```")) {
252
- if (!inCodeBlock) {
253
- inCodeBlock = true;
254
- codeBlockLang = line.trimStart().slice(3).trim().toLowerCase();
255
- } else {
256
- inCodeBlock = false;
257
- codeBlockLang = "";
258
- }
259
- continue;
260
- }
261
- if (inCodeBlock && isExampleCodeBlock(codeBlockLang)) {
262
- continue;
263
- }
264
- PATH_PATTERN.lastIndex = 0;
265
- let match;
266
- while ((match = PATH_PATTERN.exec(line)) !== null) {
267
- const value = match[1];
268
- if (PATH_EXCLUDE.test(value)) continue;
269
- if (value.length < 3) continue;
270
- if (/^v?\d+\.\d+\//.test(value)) continue;
271
- const column = match.index + match[0].length - match[1].length + 1;
272
- paths.push({
273
- value,
274
- line: i + 1,
275
- // 1-indexed
276
- column,
277
- section: getSectionForLine(i + 1, sections)
278
- });
279
- }
280
- }
281
- return paths;
282
- }
283
- function isExampleCodeBlock(lang) {
284
- return [
285
- "javascript",
286
- "js",
287
- "typescript",
288
- "ts",
289
- "python",
290
- "py",
291
- "go",
292
- "rust",
293
- "java",
294
- "c",
295
- "cpp",
296
- "ruby",
297
- "php",
298
- "json",
299
- "yaml",
300
- "yml",
301
- "toml",
302
- "xml",
303
- "html",
304
- "css",
305
- "sql",
306
- "graphql",
307
- "jsx",
308
- "tsx"
309
- ].includes(lang);
310
- }
311
- function extractCommandReferences(lines, sections) {
312
- const commands = [];
313
- let inCodeBlock = false;
314
- let codeBlockLang = "";
315
- for (let i = 0; i < lines.length; i++) {
316
- const line = lines[i];
317
- if (line.trimStart().startsWith("```")) {
318
- if (!inCodeBlock) {
319
- inCodeBlock = true;
320
- codeBlockLang = line.trimStart().slice(3).trim().toLowerCase();
321
- } else {
322
- inCodeBlock = false;
323
- codeBlockLang = "";
324
- }
325
- continue;
326
- }
327
- const prefixMatch = line.match(COMMAND_PREFIXES);
328
- if (prefixMatch) {
329
- commands.push({
330
- value: prefixMatch[1].trim(),
331
- line: i + 1,
332
- column: prefixMatch.index + prefixMatch[0].length - prefixMatch[1].length + 1,
333
- section: getSectionForLine(i + 1, sections)
334
- });
335
- continue;
336
- }
337
- if (inCodeBlock && ["bash", "sh", "shell", "zsh", ""].includes(codeBlockLang)) {
338
- const trimmed = line.trim();
339
- if (trimmed && !trimmed.startsWith("#") && !trimmed.startsWith("//")) {
340
- if (COMMON_COMMANDS.test(trimmed) || trimmed.startsWith("$") || trimmed.startsWith(">")) {
341
- const cmd = trimmed.replace(/^\s*[\$>]\s*/, "");
342
- if (cmd) {
343
- const cmdStart = line.indexOf(trimmed) + trimmed.indexOf(cmd);
344
- commands.push({
345
- value: cmd,
346
- line: i + 1,
347
- column: cmdStart + 1,
348
- section: getSectionForLine(i + 1, sections)
349
- });
350
- }
351
- }
352
- }
353
- continue;
354
- }
355
- const inlineMatches = line.matchAll(/`([^`]+)`/g);
356
- for (const m of inlineMatches) {
357
- const cmd = m[1].trim();
358
- if (COMMON_COMMANDS.test(cmd)) {
359
- commands.push({
360
- value: cmd,
361
- line: i + 1,
362
- column: (m.index ?? 0) + 2,
363
- section: getSectionForLine(i + 1, sections)
364
- });
365
- }
366
- }
367
- }
368
- return commands;
369
- }
370
-
371
- // src/core/checks/paths.ts
372
- import * as path3 from "path";
373
- import levenshteinPkg from "fast-levenshtein";
374
- import { glob as glob2 } from "glob";
375
-
376
- // src/utils/git.ts
377
- import simpleGit from "simple-git";
378
- var gitInstance = null;
379
- var gitProjectRoot = null;
380
- function getGit(projectRoot) {
381
- if (!gitInstance || gitProjectRoot !== projectRoot) {
382
- gitInstance = simpleGit(projectRoot);
383
- gitProjectRoot = projectRoot;
384
- }
385
- return gitInstance;
386
- }
387
- function resetGit() {
388
- gitInstance = null;
389
- gitProjectRoot = null;
390
- }
391
- async function isGitRepo(projectRoot) {
392
- try {
393
- const git = simpleGit(projectRoot);
394
- await git.revparse(["--is-inside-work-tree"]);
395
- return true;
396
- } catch {
397
- return false;
398
- }
399
- }
400
- async function getFileLastModified(projectRoot, filePath) {
401
- try {
402
- const git = getGit(projectRoot);
403
- const log = await git.log({ file: filePath, maxCount: 1 });
404
- if (log.latest?.date) {
405
- return new Date(log.latest.date);
406
- }
407
- return null;
408
- } catch {
409
- return null;
410
- }
411
- }
412
- async function getCommitsSince(projectRoot, filePath, since) {
413
- try {
414
- const git = getGit(projectRoot);
415
- const log = await git.log({
416
- file: filePath,
417
- "--since": since.toISOString()
418
- });
419
- return log.total;
420
- } catch {
421
- return 0;
422
- }
423
- }
424
- async function findRenames(projectRoot, filePath) {
425
- try {
426
- const git = getGit(projectRoot);
427
- const result = await git.raw([
428
- "log",
429
- "--diff-filter=R",
430
- "--find-renames",
431
- "--name-status",
432
- "--format=%H %ai",
433
- "-10",
434
- "--",
435
- filePath
436
- ]);
437
- if (!result.trim()) return null;
438
- const lines = result.trim().split("\n");
439
- for (let i = 0; i < lines.length; i++) {
440
- const line = lines[i];
441
- if (line.startsWith("R")) {
442
- const parts = line.split(" ");
443
- if (parts.length >= 3) {
444
- const hashLine = lines[i - 1] || "";
445
- const hashMatch = hashLine.match(/^([a-f0-9]+)\s+(.+)/);
446
- const commitHash = hashMatch?.[1]?.substring(0, 7) || "unknown";
447
- const dateStr = hashMatch?.[2];
448
- const daysAgo = dateStr ? Math.floor((Date.now() - new Date(dateStr).getTime()) / (1e3 * 60 * 60 * 24)) : 0;
449
- return {
450
- oldPath: parts[1],
451
- newPath: parts[2],
452
- commitHash,
453
- daysAgo
454
- };
455
- }
456
- }
457
- }
458
- return null;
459
- } catch {
460
- return null;
461
- }
462
- }
463
-
464
- // src/core/checks/paths.ts
465
- var levenshtein = levenshteinPkg.get;
466
- var cachedProjectFiles = null;
467
- function getProjectFiles(projectRoot) {
468
- if (cachedProjectFiles?.root === projectRoot) return cachedProjectFiles.files;
469
- const files = getAllProjectFiles(projectRoot);
470
- cachedProjectFiles = { root: projectRoot, files };
471
- return files;
472
- }
473
- function resetPathsCache() {
474
- cachedProjectFiles = null;
475
- }
476
- async function checkPaths(file, projectRoot) {
477
- const issues = [];
478
- const projectFiles = getProjectFiles(projectRoot);
479
- const contextDir = path3.dirname(file.filePath);
480
- for (const ref of file.references.paths) {
481
- const baseDir = ref.value.startsWith("./") || ref.value.startsWith("../") ? contextDir : projectRoot;
482
- const resolvedPath = path3.resolve(baseDir, ref.value);
483
- const normalizedRef = ref.value.replace(/\\/g, "/");
484
- if (normalizedRef.includes("*")) {
485
- const matches = await glob2(normalizedRef, { cwd: baseDir, nodir: false });
486
- if (matches.length === 0) {
487
- issues.push({
488
- severity: "error",
489
- check: "paths",
490
- line: ref.line,
491
- message: `${ref.value} matches no files`,
492
- suggestion: "Verify the glob pattern is correct"
493
- });
494
- }
495
- continue;
496
- }
497
- const isDir = normalizedRef.endsWith("/");
498
- if (isDir) {
499
- const dirPath = path3.resolve(baseDir, normalizedRef);
500
- if (!isDirectory(dirPath)) {
501
- issues.push({
502
- severity: "error",
503
- check: "paths",
504
- line: ref.line,
505
- message: `${ref.value} directory does not exist`
506
- });
507
- }
508
- continue;
509
- }
510
- if (fileExists(resolvedPath) || isDirectory(resolvedPath)) {
511
- continue;
512
- }
513
- let suggestion;
514
- let detail;
515
- let fixTarget;
516
- const rename = await findRenames(projectRoot, ref.value);
517
- if (rename) {
518
- fixTarget = rename.newPath;
519
- suggestion = `Did you mean ${rename.newPath}?`;
520
- detail = `Renamed ${rename.daysAgo} days ago in commit ${rename.commitHash}`;
521
- } else {
522
- const match = findClosestMatch(normalizedRef, projectFiles);
523
- if (match) {
524
- fixTarget = match;
525
- suggestion = `Did you mean ${match}?`;
526
- }
527
- }
528
- issues.push({
529
- severity: "error",
530
- check: "paths",
531
- line: ref.line,
532
- message: `${ref.value} does not exist`,
533
- suggestion,
534
- detail,
535
- fix: fixTarget ? { file: file.filePath, line: ref.line, oldText: ref.value, newText: fixTarget } : void 0
536
- });
537
- }
538
- return issues;
4
+ if (process.argv.includes("--mcp")) {
5
+ await import("./server-7C2IQ7VV.js");
6
+ } else {
7
+ const { runCli } = await import("./cli-VYWAONGX.js");
8
+ await runCli();
539
9
  }
540
- function findClosestMatch(target, files) {
541
- const targetNorm = target.replace(/\\/g, "/");
542
- const targetBase = path3.basename(targetNorm);
543
- let bestMatch = null;
544
- let bestDistance = Infinity;
545
- for (const file of files) {
546
- const fileNorm = file.replace(/\\/g, "/");
547
- if (path3.basename(fileNorm) === targetBase && fileNorm !== targetNorm) {
548
- const dist = levenshtein(targetNorm, fileNorm);
549
- if (dist < bestDistance) {
550
- bestDistance = dist;
551
- bestMatch = fileNorm;
552
- }
553
- }
554
- }
555
- if (!bestMatch) {
556
- for (const file of files) {
557
- const fileNorm = file.replace(/\\/g, "/");
558
- const dist = levenshtein(targetNorm, fileNorm);
559
- if (dist < bestDistance && dist <= Math.max(targetNorm.length * 0.4, 5)) {
560
- bestDistance = dist;
561
- bestMatch = fileNorm;
562
- }
563
- }
564
- }
565
- return bestMatch;
566
- }
567
-
568
- // src/core/checks/commands.ts
569
- import * as fs3 from "fs";
570
- import * as path4 from "path";
571
- var NPM_SCRIPT_PATTERN = /^(?:npm\s+run|pnpm(?:\s+run)?|yarn(?:\s+run)?|bun(?:\s+run)?)\s+(\S+)/;
572
- var MAKE_PATTERN = /^make\s+(\S+)/;
573
- async function checkCommands(file, projectRoot) {
574
- const issues = [];
575
- const pkgJson = loadPackageJson(projectRoot);
576
- const makefile = loadMakefile(projectRoot);
577
- for (const ref of file.references.commands) {
578
- const cmd = ref.value;
579
- const scriptMatch = cmd.match(NPM_SCRIPT_PATTERN);
580
- if (scriptMatch && pkgJson) {
581
- const scriptName = scriptMatch[1];
582
- if (pkgJson.scripts && !(scriptName in pkgJson.scripts)) {
583
- const available = Object.keys(pkgJson.scripts).join(", ");
584
- issues.push({
585
- severity: "error",
586
- check: "commands",
587
- line: ref.line,
588
- message: `"${cmd}" \u2014 script "${scriptName}" not found in package.json`,
589
- suggestion: available ? `Available scripts: ${available}` : void 0
590
- });
591
- }
592
- continue;
593
- }
594
- const shorthandMatch = cmd.match(/^(npm|pnpm|yarn|bun)\s+(test|start|build|dev|lint|format|check|typecheck|clean|serve|preview|e2e)\b/);
595
- if (shorthandMatch && pkgJson) {
596
- const scriptName = shorthandMatch[2];
597
- if (pkgJson.scripts && !(scriptName in pkgJson.scripts)) {
598
- issues.push({
599
- severity: "error",
600
- check: "commands",
601
- line: ref.line,
602
- message: `"${cmd}" \u2014 script "${scriptName}" not found in package.json`
603
- });
604
- }
605
- continue;
606
- }
607
- const makeMatch = cmd.match(MAKE_PATTERN);
608
- if (makeMatch) {
609
- const target = makeMatch[1];
610
- if (makefile && !hasMakeTarget(makefile, target)) {
611
- issues.push({
612
- severity: "error",
613
- check: "commands",
614
- line: ref.line,
615
- message: `"${cmd}" \u2014 target "${target}" not found in Makefile`
616
- });
617
- } else if (!makefile) {
618
- issues.push({
619
- severity: "error",
620
- check: "commands",
621
- line: ref.line,
622
- message: `"${cmd}" \u2014 no Makefile found in project`
623
- });
624
- }
625
- continue;
626
- }
627
- const toolMatch = cmd.match(/^(vitest|jest|pytest|mocha|eslint|prettier|tsc)\b/);
628
- if (toolMatch && pkgJson) {
629
- const tool = toolMatch[1];
630
- const allDeps = {
631
- ...pkgJson.dependencies,
632
- ...pkgJson.devDependencies
633
- };
634
- if (!(tool in allDeps)) {
635
- const binPath = path4.join(projectRoot, "node_modules", ".bin", tool);
636
- try {
637
- fs3.accessSync(binPath);
638
- } catch {
639
- issues.push({
640
- severity: "warning",
641
- check: "commands",
642
- line: ref.line,
643
- message: `"${cmd}" \u2014 "${tool}" not found in dependencies or node_modules/.bin`
644
- });
645
- }
646
- }
647
- }
648
- }
649
- return issues;
650
- }
651
- function loadMakefile(projectRoot) {
652
- try {
653
- return fs3.readFileSync(path4.join(projectRoot, "Makefile"), "utf-8");
654
- } catch {
655
- return null;
656
- }
657
- }
658
- function hasMakeTarget(makefile, target) {
659
- const pattern = new RegExp(`^${target.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*:`, "m");
660
- return pattern.test(makefile);
661
- }
662
-
663
- // src/core/checks/staleness.ts
664
- import * as path5 from "path";
665
- var WARNING_DAYS = 30;
666
- var INFO_DAYS = 14;
667
- async function checkStaleness(file, projectRoot) {
668
- const issues = [];
669
- if (!await isGitRepo(projectRoot)) {
670
- return issues;
671
- }
672
- const relativePath = path5.relative(projectRoot, file.filePath).replace(/\\/g, "/");
673
- const lastModified = await getFileLastModified(projectRoot, relativePath);
674
- if (!lastModified || isNaN(lastModified.getTime())) {
675
- return issues;
676
- }
677
- const daysSinceUpdate = Math.floor((Date.now() - lastModified.getTime()) / (1e3 * 60 * 60 * 24));
678
- if (daysSinceUpdate < INFO_DAYS) {
679
- return issues;
680
- }
681
- const referencedPaths = /* @__PURE__ */ new Set();
682
- for (const ref of file.references.paths) {
683
- const parts = ref.value.split("/");
684
- if (parts.length > 1) {
685
- referencedPaths.add(parts.slice(0, -1).join("/"));
686
- }
687
- referencedPaths.add(ref.value);
688
- }
689
- let totalCommits = 0;
690
- let mostActiveRef = "";
691
- let mostActiveCommits = 0;
692
- for (const refPath of referencedPaths) {
693
- const commits = await getCommitsSince(projectRoot, refPath, lastModified);
694
- totalCommits += commits;
695
- if (commits > mostActiveCommits) {
696
- mostActiveCommits = commits;
697
- mostActiveRef = refPath;
698
- }
699
- }
700
- if (totalCommits === 0) {
701
- return issues;
702
- }
703
- const severity = daysSinceUpdate >= WARNING_DAYS ? "warning" : "info";
704
- issues.push({
705
- severity,
706
- check: "staleness",
707
- line: 1,
708
- message: `Last updated ${daysSinceUpdate} days ago. ${mostActiveRef} has ${mostActiveCommits} commits since.`,
709
- suggestion: "Review and update this context file to reflect recent changes.",
710
- detail: `${totalCommits} total commits to referenced paths since last update.`
711
- });
712
- return issues;
713
- }
714
-
715
- // src/core/checks/tokens.ts
716
- var DEFAULT_THRESHOLDS = {
717
- info: 1e3,
718
- warning: 3e3,
719
- error: 8e3,
720
- aggregate: 5e3
721
- };
722
- var currentThresholds = DEFAULT_THRESHOLDS;
723
- function setTokenThresholds(overrides) {
724
- currentThresholds = { ...DEFAULT_THRESHOLDS, ...overrides };
725
- }
726
- function resetTokenThresholds() {
727
- currentThresholds = DEFAULT_THRESHOLDS;
728
- }
729
- async function checkTokens(file, _projectRoot) {
730
- const issues = [];
731
- const tokens = file.totalTokens;
732
- if (tokens >= currentThresholds.error) {
733
- issues.push({
734
- severity: "error",
735
- check: "tokens",
736
- line: 1,
737
- message: `${tokens.toLocaleString()} tokens \u2014 consumes significant context window space`,
738
- suggestion: "Consider splitting into focused sections or removing redundant content."
739
- });
740
- } else if (tokens >= currentThresholds.warning) {
741
- issues.push({
742
- severity: "warning",
743
- check: "tokens",
744
- line: 1,
745
- message: `${tokens.toLocaleString()} tokens \u2014 large context file`,
746
- suggestion: "Consider trimming \u2014 research shows diminishing returns past ~300 lines."
747
- });
748
- } else if (tokens >= currentThresholds.info) {
749
- issues.push({
750
- severity: "info",
751
- check: "tokens",
752
- line: 1,
753
- message: `Uses ~${tokens.toLocaleString()} tokens per session`
754
- });
755
- }
756
- return issues;
757
- }
758
- function checkAggregateTokens(files) {
759
- const total = files.reduce((sum, f) => sum + f.tokens, 0);
760
- if (total > currentThresholds.aggregate && files.length > 1) {
761
- return {
762
- severity: "warning",
763
- check: "tokens",
764
- line: 0,
765
- message: `${files.length} context files consume ${total.toLocaleString()} tokens combined`,
766
- suggestion: "Consider consolidating or trimming to reduce per-session context cost."
767
- };
768
- }
769
- return null;
770
- }
771
-
772
- // src/core/checks/redundancy.ts
773
- import * as path6 from "path";
774
- var PACKAGE_TECH_MAP = {
775
- react: ["React", "react"],
776
- "react-dom": ["React DOM", "ReactDOM"],
777
- next: ["Next.js", "NextJS", "next.js"],
778
- express: ["Express", "express.js"],
779
- fastify: ["Fastify"],
780
- typescript: ["TypeScript"],
781
- vue: ["Vue", "Vue.js", "vue.js"],
782
- angular: ["Angular"],
783
- svelte: ["Svelte", "SvelteKit"],
784
- tailwindcss: ["Tailwind", "TailwindCSS", "tailwind"],
785
- prisma: ["Prisma"],
786
- drizzle: ["Drizzle"],
787
- "drizzle-orm": ["Drizzle"],
788
- jest: ["Jest"],
789
- vitest: ["Vitest"],
790
- mocha: ["Mocha"],
791
- eslint: ["ESLint"],
792
- prettier: ["Prettier"],
793
- webpack: ["Webpack"],
794
- vite: ["Vite"],
795
- esbuild: ["esbuild"],
796
- tsup: ["tsup"],
797
- rollup: ["Rollup"],
798
- graphql: ["GraphQL"],
799
- mongoose: ["Mongoose"],
800
- sequelize: ["Sequelize"],
801
- "socket.io": ["Socket.IO", "socket.io"],
802
- redis: ["Redis"],
803
- ioredis: ["Redis"],
804
- postgres: ["PostgreSQL", "Postgres"],
805
- pg: ["PostgreSQL", "Postgres"],
806
- mysql2: ["MySQL"],
807
- sqlite3: ["SQLite"],
808
- "better-sqlite3": ["SQLite"],
809
- zod: ["Zod"],
810
- joi: ["Joi"],
811
- axios: ["Axios"],
812
- lodash: ["Lodash", "lodash"],
813
- underscore: ["Underscore"],
814
- moment: ["Moment", "moment.js"],
815
- dayjs: ["Day.js", "dayjs"],
816
- "date-fns": ["date-fns"],
817
- docker: ["Docker"],
818
- kubernetes: ["Kubernetes", "K8s"],
819
- terraform: ["Terraform"],
820
- storybook: ["Storybook"],
821
- playwright: ["Playwright"],
822
- cypress: ["Cypress"],
823
- puppeteer: ["Puppeteer"]
824
- };
825
- async function checkRedundancy(file, projectRoot) {
826
- const issues = [];
827
- const pkgJson = loadPackageJson(projectRoot);
828
- if (pkgJson) {
829
- const allDeps = /* @__PURE__ */ new Set([
830
- ...Object.keys(pkgJson.dependencies || {}),
831
- ...Object.keys(pkgJson.devDependencies || {})
832
- ]);
833
- const lines2 = file.content.split("\n");
834
- for (let i = 0; i < lines2.length; i++) {
835
- const line = lines2[i];
836
- for (const [pkg, mentions] of Object.entries(PACKAGE_TECH_MAP)) {
837
- if (!allDeps.has(pkg)) continue;
838
- for (const mention of mentions) {
839
- const patterns = [
840
- new RegExp(
841
- `\\b(?:use|using|built with|powered by|written in)\\s+${escapeRegex(mention)}\\b`,
842
- "i"
843
- ),
844
- new RegExp(`\\bwe\\s+use\\s+${escapeRegex(mention)}\\b`, "i"),
845
- new RegExp(
846
- `\\b${escapeRegex(mention)}\\s+(?:project|app|application|codebase)\\b`,
847
- "i"
848
- ),
849
- new RegExp(`\\bThis is a\\s+${escapeRegex(mention)}\\b`, "i")
850
- ];
851
- for (const pattern of patterns) {
852
- if (pattern.test(line)) {
853
- const wastedTokens = countTokens(line.trim());
854
- issues.push({
855
- severity: "info",
856
- check: "redundancy",
857
- line: i + 1,
858
- message: `"${mention}" is in package.json ${pkgJson.dependencies?.[pkg] ? "dependencies" : "devDependencies"} \u2014 agent can infer this`,
859
- suggestion: `~${wastedTokens} tokens could be saved`
860
- });
861
- break;
862
- }
863
- }
864
- }
865
- }
866
- }
867
- }
868
- const lines = file.content.split("\n");
869
- for (let i = 0; i < lines.length; i++) {
870
- const line = lines[i];
871
- const dirMatch = line.match(
872
- /(?:are|go|live|found|located|stored)\s+(?:in|at|under)\s+[`"]?(\S+\/)[`"]?/i
873
- );
874
- if (dirMatch) {
875
- const dir = dirMatch[1].replace(/[`"]/g, "");
876
- const fullPath = path6.resolve(projectRoot, dir);
877
- if (isDirectory(fullPath)) {
878
- issues.push({
879
- severity: "info",
880
- check: "redundancy",
881
- line: i + 1,
882
- message: `Directory "${dir}" exists and is discoverable \u2014 agent can find this by listing files`,
883
- suggestion: "Only keep if there is non-obvious context about this directory"
884
- });
885
- }
886
- }
887
- }
888
- return issues;
889
- }
890
- function checkDuplicateContent(files) {
891
- const issues = [];
892
- for (let i = 0; i < files.length; i++) {
893
- for (let j = i + 1; j < files.length; j++) {
894
- const overlap = calculateLineOverlap(files[i].content, files[j].content);
895
- if (overlap > 0.6) {
896
- issues.push({
897
- severity: "warning",
898
- check: "redundancy",
899
- line: 1,
900
- message: `${files[i].relativePath} and ${files[j].relativePath} have ${Math.round(overlap * 100)}% content overlap`,
901
- suggestion: "Consider consolidating into a single context file"
902
- });
903
- }
904
- }
905
- }
906
- return issues;
907
- }
908
- function calculateLineOverlap(contentA, contentB) {
909
- const linesA = new Set(
910
- contentA.split("\n").map((l) => l.trim()).filter((l) => l.length > 10)
911
- );
912
- const linesB = new Set(
913
- contentB.split("\n").map((l) => l.trim()).filter((l) => l.length > 10)
914
- );
915
- if (linesA.size === 0 || linesB.size === 0) return 0;
916
- let overlap = 0;
917
- for (const line of linesA) {
918
- if (linesB.has(line)) overlap++;
919
- }
920
- return overlap / Math.min(linesA.size, linesB.size);
921
- }
922
- function escapeRegex(str) {
923
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
924
- }
925
-
926
- // src/core/reporter.ts
927
- import chalk from "chalk";
928
- function formatText(result, verbose = false) {
929
- const lines = [];
930
- lines.push("");
931
- lines.push(chalk.bold(`ctxlint v${result.version}`));
932
- lines.push("");
933
- lines.push(`Scanning ${result.projectRoot}...`);
934
- lines.push("");
935
- const totalTokens = result.summary.totalTokens;
936
- lines.push(
937
- `Found ${result.files.length} context file${result.files.length !== 1 ? "s" : ""} (${totalTokens.toLocaleString()} tokens total)`
938
- );
939
- for (const file of result.files) {
940
- let desc = ` ${file.path} (${file.tokens.toLocaleString()} tokens, ${file.lines} lines)`;
941
- if (file.isSymlink && file.symlinkTarget) {
942
- desc = ` ${file.path} ${chalk.dim(`\u2192 ${file.symlinkTarget} (symlink)`)}`;
943
- }
944
- lines.push(desc);
945
- }
946
- lines.push("");
947
- for (const file of result.files) {
948
- const fileIssues = file.issues;
949
- if (fileIssues.length === 0 && !verbose) continue;
950
- lines.push(chalk.underline(file.path));
951
- if (fileIssues.length === 0) {
952
- lines.push(chalk.green(" \u2713 All checks passed"));
953
- } else {
954
- for (const issue of fileIssues) {
955
- lines.push(formatIssue(issue));
956
- }
957
- }
958
- lines.push("");
959
- }
960
- const { errors, warnings, info } = result.summary;
961
- const parts = [];
962
- if (errors > 0) parts.push(chalk.red(`${errors} error${errors !== 1 ? "s" : ""}`));
963
- if (warnings > 0) parts.push(chalk.yellow(`${warnings} warning${warnings !== 1 ? "s" : ""}`));
964
- if (info > 0) parts.push(chalk.blue(`${info} info`));
965
- if (parts.length > 0) {
966
- lines.push(`Summary: ${parts.join(", ")}`);
967
- } else {
968
- lines.push(chalk.green("No issues found!"));
969
- }
970
- lines.push(` Token usage: ${totalTokens.toLocaleString()} tokens per agent session`);
971
- if (result.summary.estimatedWaste > 0) {
972
- lines.push(` Estimated waste: ~${result.summary.estimatedWaste} tokens (redundant content)`);
973
- }
974
- lines.push("");
975
- return lines.join("\n");
976
- }
977
- function formatJson(result) {
978
- return JSON.stringify(result, null, 2);
979
- }
980
- function formatTokenReport(result) {
981
- const lines = [];
982
- lines.push("");
983
- lines.push(chalk.bold("Token Usage Report"));
984
- lines.push("");
985
- const maxPathLen = Math.max(...result.files.map((f) => f.path.length), 4);
986
- lines.push(
987
- ` ${chalk.dim("File".padEnd(maxPathLen))} ${chalk.dim("Tokens".padStart(8))} ${chalk.dim("Lines".padStart(6))}`
988
- );
989
- lines.push(` ${"\u2500".repeat(maxPathLen)} ${"\u2500".repeat(8)} ${"\u2500".repeat(6)}`);
990
- for (const file of result.files) {
991
- const tokenStr = file.tokens.toLocaleString().padStart(8);
992
- const lineStr = file.lines.toString().padStart(6);
993
- lines.push(` ${file.path.padEnd(maxPathLen)} ${tokenStr} ${lineStr}`);
994
- }
995
- lines.push(` ${"\u2500".repeat(maxPathLen)} ${"\u2500".repeat(8)} ${"\u2500".repeat(6)}`);
996
- lines.push(
997
- ` ${"Total".padEnd(maxPathLen)} ${result.summary.totalTokens.toLocaleString().padStart(8)}`
998
- );
999
- if (result.summary.estimatedWaste > 0) {
1000
- lines.push("");
1001
- lines.push(
1002
- chalk.yellow(
1003
- ` ~${result.summary.estimatedWaste} tokens estimated waste from redundant content`
1004
- )
1005
- );
1006
- }
1007
- lines.push("");
1008
- return lines.join("\n");
1009
- }
1010
- function formatIssue(issue) {
1011
- const icon = issue.severity === "error" ? chalk.red("\u2717") : issue.severity === "warning" ? chalk.yellow("\u26A0") : chalk.blue("\u2139");
1012
- const lineRef = issue.line > 0 ? `Line ${issue.line}: ` : "";
1013
- let line = ` ${icon} ${lineRef}${issue.message}`;
1014
- if (issue.suggestion) {
1015
- line += `
1016
- ${chalk.dim("\u2192")} ${chalk.dim(issue.suggestion)}`;
1017
- }
1018
- if (issue.detail) {
1019
- line += `
1020
- ${chalk.dim(issue.detail)}`;
1021
- }
1022
- return line;
1023
- }
1024
-
1025
- // src/core/fixer.ts
1026
- import * as fs4 from "fs";
1027
- import chalk2 from "chalk";
1028
- function applyFixes(result) {
1029
- const fixesByFile = /* @__PURE__ */ new Map();
1030
- for (const file of result.files) {
1031
- for (const issue of file.issues) {
1032
- if (issue.fix) {
1033
- const existing = fixesByFile.get(issue.fix.file) || [];
1034
- existing.push(issue.fix);
1035
- fixesByFile.set(issue.fix.file, existing);
1036
- }
1037
- }
1038
- }
1039
- let totalFixes = 0;
1040
- const filesModified = [];
1041
- for (const [filePath, fixes] of fixesByFile) {
1042
- const content = fs4.readFileSync(filePath, "utf-8");
1043
- const lines = content.split("\n");
1044
- let modified = false;
1045
- const sortedFixes = [...fixes].sort((a, b) => b.line - a.line);
1046
- for (const fix of sortedFixes) {
1047
- const lineIdx = fix.line - 1;
1048
- if (lineIdx < 0 || lineIdx >= lines.length) continue;
1049
- const line = lines[lineIdx];
1050
- if (line.includes(fix.oldText)) {
1051
- lines[lineIdx] = line.replace(fix.oldText, fix.newText);
1052
- modified = true;
1053
- totalFixes++;
1054
- console.log(
1055
- chalk2.green(" Fixed") + ` Line ${fix.line}: ${chalk2.dim(fix.oldText)} ${chalk2.dim("\u2192")} ${fix.newText}`
1056
- );
1057
- }
1058
- }
1059
- if (modified) {
1060
- fs4.writeFileSync(filePath, lines.join("\n"), "utf-8");
1061
- filesModified.push(filePath);
1062
- }
1063
- }
1064
- return { totalFixes, filesModified };
1065
- }
1066
-
1067
- // src/core/config.ts
1068
- import * as fs5 from "fs";
1069
- import * as path7 from "path";
1070
- var CONFIG_FILENAMES = [".ctxlintrc", ".ctxlintrc.json"];
1071
- function loadConfig(projectRoot) {
1072
- for (const filename of CONFIG_FILENAMES) {
1073
- const filePath = path7.join(projectRoot, filename);
1074
- try {
1075
- const content = fs5.readFileSync(filePath, "utf-8");
1076
- return JSON.parse(content);
1077
- } catch {
1078
- continue;
1079
- }
1080
- }
1081
- return null;
1082
- }
1083
-
1084
- // src/index.ts
1085
- import * as path8 from "path";
1086
-
1087
- // src/version.ts
1088
- function loadVersion() {
1089
- if (true) return "0.2.2";
1090
- const fs6 = __require("fs");
1091
- const path9 = __require("path");
1092
- const pkgPath = path9.resolve(__dirname, "../package.json");
1093
- const pkg = JSON.parse(fs6.readFileSync(pkgPath, "utf-8"));
1094
- return pkg.version;
1095
- }
1096
- var VERSION = loadVersion();
1097
-
1098
- // src/index.ts
1099
- var ALL_CHECKS = ["paths", "commands", "staleness", "tokens", "redundancy"];
1100
- var program = new Command();
1101
- program.name("ctxlint").description(
1102
- "Lint your AI agent context files (CLAUDE.md, AGENTS.md, etc.) against your actual codebase"
1103
- ).version(VERSION).argument("[path]", "Project directory to scan", ".").option("--strict", "Exit code 1 on any warning or error (for CI)", false).option("--checks <checks>", "Comma-separated list of checks to run", "").option("--format <format>", "Output format: text or json", "text").option("--tokens", "Show token breakdown per file", false).option("--verbose", "Show passing checks too", false).option("--fix", "Auto-fix broken paths using git history and fuzzy matching", false).option("--ignore <checks>", "Comma-separated list of checks to ignore", "").action(async (projectPath, opts) => {
1104
- const resolvedPath = path8.resolve(projectPath);
1105
- const config = loadConfig(resolvedPath);
1106
- const options = {
1107
- projectPath: resolvedPath,
1108
- checks: opts.checks ? opts.checks.split(",").map((c) => c.trim()) : config?.checks || ALL_CHECKS,
1109
- strict: opts.strict || config?.strict || false,
1110
- format: opts.format,
1111
- verbose: opts.verbose,
1112
- fix: opts.fix,
1113
- ignore: opts.ignore ? opts.ignore.split(",").map((c) => c.trim()) : config?.ignore || [],
1114
- tokensOnly: opts.tokens
1115
- };
1116
- if (config?.tokenThresholds) {
1117
- setTokenThresholds(config.tokenThresholds);
1118
- }
1119
- const activeChecks = options.checks.filter((c) => !options.ignore.includes(c));
1120
- const spinner = options.format === "text" ? ora("Scanning for context files...").start() : void 0;
1121
- try {
1122
- const discovered = await scanForContextFiles(options.projectPath);
1123
- if (discovered.length === 0) {
1124
- spinner?.stop();
1125
- if (options.format === "json") {
1126
- console.log(
1127
- JSON.stringify({
1128
- version: VERSION,
1129
- scannedAt: (/* @__PURE__ */ new Date()).toISOString(),
1130
- projectRoot: options.projectPath,
1131
- files: [],
1132
- summary: { errors: 0, warnings: 0, info: 0, totalTokens: 0, estimatedWaste: 0 }
1133
- })
1134
- );
1135
- } else {
1136
- console.log("\nNo context files found.\n");
1137
- }
1138
- process.exit(0);
1139
- }
1140
- if (spinner)
1141
- spinner.text = `Parsing ${discovered.length} context file${discovered.length !== 1 ? "s" : ""}...`;
1142
- const parsed = discovered.map((f) => parseContextFile(f));
1143
- if (spinner) spinner.text = "Running checks...";
1144
- const fileResults = [];
1145
- for (const file of parsed) {
1146
- const issues = [];
1147
- if (activeChecks.includes("paths")) {
1148
- issues.push(...await checkPaths(file, options.projectPath));
1149
- }
1150
- if (activeChecks.includes("commands")) {
1151
- issues.push(...await checkCommands(file, options.projectPath));
1152
- }
1153
- if (activeChecks.includes("staleness")) {
1154
- issues.push(...await checkStaleness(file, options.projectPath));
1155
- }
1156
- if (activeChecks.includes("tokens")) {
1157
- issues.push(...await checkTokens(file, options.projectPath));
1158
- }
1159
- if (activeChecks.includes("redundancy")) {
1160
- issues.push(...await checkRedundancy(file, options.projectPath));
1161
- }
1162
- fileResults.push({
1163
- path: file.relativePath,
1164
- isSymlink: file.isSymlink,
1165
- symlinkTarget: file.symlinkTarget,
1166
- tokens: file.totalTokens,
1167
- lines: file.totalLines,
1168
- issues
1169
- });
1170
- }
1171
- if (activeChecks.includes("tokens")) {
1172
- const aggIssue = checkAggregateTokens(
1173
- fileResults.map((f) => ({ path: f.path, tokens: f.tokens }))
1174
- );
1175
- if (aggIssue && fileResults.length > 0) {
1176
- fileResults[0].issues.push(aggIssue);
1177
- }
1178
- }
1179
- if (activeChecks.includes("redundancy")) {
1180
- const dupIssues = checkDuplicateContent(parsed);
1181
- if (dupIssues.length > 0 && fileResults.length > 0) {
1182
- fileResults[0].issues.push(...dupIssues);
1183
- }
1184
- }
1185
- let estimatedWaste = 0;
1186
- for (const fr of fileResults) {
1187
- for (const issue of fr.issues) {
1188
- if (issue.check === "redundancy" && issue.suggestion) {
1189
- const tokenMatch = issue.suggestion.match(/~(\d+)\s+tokens/);
1190
- if (tokenMatch) {
1191
- estimatedWaste += parseInt(tokenMatch[1], 10);
1192
- }
1193
- }
1194
- }
1195
- }
1196
- const result = {
1197
- version: VERSION,
1198
- scannedAt: (/* @__PURE__ */ new Date()).toISOString(),
1199
- projectRoot: options.projectPath,
1200
- files: fileResults,
1201
- summary: {
1202
- errors: fileResults.reduce(
1203
- (sum, f) => sum + f.issues.filter((i) => i.severity === "error").length,
1204
- 0
1205
- ),
1206
- warnings: fileResults.reduce(
1207
- (sum, f) => sum + f.issues.filter((i) => i.severity === "warning").length,
1208
- 0
1209
- ),
1210
- info: fileResults.reduce(
1211
- (sum, f) => sum + f.issues.filter((i) => i.severity === "info").length,
1212
- 0
1213
- ),
1214
- totalTokens: fileResults.reduce((sum, f) => sum + f.tokens, 0),
1215
- estimatedWaste
1216
- }
1217
- };
1218
- spinner?.stop();
1219
- if (options.fix) {
1220
- const fixSummary = applyFixes(result);
1221
- if (fixSummary.totalFixes > 0) {
1222
- console.log(
1223
- `
1224
- Fixed ${fixSummary.totalFixes} issue${fixSummary.totalFixes !== 1 ? "s" : ""} in ${fixSummary.filesModified.length} file${fixSummary.filesModified.length !== 1 ? "s" : ""}.
1225
- `
1226
- );
1227
- }
1228
- }
1229
- if (options.tokensOnly) {
1230
- console.log(formatTokenReport(result));
1231
- } else if (options.format === "json") {
1232
- console.log(formatJson(result));
1233
- } else {
1234
- console.log(formatText(result, options.verbose));
1235
- }
1236
- if (options.strict && (result.summary.errors > 0 || result.summary.warnings > 0)) {
1237
- process.exit(1);
1238
- }
1239
- } catch (err) {
1240
- spinner?.stop();
1241
- console.error("Error:", err instanceof Error ? err.message : err);
1242
- process.exit(2);
1243
- } finally {
1244
- freeEncoder();
1245
- resetGit();
1246
- resetPathsCache();
1247
- resetTokenThresholds();
1248
- }
1249
- });
1250
- program.command("init").description("Set up a git pre-commit hook that runs ctxlint --strict").action(async () => {
1251
- const fs6 = await import("fs");
1252
- const hooksDir = path8.resolve(".git", "hooks");
1253
- if (!fs6.existsSync(path8.resolve(".git"))) {
1254
- console.error('Error: not a git repository. Run "git init" first.');
1255
- process.exit(1);
1256
- }
1257
- if (!fs6.existsSync(hooksDir)) {
1258
- fs6.mkdirSync(hooksDir, { recursive: true });
1259
- }
1260
- const hookPath = path8.join(hooksDir, "pre-commit");
1261
- const hookContent = `#!/bin/sh
1262
- # ctxlint pre-commit hook
1263
- npx @yawlabs/ctxlint --strict
1264
- `;
1265
- if (fs6.existsSync(hookPath)) {
1266
- const existing = fs6.readFileSync(hookPath, "utf-8");
1267
- if (existing.includes("ctxlint")) {
1268
- console.log("Pre-commit hook already includes ctxlint.");
1269
- return;
1270
- }
1271
- fs6.appendFileSync(hookPath, "\n" + hookContent);
1272
- console.log("Added ctxlint to existing pre-commit hook.");
1273
- } else {
1274
- fs6.writeFileSync(hookPath, hookContent, { mode: 493 });
1275
- console.log("Created pre-commit hook at .git/hooks/pre-commit");
1276
- }
1277
- console.log("ctxlint will now run automatically before each commit.");
1278
- });
1279
- program.parse();