From d6940e6672abcd0d1d2f5c12a4df512aef48e29d Mon Sep 17 00:00:00 2001 From: Matt Van Horn Date: Wed, 18 Nov 2026 18:26:17 +0000 Subject: [PATCH 1/4] fix(security): show where SkillSpector parse limits apply in incomplete scans Incomplete SkillSpector scans dropped parser_diagnostic on static_parse_limit rows, so JavaScript helpers showed no span, cause, or check. Label those rows from a well-formed diagnostic, keep a bounded copy in skillspector_completeness, and hint when every parse-limit row is runtime_dependent. The security check stays INCOMPLETE. Signed-off-by: Matt Van Horn --- CHANGELOG.md | 5 + docs/tier1-reference.mdx | 22 +- .../skillspector_diagnostics.py | 27 + src/skillevaluator/skillspector_references.py | 38 +- src/skillevaluator/validators/security.py | 69 +- ...2.13.4-mjs-runtime-parse-limit-no-llm.json | 658 ++++++++++++++++++ tests/reporting/test_tier3_validate_cases.py | 20 + .../test_skillspector_diagnostics.py | 75 ++ .../test_skillspector_hook_surface.py | 5 +- .../test_skillspector_parser_locations.py | 211 ++++++ ...test_skillspector_reference_diagnostics.py | 131 ++++ 11 files changed, 1248 insertions(+), 13 deletions(-) create mode 100644 tests/fixtures/skillspector-2.13.4-mjs-runtime-parse-limit-no-llm.json create mode 100644 tests/validators/test_skillspector_parser_locations.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d14f2557..8e547df9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,11 @@ All notable changes to SkillEvaluator are documented in this file. environment secrets. Existing consumers keep deployment tracking by default. - Point the PyPI Documentation link at the NVIDIA documentation instead of the GitHub README, starting with the next release. Published 1.0.1 metadata is unchanged. +- Incomplete SkillSpector scans now quote the parser span, cause, and check from + `parser_diagnostic` on `static_parse_limit` rows that have no line of their own, + keep a bounded copy of that diagnostic in `skillspector_completeness`, and, when + every such row is `runtime_dependent`, explain that SkillSpector could not resolve + a command or code string known only at run time. The check stays `INCOMPLETE`. ## 1.0.1 - 2026-11-17 diff --git a/docs/tier1-reference.mdx b/docs/tier1-reference.mdx index 7ae38b61a..fab0a2c00 100644 --- a/docs/tier1-reference.mdx +++ b/docs/tier1-reference.mdx @@ -941,6 +941,26 @@ Tier 1 checks always gate the exit code inside `validate`. Tier 2 gates when it SkillSpector releases before v2.13.1 can stop inspecting a valid Python or Perl helper early and record a `static_parse_limit`, `obfuscated_instruction_text`, or `runtime_limit` ledger exception. The security check is then `INCOMPLETE`, often with a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names the helper. The finding's suggestion names the helper and the reason, such as `static_parse_limit (static_patterns_tool_misuse)`. Check the resolved release with `skillevaluator doctor --tier 1` and follow [scanner setup](/skills/skillevaluator/installation-options#system-tools) to update an older installation. If the exception remains after the upgrade, investigate it like any other incomplete scan. + + SkillSpector 2.13.4 through 2.13.6 can stop inspecting a JavaScript helper + (`.js`, `.mjs`, `.cjs`) or another script when a command or code string is + only known at run time, for example `spawnSync(process.execPath, [helper, + ...process.argv.slice(2)])`. It records a `static_parse_limit` ledger + exception whose `start_line` is empty and whose `parser_diagnostic` names + the span, `cause` (`runtime_dependent`), and `check` + (`command_string_runtime`). The security check stays `INCOMPLETE`. The + error now labels that row as `scripts/helper.mjs:74-170 [static; + static_parse_limit; runtime_dependent command_string_runtime; + analyzers=static_patterns_tool_misuse]` and adds a short hint to review + those lines and prefer fixed argument lists. Updating SkillSpector does + not clear this limit today. If the helper is valid and the command is + safe, report a minimal reproducer to SkillSpector. JSON reports keep a + bounded `parser_diagnostic` on the matching + `skillspector_completeness` row (`cause`, `check`, `start_line`, + `end_line`, `unchecked_scope`, `full_input_checked`; never source text or + byte offsets). These diagnostics never turn an incomplete scan into a + pass. + With SkillSpector v2.12.0 and later, a skill, folder or hooks-only plugin with an ordinary command or HTTP hook fails the security check with the @@ -976,7 +996,7 @@ Tier 1 checks always gate the exit code inside `validate`. Tier 2 gates when it SkillSpector v2.13.4 also reads a hook's `"timeout"` key as a command wrapper it cannot resolve and records - `hooks/hooks.json [static; static_parse_limit; analyzers=static_patterns_tool_misuse]`. + `hooks/hooks.json:11 [static; static_parse_limit; boundary_unresolved command_word_boundary; analyzers=static_patterns_tool_misuse]`. That row is an ordinary analysis gap, so with v2.13.4 the SkillSpector scan of such a manifest is also recorded as incomplete (`incomplete_scans` in the JSON report, and publication eligibility **Incomplete**), with an diff --git a/src/skillevaluator/skillspector_diagnostics.py b/src/skillevaluator/skillspector_diagnostics.py index 1783cef6c..f62ae2efb 100644 --- a/src/skillevaluator/skillspector_diagnostics.py +++ b/src/skillevaluator/skillspector_diagnostics.py @@ -27,6 +27,30 @@ def _count(value: object) -> int: return value if type(value) is int and 0 <= value <= 1_000_000_000 else 0 +def _line_number(value: object) -> int | None: + return value if type(value) is int and 0 < value <= 1_000_000_000 else None + + +def parser_diagnostic_record(value: object) -> dict | None: + """Project ``parser_diagnostic`` without source text or byte offsets.""" + if not isinstance(value, dict): + return None + item: dict = {} + for key in ("cause", "check", "unchecked_scope"): + raw = value.get(key) + if isinstance(raw, str) and raw.strip(): + item[key] = _text(raw) + start = _line_number(value.get("start_line")) + end = _line_number(value.get("end_line")) + if start is not None and end is not None and end >= start: + item["start_line"] = start + item["end_line"] = end + checked = value.get("full_input_checked") + if type(checked) is bool: + item["full_input_checked"] = checked + return item or None + + def completeness_record(completeness: dict, stage: str) -> dict: """Project only diagnostic fields; do not copy arbitrary scanner payloads.""" rows = completeness.get("ledger_exceptions") @@ -45,6 +69,9 @@ def completeness_record(completeness: dict, stage: str) -> dict: if isinstance(analyzers, list): item["analyzers"] = [_text(value) for value in analyzers[:8]] item["omitted_analyzers"] = max(0, len(analyzers) - 8) + _count(row.get("omitted_analyzers")) + diagnostic = parser_diagnostic_record(row.get("parser_diagnostic")) + if diagnostic is not None: + item["parser_diagnostic"] = diagnostic exceptions.append(item) return { "stage": stage if isinstance(stage, str) and stage in {"skillspector", "skillspector-llm"} else "unknown", diff --git a/src/skillevaluator/skillspector_references.py b/src/skillevaluator/skillspector_references.py index c2c415854..51e5ebc86 100644 --- a/src/skillevaluator/skillspector_references.py +++ b/src/skillevaluator/skillspector_references.py @@ -71,6 +71,9 @@ # must stay the same across runs, so it shows only the limits that the file and # the configuration fix; the finding's metadata keeps every limit. _RUN_DEPENDENT_LIMITS = frozenset(field for field, seconds in _LIMIT_FIELDS if seconds) +# Set on a reason only while building the suggestion, then dropped. A row's own +# end_line stays in metadata and must not change grouping or finding IDs. +_PARSER_SPAN = "_parser_span" def diagnostic_text(value: object, *, max_length: int = 4096) -> str | None: @@ -192,6 +195,15 @@ def _reasons(rows: object, text: Callable[..., str | None]) -> list[dict]: for field in ("start_line", "end_line"): if (line := _line(row.get(field))) is not None: reason[field] = line + if "start_line" not in reason: + diagnostic = row.get("parser_diagnostic") + if isinstance(diagnostic, dict): + start = _line(diagnostic.get("start_line")) + end = _line(diagnostic.get("end_line")) + if start is not None and end is not None and end >= start: + reason["start_line"] = start + reason["end_line"] = end + reason[_PARSER_SPAN] = True metrics = row.get("limits") if isinstance(metrics, dict): limits = {} @@ -348,22 +360,35 @@ def _reason_details(reasons: list[dict]) -> list[str]: The run time and the time budget (``observed_seconds``, ``limit_seconds``) are left out, so the text, and the ``finding_id`` that hashes it, is the - same in every run of one scan. + same in every run of one scan. A ``parser_diagnostic`` span is part of that + text; an ``end_line`` that was already on the row is not. """ grouped: dict[tuple, list[str]] = {} for reason in reasons: limits = sorted( (key, value) for key, value in (reason.get("limits") or {}).items() if key not in _RUN_DEPENDENT_LIMITS ) - key = (reason["reason_code"], reason.get("start_line"), reason.get("message"), tuple(limits)) + start_line = reason.get("start_line") + parser_end = reason.get("end_line") if reason.get(_PARSER_SPAN) is True else None + if parser_end == start_line: + parser_end = None + key = ( + reason["reason_code"], + start_line, + parser_end, + reason.get("message"), + tuple(limits), + ) analyzers = grouped.setdefault(key, []) analyzers.extend(name for name in reason.get("analyzers", []) if name not in analyzers) details = [] - for (reason_code, start_line, message, limits), analyzers in grouped.items(): + for (reason_code, start_line, parser_end, message, limits), analyzers in grouped.items(): detail = reason_code if analyzers: detail += f" ({', '.join(analyzers)})" - if start_line: + if reason_code == "static_parse_limit" and start_line and parser_end: + detail += f" at target lines {start_line}-{parser_end}" + elif start_line: detail += f" at target line {start_line}" if message: detail += f": {message.rstrip('.')}" @@ -405,7 +430,10 @@ def reference_suggestion( "`--format json` and review the rows for this file in " "`analysis_completeness.ledger_exceptions`, then address every limitation before rerunning the scan." ) - return " ".join([summary, *_reason_details(reasons), action]) + details = _reason_details(reasons) + for reason in reasons: + reason.pop(_PARSER_SPAN, None) + return " ".join([summary, *details, action]) def reference_summary(findings: Iterable[object]) -> dict | None: diff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.py index feebf9b19..6a259b6e0 100644 --- a/src/skillevaluator/validators/security.py +++ b/src/skillevaluator/validators/security.py @@ -1161,13 +1161,42 @@ def _skillspector_report_text(value: object) -> str | None: return text or None +def _skillspector_parser_diagnostic_span(diagnostic: object) -> tuple[int, int] | None: + """Inclusive ``(start, end)`` from a well-formed ``parser_diagnostic``, else ``None``.""" + if not isinstance(diagnostic, Mapping): + return None + start = diagnostic.get("start_line") + end = diagnostic.get("end_line") + if type(start) is not int or type(end) is not int: + return None + if not 0 < start <= end <= 1_000_000_000: + return None + return start, end + + +def _skillspector_parser_diagnostic_context(exception: Mapping[str, object]) -> str | None: + """Sanitized ``cause check`` text for a ``static_parse_limit`` row, else ``None``.""" + if exception.get("reason_code") != "static_parse_limit": + return None + diagnostic = exception.get("parser_diagnostic") + if not isinstance(diagnostic, Mapping): + return None + parts = [text for key in ("cause", "check") if (text := _skillspector_report_text(diagnostic.get(key)))] + return " ".join(parts) or None + + def _skillspector_ledger_exception_label(exception: Mapping[str, object]) -> str: - """Describe one ledger exception as ``path[:line] [phase; reason; analyzers=...]``.""" + """Describe one ledger exception as ``path[:line[-end]] [phase; reason; cause check; analyzers=...]``.""" location = _skillspector_report_text(exception.get("path")) or "unknown" start_line = exception.get("start_line") if isinstance(start_line, int) and not isinstance(start_line, bool): location = f"{location}:{start_line}" + elif (span := _skillspector_parser_diagnostic_span(exception.get("parser_diagnostic"))) is not None: + start, end = span + location = f"{location}:{start}" if start == end else f"{location}:{start}-{end}" context = [text for key in ("phase", "reason_code") if (text := _skillspector_report_text(exception.get(key)))] + if extra := _skillspector_parser_diagnostic_context(exception): + context.append(extra) analyzers = exception.get("analyzers") if isinstance(analyzers, list) and ( analyzer_text := _skillspector_report_text(",".join(name for name in analyzers if isinstance(name, str))) @@ -1236,10 +1265,31 @@ def _skillspector_runtime_limit_hint(ledger_exceptions: Iterable[Mapping[str, ob "Missing references require a standalone target with complete, matching reference and scan evidence. " "See https://docs.nvidia.com/skills/skillevaluator/tier1-validation." ) +_SKILLSPECTOR_PARSE_LIMIT_HINT = ( + "SkillSpector could not resolve a command or code string that is only known at run time " + "(for example a process spawn whose arguments come from variables), in the reported lines. " + "Review those lines, prefer fixed argument lists, and if the code is valid and safe report a " + "minimal reproducer to SkillSpector; updating SkillSpector does not clear this limit today." +) + + +def _skillspector_parse_limit_hint(ledger_exceptions: Iterable[Mapping[str, object]]) -> str | None: + """Explain ``runtime_dependent`` parse limits, or ``None`` when that is not every parse-limit row.""" + parse_limit_rows = [row for row in ledger_exceptions if row.get("reason_code") == "static_parse_limit"] + if not parse_limit_rows: + return None + for row in parse_limit_rows: + diagnostic = row.get("parser_diagnostic") + if not isinstance(diagnostic, Mapping): + return None + cause = diagnostic.get("cause") + if not isinstance(cause, str) or cause.strip() != "runtime_dependent": + return None + return _SKILLSPECTOR_PARSE_LIMIT_HINT def _skillspector_incomplete_analysis_error(status: str, ledger_exceptions: list[dict]) -> str: - """Describe a partial SkillSpector analysis with example gaps and, for runtime limits, a remedy.""" + """Describe a partial SkillSpector analysis with example gaps and, where known, a remedy.""" message = f"skillspector JSON field 'analysis_completeness' reports incomplete analysis (status '{status}')" if ledger_exceptions: shown = ledger_exceptions[:_SKILLSPECTOR_INCOMPLETE_EXAMPLES] @@ -1252,10 +1302,17 @@ def _skillspector_incomplete_analysis_error(status: str, ledger_exceptions: list f"(incomplete files by reason: {_skillspector_incomplete_files_by_reason(ledger_exceptions)})" ) message = f"{message}; security scan did not complete" - hint = _skillspector_runtime_limit_hint(ledger_exceptions) - if not hint and ledger_exceptions and all(row.get("phase") == "reference_resolution" for row in ledger_exceptions): - hint = _SKILLSPECTOR_REFERENCE_REJECTION_HINT - return f"{message}. {hint}" if hint else message + hints = [ + hint + for hint in ( + _skillspector_runtime_limit_hint(ledger_exceptions), + _skillspector_parse_limit_hint(ledger_exceptions), + ) + if hint + ] + if not hints and ledger_exceptions and all(row.get("phase") == "reference_resolution" for row in ledger_exceptions): + hints.append(_SKILLSPECTOR_REFERENCE_REJECTION_HINT) + return f"{message}. {' '.join(hints)}" if hints else message # SkillSpector's static pattern analyzers read text, so each records a referenced diff --git a/tests/fixtures/skillspector-2.13.4-mjs-runtime-parse-limit-no-llm.json b/tests/fixtures/skillspector-2.13.4-mjs-runtime-parse-limit-no-llm.json new file mode 100644 index 000000000..40332e2ad --- /dev/null +++ b/tests/fixtures/skillspector-2.13.4-mjs-runtime-parse-limit-no-llm.json @@ -0,0 +1,658 @@ +{ + "skill": { + "name": "spawn-helper", + "source": "/fixture/mjs-runtime-parse-limit", + "scanned_at": "2026-11-18T17:55:45.468924+00:00" + }, + "risk_assessment": { + "score": 33, + "severity": "MEDIUM", + "recommendation": "CAUTION", + "max_issue_severity": null + }, + "components": [ + { + "path": "SKILL.md", + "type": "markdown", + "lines": 153, + "executable": false, + "size_bytes": 18083, + "source_url": null, + "source_identity": null, + "source_digest": null + }, + { + "path": "scripts/admission.mjs", + "type": "javascript", + "lines": 170, + "executable": true, + "size_bytes": 8653, + "source_url": null, + "source_identity": null, + "source_digest": null + }, + { + "path": "scripts/machine-reading.mjs", + "type": "javascript", + "lines": 236, + "executable": true, + "size_bytes": 12926, + "source_url": null, + "source_identity": null, + "source_digest": null + } + ], + "structured_summaries": [], + "issues": [], + "suppressed_count": 0, + "suppressed": [], + "metadata": { + "has_executable_scripts": true, + "skillspector_version": "2.13.4", + "llm_requested": false, + "llm_available": false, + "meta_analysis_applied": false, + "inference_usage": [], + "llm_provenance": { + "schema_version": 1, + "provider": { + "configured_adapter": "unknown", + "resolved_adapter": "unknown", + "effective_adapter": "not_applicable", + "effective_adapters": [], + "service": "unknown", + "routing": { + "deployment_override": null, + "deployment_source": "unknown", + "api_version": null, + "api_version_source": "unknown" + } + }, + "analyzers": [ + { + "analyzer_id": "mcp_tool_poisoning", + "model": "z-ai/glm-5.3", + "model_source": "resolved_configuration", + "analyzer_revision": { + "value": "2.13.4", + "source": "skillspector_package", + "source_revision": { + "value": "unknown", + "source": "unknown" + } + } + }, + { + "analyzer_id": "semantic_developer_intent", + "model": "z-ai/glm-5.3", + "model_source": "resolved_configuration", + "analyzer_revision": { + "value": "2.13.4", + "source": "skillspector_package", + "source_revision": { + "value": "unknown", + "source": "unknown" + } + } + }, + { + "analyzer_id": "semantic_quality_policy", + "model": "z-ai/glm-5.3", + "model_source": "resolved_configuration", + "analyzer_revision": { + "value": "2.13.4", + "source": "skillspector_package", + "source_revision": { + "value": "unknown", + "source": "unknown" + } + } + }, + { + "analyzer_id": "semantic_security_discovery", + "model": "z-ai/glm-5.3", + "model_source": "resolved_configuration", + "analyzer_revision": { + "value": "2.13.4", + "source": "skillspector_package", + "source_revision": { + "value": "unknown", + "source": "unknown" + } + } + }, + { + "analyzer_id": "meta_analyzer", + "model": "z-ai/glm-5.3", + "model_source": "resolved_configuration", + "analyzer_revision": { + "value": "2.13.4", + "source": "skillspector_package", + "source_revision": { + "value": "unknown", + "source": "unknown" + } + } + } + ], + "sampling": { + "temperature": { + "requested": null, + "source": "provider_default", + "forwarded_to_client": null, + "adapter_support": false, + "provider_support": "unknown" + }, + "seed": { + "requested": null, + "source": "unset", + "forwarded_to_client": null, + "adapter_support": false, + "provider_support": "unknown" + }, + "reasoning_effort": { + "requested": null, + "source": "provider_default", + "forwarded_to_client": null, + "adapter_support": false, + "provider_support": "unknown" + } + }, + "determinism": { + "classification": "not_applicable", + "control_status": "not_applied", + "provider_guarantee": false, + "reason": "LLM analysis was not executed for this scan." + } + }, + "filtering_mode": "heuristic" + }, + "execution_successful": true, + "analysis_completeness": { + "total_components": 9, + "scanned_components": 7, + "coverage_percent": 77.8, + "is_complete": false, + "status": "partial", + "execution_successful": true, + "fully_inspected_files": 7, + "partially_inspected_files": 2, + "entirely_uninspected_files": 0, + "ledger_exceptions": [ + { + "outcome": "partial", + "phase": "reference_resolution", + "reason_code": "reference_missing", + "message": "A local path-like reference does not match any bundled artifact, such as a file the skill writes at runtime.", + "path": "SKILL.md", + "start_line": 150, + "end_line": 150, + "fatal": false + }, + { + "outcome": "partial", + "phase": "static", + "reason_code": "static_parse_limit", + "message": "A security-relevant expression could not be fully resolved by the bounded static parser. Full inspection depends on information available only when this code runs. Check: command string runtime; location: reported source range; unchecked scope: remaining input. Relevant parser input not fully checked.", + "path": "scripts/admission.mjs", + "start_line": null, + "end_line": null, + "fatal": false, + "analyzers": [ + "static_patterns_tool_misuse" + ], + "parser_diagnostic": { + "cause": "runtime_dependent", + "check": "command_string_runtime", + "source_start_offset": 3958, + "source_end_offset": 8650, + "start_line": 74, + "end_line": 170, + "unchecked_scope": "remaining_input", + "observed_is_lower_bound": false, + "full_input_checked": false, + "location_precision": "source_span" + } + }, + { + "outcome": "partial", + "phase": "static", + "reason_code": "static_parse_limit", + "message": "A security-relevant expression could not be fully resolved by the bounded static parser. Full inspection depends on information available only when this code runs. Check: command string runtime; location: reported source range; unchecked scope: remaining input. Relevant parser input not fully checked.", + "path": "scripts/machine-reading.mjs", + "start_line": null, + "end_line": null, + "fatal": false, + "analyzers": [ + "static_patterns_tool_misuse" + ], + "parser_diagnostic": { + "cause": "runtime_dependent", + "check": "command_string_runtime", + "source_start_offset": 6674, + "source_end_offset": 12915, + "start_line": 104, + "end_line": 236, + "unchecked_scope": "remaining_input", + "observed_is_lower_bound": false, + "full_input_checked": false, + "location_precision": "source_span" + } + } + ], + "scope_exclusions": [], + "analyzer_statuses": [ + { + "analyzer_id": "artifact_integrity", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "behavioral_ast", + "status": "not_applicable", + "planned_work": 0, + "completed": 0, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0, + "reason_code": "no_applicable_files", + "message": "No files matched this analyzer's applicability contract." + }, + { + "analyzer_id": "behavioral_taint_tracking", + "status": "not_applicable", + "planned_work": 0, + "completed": 0, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0, + "reason_code": "no_applicable_files", + "message": "No files matched this analyzer's applicability contract." + }, + { + "analyzer_id": "bundled_execution_surface", + "status": "not_applicable", + "planned_work": 0, + "completed": 0, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0, + "reason_code": "no_applicable_files", + "message": "No files matched this analyzer's applicability contract." + }, + { + "analyzer_id": "mcp_least_privilege", + "status": "completed", + "planned_work": 3, + "completed": 3, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "mcp_rug_pull", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "mcp_tool_poisoning", + "status": "completed", + "planned_work": 1, + "completed": 1, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "meta_analyzer", + "status": "disabled", + "planned_work": 0, + "completed": 0, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0, + "reason_code": "disabled_by_configuration", + "message": "Analyzer was disabled by the requested configuration." + }, + { + "analyzer_id": "semantic_developer_intent", + "status": "disabled", + "planned_work": 0, + "completed": 0, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0, + "reason_code": "disabled_by_configuration", + "message": "Analyzer was disabled by the requested configuration." + }, + { + "analyzer_id": "semantic_quality_policy", + "status": "disabled", + "planned_work": 0, + "completed": 0, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0, + "reason_code": "disabled_by_configuration", + "message": "Analyzer was disabled by the requested configuration." + }, + { + "analyzer_id": "semantic_security_discovery", + "status": "disabled", + "planned_work": 0, + "completed": 0, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0, + "reason_code": "disabled_by_configuration", + "message": "Analyzer was disabled by the requested configuration." + }, + { + "analyzer_id": "static_patterns_agent_snooping", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_anti_refusal", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_data_exfiltration", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_deserialization", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_excessive_agency", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_harmful_content", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_memory_poisoning", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_output_handling", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_privilege_escalation", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_prompt_injection", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_rogue_agent", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_ssrf", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_supply_chain", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_system_prompt_leakage", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_tool_misuse", + "status": "degraded", + "planned_work": 9, + "completed": 7, + "partial": 2, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_yara", + "status": "completed", + "planned_work": 9, + "completed": 9, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + } + ], + "references": [ + { + "source_path": "SKILL.md", + "line": 47, + "column": 292, + "evidence": "-out did not happen and why, spawn denied vs. no fan-out tool on the platform (`references/receipt.md`); never reported as a swarm that ran |", + "target_path": "references/receipt.md", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 68, + "column": 11, + "evidence": "Example: `references/example.md`.", + "target_path": "references/example.md", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 104, + "column": 337, + "evidence": "r merges independent spots; wave width bounds each wave, never the unit count (`references/taxonomy.md`). Unit count sizes the swarm.", + "target_path": "references/taxonomy.md", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 108, + "column": 1047, + "evidence": "lock. The engine applies the stricter of the global and project values itself (`references/admission-control.md`, P29); you pass nothing. Spawn wave by wave; ea", + "target_path": "references/admission-control.md", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 108, + "column": 1162, + "evidence": "29); you pass nothing. Spawn wave by wave; each worker gets the work-contract (`references/contract-template.md`) carrying its scope + the shared-digest + the l", + "target_path": "references/contract-template.md", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 116, + "column": 211, + "evidence": "ate \u00b7 quarantined items + why \u00b7 test-uncovered flags. Format + layman wording: `references/receipt.md`. The receipt + heads-up speak the USER'S language; techni", + "target_path": "references/receipt.md", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 128, + "column": 55, + "evidence": "Per-domain unit/invariant/gate tables + mode detail: `references/taxonomy.md`.", + "target_path": "references/taxonomy.md", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 141, + "column": 150, + "evidence": " it; else native subagent waves. Riding Claude Code's `Workflow` tool \u2192 **read `references/workflow-engine.md` first** (P28: waves not `parallel(all-N)` \u00b7 scatt", + "target_path": "references/workflow-engine.md", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 150, + "column": 589, + "evidence": "list \u2014 first found wins, the walk stops at home: **(1)** your own agent's dir (`.claude/coal/coalface.json` on Claude Code, `.agents/coal/coalface.json` on Anti", + "target_path": null, + "status": "missing", + "disposition": "partial", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 150, + "column": 634, + "evidence": "me: **(1)** your own agent's dir (`.claude/coal/coalface.json` on Claude Code, `.agents/coal/coalface.json` on Antigravity); **(2)** the other dirs' `coal/coalf", + "target_path": null, + "status": "missing", + "disposition": "partial", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 150, + "column": 704, + "evidence": "de Code, `.agents/coal/coalface.json` on Antigravity); **(2)** the other dirs' `coal/coalface.json`, `.claude` \u2192 `.agents` \u2192 `.gemini`; **(3)** DEPRECATED neste", + "target_path": null, + "status": "missing", + "disposition": "partial", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 150, + "column": 850, + "evidence": "PRECATED nested `./.coalface.json`, same order; **(4)** DEPRECATED root `.coalface.json`. Keys: `coalfaceMode` \u00b7 `bandwidth` \u00b7 `autoFanoutFloor` \u00b7 `maxLo", + "target_path": null, + "status": "missing", + "disposition": "partial", + "reference_kind": "quoted_or_code" + } + ], + "limitations": [ + "Analyzer static_patterns_tool_misuse status: degraded." + ], + "findings_before_filtering": 2, + "findings_after_filtering": 2 + } +} diff --git a/tests/reporting/test_tier3_validate_cases.py b/tests/reporting/test_tier3_validate_cases.py index cdd6c0332..a56f58525 100644 --- a/tests/reporting/test_tier3_validate_cases.py +++ b/tests/reporting/test_tier3_validate_cases.py @@ -585,6 +585,26 @@ def test_unresolved_reference_keeps_spaces_in_the_path(): assert "scripts/run.py" not in text +def test_unresolved_reference_still_matches_when_parse_limit_rows_have_spans(): + from skillevaluator.models.result import ValidationResult + from skillevaluator.reporting.console_ui import summarize_tier1 + + security = ValidationResult(validator_name="Security Scan", passed=False) + security.metadata["incomplete_scans"] = ["skillspector"] + security.metadata["scanners"] = {"skillspector": "2.13.4"} + security.add_error( + "skillspector JSON field 'analysis_completeness' reports incomplete analysis (status 'partial'): " + "SKILL.md:150 [reference_resolution; reference_missing]; " + "scripts/admission.mjs:74-170 [static; static_parse_limit; runtime_dependent command_string_runtime; " + "analyzers=static_patterns_tool_misuse]; security scan did not complete" + ) + + _ok, rows = summarize_tier1([security]) + text = _text(rows) + assert "SkillSpector ran, but couldn't resolve the file reference at SKILL.md:150" in text + assert "admission.mjs" not in text + + def test_tier1_summary_counts_validators_and_their_sub_checks(): from skillevaluator.models.result import ValidationResult from skillevaluator.reporting.console_ui import summarize_tier1 diff --git a/tests/validators/test_skillspector_diagnostics.py b/tests/validators/test_skillspector_diagnostics.py index 99295d9f7..d99e8b65b 100644 --- a/tests/validators/test_skillspector_diagnostics.py +++ b/tests/validators/test_skillspector_diagnostics.py @@ -130,6 +130,81 @@ def test_diagnostic_text_and_lists_are_bounded_redacted_and_idempotent(): assert sanitize_completeness(merged) == merged +def test_parser_diagnostic_is_projected_without_source_offsets_and_survives_merge(): + raw = { + "ledger_exceptions": [ + { + "path": "scripts/admission.mjs", + "phase": "static", + "reason_code": "static_parse_limit", + "analyzers": ["static_patterns_tool_misuse"], + "parser_diagnostic": { + "cause": "runtime_dependent", + "check": "command_string_runtime", + "start_line": 74, + "end_line": 170, + "unchecked_scope": "remaining_input", + "full_input_checked": False, + "source_start_offset": 3958, + "source_end_offset": 8650, + "location_precision": "source_span", + "observed_is_lower_bound": False, + }, + } + ] + } + record = completeness_record(raw, "skillspector") + diagnostic = record["ledger_exceptions"][0]["parser_diagnostic"] + assert diagnostic == { + "cause": "runtime_dependent", + "check": "command_string_runtime", + "start_line": 74, + "end_line": 170, + "unchecked_scope": "remaining_input", + "full_input_checked": False, + } + encoded = json.dumps(record) + assert "source_start_offset" not in encoded + assert "3958" not in encoded + assert "location_precision" not in encoded + wrapped = {"records": [record], "omitted_records": 0} + assert sanitize_completeness(wrapped) == wrapped + merged = merge_completeness({}, wrapped, prefix="spawn-helper") + assert merged["records"][0]["skill"] == "spawn-helper" + assert merged["records"][0]["ledger_exceptions"][0]["parser_diagnostic"] == diagnostic + assert sanitize_completeness(merged) == merged + record["ledger_exceptions"][0]["parser_diagnostic"]["source_start_offset"] = 3958 + saved = sanitize_completeness({"records": [record]}) + reprojected = saved["records"][0]["ledger_exceptions"][0]["parser_diagnostic"] + assert "source_start_offset" not in reprojected + + +@pytest.mark.parametrize( + "diagnostic", + [ + "not-a-dict", + True, + {"cause": "runtime_dependent", "start_line": "74", "end_line": 170}, + {"cause": True, "check": False, "start_line": -1, "end_line": 10, "full_input_checked": "no"}, + {"cause": "runtime_dependent", "start_line": 170, "end_line": 74}, + ], + ids=["string", "bool", "string-line", "bool-fields", "end-before-start"], +) +def test_malformed_parser_diagnostic_is_dropped_or_stripped_to_safe_fields(diagnostic: object): + record = completeness_record( + {"ledger_exceptions": [{"path": "scripts/helper.mjs", "parser_diagnostic": diagnostic}]}, + "skillspector", + ) + projected = record["ledger_exceptions"][0].get("parser_diagnostic") + if projected is None: + return + assert "start_line" not in projected + assert "end_line" not in projected + assert projected.get("full_input_checked") is not True + text_keys = {key for key in projected if key not in {"start_line", "end_line", "full_input_checked"}} + assert all(isinstance(projected[key], str) for key in text_keys) + + def test_saved_diagnostic_metadata_is_revalidated_at_json_boundary(): result = partial_result() record = result.metadata["skillspector_completeness"]["records"][0] diff --git a/tests/validators/test_skillspector_hook_surface.py b/tests/validators/test_skillspector_hook_surface.py index cc10bfc0e..b6fa7dbb2 100644 --- a/tests/validators/test_skillspector_hook_surface.py +++ b/tests/validators/test_skillspector_hook_surface.py @@ -91,7 +91,10 @@ def _settings_variant_report(version: str, case: str) -> str: "fatal": False, "analyzers": ["bundled_execution_surface"], } -_PARSE_LIMIT_ROW = "hooks/hooks.json [static; static_parse_limit; analyzers=static_patterns_tool_misuse]" +_PARSE_LIMIT_ROW = ( + "hooks/hooks.json:11 [static; static_parse_limit; boundary_unresolved command_word_boundary; " + "analyzers=static_patterns_tool_misuse]" +) _SETTINGS_HOOK_ROW = ".claude/settings.json [static; opaque_content; analyzers=bundled_execution_surface]" # The skill scanned for the settings-hook reports. diff --git a/tests/validators/test_skillspector_parser_locations.py b/tests/validators/test_skillspector_parser_locations.py new file mode 100644 index 000000000..fc865c2b5 --- /dev/null +++ b/tests/validators/test_skillspector_parser_locations.py @@ -0,0 +1,211 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Incomplete SkillSpector scans name parser_diagnostic spans, causes, and checks. + +SkillSpector 2.13.4 records ``static_parse_limit`` on some JavaScript helpers +with ``start_line`` empty and the span, cause and check only in +``parser_diagnostic``. The security check stays ``INCOMPLETE``; these tests +cover the labels, the runtime-dependent hint, and the JSON projection. +""" + +import json +from pathlib import Path +from unittest.mock import patch + +import pytest +from tests.validators.test_security import ( + _REGULAR_ANALYZERS, + _ledger_exception, + _skillspector_partial_report, + _validate_skillspector_payload, +) + +from skillevaluator.reporting.json_reporter import JSONReporter +from skillevaluator.validators.security import ( + _SKILLSPECTOR_PARSE_LIMIT_HINT, + _SKILLSPECTOR_REFERENCE_REJECTION_HINT, + _skillspector_incomplete_analysis_error, + _skillspector_ledger_exception_label, +) + +_FIXTURE = Path(__file__).parents[1] / "fixtures" / "skillspector-2.13.4-mjs-runtime-parse-limit-no-llm.json" +_RUNTIME_DIAGNOSTIC = { + "cause": "runtime_dependent", + "check": "command_string_runtime", + "start_line": 74, + "end_line": 170, + "unchecked_scope": "remaining_input", + "full_input_checked": False, + "source_start_offset": 3958, + "source_end_offset": 8650, + "location_precision": "source_span", +} +_BOUNDARY_DIAGNOSTIC = { + "cause": "boundary_unresolved", + "check": "command_word_boundary", + "start_line": 11, + "end_line": 11, + "unchecked_scope": "command_string", + "full_input_checked": False, +} + + +def _parse_limit_row(**overrides) -> dict: + row = { + **_ledger_exception("scripts/helper.mjs", "static_parse_limit"), + "parser_diagnostic": dict(_RUNTIME_DIAGNOSTIC), + } + row.update(overrides) + return row + + +def test_captured_mjs_rows_use_the_parser_span_and_runtime_dependent_context() -> None: + report = json.loads(_FIXTURE.read_text(encoding="utf-8")) + rows = report["analysis_completeness"]["ledger_exceptions"] + labels = [_skillspector_ledger_exception_label(row) for row in rows] + assert labels == [ + "SKILL.md:150 [reference_resolution; reference_missing]", + "scripts/admission.mjs:74-170 [static; static_parse_limit; runtime_dependent command_string_runtime; " + "analyzers=static_patterns_tool_misuse]", + "scripts/machine-reading.mjs:104-236 [static; static_parse_limit; runtime_dependent command_string_runtime; " + "analyzers=static_patterns_tool_misuse]", + ] + error = _skillspector_incomplete_analysis_error("partial", rows) + assert error.startswith( + "skillspector JSON field 'analysis_completeness' reports incomplete analysis (status 'partial'): " + ) + assert labels[0] in error and labels[1] in error and labels[2] in error + assert error.endswith(_SKILLSPECTOR_PARSE_LIMIT_HINT) + assert _SKILLSPECTOR_REFERENCE_REJECTION_HINT not in error + + +def test_parser_span_uses_a_range_or_a_single_line() -> None: + range_label = _skillspector_ledger_exception_label(_parse_limit_row()) + assert range_label.startswith("scripts/helper.mjs:74-170 [") + single = _parse_limit_row(parser_diagnostic=dict(_BOUNDARY_DIAGNOSTIC)) + assert _skillspector_ledger_exception_label(single).startswith("scripts/helper.mjs:11 [") + assert "11-11" not in _skillspector_ledger_exception_label(single) + + +def test_row_start_line_is_unchanged_when_parser_diagnostic_also_has_a_span() -> None: + row = _parse_limit_row(start_line=12) + assert _skillspector_ledger_exception_label(row) == ( + f"scripts/helper.mjs:12 [static; static_parse_limit; runtime_dependent command_string_runtime; " + f"analyzers={','.join(_REGULAR_ANALYZERS)}]" + ) + + +@pytest.mark.parametrize( + "diagnostic", + [ + "not-a-dict", + ["runtime_dependent"], + None, + {"cause": "runtime_dependent", "check": "command_string_runtime", "start_line": "74", "end_line": "170"}, + {"cause": "runtime_dependent", "check": "command_string_runtime", "start_line": True, "end_line": True}, + {"cause": "runtime_dependent", "check": "command_string_runtime", "start_line": -1, "end_line": 10}, + {"cause": "runtime_dependent", "check": "command_string_runtime", "start_line": 170, "end_line": 74}, + {"cause": "runtime_dependent", "check": "command_string_runtime", "start_line": 74, "end_line": False}, + ], + ids=[ + "string", + "list", + "none", + "string-lines", + "bool-lines", + "negative", + "end-before-start", + "bool-end", + ], +) +def test_malformed_parser_diagnostic_does_not_supply_a_location(diagnostic: object) -> None: + row = _parse_limit_row(parser_diagnostic=diagnostic) + label = _skillspector_ledger_exception_label(row) + assert label.startswith("scripts/helper.mjs [static; static_parse_limit") + assert ":74" not in label + assert ":170" not in label + + +def test_cause_and_check_are_sanitized_and_truncated() -> None: + row = _parse_limit_row( + parser_diagnostic={ + "cause": "runtime\ndependent-" + "x" * 400, + "check": "command\tstring-" + "y" * 400, + "start_line": 74, + "end_line": 170, + } + ) + label = _skillspector_ledger_exception_label(row) + assert "\n" not in label and "\t" not in label + assert "runtime dependent-" + "x" * 179 + "..." in label + assert "x" * 180 not in label + assert "command string-" + "y" * 182 + "..." in label + assert "y" * 183 not in label + other_reason = _ledger_exception("scripts/helper.mjs", "opaque_content") + other_reason["parser_diagnostic"] = dict(_RUNTIME_DIAGNOSTIC) + assert "runtime_dependent" not in _skillspector_ledger_exception_label(other_reason) + + +def test_runtime_dependent_hint_requires_every_parse_limit_row() -> None: + runtime = _parse_limit_row() + other = _parse_limit_row(path="scripts/other.mjs", parser_diagnostic=dict(_BOUNDARY_DIAGNOSTIC)) + missing = _ledger_exception("scripts/plain.mjs", "static_parse_limit") + assert _SKILLSPECTOR_PARSE_LIMIT_HINT in _skillspector_incomplete_analysis_error("partial", [runtime]) + mixed = _skillspector_incomplete_analysis_error("partial", [runtime, other]) + assert _SKILLSPECTOR_PARSE_LIMIT_HINT not in mixed + assert "scripts/other.mjs:11 [" in mixed + assert _SKILLSPECTOR_PARSE_LIMIT_HINT not in _skillspector_incomplete_analysis_error("partial", [missing]) + assert _SKILLSPECTOR_PARSE_LIMIT_HINT not in _skillspector_incomplete_analysis_error( + "partial", [_ledger_exception("scripts/render.py", "static_parse_limit") | {"start_line": 12}] + ) + + +def test_parse_limit_hint_combines_with_runtime_limit_and_not_with_reference_rejection() -> None: + runtime_limit = _ledger_exception("references/sect-1.html") + parse_limit = _parse_limit_row() + reference = { + **_ledger_exception("SKILL.md", "reference_missing", analyzers=(), phase="reference_resolution"), + "start_line": 150, + } + combined = _skillspector_incomplete_analysis_error("partial", [runtime_limit, parse_limit]) + assert "SkillSpector reached a runtime limit before it finished 1 file(s)." in combined + assert _SKILLSPECTOR_PARSE_LIMIT_HINT in combined + assert _SKILLSPECTOR_REFERENCE_REJECTION_HINT not in combined + with_reference = _skillspector_incomplete_analysis_error("partial", [reference, parse_limit]) + assert "SKILL.md:150 [reference_resolution; reference_missing]" in with_reference + assert _SKILLSPECTOR_PARSE_LIMIT_HINT in with_reference + assert _SKILLSPECTOR_REFERENCE_REJECTION_HINT not in with_reference + only_reference = _skillspector_incomplete_analysis_error("partial", [reference]) + assert only_reference.endswith(_SKILLSPECTOR_REFERENCE_REJECTION_HINT) + assert _SKILLSPECTOR_PARSE_LIMIT_HINT not in only_reference + + +@patch("skillevaluator.validators.security.Tools") +def test_partial_scan_stays_incomplete_and_projects_parser_diagnostic(mock_tools, sample_skill_dir: Path) -> None: + payload = _skillspector_partial_report([_parse_limit_row(analyzers=["static_patterns_tool_misuse"])]) + + result = _validate_skillspector_payload(mock_tools, sample_skill_dir, payload) + + assert result.status == "incomplete" + assert not result.passed + assert result.incomplete_scans == ["skillspector"] + assert ( + "scripts/helper.mjs:74-170 [static; static_parse_limit; runtime_dependent command_string_runtime; " + "analyzers=static_patterns_tool_misuse]" + ) in result.errors[0] + assert result.errors[0].endswith(_SKILLSPECTOR_PARSE_LIMIT_HINT) + record = json.loads(JSONReporter().render(result))["skillspector_completeness"]["records"][0] + diagnostic = record["ledger_exceptions"][0]["parser_diagnostic"] + assert diagnostic == { + "cause": "runtime_dependent", + "check": "command_string_runtime", + "start_line": 74, + "end_line": 170, + "unchecked_scope": "remaining_input", + "full_input_checked": False, + } + encoded = json.dumps(record) + assert "source_start_offset" not in encoded + assert "source_end_offset" not in encoded + assert "location_precision" not in encoded diff --git a/tests/validators/test_skillspector_reference_diagnostics.py b/tests/validators/test_skillspector_reference_diagnostics.py index a0ae8b28e..02cc0e856 100644 --- a/tests/validators/test_skillspector_reference_diagnostics.py +++ b/tests/validators/test_skillspector_reference_diagnostics.py @@ -343,6 +343,137 @@ def test_evidence_and_limits_are_bounded_and_sanitized(self) -> None: {"file": "SKILL.md"}, ] + def test_static_parse_limit_uses_parser_span_when_the_reason_has_no_line(self) -> None: + issue = _report()["issues"][0] + issue["evidence"] = { + "target_path": "scripts/helper.mjs", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "phase": "static", + "message": "A security-relevant expression could not be fully resolved.", + "analyzers": ["static_patterns_tool_misuse"], + "parser_diagnostic": { + "cause": "runtime_dependent", + "check": "command_string_runtime", + "start_line": 74, + "end_line": 170, + "source_start_offset": 3958, + }, + } + ], + } + + finding, is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert is_error + assert "at target lines 74-170" in finding.suggestion + reason = finding.metadata["skillspector_evidence"]["reasons"][0] + assert reason["start_line"] == 74 + assert reason["end_line"] == 170 + assert "parser_diagnostic" not in reason + assert "_parser_span" not in reason + assert "source_start_offset" not in json.dumps(finding.metadata) + + def test_static_parse_limit_keeps_the_reason_line_when_present(self) -> None: + issue = _report()["issues"][0] + issue["evidence"] = { + "target_path": "scripts/helper.pl", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "analyzers": ["static_patterns_tool_misuse"], + "start_line": 3, + "parser_diagnostic": {"start_line": 74, "end_line": 170}, + } + ], + } + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert "at target line 3" in finding.suggestion + assert "74-170" not in finding.suggestion + assert finding.metadata["skillspector_evidence"]["reasons"][0]["start_line"] == 3 + assert "end_line" not in finding.metadata["skillspector_evidence"]["reasons"][0] + + def test_static_parse_limit_does_not_invent_a_parser_span(self) -> None: + issue = _report()["issues"][0] + issue["evidence"] = { + "target_path": "scripts/helper.pl", + "target_disposition": "partial", + "reasons": [{"reason_code": "static_parse_limit", "analyzers": ["static_patterns_tool_misuse"]}], + } + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert "at target line" not in finding.suggestion + assert "at target lines" not in finding.suggestion + + def test_static_parse_limit_single_line_span_uses_target_line(self) -> None: + issue = _report()["issues"][0] + issue["evidence"] = { + "target_path": "hooks/hooks.json", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "analyzers": ["static_patterns_tool_misuse"], + "parser_diagnostic": {"start_line": 11, "end_line": 11}, + } + ], + } + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert "at target line 11" in finding.suggestion + assert "at target lines" not in finding.suggestion + + def test_row_end_line_without_parser_diagnostic_keeps_upstream_suggestion_and_id(self) -> None: + """A row that already has lines 3-7 must keep the upstream suggestion and finding ID.""" + issue = _report()["issues"][0] + issue["evidence"] = { + "target_path": "scripts/helper.pl", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "analyzers": ["static_patterns_tool_misuse"], + "start_line": 3, + "end_line": 7, + } + ], + } + baseline_issue = copy.deepcopy(issue) + del baseline_issue["evidence"]["reasons"][0]["end_line"] + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + baseline, _ = SecurityValidator._convert_skillspector_issue(baseline_issue) + + assert finding.suggestion == baseline.suggestion + assert finding.finding_id == baseline.finding_id + assert "at target line 3" in finding.suggestion + assert "3-7" not in finding.suggestion + assert "at target lines" not in finding.suggestion + assert finding.metadata["skillspector_evidence"]["reasons"][0]["end_line"] == 7 + assert "_parser_span" not in finding.metadata["skillspector_evidence"]["reasons"][0] + + issue["evidence"]["reasons"] = [ + {"reason_code": "read_error", "start_line": 4, "end_line": 5}, + {"reason_code": "read_error", "start_line": 4, "end_line": 12}, + ] + baseline_issue = copy.deepcopy(issue) + for reason in baseline_issue["evidence"]["reasons"]: + del reason["end_line"] + grouped, _ = SecurityValidator._convert_skillspector_issue(issue) + grouped_baseline, _ = SecurityValidator._convert_skillspector_issue(baseline_issue) + assert grouped.suggestion == grouped_baseline.suggestion + assert grouped.finding_id == grouped_baseline.finding_id + assert grouped.suggestion.count("read_error") == 1 + assert "at target line 4" in grouped.suggestion + assert "at target lines" not in grouped.suggestion + @pytest.mark.parametrize("field", ["observed_characters", "observed_seconds"]) @pytest.mark.parametrize( "value", From 2fd357cbd53f59e543fa2519ac8db40133d6cb25 Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:26:29 -0800 Subject: [PATCH 2/4] fix(security): take the AE1 parse-limit span from the matching ledger row SkillSpector 2.13.x builds an AE1 finding's evidence.reasons without parser_diagnostic, so the span branch never ran on real reports. When a structured reason has no line, read the span from the one analysis_completeness.ledger_exceptions row with the same normalized path and reason_code; skip it when zero or several rows match. Tests now use the captured 2.13.4 mjs fixture plus an AE1 issue in the scanner's shape. The CHANGELOG notes the one-time AE1 finding_id change. Signed-off-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> --- CHANGELOG.md | 7 + docs/tier1-reference.mdx | 4 +- src/skillevaluator/skillspector_references.py | 56 +++++++- ...test_skillspector_reference_diagnostics.py | 121 ++++++++++-------- 4 files changed, 132 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 947a65fbd..3be3aa01a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,13 @@ All notable changes to SkillEvaluator are documented in this file. keep a bounded copy of that diagnostic in `skillspector_completeness`, and, when every such row is `runtime_dependent`, explain that SkillSpector could not resolve a command or code string known only at run time. The check stays `INCOMPLETE`. + An AE1 finding for that file now names the same lines in its suggestion, such + as `static_parse_limit (static_patterns_tool_misuse) at target lines 74-170`: + SkillSpector leaves `parser_diagnostic` out of the finding's `evidence.reasons`, + so the span comes from the one `analysis_completeness.ledger_exceptions` row + with the same path and `reason_code`, and none is shown when several rows + match. Because the suggestion text changes, the `finding_id` of each such AE1 + finding changes once with this release. ## 1.0.1 - 2026-11-17 diff --git a/docs/tier1-reference.mdx b/docs/tier1-reference.mdx index fab0a2c00..e24757333 100644 --- a/docs/tier1-reference.mdx +++ b/docs/tier1-reference.mdx @@ -952,7 +952,9 @@ Tier 1 checks always gate the exit code inside `validate`. Tier 2 gates when it error now labels that row as `scripts/helper.mjs:74-170 [static; static_parse_limit; runtime_dependent command_string_runtime; analyzers=static_patterns_tool_misuse]` and adds a short hint to review - those lines and prefer fixed argument lists. Updating SkillSpector does + those lines and prefer fixed argument lists. An AE1 finding for a skill + line that names the helper quotes the same span in its suggestion + (`at target lines 74-170`), read from that ledger row. Updating SkillSpector does not clear this limit today. If the helper is valid and the command is safe, report a minimal reproducer to SkillSpector. JSON reports keep a bounded `parser_diagnostic` on the matching diff --git a/src/skillevaluator/skillspector_references.py b/src/skillevaluator/skillspector_references.py index 51e5ebc86..9f82f92b6 100644 --- a/src/skillevaluator/skillspector_references.py +++ b/src/skillevaluator/skillspector_references.py @@ -296,6 +296,54 @@ def normalize_once(path: object) -> str | None: return by_target +def _with_ledger_parser_spans( + rows: object, + target: str, + completeness: object, + normalize_path: Callable[[object], str | None], + text: Callable[..., str | None], +) -> object: + """*rows* with a ledger ``parser_diagnostic`` on each structured reason that has no line. + + SkillSpector builds an AE1 finding's ``evidence.reasons`` without the + ``parser_diagnostic`` of the ledger row behind each reason, so the span is + read from ``analysis_completeness.ledger_exceptions``: the one row for the + same target and ``reason_code``. A reason with a line of its own, or with + no row or several rows to match, is left as it is. + """ + if not isinstance(rows, list) or not isinstance(completeness, dict): + return rows + ledger = completeness.get("ledger_exceptions") + if not isinstance(ledger, list): + return rows + + def needs_span(row: object) -> bool: + return ( + isinstance(row, dict) + and _line(row.get("start_line")) is None + and not isinstance(row.get("parser_diagnostic"), dict) + and text(row.get("reason_code"), max_length=128) is not None + ) + + if not any(needs_span(row) for row in rows[:_MAX_REASONS]): + return rows + matches: dict[str, list[dict]] = {} + for entry in ledger: + if not isinstance(entry, dict) or normalize_path(entry.get("path")) != target: + continue + if reason_code := text(entry.get("reason_code"), max_length=128): + matches.setdefault(reason_code, []).append(entry) + filled: list[object] = [] + for row in rows: + if needs_span(row): + candidates = matches.get(text(row.get("reason_code"), max_length=128) or "", []) + diagnostic = candidates[0].get("parser_diagnostic") if len(candidates) == 1 else None + if isinstance(diagnostic, dict): + row = {**row, "parser_diagnostic": diagnostic} + filled.append(row) + return filled + + def issue_diagnostics( issue: Mapping[str, object], *, @@ -310,7 +358,9 @@ def issue_diagnostics( and up to 16 ``reasons``, with ``reasons_truncated`` when SkillSpector or this projection left some out. Before v2.12.0 the reasons come from the target's ledger rows in *completeness* (or *legacy_reason_index*), and the - finding gets no evidence without them. ``skillspector_occurrences`` lists + finding gets no evidence without them. A structured reason without a line + takes the ``parser_diagnostic`` span of its one matching ledger row in + *completeness*. ``skillspector_occurrences`` lists up to 128 of the issue's ``occurrences``. Any other issue gets ``{}``. Paths go through *normalize_path* and other text through *text*. """ @@ -323,7 +373,9 @@ def issue_diagnostics( evidence = issue.get("evidence") evidence = evidence if isinstance(evidence, dict) else {} rows = evidence.get("reasons") if structured else None - if not rows: + if rows: + rows = _with_ledger_parser_spans(rows, target, completeness, normalize_path, text) + else: if legacy_reason_index is None: legacy_reason_index = index_legacy_reference_reasons( [issue], completeness=completeness, normalize_path=normalize_path, text=text diff --git a/tests/validators/test_skillspector_reference_diagnostics.py b/tests/validators/test_skillspector_reference_diagnostics.py index 02cc0e856..aa34c4416 100644 --- a/tests/validators/test_skillspector_reference_diagnostics.py +++ b/tests/validators/test_skillspector_reference_diagnostics.py @@ -46,6 +46,7 @@ _HOST_LANGUAGE_REPORT = "skillspector-2.12.0-host-language-parse-limits-ae1-no-llm.json" _PARSE_LIMIT_REPORT = "skillspector-2.13.3-perl-parse-limit-ae1-no-llm.json" _IMAGE_PATH_REPORT = "skillspector-2.12.0-image-path-reference-no-llm.json" +_MJS_PARSE_LIMIT_REPORT = "skillspector-2.13.4-mjs-runtime-parse-limit-no-llm.json" _CHECK_NAME = f"{AE1_PATTERN} (AE1)" _INCOMPLETE = "skillspector JSON field 'analysis_completeness' reports incomplete analysis (status 'partial')" _OBFUSCATION_ANALYZERS = [ @@ -343,55 +344,74 @@ def test_evidence_and_limits_are_bounded_and_sanitized(self) -> None: {"file": "SKILL.md"}, ] - def test_static_parse_limit_uses_parser_span_when_the_reason_has_no_line(self) -> None: - issue = _report()["issues"][0] + @staticmethod + def _runtime_parse_limit_issue(target: str = "scripts/admission.mjs", **reason: object) -> dict: + """An AE1 issue for *target* in the shape SkillSpector 2.13.x emits. + + Its ``evidence.reasons`` carry ``reason_code``, ``message``, ``phase``, + ``analyzers`` and the event's own lines, never ``parser_diagnostic``. + """ + issue = _report(_PARSE_LIMIT_REPORT)["issues"][0] + issue["finding"] = f"{target} (partial)" issue["evidence"] = { - "target_path": "scripts/helper.mjs", + "target_path": target, "target_disposition": "partial", "reasons": [ { "reason_code": "static_parse_limit", + "message": "A security-relevant expression could not be fully resolved by the bounded static parser.", "phase": "static", - "message": "A security-relevant expression could not be fully resolved.", "analyzers": ["static_patterns_tool_misuse"], - "parser_diagnostic": { - "cause": "runtime_dependent", - "check": "command_string_runtime", - "start_line": 74, - "end_line": 170, - "source_start_offset": 3958, - }, + **reason, } ], } + return issue - finding, is_error = SecurityValidator._convert_skillspector_issue(issue) + def test_captured_ledger_span_reaches_a_scanner_shaped_finding(self) -> None: + """The 2.13.4 capture's ledger row gives its AE1 finding lines 74-170.""" + report = _report(_MJS_PARSE_LIMIT_REPORT) + report["issues"].append(self._runtime_parse_limit_issue()) + without_ledger = copy.deepcopy(report["issues"][-1]) - assert is_error - assert "at target lines 74-170" in finding.suggestion + result = _process(report) + + [finding] = _ae1(result) + assert "static_parse_limit (static_patterns_tool_misuse) at target lines 74-170:" in finding.suggestion reason = finding.metadata["skillspector_evidence"]["reasons"][0] - assert reason["start_line"] == 74 - assert reason["end_line"] == 170 + assert (reason["start_line"], reason["end_line"]) == (74, 170) assert "parser_diagnostic" not in reason assert "_parser_span" not in reason assert "source_start_offset" not in json.dumps(finding.metadata) + # The suggestion is new, so the finding_id changes once from a finding without the span. + baseline, _ = SecurityValidator._convert_skillspector_issue(without_ledger) + assert "at target line" not in baseline.suggestion + assert finding.finding_id != baseline.finding_id - def test_static_parse_limit_keeps_the_reason_line_when_present(self) -> None: - issue = _report()["issues"][0] - issue["evidence"] = { - "target_path": "scripts/helper.pl", - "target_disposition": "partial", - "reasons": [ - { - "reason_code": "static_parse_limit", - "analyzers": ["static_patterns_tool_misuse"], - "start_line": 3, - "parser_diagnostic": {"start_line": 74, "end_line": 170}, - } - ], - } + def test_ledger_span_is_read_only_from_the_one_matching_row(self) -> None: + completeness = copy.deepcopy(_report(_MJS_PARSE_LIMIT_REPORT)["analysis_completeness"]) + rows = completeness["ledger_exceptions"] - finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + other_target, _ = SecurityValidator._convert_skillspector_issue( + self._runtime_parse_limit_issue("scripts/helper.mjs"), completeness=completeness + ) + other_reason = self._runtime_parse_limit_issue() + other_reason["evidence"]["reasons"][0]["reason_code"] = "obfuscated_instruction_text" + other_code, _ = SecurityValidator._convert_skillspector_issue(other_reason, completeness=completeness) + rows.append({**rows[1], "parser_diagnostic": {**rows[1]["parser_diagnostic"], "start_line": 200}}) + ambiguous, _ = SecurityValidator._convert_skillspector_issue( + self._runtime_parse_limit_issue(), completeness=completeness + ) + + for finding in (other_target, other_code, ambiguous): + assert "at target line" not in finding.suggestion + assert "start_line" not in finding.metadata["skillspector_evidence"]["reasons"][0] + + def test_reason_line_is_kept_over_the_ledger_span(self) -> None: + completeness = _report(_MJS_PARSE_LIMIT_REPORT)["analysis_completeness"] + issue = self._runtime_parse_limit_issue(start_line=3) + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue, completeness=completeness) assert "at target line 3" in finding.suggestion assert "74-170" not in finding.suggestion @@ -399,37 +419,32 @@ def test_static_parse_limit_keeps_the_reason_line_when_present(self) -> None: assert "end_line" not in finding.metadata["skillspector_evidence"]["reasons"][0] def test_static_parse_limit_does_not_invent_a_parser_span(self) -> None: - issue = _report()["issues"][0] - issue["evidence"] = { - "target_path": "scripts/helper.pl", - "target_disposition": "partial", - "reasons": [{"reason_code": "static_parse_limit", "analyzers": ["static_patterns_tool_misuse"]}], - } - - finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + finding, _is_error = SecurityValidator._convert_skillspector_issue(self._runtime_parse_limit_issue()) assert "at target line" not in finding.suggestion assert "at target lines" not in finding.suggestion - def test_static_parse_limit_single_line_span_uses_target_line(self) -> None: - issue = _report()["issues"][0] - issue["evidence"] = { - "target_path": "hooks/hooks.json", - "target_disposition": "partial", - "reasons": [ - { - "reason_code": "static_parse_limit", - "analyzers": ["static_patterns_tool_misuse"], - "parser_diagnostic": {"start_line": 11, "end_line": 11}, - } - ], - } + def test_single_line_ledger_span_uses_target_line(self) -> None: + completeness = copy.deepcopy(_report(_MJS_PARSE_LIMIT_REPORT)["analysis_completeness"]) + completeness["ledger_exceptions"][1]["parser_diagnostic"].update(start_line=11, end_line=11) - finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + finding, _is_error = SecurityValidator._convert_skillspector_issue( + self._runtime_parse_limit_issue(), completeness=completeness + ) assert "at target line 11" in finding.suggestion assert "at target lines" not in finding.suggestion + def test_legacy_ledger_row_parser_span_is_quoted(self) -> None: + """Without structured reasons, the ledger row itself carries the span.""" + issue = self._runtime_parse_limit_issue() + issue["evidence"]["reasons"] = [] + completeness = _report(_MJS_PARSE_LIMIT_REPORT)["analysis_completeness"] + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue, completeness=completeness) + + assert "at target lines 74-170" in finding.suggestion + def test_row_end_line_without_parser_diagnostic_keeps_upstream_suggestion_and_id(self) -> None: """A row that already has lines 3-7 must keep the upstream suggestion and finding ID.""" issue = _report()["issues"][0] From dcee7421cb2280eddd50eee5b175d54f1e077650 Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:06:21 -0800 Subject: [PATCH 3/4] fix(security): mark parser spans with a public line_source field A reason whose lines come from a parser_diagnostic now carries line_source: "parser_diagnostic" instead of the private _parser_span marker. reference_suggestion reads that field and no longer mutates the evidence it is given, so issue_diagnostics output has no underscore-prefixed keys and repeated calls return the same suggestion and finding ID. Signed-off-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> --- CHANGELOG.md | 3 ++- docs/tier1-reference.mdx | 4 ++- src/skillevaluator/skillspector_references.py | 27 ++++++++++--------- ...test_skillspector_reference_diagnostics.py | 24 ++++++++++++++--- 4 files changed, 40 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f6d395754..38244efd3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,7 +87,8 @@ All notable changes to SkillEvaluator are documented in this file. SkillSpector leaves `parser_diagnostic` out of the finding's `evidence.reasons`, so the span comes from the one `analysis_completeness.ledger_exceptions` row with the same path and `reason_code`, and none is shown when several rows - match. Because the suggestion text changes, the `finding_id` of each such AE1 + match. That reason in `skillspector_evidence.reasons` carries + `line_source: "parser_diagnostic"`. Because the suggestion text changes, the `finding_id` of each such AE1 finding changes once with this release. ## 1.0.1 - 2026-11-17 diff --git a/docs/tier1-reference.mdx b/docs/tier1-reference.mdx index e24757333..6bbc48a07 100644 --- a/docs/tier1-reference.mdx +++ b/docs/tier1-reference.mdx @@ -954,7 +954,9 @@ Tier 1 checks always gate the exit code inside `validate`. Tier 2 gates when it analyzers=static_patterns_tool_misuse]` and adds a short hint to review those lines and prefer fixed argument lists. An AE1 finding for a skill line that names the helper quotes the same span in its suggestion - (`at target lines 74-170`), read from that ledger row. Updating SkillSpector does + (`at target lines 74-170`), read from that ledger row; the reason in + its `skillspector_evidence` metadata has + `line_source: "parser_diagnostic"`. Updating SkillSpector does not clear this limit today. If the helper is valid and the command is safe, report a minimal reproducer to SkillSpector. JSON reports keep a bounded `parser_diagnostic` on the matching diff --git a/src/skillevaluator/skillspector_references.py b/src/skillevaluator/skillspector_references.py index 9f82f92b6..a83d496b9 100644 --- a/src/skillevaluator/skillspector_references.py +++ b/src/skillevaluator/skillspector_references.py @@ -71,9 +71,10 @@ # must stay the same across runs, so it shows only the limits that the file and # the configuration fix; the finding's metadata keeps every limit. _RUN_DEPENDENT_LIMITS = frozenset(field for field, seconds in _LIMIT_FIELDS if seconds) -# Set on a reason only while building the suggestion, then dropped. A row's own -# end_line stays in metadata and must not change grouping or finding IDs. -_PARSER_SPAN = "_parser_span" +# A reason's ``line_source`` when its lines come from a ``parser_diagnostic``. +# Only such a span is quoted as a range: a row's own end_line stays in +# metadata and must not change grouping or finding IDs. +_PARSER_DIAGNOSTIC = "parser_diagnostic" def diagnostic_text(value: object, *, max_length: int = 4096) -> str | None: @@ -203,7 +204,7 @@ def _reasons(rows: object, text: Callable[..., str | None]) -> list[dict]: if start is not None and end is not None and end >= start: reason["start_line"] = start reason["end_line"] = end - reason[_PARSER_SPAN] = True + reason["line_source"] = _PARSER_DIAGNOSTIC metrics = row.get("limits") if isinstance(metrics, dict): limits = {} @@ -360,7 +361,8 @@ def issue_diagnostics( target's ledger rows in *completeness* (or *legacy_reason_index*), and the finding gets no evidence without them. A structured reason without a line takes the ``parser_diagnostic`` span of its one matching ledger row in - *completeness*. ``skillspector_occurrences`` lists + *completeness*; a reason whose lines come from a ``parser_diagnostic`` + has ``line_source: "parser_diagnostic"``. ``skillspector_occurrences`` lists up to 128 of the issue's ``occurrences``. Any other issue gets ``{}``. Paths go through *normalize_path* and other text through *text*. """ @@ -412,8 +414,9 @@ def _reason_details(reasons: list[dict]) -> list[str]: The run time and the time budget (``observed_seconds``, ``limit_seconds``) are left out, so the text, and the ``finding_id`` that hashes it, is the - same in every run of one scan. A ``parser_diagnostic`` span is part of that - text; an ``end_line`` that was already on the row is not. + same in every run of one scan. A span whose ``line_source`` is + ``parser_diagnostic`` is part of that text; an ``end_line`` that was + already on the row is not. """ grouped: dict[tuple, list[str]] = {} for reason in reasons: @@ -421,7 +424,7 @@ def _reason_details(reasons: list[dict]) -> list[str]: (key, value) for key, value in (reason.get("limits") or {}).items() if key not in _RUN_DEPENDENT_LIMITS ) start_line = reason.get("start_line") - parser_end = reason.get("end_line") if reason.get(_PARSER_SPAN) is True else None + parser_end = reason.get("end_line") if reason.get("line_source") == _PARSER_DIAGNOSTIC else None if parser_end == start_line: parser_end = None key = ( @@ -458,7 +461,8 @@ def reference_suggestion( SkillSpector's own remediation is kept unless it is missing or the generic text of releases before v2.12.0. A specific remedy is then chosen only from a complete list of reasons, because the visible part of a truncated list - cannot show that one remedy covers every cause. + cannot show that one remedy covers every cause. *evidence* is not + changed, so every call returns the same text. """ reasons = evidence["reasons"] truncated = evidence.get("reasons_truncated") is True @@ -482,10 +486,7 @@ def reference_suggestion( "`--format json` and review the rows for this file in " "`analysis_completeness.ledger_exceptions`, then address every limitation before rerunning the scan." ) - details = _reason_details(reasons) - for reason in reasons: - reason.pop(_PARSER_SPAN, None) - return " ".join([summary, *details, action]) + return " ".join([summary, *_reason_details(reasons), action]) def reference_summary(findings: Iterable[object]) -> dict | None: diff --git a/tests/validators/test_skillspector_reference_diagnostics.py b/tests/validators/test_skillspector_reference_diagnostics.py index aa34c4416..c74c5aca7 100644 --- a/tests/validators/test_skillspector_reference_diagnostics.py +++ b/tests/validators/test_skillspector_reference_diagnostics.py @@ -34,6 +34,7 @@ AE1_PATTERN, index_legacy_reference_reasons, issue_diagnostics, + reference_suggestion, reference_summary_message, report_path, ) @@ -380,14 +381,31 @@ def test_captured_ledger_span_reaches_a_scanner_shaped_finding(self) -> None: assert "static_parse_limit (static_patterns_tool_misuse) at target lines 74-170:" in finding.suggestion reason = finding.metadata["skillspector_evidence"]["reasons"][0] assert (reason["start_line"], reason["end_line"]) == (74, 170) - assert "parser_diagnostic" not in reason - assert "_parser_span" not in reason + assert reason["line_source"] == "parser_diagnostic" + assert not any(key.startswith("_") for key in reason) assert "source_start_offset" not in json.dumps(finding.metadata) # The suggestion is new, so the finding_id changes once from a finding without the span. baseline, _ = SecurityValidator._convert_skillspector_issue(without_ledger) assert "at target line" not in baseline.suggestion assert finding.finding_id != baseline.finding_id + def test_parser_span_suggestion_does_not_depend_on_call_order(self) -> None: + """``issue_diagnostics`` alone has no private keys, and ``reference_suggestion`` is repeatable.""" + completeness = _report(_MJS_PARSE_LIMIT_REPORT)["analysis_completeness"] + metadata = issue_diagnostics( + self._runtime_parse_limit_issue(), normalize_path=report_path, completeness=completeness + ) + evidence = metadata["skillspector_evidence"] + assert not any(key.startswith("_") for reason in evidence["reasons"] for key in reason) + before = copy.deepcopy(evidence) + + first = reference_suggestion(evidence, None) + second = reference_suggestion(evidence, None) + + assert "at target lines 74-170" in first + assert second == first + assert evidence == before + def test_ledger_span_is_read_only_from_the_one_matching_row(self) -> None: completeness = copy.deepcopy(_report(_MJS_PARSE_LIMIT_REPORT)["analysis_completeness"]) rows = completeness["ledger_exceptions"] @@ -472,7 +490,7 @@ def test_row_end_line_without_parser_diagnostic_keeps_upstream_suggestion_and_id assert "3-7" not in finding.suggestion assert "at target lines" not in finding.suggestion assert finding.metadata["skillspector_evidence"]["reasons"][0]["end_line"] == 7 - assert "_parser_span" not in finding.metadata["skillspector_evidence"]["reasons"][0] + assert "line_source" not in finding.metadata["skillspector_evidence"]["reasons"][0] issue["evidence"]["reasons"] = [ {"reason_code": "read_error", "start_line": 4, "end_line": 5}, From 2fc30009516bb961de887c35c8573cfee27f1345 Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:29:43 -0800 Subject: [PATCH 4/4] fix(security): name runtime-dependent parse-limit locations in the hint The incomplete-analysis error shows only the first three ledger rows, so runtime-dependent parse-limit rows could fall into "and N more" behind reference_missing rows, leaving the hint pointing at lines that were not shown. The hint now names up to three path:start-end locations itself, built the same way as the row labels. Extra locations and rows without a usable span point to parser_diagnostic on the skillspector_completeness rows of the JSON report. Signed-off-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> --- src/skillevaluator/validators/security.py | 54 ++++++++++---- .../test_skillspector_parser_locations.py | 70 ++++++++++++++++--- 2 files changed, 102 insertions(+), 22 deletions(-) diff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.py index 6a259b6e0..b55881b67 100644 --- a/src/skillevaluator/validators/security.py +++ b/src/skillevaluator/validators/security.py @@ -1185,15 +1185,22 @@ def _skillspector_parser_diagnostic_context(exception: Mapping[str, object]) -> return " ".join(parts) or None -def _skillspector_ledger_exception_label(exception: Mapping[str, object]) -> str: - """Describe one ledger exception as ``path[:line[-end]] [phase; reason; cause check; analyzers=...]``.""" - location = _skillspector_report_text(exception.get("path")) or "unknown" +def _skillspector_ledger_exception_lines(exception: Mapping[str, object]) -> str | None: + """``line`` or ``start-end`` from the row's ``start_line`` or its ``parser_diagnostic`` span, else ``None``.""" start_line = exception.get("start_line") if isinstance(start_line, int) and not isinstance(start_line, bool): - location = f"{location}:{start_line}" - elif (span := _skillspector_parser_diagnostic_span(exception.get("parser_diagnostic"))) is not None: + return str(start_line) + if (span := _skillspector_parser_diagnostic_span(exception.get("parser_diagnostic"))) is not None: start, end = span - location = f"{location}:{start}" if start == end else f"{location}:{start}-{end}" + return str(start) if start == end else f"{start}-{end}" + return None + + +def _skillspector_ledger_exception_label(exception: Mapping[str, object]) -> str: + """Describe one ledger exception as ``path[:line[-end]] [phase; reason; cause check; analyzers=...]``.""" + location = _skillspector_report_text(exception.get("path")) or "unknown" + if lines := _skillspector_ledger_exception_lines(exception): + location = f"{location}:{lines}" context = [text for key in ("phase", "reason_code") if (text := _skillspector_report_text(exception.get(key)))] if extra := _skillspector_parser_diagnostic_context(exception): context.append(extra) @@ -1265,16 +1272,19 @@ def _skillspector_runtime_limit_hint(ledger_exceptions: Iterable[Mapping[str, ob "Missing references require a standalone target with complete, matching reference and scan evidence. " "See https://docs.nvidia.com/skills/skillevaluator/tier1-validation." ) -_SKILLSPECTOR_PARSE_LIMIT_HINT = ( - "SkillSpector could not resolve a command or code string that is only known at run time " - "(for example a process spawn whose arguments come from variables), in the reported lines. " - "Review those lines, prefer fixed argument lists, and if the code is valid and safe report a " +_SKILLSPECTOR_PARSE_LIMIT_ADVICE = ( + "Review that code, prefer fixed argument lists, and if the code is valid and safe report a " "minimal reproducer to SkillSpector; updating SkillSpector does not clear this limit today." ) +_SKILLSPECTOR_PARSE_LIMIT_JSON_POINTER = "parser_diagnostic on the skillspector_completeness rows of the JSON report" def _skillspector_parse_limit_hint(ledger_exceptions: Iterable[Mapping[str, object]]) -> str | None: - """Explain ``runtime_dependent`` parse limits, or ``None`` when that is not every parse-limit row.""" + """Explain ``runtime_dependent`` parse limits, or ``None`` when that is not every parse-limit row. + + The hint names the affected locations itself, because the error shows only the + first few ledger rows and those may all be unrelated (for example missing references). + """ parse_limit_rows = [row for row in ledger_exceptions if row.get("reason_code") == "static_parse_limit"] if not parse_limit_rows: return None @@ -1285,7 +1295,27 @@ def _skillspector_parse_limit_hint(ledger_exceptions: Iterable[Mapping[str, obje cause = diagnostic.get("cause") if not isinstance(cause, str) or cause.strip() != "runtime_dependent": return None - return _SKILLSPECTOR_PARSE_LIMIT_HINT + locations: list[str] = [] + for row in parse_limit_rows: + path = _skillspector_report_text(row.get("path")) + lines = _skillspector_ledger_exception_lines(row) + if path is None and lines is None: + continue + location = f"{path or 'unknown'}:{lines}" if lines else str(path) + if location not in locations: + locations.append(location) + shown = locations[:_SKILLSPECTOR_INCOMPLETE_EXAMPLES] + if not shown: + where = f"at the locations in {_SKILLSPECTOR_PARSE_LIMIT_JSON_POINTER}" + else: + where = f"in {shown[0]}" if len(shown) == 1 else f"in {', '.join(shown[:-1])} and {shown[-1]}" + if remaining := len(locations) - len(shown): + where = f"{where}, and {remaining} more listed in {_SKILLSPECTOR_PARSE_LIMIT_JSON_POINTER}" + return ( + "SkillSpector could not resolve a command or code string that is only known at run time " + f"(for example a process spawn whose arguments come from variables) {where}. " + f"{_SKILLSPECTOR_PARSE_LIMIT_ADVICE}" + ) def _skillspector_incomplete_analysis_error(status: str, ledger_exceptions: list[dict]) -> str: diff --git a/tests/validators/test_skillspector_parser_locations.py b/tests/validators/test_skillspector_parser_locations.py index fc865c2b5..c31e100be 100644 --- a/tests/validators/test_skillspector_parser_locations.py +++ b/tests/validators/test_skillspector_parser_locations.py @@ -23,7 +23,7 @@ from skillevaluator.reporting.json_reporter import JSONReporter from skillevaluator.validators.security import ( - _SKILLSPECTOR_PARSE_LIMIT_HINT, + _SKILLSPECTOR_PARSE_LIMIT_ADVICE, _SKILLSPECTOR_REFERENCE_REJECTION_HINT, _skillspector_incomplete_analysis_error, _skillspector_ledger_exception_label, @@ -76,7 +76,11 @@ def test_captured_mjs_rows_use_the_parser_span_and_runtime_dependent_context() - "skillspector JSON field 'analysis_completeness' reports incomplete analysis (status 'partial'): " ) assert labels[0] in error and labels[1] in error and labels[2] in error - assert error.endswith(_SKILLSPECTOR_PARSE_LIMIT_HINT) + assert ( + "(for example a process spawn whose arguments come from variables) in " + "scripts/admission.mjs:74-170 and scripts/machine-reading.mjs:104-236. " + ) in error + assert error.endswith(_SKILLSPECTOR_PARSE_LIMIT_ADVICE) assert _SKILLSPECTOR_REFERENCE_REJECTION_HINT not in error @@ -151,12 +155,12 @@ def test_runtime_dependent_hint_requires_every_parse_limit_row() -> None: runtime = _parse_limit_row() other = _parse_limit_row(path="scripts/other.mjs", parser_diagnostic=dict(_BOUNDARY_DIAGNOSTIC)) missing = _ledger_exception("scripts/plain.mjs", "static_parse_limit") - assert _SKILLSPECTOR_PARSE_LIMIT_HINT in _skillspector_incomplete_analysis_error("partial", [runtime]) + assert _SKILLSPECTOR_PARSE_LIMIT_ADVICE in _skillspector_incomplete_analysis_error("partial", [runtime]) mixed = _skillspector_incomplete_analysis_error("partial", [runtime, other]) - assert _SKILLSPECTOR_PARSE_LIMIT_HINT not in mixed + assert _SKILLSPECTOR_PARSE_LIMIT_ADVICE not in mixed assert "scripts/other.mjs:11 [" in mixed - assert _SKILLSPECTOR_PARSE_LIMIT_HINT not in _skillspector_incomplete_analysis_error("partial", [missing]) - assert _SKILLSPECTOR_PARSE_LIMIT_HINT not in _skillspector_incomplete_analysis_error( + assert _SKILLSPECTOR_PARSE_LIMIT_ADVICE not in _skillspector_incomplete_analysis_error("partial", [missing]) + assert _SKILLSPECTOR_PARSE_LIMIT_ADVICE not in _skillspector_incomplete_analysis_error( "partial", [_ledger_exception("scripts/render.py", "static_parse_limit") | {"start_line": 12}] ) @@ -170,15 +174,61 @@ def test_parse_limit_hint_combines_with_runtime_limit_and_not_with_reference_rej } combined = _skillspector_incomplete_analysis_error("partial", [runtime_limit, parse_limit]) assert "SkillSpector reached a runtime limit before it finished 1 file(s)." in combined - assert _SKILLSPECTOR_PARSE_LIMIT_HINT in combined + assert _SKILLSPECTOR_PARSE_LIMIT_ADVICE in combined assert _SKILLSPECTOR_REFERENCE_REJECTION_HINT not in combined with_reference = _skillspector_incomplete_analysis_error("partial", [reference, parse_limit]) assert "SKILL.md:150 [reference_resolution; reference_missing]" in with_reference - assert _SKILLSPECTOR_PARSE_LIMIT_HINT in with_reference + assert _SKILLSPECTOR_PARSE_LIMIT_ADVICE in with_reference assert _SKILLSPECTOR_REFERENCE_REJECTION_HINT not in with_reference only_reference = _skillspector_incomplete_analysis_error("partial", [reference]) assert only_reference.endswith(_SKILLSPECTOR_REFERENCE_REJECTION_HINT) - assert _SKILLSPECTOR_PARSE_LIMIT_HINT not in only_reference + assert _SKILLSPECTOR_PARSE_LIMIT_ADVICE not in only_reference + + +def _reference_row(line: int) -> dict: + return { + **_ledger_exception("SKILL.md", "reference_missing", analyzers=(), phase="reference_resolution"), + "start_line": line, + } + + +def test_parse_limit_hint_names_locations_hidden_behind_earlier_rows() -> None: + rows = [_reference_row(10), _reference_row(20), _reference_row(30), _parse_limit_row()] + error = _skillspector_incomplete_analysis_error("partial", rows) + # The shown examples are the three reference rows; the helper's span is in "and 1 more". + assert "scripts/helper.mjs:74-170 [" not in error + assert "; and 1 more " in error + assert ( + "(for example a process spawn whose arguments come from variables) in scripts/helper.mjs:74-170. " + f"{_SKILLSPECTOR_PARSE_LIMIT_ADVICE}" + ) in error + + +def test_parse_limit_hint_caps_named_locations_and_points_to_the_json_report() -> None: + rows = [ + _parse_limit_row(path=f"scripts/helper{index}.mjs", parser_diagnostic=dict(_RUNTIME_DIAGNOSTIC)) + for index in range(5) + ] + rows.append(_parse_limit_row(path="scripts/helper0.mjs")) + error = _skillspector_incomplete_analysis_error("partial", rows) + assert ( + "in scripts/helper0.mjs:74-170, scripts/helper1.mjs:74-170 and scripts/helper2.mjs:74-170, " + "and 2 more listed in parser_diagnostic on the skillspector_completeness rows of the JSON report. " + ) in error + + +def test_parse_limit_hint_without_a_span_names_the_path_or_the_json_report() -> None: + no_span = {"cause": "runtime_dependent", "check": "command_string_runtime"} + path_only = _skillspector_incomplete_analysis_error("partial", [_parse_limit_row(parser_diagnostic=no_span)]) + assert "come from variables) in scripts/helper.mjs. " in path_only + nothing = _parse_limit_row(parser_diagnostic=no_span) + del nothing["path"] + unknown = _skillspector_incomplete_analysis_error("partial", [nothing]) + assert ( + "come from variables) at the locations in parser_diagnostic on the skillspector_completeness rows " + "of the JSON report. " + ) in unknown + assert unknown.endswith(_SKILLSPECTOR_PARSE_LIMIT_ADVICE) @patch("skillevaluator.validators.security.Tools") @@ -194,7 +244,7 @@ def test_partial_scan_stays_incomplete_and_projects_parser_diagnostic(mock_tools "scripts/helper.mjs:74-170 [static; static_parse_limit; runtime_dependent command_string_runtime; " "analyzers=static_patterns_tool_misuse]" ) in result.errors[0] - assert result.errors[0].endswith(_SKILLSPECTOR_PARSE_LIMIT_HINT) + assert result.errors[0].endswith(_SKILLSPECTOR_PARSE_LIMIT_ADVICE) record = json.loads(JSONReporter().render(result))["skillspector_completeness"]["records"][0] diagnostic = record["ledger_exceptions"][0]["parser_diagnostic"] assert diagnostic == {