@arx-hq/collectors-core 0.4.1 → 0.4.2

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
@@ -138,6 +138,8 @@ var ENTRYPOINT_BASENAMES = /* @__PURE__ */ new Set([
138
138
  "not-found",
139
139
  "middleware"
140
140
  ]);
141
+ var JSON_EXTENSIONS = /* @__PURE__ */ new Set([".json"]);
142
+ var SCRIPT_FILE_REF_REGEX = /(?:^|[\s"'=])((?:\.{0,2}\/)?[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*\.(?:[cm]?[jt]sx?))(?=$|[\s"';&|)])/g;
141
143
  function extractRelativeSpecifiers(filePath, content) {
142
144
  const sourceFile = ts.createSourceFile(
143
145
  filePath,
@@ -191,6 +193,57 @@ function resolveLocalImport(fromRelFile, specifier, allFilesSet) {
191
193
  }
192
194
  return null;
193
195
  }
196
+ function collectPackageJsonStrings(value, out) {
197
+ if (typeof value === "string") {
198
+ out.push(value);
199
+ return;
200
+ }
201
+ if (Array.isArray(value)) {
202
+ for (const item of value) {
203
+ collectPackageJsonStrings(item, out);
204
+ }
205
+ return;
206
+ }
207
+ if (typeof value === "object" && value !== null) {
208
+ for (const nested of Object.values(value)) {
209
+ collectPackageJsonStrings(nested, out);
210
+ }
211
+ }
212
+ }
213
+ function extractPackageJsonReferencedFiles(pkgRelFile, rawJson, allFilesSet) {
214
+ let parsed;
215
+ try {
216
+ parsed = JSON.parse(rawJson);
217
+ } catch {
218
+ return [];
219
+ }
220
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
221
+ return [];
222
+ }
223
+ const record = parsed;
224
+ const candidates = [];
225
+ for (const field of ["scripts", "main", "module", "bin", "exports"]) {
226
+ if (field in record) {
227
+ collectPackageJsonStrings(record[field], candidates);
228
+ }
229
+ }
230
+ const resolved = [];
231
+ for (const text of candidates) {
232
+ SCRIPT_FILE_REF_REGEX.lastIndex = 0;
233
+ let match = SCRIPT_FILE_REF_REGEX.exec(text);
234
+ while (match !== null) {
235
+ const token = match[1];
236
+ if (token) {
237
+ const hit = resolveLocalImport(pkgRelFile, token, allFilesSet);
238
+ if (hit) {
239
+ resolved.push(hit);
240
+ }
241
+ }
242
+ match = SCRIPT_FILE_REF_REGEX.exec(text);
243
+ }
244
+ }
245
+ return resolved;
246
+ }
194
247
  function isLikelyEntrypoint(relFile) {
195
248
  const posix = toPosixPath(relFile);
196
249
  if (posix.includes("/test/") || posix.includes("/tests/") || posix.startsWith("test/") || posix.startsWith("tests/") || posix.startsWith("scripts/") || /\.test\.[a-z]+$/.test(posix) || /\.spec\.[a-z]+$/.test(posix) || /\.config\.[a-z]+$/.test(posix) || posix.endsWith(".d.ts")) {
@@ -233,6 +286,24 @@ function createCodeDeadCollector() {
233
286
  }
234
287
  }
235
288
  }
289
+ const jsonFiles = await walkFiles({
290
+ rootDir: ctx.rootDir,
291
+ ignorePaths: ctx.config.ignorePaths,
292
+ extensions: JSON_EXTENSIONS
293
+ });
294
+ for (const relJson of jsonFiles) {
295
+ if (path2.posix.basename(relJson) !== "package.json") {
296
+ continue;
297
+ }
298
+ const raw = await readFile2(path2.resolve(ctx.rootDir, relJson), "utf8");
299
+ for (const hit of extractPackageJsonReferencedFiles(
300
+ relJson,
301
+ raw,
302
+ allSet
303
+ )) {
304
+ importedSet.add(hit);
305
+ }
306
+ }
236
307
  const findings = [];
237
308
  for (const relFile of files) {
238
309
  if (isLikelyEntrypoint(relFile) || importedSet.has(relFile)) {
@@ -250,10 +321,10 @@ function createCodeDeadCollector() {
250
321
  tier: "T2",
251
322
  severity: "low",
252
323
  title: `Unreferenced source file: ${relFile}`,
253
- plainSummary: `${relFile} is never imported by any module or test.`,
324
+ plainSummary: `Observed: ${relFile} is not imported by any module/test or referenced by any package.json script/entrypoint.`,
254
325
  evidence: { file: relFile },
255
326
  autoFixable: false,
256
- repairHint: `Import ${relFile} where needed or remove dead code file.`,
327
+ repairHint: `Import ${relFile} where needed, reference it in package.json, or remove dead code file.`,
257
328
  collector: "code-dead-files"
258
329
  });
259
330
  }
@@ -391,6 +462,19 @@ function countLines(content) {
391
462
  return normalized.split(/\r?\n/).length;
392
463
  }
393
464
  var MARKDOWN_LINK_REGEX = /\[[^\]]+\]\(([^)\s]+)\)/g;
465
+ var PUBLISHED_VERSION_CLAIM_REGEX = /(?:published\s+version|current\s+release|latest\s+release|released\s+version|yayımdaki\s+sürüm|yayındaki\s+sürüm|güncel\s+sürüm)\s*[:—-]\s*`?v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)`?/i;
466
+ function findStaleStatusVersionClaim(statusContent, packageVersion) {
467
+ const lines = statusContent.replace(/\r\n/g, "\n").split("\n");
468
+ for (let i = 0; i < lines.length; i += 1) {
469
+ const line = lines[i] ?? "";
470
+ const match = PUBLISHED_VERSION_CLAIM_REGEX.exec(line);
471
+ const declared = match?.[1];
472
+ if (declared && declared !== packageVersion) {
473
+ return { declared, line: i + 1 };
474
+ }
475
+ }
476
+ return null;
477
+ }
394
478
  function extractRelativeDocLinks(markdown) {
395
479
  const links = [];
396
480
  const lines = markdown.replace(/\r\n/g, "\n").split("\n");
@@ -449,14 +533,40 @@ function createArchDocLintCollector() {
449
533
  pillar: "ARCH",
450
534
  tier: "T1",
451
535
  severity: "high",
452
- title: `docs/STATUS.md has ${lineCount} lines (budget: <= ${statusMax})`,
453
- plainSummary: `Project status memory file grew to ${lineCount} lines, exceeding the ${statusMax}-line budget.`,
536
+ title: `Documentation budget: docs/STATUS.md has ${lineCount} lines (budget: <= ${statusMax})`,
537
+ plainSummary: `Observed: docs/STATUS.md is ${lineCount} lines, exceeding the configured ${statusMax}-line documentation budget. Impact: oversized status files bloat agent context.`,
454
538
  evidence: { file: "docs/STATUS.md", line: statusMax + 1 },
455
539
  autoFixable: false,
456
- repairHint: `Condense docs/STATUS.md to ${statusMax} lines or fewer, archiving historical detail elsewhere.`,
540
+ repairHint: `Condense docs/STATUS.md to ${statusMax} lines or fewer, archiving historical detail elsewhere (or adjust budgets.statusMaxLines in arx.config.ts).`,
457
541
  collector: "arx-doc-lint"
458
542
  });
459
543
  }
544
+ const pkg = await readPackageJson(ctx.rootDir);
545
+ const pkgVersion = pkg && "version" in pkg && typeof pkg.version === "string" ? pkg.version : void 0;
546
+ if (pkgVersion) {
547
+ const stale = findStaleStatusVersionClaim(statusContent, pkgVersion);
548
+ if (stale) {
549
+ findings.push({
550
+ id: "ARCH-03",
551
+ fingerprint: createFindingFingerprint3({
552
+ id: "ARCH-03",
553
+ collector: "arx-doc-lint",
554
+ file: "docs/STATUS.md",
555
+ line: stale.line,
556
+ detail: "status-stale-version"
557
+ }),
558
+ pillar: "ARCH",
559
+ tier: "T1",
560
+ severity: "medium",
561
+ title: `Stale published version in docs/STATUS.md:${stale.line} (${stale.declared} vs package.json ${pkgVersion})`,
562
+ plainSummary: `Observed: docs/STATUS.md:${stale.line} states published version "${stale.declared}" while package.json is "${pkgVersion}". Impact: readers and agents rely on outdated release status.`,
563
+ evidence: { file: "docs/STATUS.md", line: stale.line },
564
+ autoFixable: false,
565
+ repairHint: `Update the current/published version declaration at docs/STATUS.md:${stale.line} to ${pkgVersion}.`,
566
+ collector: "arx-doc-lint"
567
+ });
568
+ }
569
+ }
460
570
  }
461
571
  const agentsPath = path4.resolve(ctx.rootDir, "AGENTS.md");
462
572
  const agentsContent = await readTextIfExists(agentsPath);
@@ -474,8 +584,8 @@ function createArchDocLintCollector() {
474
584
  pillar: "ARCH",
475
585
  tier: "T1",
476
586
  severity: "high",
477
- title: `AGENTS.md has ${lineCount} lines (budget: <= ${agentsMax})`,
478
- plainSummary: `Agent instruction file grew to ${lineCount} lines, risking context bloat.`,
587
+ title: `Documentation budget: AGENTS.md has ${lineCount} lines (budget: <= ${agentsMax})`,
588
+ plainSummary: `Observed: AGENTS.md is ${lineCount} lines, exceeding the configured ${agentsMax}-line budget. Impact: large rule files degrade agent instruction adherence.`,
479
589
  evidence: { file: "AGENTS.md", line: agentsMax + 1 },
480
590
  autoFixable: false,
481
591
  repairHint: `Trim AGENTS.md to ${agentsMax} lines or fewer and move deep references to docs/.`,
@@ -507,7 +617,7 @@ function createArchDocLintCollector() {
507
617
  tier: "T1",
508
618
  severity: "medium",
509
619
  title: `Broken architecture reference: ${link.target}`,
510
- plainSummary: `docs/ARCHITECTURE.md points to "${relDisplay}", which does not exist.`,
620
+ plainSummary: `Observed: docs/ARCHITECTURE.md points to "${relDisplay}", which does not exist.`,
511
621
  evidence: {
512
622
  file: archRel,
513
623
  line: link.line,
@@ -827,9 +937,67 @@ import {
827
937
  } from "@arx-hq/contracts";
828
938
  import ts2 from "typescript";
829
939
  var TODO_COMMENT_REGEX = /\b(?:TODO|FIXME)\b/;
940
+ var CRITICAL_TRY_PATH_REGEX = /\b(?:writeFile|writeFileSync|appendFile|appendFileSync|save|insert|update|delete|drop|query|exec|prepare|run|commit|transaction|fetch|post|put|patch|send|json|writeHead|setHeader|auth|verify|sign|charge|pay|encrypt|decrypt)\s*\(/i;
941
+ var BEST_EFFORT_TRY_PATH_REGEX = /\b(?:stat(?:Sync)?|lstat(?:Sync)?|access(?:Sync)?|exists(?:Sync)?|unlink(?:Sync)?|rm(?:Sync)?|rmdir(?:Sync)?|close[A-Za-z0-9_]*|destroy[A-Za-z0-9_]*|end|kill|open[A-Za-z0-9_]*|launch[A-Za-z0-9_]*|spawn[A-Za-z0-9_]*|execFile[A-Za-z0-9_]*|focus|blur|scrollIntoView|clipboard|localStorage|sessionStorage|JSON\.parse)\b/i;
942
+ var FALSE_SUCCESS_AFTER_TRY_REGEX = /return\s+(?:true|\{[^}]*(?:ok\s*:\s*true|saved\s*:\s*true|success\s*:\s*true))|status\(\s*20\d\s*\)|["'](?:saved|ok|success)["']/i;
943
+ function isTestOrHelperFile(relFile) {
944
+ const posix = toPosixPath(relFile);
945
+ return posix.startsWith("test/") || posix.startsWith("tests/") || posix.includes("/test/") || posix.includes("/tests/") || /\.(?:test|spec)\.[a-z]+$/.test(posix);
946
+ }
947
+ function getStatementsAfterTry(tryStmt, sourceFile) {
948
+ const parent = tryStmt.parent;
949
+ if (!ts2.isBlock(parent) && !ts2.isSourceFile(parent)) {
950
+ return "";
951
+ }
952
+ const stmts = parent.statements;
953
+ const idx = stmts.indexOf(tryStmt);
954
+ if (idx === -1 || idx + 1 >= stmts.length) {
955
+ return "";
956
+ }
957
+ return stmts.slice(idx + 1, idx + 4).map((stmt) => stmt.getText(sourceFile)).join("\n");
958
+ }
959
+ function classifyEmptyCatch(catchNode, sourceFile) {
960
+ const parent = catchNode.parent;
961
+ if (!ts2.isTryStatement(parent)) {
962
+ return {
963
+ severity: "high",
964
+ kind: "empty-catch",
965
+ label: "Empty catch block",
966
+ impact: "An empty error handler silently hides unexpected runtime failures."
967
+ };
968
+ }
969
+ const tryText = parent.tryBlock.getText(sourceFile);
970
+ const afterText = getStatementsAfterTry(parent, sourceFile);
971
+ const hasCriticalOp = CRITICAL_TRY_PATH_REGEX.test(tryText);
972
+ const hasFalseSuccessAfter = FALSE_SUCCESS_AFTER_TRY_REGEX.test(afterText);
973
+ const hasBestEffortOp = BEST_EFFORT_TRY_PATH_REGEX.test(tryText);
974
+ if (hasCriticalOp || hasFalseSuccessAfter) {
975
+ return {
976
+ severity: "high",
977
+ kind: "empty-catch-critical-path",
978
+ label: "Empty catch swallows failure on write/state path",
979
+ impact: "Failures during state/persistence/network work can silently lose data or report false success."
980
+ };
981
+ }
982
+ if (hasBestEffortOp) {
983
+ return {
984
+ severity: "medium",
985
+ kind: "empty-catch-fallback",
986
+ label: "Empty catch swallows best-effort/cleanup error",
987
+ impact: "Lower risk than write-path failures, but still hides unexpected exceptions on cleanup/probe/launch fallback paths."
988
+ };
989
+ }
990
+ return {
991
+ severity: "high",
992
+ kind: "empty-catch",
993
+ label: "Empty catch block",
994
+ impact: "An empty error handler silently hides unexpected runtime failures."
995
+ };
996
+ }
830
997
  function scanSourceForAiSlop(relFile, content, maxFileLines) {
831
998
  const findings = [];
832
999
  const lines = content.replace(/\r\n/g, "\n").split("\n");
1000
+ const isTestFile = isTestOrHelperFile(relFile);
833
1001
  if (lines.length > maxFileLines && !isSuppressedAtLine(lines, 1, "CODE-06")) {
834
1002
  findings.push({
835
1003
  id: "CODE-06",
@@ -843,7 +1011,7 @@ function scanSourceForAiSlop(relFile, content, maxFileLines) {
843
1011
  tier: "T1",
844
1012
  severity: "medium",
845
1013
  title: `File exceeds ${maxFileLines}-line budget (${lines.length} lines)`,
846
- plainSummary: `${relFile} is ${lines.length} lines long; large files are harder to maintain safely.`,
1014
+ plainSummary: `Observed: ${relFile} is ${lines.length} lines (budget: <= ${maxFileLines}). Impact: oversized modules are harder to review and maintain safely.`,
847
1015
  evidence: { file: relFile, line: maxFileLines + 1 },
848
1016
  autoFixable: false,
849
1017
  repairHint: `Split ${relFile} into cohesive modules of ${maxFileLines} lines or fewer.`,
@@ -905,7 +1073,7 @@ function scanSourceForAiSlop(relFile, content, maxFileLines) {
905
1073
  "medium",
906
1074
  "todo-marker",
907
1075
  `Unfinished TODO/FIXME marker in ${relFile}:${pos.line + 1}`,
908
- `Unfinished placeholder work was left in ${relFile}.`,
1076
+ `Observed: unresolved TODO/FIXME comment in ${relFile}:${pos.line + 1}. Impact: incomplete work may ship unintentionally.`,
909
1077
  `Complete the work and remove the TODO/FIXME comment at ${relFile}:${pos.line + 1}.`
910
1078
  );
911
1079
  }
@@ -920,28 +1088,41 @@ function scanSourceForAiSlop(relFile, content, maxFileLines) {
920
1088
  const pos = sourceFile.getLineAndCharacterOfPosition(
921
1089
  node.getStart(sourceFile)
922
1090
  );
923
- addSlopFinding(
924
- pos.line + 1,
925
- pos.character + 1,
926
- "high",
927
- "explicit-any",
928
- `Explicit "any" type in ${relFile}:${pos.line + 1}`,
929
- `Unsafe "any" type disables static type checking in ${relFile}.`,
930
- `Replace "any" at ${relFile}:${pos.line + 1} with a concrete type or "unknown" + narrowing.`
931
- );
1091
+ if (isTestFile) {
1092
+ addSlopFinding(
1093
+ pos.line + 1,
1094
+ pos.character + 1,
1095
+ "medium",
1096
+ "explicit-any-test",
1097
+ `Explicit "any" type in test helper ${relFile}:${pos.line + 1}`,
1098
+ `Observed: explicit "any" in test/helper file ${relFile}:${pos.line + 1}. Impact: weakens test type guarantees (lower production risk than runtime code).`,
1099
+ `Replace "any" at ${relFile}:${pos.line + 1} with a concrete test type or "unknown" + narrowing.`
1100
+ );
1101
+ } else {
1102
+ addSlopFinding(
1103
+ pos.line + 1,
1104
+ pos.character + 1,
1105
+ "high",
1106
+ "explicit-any",
1107
+ `Explicit "any" type in ${relFile}:${pos.line + 1}`,
1108
+ `Observed: explicit "any" in production source ${relFile}:${pos.line + 1}. Impact: disables static type safety on runtime paths.`,
1109
+ `Replace "any" at ${relFile}:${pos.line + 1} with a concrete type or "unknown" + narrowing.`
1110
+ );
1111
+ }
932
1112
  }
933
1113
  if (ts2.isCatchClause(node) && node.block.statements.length === 0) {
934
1114
  const pos = sourceFile.getLineAndCharacterOfPosition(
935
1115
  node.getStart(sourceFile)
936
1116
  );
1117
+ const classified = classifyEmptyCatch(node, sourceFile);
937
1118
  addSlopFinding(
938
1119
  pos.line + 1,
939
1120
  pos.character + 1,
940
- "high",
941
- "empty-catch",
942
- `Empty catch block in ${relFile}:${pos.line + 1}`,
943
- `An empty error handler silently hides failures in ${relFile}.`,
944
- `Handle, log, or rethrow the error in catch block at ${relFile}:${pos.line + 1}.`
1121
+ classified.severity,
1122
+ classified.kind,
1123
+ `${classified.label} in ${relFile}:${pos.line + 1}`,
1124
+ `Observed: empty catch block at ${relFile}:${pos.line + 1}. Impact: ${classified.impact}`,
1125
+ `Handle, log, return a typed fallback, or rethrow the error at ${relFile}:${pos.line + 1} (if intentionally ignored, handle explicitly rather than an empty catch).`
945
1126
  );
946
1127
  }
947
1128
  ts2.forEachChild(node, visit);
@@ -1154,7 +1335,7 @@ ${result.stderr}`.trim();
1154
1335
  }
1155
1336
 
1156
1337
  // src/collectors/ops-env-example.ts
1157
- import { readFile as readFile5 } from "fs/promises";
1338
+ import { readdir as readdir2, readFile as readFile5 } from "fs/promises";
1158
1339
  import path10 from "path";
1159
1340
  import {
1160
1341
  createFindingFingerprint as createFindingFingerprint8
@@ -1164,22 +1345,63 @@ var IGNORED_ENV_KEYS = /* @__PURE__ */ new Set([
1164
1345
  "NODE_ENV",
1165
1346
  "CI",
1166
1347
  "GITHUB_ACTIONS",
1348
+ "GITHUB_TOKEN",
1349
+ "GITHUB_WORKSPACE",
1350
+ "GITHUB_REPOSITORY",
1351
+ "GITHUB_OUTPUT",
1352
+ "GITHUB_STEP_SUMMARY",
1353
+ "GITHUB_EVENT_PATH",
1354
+ "GITHUB_REF",
1355
+ "GITHUB_REF_NAME",
1356
+ "GITHUB_SHA",
1167
1357
  "PATH",
1168
1358
  "HOME",
1169
1359
  "USER",
1170
1360
  "USERNAME",
1171
1361
  "USERPROFILE",
1362
+ "APPDATA",
1363
+ "LOCALAPPDATA",
1364
+ "PROGRAMDATA",
1365
+ "HOMEDRIVE",
1366
+ "HOMEPATH",
1367
+ "SYSTEMROOT",
1368
+ "WINDIR",
1369
+ "COMSPEC",
1370
+ "PATHEXT",
1371
+ "COMPUTERNAME",
1372
+ "OS",
1172
1373
  "TEMP",
1173
1374
  "TMP",
1375
+ "TMPDIR",
1376
+ "XDG_CONFIG_HOME",
1377
+ "XDG_DATA_HOME",
1378
+ "XDG_CACHE_HOME",
1379
+ "XDG_STATE_HOME",
1380
+ "XDG_RUNTIME_DIR",
1174
1381
  "PWD",
1175
1382
  "SHELL",
1383
+ "TERM",
1384
+ "COLORTERM",
1385
+ "EDITOR",
1386
+ "VISUAL",
1387
+ "LANG",
1388
+ "LC_ALL",
1389
+ "LC_CTYPE",
1390
+ "HOSTNAME",
1391
+ "LOGNAME",
1176
1392
  "TZ",
1177
1393
  "DEBUG",
1178
1394
  "FORCE_COLOR",
1179
1395
  "NO_COLOR",
1180
1396
  "VITEST",
1181
- "JEST_WORKER_ID"
1397
+ "JEST_WORKER_ID",
1398
+ "INIT_CWD",
1399
+ "npm_lifecycle_event",
1400
+ "npm_package_version"
1182
1401
  ]);
1402
+ function isTestOnlyPath(relFile) {
1403
+ return relFile.endsWith(".d.ts") || relFile.startsWith("test/") || relFile.startsWith("tests/") || relFile.includes("/test/") || relFile.includes("/tests/") || /\.(?:test|spec)\.[a-z]+$/.test(relFile);
1404
+ }
1183
1405
  function extractProcessEnvKeys(relFile, content) {
1184
1406
  const refs = [];
1185
1407
  const lines = content.replace(/\r\n/g, "\n").split("\n");
@@ -1233,6 +1455,49 @@ function parseEnvExampleKeys(content) {
1233
1455
  }
1234
1456
  return keys;
1235
1457
  }
1458
+ async function loadDocTexts(rootDir) {
1459
+ const docs = [];
1460
+ try {
1461
+ const rootEntries = await readdir2(rootDir, { withFileTypes: true });
1462
+ for (const entry of rootEntries) {
1463
+ if (entry.isFile() && /^README(?:\.[A-Za-z0-9_-]+)?\.md$/i.test(entry.name)) {
1464
+ const content = await readTextIfExists(
1465
+ path10.resolve(rootDir, entry.name)
1466
+ );
1467
+ if (content !== null) {
1468
+ docs.push({ file: entry.name, content });
1469
+ }
1470
+ }
1471
+ }
1472
+ } catch {
1473
+ return docs;
1474
+ }
1475
+ const docsDir = path10.resolve(rootDir, "docs");
1476
+ try {
1477
+ const docEntries = await readdir2(docsDir, { withFileTypes: true });
1478
+ for (const entry of docEntries) {
1479
+ if (entry.isFile() && entry.name.endsWith(".md")) {
1480
+ const content = await readTextIfExists(path10.join(docsDir, entry.name));
1481
+ if (content !== null) {
1482
+ docs.push({ file: `docs/${entry.name}`, content });
1483
+ }
1484
+ }
1485
+ }
1486
+ } catch {
1487
+ return docs;
1488
+ }
1489
+ return docs;
1490
+ }
1491
+ function findDocumentingFile(key, docs) {
1492
+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1493
+ const tokenRegex = new RegExp(`\\b${escaped}\\b`);
1494
+ for (const doc of docs) {
1495
+ if (tokenRegex.test(doc.content)) {
1496
+ return doc.file;
1497
+ }
1498
+ }
1499
+ return null;
1500
+ }
1236
1501
  function createOpsEnvExampleCollector() {
1237
1502
  return {
1238
1503
  name: "ops-env-example",
@@ -1255,7 +1520,7 @@ function createOpsEnvExampleCollector() {
1255
1520
  });
1256
1521
  const firstRefByKey = /* @__PURE__ */ new Map();
1257
1522
  for (const relFile of files) {
1258
- if (relFile.endsWith(".d.ts") || relFile.includes("/test/") || relFile.includes("/tests/") || /\.test\.[a-z]+$/.test(relFile)) {
1523
+ if (isTestOnlyPath(relFile)) {
1259
1524
  continue;
1260
1525
  }
1261
1526
  const content = await readFile5(
@@ -1274,34 +1539,61 @@ function createOpsEnvExampleCollector() {
1274
1539
  const envExampleContent = await readTextIfExists(
1275
1540
  path10.resolve(ctx.rootDir, ".env.example")
1276
1541
  );
1277
- const documentedKeys = envExampleContent !== null ? parseEnvExampleKeys(envExampleContent) : /* @__PURE__ */ new Set();
1542
+ const envExampleKeys = envExampleContent !== null ? parseEnvExampleKeys(envExampleContent) : /* @__PURE__ */ new Set();
1543
+ const docs = await loadDocTexts(ctx.rootDir);
1278
1544
  const findings = [];
1279
1545
  for (const [key, ref] of firstRefByKey.entries()) {
1280
- if (documentedKeys.has(key)) {
1546
+ if (envExampleKeys.has(key)) {
1281
1547
  continue;
1282
1548
  }
1283
- findings.push({
1284
- id: "OPS-02",
1285
- fingerprint: createFindingFingerprint8({
1549
+ const docFile = findDocumentingFile(key, docs);
1550
+ if (docFile) {
1551
+ findings.push({
1286
1552
  id: "OPS-02",
1287
- collector: "ops-env-example",
1288
- file: ".env.example",
1289
- detail: key
1290
- }),
1291
- pillar: "OPS",
1292
- tier: "T1",
1293
- severity: "medium",
1294
- title: `Undocumented environment variable: ${key}`,
1295
- plainSummary: `Code reads process.env.${key} (${ref.file}:${ref.line}), but ${key} is missing from .env.example.`,
1296
- evidence: {
1297
- file: ref.file,
1298
- line: ref.line,
1299
- snippet: `process.env.${key}`
1300
- },
1301
- autoFixable: true,
1302
- repairHint: `Add "${key}=" with a safe placeholder value to .env.example.`,
1303
- collector: "ops-env-example"
1304
- });
1553
+ fingerprint: createFindingFingerprint8({
1554
+ id: "OPS-02",
1555
+ collector: "ops-env-example",
1556
+ file: ".env.example",
1557
+ detail: key
1558
+ }),
1559
+ pillar: "OPS",
1560
+ tier: "T1",
1561
+ severity: "low",
1562
+ title: `Environment variable not listed in .env.example (documented in ${docFile}): ${key}`,
1563
+ plainSummary: `Observed: process.env.${key} (${ref.file}:${ref.line}) is documented in ${docFile} but absent from .env.example. Impact: minor onboarding friction if users copy .env.example.`,
1564
+ evidence: {
1565
+ file: ref.file,
1566
+ line: ref.line,
1567
+ snippet: `process.env.${key}`
1568
+ },
1569
+ autoFixable: true,
1570
+ repairHint: `Optionally add "${key}=" to .env.example if contributors configure it via .env files, or suppress with // arx-ignore OPS-02 --reason "documented in ${docFile}".`,
1571
+ collector: "ops-env-example"
1572
+ });
1573
+ } else {
1574
+ findings.push({
1575
+ id: "OPS-02",
1576
+ fingerprint: createFindingFingerprint8({
1577
+ id: "OPS-02",
1578
+ collector: "ops-env-example",
1579
+ file: ".env.example",
1580
+ detail: key
1581
+ }),
1582
+ pillar: "OPS",
1583
+ tier: "T1",
1584
+ severity: "medium",
1585
+ title: `Environment variable missing from .env.example and docs: ${key}`,
1586
+ plainSummary: `Observed: process.env.${key} (${ref.file}:${ref.line}) is missing from .env.example and not mentioned in README/docs. Impact: deployments or new developers may miss required runtime settings.`,
1587
+ evidence: {
1588
+ file: ref.file,
1589
+ line: ref.line,
1590
+ snippet: `process.env.${key}`
1591
+ },
1592
+ autoFixable: true,
1593
+ repairHint: `Add "${key}=" with a safe placeholder value to .env.example (or document it in README.md).`,
1594
+ collector: "ops-env-example"
1595
+ });
1596
+ }
1305
1597
  }
1306
1598
  return findings;
1307
1599
  }
@@ -1559,36 +1851,92 @@ var SECRET_PATTERNS = [
1559
1851
  {
1560
1852
  kind: "aws-access-key",
1561
1853
  label: "AWS Access Key ID",
1854
+ prefixRegex: /^AKIA/,
1562
1855
  regex: /\bAKIA[0-9A-Z]{16}\b/
1563
1856
  },
1564
1857
  {
1565
1858
  kind: "github-pat",
1566
1859
  label: "GitHub Personal Access Token",
1860
+ prefixRegex: /^(?:ghp_|github_pat_)/,
1567
1861
  regex: /\b(?:ghp_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{22,})\b/
1568
1862
  },
1569
1863
  {
1570
1864
  kind: "stripe-or-api-secret",
1571
1865
  label: "Live Secret API Key",
1572
- regex: /\b(?:sk_live_|rk_live_)[A-Za-z0-9]{16,}\b/
1866
+ prefixRegex: /^(?:sk_live_|rk_live_)/,
1867
+ regex: /\b(?:sk_live_|rk_live_)[A-Za-z0-9_-]{16,}\b/
1573
1868
  },
1574
1869
  {
1575
1870
  kind: "openai-anthropic-key",
1576
1871
  label: "AI Provider Secret Key",
1872
+ prefixRegex: /^sk-(?:proj-|ant-)?/,
1577
1873
  regex: /\bsk-(?:proj-|ant-)?[A-Za-z0-9_-]{24,}\b/
1578
1874
  },
1579
1875
  {
1580
1876
  kind: "slack-token",
1581
1877
  label: "Slack Token",
1878
+ prefixRegex: /^xox[baprs]-/,
1582
1879
  regex: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/
1583
1880
  },
1584
1881
  {
1585
1882
  kind: "private-key",
1586
1883
  label: "Private Key Material",
1884
+ prefixRegex: /^-----BEGIN /,
1587
1885
  regex: /-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/
1588
1886
  }
1589
1887
  ];
1590
1888
  var GENERIC_ASSIGNMENT_REGEX = /(?:api[_-]?key|secret[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|private[_-]?key|db[_-]?password)\s*[:=]\s*["']([^"'\s]{20,})["']/i;
1591
1889
  var PLACEHOLDER_REGEX = /(?:example|placeholder|changeme|your[_-]|replace[_-]|xxxxx|00000000|dummy_placeholder)/i;
1890
+ var EXPLICIT_PLACEHOLDER_WORDS = /* @__PURE__ */ new Set([
1891
+ "placeholder",
1892
+ "example",
1893
+ "sample",
1894
+ "dummy",
1895
+ "fake",
1896
+ "mock",
1897
+ "value",
1898
+ "token",
1899
+ "secret",
1900
+ "key",
1901
+ "here",
1902
+ "redacted",
1903
+ "your",
1904
+ "replace",
1905
+ "changeme",
1906
+ "invalid",
1907
+ "not",
1908
+ "real",
1909
+ "test",
1910
+ "demo",
1911
+ "fixture",
1912
+ "api",
1913
+ "proj",
1914
+ "live",
1915
+ "me",
1916
+ "local",
1917
+ "dev",
1918
+ "docs",
1919
+ "doc",
1920
+ "xxx",
1921
+ "xxxx",
1922
+ "xxxxx"
1923
+ ]);
1924
+ function isExplicitPlaceholderToken(matchedToken, prefixRegex) {
1925
+ if (matchedToken.startsWith("-----BEGIN ")) {
1926
+ return false;
1927
+ }
1928
+ const suffix = matchedToken.replace(prefixRegex, "");
1929
+ if (suffix.length === 0) {
1930
+ return false;
1931
+ }
1932
+ const segments = suffix.split(/[-_.]+/).map((segment) => segment.toLowerCase()).filter((segment) => segment.length > 0);
1933
+ if (segments.length < 2) {
1934
+ return false;
1935
+ }
1936
+ return segments.every(
1937
+ (segment) => /^[a-z]+$/.test(segment) && EXPLICIT_PLACEHOLDER_WORDS.has(segment)
1938
+ );
1939
+ }
1592
1940
  function calculateShannonEntropy(value) {
1593
1941
  if (value.length === 0) {
1594
1942
  return 0;
@@ -1624,6 +1972,11 @@ function scanContentForSecrets(relFile, content) {
1624
1972
  const match = pattern.regex.exec(line);
1625
1973
  if (match?.[0]) {
1626
1974
  matchedRule = true;
1975
+ if (isExplicitPlaceholderToken(match[0], pattern.prefixRegex)) {
1976
+ break;
1977
+ }
1978
+ const suffix = match[0].replace(pattern.prefixRegex, "");
1979
+ const entropy = calculateShannonEntropy(suffix);
1627
1980
  findings.push({
1628
1981
  id: "SEC-01",
1629
1982
  fingerprint: createFindingFingerprint11({
@@ -1637,14 +1990,14 @@ function scanContentForSecrets(relFile, content) {
1637
1990
  tier: "T1",
1638
1991
  severity: "blocker",
1639
1992
  title: `Hardcoded ${pattern.label} in ${relFile}:${lineNum}`,
1640
- plainSummary: `A secret key (${pattern.label}) appears hardcoded in ${relFile} on line ${lineNum}.`,
1993
+ plainSummary: `Observed: matched ${pattern.label} format (non-placeholder payload, entropy=${entropy.toFixed(2)}) at ${relFile}:${lineNum}. Impact: if live, credential leaks into source history. Verify before shipping.`,
1641
1994
  evidence: {
1642
1995
  file: relFile,
1643
1996
  line: lineNum,
1644
1997
  snippet: redactToken(match[0])
1645
1998
  },
1646
1999
  autoFixable: false,
1647
- repairHint: `Remove the hardcoded secret at ${relFile}:${lineNum}, rotate the credential if live, and read it from process.env.`,
2000
+ repairHint: `If live, remove the key at ${relFile}:${lineNum}, rotate it immediately, and read from process.env. If intentionally synthetic, use explicit placeholder words or // arx-ignore SEC-01 --reason "...".`,
1648
2001
  collector: "sec-secrets"
1649
2002
  });
1650
2003
  break;
@@ -1656,6 +2009,7 @@ function scanContentForSecrets(relFile, content) {
1656
2009
  const genericMatch = GENERIC_ASSIGNMENT_REGEX.exec(line);
1657
2010
  const candidate = genericMatch?.[1];
1658
2011
  if (candidate && !PLACEHOLDER_REGEX.test(candidate) && calculateShannonEntropy(candidate) >= 3.8) {
2012
+ const entropy = calculateShannonEntropy(candidate);
1659
2013
  findings.push({
1660
2014
  id: "SEC-01",
1661
2015
  fingerprint: createFindingFingerprint11({
@@ -1669,14 +2023,14 @@ function scanContentForSecrets(relFile, content) {
1669
2023
  tier: "T1",
1670
2024
  severity: "blocker",
1671
2025
  title: `High-entropy hardcoded secret in ${relFile}:${lineNum}`,
1672
- plainSummary: `A high-entropy credential appears hardcoded in ${relFile} on line ${lineNum}.`,
2026
+ plainSummary: `Observed: high-entropy secret literal (entropy=${entropy.toFixed(2)}) assigned at ${relFile}:${lineNum}. Impact: if live, exposes credentials in source history.`,
1673
2027
  evidence: {
1674
2028
  file: relFile,
1675
2029
  line: lineNum,
1676
2030
  snippet: redactToken(candidate)
1677
2031
  },
1678
2032
  autoFixable: false,
1679
- repairHint: `Move the secret assigned at ${relFile}:${lineNum} into environment variables and document the key name in .env.example.`,
2033
+ repairHint: `Move the credential at ${relFile}:${lineNum} into process.env and document the variable name in .env.example (or mark synthetic fixtures with // arx-ignore SEC-01 --reason "...").`,
1680
2034
  collector: "sec-secrets"
1681
2035
  });
1682
2036
  }
@@ -2055,13 +2409,17 @@ export {
2055
2409
  createSecUnsafeAstCollector,
2056
2410
  createTestRunnerCollector,
2057
2411
  detectCyclesInGraph,
2412
+ extractPackageJsonReferencedFiles,
2058
2413
  extractProcessEnvKeys,
2059
2414
  extractRelativeDocLinks,
2060
2415
  extractRelativeSpecifiers,
2416
+ findStaleStatusVersionClaim,
2061
2417
  getPackageManagerRunArgs,
2062
2418
  gitignoreCoversEnv,
2419
+ isExplicitPlaceholderToken,
2063
2420
  isSensitiveTrackedFile,
2064
2421
  isSuppressedAtLine,
2422
+ isTestOnlyPath,
2065
2423
  parseAuditJsonCounts,
2066
2424
  parseBiomeTextOutput,
2067
2425
  parseEnvExampleKeys,