@arsh342/athena 0.1.4 → 0.1.6

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.cjs CHANGED
@@ -26,9 +26,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  mod
27
27
  ));
28
28
 
29
- // ../node_modules/commander/lib/error.js
29
+ // node_modules/commander/lib/error.js
30
30
  var require_error = __commonJS({
31
- "../node_modules/commander/lib/error.js"(exports2) {
31
+ "node_modules/commander/lib/error.js"(exports2) {
32
32
  "use strict";
33
33
  var CommanderError2 = class extends Error {
34
34
  /**
@@ -62,9 +62,9 @@ var require_error = __commonJS({
62
62
  }
63
63
  });
64
64
 
65
- // ../node_modules/commander/lib/argument.js
65
+ // node_modules/commander/lib/argument.js
66
66
  var require_argument = __commonJS({
67
- "../node_modules/commander/lib/argument.js"(exports2) {
67
+ "node_modules/commander/lib/argument.js"(exports2) {
68
68
  "use strict";
69
69
  var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
70
70
  var Argument2 = class {
@@ -191,9 +191,9 @@ var require_argument = __commonJS({
191
191
  }
192
192
  });
193
193
 
194
- // ../node_modules/commander/lib/help.js
194
+ // node_modules/commander/lib/help.js
195
195
  var require_help = __commonJS({
196
- "../node_modules/commander/lib/help.js"(exports2) {
196
+ "node_modules/commander/lib/help.js"(exports2) {
197
197
  "use strict";
198
198
  var { humanReadableArgName } = require_argument();
199
199
  var Help2 = class {
@@ -794,9 +794,9 @@ ${itemIndentStr}`);
794
794
  }
795
795
  });
796
796
 
797
- // ../node_modules/commander/lib/option.js
797
+ // node_modules/commander/lib/option.js
798
798
  var require_option = __commonJS({
799
- "../node_modules/commander/lib/option.js"(exports2) {
799
+ "node_modules/commander/lib/option.js"(exports2) {
800
800
  "use strict";
801
801
  var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
802
802
  var Option2 = class {
@@ -1108,9 +1108,9 @@ var require_option = __commonJS({
1108
1108
  }
1109
1109
  });
1110
1110
 
1111
- // ../node_modules/commander/lib/suggestSimilar.js
1111
+ // node_modules/commander/lib/suggestSimilar.js
1112
1112
  var require_suggestSimilar = __commonJS({
1113
- "../node_modules/commander/lib/suggestSimilar.js"(exports2) {
1113
+ "node_modules/commander/lib/suggestSimilar.js"(exports2) {
1114
1114
  "use strict";
1115
1115
  var maxDistance = 3;
1116
1116
  function editDistance(a, b) {
@@ -1189,9 +1189,9 @@ var require_suggestSimilar = __commonJS({
1189
1189
  }
1190
1190
  });
1191
1191
 
1192
- // ../node_modules/commander/lib/command.js
1192
+ // node_modules/commander/lib/command.js
1193
1193
  var require_command = __commonJS({
1194
- "../node_modules/commander/lib/command.js"(exports2) {
1194
+ "node_modules/commander/lib/command.js"(exports2) {
1195
1195
  "use strict";
1196
1196
  var EventEmitter = require("events").EventEmitter;
1197
1197
  var childProcess = require("child_process");
@@ -2271,10 +2271,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2271
2271
  }
2272
2272
  if (!proc.killed) {
2273
2273
  const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2274
- signals.forEach((signal2) => {
2275
- process2.on(signal2, () => {
2274
+ signals.forEach((signal4) => {
2275
+ process2.on(signal4, () => {
2276
2276
  if (proc.killed === false && proc.exitCode === null) {
2277
- proc.kill(signal2);
2277
+ proc.kill(signal4);
2278
2278
  }
2279
2279
  });
2280
2280
  });
@@ -3436,9 +3436,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
3436
3436
  }
3437
3437
  });
3438
3438
 
3439
- // ../node_modules/commander/index.js
3439
+ // node_modules/commander/index.js
3440
3440
  var require_commander = __commonJS({
3441
- "../node_modules/commander/index.js"(exports2) {
3441
+ "node_modules/commander/index.js"(exports2) {
3442
3442
  "use strict";
3443
3443
  var { Argument: Argument2 } = require_argument();
3444
3444
  var { Command: Command2 } = require_command();
@@ -5726,7 +5726,7 @@ var require_typescript = __commonJS({
5726
5726
  walkUpParenthesizedTypesAndGetParentAndChild: () => walkUpParenthesizedTypesAndGetParentAndChild,
5727
5727
  whitespaceOrMapCommentRegExp: () => whitespaceOrMapCommentRegExp,
5728
5728
  writeCommentRange: () => writeCommentRange,
5729
- writeFile: () => writeFile2,
5729
+ writeFile: () => writeFile3,
5730
5730
  writeFileEnsuringDirectories: () => writeFileEnsuringDirectories,
5731
5731
  zipWith: () => zipWith
5732
5732
  });
@@ -12058,7 +12058,7 @@ ${lanes.join("\n")}
12058
12058
  writeOutputIsTTY() {
12059
12059
  return process.stdout.isTTY;
12060
12060
  },
12061
- readFile: readFile2,
12061
+ readFile: readFile3,
12062
12062
  writeFile: writeFile22,
12063
12063
  watchFile: watchFile2,
12064
12064
  watchDirectory,
@@ -12264,7 +12264,7 @@ ${lanes.join("\n")}
12264
12264
  callback
12265
12265
  );
12266
12266
  }
12267
- function readFile2(fileName, _encoding) {
12267
+ function readFile3(fileName, _encoding) {
12268
12268
  let buffer;
12269
12269
  try {
12270
12270
  buffer = _fs.readFileSync(fileName);
@@ -24369,7 +24369,7 @@ ${lanes.join("\n")}
24369
24369
  sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
24370
24370
  return combinePaths(newDirPath, sourceFilePath);
24371
24371
  }
24372
- function writeFile2(host, diagnostics, fileName, text, writeByteOrderMark, sourceFiles, data) {
24372
+ function writeFile3(host, diagnostics, fileName, text, writeByteOrderMark, sourceFiles, data) {
24373
24373
  host.writeFile(
24374
24374
  fileName,
24375
24375
  text,
@@ -48820,7 +48820,7 @@ ${lanes.join("\n")}
48820
48820
  const possibleOption = getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
48821
48821
  return possibleOption ? createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
48822
48822
  }
48823
- function parseCommandLineWorker(diagnostics, commandLine, readFile2) {
48823
+ function parseCommandLineWorker(diagnostics, commandLine, readFile3) {
48824
48824
  const options = {};
48825
48825
  let watchOptions;
48826
48826
  const fileNames = [];
@@ -48868,7 +48868,7 @@ ${lanes.join("\n")}
48868
48868
  }
48869
48869
  }
48870
48870
  function parseResponseFile(fileName) {
48871
- const text = tryReadFile(fileName, readFile2 || ((fileName2) => sys.readFile(fileName2)));
48871
+ const text = tryReadFile(fileName, readFile3 || ((fileName2) => sys.readFile(fileName2)));
48872
48872
  if (!isString(text)) {
48873
48873
  errors.push(text);
48874
48874
  return;
@@ -48971,8 +48971,8 @@ ${lanes.join("\n")}
48971
48971
  unknownDidYouMeanDiagnostic: Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
48972
48972
  optionTypeMismatchDiagnostic: Diagnostics.Compiler_option_0_expects_an_argument
48973
48973
  };
48974
- function parseCommandLine(commandLine, readFile2) {
48975
- return parseCommandLineWorker(compilerOptionsDidYouMeanDiagnostics, commandLine, readFile2);
48974
+ function parseCommandLine(commandLine, readFile3) {
48975
+ return parseCommandLineWorker(compilerOptionsDidYouMeanDiagnostics, commandLine, readFile3);
48976
48976
  }
48977
48977
  function getOptionFromName(optionName, allowShort) {
48978
48978
  return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
@@ -49054,8 +49054,8 @@ ${lanes.join("\n")}
49054
49054
  watchOptionsToExtend
49055
49055
  );
49056
49056
  }
49057
- function readConfigFile(fileName, readFile2) {
49058
- const textOrDiagnostic = tryReadFile(fileName, readFile2);
49057
+ function readConfigFile(fileName, readFile3) {
49058
+ const textOrDiagnostic = tryReadFile(fileName, readFile3);
49059
49059
  return isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
49060
49060
  }
49061
49061
  function parseConfigFileTextToJson(fileName, jsonText) {
@@ -49070,14 +49070,14 @@ ${lanes.join("\n")}
49070
49070
  error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : void 0
49071
49071
  };
49072
49072
  }
49073
- function readJsonConfigFile(fileName, readFile2) {
49074
- const textOrDiagnostic = tryReadFile(fileName, readFile2);
49073
+ function readJsonConfigFile(fileName, readFile3) {
49074
+ const textOrDiagnostic = tryReadFile(fileName, readFile3);
49075
49075
  return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { fileName, parseDiagnostics: [textOrDiagnostic] };
49076
49076
  }
49077
- function tryReadFile(fileName, readFile2) {
49077
+ function tryReadFile(fileName, readFile3) {
49078
49078
  let text;
49079
49079
  try {
49080
- text = readFile2(fileName);
49080
+ text = readFile3(fileName);
49081
49081
  } catch (e) {
49082
49082
  return createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
49083
49083
  }
@@ -133120,7 +133120,7 @@ ${lanes.join("\n")}
133120
133120
  return;
133121
133121
  }
133122
133122
  const buildInfo = host.getBuildInfo() || { version };
133123
- writeFile2(
133123
+ writeFile3(
133124
133124
  host,
133125
133125
  emitterDiagnostics,
133126
133126
  buildInfoPath,
@@ -133332,7 +133332,7 @@ ${lanes.join("\n")}
133332
133332
  }
133333
133333
  if (sourceMapFilePath) {
133334
133334
  const sourceMap = sourceMapGenerator.toString();
133335
- writeFile2(
133335
+ writeFile3(
133336
133336
  host,
133337
133337
  emitterDiagnostics,
133338
133338
  sourceMapFilePath,
@@ -133347,7 +133347,7 @@ ${lanes.join("\n")}
133347
133347
  }
133348
133348
  const text = writer.getText();
133349
133349
  const data = { sourceMapUrlPos, diagnostics: transform2.diagnostics };
133350
- writeFile2(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, data);
133350
+ writeFile3(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, data);
133351
133351
  writer.clear();
133352
133352
  return !data.skippedDtsWrite;
133353
133353
  }
@@ -138735,12 +138735,12 @@ ${lanes.join("\n")}
138735
138735
  function createCompilerHost(options, setParentNodes) {
138736
138736
  return createCompilerHostWorker(options, setParentNodes);
138737
138737
  }
138738
- function createGetSourceFile(readFile2, setParentNodes) {
138738
+ function createGetSourceFile(readFile3, setParentNodes) {
138739
138739
  return (fileName, languageVersionOrOptions, onError) => {
138740
138740
  let text;
138741
138741
  try {
138742
138742
  mark("beforeIORead");
138743
- text = readFile2(fileName);
138743
+ text = readFile3(fileName);
138744
138744
  mark("afterIORead");
138745
138745
  measure("I/O Read", "beforeIORead", "afterIORead");
138746
138746
  } catch (e) {
@@ -139644,7 +139644,7 @@ ${lanes.join("\n")}
139644
139644
  getRedirectFromOutput,
139645
139645
  forEachResolvedProjectReference: forEachResolvedProjectReference2
139646
139646
  });
139647
- const readFile2 = host.readFile.bind(host);
139647
+ const readFile3 = host.readFile.bind(host);
139648
139648
  (_e = tracing) == null ? void 0 : _e.push(tracing.Phase.Program, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram });
139649
139649
  const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
139650
139650
  (_f = tracing) == null ? void 0 : _f.pop();
@@ -139870,7 +139870,7 @@ ${lanes.join("\n")}
139870
139870
  shouldTransformImportCall,
139871
139871
  emitBuildInfo,
139872
139872
  fileExists,
139873
- readFile: readFile2,
139873
+ readFile: readFile3,
139874
139874
  directoryExists,
139875
139875
  getSymlinkCache,
139876
139876
  realpath: (_o = host.realpath) == null ? void 0 : _o.bind(host),
@@ -201229,7 +201229,7 @@ ${options.prefix}` : "\n" : options.prefix
201229
201229
  walkUpParenthesizedTypesAndGetParentAndChild: () => walkUpParenthesizedTypesAndGetParentAndChild,
201230
201230
  whitespaceOrMapCommentRegExp: () => whitespaceOrMapCommentRegExp,
201231
201231
  writeCommentRange: () => writeCommentRange,
201232
- writeFile: () => writeFile2,
201232
+ writeFile: () => writeFile3,
201233
201233
  writeFileEnsuringDirectories: () => writeFileEnsuringDirectories,
201234
201234
  zipWith: () => zipWith
201235
201235
  });
@@ -214201,7 +214201,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
214201
214201
  }
214202
214202
  });
214203
214203
 
214204
- // ../node_modules/commander/esm.mjs
214204
+ // node_modules/commander/esm.mjs
214205
214205
  var import_index = __toESM(require_commander(), 1);
214206
214206
  var {
214207
214207
  program,
@@ -214230,15 +214230,17 @@ var defaultWeights = {
214230
214230
  namingEntropy: 10,
214231
214231
  boilerplatePatterns: 10,
214232
214232
  helperOrdering: 10,
214233
- emojiComments: 10
214233
+ emojiComments: 10,
214234
+ perplexity: 12,
214235
+ burstiness: 12
214234
214236
  };
214235
214237
  var defaultConfig = {
214236
- threshold: 65,
214238
+ threshold: 9,
214237
214239
  blockOn: ["CRITICAL", "HIGH"],
214238
214240
  exclude: ["node_modules/", "dist/", "build/", ".git/", "coverage/"],
214239
214241
  secretDetection: true,
214240
214242
  hallucinationDetection: true,
214241
- maxFileSize: 102400,
214243
+ maxFileSize: 1048576,
214242
214244
  weights: defaultWeights
214243
214245
  };
214244
214246
  function mergeConfig(config = {}) {
@@ -214294,9 +214296,9 @@ var secretPatterns = [
214294
214296
  { ruleId: "secret.aws-access-key", label: "AWS access key", pattern: /AKIA[0-9A-Z]{16}/g },
214295
214297
  { ruleId: "secret.github-token", label: "GitHub token", pattern: /gh[ps]_[A-Za-z0-9_]{36,}/g },
214296
214298
  { ruleId: "secret.jwt", label: "JWT token", pattern: /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g },
214297
- { ruleId: "secret.private-key", label: "Private key", pattern: /-----BEGIN [A-Z ]+PRIVATE KEY-----/g },
214298
- { ruleId: "secret.password", label: "Hardcoded password", pattern: /(password|api[_-]?key|token|secret)\s*[:=]\s*['"][^'"]{8,}['"]/gi }
214299
+ { ruleId: "secret.private-key", label: "Private key", pattern: /-----BEGIN [A-Z ]+PRIVATE KEY-----/g }
214299
214300
  ];
214301
+ var hardcodedCredentialPattern = /(password|api[_-]?key|token|secret)\s*[:=]\s*['"][^'"]{8,}['"]/gi;
214300
214302
  function detectSecrets(scored) {
214301
214303
  const findings = [];
214302
214304
  for (const definition of secretPatterns) {
@@ -214304,12 +214306,29 @@ function detectSecrets(scored) {
214304
214306
  findings.push(createFinding(scored, definition.ruleId, definition.label, match[0], "credential-exposure"));
214305
214307
  }
214306
214308
  }
214309
+ for (const match of scored.unit.code.matchAll(hardcodedCredentialPattern)) {
214310
+ const matchedKey = match[1]?.toLowerCase() ?? "";
214311
+ const { ruleId, type } = classifyHardcodedCredential(matchedKey);
214312
+ findings.push(createFinding(scored, ruleId, type, match[0], "credential-exposure"));
214313
+ }
214307
214314
  const highEntropyStrings = [...scored.unit.code.matchAll(/['"]([A-Za-z0-9+/=_-]{24,})['"]/g)].map((match) => match[1]).filter((value) => shannonEntropy(value) > 4.5 && !looksLikeFalsePositive(value));
214308
214315
  for (const value of highEntropyStrings) {
214309
214316
  findings.push(createFinding(scored, "secret.high-entropy-string", "Possible high-entropy secret", value, "credential-exposure"));
214310
214317
  }
214311
214318
  return findings;
214312
214319
  }
214320
+ function classifyHardcodedCredential(key) {
214321
+ if (key.includes("password")) {
214322
+ return { ruleId: "secret.hardcoded-password", type: "Hardcoded password" };
214323
+ }
214324
+ if (key.includes("api") && key.includes("key")) {
214325
+ return { ruleId: "secret.hardcoded-api-key", type: "Hardcoded API key" };
214326
+ }
214327
+ if (key.includes("token")) {
214328
+ return { ruleId: "secret.hardcoded-token", type: "Hardcoded token" };
214329
+ }
214330
+ return { ruleId: "secret.hardcoded-secret", type: "Hardcoded secret" };
214331
+ }
214313
214332
  function createFinding(scored, ruleId, type, code, category) {
214314
214333
  return {
214315
214334
  id: (0, import_node_crypto2.createHash)("sha1").update(`${ruleId}:${scored.unit.filePath}:${scored.unit.startLine}:${code}`).digest("hex").slice(0, 10),
@@ -214485,7 +214504,7 @@ function estimateComplexity(node) {
214485
214504
 
214486
214505
  // ../core/dist/report/report-generator.js
214487
214506
  var severityOrder = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];
214488
- function generateReport(startedAt, files, totalLoc, blockOn) {
214507
+ function generateReport(startedAt, files, totalLoc, skippedFiles, config) {
214489
214508
  const units = files.flatMap((file) => file.units);
214490
214509
  const findings = files.flatMap((file) => file.findings);
214491
214510
  const severityCounts = severityOrder.reduce((acc, severity) => ({ ...acc, [severity]: findings.filter((finding) => finding.severity === severity).length }), { CRITICAL: 0, HIGH: 0, MEDIUM: 0, LOW: 0 });
@@ -214496,24 +214515,46 @@ function generateReport(startedAt, files, totalLoc, blockOn) {
214496
214515
  };
214497
214516
  const flaggedUnits = units.filter((unit) => unit.flagged).length;
214498
214517
  const aiScore = Math.round(units.reduce((sum, unit) => sum + unit.score, 0) / Math.max(1, units.length));
214518
+ const blocked = findings.some((finding) => config.blockOn.includes(finding.severity));
214519
+ const riskDensity = {
214520
+ criticalPer1kLoc: roundPerK(severityCounts.CRITICAL, totalLoc),
214521
+ findingsPer1kLoc: roundPerK(findings.length, totalLoc),
214522
+ flaggedRatio: flaggedUnits / Math.max(1, units.length)
214523
+ };
214524
+ const aiOrigin = {
214525
+ score: aiScore,
214526
+ flaggedUnits,
214527
+ flagRatio: flaggedUnits / Math.max(1, units.length),
214528
+ percentage: Math.round(flaggedUnits / Math.max(1, units.length) * 100),
214529
+ confidenceBands
214530
+ };
214531
+ const weightedContributions = summarizeWeightedContributions(units);
214499
214532
  return {
214500
214533
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
214501
214534
  duration: Date.now() - startedAt,
214502
214535
  summary: {
214503
214536
  filesScanned: files.length,
214537
+ skippedFiles,
214504
214538
  totalUnits: units.length,
214505
214539
  flaggedUnits,
214506
214540
  findings: severityCounts,
214507
- blocked: findings.some((finding) => blockOn.includes(finding.severity)),
214541
+ blocked,
214508
214542
  aiScore,
214509
- aiFlagRatio: flaggedUnits / Math.max(1, units.length),
214510
- aiPercentage: Math.round(flaggedUnits / Math.max(1, units.length) * 100),
214511
- riskDensity: {
214512
- criticalPer1kLoc: roundPerK(severityCounts.CRITICAL, totalLoc),
214513
- findingsPer1kLoc: roundPerK(findings.length, totalLoc),
214514
- flaggedRatio: flaggedUnits / Math.max(1, units.length)
214543
+ aiFlagRatio: aiOrigin.flagRatio,
214544
+ aiPercentage: aiOrigin.percentage,
214545
+ riskDensity,
214546
+ confidenceBands,
214547
+ aiOrigin,
214548
+ security: {
214549
+ findings: severityCounts,
214550
+ blocked,
214551
+ riskDensity
214515
214552
  },
214516
- confidenceBands
214553
+ weightedContributions,
214554
+ calibration: {
214555
+ thresholdUsed: config.threshold,
214556
+ source: "default"
214557
+ }
214517
214558
  },
214518
214559
  files
214519
214560
  };
@@ -214524,10 +214565,119 @@ function countBand(units, band) {
214524
214565
  function roundPerK(count, loc) {
214525
214566
  return Math.round(count / Math.max(1, loc) * 1e3 * 10) / 10;
214526
214567
  }
214568
+ function summarizeWeightedContributions(units) {
214569
+ const totals = /* @__PURE__ */ new Map();
214570
+ for (const unit of units) {
214571
+ for (const signal4 of unit.signals) {
214572
+ const existing = totals.get(signal4.signal) ?? { score: 0, maxWeight: 0 };
214573
+ existing.score += signal4.score;
214574
+ existing.maxWeight += signal4.maxWeight;
214575
+ totals.set(signal4.signal, existing);
214576
+ }
214577
+ }
214578
+ const totalScore = Array.from(totals.values()).reduce((sum, item) => sum + item.score, 0);
214579
+ return Array.from(totals.entries()).map(([signal4, values]) => ({
214580
+ signal: signal4,
214581
+ contribution: totalScore === 0 ? 0 : Math.round(values.score / totalScore * 100),
214582
+ score: values.score,
214583
+ maxWeight: values.maxWeight
214584
+ })).sort((a, b) => b.score - a.score).slice(0, 8);
214585
+ }
214527
214586
  function formatJsonl(report) {
214528
214587
  return report.files.flatMap((file) => file.findings).map((finding) => JSON.stringify(finding)).join("\n");
214529
214588
  }
214530
214589
 
214590
+ // ../core/dist/analyzers/burstiness-analyzer.js
214591
+ function scoreBurstiness(unit, maxWeight) {
214592
+ const sentences = splitSentences(unit.code);
214593
+ if (sentences.length < 3) {
214594
+ return signal("burstiness", 0, maxWeight, "insufficient sentence count for burstiness estimate");
214595
+ }
214596
+ const lengths = sentences.map((sentence) => tokenize(sentence).length).filter((count) => count > 0);
214597
+ if (lengths.length < 3) {
214598
+ return signal("burstiness", 0, maxWeight, "insufficient tokenized sentences for burstiness estimate");
214599
+ }
214600
+ const mean = average(lengths);
214601
+ const stdDev = standardDeviation(lengths, mean);
214602
+ const coeffVar = stdDev / Math.max(1, mean);
214603
+ const openerVariety = sentenceOpenerVariety(sentences);
214604
+ const lowLengthVariation = clamp01((0.55 - coeffVar) / 0.55);
214605
+ const lowOpenerVariation = clamp01((0.75 - openerVariety) / 0.75);
214606
+ const score = Math.round(maxWeight * (lowLengthVariation * 0.7 + lowOpenerVariation * 0.3));
214607
+ return signal("burstiness", score, maxWeight, `sentence cv ${coeffVar.toFixed(2)}, opener variety ${Math.round(openerVariety * 100)}%`);
214608
+ }
214609
+ function splitSentences(code) {
214610
+ return code.replace(/\s+/g, " ").split(/[.!?;]+/).map((line) => line.trim()).filter((line) => line.length > 0);
214611
+ }
214612
+ function tokenize(value) {
214613
+ return value.toLowerCase().split(/[^a-z0-9_]+/).map((part) => part.trim()).filter((part) => part.length > 0);
214614
+ }
214615
+ function sentenceOpenerVariety(sentences) {
214616
+ const starters = sentences.map((sentence) => tokenize(sentence)[0]).filter((token) => Boolean(token));
214617
+ if (starters.length === 0)
214618
+ return 0;
214619
+ return new Set(starters).size / starters.length;
214620
+ }
214621
+ function average(values) {
214622
+ return values.reduce((sum, value) => sum + value, 0) / Math.max(1, values.length);
214623
+ }
214624
+ function standardDeviation(values, mean) {
214625
+ const variance = values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / Math.max(1, values.length);
214626
+ return Math.sqrt(variance);
214627
+ }
214628
+ function clamp01(value) {
214629
+ return Math.max(0, Math.min(1, value));
214630
+ }
214631
+ function signal(signalName, score, maxWeight, evidence) {
214632
+ return {
214633
+ signal: signalName,
214634
+ score: Math.max(0, Math.min(maxWeight, Math.round(score))),
214635
+ maxWeight,
214636
+ evidence
214637
+ };
214638
+ }
214639
+
214640
+ // ../core/dist/analyzers/perplexity-analyzer.js
214641
+ function scorePerplexity(unit, maxWeight) {
214642
+ const tokens = tokenize2(unit.code);
214643
+ if (tokens.length < 8) {
214644
+ return signal2("perplexity", 0, maxWeight, "insufficient tokens for perplexity estimate");
214645
+ }
214646
+ const entropy = shannonEntropy2(tokens);
214647
+ const normalizedEntropy = clamp012((entropy - 2.2) / 2.2);
214648
+ const repetitionPenalty = repetitionRate(tokens);
214649
+ const predictability = clamp012((1 - normalizedEntropy) * 0.75 + repetitionPenalty * 0.25);
214650
+ const score = Math.round(maxWeight * predictability);
214651
+ return signal2("perplexity", score, maxWeight, `token entropy ${entropy.toFixed(2)}, repetition ${Math.round(repetitionPenalty * 100)}%`);
214652
+ }
214653
+ function tokenize2(code) {
214654
+ return code.toLowerCase().split(/[^a-z0-9_]+/).map((part) => part.trim()).filter((part) => part.length > 0);
214655
+ }
214656
+ function shannonEntropy2(tokens) {
214657
+ const counts = /* @__PURE__ */ new Map();
214658
+ for (const token of tokens)
214659
+ counts.set(token, (counts.get(token) ?? 0) + 1);
214660
+ return Array.from(counts.values()).reduce((entropy, count) => {
214661
+ const p = count / tokens.length;
214662
+ return entropy - p * Math.log2(p);
214663
+ }, 0);
214664
+ }
214665
+ function repetitionRate(tokens) {
214666
+ const unique = new Set(tokens).size;
214667
+ return clamp012(1 - unique / Math.max(1, tokens.length));
214668
+ }
214669
+ function clamp012(value) {
214670
+ return Math.max(0, Math.min(1, value));
214671
+ }
214672
+ function signal2(signalName, score, maxWeight, evidence) {
214673
+ return {
214674
+ signal: signalName,
214675
+ score: Math.max(0, Math.min(maxWeight, Math.round(score))),
214676
+ maxWeight,
214677
+ evidence
214678
+ };
214679
+ }
214680
+
214531
214681
  // ../core/dist/scorer/heuristic-scorer.js
214532
214682
  var genericNames = /* @__PURE__ */ new Set([
214533
214683
  "data",
@@ -214557,10 +214707,12 @@ function scoreUnit(unit, config) {
214557
214707
  scoreNamingEntropy(unit, config.weights.namingEntropy),
214558
214708
  scoreBoilerplatePatterns(unit, config.weights.boilerplatePatterns),
214559
214709
  scoreHelperOrdering(unit, config.weights.helperOrdering),
214560
- scoreEmojiComments(unit, config.weights.emojiComments)
214710
+ scoreEmojiComments(unit, config.weights.emojiComments),
214711
+ scorePerplexity(unit, config.weights.perplexity),
214712
+ scoreBurstiness(unit, config.weights.burstiness)
214561
214713
  ];
214562
- const max = signals.reduce((sum, signal2) => sum + signal2.maxWeight, 0);
214563
- const raw = signals.reduce((sum, signal2) => sum + signal2.score, 0);
214714
+ const max = signals.reduce((sum, signal4) => sum + signal4.maxWeight, 0);
214715
+ const raw = signals.reduce((sum, signal4) => sum + signal4.score, 0);
214564
214716
  const score = Math.round(raw / max * 100);
214565
214717
  const explained = explain(score, signals);
214566
214718
  return {
@@ -214571,9 +214723,9 @@ function scoreUnit(unit, config) {
214571
214723
  explained
214572
214724
  };
214573
214725
  }
214574
- function signal(signal2, score, maxWeight, evidence) {
214726
+ function signal3(signal4, score, maxWeight, evidence) {
214575
214727
  return {
214576
- signal: signal2,
214728
+ signal: signal4,
214577
214729
  score: Math.max(0, Math.min(maxWeight, Math.round(score))),
214578
214730
  maxWeight,
214579
214731
  evidence
@@ -214583,36 +214735,36 @@ function scoreGenericNames(unit, max) {
214583
214735
  const identifiers = unit.metadata.identifiers;
214584
214736
  const hits = identifiers.filter((name) => genericNames.has(name.toLowerCase())).length;
214585
214737
  const ratio = hits / Math.max(1, identifiers.length);
214586
- return signal("genericNames", ratio * max * 3, max, `${hits}/${identifiers.length} identifiers are generic`);
214738
+ return signal3("genericNames", ratio * max * 3, max, `${hits}/${identifiers.length} identifiers are generic`);
214587
214739
  }
214588
214740
  function scoreCommentRatio(unit, max) {
214589
214741
  const ratio = unit.metadata.commentRatio;
214590
- return signal("commentRatio", ratio >= 0.4 ? max : ratio / 0.4 * max, max, `comment ratio ${ratio.toFixed(2)}`);
214742
+ return signal3("commentRatio", ratio >= 0.4 ? max : ratio / 0.4 * max, max, `comment ratio ${ratio.toFixed(2)}`);
214591
214743
  }
214592
214744
  function scoreObviousComments(unit, max) {
214593
214745
  const obvious = /\/\/\s*(set|get|return|create|update|delete|loop|check|initialize|calculate|fetch)\b/i.test(unit.code);
214594
- return signal("obviousComments", obvious ? max : 0, max, obvious ? "obvious explanatory comment found" : "no obvious comments");
214746
+ return signal3("obviousComments", obvious ? max : 0, max, obvious ? "obvious explanatory comment found" : "no obvious comments");
214595
214747
  }
214596
214748
  function scoreEmptyCatch(unit, max) {
214597
214749
  const emptyCatch = /catch\s*\([^)]*\)\s*\{\s*(console\.(error|log)\([^)]*\);\s*)?\}/s.test(unit.code);
214598
- return signal("emptyCatch", emptyCatch ? max : 0, max, emptyCatch ? "empty or log-only catch block" : "catch blocks include handling");
214750
+ return signal3("emptyCatch", emptyCatch ? max : 0, max, emptyCatch ? "empty or log-only catch block" : "catch blocks include handling");
214599
214751
  }
214600
214752
  function scoreNullChecks(unit, max) {
214601
214753
  const checks = (unit.code.match(/(\?\?|\?\.|typeof\s+\w+\s*===\s*['"]undefined['"]|!==\s*null|===\s*null)/g) ?? []).length;
214602
- return signal("nullChecks", Math.min(max, checks * 2), max, `${checks} defensive null/undefined checks`);
214754
+ return signal3("nullChecks", Math.min(max, checks * 2), max, `${checks} defensive null/undefined checks`);
214603
214755
  }
214604
214756
  function scoreFormattingUniformity(unit, max) {
214605
214757
  const indents = unit.code.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => line.match(/^\s*/)?.[0].length ?? 0);
214606
214758
  const unique = new Set(indents);
214607
- return signal("formattingUniformity", unique.size <= 3 && indents.length > 8 ? max : max * 0.2, max, `${unique.size} indentation levels`);
214759
+ return signal3("formattingUniformity", unique.size <= 3 && indents.length > 8 ? max : max * 0.2, max, `${unique.size} indentation levels`);
214608
214760
  }
214609
214761
  function scoreUniversalJsdoc(unit, max) {
214610
- return signal("universalJsdoc", unit.metadata.hasJSDoc ? max : 0, max, unit.metadata.hasJSDoc ? "JSDoc present" : "no JSDoc");
214762
+ return signal3("universalJsdoc", unit.metadata.hasJSDoc ? max : 0, max, unit.metadata.hasJSDoc ? "JSDoc present" : "no JSDoc");
214611
214763
  }
214612
214764
  function scoreNamingEntropy(unit, max) {
214613
- const entropy = shannonEntropy2(unit.metadata.identifiers.join(""));
214765
+ const entropy = shannonEntropy3(unit.metadata.identifiers.join(""));
214614
214766
  const score = entropy < 3.2 ? max : entropy < 3.8 ? max * 0.5 : 0;
214615
- return signal("namingEntropy", score, max, `identifier entropy ${entropy.toFixed(2)}`);
214767
+ return signal3("namingEntropy", score, max, `identifier entropy ${entropy.toFixed(2)}`);
214616
214768
  }
214617
214769
  function scoreBoilerplatePatterns(unit, max) {
214618
214770
  const patterns = [
@@ -214622,18 +214774,18 @@ function scoreBoilerplatePatterns(unit, max) {
214622
214774
  /useState\([^)]*\)[\s\S]*useEffect/i
214623
214775
  ];
214624
214776
  const hits = patterns.filter((pattern) => pattern.test(unit.code)).length;
214625
- return signal("boilerplatePatterns", hits * (max / 2), max, `${hits} boilerplate patterns`);
214777
+ return signal3("boilerplatePatterns", hits * (max / 2), max, `${hits} boilerplate patterns`);
214626
214778
  }
214627
214779
  function scoreHelperOrdering(unit, max) {
214628
214780
  const helperDefinitions = (unit.code.match(/function\s+(validate|format|process|handle|create|update)\w*/gi) ?? []).length;
214629
214781
  const sequentialCalls = /(validate\w*\([^)]*\)[\s\S]*format\w*\([^)]*\)[\s\S]*process\w*\([^)]*\))/i.test(unit.code);
214630
- return signal("helperOrdering", helperDefinitions >= 2 || sequentialCalls ? max : 0, max, `${helperDefinitions} helper-like definitions`);
214782
+ return signal3("helperOrdering", helperDefinitions >= 2 || sequentialCalls ? max : 0, max, `${helperDefinitions} helper-like definitions`);
214631
214783
  }
214632
214784
  function scoreEmojiComments(unit, max) {
214633
214785
  const emojiLike = /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(unit.code);
214634
- return signal("emojiComments", emojiLike ? max : 0, max, emojiLike ? "emoji-like character found" : "no emoji comments");
214786
+ return signal3("emojiComments", emojiLike ? max : 0, max, emojiLike ? "emoji-like character found" : "no emoji comments");
214635
214787
  }
214636
- function shannonEntropy2(value) {
214788
+ function shannonEntropy3(value) {
214637
214789
  if (!value)
214638
214790
  return 0;
214639
214791
  const counts = /* @__PURE__ */ new Map();
@@ -214646,15 +214798,15 @@ function shannonEntropy2(value) {
214646
214798
  }
214647
214799
  function explain(score, signals) {
214648
214800
  const band = score < 40 ? "LOW" : score < 70 ? "UNCERTAIN" : "HIGH";
214649
- const total = signals.reduce((sum, signal2) => sum + signal2.score, 0);
214801
+ const total = signals.reduce((sum, signal4) => sum + signal4.score, 0);
214650
214802
  const mean = total / Math.max(1, signals.length);
214651
- const variance = signals.reduce((sum, signal2) => sum + (signal2.score - mean) ** 2, 0) / Math.max(1, signals.length);
214803
+ const variance = signals.reduce((sum, signal4) => sum + (signal4.score - mean) ** 2, 0) / Math.max(1, signals.length);
214652
214804
  return {
214653
214805
  score,
214654
214806
  band,
214655
- signalsTriggered: signals.filter((signal2) => signal2.score > 0).length,
214807
+ signalsTriggered: signals.filter((signal4) => signal4.score > 0).length,
214656
214808
  variance: Math.round(variance),
214657
- topSignals: signals.filter((signal2) => signal2.score > 0).sort((a, b) => b.score - a.score).slice(0, 3).map((signalResult) => ({
214809
+ topSignals: signals.filter((signal4) => signal4.score > 0).sort((a, b) => b.score - a.score).slice(0, 3).map((signalResult) => ({
214658
214810
  signal: signalResult.signal,
214659
214811
  contribution: total === 0 ? 0 : Math.round(signalResult.score / total * 100),
214660
214812
  score: signalResult.score
@@ -214668,10 +214820,15 @@ async function scanFiles(filePaths, configInput = {}) {
214668
214820
  const config = mergeConfig(configInput);
214669
214821
  const files = [];
214670
214822
  let totalLoc = 0;
214823
+ let skippedFiles = 0;
214671
214824
  for (const filePath of filePaths) {
214672
214825
  const fileStat = await (0, import_promises2.stat)(filePath).catch(() => null);
214673
- if (!fileStat || fileStat.size > config.maxFileSize)
214826
+ if (!fileStat)
214674
214827
  continue;
214828
+ if (fileStat.size > config.maxFileSize) {
214829
+ skippedFiles += 1;
214830
+ continue;
214831
+ }
214675
214832
  const units = await parseFile(filePath).catch(() => []);
214676
214833
  const scoredUnits = units.map((unit) => scoreUnit(unit, config));
214677
214834
  const findings = scoredUnits.flatMap((scored) => scored.flagged ? analyzeSecurity(scored, config) : []);
@@ -214682,7 +214839,7 @@ async function scanFiles(filePaths, configInput = {}) {
214682
214839
  findings
214683
214840
  });
214684
214841
  }
214685
- return generateReport(startedAt, files, totalLoc, config.blockOn);
214842
+ return generateReport(startedAt, files, totalLoc, skippedFiles, config);
214686
214843
  }
214687
214844
 
214688
214845
  // ../core/dist/report/terminal-formatter.js
@@ -214690,7 +214847,6 @@ var c = {
214690
214847
  reset: "\x1B[0m",
214691
214848
  bold: "\x1B[1m",
214692
214849
  dim: "\x1B[2m",
214693
- cyan: "\x1B[36m",
214694
214850
  green: "\x1B[32m",
214695
214851
  yellow: "\x1B[33m",
214696
214852
  orange: "\x1B[38;5;208m",
@@ -214702,18 +214858,22 @@ var severityColor = {
214702
214858
  CRITICAL: c.red,
214703
214859
  HIGH: c.orange,
214704
214860
  MEDIUM: c.yellow,
214705
- LOW: c.cyan
214861
+ LOW: c.gray
214706
214862
  };
214707
214863
  function formatTerminalReport(report) {
214708
214864
  const lines = [];
214709
214865
  const summary = report.summary;
214866
+ const securityFindingsTotal = Object.values(summary.findings).reduce((sum, count) => sum + count, 0);
214867
+ const thresholdUsed = summary.calibration?.thresholdUsed;
214868
+ const aiScoreRelation = typeof thresholdUsed === "number" ? summary.aiScore === thresholdUsed ? "at threshold" : summary.aiScore < thresholdUsed ? "below threshold" : "above threshold" : "threshold unavailable";
214869
+ const gateReason = summary.blocked ? securityFindingsTotal > 0 ? "blocked (security findings matched block policy)" : `blocked (ai score ${aiScoreRelation})` : securityFindingsTotal === 0 ? `pass (no security findings, ai score ${aiScoreRelation})` : `pass (security findings present but below block policy, ai score ${aiScoreRelation})`;
214710
214870
  lines.push("");
214711
214871
  lines.push(sectionRule("Athena Report"));
214712
214872
  lines.push("");
214713
214873
  lines.push(metricLine([
214714
214874
  ["files", String(summary.filesScanned)],
214715
214875
  ["units", String(summary.totalUnits)],
214716
- ["flagged", String(summary.flaggedUnits)],
214876
+ ["ai-flagged units", String(summary.flaggedUnits)],
214717
214877
  ["duration", `${report.duration}ms`]
214718
214878
  ]));
214719
214879
  lines.push(metricLine([
@@ -214722,7 +214882,33 @@ function formatTerminalReport(report) {
214722
214882
  ["risk", `${summary.riskDensity.findingsPer1kLoc}/1k LOC`],
214723
214883
  ["gate", summary.blocked ? `${c.red}blocked${c.reset}` : `${c.green}pass${c.reset}`]
214724
214884
  ]));
214885
+ lines.push(` ${c.dim}gate reason${c.reset} ${c.white}${gateReason}${c.reset}`);
214725
214886
  lines.push("");
214887
+ if (summary.aiOrigin) {
214888
+ lines.push(` ${c.bold}AI-Origin Confidence${c.reset}`);
214889
+ lines.push(metricLine([
214890
+ ["score", `${summary.aiOrigin.score}/100`],
214891
+ ["flagged units", String(summary.aiOrigin.flaggedUnits)],
214892
+ ["ratio", `${Math.round(summary.aiOrigin.flagRatio * 100)}%`],
214893
+ ["threshold", String(summary.calibration?.thresholdUsed ?? "n/a")]
214894
+ ]));
214895
+ lines.push("");
214896
+ }
214897
+ if (summary.weightedContributions && summary.weightedContributions.length > 0) {
214898
+ lines.push(` ${c.bold}Top Weighted Signals${c.reset}`);
214899
+ lines.push(` ${summary.weightedContributions.slice(0, 4).map((item) => `${c.dim}${item.signal}${c.reset} ${c.orange}${item.contribution}%${c.reset}`).join(" ")}`);
214900
+ lines.push("");
214901
+ }
214902
+ if (summary.security) {
214903
+ lines.push(` ${c.bold}Security Findings${c.reset}`);
214904
+ lines.push(metricLine([
214905
+ ["critical", String(summary.security.findings.CRITICAL)],
214906
+ ["high", String(summary.security.findings.HIGH)],
214907
+ ["medium", String(summary.security.findings.MEDIUM)],
214908
+ ["low", String(summary.security.findings.LOW)]
214909
+ ]));
214910
+ lines.push("");
214911
+ }
214726
214912
  lines.push(` ${c.bold}Severity${c.reset}`);
214727
214913
  lines.push(` ${severityBar(report)}`);
214728
214914
  lines.push("");
@@ -214744,10 +214930,10 @@ function formatTerminalReport(report) {
214744
214930
  for (const finding of findings.slice(0, 20)) {
214745
214931
  const sevColor = severityColor[finding.severity];
214746
214932
  lines.push(` ${sevColor}${finding.severity.padEnd(9)}${c.reset}${c.bold}${finding.type}${c.reset} ${c.dim}${finding.id}${c.reset}`);
214747
- lines.push(` ${c.cyan}${finding.file}:${finding.line}${c.reset} ${c.dim}ai=${finding.aiScore} source=${finding.source}${c.reset}`);
214933
+ lines.push(` ${c.orange}${finding.file}:${finding.line}${c.reset} ${c.dim}ai=${finding.aiScore} source=${finding.source}${c.reset}`);
214748
214934
  lines.push(` ${c.dim}${finding.message}${c.reset}`);
214749
214935
  if (finding.explainedScore.topSignals.length > 0) {
214750
- const signals = finding.explainedScore.topSignals.map((s) => `${s.signal}:${c.cyan}${s.contribution}%${c.reset}`).join(" ");
214936
+ const signals = finding.explainedScore.topSignals.map((s) => `${s.signal}:${c.orange}${s.contribution}%${c.reset}`).join(" ");
214751
214937
  lines.push(` ${c.dim}signals:${c.reset} ${signals}`);
214752
214938
  }
214753
214939
  lines.push("");
@@ -214761,7 +214947,7 @@ function formatTerminalReport(report) {
214761
214947
  function sectionRule(title) {
214762
214948
  const ruleWidth = Math.max(48, title.length + 10);
214763
214949
  const dashCount = ruleWidth - title.length - 5;
214764
- return ` ${c.cyan}\u2500\u2500${c.reset} ${c.bold}${title}${c.reset} ${c.cyan}${"\u2500".repeat(dashCount)}${c.reset}`;
214950
+ return ` ${c.orange}\u2500\u2500${c.reset} ${c.bold}${title}${c.reset} ${c.orange}${"\u2500".repeat(dashCount)}${c.reset}`;
214765
214951
  }
214766
214952
  function metricLine(metrics) {
214767
214953
  return " " + metrics.map(([label, value]) => `${c.dim}${label}${c.reset} ${c.white}${value}${c.reset}`).join(" ");
@@ -214778,7 +214964,7 @@ function severityBar(report) {
214778
214964
  }
214779
214965
 
214780
214966
  // src/commands/check.ts
214781
- var import_node_path2 = require("path");
214967
+ var import_node_path3 = require("path");
214782
214968
 
214783
214969
  // src/utils/file-filter.ts
214784
214970
  var import_promises3 = require("fs/promises");
@@ -214812,11 +214998,25 @@ async function walk(dir, output) {
214812
214998
  var import_node_child_process = require("child_process");
214813
214999
  var import_node_util = require("util");
214814
215000
  var execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
215001
+ function logGitWarning(context, error) {
215002
+ const message = error instanceof Error ? error.message : String(error);
215003
+ console.warn(`[athena-cli] ${context}: ${message}`);
215004
+ }
214815
215005
  async function getGitRoot() {
214816
215006
  try {
214817
215007
  const { stdout } = await execFileAsync("git", ["rev-parse", "--show-toplevel"]);
214818
215008
  return stdout.trim();
214819
- } catch {
215009
+ } catch (error) {
215010
+ logGitWarning("Unable to resolve git root", error);
215011
+ return null;
215012
+ }
215013
+ }
215014
+ async function getGitHooksDir() {
215015
+ try {
215016
+ const { stdout } = await execFileAsync("git", ["rev-parse", "--git-path", "hooks"]);
215017
+ return stdout.trim();
215018
+ } catch (error) {
215019
+ logGitWarning("Unable to resolve git hooks directory", error);
214820
215020
  return null;
214821
215021
  }
214822
215022
  }
@@ -214824,11 +215024,75 @@ async function getStagedFiles() {
214824
215024
  try {
214825
215025
  const { stdout } = await execFileAsync("git", ["diff", "--cached", "--name-only", "--diff-filter=ACM"]);
214826
215026
  return stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
214827
- } catch {
215027
+ } catch (error) {
215028
+ logGitWarning("Unable to read staged files", error);
214828
215029
  return [];
214829
215030
  }
214830
215031
  }
214831
215032
 
215033
+ // src/utils/history.ts
215034
+ var import_promises4 = require("fs/promises");
215035
+ var import_node_os = require("os");
215036
+ var import_node_path2 = require("path");
215037
+ var ATHENA_DIR = (0, import_node_path2.join)((0, import_node_os.homedir)(), ".athena");
215038
+ var HISTORY_PATH = (0, import_node_path2.join)(ATHENA_DIR, "scan-history.jsonl");
215039
+ var MAX_HISTORY_LINES = 300;
215040
+ function logHistoryWarning(context, error) {
215041
+ const message = error instanceof Error ? error.message : String(error);
215042
+ console.warn(`[athena-cli] ${context}: ${message}`);
215043
+ }
215044
+ async function appendScanHistory(entry) {
215045
+ try {
215046
+ await (0, import_promises4.mkdir)(ATHENA_DIR, { recursive: true });
215047
+ let lines = [];
215048
+ try {
215049
+ const existing = await (0, import_promises4.readFile)(HISTORY_PATH, "utf8");
215050
+ lines = existing.split("\n").map((line) => line.trim()).filter(Boolean);
215051
+ } catch (error) {
215052
+ logHistoryWarning("History file not readable, starting new history", error);
215053
+ }
215054
+ lines.push(JSON.stringify(entry));
215055
+ const trimmed = lines.slice(-MAX_HISTORY_LINES);
215056
+ await (0, import_promises4.writeFile)(HISTORY_PATH, `${trimmed.join("\n")}
215057
+ `, "utf8");
215058
+ } catch (error) {
215059
+ logHistoryWarning("Failed to persist scan history", error);
215060
+ }
215061
+ }
215062
+ async function getRecentScanHistory(limit = 3) {
215063
+ try {
215064
+ const content = await (0, import_promises4.readFile)(HISTORY_PATH, "utf8");
215065
+ const lines = content.split("\n").map((line) => line.trim()).filter(Boolean).slice(-Math.max(1, limit));
215066
+ return lines.map((line) => {
215067
+ try {
215068
+ return JSON.parse(line);
215069
+ } catch (error) {
215070
+ logHistoryWarning("Skipping malformed history entry", error);
215071
+ return null;
215072
+ }
215073
+ }).filter((entry) => entry !== null).reverse();
215074
+ } catch (error) {
215075
+ logHistoryWarning("Failed to read scan history", error);
215076
+ return [];
215077
+ }
215078
+ }
215079
+ function formatRecentHistory(entries) {
215080
+ if (entries.length === 0) {
215081
+ return "history: none";
215082
+ }
215083
+ const parts = entries.map((entry) => {
215084
+ const stamp = new Date(entry.timestamp).toLocaleTimeString([], {
215085
+ hour: "2-digit",
215086
+ minute: "2-digit",
215087
+ hour12: false
215088
+ });
215089
+ const status = entry.blocked ? "blocked" : "pass";
215090
+ const score = Number.isFinite(entry.aiScore) ? Math.round(entry.aiScore) : 0;
215091
+ return `${entry.mode} ${stamp} ${status} ${score}`;
215092
+ });
215093
+ return `history: ${parts.join(" | ")}`;
215094
+ }
215095
+
214832
215096
  // src/utils/colors.ts
214833
215097
  var c2 = {
214834
215098
  reset: "\x1B[0m",
@@ -214836,7 +215100,7 @@ var c2 = {
214836
215100
  dim: "\x1B[2m",
214837
215101
  italic: "\x1B[3m",
214838
215102
  inverse: "\x1B[7m",
214839
- red: "\x1B[31m",
215103
+ red: "\x1B[38;2;232;122;65m",
214840
215104
  green: "\x1B[32m",
214841
215105
  yellow: "\x1B[33m",
214842
215106
  blue: "\x1B[34m",
@@ -214847,18 +215111,22 @@ var c2 = {
214847
215111
  brightBlue: "\x1B[94m",
214848
215112
  brightCyan: "\x1B[96m",
214849
215113
  brightWhite: "\x1B[97m",
214850
- orange: "\x1B[38;5;208m",
214851
- /** Primary accent — npm-like red profile. */
214852
- accent: "\x1B[38;5;160m"
215114
+ orange: "\x1B[38;2;232;122;65m",
215115
+ /** Primary accent — ATHENA orange profile. */
215116
+ accent: "\x1B[38;2;232;122;65m",
215117
+ /** ATHENA logo box background (#E87A41). */
215118
+ bannerBg: "\x1B[48;2;232;122;65m",
215119
+ /** ATHENA logo glyph color matches site dark bg (#0f0f0f). */
215120
+ bannerFg: "\x1B[38;2;15;15;15m"
214853
215121
  };
214854
215122
 
214855
215123
  // src/utils/banner.ts
214856
215124
  var BANNER_LARGE = [
214857
- " \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588 ",
214858
- "\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588",
214859
- "\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588",
214860
- "\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588",
214861
- "\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588\u2588 \u2588\u2588 \u2588\u2588"
215125
+ " _ _____ _ _ _____ _ _ _ ",
215126
+ " / \\|_ _| | | | ____| \\ | | / \\ ",
215127
+ " / _ \\ | | | |_| | _| | \\| | / _ \\ ",
215128
+ " / ___ \\| | | _ | |___| |\\ |/ ___ \\",
215129
+ "/_/ \\_\\_| |_| |_|_____|_| \\_/_/ \\_\\"
214862
215130
  ];
214863
215131
  var BANNER_COMPACT = [
214864
215132
  "\u2584\u2580\u2588 \u2580\u2588\u2580 \u2588 \u2588 \u2588\u2580\u2580 \u2588\u2584 \u2588 \u2584\u2580\u2588",
@@ -214867,10 +215135,12 @@ var BANNER_COMPACT = [
214867
215135
  function printBanner() {
214868
215136
  if (!process.stdout.isTTY) return;
214869
215137
  const cols = process.stdout.columns ?? 80;
214870
- const banner = cols >= 56 ? BANNER_LARGE : BANNER_COMPACT;
215138
+ const useLarge = cols >= 56;
215139
+ const banner = useLarge ? BANNER_LARGE : BANNER_COMPACT;
214871
215140
  console.log("");
214872
215141
  for (const line of banner) {
214873
- console.log(` ${c2.accent}${line}${c2.reset}`);
215142
+ const style = useLarge ? `${c2.accent}${c2.bold}` : c2.accent;
215143
+ console.log(` ${style}${line}${c2.reset}`);
214874
215144
  }
214875
215145
  }
214876
215146
  function dashedLine(width) {
@@ -214883,6 +215153,9 @@ function truncate(value, max) {
214883
215153
  }
214884
215154
 
214885
215155
  // src/utils/terminal.ts
215156
+ function clearScreen() {
215157
+ process.stdout.write("\x1B[3J\x1B[2J\x1B[H");
215158
+ }
214886
215159
  function printRunHeader(mode, target) {
214887
215160
  const cols = Math.min(process.stdout.columns ?? 80, 72);
214888
215161
  printBanner();
@@ -214906,8 +215179,13 @@ function printRunResult(blocked) {
214906
215179
  // src/commands/check.ts
214907
215180
  async function checkCommand(files, options) {
214908
215181
  const selected = files.length > 0 ? files : await getStagedFiles();
214909
- const sourceFiles = selected.filter(isSourceFile).map((file) => (0, import_node_path2.resolve)(process.cwd(), file));
214910
- printRunHeader("check", `${sourceFiles.length} staged/source files`);
215182
+ const sourceFiles = selected.filter(isSourceFile).map((file) => (0, import_node_path3.resolve)(process.cwd(), file));
215183
+ if (!options.quietHeader) {
215184
+ if (process.stdout.isTTY) {
215185
+ clearScreen();
215186
+ }
215187
+ printRunHeader("check", `${sourceFiles.length} staged/source files`);
215188
+ }
214911
215189
  const expanded = sourceFiles.length === 1 ? await findSourceFiles(sourceFiles[0]) : sourceFiles;
214912
215190
  const report = await scanFiles(expanded, { threshold: Number(options.threshold) });
214913
215191
  if (options.format === "json") {
@@ -214917,28 +215195,37 @@ async function checkCommand(files, options) {
214917
215195
  } else {
214918
215196
  console.log(formatTerminalReport(report));
214919
215197
  }
215198
+ await appendScanHistory({
215199
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
215200
+ mode: "check",
215201
+ target: `${sourceFiles.length} staged/source files`,
215202
+ blocked: report.summary.blocked,
215203
+ filesScanned: report.summary.filesScanned,
215204
+ aiScore: report.summary.aiScore
215205
+ });
214920
215206
  printRunResult(report.summary.blocked);
214921
215207
  process.exitCode = report.summary.blocked ? 1 : 0;
214922
215208
  }
214923
215209
 
214924
215210
  // src/commands/init.ts
214925
- var import_promises4 = require("fs/promises");
214926
- var import_node_path3 = require("path");
215211
+ var import_promises5 = require("fs/promises");
215212
+ var import_node_path4 = require("path");
214927
215213
  async function initCommand() {
214928
215214
  const root = await getGitRoot();
214929
- if (!root) {
215215
+ const hooksDir = await getGitHooksDir();
215216
+ if (!root || !hooksDir) {
214930
215217
  console.error("Athena needs a git repository for pre-commit hook install.");
214931
215218
  process.exitCode = 1;
214932
215219
  return;
214933
215220
  }
214934
- const hookPath = (0, import_node_path3.join)(root, ".git", "hooks", "pre-commit");
215221
+ const hookPath = (0, import_node_path4.join)(hooksDir, "pre-commit");
214935
215222
  const hook = [
214936
215223
  "#!/bin/sh",
214937
215224
  'echo "athena: checking staged JS/TS files"',
214938
215225
  "npx athena check"
214939
215226
  ].join("\n");
214940
- await (0, import_promises4.mkdir)((0, import_node_path3.dirname)(hookPath), { recursive: true });
214941
- await (0, import_promises4.writeFile)(hookPath, `${hook}
215227
+ await (0, import_promises5.mkdir)((0, import_node_path4.dirname)(hookPath), { recursive: true });
215228
+ await (0, import_promises5.writeFile)(hookPath, `${hook}
214942
215229
  `, { mode: 493 });
214943
215230
  console.log(`Athena pre-commit hook installed at ${hookPath}`);
214944
215231
  }
@@ -214947,10 +215234,15 @@ async function initCommand() {
214947
215234
  var import_node_readline = require("readline");
214948
215235
 
214949
215236
  // src/commands/scan.ts
214950
- var import_node_path4 = require("path");
215237
+ var import_node_path5 = require("path");
214951
215238
  async function scanCommand(dir, options) {
214952
- const root = (0, import_node_path4.resolve)(process.cwd(), dir);
214953
- printRunHeader("scan", root);
215239
+ const root = (0, import_node_path5.resolve)(process.cwd(), dir);
215240
+ if (!options.quietHeader) {
215241
+ if (process.stdout.isTTY) {
215242
+ clearScreen();
215243
+ }
215244
+ printRunHeader("scan", root);
215245
+ }
214954
215246
  const files = await findSourceFiles(root);
214955
215247
  const report = await scanFiles(files, { threshold: Number(options.threshold) });
214956
215248
  if (options.format === "json") {
@@ -214960,29 +215252,38 @@ async function scanCommand(dir, options) {
214960
215252
  } else {
214961
215253
  console.log(formatTerminalReport(report));
214962
215254
  }
215255
+ await appendScanHistory({
215256
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
215257
+ mode: "scan",
215258
+ target: root,
215259
+ blocked: report.summary.blocked,
215260
+ filesScanned: report.summary.filesScanned,
215261
+ aiScore: report.summary.aiScore
215262
+ });
214963
215263
  printRunResult(report.summary.blocked);
214964
215264
  process.exitCode = report.summary.blocked ? 1 : 0;
214965
215265
  }
214966
215266
 
214967
215267
  // src/commands/uninstall.ts
214968
- var import_promises5 = require("fs/promises");
214969
- var import_node_path5 = require("path");
215268
+ var import_promises6 = require("fs/promises");
215269
+ var import_node_path6 = require("path");
214970
215270
  async function uninstallCommand() {
214971
215271
  const root = await getGitRoot();
214972
- if (!root) {
215272
+ const hooksDir = await getGitHooksDir();
215273
+ if (!root || !hooksDir) {
214973
215274
  console.error("Athena needs a git repository for hook uninstall.");
214974
215275
  process.exitCode = 1;
214975
215276
  return;
214976
215277
  }
214977
- const hookPath = (0, import_node_path5.join)(root, ".git", "hooks", "pre-commit");
214978
- await (0, import_promises5.rm)(hookPath, { force: true });
215278
+ const hookPath = (0, import_node_path6.join)(hooksDir, "pre-commit");
215279
+ await (0, import_promises6.rm)(hookPath, { force: true });
214979
215280
  console.log(`Athena pre-commit hook removed from ${hookPath}`);
214980
215281
  }
214981
215282
 
214982
215283
  // package.json
214983
215284
  var package_default = {
214984
215285
  name: "@arsh342/athena",
214985
- version: "0.1.4",
215286
+ version: "0.1.6",
214986
215287
  description: "AI code provenance tracker and terminal scanner for JavaScript and TypeScript repositories.",
214987
215288
  type: "module",
214988
215289
  bin: {
@@ -214993,12 +215294,14 @@ var package_default = {
214993
215294
  build: "tsup",
214994
215295
  dev: "tsx src/index.ts",
214995
215296
  prepack: "npm run build",
214996
- "pack:dry": "npm pack --dry-run"
215297
+ "pack:dry": "npm pack --dry-run",
215298
+ test: "node --import tsx --test test/**/*.test.ts"
214997
215299
  },
214998
215300
  files: [
214999
215301
  "dist",
215000
215302
  "README.md",
215001
- "LICENSE"
215303
+ "LICENSE",
215304
+ "null-pointer-font"
215002
215305
  ],
215003
215306
  keywords: [
215004
215307
  "ai",
@@ -215048,14 +215351,14 @@ async function menuCommand(program3) {
215048
215351
  desc: "Run full recursive JS/TS scan from cwd.",
215049
215352
  command: "athena scan .",
215050
215353
  detail: "Parse code units, score AI provenance, run targeted security checks, print report.",
215051
- run: () => scanCommand(".", { threshold: "65", format: "terminal" })
215354
+ run: () => scanCommand(".", { threshold: "9", format: "terminal", quietHeader: true })
215052
215355
  },
215053
215356
  {
215054
215357
  label: "Check staged files",
215055
215358
  desc: "Scan staged JS/TS files, same path used by pre-commit hook.",
215056
215359
  command: "athena check",
215057
215360
  detail: "Fast gate for commit flow. Reads git staged files and exits 1 on blocking risk.",
215058
- run: () => checkCommand([], { threshold: "65", format: "terminal" })
215361
+ run: () => checkCommand([], { threshold: "9", format: "terminal", quietHeader: true })
215059
215362
  },
215060
215363
  {
215061
215364
  label: "Install pre-commit hook",
@@ -215086,22 +215389,31 @@ async function menuCommand(program3) {
215086
215389
  run: () => void 0
215087
215390
  }
215088
215391
  ];
215089
- const choice = await select(items);
215090
- if (choice === null || items[choice]?.label === "Exit") {
215091
- console.log(`
215392
+ enterAltScreen();
215393
+ try {
215394
+ while (true) {
215395
+ const choice = await select(items);
215396
+ if (choice === null || items[choice]?.label === "Exit") {
215397
+ break;
215398
+ }
215399
+ clear();
215400
+ await items[choice].run();
215401
+ await waitForReturnToMenu();
215402
+ }
215403
+ } finally {
215404
+ exitAltScreen();
215405
+ }
215406
+ console.log(`
215092
215407
  ${c2.dim}athena selector closed${c2.reset}
215093
215408
  `);
215094
- return;
215095
- }
215096
- clear();
215097
- await items[choice].run();
215098
215409
  }
215099
215410
  async function select(items) {
215411
+ const historyText = formatRecentHistory(await getRecentScanHistory(3));
215100
215412
  (0, import_node_readline.emitKeypressEvents)(process.stdin);
215101
215413
  process.stdin.setRawMode(true);
215102
215414
  process.stdin.resume();
215103
215415
  let index = 0;
215104
- render(items, index);
215416
+ render(items, index, historyText);
215105
215417
  return new Promise((resolve3) => {
215106
215418
  const cleanup = () => {
215107
215419
  process.stdin.setRawMode(false);
@@ -215117,11 +215429,11 @@ async function select(items) {
215117
215429
  if (key.name === "q" || key.name === "escape") done(null);
215118
215430
  if (key.name === "up") {
215119
215431
  index = (index - 1 + items.length) % items.length;
215120
- render(items, index);
215432
+ render(items, index, historyText);
215121
215433
  }
215122
215434
  if (key.name === "down") {
215123
215435
  index = (index + 1) % items.length;
215124
- render(items, index);
215436
+ render(items, index, historyText);
215125
215437
  }
215126
215438
  if (key.name === "return") done(index);
215127
215439
  const number = Number(key.sequence);
@@ -215132,7 +215444,7 @@ async function select(items) {
215132
215444
  process.stdin.on("keypress", onKeypress);
215133
215445
  });
215134
215446
  }
215135
- function render(items, selected) {
215447
+ function render(items, selected, historyText) {
215136
215448
  clear();
215137
215449
  const cols = Math.min(process.stdout.columns ?? 80, 72);
215138
215450
  const selectedItem = items[selected];
@@ -215144,6 +215456,7 @@ function render(items, selected) {
215144
215456
  console.log(` ${dashedLine(cols - 4)}`);
215145
215457
  console.log("");
215146
215458
  console.log(` ${c2.dim}\u2191/\u2193${c2.reset} navigate ${c2.dim}enter${c2.reset} run ${c2.dim}1-${items.length}${c2.reset} jump ${c2.dim}q${c2.reset} quit`);
215459
+ console.log(` ${c2.dim}${truncate(historyText, cols - 4)}${c2.reset}`);
215147
215460
  console.log("");
215148
215461
  for (let i = 0; i < items.length; i++) {
215149
215462
  const item = items[i];
@@ -215164,21 +215477,49 @@ function render(items, selected) {
215164
215477
  console.log("");
215165
215478
  }
215166
215479
  function clear() {
215167
- process.stdout.write("\x1B[2J\x1B[H");
215480
+ clearScreen();
215481
+ }
215482
+ function enterAltScreen() {
215483
+ process.stdout.write("\x1B[?1049h");
215484
+ }
215485
+ function exitAltScreen() {
215486
+ process.stdout.write("\x1B[?1049l");
215168
215487
  }
215169
215488
  function pad(n) {
215170
215489
  return " ".repeat(Math.max(1, n));
215171
215490
  }
215491
+ async function waitForReturnToMenu() {
215492
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return;
215493
+ console.log(` ${c2.dim}press any key to return to selector${c2.reset}`);
215494
+ (0, import_node_readline.emitKeypressEvents)(process.stdin);
215495
+ process.stdin.setRawMode(true);
215496
+ process.stdin.resume();
215497
+ await new Promise((resolve3) => {
215498
+ const cleanup = () => {
215499
+ process.stdin.setRawMode(false);
215500
+ process.stdin.pause();
215501
+ process.stdin.off("keypress", onKeypress);
215502
+ };
215503
+ const onKeypress = () => {
215504
+ cleanup();
215505
+ resolve3();
215506
+ };
215507
+ process.stdin.on("keypress", onKeypress);
215508
+ });
215509
+ }
215172
215510
 
215173
215511
  // src/index.ts
215174
215512
  var program2 = new Command();
215175
215513
  program2.name("athena").description("AI code provenance tracker for JavaScript and TypeScript repositories").version(CLI_VERSION);
215176
- program2.command("scan").argument("[dir]", "directory to scan", ".").option("-t, --threshold <number>", "AI score threshold", "65").option("-f, --format <format>", "terminal | json | jsonl", "terminal").description("scan a directory recursively").action(scanCommand);
215177
- program2.command("check").argument("[files...]", "files to check; defaults to staged JS/TS files").option("-t, --threshold <number>", "AI score threshold", "65").option("-f, --format <format>", "terminal | json | jsonl", "terminal").description("check changed files for blocking findings").action(checkCommand);
215514
+ program2.command("scan").argument("[dir]", "directory to scan", ".").option("-t, --threshold <number>", "AI score threshold", "9").option("-f, --format <format>", "terminal | json | jsonl", "terminal").description("scan a directory recursively").action(scanCommand);
215515
+ program2.command("check").argument("[files...]", "files to check; defaults to staged JS/TS files").option("-t, --threshold <number>", "AI score threshold", "9").option("-f, --format <format>", "terminal | json | jsonl", "terminal").description("check changed files for blocking findings").action(checkCommand);
215178
215516
  program2.command("init").description("install Athena pre-commit hook").action(initCommand);
215179
215517
  program2.command("uninstall").description("remove Athena pre-commit hook").action(uninstallCommand);
215180
215518
  program2.command("menu").description("open interactive terminal selector").action(() => menuCommand(program2));
215181
215519
  async function main() {
215520
+ if (process.stdout.isTTY) {
215521
+ clearScreen();
215522
+ }
215182
215523
  if (process.argv.length <= 2) {
215183
215524
  await menuCommand(program2);
215184
215525
  } else {