sentinelayer-cli 0.8.0 → 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 (153) hide show
  1. package/README.md +13 -0
  2. package/package.json +4 -4
  3. package/src/agents/ai-governance/index.js +12 -0
  4. package/src/agents/ai-governance/tools/base.js +171 -0
  5. package/src/agents/ai-governance/tools/eval-regression.js +47 -0
  6. package/src/agents/ai-governance/tools/hitl-audit.js +81 -0
  7. package/src/agents/ai-governance/tools/index.js +52 -0
  8. package/src/agents/ai-governance/tools/prompt-drift.js +42 -0
  9. package/src/agents/ai-governance/tools/provenance-check.js +69 -0
  10. package/src/agents/backend/index.js +12 -0
  11. package/src/agents/backend/tools/base.js +189 -0
  12. package/src/agents/backend/tools/circuit-breaker-check.js +123 -0
  13. package/src/agents/backend/tools/idempotency-audit.js +105 -0
  14. package/src/agents/backend/tools/index.js +87 -0
  15. package/src/agents/backend/tools/retry-audit.js +132 -0
  16. package/src/agents/backend/tools/timeout-audit.js +144 -0
  17. package/src/agents/code-quality/index.js +12 -0
  18. package/src/agents/code-quality/tools/base.js +159 -0
  19. package/src/agents/code-quality/tools/complexity-measure.js +197 -0
  20. package/src/agents/code-quality/tools/coupling-analysis.js +81 -0
  21. package/src/agents/code-quality/tools/cycle-detect.js +49 -0
  22. package/src/agents/code-quality/tools/dep-graph.js +196 -0
  23. package/src/agents/code-quality/tools/index.js +89 -0
  24. package/src/agents/data-layer/index.js +12 -0
  25. package/src/agents/data-layer/tools/base.js +181 -0
  26. package/src/agents/data-layer/tools/index-audit.js +165 -0
  27. package/src/agents/data-layer/tools/index.js +83 -0
  28. package/src/agents/data-layer/tools/migration-scan.js +135 -0
  29. package/src/agents/data-layer/tools/query-explain.js +120 -0
  30. package/src/agents/data-layer/tools/tenancy-scan.js +166 -0
  31. package/src/agents/documentation/index.js +12 -0
  32. package/src/agents/documentation/tools/api-diff.js +91 -0
  33. package/src/agents/documentation/tools/base.js +151 -0
  34. package/src/agents/documentation/tools/dead-link-check.js +58 -0
  35. package/src/agents/documentation/tools/docstring-coverage.js +78 -0
  36. package/src/agents/documentation/tools/index.js +52 -0
  37. package/src/agents/documentation/tools/readme-freshness.js +61 -0
  38. package/src/agents/envelope/fix-cycle.js +45 -0
  39. package/src/agents/envelope/index.js +31 -0
  40. package/src/agents/envelope/loop.js +150 -0
  41. package/src/agents/envelope/pulse.js +18 -0
  42. package/src/agents/envelope/stream.js +40 -0
  43. package/src/agents/infrastructure/index.js +12 -0
  44. package/src/agents/infrastructure/tools/base.js +171 -0
  45. package/src/agents/infrastructure/tools/checkov-run.js +32 -0
  46. package/src/agents/infrastructure/tools/drift-detect.js +59 -0
  47. package/src/agents/infrastructure/tools/iam-least-priv-check.js +78 -0
  48. package/src/agents/infrastructure/tools/index.js +52 -0
  49. package/src/agents/infrastructure/tools/tflint-run.js +31 -0
  50. package/src/agents/jules/loop.js +7 -4
  51. package/src/agents/jules/swarm/sub-agent.js +5 -1
  52. package/src/agents/jules/tools/auth-audit.js +10 -1
  53. package/src/agents/mode.js +113 -0
  54. package/src/agents/observability/index.js +12 -0
  55. package/src/agents/observability/tools/alert-audit.js +39 -0
  56. package/src/agents/observability/tools/base.js +181 -0
  57. package/src/agents/observability/tools/dashboard-gap.js +42 -0
  58. package/src/agents/observability/tools/index.js +54 -0
  59. package/src/agents/observability/tools/log-schema-check.js +74 -0
  60. package/src/agents/observability/tools/span-coverage.js +74 -0
  61. package/src/agents/persona-visuals.js +38 -0
  62. package/src/agents/release/index.js +12 -0
  63. package/src/agents/release/tools/base.js +181 -0
  64. package/src/agents/release/tools/changelog-diff.js +86 -0
  65. package/src/agents/release/tools/feature-flag-audit.js +126 -0
  66. package/src/agents/release/tools/index.js +61 -0
  67. package/src/agents/release/tools/rollback-verify.js +129 -0
  68. package/src/agents/release/tools/semver-check.js +109 -0
  69. package/src/agents/reliability/index.js +12 -0
  70. package/src/agents/reliability/tools/backpressure-check.js +129 -0
  71. package/src/agents/reliability/tools/base.js +181 -0
  72. package/src/agents/reliability/tools/chaos-probe.js +109 -0
  73. package/src/agents/reliability/tools/graceful-degradation-check.js +114 -0
  74. package/src/agents/reliability/tools/health-check-audit.js +111 -0
  75. package/src/agents/reliability/tools/index.js +87 -0
  76. package/src/agents/run-persona.js +109 -0
  77. package/src/agents/security/index.js +12 -0
  78. package/src/agents/security/tools/authz-audit.js +134 -0
  79. package/src/agents/security/tools/base.js +190 -0
  80. package/src/agents/security/tools/crypto-review.js +175 -0
  81. package/src/agents/security/tools/index.js +97 -0
  82. package/src/agents/security/tools/sast-scan.js +175 -0
  83. package/src/agents/security/tools/secrets-scan.js +216 -0
  84. package/src/agents/supply-chain/index.js +12 -0
  85. package/src/agents/supply-chain/tools/attestation-check.js +42 -0
  86. package/src/agents/supply-chain/tools/base.js +151 -0
  87. package/src/agents/supply-chain/tools/index.js +52 -0
  88. package/src/agents/supply-chain/tools/lockfile-integrity.js +73 -0
  89. package/src/agents/supply-chain/tools/package-verify.js +56 -0
  90. package/src/agents/supply-chain/tools/sbom-diff.js +34 -0
  91. package/src/agents/testing/index.js +12 -0
  92. package/src/agents/testing/tools/base.js +202 -0
  93. package/src/agents/testing/tools/coverage-gap.js +144 -0
  94. package/src/agents/testing/tools/flake-detect.js +125 -0
  95. package/src/agents/testing/tools/index.js +85 -0
  96. package/src/agents/testing/tools/mutation-test.js +143 -0
  97. package/src/agents/testing/tools/snapshot-diff.js +103 -0
  98. package/src/auth/gate.js +65 -37
  99. package/src/cli.js +1 -1
  100. package/src/commands/chat.js +3 -10
  101. package/src/commands/legacy-args.js +10 -0
  102. package/src/commands/omargate.js +36 -2
  103. package/src/commands/persona.js +46 -1
  104. package/src/commands/scan.js +3 -10
  105. package/src/commands/session.js +654 -6
  106. package/src/commands/spec.js +3 -10
  107. package/src/coord/events-log.js +141 -0
  108. package/src/coord/handshake.js +719 -0
  109. package/src/coord/index.js +35 -0
  110. package/src/coord/paths.js +84 -0
  111. package/src/coord/priority.js +62 -0
  112. package/src/coord/tarjan.js +157 -0
  113. package/src/cost/tokenizer.js +160 -0
  114. package/src/cost/tracker.js +61 -0
  115. package/src/daemon/artifact-lineage.js +362 -0
  116. package/src/daemon/assignment-ledger.js +117 -0
  117. package/src/daemon/ast-drift.js +496 -0
  118. package/src/daemon/ingest-refresh.js +69 -2
  119. package/src/ingest/engine.js +15 -0
  120. package/src/ingest/ownership.js +380 -0
  121. package/src/legacy-cli.js +68 -1
  122. package/src/orchestrator/kai-chen.js +126 -0
  123. package/src/review/ai-review.js +3 -10
  124. package/src/review/compliance-pack.js +389 -0
  125. package/src/review/investor-dd-config.js +54 -0
  126. package/src/review/investor-dd-file-loop.js +303 -0
  127. package/src/review/investor-dd-file-router.js +406 -0
  128. package/src/review/investor-dd-html-report.js +233 -0
  129. package/src/review/investor-dd-notification.js +120 -0
  130. package/src/review/investor-dd-orchestrator.js +405 -0
  131. package/src/review/investor-dd-persona-runner.js +275 -0
  132. package/src/review/live-validator.js +253 -0
  133. package/src/review/omargate-orchestrator.js +90 -2
  134. package/src/review/persona-prompts.js +244 -56
  135. package/src/review/reconciliation-rules.js +329 -0
  136. package/src/review/reproducibility-chain.js +136 -0
  137. package/src/review/scan-modes.js +102 -3
  138. package/src/session/agent-registry.js +7 -0
  139. package/src/session/analytics.js +479 -0
  140. package/src/session/daemon.js +609 -14
  141. package/src/session/file-locks.js +666 -0
  142. package/src/session/paths.js +4 -0
  143. package/src/session/recap.js +567 -0
  144. package/src/session/redact.js +82 -0
  145. package/src/session/runtime-bridge.js +24 -1
  146. package/src/session/scoring.js +406 -0
  147. package/src/session/setup-guides.js +304 -0
  148. package/src/session/store.js +318 -2
  149. package/src/session/stream.js +9 -1
  150. package/src/session/sync.js +753 -0
  151. package/src/session/tasks.js +1054 -0
  152. package/src/session/templates.js +188 -0
  153. package/src/swarm/runtime.js +1 -8
@@ -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
+ }