Skip to content

Commit dccfa52

Browse files
steipetePeter Steinberger
andauthored
refactor: decompose clawsweeper entrypoint into focused subsystems (#1005)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent f43618f commit dccfa52

17 files changed

Lines changed: 16292 additions & 12058 deletions

‎src/clawsweeper-apply-decision-workflow.ts‎

Lines changed: 4091 additions & 0 deletions
Large diffs are not rendered by default.

‎src/clawsweeper-command-operations.ts‎

Lines changed: 935 additions & 0 deletions
Large diffs are not rendered by default.

‎src/clawsweeper-context-hydration.ts‎

Lines changed: 1150 additions & 0 deletions
Large diffs are not rendered by default.

‎src/clawsweeper-dashboard-audit.ts‎

Lines changed: 968 additions & 0 deletions
Large diffs are not rendered by default.

‎src/clawsweeper-item-context.ts‎

Lines changed: 424 additions & 0 deletions
Large diffs are not rendered by default.

‎src/clawsweeper-report-helpers.ts‎

Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
1+
import { SECURITY_CONCERN_SEVERITIES } from "./clawsweeper-policy.js";
2+
import type {
3+
AgentsPolicyStatus,
4+
ReviewFinding,
5+
SecurityConcernSeverity,
6+
} from "./clawsweeper-types.js";
7+
8+
interface CreateReportHelpersDependencies {
9+
OWNED_REVIEW_SECTION_HEADINGS: Set<string>;
10+
parseBacktickLocation: (
11+
value: string,
12+
) => { file: string; lineStart: number; lineEnd: number } | null;
13+
}
14+
15+
export function createReportHelpers(dependencies: CreateReportHelpersDependencies) {
16+
const { OWNED_REVIEW_SECTION_HEADINGS, parseBacktickLocation } = dependencies;
17+
18+
function parseBoldListHeading(line: string): { label: string; detail: string } | null {
19+
const prefix = "- **";
20+
if (!line.startsWith(prefix)) return null;
21+
const delimiter = ":**";
22+
const delimiterIndex = line.indexOf(delimiter, prefix.length);
23+
if (delimiterIndex === -1) return null;
24+
return {
25+
label: line.slice(prefix.length, delimiterIndex),
26+
detail: line.slice(delimiterIndex + delimiter.length).trimStart(),
27+
};
28+
}
29+
30+
function parseReviewFindingHeading(line: string): {
31+
priority: ReviewFinding["priority"];
32+
title: string;
33+
file: string;
34+
lineStart: number;
35+
lineEnd: number;
36+
} | null {
37+
const prefix = "- **[P";
38+
if (!line.startsWith(prefix)) return null;
39+
const priority = Number(line[prefix.length]);
40+
if (!Number.isInteger(priority) || priority < 0 || priority > 3) return null;
41+
const titleStart = prefix.length + 3;
42+
if (line.slice(prefix.length + 1, titleStart) !== "] ") return null;
43+
const titleEnd = line.indexOf(":**", titleStart);
44+
if (titleEnd === -1) return null;
45+
46+
const location = parseBacktickLocation(line.slice(titleEnd + 3).trim());
47+
if (!location) return null;
48+
return {
49+
priority: priority as ReviewFinding["priority"],
50+
title: line.slice(titleStart, titleEnd),
51+
...location,
52+
};
53+
}
54+
55+
function parseSecurityConcernHeading(line: string): {
56+
severity: SecurityConcernSeverity;
57+
title: string;
58+
file: string | null;
59+
line: number | null;
60+
} | null {
61+
const prefix = "- **[";
62+
if (!line.startsWith(prefix)) return null;
63+
const severityEnd = line.indexOf("] ", prefix.length);
64+
if (severityEnd === -1) return null;
65+
const severity = line.slice(prefix.length, severityEnd);
66+
if (!SECURITY_CONCERN_SEVERITIES.has(severity as SecurityConcernSeverity)) return null;
67+
const titleStart = severityEnd + 2;
68+
const titleEnd = line.indexOf(":**", titleStart);
69+
if (titleEnd === -1) return null;
70+
71+
const locationText = line.slice(titleEnd + 3).trim();
72+
const location = locationText ? parseBacktickLocation(locationText) : null;
73+
return {
74+
severity: severity as SecurityConcernSeverity,
75+
title: line.slice(titleStart, titleEnd),
76+
file: location?.file ?? null,
77+
line: location?.lineStart ?? null,
78+
};
79+
}
80+
81+
function sectionLineValue(section: string, label: string): string | undefined {
82+
const prefix = `${label}:`;
83+
for (const line of section.split("\n")) {
84+
if (line.startsWith(prefix)) {
85+
const value = line.slice(prefix.length).trim();
86+
return value || undefined;
87+
}
88+
}
89+
return undefined;
90+
}
91+
92+
function sectionList(section: string, label: string): string[] {
93+
const lines = section.split("\n");
94+
const start = lines.findIndex((line) => line.trim() === `${label}:`);
95+
if (start === -1) return [];
96+
const values: string[] = [];
97+
for (let index = start + 1; index < lines.length; index += 1) {
98+
const line = lines[index]!;
99+
if (/^[A-Z][A-Za-z -]+:/.test(line)) break;
100+
const trimmed = line.trimStart();
101+
if (!trimmed.startsWith("- ")) continue;
102+
const item = trimmed.slice(2).trim();
103+
if (item) values.push(item);
104+
}
105+
return values;
106+
}
107+
108+
function agentsPolicyStatusLine(status: AgentsPolicyStatus | undefined): string {
109+
switch (status?.status) {
110+
case "found_applied":
111+
return "AGENTS.md: found and applied where relevant.";
112+
case "found_not_applicable":
113+
return "AGENTS.md: found, but no applicable review policy affected this item.";
114+
case "not_found":
115+
return "AGENTS.md: not found in the target repository.";
116+
case "conflict_not_applied":
117+
return "AGENTS.md: found but not applied because it conflicted with ClawSweeper's review contract.";
118+
case "unreadable_or_unclear":
119+
return "AGENTS.md: unclear because the file could not be read completely.";
120+
default:
121+
return "";
122+
}
123+
}
124+
125+
function publicTableCell(value: string): string {
126+
// Escape report-provided HTML (tags and comment openers) before inserting the
127+
// renderer-owned <br> tags; &lt; renders identically to a literal <.
128+
return value
129+
.replace(/\\/g, "\\\\")
130+
.replace(/<(?=[a-z/!?])/gi, "&lt;")
131+
.replace(/\r?\n|\r/g, "<br>")
132+
.replace(/\|/g, "\\|")
133+
.trim();
134+
}
135+
136+
function neutralizeOwnedSectionSpoofing(value: string): string {
137+
// GitHub normalizes CRLF and bare CR to line endings, so normalize first or a
138+
// bare-CR line break could smuggle a heading past the per-line checks.
139+
return value
140+
.replace(/\r\n?/g, "\n")
141+
.split("\n")
142+
.map((line) => {
143+
// Strip blockquote/list container prefixes so nested heading constructs are
144+
// neutralized too.
145+
// CommonMark accepts blockquotes without a following space and ordered lists
146+
// with either "1." or "1)".
147+
const containerPrefix =
148+
line.match(/^[ \t]*(?:(?:>|(?:[-*+]|\d+[.)])[ \t])[ \t]*)*/)?.[0] ?? "";
149+
// Escape every raw HTML delimiter (renderer-emitted <br> excepted) so inline
150+
// tags and comment openers cannot restructure or hide trusted sections;
151+
// &lt; renders identically to a literal <.
152+
const content = line.slice(containerPrefix.length).replace(/<(?!br\s*\/?>)/gi, "&lt;");
153+
const trimmed = content.trim();
154+
if (/^#{1,6}\s+\S/.test(trimmed)) {
155+
return `${containerPrefix}${content.replace("#", "\\#")}`;
156+
}
157+
if (/^\*\*[^*\n]+\*\*:?\s*$/.test(trimmed)) {
158+
return `${containerPrefix}${content.replace("**", "\\*\\*")}`;
159+
}
160+
if (/^(?:```|~~~)/.test(trimmed)) {
161+
return `${containerPrefix}${content.replace(/[`~]/, "\\$&")}`;
162+
}
163+
// A run of = or - alone on a line is a Setext underline that would promote the
164+
// previous line to a heading.
165+
if (/^(?:=+|-+)[ \t]*$/.test(trimmed)) {
166+
return `${containerPrefix}${content.replace(/[=-]/, "\\$&")}`;
167+
}
168+
if (
169+
trimmed.endsWith(":") &&
170+
OWNED_REVIEW_SECTION_HEADINGS.has(trimmed.slice(0, -1).trim().toLowerCase())
171+
) {
172+
return `${containerPrefix}${content.trimEnd().slice(0, -1)}&#58;`;
173+
}
174+
return `${containerPrefix}${content}`;
175+
})
176+
.join("\n");
177+
}
178+
179+
function sanitizeArchitectureDiagram(value: string): string {
180+
const diagram = value.trim();
181+
if (!diagram || diagram.length > 4000) return "";
182+
if (!/^flowchart\b/i.test(diagram)) return "";
183+
// No fence-breaking backticks, node metadata (image/icon nodes), HTML tags, init
184+
// directives, or URLs of any form, including scheme-relative and data: URLs.
185+
if (diagram.includes("`") || diagram.includes("~~~") || diagram.includes("@{")) return "";
186+
if (/<[a-z!/]/i.test(diagram)) return "";
187+
// Heading-shaped lines could terminate the report section the diagram is
188+
// serialized into; Mermaid flowcharts never need a leading #.
189+
if (/^[ \t]*#/m.test(diagram)) return "";
190+
if (/%%\{/.test(diagram)) return "";
191+
if (diagram.includes("//")) return "";
192+
// Require a non-space after the colon so human-readable labels such as
193+
// "Data: PR input" are not mistaken for data:/file: URLs.
194+
if (/\b(?:data|javascript|vbscript|https?|ftp|file|blob|mailto):\S/i.test(diagram)) return "";
195+
// The declaration line must be exactly "flowchart <direction>" so no further
196+
// statement can hide after it on the same line.
197+
const declarationLine = diagram.split(/\r?\n/, 1)[0] ?? "";
198+
if (!/^flowchart[ \t]+(?:LR|RL|TB|BT|TD)[ \t]*;?[ \t]*$/i.test(declarationLine)) return "";
199+
// Interaction and styling directives start a statement (newline- or
200+
// semicolon-separated); the same words are fine inside human-readable node labels.
201+
for (const statement of diagram.split(/[;\r\n]+/)) {
202+
if (/^\s*(?:click|style|classDef|class|linkStyle)\b/i.test(statement)) return "";
203+
}
204+
// Directive shapes are also rejected mid-line, where Mermaid can begin a new
205+
// statement without a separator.
206+
if (/\bclick[ \t]+[\w-]+[ \t]+(?:href|call)\b/i.test(diagram)) return "";
207+
if (/\b(?:style|linkStyle)[ \t]+[\w-]+[ \t]+[\w-]+[ \t]*:/i.test(diagram)) return "";
208+
if (/\bclassDef[ \t]+[\w-]+[ \t]+[\w-]+[ \t]*:/i.test(diagram)) return "";
209+
return diagram;
210+
}
211+
212+
return {
213+
agentsPolicyStatusLine,
214+
neutralizeOwnedSectionSpoofing,
215+
parseBoldListHeading,
216+
parseReviewFindingHeading,
217+
parseSecurityConcernHeading,
218+
publicTableCell,
219+
sanitizeArchitectureDiagram,
220+
sectionLineValue,
221+
sectionList,
222+
};
223+
}

0 commit comments

Comments
 (0)