From 0cda5043b0df00edb0c3816e3aa2d8c548049b38 Mon Sep 17 00:00:00 2001 From: Adith K B <20210193@sastra.ac.in> Date: Fri, 18 Sep 2026 11:17:19 +0100 Subject: [PATCH 1/2] feat: add GitHub Copilot CLI agent adapter Adds CopilotAdapter for the standalone `copilot` binary (npm @github/copilot, GA since Feb 2026) -- not the retired `gh copilot` extension, which now just shells out to this same binary. Flags verified against a real `copilot --help` (v1.0.86) and against a real end-to-end `secfoo run --skill sast --agent copilot` invocation, not just docs (the pre-GA extension used different flags entirely, and these change often). Also fixes report/markdown.py's strip_preamble(): it assumed every agent emits a literal top-level "# Report" heading to anchor on, but real testing against Copilot CLI found it unpromptedly runs its own native security-scan tool first (an unrelated "##"/"###" preamble) and then never emits that single top-level heading at all, so the anchor search found nothing and left the whole duplicated block in the stored report. Adds a fallback anchor on "## 1. Executive Summary" -- every skill's contract requires that as its first numbered section regardless of agent, so it's a safe backstop that doesn't change behavior for any already-compliant agent. Verified against the actual captured Copilot report: 713 lines down to 281, landing exactly on the real content. Co-Authored-By: Claude Sonnet 5 --- src/secfoo/agents/copilot.py | 76 ++++++++++++++++++++++++++++++ src/secfoo/agents/registry.py | 2 + src/secfoo/cli.py | 1 + src/secfoo/report/markdown.py | 21 ++++++++- tests/test_agents/test_copilot.py | 62 ++++++++++++++++++++++++ tests/test_report/test_markdown.py | 28 +++++++++++ 6 files changed, 188 insertions(+), 2 deletions(-) create mode 100644 src/secfoo/agents/copilot.py create mode 100644 tests/test_agents/test_copilot.py diff --git a/src/secfoo/agents/copilot.py b/src/secfoo/agents/copilot.py new file mode 100644 index 0000000..abc2ea8 --- /dev/null +++ b/src/secfoo/agents/copilot.py @@ -0,0 +1,76 @@ +"""GitHub Copilot CLI adapter. + +Binary is `copilot` (npm package `@github/copilot`, GA since Feb 2026) -- +not the older `gh copilot` GitHub CLI extension, which is now just a thin +wrapper that shells out to this same binary. Flags verified against a real +`copilot --help` (Sep 2026, CLI version 1.0.86); the CLI ships updates +often and flags have already drifted once (the pre-GA `gh copilot` +extension used different flags entirely), so re-verify before trusting an +older doc. + +`--allow-all-tools` is not a convenience flag here -- `copilot --help` +states it directly: "required for non-interactive mode." Without it, `-p` +just hangs waiting for a permission prompt that can never be answered +non-interactively. + +Deliberately does NOT pass `--allow-all-paths` or `--allow-all-urls` (both +folded into the broader `--allow-all`/`--yolo` flags) -- a read-only +security review only needs to read files already inside the target +workdir and never needs unrestricted filesystem or network access. +`--allow-all-tools` alone still lets the model use tools like `write` +without a prompt, but secfoo's prompts are read-only reviews by +instruction, not by sandboxing, matching the same trust level the other +adapters accept (none of claude.py/cursor.py/gemini.py/antigravity.py +sandbox writes at the OS level either). + +`-s`/`--silent` drops the token-usage stats banner so stdout is just the +agent's answer -- confirmed directly (no JSON envelope to unwrap, unlike +claude.py/gemini.py), so `extract_report()` is not overridden here. + +CONFIRMED QUIRK (reproduced twice, Sep 2026 -- once on a casual prompt, +once on a real `secfoo run --skill sast --agent copilot` end-to-end run): +this CLI unpromptedly auto-invokes its own built-in security-scanning +tool first, emitting a "## Security Findings" / "### Alert N" block (plus +its own Remediation Roadmap) *before* going on to separately produce the +skill's actual requested Markdown contract. The result is a report.md +roughly double the length it should be, with the required content +duplicated in two different shapes back-to-back. + +This is cosmetic, not a data-integrity bug -- confirmed directly against +report/sast.py's real parser: `extract_findings_register_rows()` finds +the genuine "## 3. Findings Register" section by name regardless of what +precedes it, and `count_severities()`'s `### [SEVERITY]` pattern only +matches the compliant second half (Copilot's own native Alert format +uses plain "Severity: CRITICAL" text, no brackets), so the SAST Findings +Register and dashboard severity counts both come out correct. The actual +casualty was `report/markdown.py`'s `strip_preamble()`: it assumed every +agent emits a single top-level `# Report` heading to anchor on, +but Copilot's output never uses a single `#` anywhere (every heading is +`##`/`###`), so the preamble-stripping regex found nothing to anchor on +and left the whole duplicated block in place. Fixed there (not here) by +adding a fallback anchor on "## 1. Executive Summary" -- every skill's +contract requires that as its first numbered section regardless of +which agent is running it, so it's a safe, skill-agnostic backstop for +any agent that skips the title outright. Verified against this exact +captured report: 713 lines / 29396 chars down to 281 / 14442, landing +exactly on the real content with no pollution left. No attempt was made +to suppress Copilot's native tool from firing in the first place (e.g. +via `--deny-tool`) -- the tool/skill name isn't known and guessing at it +without being able to verify the guess isn't worth the risk; cutting the +resulting preamble downstream is the safer fix. +""" + +from __future__ import annotations + +from pathlib import Path + +from secfoo.agents.base import AgentAdapter + + +class CopilotAdapter(AgentAdapter): + name = "copilot" + binary = "copilot" + default_timeout_seconds = 1800 + + def build_command(self, prompt: str, *, workdir: Path) -> list[str]: + return [self.binary, "-p", prompt, "-s", "--allow-all-tools"] diff --git a/src/secfoo/agents/registry.py b/src/secfoo/agents/registry.py index 858b90e..b6a1b29 100644 --- a/src/secfoo/agents/registry.py +++ b/src/secfoo/agents/registry.py @@ -3,6 +3,7 @@ from secfoo.agents.antigravity import AntigravityAdapter from secfoo.agents.base import AgentAdapter from secfoo.agents.claude import ClaudeAdapter +from secfoo.agents.copilot import CopilotAdapter from secfoo.agents.cursor import CursorAdapter from secfoo.agents.gemini import GeminiAdapter @@ -11,6 +12,7 @@ CursorAdapter.name: CursorAdapter, AntigravityAdapter.name: AntigravityAdapter, GeminiAdapter.name: GeminiAdapter, + CopilotAdapter.name: CopilotAdapter, } diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index effb5c2..77a5819 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -72,6 +72,7 @@ class AgentId(str, Enum): CURSOR = "agent" ANTIGRAVITY = "agy" GEMINI = "gemini" + COPILOT = "copilot" class DepthId(str, Enum): diff --git a/src/secfoo/report/markdown.py b/src/secfoo/report/markdown.py index 8612610..e35e762 100644 --- a/src/secfoo/report/markdown.py +++ b/src/secfoo/report/markdown.py @@ -46,6 +46,18 @@ ) _TOP_LEVEL_HEADING_RE = re.compile(r"^#\s+.+$", re.MULTILINE) +# Fallback anchor for an agent that skips the literal "# Report" +# title outright (observed with the copilot adapter: it unpromptedly runs +# its own native security-scan tool first, emitting an unrelated "##"/"###" +# preamble, then goes straight into the skill's required numbered sections +# without ever writing a single top-level "#" heading anywhere). Every +# skill's contract requires "## 1. Executive Summary" as its first numbered +# section (see skills/renderer.py's shared "Required output format" block), +# so it's a safe, skill-agnostic anchor to fall back to -- tried only when +# the primary title search above finds nothing, so a compliant agent's +# report (which always has both) is unaffected. +_NUMBERED_SECTION_ONE_RE = re.compile(r"^##\s+1\.\s+.+$", re.MULTILINE) + # "commonmark" alone is the strict base spec and does NOT parse GFM pipe # tables -- every `| a | b |` block silently fell through as a plain # paragraph of literal text. `enable(["table"])` turns on just the table @@ -71,10 +83,15 @@ def strip_preamble(text: str) -> str: """Drops any assistant chatter before the report's required top-level heading (`# Report`). The prompt explicitly forbids a preamble, but that instruction isn't 100% reliable in practice -- this is the - defensive backstop. Leaves text unchanged if no top-level heading is - found at all, rather than risk hiding a malformed report. + defensive backstop. Falls back to anchoring on "## 1. Executive + Summary" (see _NUMBERED_SECTION_ONE_RE above) when no top-level heading + exists at all, for an agent that skips the title outright but still + gets to the required sections eventually. Leaves text unchanged if + neither anchor is found, rather than risk hiding a malformed report. """ match = _TOP_LEVEL_HEADING_RE.search(text) + if match is None: + match = _NUMBERED_SECTION_ONE_RE.search(text) if match is None: return text return text[match.start():] diff --git a/tests/test_agents/test_copilot.py b/tests/test_agents/test_copilot.py new file mode 100644 index 0000000..0656a81 --- /dev/null +++ b/tests/test_agents/test_copilot.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from secfoo.agents.copilot import CopilotAdapter + + +def test_build_command(tmp_path): + adapter = CopilotAdapter() + cmd = adapter.build_command("hi", workdir=tmp_path) + assert cmd == ["copilot", "-p", "hi", "-s", "--allow-all-tools"] + + +def test_build_command_never_grants_unrestricted_paths_or_urls(tmp_path): + """--allow-all-tools is required for non-interactive mode, but the + broader --allow-all/--yolo/--allow-all-paths/--allow-all-urls escape + hatches are a materially bigger grant (arbitrary filesystem/network + access) that a read-only security review never needs. + """ + adapter = CopilotAdapter() + cmd = adapter.build_command("hi", workdir=tmp_path) + for forbidden in ("--allow-all", "--yolo", "--allow-all-paths", "--allow-all-urls"): + assert forbidden not in cmd + + +def test_binary_and_name(): + assert CopilotAdapter.binary == "copilot" + assert CopilotAdapter.name == "copilot" + + +def test_extract_report_defaults_to_raw_stdout(): + """Unlike claude.py/gemini.py, `copilot -s` prints the answer directly + with no JSON envelope to unwrap -- confirmed against a real invocation. + """ + adapter = CopilotAdapter() + assert adapter.extract_report("# SAST Report\n...") == "# SAST Report\n..." + + +def test_is_available_uses_binary_name(monkeypatch): + monkeypatch.setattr("secfoo.agents.base.shutil.which", lambda name: "/usr/bin/copilot" if name == "copilot" else None) + assert CopilotAdapter().is_available() is True + + +def test_is_available_false_when_binary_missing(monkeypatch): + monkeypatch.setattr("secfoo.agents.base.shutil.which", lambda name: None) + assert CopilotAdapter().is_available() is False + + +def test_run_success(fake_popen, tmp_path): + fake_popen(stdout="# SAST Report\n\nfindings...", stderr="", returncode=0) + adapter = CopilotAdapter() + result = adapter.run("hi", workdir=tmp_path) + assert result.status == "success" + assert result.raw_report == "# SAST Report\n\nfindings..." + + +def test_run_timeout_does_not_raise(fake_popen, tmp_path): + fake_popen(raise_timeout=True, stdout="partial", stderr="") + adapter = CopilotAdapter() + result = adapter.run("hi", workdir=tmp_path, timeout=1) + assert result.status == "timeout" + assert result.timed_out is True + assert result.exit_code is None + assert result.raw_report == "" diff --git a/tests/test_report/test_markdown.py b/tests/test_report/test_markdown.py index d24f0b8..84d73f9 100644 --- a/tests/test_report/test_markdown.py +++ b/tests/test_report/test_markdown.py @@ -69,6 +69,34 @@ def test_strip_preamble_leaves_text_unchanged_when_no_heading_found(): assert strip_preamble(text) == text +def test_strip_preamble_falls_back_to_numbered_section_one(): + """Regression test for the copilot adapter: it unpromptedly runs its + own native security-scan tool first (an unrelated "##"/"###" preamble + with no single top-level "#" heading anywhere) before going straight + into the required numbered sections without ever writing the "# + Report" title. The primary anchor never fires here, so this + must fall back to "## 1. Executive Summary" instead of giving up. + """ + required_report = "## 1. Executive Summary\nRisk is high.\n\n## 2. Scope\n..." + text = ( + "## Security Findings\n\n" + "### Alert 1\n**Severity: CRITICAL**\nSome native alert content.\n\n" + "## Remediation Roadmap\n- fix it\n\n" + + required_report + ) + assert strip_preamble(text) == required_report + + +def test_strip_preamble_prefers_top_level_heading_over_numbered_fallback(): + """When both anchors are present, the title must win so the report + keeps its own heading -- proved by placing "## 1." chatter *before* + the real title, which the fallback alone would cut into instead of + past entirely. + """ + text = "## 1. This is chatter mentioning numbered sections, not the report.\n\n" + SAMPLE_REPORT + assert strip_preamble(text) == SAMPLE_REPORT + + FINDINGS_REGISTER_REPORT = """\ # Threat Assessment Report From b2d00ba5e14fe3c073bc4475b40b86dc436bfb03 Mon Sep 17 00:00:00 2001 From: Adith K B <20210193@sastra.ac.in> Date: Fri, 18 Sep 2026 14:42:05 +0100 Subject: [PATCH 2/2] fix: tighten strip_preamble's numbered-section fallback to an exact match The fallback added for the copilot adapter matched any "## 1. " heading, not specifically "## 1. Executive Summary". That's too loose: a preamble that numbers its own unrelated section "1." (a plan, a to-do list) would get matched instead of the real report, cutting to that wrong, earlier point instead of skipping the preamble entirely. Tightens the regex to the literal "## 1. Executive Summary" text -- every skill's contract requires that exact phrase (skills/renderer.py), so it's no less general, just no longer over-matching. Adds a regression test for the false-positive this closes, and re-verified against both real captured Copilot reports from earlier end-to-end testing to confirm the actual fix still works. Co-Authored-By: Claude Sonnet 5 --- src/secfoo/report/markdown.py | 17 +++++++++++------ tests/test_report/test_markdown.py | 25 +++++++++++++++++++++---- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/secfoo/report/markdown.py b/src/secfoo/report/markdown.py index e35e762..61cde34 100644 --- a/src/secfoo/report/markdown.py +++ b/src/secfoo/report/markdown.py @@ -51,12 +51,17 @@ # its own native security-scan tool first, emitting an unrelated "##"/"###" # preamble, then goes straight into the skill's required numbered sections # without ever writing a single top-level "#" heading anywhere). Every -# skill's contract requires "## 1. Executive Summary" as its first numbered -# section (see skills/renderer.py's shared "Required output format" block), -# so it's a safe, skill-agnostic anchor to fall back to -- tried only when -# the primary title search above finds nothing, so a compliant agent's -# report (which always has both) is unaffected. -_NUMBERED_SECTION_ONE_RE = re.compile(r"^##\s+1\.\s+.+$", re.MULTILINE) +# skill's contract requires "## 1. Executive Summary" verbatim as its +# first numbered section (see skills/renderer.py's shared "Required +# output format" block -- identical across every skill, not just SAST), +# so anchoring on that literal phrase, not just "## 1." with any text, +# matters: a preamble that itself numbers an unrelated "## 1. " +# section (a plan, a to-do list) would otherwise be matched instead of the +# real report -- cutting to the wrong, earlier point instead of past the +# preamble entirely. Tried only when the primary title search above finds +# nothing, so a compliant agent's report (which always has both) is +# unaffected either way. +_NUMBERED_SECTION_ONE_RE = re.compile(r"^##\s+1\.\s+Executive Summary\s*$", re.MULTILINE | re.IGNORECASE) # "commonmark" alone is the strict base spec and does NOT parse GFM pipe # tables -- every `| a | b |` block silently fell through as a plain diff --git a/tests/test_report/test_markdown.py b/tests/test_report/test_markdown.py index 84d73f9..6e535bd 100644 --- a/tests/test_report/test_markdown.py +++ b/tests/test_report/test_markdown.py @@ -87,13 +87,30 @@ def test_strip_preamble_falls_back_to_numbered_section_one(): assert strip_preamble(text) == required_report +def test_strip_preamble_fallback_ignores_unrelated_numbered_sections(): + """The fallback must match the literal "## 1. Executive Summary" + text, not just any "## 1. " heading -- otherwise a + preamble that numbers its own unrelated section "1." (a plan, a + to-do list) gets matched instead of the real report, cutting to the + wrong, earlier point rather than past the preamble entirely. + """ + required_report = "## 1. Executive Summary\nThe real content that should be kept." + text = ( + "## My plan\n1. Read the target files\n2. Check for issues\n\n" + "## 1. Setup notes before I start\n" + "This has nothing to do with the real report at all.\n\n" + + required_report + ) + assert strip_preamble(text) == required_report + + def test_strip_preamble_prefers_top_level_heading_over_numbered_fallback(): """When both anchors are present, the title must win so the report - keeps its own heading -- proved by placing "## 1." chatter *before* - the real title, which the fallback alone would cut into instead of - past entirely. + keeps its own heading -- proved by placing "## 1. Executive Summary" + chatter *before* the real title, which the fallback alone would + match and cut into instead of skipping past entirely. """ - text = "## 1. This is chatter mentioning numbered sections, not the report.\n\n" + SAMPLE_REPORT + text = "## 1. Executive Summary\nThis mentions the section name but isn't the report.\n\n" + SAMPLE_REPORT assert strip_preamble(text) == SAMPLE_REPORT