sentinelayer-cli 0.6.2 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/README.md +1009 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/ai-governance/index.js +12 -0
  7. package/src/agents/ai-governance/tools/base.js +171 -0
  8. package/src/agents/ai-governance/tools/eval-regression.js +47 -0
  9. package/src/agents/ai-governance/tools/hitl-audit.js +81 -0
  10. package/src/agents/ai-governance/tools/index.js +52 -0
  11. package/src/agents/ai-governance/tools/prompt-drift.js +42 -0
  12. package/src/agents/ai-governance/tools/provenance-check.js +69 -0
  13. package/src/agents/backend/index.js +12 -0
  14. package/src/agents/backend/tools/base.js +189 -0
  15. package/src/agents/backend/tools/circuit-breaker-check.js +123 -0
  16. package/src/agents/backend/tools/idempotency-audit.js +105 -0
  17. package/src/agents/backend/tools/index.js +87 -0
  18. package/src/agents/backend/tools/retry-audit.js +132 -0
  19. package/src/agents/backend/tools/timeout-audit.js +144 -0
  20. package/src/agents/code-quality/index.js +12 -0
  21. package/src/agents/code-quality/tools/base.js +159 -0
  22. package/src/agents/code-quality/tools/complexity-measure.js +197 -0
  23. package/src/agents/code-quality/tools/coupling-analysis.js +81 -0
  24. package/src/agents/code-quality/tools/cycle-detect.js +49 -0
  25. package/src/agents/code-quality/tools/dep-graph.js +196 -0
  26. package/src/agents/code-quality/tools/index.js +89 -0
  27. package/src/agents/data-layer/index.js +12 -0
  28. package/src/agents/data-layer/tools/base.js +181 -0
  29. package/src/agents/data-layer/tools/index-audit.js +165 -0
  30. package/src/agents/data-layer/tools/index.js +83 -0
  31. package/src/agents/data-layer/tools/migration-scan.js +135 -0
  32. package/src/agents/data-layer/tools/query-explain.js +120 -0
  33. package/src/agents/data-layer/tools/tenancy-scan.js +166 -0
  34. package/src/agents/documentation/index.js +12 -0
  35. package/src/agents/documentation/tools/api-diff.js +91 -0
  36. package/src/agents/documentation/tools/base.js +151 -0
  37. package/src/agents/documentation/tools/dead-link-check.js +58 -0
  38. package/src/agents/documentation/tools/docstring-coverage.js +78 -0
  39. package/src/agents/documentation/tools/index.js +52 -0
  40. package/src/agents/documentation/tools/readme-freshness.js +61 -0
  41. package/src/agents/envelope/fix-cycle.js +45 -0
  42. package/src/agents/envelope/index.js +31 -0
  43. package/src/agents/envelope/loop.js +150 -0
  44. package/src/agents/envelope/pulse.js +18 -0
  45. package/src/agents/envelope/stream.js +40 -0
  46. package/src/agents/infrastructure/index.js +12 -0
  47. package/src/agents/infrastructure/tools/base.js +171 -0
  48. package/src/agents/infrastructure/tools/checkov-run.js +32 -0
  49. package/src/agents/infrastructure/tools/drift-detect.js +59 -0
  50. package/src/agents/infrastructure/tools/iam-least-priv-check.js +78 -0
  51. package/src/agents/infrastructure/tools/index.js +52 -0
  52. package/src/agents/infrastructure/tools/tflint-run.js +31 -0
  53. package/src/agents/jules/config/definition.js +160 -160
  54. package/src/agents/jules/config/system-prompt.js +182 -182
  55. package/src/agents/jules/error-intake.js +51 -51
  56. package/src/agents/jules/fix-cycle.js +17 -17
  57. package/src/agents/jules/loop.js +460 -450
  58. package/src/agents/jules/pulse.js +10 -10
  59. package/src/agents/jules/stream.js +187 -186
  60. package/src/agents/jules/swarm/file-scanner.js +74 -74
  61. package/src/agents/jules/swarm/index.js +11 -11
  62. package/src/agents/jules/swarm/orchestrator.js +362 -362
  63. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  64. package/src/agents/jules/swarm/sub-agent.js +315 -309
  65. package/src/agents/jules/tools/aidenid-email.js +189 -189
  66. package/src/agents/jules/tools/auth-audit.js +1708 -1691
  67. package/src/agents/jules/tools/dispatch.js +340 -335
  68. package/src/agents/jules/tools/file-edit.js +2 -2
  69. package/src/agents/jules/tools/file-read.js +2 -2
  70. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  71. package/src/agents/jules/tools/glob.js +2 -2
  72. package/src/agents/jules/tools/grep.js +2 -2
  73. package/src/agents/jules/tools/index.js +29 -29
  74. package/src/agents/jules/tools/path-guards.js +2 -2
  75. package/src/agents/jules/tools/runtime-audit.js +507 -507
  76. package/src/agents/jules/tools/shell.js +2 -2
  77. package/src/agents/jules/tools/url-policy.js +100 -100
  78. package/src/agents/mode.js +113 -0
  79. package/src/agents/observability/index.js +12 -0
  80. package/src/agents/observability/tools/alert-audit.js +39 -0
  81. package/src/agents/observability/tools/base.js +181 -0
  82. package/src/agents/observability/tools/dashboard-gap.js +42 -0
  83. package/src/agents/observability/tools/index.js +54 -0
  84. package/src/agents/observability/tools/log-schema-check.js +74 -0
  85. package/src/agents/observability/tools/span-coverage.js +74 -0
  86. package/src/agents/persona-visuals.js +102 -61
  87. package/src/agents/release/index.js +12 -0
  88. package/src/agents/release/tools/base.js +181 -0
  89. package/src/agents/release/tools/changelog-diff.js +86 -0
  90. package/src/agents/release/tools/feature-flag-audit.js +126 -0
  91. package/src/agents/release/tools/index.js +61 -0
  92. package/src/agents/release/tools/rollback-verify.js +129 -0
  93. package/src/agents/release/tools/semver-check.js +109 -0
  94. package/src/agents/reliability/index.js +12 -0
  95. package/src/agents/reliability/tools/backpressure-check.js +129 -0
  96. package/src/agents/reliability/tools/base.js +181 -0
  97. package/src/agents/reliability/tools/chaos-probe.js +109 -0
  98. package/src/agents/reliability/tools/graceful-degradation-check.js +114 -0
  99. package/src/agents/reliability/tools/health-check-audit.js +111 -0
  100. package/src/agents/reliability/tools/index.js +87 -0
  101. package/src/agents/run-persona.js +109 -0
  102. package/src/agents/security/index.js +12 -0
  103. package/src/agents/security/tools/authz-audit.js +134 -0
  104. package/src/agents/security/tools/base.js +190 -0
  105. package/src/agents/security/tools/crypto-review.js +175 -0
  106. package/src/agents/security/tools/index.js +97 -0
  107. package/src/agents/security/tools/sast-scan.js +175 -0
  108. package/src/agents/security/tools/secrets-scan.js +216 -0
  109. package/src/agents/shared-tools/dispatch-core.js +320 -315
  110. package/src/agents/shared-tools/file-edit.js +180 -180
  111. package/src/agents/shared-tools/file-read.js +100 -100
  112. package/src/agents/shared-tools/glob.js +168 -168
  113. package/src/agents/shared-tools/grep.js +228 -228
  114. package/src/agents/shared-tools/index.js +46 -46
  115. package/src/agents/shared-tools/path-guards.js +161 -161
  116. package/src/agents/shared-tools/shell.js +383 -383
  117. package/src/agents/supply-chain/index.js +12 -0
  118. package/src/agents/supply-chain/tools/attestation-check.js +42 -0
  119. package/src/agents/supply-chain/tools/base.js +151 -0
  120. package/src/agents/supply-chain/tools/index.js +52 -0
  121. package/src/agents/supply-chain/tools/lockfile-integrity.js +73 -0
  122. package/src/agents/supply-chain/tools/package-verify.js +56 -0
  123. package/src/agents/supply-chain/tools/sbom-diff.js +34 -0
  124. package/src/agents/testing/index.js +12 -0
  125. package/src/agents/testing/tools/base.js +202 -0
  126. package/src/agents/testing/tools/coverage-gap.js +144 -0
  127. package/src/agents/testing/tools/flake-detect.js +125 -0
  128. package/src/agents/testing/tools/index.js +85 -0
  129. package/src/agents/testing/tools/mutation-test.js +143 -0
  130. package/src/agents/testing/tools/snapshot-diff.js +103 -0
  131. package/src/ai/aidenid.js +1021 -1009
  132. package/src/ai/client.js +553 -553
  133. package/src/ai/domain-target-store.js +268 -268
  134. package/src/ai/identity-store.js +270 -270
  135. package/src/ai/proxy.js +137 -137
  136. package/src/ai/site-store.js +145 -145
  137. package/src/audit/agents/architecture.js +180 -180
  138. package/src/audit/agents/compliance.js +179 -179
  139. package/src/audit/agents/documentation.js +165 -165
  140. package/src/audit/agents/performance.js +145 -145
  141. package/src/audit/agents/security.js +215 -215
  142. package/src/audit/agents/testing.js +172 -172
  143. package/src/audit/orchestrator.js +557 -557
  144. package/src/audit/package.js +204 -204
  145. package/src/audit/registry.js +284 -284
  146. package/src/audit/replay.js +103 -103
  147. package/src/auth/gate.js +428 -371
  148. package/src/auth/http.js +681 -611
  149. package/src/auth/service.js +1106 -1106
  150. package/src/auth/session-store.js +813 -813
  151. package/src/cli.js +257 -252
  152. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  153. package/src/commands/ai/provision-governance.js +1272 -1272
  154. package/src/commands/ai/shared.js +147 -147
  155. package/src/commands/ai.js +11 -11
  156. package/src/commands/apply.js +12 -12
  157. package/src/commands/audit.js +1171 -1166
  158. package/src/commands/auth.js +419 -419
  159. package/src/commands/chat.js +184 -191
  160. package/src/commands/config.js +184 -184
  161. package/src/commands/cost.js +311 -311
  162. package/src/commands/daemon/core.js +850 -850
  163. package/src/commands/daemon/extended.js +1048 -1048
  164. package/src/commands/daemon/shared.js +213 -213
  165. package/src/commands/daemon.js +11 -11
  166. package/src/commands/guide.js +174 -174
  167. package/src/commands/ingest.js +58 -58
  168. package/src/commands/init.js +55 -55
  169. package/src/commands/legacy-args.js +20 -10
  170. package/src/commands/mcp.js +461 -461
  171. package/src/commands/omargate.js +63 -29
  172. package/src/commands/persona.js +65 -20
  173. package/src/commands/plugin.js +260 -260
  174. package/src/commands/policy.js +132 -132
  175. package/src/commands/prompt.js +238 -238
  176. package/src/commands/review.js +704 -704
  177. package/src/commands/scan.js +865 -872
  178. package/src/commands/session.js +1238 -0
  179. package/src/commands/spec.js +771 -716
  180. package/src/commands/swarm.js +651 -651
  181. package/src/commands/telemetry.js +202 -202
  182. package/src/commands/watch.js +511 -511
  183. package/src/config/agent-dictionary.js +182 -182
  184. package/src/config/io.js +56 -56
  185. package/src/config/paths.js +18 -18
  186. package/src/config/schema.js +55 -55
  187. package/src/config/service.js +184 -184
  188. package/src/coord/events-log.js +141 -0
  189. package/src/coord/handshake.js +719 -0
  190. package/src/coord/index.js +35 -0
  191. package/src/coord/paths.js +84 -0
  192. package/src/coord/priority.js +62 -0
  193. package/src/coord/tarjan.js +157 -0
  194. package/src/cost/budget.js +235 -235
  195. package/src/cost/history.js +188 -188
  196. package/src/cost/tokenizer.js +160 -0
  197. package/src/cost/tracker.js +232 -171
  198. package/src/daemon/artifact-lineage.js +896 -534
  199. package/src/daemon/assignment-ledger.js +1083 -770
  200. package/src/daemon/ast-drift.js +496 -0
  201. package/src/daemon/ast-parser-layer.js +258 -258
  202. package/src/daemon/budget-governor.js +633 -633
  203. package/src/daemon/callgraph-overlay.js +646 -646
  204. package/src/daemon/error-worker.js +1209 -626
  205. package/src/daemon/fix-cycle.js +384 -377
  206. package/src/daemon/hybrid-mapper.js +929 -929
  207. package/src/daemon/ingest-refresh.js +79 -11
  208. package/src/daemon/jira-lifecycle.js +767 -632
  209. package/src/daemon/operator-control.js +657 -657
  210. package/src/daemon/pulse.js +327 -327
  211. package/src/daemon/reliability-lane.js +471 -471
  212. package/src/daemon/scope-engine.js +1068 -0
  213. package/src/daemon/watchdog.js +971 -971
  214. package/src/events/schema.js +190 -0
  215. package/src/guide/generator.js +316 -316
  216. package/src/ingest/engine.js +933 -918
  217. package/src/ingest/ownership.js +380 -0
  218. package/src/interactive/index.js +97 -97
  219. package/src/legacy-cli.js +3228 -2994
  220. package/src/mcp/registry.js +695 -695
  221. package/src/memory/blackboard.js +301 -301
  222. package/src/memory/retrieval.js +581 -581
  223. package/src/orchestrator/kai-chen.js +126 -0
  224. package/src/plugin/manifest.js +553 -553
  225. package/src/policy/packs.js +144 -144
  226. package/src/prompt/generator.js +136 -118
  227. package/src/review/ai-review.js +672 -679
  228. package/src/review/compliance-pack.js +389 -0
  229. package/src/review/investor-dd-config.js +54 -0
  230. package/src/review/investor-dd-file-loop.js +303 -0
  231. package/src/review/investor-dd-file-router.js +406 -0
  232. package/src/review/investor-dd-html-report.js +233 -0
  233. package/src/review/investor-dd-notification.js +120 -0
  234. package/src/review/investor-dd-orchestrator.js +405 -0
  235. package/src/review/investor-dd-persona-runner.js +275 -0
  236. package/src/review/live-validator.js +253 -0
  237. package/src/review/local-review.js +1351 -1305
  238. package/src/review/omargate-interactive.js +68 -68
  239. package/src/review/omargate-orchestrator.js +492 -300
  240. package/src/review/persona-prompts.js +484 -296
  241. package/src/review/reconciliation-rules.js +329 -0
  242. package/src/review/replay.js +235 -235
  243. package/src/review/report.js +664 -664
  244. package/src/review/reproducibility-chain.js +136 -0
  245. package/src/review/scan-modes.js +147 -42
  246. package/src/review/spec-binding.js +487 -487
  247. package/src/scaffold/generator.js +67 -67
  248. package/src/scaffold/templates.js +150 -150
  249. package/src/scan/generator.js +418 -418
  250. package/src/scan/gh-secrets.js +107 -107
  251. package/src/session/agent-registry.js +359 -0
  252. package/src/session/analytics.js +479 -0
  253. package/src/session/daemon.js +1396 -0
  254. package/src/session/file-locks.js +666 -0
  255. package/src/session/paths.js +37 -0
  256. package/src/session/recap.js +567 -0
  257. package/src/session/redact.js +82 -0
  258. package/src/session/runtime-bridge.js +762 -0
  259. package/src/session/scoring.js +406 -0
  260. package/src/session/setup-guides.js +304 -0
  261. package/src/session/store.js +704 -0
  262. package/src/session/stream.js +333 -0
  263. package/src/session/sync.js +753 -0
  264. package/src/session/tasks.js +1054 -0
  265. package/src/session/templates.js +188 -0
  266. package/src/spec/generator.js +619 -519
  267. package/src/spec/regenerate.js +237 -237
  268. package/src/spec/templates.js +91 -91
  269. package/src/swarm/dashboard.js +247 -247
  270. package/src/swarm/factory.js +363 -363
  271. package/src/swarm/pentest.js +934 -934
  272. package/src/swarm/registry.js +419 -419
  273. package/src/swarm/report.js +158 -158
  274. package/src/swarm/runtime.js +569 -576
  275. package/src/swarm/scenario-dsl.js +272 -272
  276. package/src/telemetry/ledger.js +302 -302
  277. package/src/telemetry/session-tracker.js +234 -234
  278. package/src/telemetry/sync.js +203 -203
  279. package/src/ui/command-hints.js +13 -13
  280. package/src/ui/markdown.js +220 -220
@@ -0,0 +1,144 @@
1
+ // timeout-audit — flag outbound calls without explicit timeout (#A14).
2
+ //
3
+ // Default timeouts in every major HTTP client are too long:
4
+ // - Node fetch: no timeout by default — a hung downstream ties up a
5
+ // handler indefinitely
6
+ // - axios: no timeout by default
7
+ // - requests: no connect/read timeout by default
8
+ // - urllib: no timeout
9
+ // We flag outbound calls that don't carry an explicit `timeout` / `signal` /
10
+ // AbortSignal within the call arguments.
11
+
12
+ import fsp from "node:fs/promises";
13
+ import path from "node:path";
14
+
15
+ import { createFinding, findLineMatches, getLineContent, toPosix, walkRepoFiles } from "./base.js";
16
+
17
+ const JS_TS_EXTENSIONS = new Set([
18
+ ".js",
19
+ ".jsx",
20
+ ".ts",
21
+ ".tsx",
22
+ ".mjs",
23
+ ".cjs",
24
+ ]);
25
+ const PY_EXTENSIONS = new Set([".py"]);
26
+
27
+ function extractCallArgs(content, callIndex) {
28
+ // Very small bracket matcher — pulls the argument substring between the
29
+ // `(` following `callIndex` and the matching `)` (tracking nested
30
+ // parens / template literals at a simple level).
31
+ let depth = 0;
32
+ let inString = null;
33
+ let start = -1;
34
+ for (let i = callIndex; i < content.length; i += 1) {
35
+ const ch = content[i];
36
+ if (inString) {
37
+ if (ch === "\\") {
38
+ i += 1;
39
+ continue;
40
+ }
41
+ if (ch === inString) {
42
+ inString = null;
43
+ }
44
+ continue;
45
+ }
46
+ if (ch === "'" || ch === '"' || ch === "`") {
47
+ inString = ch;
48
+ continue;
49
+ }
50
+ if (ch === "(") {
51
+ depth += 1;
52
+ if (depth === 1) {
53
+ start = i + 1;
54
+ }
55
+ } else if (ch === ")") {
56
+ depth -= 1;
57
+ if (depth === 0) {
58
+ return content.slice(start, i);
59
+ }
60
+ }
61
+ }
62
+ return "";
63
+ }
64
+
65
+ function hasTimeoutInArgs(argString) {
66
+ return /timeout\s*[:=]\s*[^,)}\]]+|signal\s*:\s*[^,)}\]]+|AbortSignal\.timeout\s*\(/i.test(
67
+ argString || ""
68
+ );
69
+ }
70
+
71
+ const JS_CALLS = [
72
+ { pattern: /\bfetch\s*\(/, label: "fetch" },
73
+ { pattern: /\baxios(?:\.[a-z]+)?\s*\(/, label: "axios" },
74
+ { pattern: /\bgot(?:\.[a-z]+)?\s*\(/, label: "got" },
75
+ { pattern: /\bhttp\.(?:request|get|post)\s*\(/, label: "http" },
76
+ { pattern: /\bhttps\.(?:request|get|post)\s*\(/, label: "https" },
77
+ ];
78
+
79
+ const PY_CALLS = [
80
+ { pattern: /\brequests\.(?:get|post|put|patch|delete|request)\s*\(/, label: "requests" },
81
+ { pattern: /\burllib\.request\.urlopen\s*\(/, label: "urllib" },
82
+ { pattern: /\bhttpx\.(?:get|post|put|patch|delete|request)\s*\(/, label: "httpx" },
83
+ ];
84
+
85
+ export async function runTimeoutAudit({ rootPath, files = null } = {}) {
86
+ const resolvedRoot = path.resolve(String(rootPath || "."));
87
+ const extensions = new Set([...JS_TS_EXTENSIONS, ...PY_EXTENSIONS]);
88
+ const iterator =
89
+ Array.isArray(files) && files.length > 0
90
+ ? iterateExplicitFiles(resolvedRoot, files)
91
+ : walkRepoFiles({ rootPath: resolvedRoot, extensions });
92
+
93
+ const findings = [];
94
+ for await (const { fullPath, relativePath } of iterator) {
95
+ let content;
96
+ try {
97
+ content = await fsp.readFile(fullPath, "utf-8");
98
+ } catch {
99
+ continue;
100
+ }
101
+ const ext = path.extname(fullPath).toLowerCase();
102
+ const calls = PY_EXTENSIONS.has(ext) ? PY_CALLS : JS_CALLS;
103
+
104
+ for (const call of calls) {
105
+ for (const match of findLineMatches(content, call.pattern)) {
106
+ const argString = extractCallArgs(content, match.index);
107
+ if (hasTimeoutInArgs(argString)) {
108
+ continue;
109
+ }
110
+ findings.push(
111
+ createFinding({
112
+ tool: "timeout-audit",
113
+ kind: "backend.no-timeout",
114
+ severity: "P1",
115
+ file: toPosix(relativePath),
116
+ line: match.line,
117
+ evidence: getLineContent(content, match.line),
118
+ rootCause: `${call.label} call has no explicit timeout — a slow downstream can stall the handler indefinitely.`,
119
+ recommendedFix:
120
+ "Always pass an explicit timeout: AbortSignal.timeout(ms) for fetch, { timeout } for axios / got / requests / httpx. Pick a value that's shorter than your request SLO.",
121
+ confidence: 0.7,
122
+ })
123
+ );
124
+ }
125
+ }
126
+ }
127
+ return findings;
128
+ }
129
+
130
+ async function* iterateExplicitFiles(resolvedRoot, files) {
131
+ for (const file of files) {
132
+ const trimmed = String(file || "").trim();
133
+ if (!trimmed) {
134
+ continue;
135
+ }
136
+ const fullPath = path.isAbsolute(trimmed)
137
+ ? trimmed
138
+ : path.join(resolvedRoot, trimmed);
139
+ const relativePath = path
140
+ .relative(resolvedRoot, fullPath)
141
+ .replace(/\\/g, "/");
142
+ yield { fullPath, relativePath };
143
+ }
144
+ }
@@ -0,0 +1,12 @@
1
+ // Ethan (code-quality persona) — barrel export (#A16).
2
+
3
+ export {
4
+ CODE_QUALITY_TOOLS,
5
+ CODE_QUALITY_TOOL_IDS,
6
+ dispatchCodeQualityTool,
7
+ runAllCodeQualityTools,
8
+ runComplexityMeasure,
9
+ runCouplingAnalysis,
10
+ runCycleDetect,
11
+ runDepGraph,
12
+ } from "./tools/index.js";
@@ -0,0 +1,159 @@
1
+ // Shared helpers for Ethan's (code-quality) domain tools (#A16).
2
+ // Same per-persona base pattern as security / backend / testing.
3
+
4
+ import fsp from "node:fs/promises";
5
+ import path from "node:path";
6
+ import process from "node:process";
7
+
8
+ import ignore from "ignore";
9
+
10
+ const DEFAULT_IGNORED_DIRS = new Set([
11
+ ".git",
12
+ "node_modules",
13
+ ".venv",
14
+ ".next",
15
+ "dist",
16
+ "build",
17
+ "coverage",
18
+ ".sentinelayer",
19
+ ".sentinel",
20
+ ".turbo",
21
+ ".idea",
22
+ ".vscode",
23
+ "__pycache__",
24
+ ".cache",
25
+ ]);
26
+ const MAX_FILE_SIZE_BYTES = 1024 * 1024;
27
+ const SEVERITIES = Object.freeze(["P0", "P1", "P2", "P3"]);
28
+
29
+ export function toPosix(value) {
30
+ return String(value || "").replace(/\\/g, "/");
31
+ }
32
+
33
+ export function normalizeSeverity(value) {
34
+ const normalized = String(value || "").trim().toUpperCase();
35
+ if (SEVERITIES.includes(normalized)) {
36
+ return normalized;
37
+ }
38
+ return "P2";
39
+ }
40
+
41
+ export function createFinding({
42
+ severity,
43
+ kind,
44
+ file,
45
+ line = 0,
46
+ evidence = "",
47
+ rootCause = "",
48
+ recommendedFix = "",
49
+ confidence = null,
50
+ tool = "",
51
+ persona = "code-quality",
52
+ } = {}) {
53
+ return {
54
+ persona,
55
+ tool: String(tool || "").trim(),
56
+ kind: String(kind || "").trim() || "code-quality",
57
+ severity: normalizeSeverity(severity),
58
+ file: toPosix(file || ""),
59
+ line: Number.isFinite(Number(line)) ? Math.max(0, Math.floor(Number(line))) : 0,
60
+ evidence: String(evidence || "").trim().slice(0, 400),
61
+ rootCause: String(rootCause || "").trim(),
62
+ recommendedFix: String(recommendedFix || "").trim(),
63
+ confidence:
64
+ confidence === null || confidence === undefined
65
+ ? null
66
+ : Math.max(0, Math.min(1, Number(confidence) || 0)),
67
+ };
68
+ }
69
+
70
+ async function readIgnorePatterns(filePath) {
71
+ try {
72
+ const raw = await fsp.readFile(filePath, "utf-8");
73
+ return String(raw || "")
74
+ .split(/\r?\n/)
75
+ .map((line) => line.trim())
76
+ .filter((line) => line && !line.startsWith("#"));
77
+ } catch (err) {
78
+ if (err && typeof err === "object" && err.code === "ENOENT") {
79
+ return [];
80
+ }
81
+ throw err;
82
+ }
83
+ }
84
+
85
+ async function createIgnoreMatcher(rootPath) {
86
+ const matcher = ignore();
87
+ const gitignore = await readIgnorePatterns(path.join(rootPath, ".gitignore"));
88
+ const sentinel = await readIgnorePatterns(
89
+ path.join(rootPath, ".sentinelayerignore")
90
+ );
91
+ matcher.add([...gitignore, ...sentinel]);
92
+ return (relativePath, isDirectory) => {
93
+ const normalized = toPosix(relativePath);
94
+ if (!normalized) {
95
+ return false;
96
+ }
97
+ const candidate = isDirectory ? `${normalized}/` : normalized;
98
+ return matcher.ignores(candidate);
99
+ };
100
+ }
101
+
102
+ export async function* walkRepoFiles({
103
+ rootPath = process.cwd(),
104
+ extensions = new Set(),
105
+ maxFileSize = MAX_FILE_SIZE_BYTES,
106
+ } = {}) {
107
+ const resolvedRoot = path.resolve(rootPath);
108
+ const ignoreMatcher = await createIgnoreMatcher(resolvedRoot);
109
+ const wantedExtensions =
110
+ extensions instanceof Set
111
+ ? extensions
112
+ : new Set(Array.isArray(extensions) ? extensions : []);
113
+ const stack = [resolvedRoot];
114
+ while (stack.length > 0) {
115
+ const current = stack.pop();
116
+ let entries = [];
117
+ try {
118
+ entries = await fsp.readdir(current, { withFileTypes: true });
119
+ } catch {
120
+ continue;
121
+ }
122
+ for (const entry of entries) {
123
+ const fullPath = path.join(current, entry.name);
124
+ const relativePath = toPosix(path.relative(resolvedRoot, fullPath));
125
+ if (entry.isDirectory()) {
126
+ if (!relativePath || DEFAULT_IGNORED_DIRS.has(entry.name)) {
127
+ continue;
128
+ }
129
+ if (ignoreMatcher(relativePath, true)) {
130
+ continue;
131
+ }
132
+ stack.push(fullPath);
133
+ continue;
134
+ }
135
+ if (!entry.isFile()) {
136
+ continue;
137
+ }
138
+ if (ignoreMatcher(relativePath, false)) {
139
+ continue;
140
+ }
141
+ const ext = path.extname(entry.name).toLowerCase();
142
+ if (wantedExtensions.size > 0 && !wantedExtensions.has(ext) && !wantedExtensions.has("")) {
143
+ continue;
144
+ }
145
+ let stat = null;
146
+ try {
147
+ stat = await fsp.stat(fullPath);
148
+ } catch {
149
+ stat = null;
150
+ }
151
+ if (!stat || stat.size > maxFileSize) {
152
+ continue;
153
+ }
154
+ yield { fullPath, relativePath };
155
+ }
156
+ }
157
+ }
158
+
159
+ export { DEFAULT_IGNORED_DIRS, MAX_FILE_SIZE_BYTES, SEVERITIES };
@@ -0,0 +1,197 @@
1
+ // complexity-measure — simple cyclomatic complexity estimate per function (#A16).
2
+ //
3
+ // We don't try to be ESLint-strict — we estimate cyclomatic complexity by
4
+ // counting branching keywords within each function body. It's an
5
+ // approximation (it doesn't handle labeled break / conditional short-circuit
6
+ // perfectly) but it's enough to surface the worst offenders.
7
+ //
8
+ // Threshold defaults: P1 at CC >= 30, P2 at CC >= 15. Tune via options.
9
+
10
+ import fsp from "node:fs/promises";
11
+ import path from "node:path";
12
+
13
+ import { parse } from "@babel/parser";
14
+
15
+ import { createFinding, toPosix, walkRepoFiles } from "./base.js";
16
+
17
+ const DEFAULT_EXTENSIONS = new Set([
18
+ ".js",
19
+ ".jsx",
20
+ ".ts",
21
+ ".tsx",
22
+ ".mjs",
23
+ ".cjs",
24
+ ]);
25
+
26
+ const BRANCHING_NODE_TYPES = new Set([
27
+ "IfStatement",
28
+ "ForStatement",
29
+ "ForInStatement",
30
+ "ForOfStatement",
31
+ "WhileStatement",
32
+ "DoWhileStatement",
33
+ "SwitchCase",
34
+ "CatchClause",
35
+ "ConditionalExpression",
36
+ "LogicalExpression", // &&, ||, ??
37
+ ]);
38
+
39
+ function pickPlugins(filePath) {
40
+ const ext = path.extname(filePath).toLowerCase();
41
+ const plugins = ["importAttributes", "dynamicImport"];
42
+ if (ext === ".ts" || ext === ".tsx" || ext === ".mts" || ext === ".cts") {
43
+ plugins.push("typescript");
44
+ }
45
+ if (ext === ".jsx" || ext === ".tsx") {
46
+ plugins.push("jsx");
47
+ }
48
+ return plugins;
49
+ }
50
+
51
+ function estimateComplexity(bodyNode) {
52
+ if (!bodyNode || typeof bodyNode !== "object") {
53
+ return 1;
54
+ }
55
+ let count = 1; // Minimum CC = 1 (straight-line function)
56
+ const queue = [bodyNode];
57
+ while (queue.length > 0) {
58
+ const node = queue.shift();
59
+ if (!node || typeof node !== "object") {
60
+ continue;
61
+ }
62
+ if (BRANCHING_NODE_TYPES.has(node.type)) {
63
+ count += 1;
64
+ }
65
+ for (const value of Object.values(node)) {
66
+ if (value && typeof value === "object") {
67
+ if (Array.isArray(value)) {
68
+ queue.push(...value);
69
+ } else {
70
+ queue.push(value);
71
+ }
72
+ }
73
+ }
74
+ }
75
+ return count;
76
+ }
77
+
78
+ function functionName(node) {
79
+ if (!node) {
80
+ return "<anonymous>";
81
+ }
82
+ if (node.id?.name) {
83
+ return node.id.name;
84
+ }
85
+ return "<anonymous>";
86
+ }
87
+
88
+ function collectFunctions(astRoot, filePath) {
89
+ const results = [];
90
+ const queue = [astRoot];
91
+ while (queue.length > 0) {
92
+ const node = queue.shift();
93
+ if (!node || typeof node !== "object") {
94
+ continue;
95
+ }
96
+ if (Array.isArray(node)) {
97
+ for (const v of node) {
98
+ queue.push(v);
99
+ }
100
+ continue;
101
+ }
102
+ if (
103
+ node.type === "FunctionDeclaration" ||
104
+ node.type === "FunctionExpression" ||
105
+ node.type === "ArrowFunctionExpression" ||
106
+ node.type === "ClassMethod" ||
107
+ node.type === "ObjectMethod"
108
+ ) {
109
+ results.push({
110
+ name: functionName(node),
111
+ line: node.loc?.start?.line ?? 0,
112
+ complexity: estimateComplexity(node.body),
113
+ file: filePath,
114
+ });
115
+ }
116
+ for (const value of Object.values(node)) {
117
+ if (value && typeof value === "object") {
118
+ queue.push(value);
119
+ }
120
+ }
121
+ }
122
+ return results;
123
+ }
124
+
125
+ export async function runComplexityMeasure({
126
+ rootPath,
127
+ files = null,
128
+ p1Threshold = 30,
129
+ p2Threshold = 15,
130
+ } = {}) {
131
+ const resolvedRoot = path.resolve(String(rootPath || "."));
132
+ const iterator =
133
+ Array.isArray(files) && files.length > 0
134
+ ? iterateExplicitFiles(resolvedRoot, files)
135
+ : walkRepoFiles({ rootPath: resolvedRoot, extensions: DEFAULT_EXTENSIONS });
136
+
137
+ const findings = [];
138
+ for await (const { fullPath, relativePath } of iterator) {
139
+ let content;
140
+ try {
141
+ content = await fsp.readFile(fullPath, "utf-8");
142
+ } catch {
143
+ continue;
144
+ }
145
+ let ast;
146
+ try {
147
+ ast = parse(content, {
148
+ sourceType: "unambiguous",
149
+ errorRecovery: true,
150
+ plugins: pickPlugins(fullPath),
151
+ });
152
+ } catch {
153
+ continue;
154
+ }
155
+ const functions = collectFunctions(ast, toPosix(relativePath));
156
+ for (const fn of functions) {
157
+ if (fn.complexity < p2Threshold) {
158
+ continue;
159
+ }
160
+ const severity = fn.complexity >= p1Threshold ? "P1" : "P2";
161
+ findings.push(
162
+ createFinding({
163
+ tool: "complexity-measure",
164
+ kind: "code-quality.high-complexity",
165
+ severity,
166
+ file: fn.file,
167
+ line: fn.line,
168
+ evidence: `function '${fn.name}' has estimated CC=${fn.complexity}`,
169
+ rootCause:
170
+ "High cyclomatic complexity means many independent paths through the function — hard to test exhaustively and easy to break on edits.",
171
+ recommendedFix:
172
+ "Split on the dominant branch axis (early-return guards, extract-method on nested conditionals, or convert a long switch into a dispatch table).",
173
+ confidence: 0.7,
174
+ })
175
+ );
176
+ }
177
+ }
178
+ return findings;
179
+ }
180
+
181
+ async function* iterateExplicitFiles(resolvedRoot, files) {
182
+ for (const file of files) {
183
+ const trimmed = String(file || "").trim();
184
+ if (!trimmed) {
185
+ continue;
186
+ }
187
+ const fullPath = path.isAbsolute(trimmed)
188
+ ? trimmed
189
+ : path.join(resolvedRoot, trimmed);
190
+ const relativePath = path
191
+ .relative(resolvedRoot, fullPath)
192
+ .replace(/\\/g, "/");
193
+ yield { fullPath, relativePath };
194
+ }
195
+ }
196
+
197
+ export { BRANCHING_NODE_TYPES, estimateComplexity };
@@ -0,0 +1,81 @@
1
+ // coupling-analysis — flag high fan-out / fan-in modules (#A16).
2
+ //
3
+ // Fan-out: how many distinct modules does THIS file import? Very high
4
+ // fan-out suggests an anti-pattern — the file knows too much about the
5
+ // rest of the system.
6
+ //
7
+ // Fan-in: how many modules import THIS file? Very high fan-in marks a
8
+ // "god module" that many sites depend on; risk is concentrated here.
9
+
10
+ import path from "node:path";
11
+
12
+ import { createFinding } from "./base.js";
13
+ import { buildDependencyGraph } from "./dep-graph.js";
14
+
15
+ const FAN_OUT_THRESHOLD = 20;
16
+ const FAN_IN_THRESHOLD = 15;
17
+
18
+ export async function runCouplingAnalysis({ rootPath, files = null, graph = null } = {}) {
19
+ const resolvedRoot = path.resolve(String(rootPath || "."));
20
+ const dependencyGraph =
21
+ graph && typeof graph === "object"
22
+ ? graph
23
+ : await buildDependencyGraph({ rootPath: resolvedRoot, files });
24
+
25
+ const fanOut = {};
26
+ const fanIn = {};
27
+ for (const [file, edges] of Object.entries(dependencyGraph)) {
28
+ fanOut[file] = edges.length;
29
+ for (const edge of edges) {
30
+ if (edge.startsWith("npm:") || edge.startsWith("/")) {
31
+ continue;
32
+ }
33
+ fanIn[edge] = (fanIn[edge] || 0) + 1;
34
+ }
35
+ }
36
+
37
+ const findings = [];
38
+ for (const [file, count] of Object.entries(fanOut)) {
39
+ if (count < FAN_OUT_THRESHOLD) {
40
+ continue;
41
+ }
42
+ findings.push(
43
+ createFinding({
44
+ tool: "coupling-analysis",
45
+ kind: "code-quality.high-fan-out",
46
+ severity: count >= FAN_OUT_THRESHOLD * 2 ? "P1" : "P2",
47
+ file,
48
+ line: 0,
49
+ evidence: `fan-out = ${count} (threshold ${FAN_OUT_THRESHOLD})`,
50
+ rootCause:
51
+ "High fan-out: this module imports from many other modules, which is a sign it's doing too much and is brittle to downstream changes.",
52
+ recommendedFix:
53
+ "Split by responsibility. A Facade / Mediator can reduce the breadth of imports if the file is legitimately a coordinator.",
54
+ confidence: 0.7,
55
+ })
56
+ );
57
+ }
58
+ for (const [file, count] of Object.entries(fanIn)) {
59
+ if (count < FAN_IN_THRESHOLD) {
60
+ continue;
61
+ }
62
+ findings.push(
63
+ createFinding({
64
+ tool: "coupling-analysis",
65
+ kind: "code-quality.high-fan-in",
66
+ severity: count >= FAN_IN_THRESHOLD * 2 ? "P1" : "P2",
67
+ file,
68
+ line: 0,
69
+ evidence: `fan-in = ${count} (threshold ${FAN_IN_THRESHOLD})`,
70
+ rootCause:
71
+ "High fan-in: many modules depend on this file, so any behavior change risks a broad blast radius.",
72
+ recommendedFix:
73
+ "Stabilize the surface (consider making this module an interface / contract) and move implementation details behind it.",
74
+ confidence: 0.65,
75
+ })
76
+ );
77
+ }
78
+ return findings;
79
+ }
80
+
81
+ export { FAN_IN_THRESHOLD, FAN_OUT_THRESHOLD };
@@ -0,0 +1,49 @@
1
+ // cycle-detect — find import cycles in the module graph (#A16).
2
+ //
3
+ // Reuses findCycles() from src/coord/tarjan.js so we don't ship a second
4
+ // SCC implementation. Returns one Finding per cycle so the orchestrator
5
+ // can rank and prioritize; the cycle's component list is embedded in the
6
+ // finding's evidence + rootCause for review.
7
+
8
+ import path from "node:path";
9
+
10
+ import { findCycles } from "../../../coord/tarjan.js";
11
+
12
+ import { createFinding } from "./base.js";
13
+ import { buildDependencyGraph } from "./dep-graph.js";
14
+
15
+ export async function runCycleDetect({ rootPath, files = null, graph = null } = {}) {
16
+ const resolvedRoot = path.resolve(String(rootPath || "."));
17
+ const dependencyGraph =
18
+ graph && typeof graph === "object"
19
+ ? graph
20
+ : await buildDependencyGraph({ rootPath: resolvedRoot, files });
21
+
22
+ // Strip npm:* nodes from the graph — they're sinks, not cycle participants.
23
+ const localGraph = {};
24
+ for (const [file, edges] of Object.entries(dependencyGraph)) {
25
+ localGraph[file] = edges.filter((edge) => !edge.startsWith("npm:") && !edge.startsWith("/"));
26
+ }
27
+
28
+ const cycles = findCycles(localGraph);
29
+ const findings = [];
30
+ for (const cycle of cycles) {
31
+ const primary = cycle.slice().sort()[0];
32
+ findings.push(
33
+ createFinding({
34
+ tool: "cycle-detect",
35
+ kind: "code-quality.import-cycle",
36
+ severity: cycle.length > 3 ? "P1" : "P2",
37
+ file: primary,
38
+ line: 0,
39
+ evidence: `Cycle of ${cycle.length} modules: ${cycle.join(" → ")}`,
40
+ rootCause:
41
+ "Import cycle forces the module loader to resolve modules out of order — causes TDZ errors, half-initialized exports, and refactor-proof coupling.",
42
+ recommendedFix:
43
+ "Break the cycle by extracting shared types / interfaces into a new module that both sides can depend on, or move the behavior that creates the back-edge into a callback injected at call time.",
44
+ confidence: 0.85,
45
+ })
46
+ );
47
+ }
48
+ return findings;
49
+ }