sdtk-code-kit 0.2.1 → 0.3.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.
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { safeSegment } = require("./agent-team-export");
6
+ const { loadAgentTeamPlan } = require("./agent-team-plan");
7
+ const {
8
+ asArray,
9
+ assertPathUnderBase,
10
+ atomicWriteText,
11
+ resolveEvidencePath,
12
+ } = require("./agent-team-evidence");
13
+ const { READINESS_NOTE, loadReadiness } = require("./agent-team-readiness");
14
+
15
+ function reportBaseDir(projectPath) {
16
+ return path.resolve(projectPath || ".", ".sdtk", "agent-team", "reports");
17
+ }
18
+
19
+ function resolveReportPath(projectPath, featureKey) {
20
+ const safeFeatureKey = safeSegment(featureKey, "feature_key");
21
+ const base = reportBaseDir(projectPath);
22
+ const dir = assertPathUnderBase(path.join(base, safeFeatureKey), base);
23
+ return assertPathUnderBase(path.join(dir, "morning_report.md"), base);
24
+ }
25
+
26
+ function loadEvidenceMap(projectPath, plan) {
27
+ const evidenceMap = {};
28
+ for (const roleSpec of asArray(plan && plan.roles)) {
29
+ const role = roleSpec.role;
30
+ const evidencePath = resolveEvidencePath(projectPath, plan.feature_key, role);
31
+ if (!fs.existsSync(evidencePath)) {
32
+ evidenceMap[role] = null;
33
+ continue;
34
+ }
35
+ try {
36
+ evidenceMap[role] = JSON.parse(fs.readFileSync(evidencePath, "utf8"));
37
+ } catch (_error) {
38
+ evidenceMap[role] = { _invalid: true };
39
+ }
40
+ }
41
+ return evidenceMap;
42
+ }
43
+
44
+ function bulletList(items, fallback) {
45
+ if (!Array.isArray(items) || items.length === 0) {
46
+ return `- ${fallback}`;
47
+ }
48
+ return items.map((item) => `- ${String(item)}`).join("\n");
49
+ }
50
+
51
+ function roleStatus(readinessJson, role) {
52
+ return asArray(readinessJson && readinessJson.roles).find((entry) => entry.role === role) || {
53
+ role,
54
+ verdict: "NOT_READY",
55
+ reason: "role missing from readiness.json",
56
+ };
57
+ }
58
+
59
+ function renderEvidenceDetail(roleSpec, evidence) {
60
+ const role = roleSpec.role;
61
+ if (!evidence) {
62
+ return [
63
+ `### ${role}`,
64
+ "",
65
+ "- Evidence: not submitted",
66
+ "",
67
+ ].join("\n");
68
+ }
69
+ if (evidence._invalid) {
70
+ return [
71
+ `### ${role}`,
72
+ "",
73
+ "- Evidence: invalid JSON",
74
+ "",
75
+ ].join("\n");
76
+ }
77
+
78
+ const lines = [
79
+ `### ${role}`,
80
+ "",
81
+ `- Summary: ${evidence.summary || "(none)"}`,
82
+ "- Commands run:",
83
+ bulletList(evidence.commands_run, "none"),
84
+ `- Verification evidence: ${evidence.verification_evidence || "(none)"}`,
85
+ "- Blockers:",
86
+ bulletList(evidence.blockers, "none"),
87
+ "- Files touched:",
88
+ bulletList(evidence.files_touched, "none declared"),
89
+ `- Stop condition hit: ${evidence.stop_condition_hit === null || evidence.stop_condition_hit === undefined ? "none" : evidence.stop_condition_hit}`,
90
+ ];
91
+
92
+ if (evidence.commit_range) {
93
+ lines.push("- Commit range:");
94
+ lines.push(`- before: ${evidence.commit_range.before || "(none)"}`);
95
+ lines.push(`- after: ${evidence.commit_range.after || "(none)"}`);
96
+ }
97
+
98
+ lines.push("");
99
+ return lines.join("\n");
100
+ }
101
+
102
+ function renderMorningReport(plan, evidenceMap, readinessJson) {
103
+ const rows = asArray(plan && plan.roles).map((roleSpec) => {
104
+ const status = roleStatus(readinessJson, roleSpec.role);
105
+ return `| ${roleSpec.role} | ${status.verdict} | ${status.reason || ""} |`;
106
+ });
107
+ const details = asArray(plan && plan.roles).map((roleSpec) => renderEvidenceDetail(roleSpec, evidenceMap[roleSpec.role]));
108
+
109
+ return [
110
+ `# Agent Team Morning Report — ${plan.feature_key} (${plan.run_id})`,
111
+ "",
112
+ `Generated: ${new Date().toISOString()}`,
113
+ "",
114
+ "## Overall Verdict",
115
+ "",
116
+ "```text",
117
+ readinessJson.overall_verdict,
118
+ "```",
119
+ "",
120
+ `Reason: ${readinessJson.overall_reason || "(none)"}`,
121
+ "",
122
+ "## Readiness Note",
123
+ "",
124
+ readinessJson.readiness_note || READINESS_NOTE,
125
+ "",
126
+ "## Role Evidence Status",
127
+ "",
128
+ "| Role | Verdict | Reason |",
129
+ "| --- | --- | --- |",
130
+ ...(rows.length > 0 ? rows : ["| (none) | NOT_READY | no roles in plan |"]),
131
+ "",
132
+ "## Evidence Details",
133
+ "",
134
+ ...details,
135
+ "## Next steps",
136
+ "",
137
+ "- Review evidence files before treating READY_TO_SLEEP as final.",
138
+ "- Check code, tests, and product behavior manually before shipping.",
139
+ "- Resolve any NOT_READY or BLOCKED_BY_STOP_CONDITION role before relying on this report.",
140
+ "- This report records submitted evidence only; it does not execute or verify implementation correctness.",
141
+ "",
142
+ ].join("\n");
143
+ }
144
+
145
+ function buildMorningReport(projectPath, featureKey) {
146
+ const safeFeatureKey = safeSegment(featureKey, "feature_key");
147
+ const plan = loadAgentTeamPlan(projectPath, safeFeatureKey);
148
+ const readinessJson = loadReadiness(projectPath, safeFeatureKey);
149
+ const evidenceMap = loadEvidenceMap(projectPath, plan);
150
+ return { plan, readinessJson, evidenceMap, markdown: renderMorningReport(plan, evidenceMap, readinessJson) };
151
+ }
152
+
153
+ function writeReport(projectPath, featureKey, markdown) {
154
+ const outputPath = resolveReportPath(projectPath, featureKey);
155
+ return atomicWriteText(outputPath, markdown, reportBaseDir(projectPath));
156
+ }
157
+
158
+ module.exports = {
159
+ reportBaseDir,
160
+ resolveReportPath,
161
+ loadEvidenceMap,
162
+ renderMorningReport,
163
+ buildMorningReport,
164
+ writeReport,
165
+ };
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+
3
+ const https = require("https");
4
+ const { URL } = require("url");
5
+ const { ValidationError } = require("./errors");
6
+
7
+ const MODEL_MAX_CALLS_PER_RUN = 1;
8
+ const MODEL_CALL_TIMEOUT_MS = 120000;
9
+ const MODEL_WALLCLOCK_TIMEOUT_MS = 300000;
10
+ const MODEL_MAX_OUTPUT_TOKENS = 16000;
11
+ const CONTEXT_MAX_FILES = 20;
12
+ const CONTEXT_MAX_BYTES = 262144;
13
+ const MODEL_EGRESS_ALLOWLIST = Object.freeze(["api.anthropic.com"]);
14
+ const MODEL_ID = "claude-sonnet-4-6";
15
+ const MODEL_PRICE_INPUT_USD_PER_MTOK = 3.00;
16
+ const MODEL_PRICE_OUTPUT_USD_PER_MTOK = 15.00;
17
+ const MODEL_PRICING_SOURCE_DATE = "2026-05-26";
18
+ const MODEL_MAX_COST_USD = 1.00;
19
+ const ANTHROPIC_VERSION = "2023-06-01";
20
+ const DEFAULT_PROVIDER = "claude";
21
+
22
+ const MODEL_PRICING = Object.freeze({
23
+ [MODEL_ID]: Object.freeze({
24
+ input_usd_per_mtok: MODEL_PRICE_INPUT_USD_PER_MTOK,
25
+ output_usd_per_mtok: MODEL_PRICE_OUTPUT_USD_PER_MTOK,
26
+ source_date: MODEL_PRICING_SOURCE_DATE,
27
+ }),
28
+ });
29
+
30
+ function estimateTokensFromText(text) {
31
+ return Math.ceil(Buffer.byteLength(String(text || ""), "utf8") / 4);
32
+ }
33
+
34
+ function projectedCostUsd(modelId, inputTokenEstimate, maxOutputTokens) {
35
+ const pricing = MODEL_PRICING[modelId];
36
+ if (!pricing) {
37
+ throw new ValidationError(`FAIL_MODEL_PRICING_UNKNOWN: no pinned pricing for model_id ${modelId}`);
38
+ }
39
+ const inputCost = (Number(inputTokenEstimate || 0) / 1000000) * pricing.input_usd_per_mtok;
40
+ const outputCost = (Number(maxOutputTokens || 0) / 1000000) * pricing.output_usd_per_mtok;
41
+ return Number((inputCost + outputCost).toFixed(6));
42
+ }
43
+
44
+ function assertCostWithinCap(modelId, inputTokenEstimate, maxOutputTokens) {
45
+ const cost = projectedCostUsd(modelId, inputTokenEstimate, maxOutputTokens);
46
+ if (cost > MODEL_MAX_COST_USD) {
47
+ throw new ValidationError(`FAIL_MODEL_COST_CAP: projected model cost ${cost} exceeds cap ${MODEL_MAX_COST_USD}`);
48
+ }
49
+ return cost;
50
+ }
51
+
52
+ function assertAllowedHost(hostname) {
53
+ if (!MODEL_EGRESS_ALLOWLIST.includes(String(hostname || ""))) {
54
+ throw new ValidationError(`FAIL_EGRESS_HOST_NOT_ALLOWED: ${hostname || "(missing host)"}`);
55
+ }
56
+ }
57
+
58
+ function parseEndpoint(endpoint) {
59
+ const url = new URL(endpoint || "https://api.anthropic.com/v1/messages");
60
+ if (url.protocol !== "https:") {
61
+ throw new ValidationError("FAIL_EGRESS_HOST_NOT_ALLOWED: model egress requires https");
62
+ }
63
+ assertAllowedHost(url.hostname);
64
+ return url;
65
+ }
66
+
67
+ function defaultHttpsTransport(options, body, timeoutMs) {
68
+ return new Promise((resolve, reject) => {
69
+ const req = https.request(options, (res) => {
70
+ let data = "";
71
+ res.setEncoding("utf8");
72
+ res.on("data", (chunk) => { data += chunk; });
73
+ res.on("end", () => resolve({
74
+ statusCode: res.statusCode || 0,
75
+ headers: res.headers || {},
76
+ body: data,
77
+ connectionHost: options.hostname,
78
+ }));
79
+ });
80
+ req.setTimeout(timeoutMs, () => {
81
+ req.destroy(new Error("FAIL_MODEL_TIMEOUT: model call timed out"));
82
+ });
83
+ req.on("error", reject);
84
+ req.write(body);
85
+ req.end();
86
+ });
87
+ }
88
+
89
+ function responseText(payload) {
90
+ if (!payload || typeof payload !== "object") return "";
91
+ if (typeof payload.patch === "string") return payload.patch;
92
+ if (typeof payload.text === "string") return payload.text;
93
+ if (Array.isArray(payload.content)) {
94
+ return payload.content.map((part) => {
95
+ if (part && typeof part.text === "string") return part.text;
96
+ return "";
97
+ }).join("\n").trim();
98
+ }
99
+ return "";
100
+ }
101
+
102
+ function usageFromPayload(payload) {
103
+ const usage = payload && typeof payload === "object" && payload.usage && typeof payload.usage === "object"
104
+ ? payload.usage : {};
105
+ return {
106
+ input_tokens: typeof usage.input_tokens === "number" ? usage.input_tokens : null,
107
+ output_tokens: typeof usage.output_tokens === "number" ? usage.output_tokens : null,
108
+ };
109
+ }
110
+
111
+ async function callModelProvider(request, deps) {
112
+ const req = request || {};
113
+ const options = deps || {};
114
+ const modelId = req.model_id || MODEL_ID;
115
+ const provider = req.provider || DEFAULT_PROVIDER;
116
+ const maxOutputTokens = Number(req.max_output_tokens || MODEL_MAX_OUTPUT_TOKENS);
117
+ if (provider !== DEFAULT_PROVIDER) {
118
+ throw new ValidationError(`FAIL_EGRESS_HOST_NOT_ALLOWED: unsupported provider ${provider}`);
119
+ }
120
+ if (modelId !== MODEL_ID) {
121
+ projectedCostUsd(modelId, 0, maxOutputTokens);
122
+ }
123
+ if (maxOutputTokens > MODEL_MAX_OUTPUT_TOKENS) {
124
+ throw new ValidationError(`FAIL_MODEL_OUTPUT_TOKEN_CAP: max_output_tokens ${maxOutputTokens} exceeds ${MODEL_MAX_OUTPUT_TOKENS}`);
125
+ }
126
+ if (Number(req.call_count || 1) > MODEL_MAX_CALLS_PER_RUN) {
127
+ throw new ValidationError("FAIL_MODEL_CALL_LIMIT: only one model call is allowed per run");
128
+ }
129
+
130
+ const prompt = String(req.prompt || "");
131
+ const inputTokens = typeof req.input_token_estimate === "number" ? req.input_token_estimate : estimateTokensFromText(prompt);
132
+ const projectedCost = assertCostWithinCap(modelId, inputTokens, maxOutputTokens);
133
+
134
+ const env = options.env || process.env;
135
+ const apiKey = options.apiKey || env.ANTHROPIC_API_KEY;
136
+ if (!apiKey) {
137
+ throw new ValidationError("FAIL_MODEL_CREDENTIAL_MISSING: ANTHROPIC_API_KEY is required for --execute author mode");
138
+ }
139
+
140
+ const endpoint = parseEndpoint(req.endpoint || "https://api.anthropic.com/v1/messages");
141
+ const body = JSON.stringify({
142
+ model: modelId,
143
+ max_tokens: maxOutputTokens,
144
+ messages: [{ role: "user", content: prompt }],
145
+ });
146
+ const transport = options.transport || defaultHttpsTransport;
147
+ const transportOptions = {
148
+ protocol: "https:",
149
+ hostname: endpoint.hostname,
150
+ port: endpoint.port || 443,
151
+ method: "POST",
152
+ path: `${endpoint.pathname}${endpoint.search}`,
153
+ headers: {
154
+ "content-type": "application/json",
155
+ "content-length": Buffer.byteLength(body),
156
+ "x-api-key": apiKey,
157
+ "anthropic-version": ANTHROPIC_VERSION,
158
+ },
159
+ };
160
+
161
+ const response = await transport(transportOptions, body, MODEL_CALL_TIMEOUT_MS);
162
+ assertAllowedHost(response && response.connectionHost ? response.connectionHost : transportOptions.hostname);
163
+ const statusCode = Number(response && response.statusCode || 0);
164
+ if (statusCode >= 300 && statusCode < 400) {
165
+ const location = response.headers && response.headers.location;
166
+ if (location) {
167
+ const redirect = new URL(location, endpoint);
168
+ assertAllowedHost(redirect.hostname);
169
+ }
170
+ throw new ValidationError("FAIL_EGRESS_HOST_NOT_ALLOWED: redirects are not followed in D-2b");
171
+ }
172
+ if (statusCode < 200 || statusCode >= 300) {
173
+ throw new ValidationError(`FAIL_MODEL_PROVIDER_ERROR: provider status ${statusCode}`);
174
+ }
175
+
176
+ let payload;
177
+ try {
178
+ payload = JSON.parse(response.body || "{}");
179
+ } catch (_error) {
180
+ throw new ValidationError("FAIL_MODEL_PROVIDER_ERROR: provider returned invalid JSON");
181
+ }
182
+ const patch = responseText(payload);
183
+ const tokensUsed = usageFromPayload(payload);
184
+ if (tokensUsed.output_tokens != null && tokensUsed.output_tokens > MODEL_MAX_OUTPUT_TOKENS) {
185
+ throw new ValidationError(`FAIL_MODEL_OUTPUT_TOKEN_CAP: output tokens ${tokensUsed.output_tokens} exceeds ${MODEL_MAX_OUTPUT_TOKENS}`);
186
+ }
187
+ if (!patch) {
188
+ throw new ValidationError("FAIL_MODEL_PROVIDER_ERROR: provider returned no patch text");
189
+ }
190
+ return {
191
+ provider,
192
+ model_id: modelId,
193
+ patch,
194
+ tokens_used: tokensUsed,
195
+ projected_cost_usd: projectedCost,
196
+ model_call_count: 1,
197
+ };
198
+ }
199
+
200
+ module.exports = {
201
+ MODEL_MAX_CALLS_PER_RUN,
202
+ MODEL_CALL_TIMEOUT_MS,
203
+ MODEL_WALLCLOCK_TIMEOUT_MS,
204
+ MODEL_MAX_OUTPUT_TOKENS,
205
+ CONTEXT_MAX_FILES,
206
+ CONTEXT_MAX_BYTES,
207
+ MODEL_EGRESS_ALLOWLIST,
208
+ MODEL_ID,
209
+ MODEL_PRICE_INPUT_USD_PER_MTOK,
210
+ MODEL_PRICE_OUTPUT_USD_PER_MTOK,
211
+ MODEL_PRICING_SOURCE_DATE,
212
+ MODEL_MAX_COST_USD,
213
+ MODEL_PRICING,
214
+ estimateTokensFromText,
215
+ projectedCostUsd,
216
+ assertCostWithinCap,
217
+ assertAllowedHost,
218
+ callModelProvider,
219
+ };
@@ -64,6 +64,30 @@ function normalizeFiles(value) {
64
64
  return value.filter((entry) => typeof entry === "string").map((entry) => redact(entry));
65
65
  }
66
66
 
67
+
68
+ function normalizeContextManifest(value) {
69
+ if (!Array.isArray(value)) {
70
+ return [];
71
+ }
72
+ return value.map((entry) => {
73
+ const source = entry && typeof entry === "object" ? entry : {};
74
+ return {
75
+ path: source.path != null ? redact(String(source.path)) : null,
76
+ snapshot_sha256: typeof source.snapshot_sha256 === "string" ? source.snapshot_sha256 : null,
77
+ };
78
+ }).filter((entry) => entry.path && entry.snapshot_sha256);
79
+ }
80
+
81
+ function normalizeTokensUsed(value) {
82
+ if (!value || typeof value !== "object") {
83
+ return null;
84
+ }
85
+ return {
86
+ input_tokens: typeof value.input_tokens === "number" ? value.input_tokens : null,
87
+ output_tokens: typeof value.output_tokens === "number" ? value.output_tokens : null,
88
+ };
89
+ }
90
+
67
91
  function normalizeCommand(value) {
68
92
  if (typeof value !== "string") {
69
93
  return { command: null, truncated: false };
@@ -84,7 +108,49 @@ function buildEvent(raw) {
84
108
  const sessionId = nullableString(source.session_id);
85
109
  const toolkit = nullableString(source.toolkit);
86
110
  const eventType = inferEventType(source);
87
- const canonical = [sessionId || "", toolkit || "", eventType || "", command || "", timestamp].join("|");
111
+ // Agent-team traceability (BK-260). Redacted like any other string field and
112
+ // folded into the dedup identity so distinct runs/roles emitting the same
113
+ // command are not collapsed into a single event. Existing callers omit these,
114
+ // so the fields default to null and keep dedup deterministic.
115
+ const runId = source.run_id != null ? redact(String(source.run_id)) : null;
116
+ const agentRole = source.agent_role != null ? redact(String(source.agent_role)) : null;
117
+ const taskId = source.task_id != null ? redact(String(source.task_id)) : null;
118
+ const featureKey = source.feature_key != null ? redact(String(source.feature_key)) : null;
119
+ const stopConditionHit = source.stop_condition_hit != null
120
+ ? String(source.stop_condition_hit) : null;
121
+ const evidenceQualityOk = typeof source.evidence_quality_ok === "boolean"
122
+ ? source.evidence_quality_ok : null;
123
+ const overallVerdict = source.overall_verdict != null
124
+ ? String(source.overall_verdict) : null;
125
+ const rolesNotReadyCount = typeof source.roles_not_ready_count === "number"
126
+ ? source.roles_not_ready_count : null;
127
+ const reportPath = source.report_path != null ? redact(String(source.report_path)) : null;
128
+ const worktreePath = source.worktree_path != null ? redact(String(source.worktree_path)) : null;
129
+ const actionsExecuted = typeof source.actions_executed === "number"
130
+ ? source.actions_executed : null;
131
+ const executionMode = source.execution_mode != null
132
+ ? String(source.execution_mode) : null;
133
+ const workflowType = source.workflow_type != null
134
+ ? String(source.workflow_type) : null;
135
+ const modelProvider = source.model_provider != null ? redact(String(source.model_provider)) : null;
136
+ const modelId = source.model_id != null ? redact(String(source.model_id)) : null;
137
+ const promptSha256 = source.prompt_sha256 != null ? String(source.prompt_sha256) : null;
138
+ const contextManifest = normalizeContextManifest(source.context_manifest);
139
+ const producedPatchSha256 = source.produced_patch_sha256 != null
140
+ ? String(source.produced_patch_sha256) : null;
141
+ const modelCallCount = typeof source.model_call_count === "number"
142
+ ? source.model_call_count : null;
143
+ const tokensUsed = normalizeTokensUsed(source.tokens_used);
144
+ const canonical = [
145
+ sessionId || "",
146
+ toolkit || "",
147
+ eventType || "",
148
+ command || "",
149
+ runId || "",
150
+ agentRole || "",
151
+ taskId || "",
152
+ timestamp,
153
+ ].join("|");
88
154
 
89
155
  return {
90
156
  event_id: fingerprintId("evt", canonical),
@@ -93,6 +159,26 @@ function buildEvent(raw) {
93
159
  phase: nullableString(source.phase),
94
160
  event_type: eventType,
95
161
  command,
162
+ run_id: runId,
163
+ agent_role: agentRole,
164
+ task_id: taskId,
165
+ feature_key: featureKey,
166
+ stop_condition_hit: stopConditionHit,
167
+ evidence_quality_ok: evidenceQualityOk,
168
+ overall_verdict: overallVerdict,
169
+ roles_not_ready_count: rolesNotReadyCount,
170
+ report_path: reportPath,
171
+ ...(Object.prototype.hasOwnProperty.call(source, "worktree_path") ? { worktree_path: worktreePath } : {}),
172
+ ...(Object.prototype.hasOwnProperty.call(source, "actions_executed") ? { actions_executed: actionsExecuted } : {}),
173
+ ...(Object.prototype.hasOwnProperty.call(source, "execution_mode") ? { execution_mode: executionMode } : {}),
174
+ ...(Object.prototype.hasOwnProperty.call(source, "workflow_type") ? { workflow_type: workflowType } : {}),
175
+ ...(Object.prototype.hasOwnProperty.call(source, "model_provider") ? { model_provider: modelProvider } : {}),
176
+ ...(Object.prototype.hasOwnProperty.call(source, "model_id") ? { model_id: modelId } : {}),
177
+ ...(Object.prototype.hasOwnProperty.call(source, "prompt_sha256") ? { prompt_sha256: promptSha256 } : {}),
178
+ ...(Object.prototype.hasOwnProperty.call(source, "context_manifest") ? { context_manifest: contextManifest } : {}),
179
+ ...(Object.prototype.hasOwnProperty.call(source, "produced_patch_sha256") ? { produced_patch_sha256: producedPatchSha256 } : {}),
180
+ ...(Object.prototype.hasOwnProperty.call(source, "model_call_count") ? { model_call_count: modelCallCount } : {}),
181
+ ...(Object.prototype.hasOwnProperty.call(source, "tokens_used") ? { tokens_used: tokensUsed } : {}),
96
182
  status: normalizeStatus(source.status),
97
183
  cwd: typeof source.cwd === "string" ? redact(source.cwd) : null,
98
184
  files: normalizeFiles(source.files),
@@ -3,8 +3,10 @@
3
3
  const PRIVATE_TAG_PATTERN = /<private>[\s\S]*?<\/private>/gi;
4
4
 
5
5
  const SECRET_PATTERNS = [
6
- /(?:api[_-]?key|secret|token|password|credential|auth)[\s]*[=:]\s*["']?[A-Za-z0-9_\-/.+]{20,}["']?/gi,
7
- /Bearer\s+[A-Za-z0-9._\-+/=]{20,}/gi,
6
+ /-----BEGIN [A-Z ]*(?:PRIVATE KEY|SECRET KEY)[-A-Z ]*-----[\s\S]*?-----END [A-Z ]*(?:PRIVATE KEY|SECRET KEY)[-A-Z ]*-----/g,
7
+ /(?:api[_-]?key|secret|token|password|credential|auth)[\s]*[=:]\s*["']?[A-Za-z0-9_\-/.+]{12,}["']?/gi,
8
+ /(?:[A-Z][A-Z0-9_]{2,}(?:KEY|SECRET|TOKEN|PASSWORD|CREDENTIAL|AUTH))[\s]*=[\s]*["']?[^\s"']{8,}["']?/g,
9
+ /(?:Authorization\s*[:=]\s*)?Bearer\s+[A-Za-z0-9._\-+/=]{20,}/gi,
8
10
  /sk-proj-[A-Za-z0-9\-_]{20,}/g,
9
11
  /(?:sk|pk|rk|ak)-[A-Za-z0-9][A-Za-z0-9\-_]{19,}/g,
10
12
  /sk-ant-[A-Za-z0-9\-_]{20,}/g,
@@ -17,19 +19,40 @@ const SECRET_PATTERNS = [
17
19
  /npm_[A-Za-z0-9]{36}/g,
18
20
  /glpat-[A-Za-z0-9\-_]{20,}/g,
19
21
  /dop_v1_[A-Za-z0-9]{64}/g,
22
+ /\b[A-Za-z0-9+/=_-]{48,}\b/g,
20
23
  ];
21
24
 
25
+ function secretPatternSources() {
26
+ return SECRET_PATTERNS.map((source) => new RegExp(source.source, source.flags));
27
+ }
28
+
29
+ function containsSecretMaterial(input) {
30
+ if (typeof input !== "string" || input.length === 0) {
31
+ return false;
32
+ }
33
+ if (PRIVATE_TAG_PATTERN.test(input)) {
34
+ PRIVATE_TAG_PATTERN.lastIndex = 0;
35
+ return true;
36
+ }
37
+ PRIVATE_TAG_PATTERN.lastIndex = 0;
38
+ for (const pattern of secretPatternSources()) {
39
+ if (pattern.test(input)) {
40
+ return true;
41
+ }
42
+ }
43
+ return false;
44
+ }
45
+
22
46
  function redact(input) {
23
47
  if (typeof input !== "string") {
24
48
  return "";
25
49
  }
26
50
 
27
51
  let result = input.replace(PRIVATE_TAG_PATTERN, "[REDACTED]");
28
- for (const source of SECRET_PATTERNS) {
29
- const pattern = new RegExp(source.source, source.flags);
52
+ for (const pattern of secretPatternSources()) {
30
53
  result = result.replace(pattern, "[REDACTED_SECRET]");
31
54
  }
32
55
  return result;
33
56
  }
34
57
 
35
- module.exports = { redact, SECRET_PATTERNS };
58
+ module.exports = { redact, SECRET_PATTERNS, containsSecretMaterial };