Skip to content

Commit b30ba80

Browse files
authored
Merge pull request #725 from YMuskrat/fix/terminal-literal-text
fix(report): display terminal report text literally
2 parents 4c52fbb + b377cc6 commit b30ba80

5 files changed

Lines changed: 407 additions & 51 deletions

File tree

‎src/skillspector/cli.py‎

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@
8585
load_baseline,
8686
source_content_key,
8787
)
88+
from skillspector.terminal_text import visible_terminal_text as _visible_terminal_text
8889

8990
logger = get_logger(__name__)
9091

@@ -379,7 +380,7 @@ def _write_result(
379380
console.print(f"Report saved to: {output}")
380381
else:
381382
if format == FormatChoice.terminal:
382-
console.print(report_body, markup=False)
383+
console.print(report_body, markup=False, emoji=False)
383384
else:
384385
print(report_body)
385386

@@ -1490,23 +1491,6 @@ def _scope_finding(finding: Finding) -> Finding:
14901491
)
14911492

14921493

1493-
def _visible_terminal_text(value: str) -> str:
1494-
"""Render untrusted path text without passing terminal control characters."""
1495-
visible: list[str] = []
1496-
for character in value:
1497-
if character.isprintable():
1498-
visible.append(character)
1499-
continue
1500-
codepoint = ord(character)
1501-
if codepoint <= 0xFF:
1502-
visible.append(f"\\x{codepoint:02x}")
1503-
elif codepoint <= 0xFFFF:
1504-
visible.append(f"\\u{codepoint:04x}")
1505-
else:
1506-
visible.append(f"\\U{codepoint:08x}")
1507-
return "".join(visible)
1508-
1509-
15101494
def _discovered_files_tree(paths: list[str]) -> Tree:
15111495
"""Build a literal, control-safe tree for paths from an untrusted bundle."""
15121496
tree = Tree(Text("Discovered Files to Scan", style="bold blue"))
@@ -3356,7 +3340,7 @@ def _scan_multi_skill(
33563340
Path(output).write_text(rendered, encoding="utf-8")
33573341
progress_console.print(f"[green]Combined report saved to:[/green] {output}")
33583342
elif format is FormatChoice.terminal:
3359-
console.print(rendered)
3343+
console.print(rendered, markup=False, emoji=False)
33603344
else:
33613345
sys.stdout.write(rendered)
33623346

‎src/skillspector/nodes/report.py‎

Lines changed: 87 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@
3333
from urllib.parse import quote
3434

3535
from rich.console import Console
36-
from rich.markup import escape
3736
from rich.panel import Panel
3837
from rich.table import Table
38+
from rich.text import Text
3939

4040
from skillspector import __version__ as skillspector_version
4141
from skillspector.dependency_sources import redact_text
@@ -85,6 +85,7 @@
8585
)
8686
from skillspector.state import SkillspectorState, transitive_remaining_seconds
8787
from skillspector.suppression import Baseline, SuppressedFinding, partition_findings
88+
from skillspector.terminal_text import visible_terminal_text
8889

8990
logger = get_logger(__name__)
9091

@@ -1014,6 +1015,11 @@ def notification_from_exception(
10141015
return rendered
10151016

10161017

1018+
def _terminal_text(value: object, style: str = "") -> Text:
1019+
"""Keep dynamic text literal and render its non-printable characters visibly."""
1020+
return Text(visible_terminal_text(str(value)), style=style)
1021+
1022+
10171023
def _render_terminal_completeness(
10181024
console: Console,
10191025
completeness: Mapping[str, object],
@@ -1025,24 +1031,30 @@ def _render_terminal_completeness(
10251031
table.add_column("Metric", style="bold")
10261032
table.add_column("Value")
10271033
table.add_row("Execution", "successful" if execution_successful else "failed")
1028-
table.add_row("Status", str(completeness.get("status", "complete")))
1029-
table.add_row("Coverage", f"{completeness.get('coverage_percent', 100.0)}%")
1030-
table.add_row("Fully inspected", str(completeness.get("fully_inspected_files", 0)))
1031-
table.add_row("Partially inspected", str(completeness.get("partially_inspected_files", 0)))
1032-
table.add_row("Entirely uninspected", str(completeness.get("entirely_uninspected_files", 0)))
1034+
table.add_row("Status", _terminal_text(completeness.get("status", "complete")))
1035+
table.add_row("Coverage", _terminal_text(f"{completeness.get('coverage_percent', 100.0)}%"))
1036+
table.add_row("Fully inspected", _terminal_text(completeness.get("fully_inspected_files", 0)))
1037+
table.add_row(
1038+
"Partially inspected", _terminal_text(completeness.get("partially_inspected_files", 0))
1039+
)
1040+
table.add_row(
1041+
"Entirely uninspected", _terminal_text(completeness.get("entirely_uninspected_files", 0))
1042+
)
10331043
if completeness.get("exclude_patterns"):
10341044
table.add_row(
1035-
"Explicit exclusion patterns", escape(", ".join(completeness["exclude_patterns"]))
1045+
"Explicit exclusion patterns",
1046+
_terminal_text(", ".join(completeness["exclude_patterns"])),
10361047
)
10371048
table.add_row(
1038-
"Excluded files (not inspected)", str(completeness.get("excluded_file_count", 0))
1049+
"Excluded files (not inspected)",
1050+
_terminal_text(completeness.get("excluded_file_count", 0)),
10391051
)
10401052
console.print(table)
10411053

10421054
def render_rows(title: str, rows: object) -> None:
10431055
if not isinstance(rows, list) or not rows:
10441056
return
1045-
console.print(f"[bold]{escape(title)}[/bold]")
1057+
console.print(_terminal_text(title, "bold"))
10461058
for row in rows:
10471059
if not isinstance(row, Mapping):
10481060
continue
@@ -1057,7 +1069,7 @@ def render_rows(title: str, rows: object) -> None:
10571069
location = f"rule set {location}"
10581070
reason = str(row.get("reason_code", row.get("status", "status")))
10591071
message = str(row.get("message", ""))
1060-
console.print(f" - {escape(reason)} {escape(location)}: {escape(message)}")
1072+
console.print(_terminal_text(f" - {reason} {location}: {message}"))
10611073

10621074
render_rows("Scope exclusions", completeness.get("scope_exclusions"))
10631075
render_rows("Ledger exceptions", completeness.get("ledger_exceptions"))
@@ -1066,7 +1078,7 @@ def render_rows(title: str, rows: object) -> None:
10661078
if isinstance(limitations, list) and limitations:
10671079
console.print("[bold]Limitations[/bold]")
10681080
for limitation in limitations:
1069-
console.print(f" - {escape(str(limitation))}")
1081+
console.print(_terminal_text(f" - {limitation}"))
10701082

10711083

10721084
def _format_terminal(
@@ -1087,9 +1099,9 @@ def _format_terminal(
10871099
analysis_completeness: Mapping[str, object] | None = None,
10881100
execution_successful: bool = True,
10891101
) -> str:
1090-
"""Generate Rich terminal output and export as string."""
1102+
"""Generate styled Rich output with literal, control-safe dynamic text."""
10911103
suppressed = suppressed or []
1092-
console = Console(record=True, force_terminal=True, width=80, file=StringIO())
1104+
console = Console(record=True, force_terminal=True, width=80, file=StringIO(), emoji=False)
10931105
skill_name = (manifest.get("name") or "unknown") if manifest else "unknown"
10941106
source = skill_path or ""
10951107

@@ -1100,8 +1112,8 @@ def _format_terminal(
11001112
subtitle=f"v{skillspector_version}",
11011113
)
11021114
)
1103-
console.print(f"\n[bold]Skill:[/bold] {skill_name}")
1104-
console.print(f"[bold]Source:[/bold] {source}")
1115+
console.print(Text.assemble("\n", ("Skill: ", "bold"), _terminal_text(skill_name)))
1116+
console.print(Text.assemble(("Source: ", "bold"), _terminal_text(source)))
11051117
console.print(f"[bold]Scanned:[/bold] {datetime.now(UTC).strftime('%Y-%m-%d %H:%M:%S UTC')}")
11061118

11071119
severity_colors = {
@@ -1134,7 +1146,9 @@ def _format_terminal(
11341146
lines = comp.get("lines", 0)
11351147
exec_flag = comp.get("executable", False)
11361148
exec_marker = "[yellow]Yes[/yellow]" if exec_flag else "No"
1137-
comp_table.add_row(path, typ, str(lines), exec_marker)
1149+
comp_table.add_row(
1150+
_terminal_text(path), _terminal_text(typ), _terminal_text(lines), exec_marker
1151+
)
11381152
if len(component_metadata) > 15:
11391153
comp_table.add_row(f"... and {len(component_metadata) - 15} more", "", "", "")
11401154
console.print(comp_table)
@@ -1146,7 +1160,9 @@ def _format_terminal(
11461160
console.print()
11471161
console.print(
11481162
Panel(
1149-
f"[bold]Degraded scan[/bold]\n{effective_degraded_notice}",
1163+
Text.assemble(
1164+
("Degraded scan\n", "bold"), _terminal_text(effective_degraded_notice)
1165+
),
11501166
title="[bold red]WARNING[/bold red]",
11511167
border_style="red",
11521168
)
@@ -1156,24 +1172,50 @@ def _format_terminal(
11561172
console.print("\n")
11571173
console.print(f"[bold]Issues ({len(findings)})[/bold]\n")
11581174
severity_icons = {
1159-
"LOW": "[green]LOW[/green]",
1160-
"MEDIUM": "[yellow]MEDIUM[/yellow]",
1161-
"HIGH": "[red]HIGH[/red]",
1162-
"CRITICAL": "[bold red]CRITICAL[/bold red]",
1175+
"LOW": Text("LOW", style="green"),
1176+
"MEDIUM": Text("MEDIUM", style="yellow"),
1177+
"HIGH": Text("HIGH", style="red"),
1178+
"CRITICAL": Text("CRITICAL", style="bold red"),
11631179
}
11641180
for f in findings:
1165-
icon = severity_icons.get((f.severity or "LOW").upper(), f.severity)
1166-
console.print(f" {icon}: {f.rule_id} - {f.message[:60]}...")
1181+
icon = severity_icons.get(
1182+
(f.severity or "LOW").upper(), _terminal_text(f.severity or "")
1183+
)
1184+
console.print(
1185+
Text.assemble(
1186+
" ",
1187+
icon,
1188+
": ",
1189+
_terminal_text(f.rule_id),
1190+
" - ",
1191+
_terminal_text(f.message[:60]),
1192+
"...",
1193+
)
1194+
)
11671195
end = f"–{f.end_line}" if f.end_line and f.end_line != f.start_line else ""
1168-
console.print(f" [dim]Location:[/dim] {f.file}:{f.start_line}{end}")
1196+
console.print(
1197+
Text.assemble(
1198+
(" Location: ", "dim"), _terminal_text(f.file), f":{f.start_line}{end}"
1199+
)
1200+
)
11691201
if f.source_url:
1170-
console.print(f" [dim]Source:[/dim] {f.source_url} (depth {f.transitive_depth})")
1202+
console.print(
1203+
Text.assemble(
1204+
(" Source: ", "dim"),
1205+
_terminal_text(f.source_url),
1206+
f" (depth {f.transitive_depth})",
1207+
)
1208+
)
11711209
console.print(f" [dim]Confidence:[/dim] {f.confidence:.0%}")
11721210
if f.remediation:
1173-
console.print(f" [dim]Remediation:[/dim] {(f.remediation or '')[:150]}...")
1211+
console.print(
1212+
Text.assemble(
1213+
(" Remediation: ", "dim"), _terminal_text(f.remediation[:150]), "..."
1214+
)
1215+
)
11741216
if f.evidence:
11751217
rendered = ", ".join(f"{key}={value}" for key, value in sorted(f.evidence.items()))
1176-
console.print(f" [dim]Evidence:[/dim] {rendered}")
1218+
console.print(Text.assemble((" Evidence: ", "dim"), _terminal_text(rendered)))
11771219
console.print()
11781220
else:
11791221
console.print("\n[green]No security issues detected.[/green]\n")
@@ -1183,11 +1225,16 @@ def _format_terminal(
11831225
console.print(f"[bold]Structured Skill Summary ({len(structured_summaries)})[/bold]\n")
11841226
for summary in structured_summaries:
11851227
console.print(
1186-
f" [cyan]{summary.get('id', 'SSR-1')}[/cyan]: {summary.get('message', '')}"
1228+
Text.assemble(
1229+
" ",
1230+
_terminal_text(summary.get("id", "SSR-1"), "cyan"),
1231+
": ",
1232+
_terminal_text(summary.get("message", "")),
1233+
)
11871234
)
11881235
file = _summary_display_value(summary.get("file"))
11891236
if file:
1190-
console.print(f" [dim]File:[/dim] {file}")
1237+
console.print(Text.assemble((" File: ", "dim"), _terminal_text(file)))
11911238
for key, label in (
11921239
("protocol", "Protocol"),
11931240
("layout_kind", "Layout"),
@@ -1199,7 +1246,7 @@ def _format_terminal(
11991246
):
12001247
value = _summary_display_value(summary.get(key))
12011248
if value:
1202-
console.print(f" [dim]{label}:[/dim] {value}")
1249+
console.print(Text.assemble((f" {label}: ", "dim"), _terminal_text(value)))
12031250
console.print()
12041251

12051252
if suppressed:
@@ -1210,7 +1257,16 @@ def _format_terminal(
12101257
for sf in suppressed:
12111258
f = sf.finding
12121259
console.print(
1213-
f" [dim]- {f.rule_id} {f.file}:{f.start_line} (reason: {sf.reason})[/dim]"
1260+
Text.assemble(
1261+
" - ",
1262+
_terminal_text(f.rule_id),
1263+
" ",
1264+
_terminal_text(f.file),
1265+
f":{f.start_line} (reason: ",
1266+
_terminal_text(sf.reason),
1267+
")",
1268+
style="dim",
1269+
)
12141270
)
12151271
else:
12161272
console.print("[dim]Use --show-suppressed to list them.[/dim]")

‎src/skillspector/terminal_text.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
"""Visible rendering of untrusted text for terminal output."""
17+
18+
19+
def visible_terminal_text(value: str) -> str:
20+
"""Display non-printable characters as escapes instead of terminal instructions."""
21+
visible: list[str] = []
22+
for character in value:
23+
if character.isprintable():
24+
visible.append(character)
25+
continue
26+
codepoint = ord(character)
27+
if codepoint <= 0xFF:
28+
visible.append(f"\\x{codepoint:02x}")
29+
elif codepoint <= 0xFFFF:
30+
visible.append(f"\\u{codepoint:04x}")
31+
else:
32+
visible.append(f"\\U{codepoint:08x}")
33+
return "".join(visible)

0 commit comments

Comments
 (0)