deslop 0.2.0

A static analyzer that spots low-context and AI-assisted code patterns across naming, concurrency, security, performance, and test quality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
#!/usr/bin/env python3
"""Expand deslop findings into code-context review blocks.

This script reads a findings file such as ``temp_gopdfsuit.txt`` and writes a
single consolidated text file to ``scripts/temp.txt``. By default each finding
block includes the file path, rule description, auto-triage note, and code
context. Pass ``--details`` to emit the full metadata-rich block instead.
"""

from __future__ import annotations

import argparse
import json
import re
from collections import Counter, defaultdict
from dataclasses import dataclass
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_INPUT = ROOT / "temp_gopdfsuit.txt"
DEFAULT_OUTPUT = Path(__file__).resolve().parent / "temp.txt"
REGISTRY_PATH = ROOT / "rules" / "registry.json"
FINDING_RE = re.compile(r"^\s*-\s+(.*?):(\d+)\s+(.*?)\s+\[([^\]]+)\]\s*$")
LANGUAGE_BY_SUFFIX = {
    ".go": "go",
    ".py": "python",
    ".rs": "rust",
}
SUBJECTIVE_FAMILIES = {
    "ai_smells",
    "api_design",
    "comments",
    "domain_modeling",
    "duplication",
    "maintainability",
    "mod",
    "module_surface",
    "naming",
    "packaging",
    "quality",
    "structure",
    "style",
    "test_quality",
}
CONTEXT_FAMILIES = {
    "async_patterns",
    "boundary",
    "concurrency",
    "consistency",
    "context",
    "data_access",
    "framework",
    "gin",
    "hot_path",
    "hot_path_ext",
    "idioms",
    "library",
    "mlops",
    "performance",
    "runtime_boundary",
    "runtime_ownership",
}
RISK_FAMILIES = {
    "errors",
    "hallucination",
    "hygiene",
    "security",
    "security_footguns",
    "unsafe_soundness",
}


@dataclass(frozen=True)
class Finding:
    file_path: Path
    line_no: int
    message: str
    rule_id: str
    raw_line: str


@dataclass(frozen=True)
class RuleMetadata:
    rule_id: str
    language: str
    family: str
    default_severity: str
    status: str
    description: str


RuleMetadataById = dict[str, tuple[RuleMetadata, ...]]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "input_file",
        nargs="?",
        default=str(DEFAULT_INPUT),
        help="Path to the deslop findings text file.",
    )
    parser.add_argument(
        "--output",
        default=str(DEFAULT_OUTPUT),
        help="Path to the consolidated output file.",
    )
    parser.add_argument(
        "--context",
        type=int,
        default=1,
        help="How many lines to include above and below the flagged line.",
    )
    parser.add_argument(
        "--review-placeholder",
        default="REVIEW_NEEDED",
        help="Initial value written into the false-positive review field.",
    )
    parser.add_argument(
        "--details",
        action="store_true",
        help="Emit the full metadata-rich finding blocks instead of the compact default view.",
    )
    return parser.parse_args()


def parse_findings(input_path: Path) -> list[Finding]:
    findings: list[Finding] = []
    for raw_line in input_path.read_text(encoding="utf-8").splitlines():
        if not raw_line.lstrip().startswith("- "):
            continue
        match = FINDING_RE.match(raw_line)
        if not match:
            continue
        findings.append(
            Finding(
                file_path=Path(match.group(1)),
                line_no=int(match.group(2)),
                message=match.group(3).strip(),
                rule_id=match.group(4).strip(),
                raw_line=raw_line.strip(),
            )
        )
    return findings


def load_lines(file_path: Path) -> list[str]:
    return file_path.read_text(encoding="utf-8", errors="replace").splitlines()


def _read_rule_metadata() -> RuleMetadataById:
    registry = json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))
    grouped: dict[str, list[RuleMetadata]] = defaultdict(list)

    for item in registry:
        grouped[item["id"]].append(
            RuleMetadata(
                rule_id=item["id"],
                language=item["language"],
                family=item["family"],
                default_severity=item["default_severity"],
                status=item["status"],
                description=item["description"],
            )
        )

    return {
        rule_id: tuple(sorted(variants, key=lambda variant: variant.language))
        for rule_id, variants in grouped.items()
    }


def infer_language(file_path: Path) -> str | None:
    return LANGUAGE_BY_SUFFIX.get(file_path.suffix.lower())


def _rule_variants(rule_id: str, rule_metadata_by_id: RuleMetadataById) -> tuple[RuleMetadata, ...]:
    return rule_metadata_by_id.get(rule_id, ())


def _resolve_rule_metadata(
    finding: Finding,
    rule_metadata_by_id: RuleMetadataById,
) -> RuleMetadata | None:
    variants = _rule_variants(finding.rule_id, rule_metadata_by_id)
    inferred_language = infer_language(finding.file_path)
    return next(
        (variant for variant in variants if variant.language == inferred_language),
        variants[0] if variants else None,
    )


def _summarize_rule_metadata(
    rule_id: str,
    rule_metadata_by_id: RuleMetadataById,
) -> tuple[str, str, str, str, str]:
    variants = _rule_variants(rule_id, rule_metadata_by_id)
    if not variants:
        return (
            "unknown",
            "unknown",
            "unknown",
            "unknown",
            "Rule metadata not found in rules/registry.json.",
        )

    first = variants[0]
    languages = ", ".join(variant.language for variant in variants)
    return (
        first.family,
        first.default_severity,
        first.status,
        languages,
        first.description,
    )


def _build_rule_inventory_summary(
    findings: list[Finding],
    rule_metadata_by_id: RuleMetadataById,
) -> str:
    rule_counts = Counter(finding.rule_id for finding in findings)
    rule_summaries = {
        rule_id: _summarize_rule_metadata(rule_id, rule_metadata_by_id)
        for rule_id in rule_counts
    }
    families = {summary[0] for summary in rule_summaries.values()}
    family_finding_counts = Counter(
        {
            family: sum(
                count
                for rule_id, count in rule_counts.items()
                if rule_summaries[rule_id][0] == family
            )
            for family in families
        }
    )
    family_rule_counts = Counter(summary[0] for summary in rule_summaries.values())
    missing_rule_ids = sorted(
        rule_id for rule_id, summary in rule_summaries.items() if summary[0] == "unknown"
    )

    lines = [
        "Rule inventory:",
        f"- Registry unique rule ids: {len(rule_metadata_by_id)}",
        f"- Registry language-scoped rules: {sum(len(variants) for variants in rule_metadata_by_id.values())}",
        f"- Rule ids in findings: {len(rule_counts)}",
        f"- Rule ids missing from registry: {len(missing_rule_ids)}",
        "",
        "Family summary:",
    ]

    lines.extend(
        f"- {family} | findings={count} | rules={family_rule_counts[family]}"
        for family, count in sorted(
            family_finding_counts.items(),
            key=lambda item: (-item[1], item[0]),
        )
    )

    if missing_rule_ids:
        lines.extend(
            [
                "",
                "Registry gaps:",
                *[f"- {rule_id}" for rule_id in missing_rule_ids],
            ]
        )

    lines.extend(["", "Rule summary:"])
    lines.extend(
        (
            f"- {rule_id} | findings={count} | family={family} | severity={severity} "
            f"| status={status} | languages={languages} | description={description}"
        )
        for rule_id, count in sorted(rule_counts.items(), key=lambda item: (-item[1], item[0]))
        for family, severity, status, languages, description in [rule_summaries[rule_id]]
    )

    lines.append("")
    return "\n".join(lines)


def _build_context_block(
    finding: Finding,
    lines: list[str],
    rule_metadata_by_id: RuleMetadataById,
    *,
    context: int,
    index: int,
    total: int,
    review_placeholder: str,
    details: bool,
) -> str:
    start_line = max(1, finding.line_no - context)
    end_line = min(len(lines), finding.line_no + context)
    width = max(4, len(str(end_line)))
    rule_metadata = _resolve_rule_metadata(finding, rule_metadata_by_id)
    auto_triage, auto_reason = _triage_finding(
        finding,
        lines,
        start_line,
        end_line,
        rule_metadata,
    )
    family, severity, status, languages, description = _summarize_rule_metadata(
        finding.rule_id,
        rule_metadata_by_id,
    )

    block_lines = ["=" * 100, f"Finding {index}/{total}"]
    if details:
        block_lines.extend(
            [
                f"Source: {finding.file_path}:{finding.line_no}",
                f"Rule: [{finding.rule_id}]",
                f"Rule family: [{family}]",
                f"Rule severity: [{severity}]",
                f"Rule status: [{status}]",
                f"Rule languages: [{languages}]",
                f"Rule description: {description}",
                f"Message: {finding.message}",
                f"Suspect range: [{start_line}-{end_line}]",
                f"Auto triage: [{auto_triage}]",
                f"Auto triage note: {auto_reason}",
                f"False positive: [{review_placeholder}]",
                f"Original finding: {finding.raw_line}",
                "Code:",
            ]
        )
    else:
        block_lines.extend(
            [
                f"Source: {finding.file_path}:{finding.line_no}",
                f"Rule: [{finding.rule_id}]",
                f"Rule description: {description}",
                f"Auto triage note: {auto_reason}",
                "Code:",
            ]
        )

    block_lines.extend(
        f'{">>" if line_number == finding.line_no else "  "} {line_number:>{width}} | {lines[line_number - 1]}'
        for line_number in range(start_line, end_line + 1)
    )

    block_lines.append("")
    return "\n".join(block_lines)


def _build_missing_file_block(
    finding: Finding,
    rule_metadata_by_id: RuleMetadataById,
    *,
    index: int,
    total: int,
    review_placeholder: str,
    details: bool,
) -> str:
    rule_metadata = _resolve_rule_metadata(finding, rule_metadata_by_id)
    auto_triage, auto_reason = _triage_finding(
        finding,
        [],
        finding.line_no,
        finding.line_no,
        rule_metadata,
    )
    family, severity, status, languages, description = _summarize_rule_metadata(
        finding.rule_id,
        rule_metadata_by_id,
    )
    block_lines = ["=" * 100, f"Finding {index}/{total}"]
    if details:
        block_lines.extend(
            [
                f"Source: {finding.file_path}:{finding.line_no}",
                f"Rule: [{finding.rule_id}]",
                f"Rule family: [{family}]",
                f"Rule severity: [{severity}]",
                f"Rule status: [{status}]",
                f"Rule languages: [{languages}]",
                f"Rule description: {description}",
                f"Message: {finding.message}",
                f"Auto triage: [{auto_triage}]",
                f"Auto triage note: {auto_reason}",
                f"False positive: [{review_placeholder}]",
                f"Original finding: {finding.raw_line}",
                "Code: [FILE_NOT_FOUND]",
            ]
        )
    else:
        block_lines.extend(
            [
                f"Rule description: {description}",
                f"Auto triage note: {auto_reason}",
                "Code: [FILE_NOT_FOUND]",
            ]
        )
    block_lines.append("")
    return "\n".join(block_lines)


def write_output(
    findings: list[Finding],
    input_path: Path,
    output_path: Path,
    *,
    context: int,
    review_placeholder: str,
    details: bool,
) -> None:
    total_findings = len(findings)
    rule_metadata_by_id = _read_rule_metadata()
    cached_files: dict[Path, list[str]] = {}
    blocks = [
        f"Input file: {input_path}",
        f"Output file: {output_path}",
        f"Total findings parsed: {total_findings}",
        f"Context window: +/- {context} lines",
    ]
    if details:
        blocks.extend(["", _build_rule_inventory_summary(findings, rule_metadata_by_id)])

    for index, finding in enumerate(findings, start=1):
        if not finding.file_path.exists():
            blocks.append(
                _build_missing_file_block(
                    finding,
                    rule_metadata_by_id,
                    index=index,
                    total=total_findings,
                    review_placeholder=review_placeholder,
                    details=details,
                )
            )
            continue

        if finding.file_path not in cached_files:
            cached_files[finding.file_path] = load_lines(finding.file_path)

        blocks.append(
            _build_context_block(
                finding,
                cached_files[finding.file_path],
                rule_metadata_by_id,
                context=context,
                index=index,
                total=total_findings,
                review_placeholder=review_placeholder,
                details=details,
            )
        )

    output_path.parent.mkdir(parents=True, exist_ok=True)
    if output_path.exists():
        output_path.unlink()
    output_path.write_text("\n".join(blocks), encoding="utf-8")


def _triage_len_empty(current_line: str) -> tuple[str, str]:
    collection_hints = (
        "parts",
        "items",
        "files",
        "rows",
        "entries",
        "fonts",
        "pages",
        "results",
        "matches",
        "tokens",
        "children",
        "values",
    )
    if any(hint in current_line for hint in collection_hints):
        return (
            "LIKELY_FALSE_POSITIVE",
            "The flagged len(...) check appears to target a collection rather than a string empty-check.",
        )
    return (
        "CONTEXT_DEPENDENT",
        "This may be style-only or incorrect depending on the type of the value passed to len(...).",
    )


def _triage_by_metadata(rule_metadata: RuleMetadata | None) -> tuple[str, str]:
    if rule_metadata is None:
        return (
            "REVIEW_NEEDED",
            "No safe automatic classification was inferred from the local code context alone.",
        )

    experimental_note = (
        " The rule is marked experimental in the registry, so keep a slightly higher false-positive bar."
        if rule_metadata.status == "experimental"
        else ""
    )

    if rule_metadata.family in SUBJECTIVE_FAMILIES:
        return (
            "LIKELY_SUBJECTIVE",
            f"Registry metadata classifies this as {rule_metadata.family} guidance with {rule_metadata.default_severity} severity, so whether it matters depends on project conventions.{experimental_note}",
        )

    if rule_metadata.family in CONTEXT_FAMILIES or rule_metadata.default_severity == "contextual":
        return (
            "CONTEXT_DEPENDENT",
            f"Registry metadata classifies this as {rule_metadata.family} with {rule_metadata.default_severity} severity, so runtime path, workload, and surrounding design matter before treating it as actionable.{experimental_note}",
        )

    if rule_metadata.family in RISK_FAMILIES or rule_metadata.default_severity in {"warning", "error"}:
        return (
            "LIKELY_REAL",
            f"Registry metadata classifies this as {rule_metadata.family} with {rule_metadata.default_severity} severity, which usually maps to correctness, security, or production risk.{experimental_note}",
        )

    if rule_metadata.default_severity == "info":
        return (
            "LIKELY_SUBJECTIVE",
            f"Registry metadata marks this as info-level guidance; treat it as a review prompt rather than a clear defect.{experimental_note}",
        )

    return (
        "REVIEW_NEEDED",
        "No safe automatic classification was inferred from the local code context alone.",
    )


def _triage_finding(
    finding: Finding,
    lines: list[str],
    start_line: int,
    end_line: int,
    rule_metadata: RuleMetadata | None,
) -> tuple[str, str]:
    context_lines = lines[start_line - 1 : end_line] if lines else []
    context_text = "\n".join(context_lines).lower()
    search_start = max(0, finding.line_no - 26)
    search_end = min(len(lines), finding.line_no + 5)
    extended_text = "\n".join(lines[search_start:search_end]).lower() if lines else ""
    current_line = lines[finding.line_no - 1].strip() if lines and 0 < finding.line_no <= len(lines) else ""

    if finding.rule_id == "cgo_string_lifetime" and "caller must free" in (context_text + "\n" + extended_text):
        return (
            "LIKELY_FALSE_POSITIVE",
            "Nearby comments suggest the API intentionally transfers ownership of the allocated C string to the caller.",
        )

    if finding.rule_id == "len_string_for_empty_check":
        return _triage_len_empty(current_line)

    return _triage_by_metadata(rule_metadata)


def main() -> int:
    args = parse_args()
    input_path = Path(args.input_file).expanduser().resolve()
    output_path = Path(args.output).expanduser().resolve()

    findings = parse_findings(input_path)
    if not findings:
        raise SystemExit(f"no findings matched the expected format in {input_path}")

    write_output(
        findings,
        input_path,
        output_path,
        context=max(0, args.context),
        review_placeholder=args.review_placeholder,
        details=args.details,
    )

    print(f"Wrote {len(findings)} finding blocks to {output_path}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())