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,189 @@
1
+ // Shared helpers for Maya's (backend) domain tools (#A14).
2
+ // Mirrors src/agents/security/tools/base.js but with persona defaulting to
3
+ // "backend". Intentional per-persona copy — a later refactor (#A25+) can
4
+ // hoist this to src/agents/shared-tools/ once the 12 persona modules are
5
+ // shipped and the common surface is stable.
6
+
7
+ import fsp from "node:fs/promises";
8
+ import path from "node:path";
9
+ import process from "node:process";
10
+
11
+ import ignore from "ignore";
12
+
13
+ const DEFAULT_IGNORED_DIRS = new Set([
14
+ ".git",
15
+ "node_modules",
16
+ ".venv",
17
+ ".next",
18
+ "dist",
19
+ "build",
20
+ "coverage",
21
+ ".sentinelayer",
22
+ ".sentinel",
23
+ ".turbo",
24
+ ".idea",
25
+ ".vscode",
26
+ "__pycache__",
27
+ ".cache",
28
+ ]);
29
+ const MAX_FILE_SIZE_BYTES = 1024 * 1024;
30
+ const SEVERITIES = Object.freeze(["P0", "P1", "P2", "P3"]);
31
+
32
+ export function toPosix(value) {
33
+ return String(value || "").replace(/\\/g, "/");
34
+ }
35
+
36
+ export function normalizeSeverity(value) {
37
+ const normalized = String(value || "").trim().toUpperCase();
38
+ if (SEVERITIES.includes(normalized)) {
39
+ return normalized;
40
+ }
41
+ return "P2";
42
+ }
43
+
44
+ export function createFinding({
45
+ severity,
46
+ kind,
47
+ file,
48
+ line = 0,
49
+ evidence = "",
50
+ rootCause = "",
51
+ recommendedFix = "",
52
+ confidence = null,
53
+ tool = "",
54
+ persona = "backend",
55
+ } = {}) {
56
+ return {
57
+ persona,
58
+ tool: String(tool || "").trim(),
59
+ kind: String(kind || "").trim() || "backend",
60
+ severity: normalizeSeverity(severity),
61
+ file: toPosix(file || ""),
62
+ line: Number.isFinite(Number(line)) ? Math.max(0, Math.floor(Number(line))) : 0,
63
+ evidence: String(evidence || "").trim().slice(0, 400),
64
+ rootCause: String(rootCause || "").trim(),
65
+ recommendedFix: String(recommendedFix || "").trim(),
66
+ confidence:
67
+ confidence === null || confidence === undefined
68
+ ? null
69
+ : Math.max(0, Math.min(1, Number(confidence) || 0)),
70
+ };
71
+ }
72
+
73
+ async function readIgnorePatterns(filePath) {
74
+ try {
75
+ const raw = await fsp.readFile(filePath, "utf-8");
76
+ return String(raw || "")
77
+ .split(/\r?\n/)
78
+ .map((line) => line.trim())
79
+ .filter((line) => line && !line.startsWith("#"));
80
+ } catch (err) {
81
+ if (err && typeof err === "object" && err.code === "ENOENT") {
82
+ return [];
83
+ }
84
+ throw err;
85
+ }
86
+ }
87
+
88
+ async function createIgnoreMatcher(rootPath) {
89
+ const matcher = ignore();
90
+ const gitignore = await readIgnorePatterns(path.join(rootPath, ".gitignore"));
91
+ const sentinel = await readIgnorePatterns(
92
+ path.join(rootPath, ".sentinelayerignore")
93
+ );
94
+ matcher.add([...gitignore, ...sentinel]);
95
+ return (relativePath, isDirectory) => {
96
+ const normalized = toPosix(relativePath);
97
+ if (!normalized) {
98
+ return false;
99
+ }
100
+ const candidate = isDirectory ? `${normalized}/` : normalized;
101
+ return matcher.ignores(candidate);
102
+ };
103
+ }
104
+
105
+ export async function* walkRepoFiles({
106
+ rootPath = process.cwd(),
107
+ extensions = new Set(),
108
+ maxFileSize = MAX_FILE_SIZE_BYTES,
109
+ } = {}) {
110
+ const resolvedRoot = path.resolve(rootPath);
111
+ const ignoreMatcher = await createIgnoreMatcher(resolvedRoot);
112
+ const wantedExtensions =
113
+ extensions instanceof Set
114
+ ? extensions
115
+ : new Set(Array.isArray(extensions) ? extensions : []);
116
+ const stack = [resolvedRoot];
117
+ while (stack.length > 0) {
118
+ const current = stack.pop();
119
+ let entries = [];
120
+ try {
121
+ entries = await fsp.readdir(current, { withFileTypes: true });
122
+ } catch {
123
+ continue;
124
+ }
125
+ for (const entry of entries) {
126
+ const fullPath = path.join(current, entry.name);
127
+ const relativePath = toPosix(path.relative(resolvedRoot, fullPath));
128
+ if (entry.isDirectory()) {
129
+ if (!relativePath || DEFAULT_IGNORED_DIRS.has(entry.name)) {
130
+ continue;
131
+ }
132
+ if (ignoreMatcher(relativePath, true)) {
133
+ continue;
134
+ }
135
+ stack.push(fullPath);
136
+ continue;
137
+ }
138
+ if (!entry.isFile()) {
139
+ continue;
140
+ }
141
+ if (ignoreMatcher(relativePath, false)) {
142
+ continue;
143
+ }
144
+ const ext = path.extname(entry.name).toLowerCase();
145
+ if (wantedExtensions.size > 0 && !wantedExtensions.has(ext) && !wantedExtensions.has("")) {
146
+ continue;
147
+ }
148
+ let stat = null;
149
+ try {
150
+ stat = await fsp.stat(fullPath);
151
+ } catch {
152
+ stat = null;
153
+ }
154
+ if (!stat || stat.size > maxFileSize) {
155
+ continue;
156
+ }
157
+ yield { fullPath, relativePath };
158
+ }
159
+ }
160
+ }
161
+
162
+ export function findLineMatches(content, pattern) {
163
+ const text = String(content || "");
164
+ if (!pattern) {
165
+ return [];
166
+ }
167
+ const global = new RegExp(
168
+ pattern.source,
169
+ pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`
170
+ );
171
+ const matches = [];
172
+ let match;
173
+ while ((match = global.exec(text)) !== null) {
174
+ const lineIndex = text.slice(0, match.index).split(/\r?\n/).length;
175
+ matches.push({
176
+ index: match.index,
177
+ line: lineIndex,
178
+ match: match[0],
179
+ });
180
+ }
181
+ return matches;
182
+ }
183
+
184
+ export function getLineContent(content, line) {
185
+ const lines = String(content || "").split(/\r?\n/);
186
+ return (lines[Math.max(0, (Number(line) || 1) - 1)] || "").trim();
187
+ }
188
+
189
+ export { DEFAULT_IGNORED_DIRS, MAX_FILE_SIZE_BYTES, SEVERITIES };
@@ -0,0 +1,123 @@
1
+ // circuit-breaker-check — flag outbound calls lacking a circuit breaker (#A14).
2
+ //
3
+ // A "circuit breaker" in backend-runtime reviews is any guard that bounds
4
+ // failure propagation — opossum, cockatiel, Polly (in .NET interop),
5
+ // resilience4j, hystrix-style patterns, or hand-rolled "open/half-open"
6
+ // state machines. The heuristic: look for outbound primitive calls (fetch,
7
+ // axios, got, http.request, node-fetch, requests, urllib, aiohttp) and
8
+ // verify there's a breaker mention in the same file or a common wrapper
9
+ // file. Absence → P1 finding for human review.
10
+ //
11
+ // We stay conservative: one finding per file per outbound surface (not per
12
+ // call site) so a file with 40 fetches doesn't produce 40 identical
13
+ // findings.
14
+
15
+ import fsp from "node:fs/promises";
16
+ import path from "node:path";
17
+
18
+ import { createFinding, toPosix, walkRepoFiles } from "./base.js";
19
+
20
+ const JS_TS_EXTENSIONS = new Set([
21
+ ".js",
22
+ ".jsx",
23
+ ".ts",
24
+ ".tsx",
25
+ ".mjs",
26
+ ".cjs",
27
+ ]);
28
+ const PY_EXTENSIONS = new Set([".py"]);
29
+ const CODE_EXTENSIONS = new Set([...JS_TS_EXTENSIONS, ...PY_EXTENSIONS]);
30
+
31
+ const OUTBOUND_PATTERNS_JS = [
32
+ /\bfetch\s*\(/,
33
+ /\baxios(?:\.[a-z]+)?\s*\(/,
34
+ /\bgot(?:\.[a-z]+)?\s*\(/,
35
+ /\bhttp\.(?:request|get|post)\s*\(/,
36
+ /\bhttps\.(?:request|get|post)\s*\(/,
37
+ /\bsuperagent(?:\.[a-z]+)?\s*\(/,
38
+ ];
39
+
40
+ const OUTBOUND_PATTERNS_PY = [
41
+ /\brequests\.(?:get|post|put|patch|delete|request)\s*\(/,
42
+ /\burllib\.request\.urlopen\s*\(/,
43
+ /\baiohttp\.ClientSession\s*\(/,
44
+ /\bhttpx\.(?:get|post|put|patch|delete|request)\s*\(/,
45
+ ];
46
+
47
+ const BREAKER_SIGNALS = [
48
+ /circuitBreaker|circuit_breaker|CircuitBreaker/,
49
+ /opossum|cockatiel|resilience4j|hystrix|Polly/i,
50
+ /\bbreaker\.(?:fire|exec|execute)\s*\(/,
51
+ ];
52
+
53
+ export async function runCircuitBreakerCheck({ rootPath, files = null } = {}) {
54
+ const resolvedRoot = path.resolve(String(rootPath || "."));
55
+ const iterator =
56
+ Array.isArray(files) && files.length > 0
57
+ ? iterateExplicitFiles(resolvedRoot, files)
58
+ : walkRepoFiles({ rootPath: resolvedRoot, extensions: CODE_EXTENSIONS });
59
+
60
+ const findings = [];
61
+ for await (const { fullPath, relativePath } of iterator) {
62
+ let content;
63
+ try {
64
+ content = await fsp.readFile(fullPath, "utf-8");
65
+ } catch {
66
+ continue;
67
+ }
68
+ const ext = path.extname(fullPath).toLowerCase();
69
+ const outboundPatterns = PY_EXTENSIONS.has(ext)
70
+ ? OUTBOUND_PATTERNS_PY
71
+ : OUTBOUND_PATTERNS_JS;
72
+
73
+ const hasBreaker = BREAKER_SIGNALS.some((pattern) => pattern.test(content));
74
+ if (hasBreaker) {
75
+ continue;
76
+ }
77
+
78
+ const seenPatterns = new Set();
79
+ for (const pattern of outboundPatterns) {
80
+ if (!pattern.test(content)) {
81
+ continue;
82
+ }
83
+ if (seenPatterns.has(pattern.source)) {
84
+ continue;
85
+ }
86
+ seenPatterns.add(pattern.source);
87
+ const match = pattern.exec(content);
88
+ const lineIndex = content.slice(0, match?.index || 0).split(/\r?\n/).length;
89
+ findings.push(
90
+ createFinding({
91
+ tool: "circuit-breaker-check",
92
+ kind: "backend.no-circuit-breaker",
93
+ severity: "P1",
94
+ file: toPosix(relativePath),
95
+ line: lineIndex,
96
+ evidence: `${pattern.source} called without a circuit breaker in this file`,
97
+ rootCause:
98
+ "Outbound primitive call has no circuit breaker in scope — a slow or failing dependency cascades into the caller's runtime.",
99
+ recommendedFix:
100
+ "Wrap the dependency in a circuit breaker (opossum on Node, pybreaker / hyx in Python) with OPEN / HALF_OPEN / CLOSED transitions and fail-closed defaults.",
101
+ confidence: 0.55,
102
+ })
103
+ );
104
+ }
105
+ }
106
+ return findings;
107
+ }
108
+
109
+ async function* iterateExplicitFiles(resolvedRoot, files) {
110
+ for (const file of files) {
111
+ const trimmed = String(file || "").trim();
112
+ if (!trimmed) {
113
+ continue;
114
+ }
115
+ const fullPath = path.isAbsolute(trimmed)
116
+ ? trimmed
117
+ : path.join(resolvedRoot, trimmed);
118
+ const relativePath = path
119
+ .relative(resolvedRoot, fullPath)
120
+ .replace(/\\/g, "/");
121
+ yield { fullPath, relativePath };
122
+ }
123
+ }
@@ -0,0 +1,105 @@
1
+ // idempotency-audit — flag mutation endpoints without idempotency plumbing (#A14).
2
+ //
3
+ // Backend-runtime review: every POST / PUT / PATCH that can be retried by a
4
+ // client (or a queue / webhook) should carry an idempotency key, and the
5
+ // server should dedupe on it. We scan for handler declarations and look for
6
+ // signals that idempotency is being honored — presence of
7
+ // `idempotency_key`, `Idempotency-Key`, or a deduplication table lookup —
8
+ // anywhere in the file.
9
+
10
+ import fsp from "node:fs/promises";
11
+ import path from "node:path";
12
+
13
+ import { createFinding, findLineMatches, getLineContent, toPosix, walkRepoFiles } from "./base.js";
14
+
15
+ const JS_TS_EXTENSIONS = new Set([
16
+ ".js",
17
+ ".jsx",
18
+ ".ts",
19
+ ".tsx",
20
+ ".mjs",
21
+ ".cjs",
22
+ ]);
23
+ const PY_EXTENSIONS = new Set([".py"]);
24
+
25
+ const MUTATION_PATTERNS = [
26
+ // JS / TS routers: Express, Fastify, Koa, Hono
27
+ /\b(?:app|router|server|route)\.(post|put|patch)\s*\(/,
28
+ /\bfastify\.(post|put|patch)\s*\(/,
29
+ /\bhono\.(post|put|patch)\s*\(/,
30
+ // Next.js app-router handlers
31
+ /^export\s+async\s+function\s+(POST|PUT|PATCH)\s*\(/m,
32
+ // Python: FastAPI / Flask
33
+ /@(?:app|router|blueprint)\.(post|put|patch)\s*\(/,
34
+ ];
35
+
36
+ const IDEMPOTENCY_SIGNALS = [
37
+ /idempotency[_-]?key/i,
38
+ /Idempotency-Key/,
39
+ /dedupe|deduplicat|already_processed/i,
40
+ ];
41
+
42
+ export async function runIdempotencyAudit({ rootPath, files = null } = {}) {
43
+ const resolvedRoot = path.resolve(String(rootPath || "."));
44
+ const extensions = new Set([...JS_TS_EXTENSIONS, ...PY_EXTENSIONS]);
45
+ const iterator =
46
+ Array.isArray(files) && files.length > 0
47
+ ? iterateExplicitFiles(resolvedRoot, files)
48
+ : walkRepoFiles({ rootPath: resolvedRoot, extensions });
49
+
50
+ const findings = [];
51
+ for await (const { fullPath, relativePath } of iterator) {
52
+ let content;
53
+ try {
54
+ content = await fsp.readFile(fullPath, "utf-8");
55
+ } catch {
56
+ continue;
57
+ }
58
+ const hasSignal = IDEMPOTENCY_SIGNALS.some((pattern) => pattern.test(content));
59
+ if (hasSignal) {
60
+ continue;
61
+ }
62
+
63
+ const allMatches = [];
64
+ for (const pattern of MUTATION_PATTERNS) {
65
+ allMatches.push(...findLineMatches(content, pattern));
66
+ }
67
+ if (allMatches.length === 0) {
68
+ continue;
69
+ }
70
+ allMatches.sort((a, b) => a.line - b.line);
71
+ const first = allMatches[0];
72
+ findings.push(
73
+ createFinding({
74
+ tool: "idempotency-audit",
75
+ kind: "backend.no-idempotency",
76
+ severity: "P2",
77
+ file: toPosix(relativePath),
78
+ line: first.line,
79
+ evidence: getLineContent(content, first.line),
80
+ rootCause:
81
+ "Mutation-style route handler(s) declared in a file with no idempotency / dedupe plumbing. Retries from clients, queues, or webhooks risk double-charge / double-send.",
82
+ recommendedFix:
83
+ "Accept an Idempotency-Key header, persist (key, response) for a reasonable window (e.g. 24h), and return the cached response on replay.",
84
+ confidence: 0.5,
85
+ })
86
+ );
87
+ }
88
+ return findings;
89
+ }
90
+
91
+ async function* iterateExplicitFiles(resolvedRoot, files) {
92
+ for (const file of files) {
93
+ const trimmed = String(file || "").trim();
94
+ if (!trimmed) {
95
+ continue;
96
+ }
97
+ const fullPath = path.isAbsolute(trimmed)
98
+ ? trimmed
99
+ : path.join(resolvedRoot, trimmed);
100
+ const relativePath = path
101
+ .relative(resolvedRoot, fullPath)
102
+ .replace(/\\/g, "/");
103
+ yield { fullPath, relativePath };
104
+ }
105
+ }
@@ -0,0 +1,87 @@
1
+ // Maya (backend persona) domain-tool registry (#A14).
2
+
3
+ import { runCircuitBreakerCheck } from "./circuit-breaker-check.js";
4
+ import { runIdempotencyAudit } from "./idempotency-audit.js";
5
+ import { runRetryAudit } from "./retry-audit.js";
6
+ import { runTimeoutAudit } from "./timeout-audit.js";
7
+
8
+ export const BACKEND_TOOLS = Object.freeze({
9
+ "circuit-breaker-check": {
10
+ id: "circuit-breaker-check",
11
+ description:
12
+ "Flag files that make outbound HTTP calls (fetch / axios / got / http(s) / requests / httpx / urllib / aiohttp) without any circuit-breaker signal in scope.",
13
+ schema: {
14
+ type: "object",
15
+ properties: {
16
+ rootPath: { type: "string" },
17
+ files: { type: "array", items: { type: "string" } },
18
+ },
19
+ },
20
+ handler: runCircuitBreakerCheck,
21
+ },
22
+ "retry-audit": {
23
+ id: "retry-audit",
24
+ description:
25
+ "Flag hand-rolled retry loops using constant delays (classic thundering-herd risk). Does not fire when p-retry / async-retry / tenacity / Polly is already in use.",
26
+ schema: {
27
+ type: "object",
28
+ properties: {
29
+ rootPath: { type: "string" },
30
+ files: { type: "array", items: { type: "string" } },
31
+ },
32
+ },
33
+ handler: runRetryAudit,
34
+ },
35
+ "timeout-audit": {
36
+ id: "timeout-audit",
37
+ description:
38
+ "Flag outbound HTTP calls declared without an explicit timeout / AbortSignal — default timeouts in major clients are effectively infinite.",
39
+ schema: {
40
+ type: "object",
41
+ properties: {
42
+ rootPath: { type: "string" },
43
+ files: { type: "array", items: { type: "string" } },
44
+ },
45
+ },
46
+ handler: runTimeoutAudit,
47
+ },
48
+ "idempotency-audit": {
49
+ id: "idempotency-audit",
50
+ description:
51
+ "Flag files that declare POST/PUT/PATCH handlers without any idempotency-key or dedupe plumbing. Catches double-charge / double-send risk.",
52
+ schema: {
53
+ type: "object",
54
+ properties: {
55
+ rootPath: { type: "string" },
56
+ files: { type: "array", items: { type: "string" } },
57
+ },
58
+ },
59
+ handler: runIdempotencyAudit,
60
+ },
61
+ });
62
+
63
+ export const BACKEND_TOOL_IDS = Object.freeze(Object.keys(BACKEND_TOOLS));
64
+
65
+ export async function dispatchBackendTool(toolId, args = {}) {
66
+ const tool = BACKEND_TOOLS[toolId];
67
+ if (!tool) {
68
+ throw new Error(`Unknown backend tool: ${toolId}`);
69
+ }
70
+ return tool.handler(args);
71
+ }
72
+
73
+ export async function runAllBackendTools({ rootPath, files = null } = {}) {
74
+ const findings = [];
75
+ for (const toolId of BACKEND_TOOL_IDS) {
76
+ const out = await dispatchBackendTool(toolId, { rootPath, files });
77
+ findings.push(...out);
78
+ }
79
+ return findings;
80
+ }
81
+
82
+ export {
83
+ runCircuitBreakerCheck,
84
+ runIdempotencyAudit,
85
+ runRetryAudit,
86
+ runTimeoutAudit,
87
+ };
@@ -0,0 +1,132 @@
1
+ // retry-audit — flag retry loops without exponential backoff + jitter (#A14).
2
+ //
3
+ // Retries are a footgun: a linear / fixed-interval retry against a failing
4
+ // downstream is a synchronized flood, which is exactly when you want jitter
5
+ // and exponential backoff. We look for loops that include `setTimeout(...)`
6
+ // or `sleep(...)` with constant delays as a heuristic — the LLM review
7
+ // layer confirms.
8
+
9
+ import fsp from "node:fs/promises";
10
+ import path from "node:path";
11
+
12
+ import { createFinding, findLineMatches, toPosix, walkRepoFiles } from "./base.js";
13
+
14
+ const JS_TS_EXTENSIONS = new Set([
15
+ ".js",
16
+ ".jsx",
17
+ ".ts",
18
+ ".tsx",
19
+ ".mjs",
20
+ ".cjs",
21
+ ]);
22
+ const PY_EXTENSIONS = new Set([".py"]);
23
+
24
+ // "for-loop with constant sleep" pattern — a classic bad-retry shape.
25
+ const BAD_RETRY_PATTERNS = [
26
+ // for (let i = 0; i < 5; i++) { ...; await sleep(1000); } — constant 1000 ms
27
+ {
28
+ pattern: /for\s*\([^)]*;[^)]*<[^)]*\)\s*\{[\s\S]{0,500}?(?:setTimeout|sleep|delay|wait)\s*\([^)]*\b\d{2,}\b[^)]*\)/,
29
+ kind: "backend.retry-constant-delay",
30
+ severity: "P2",
31
+ rootCause:
32
+ "A for-loop retry with a constant delay creates synchronized load on the downstream when it recovers.",
33
+ recommendedFix:
34
+ "Replace with exponential backoff + jitter. Libraries: p-retry / async-retry on Node, tenacity on Python.",
35
+ confidence: 0.6,
36
+ },
37
+ {
38
+ pattern: /while\s*\([^)]*(?:retry|attempt)[^)]*\)\s*\{[\s\S]{0,500}?(?:setTimeout|sleep|delay|wait)\s*\([^)]*\b\d{2,}\b[^)]*\)/,
39
+ kind: "backend.retry-constant-delay",
40
+ severity: "P2",
41
+ rootCause:
42
+ "A while-retry loop with a constant delay thunders herd once the downstream recovers.",
43
+ recommendedFix:
44
+ "Add exponential backoff and jitter. A simple formula: delay = Math.min(maxDelay, baseDelay * 2**attempt * (0.5 + Math.random())).",
45
+ confidence: 0.55,
46
+ },
47
+ {
48
+ pattern: /for\s+\w+\s+in\s+range\s*\([^)]*\)\s*:\s*\n[\s\S]{0,400}?time\.sleep\s*\(\s*\d+\s*\)/,
49
+ kind: "backend.retry-constant-delay",
50
+ severity: "P2",
51
+ rootCause:
52
+ "Python retry loop uses time.sleep with a constant — synchronized retry storm risk.",
53
+ recommendedFix:
54
+ "Switch to tenacity.retry with stop_after_attempt + wait_exponential_jitter.",
55
+ confidence: 0.55,
56
+ },
57
+ ];
58
+
59
+ // "no jitter" signal: we look for files that DO have retry logic (mentioned
60
+ // keywords) but don't mention jitter / random.
61
+ function hasJitter(content) {
62
+ return /jitter|Math\.random|random\.(?:random|uniform)|secrets\.randbelow/.test(
63
+ content
64
+ );
65
+ }
66
+
67
+ function hasRetryLibraryHint(content) {
68
+ return /p-retry|async-retry|retry\.operation|tenacity\.retry|@retry|retry_strategy|Polly/.test(
69
+ content
70
+ );
71
+ }
72
+
73
+ export async function runRetryAudit({ rootPath, files = null } = {}) {
74
+ const resolvedRoot = path.resolve(String(rootPath || "."));
75
+ const extensions = new Set([...JS_TS_EXTENSIONS, ...PY_EXTENSIONS]);
76
+ const iterator =
77
+ Array.isArray(files) && files.length > 0
78
+ ? iterateExplicitFiles(resolvedRoot, files)
79
+ : walkRepoFiles({ rootPath: resolvedRoot, extensions });
80
+
81
+ const findings = [];
82
+ for await (const { fullPath, relativePath } of iterator) {
83
+ let content;
84
+ try {
85
+ content = await fsp.readFile(fullPath, "utf-8");
86
+ } catch {
87
+ continue;
88
+ }
89
+
90
+ if (hasRetryLibraryHint(content)) {
91
+ // Retry library is in use — assume it handles backoff correctly.
92
+ continue;
93
+ }
94
+
95
+ for (const rule of BAD_RETRY_PATTERNS) {
96
+ const matches = findLineMatches(content, rule.pattern);
97
+ if (matches.length === 0) {
98
+ continue;
99
+ }
100
+ findings.push(
101
+ createFinding({
102
+ tool: "retry-audit",
103
+ kind: rule.kind,
104
+ severity: rule.severity,
105
+ file: toPosix(relativePath),
106
+ line: matches[0].line,
107
+ evidence: (content.split(/\r?\n/)[matches[0].line - 1] || "").trim(),
108
+ rootCause: rule.rootCause,
109
+ recommendedFix: rule.recommendedFix,
110
+ confidence: hasJitter(content) ? Math.max(0.3, rule.confidence - 0.2) : rule.confidence,
111
+ })
112
+ );
113
+ }
114
+ }
115
+ return findings;
116
+ }
117
+
118
+ async function* iterateExplicitFiles(resolvedRoot, files) {
119
+ for (const file of files) {
120
+ const trimmed = String(file || "").trim();
121
+ if (!trimmed) {
122
+ continue;
123
+ }
124
+ const fullPath = path.isAbsolute(trimmed)
125
+ ? trimmed
126
+ : path.join(resolvedRoot, trimmed);
127
+ const relativePath = path
128
+ .relative(resolvedRoot, fullPath)
129
+ .replace(/\\/g, "/");
130
+ yield { fullPath, relativePath };
131
+ }
132
+ }