Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

feat(scan-code): add source & dependency security scan skill (#231)

Ramachandran R1dcf20178c18
diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.md
index 53bb6c115..e4d0f5404 100644
--- a/plugins/power-pages/README.md
+++ b/plugins/power-pages/README.md
@@ -38,7 +38,7 @@ This keeps hook behavior in one place and avoids relying on skill-frontmatter ho
## Skills
-The plugin provides 30 skills that cover the full lifecycle of a Power Pages code site — scaffolding, deployment, data modeling, backend integration, authentication, ALM and CI/CD, security review, testing, and auditing. Each skill is invoked conversationally — just describe what you want to do.
+The plugin provides 31 skills that cover the full lifecycle of a Power Pages code site — scaffolding, deployment, data modeling, backend integration, authentication, ALM and CI/CD, security review, testing, and auditing. Each skill is invoked conversationally — just describe what you want to do.
### Site scaffolding and deployment
@@ -221,6 +221,16 @@ Runs a security scan on a deployed Power Pages site, fetches the latest scan rep
- Fetches and explains the latest scan report
- Surfaces issues grouped by severity
+#### `/scan-code`
+
+> "Check my source code and dependencies for security issues"
+
+Scans a Power Pages site project's source files and dependencies for security problems — static analysis of the code plus dependency, secret, and license scanning — then surfaces findings in plain language.
+
+- Runs static analysis (opengrep) and dependency/secret/license scanning (trivy)
+- Groups findings by category — code patterns, vulnerable packages, secrets, licenses
+- Offers an agent-driven review fallback when the scanning tools are not installed
+
#### `/manage-firewall`
> "Block traffic from a specific country and add a rate limit to /login"
@@ -245,9 +255,9 @@ Inspects and configures the security headers a Power Pages site sends to browser
> "Do a full security review before we ship"
-Runs a guided, end-to-end security review of a Power Pages site and consolidates every finding into one HTML report covering the live site, browser headers, firewall, authentication, and role-based permissions.
+Runs a guided, end-to-end security review of a Power Pages site and consolidates every finding into one HTML report covering source code and dependencies, the live site, browser headers, firewall, authentication, and role-based permissions.
-- Orchestrates `/scan-site`, `/manage-headers`, `/manage-firewall`, `/audit-permissions`, and auth checks
+- Orchestrates `/scan-code`, `/scan-site`, `/manage-headers`, `/manage-firewall`, `/audit-permissions`, and auth checks
- Consolidates findings into a single HTML report
- Suitable for release-readiness or live-site monitoring
diff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.md
index a41131b9c..c1894df8a 100644
--- a/plugins/power-pages/references/approval-gates.md
+++ b/plugins/power-pages/references/approval-gates.md
@@ -652,7 +652,7 @@ The `### Option rules` sections in `manage-firewall` and `scan-site` retain `<!-
| ID | Kind | Category | Phase | Trigger / question | Cancel leaves |
|---|---|---|---|---|---|
-| `security-review:2.1.goal` | gate | plan | 2.1 | *"What to review? Access & config / Release readiness / Deployed site"* — branches into 3 different sub-skill sets. | nothing |
+| `security-review:2.1.goal` | gate | plan | 2.1 | *"What to review? Code & config / Release readiness / Deployed site"* — branches into 3 different sub-skill sets. | nothing |
| `security-review:5.3.next-action` | gate | plan | 5.3 | Post-report prompt — *"Walk me through the fixes / Re-run the review / Done for now"*. Drives whether remediation skills get invoked next. | nothing |
---
@@ -670,6 +670,18 @@ New skill introduced by PR #144. Orchestrates AI summarization API integration a
---
+### 6.30 `scan-code` (3 gate IDs)
+
+New skill (Power Pages source & dependency security scan). Runs local static analysis and dependency/secret/license scanning, then surfaces findings. All gates are `plan` — every prompt configures a read-only scan, so cancelling never leaves behind state to undo.
+
+| ID | Kind | Category | Phase | Trigger / question | Cancel leaves |
+|---|---|---|---|---|---|
+| `scan-code:1.agent-review-fallback` | gate | plan | 1.2 | Offer the high-token agent-driven review when a scanning tool is missing. Fires only on a missing tool, interactive mode only. | nothing |
+| `scan-code:2.scope-choice` | gate | plan | 2 (`### Scope selection`, Q1) | *"What to check? Everything / Code only / Packages only"* — selects which scanners run. Skipped in review mode and when the initial request already names the scope. | nothing |
+| `scan-code:2.depth-choice` | gate | plan | 2 (`### Scope selection`, Q2) | *"How thorough? Advanced / Basic"* — sets the code-scan depth. Asked only when code checking is included; skipped in review mode. | nothing |
+
+---
+
### Cross-plugin shared skills — out of catalog scope
`report-issue` — Its prompts are cross-plugin, not power-pages-specific, so they are not catalogued here. If the shared workflow is ever governed by per-plugin approval-gate linting, add a `report-issue:*` section to this catalog.
@@ -712,6 +724,7 @@ These need explicit confirmation from the reviewer before SKILL.md edits land. R
- §6.13–§6.24 added — full catalog rows for `create-site`, `deploy-site`, `add-server-logic`, `add-cloud-flow`, `setup-auth`, `integrate-webapi`, `setup-datamodel`, `add-sample-data`, `add-seo`, `create-webroles`, `audit-permissions`, `integrate-backend` (45 gates + 9 not-a-gates).
- §6.24a–§6.28 added — security skills introduced by PR #151 (`manage-firewall`, `manage-headers`, `scan-site`, `security-review`). The new skills use a runtime-loop prompt pattern; §6.24a documents the marker convention for that pattern. 3 gates + 2 not-a-gates.
+- §6.30 added — `scan-code` (Power Pages source & dependency security scan). 3 `plan` gates (`scan-code:1.agent-review-fallback`, `scan-code:2.scope-choice`, `scan-code:2.depth-choice`); no not-a-gates.
- Markers added to all non-ALM SKILL.md files (HTML comment + 🚦 block per gate; `not-a-gate` comment per data-gathering prompt or meta-mention).
- `scripts/lint-skills-alm.js` warn-only branch removed — all skills now hard-fail.
- `AGENTS.md` Key Patterns updated — Approval Gate convention applies plugin-wide; new skills must extend §6 in the same PR they introduce a prompt.
diff --git a/plugins/power-pages/references/skill-tracking-reference.md b/plugins/power-pages/references/skill-tracking-reference.md
index 6b0332d65..994f7038a 100644
--- a/plugins/power-pages/references/skill-tracking-reference.md
+++ b/plugins/power-pages/references/skill-tracking-reference.md
@@ -46,6 +46,7 @@ If the tracking script creates or updates site setting YAML files, include those
| manage-headers | ManageHeaders | Site/AI/Skills/ManageHeaders |
| manage-firewall | ManageFirewall | Site/AI/Skills/ManageFirewall |
| security-review | SecurityReview | Site/AI/Skills/SecurityReview |
+| scan-code | ScanCode | Site/AI/Skills/ScanCode |
| setup-solution | SetupSolution | Site/AI/Skills/SetupSolution |
| export-solution | ExportSolution | Site/AI/Skills/ExportSolution |
| import-solution | ImportSolution | Site/AI/Skills/ImportSolution |
diff --git a/plugins/power-pages/scripts/build-review-data.js b/plugins/power-pages/scripts/build-review-data.js
index 07b907cb4..5420a6e37 100644
--- a/plugins/power-pages/scripts/build-review-data.js
+++ b/plugins/power-pages/scripts/build-review-data.js
@@ -13,6 +13,7 @@ const REQUIRED_FLAGS = [
];
const SECTION_MAP = {
+ 'scan-code.json': { id: 'code-scan', label: 'Code & Packages', icon: '▦' },
'scan-site.json': { id: 'site-scan', label: 'Live Site Scan', icon: '◐' },
'manage-headers.json': { id: 'headers', label: 'Browser Headers', icon: '◑' },
'manage-firewall.json': {
diff --git a/plugins/power-pages/scripts/tests/build-review-data.test.js b/plugins/power-pages/scripts/tests/build-review-data.test.js
index 142b4c748..401eaba3d 100644
--- a/plugins/power-pages/scripts/tests/build-review-data.test.js
+++ b/plugins/power-pages/scripts/tests/build-review-data.test.js
@@ -31,8 +31,9 @@ function runCli(args, env = {}) {
});
}
-test('SECTION_MAP recognizes the five known per-skill files', () => {
+test('SECTION_MAP recognizes the six known per-skill files', () => {
const expected = [
+ 'scan-code.json',
'scan-site.json',
'manage-headers.json',
'manage-firewall.json',
@@ -46,6 +47,27 @@ test('SECTION_MAP recognizes the five known per-skill files', () => {
}
});
+test('buildSections renders scan-code findings with severity totals', (t) => {
+ const dir = withTempDir(t);
+ writeJson(dir, 'scan-code.json', {
+ status: 'ok',
+ findings: [
+ { id: 'a', severity: 'critical', category: 'vulnerability', title: 't' },
+ { id: 'b', severity: 'high', category: 'secret', title: 't' },
+ { id: 'c', severity: 'warning', confidence: 'HIGH', title: 't' },
+ ],
+ });
+
+ const { sections, totals } = buildSections(dir, 'data.json');
+ assert.equal(sections.length, 1);
+ assert.equal(sections[0].id, 'code-scan');
+ assert.equal(sections[0].label, 'Code & Packages');
+ assert.equal(sections[0].findings.length, 3);
+ assert.equal(totals.critical, 1);
+ assert.equal(totals.high, 1);
+ assert.equal(totals.warning, 1);
+});
+
test('SEVERITIES lists the seven supported severity buckets in precedence order', () => {
assert.deepEqual(SEVERITIES, [
'critical',
diff --git a/plugins/power-pages/scripts/tests/scan-code-check-tools.test.js b/plugins/power-pages/scripts/tests/scan-code-check-tools.test.js
new file mode 100644
index 000000000..a8b674da2
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/scan-code-check-tools.test.js
@@ -0,0 +1,39 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const SCRIPT = path.join(__dirname, '..', '..', 'skills', 'scan-code', 'scripts', 'check-tools.js');
+
+function run(args, env = {}) {
+ return spawnSync(process.execPath, [SCRIPT, ...args], {
+ encoding: 'utf8',
+ env: { ...process.env, ...env },
+ });
+}
+
+test('check-tools.js --help exits 0 and prints usage', () => {
+ const res = run(['--help']);
+ assert.equal(res.status, 0, `stderr: ${res.stderr}`);
+ assert.match(res.stdout, /check-tools\.js/);
+});
+
+test('check-tools.js reports both tools unavailable when neither is on PATH', (t) => {
+ // Point PATH at an empty dir so opengrep/trivy cannot be resolved; the interpreter
+ // itself is launched via process.execPath so it still runs. ComSpec/SystemRoot are
+ // inherited (spread) so cmd.exe is still found on Windows.
+ const emptyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'no-tools-'));
+ t.after(() => fs.rmSync(emptyDir, { recursive: true, force: true }));
+
+ const res = run([], { PATH: emptyDir, Path: emptyDir });
+ assert.equal(res.status, 1, `stderr: ${res.stderr}`);
+
+ const out = JSON.parse(res.stdout);
+ for (const tool of ['opengrep', 'trivy']) {
+ assert.equal(out[tool].available, false, `${tool} should be unavailable`);
+ assert.equal(out[tool].version, null);
+ assert.ok(typeof out[tool].error === 'string' && out[tool].error.length > 0);
+ }
+});
diff --git a/plugins/power-pages/scripts/tests/scan-code-run-opengrep.test.js b/plugins/power-pages/scripts/tests/scan-code-run-opengrep.test.js
new file mode 100644
index 000000000..9ddc4dc5c
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/scan-code-run-opengrep.test.js
@@ -0,0 +1,24 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const SCRIPT = path.join(__dirname, '..', '..', 'skills', 'scan-code', 'scripts', 'run-opengrep.js');
+
+function run(args) {
+ return spawnSync(process.execPath, [SCRIPT, ...args], { encoding: 'utf8' });
+}
+
+test('run-opengrep.js --help exits 0 and prints usage', () => {
+ const res = run(['--help']);
+ assert.equal(res.status, 0, `stderr: ${res.stderr}`);
+ assert.match(res.stdout, /run-opengrep\.js/);
+});
+
+test('run-opengrep.js exits 1 with usage when --projectRoot is missing', () => {
+ // No args: the script rejects before ever invoking the external opengrep binary,
+ // so this is safe without opengrep installed.
+ const res = run([]);
+ assert.equal(res.status, 1, `stderr: ${res.stderr}`);
+ assert.match(res.stderr, /--projectRoot/);
+});
diff --git a/plugins/power-pages/scripts/tests/scan-code-run-trivy.test.js b/plugins/power-pages/scripts/tests/scan-code-run-trivy.test.js
new file mode 100644
index 000000000..eb662f922
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/scan-code-run-trivy.test.js
@@ -0,0 +1,24 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const SCRIPT = path.join(__dirname, '..', '..', 'skills', 'scan-code', 'scripts', 'run-trivy.js');
+
+function run(args) {
+ return spawnSync(process.execPath, [SCRIPT, ...args], { encoding: 'utf8' });
+}
+
+test('run-trivy.js --help exits 0 and prints usage', () => {
+ const res = run(['--help']);
+ assert.equal(res.status, 0, `stderr: ${res.stderr}`);
+ assert.match(res.stdout, /run-trivy\.js/);
+});
+
+test('run-trivy.js exits 1 with usage when --projectRoot is missing', () => {
+ // No args: the script rejects before ever invoking the external trivy binary,
+ // so this is safe without trivy installed.
+ const res = run([]);
+ assert.equal(res.status, 1, `stderr: ${res.stderr}`);
+ assert.match(res.stderr, /--projectRoot/);
+});
diff --git a/plugins/power-pages/scripts/tests/transform-scan-code.test.js b/plugins/power-pages/scripts/tests/transform-scan-code.test.js
new file mode 100644
index 000000000..520a59eee
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/transform-scan-code.test.js
@@ -0,0 +1,139 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const {
+ transformOpengrep,
+ transformTrivy,
+} = require('../../skills/scan-code/scripts/transform-scan-code');
+
+// --- transformOpengrep ---------------------------------------------------
+
+test('transformOpengrep groups occurrences by check_id into one finding per rule', () => {
+ const raw = {
+ results: [
+ {
+ check_id: 'rule.sqli',
+ path: '/proj/a.js',
+ start: { line: 5 },
+ extra: {
+ severity: 'ERROR',
+ message: 'SQL injection',
+ metadata: { category: 'security', confidence: 'HIGH', vulnerability_class: ['SQL Injection'], references: ['https://x'] },
+ },
+ },
+ {
+ check_id: 'rule.sqli',
+ path: '/proj/b.js',
+ start: { line: 9 },
+ extra: { severity: 'ERROR', message: 'SQL injection', metadata: { category: 'security', references: [] } },
+ },
+ ],
+ };
+
+ const findings = transformOpengrep(raw, '/proj');
+ assert.equal(findings.length, 1);
+ const f = findings[0];
+ assert.equal(f.severity, 'critical');
+ assert.equal(f.category, 'security');
+ assert.equal(f.confidence, 'HIGH');
+ assert.equal(f.title, 'SQL Injection');
+ assert.equal(f.tag, 'rule.sqli');
+ assert.equal(f.location, 'a.js:5');
+ assert.match(f.details, /2 occurrences/);
+ assert.match(f.details, /References:/);
+});
+
+test('transformOpengrep maps WARNING and INFO severities', () => {
+ const mk = (sev) => ({
+ results: [{ check_id: 'r', path: '/p/x.js', start: { line: 1 }, extra: { severity: sev, message: 'm', metadata: {} } }],
+ });
+ assert.equal(transformOpengrep(mk('WARNING'), '/p')[0].severity, 'warning');
+ assert.equal(transformOpengrep(mk('INFO'), '/p')[0].severity, 'info');
+});
+
+test('transformOpengrep returns [] when results is missing (empty "{}" fallback)', () => {
+ assert.deepEqual(transformOpengrep({}, '/proj'), []);
+ assert.deepEqual(transformOpengrep({ results: null }, '/proj'), []);
+});
+
+test('transformOpengrep does not throw when a rule omits references/metadata', () => {
+ const raw = {
+ results: [
+ { check_id: 'r1', path: '/p/a.js', start: { line: 2 }, extra: { severity: 'WARNING', message: 'm', metadata: { category: 'best-practice' } } },
+ { check_id: 'r2', path: '/p/b.js', start: { line: 3 }, extra: { severity: 'INFO', message: 'm' } },
+ ],
+ };
+ const findings = transformOpengrep(raw, '/p');
+ assert.equal(findings.length, 2);
+ assert.doesNotMatch(findings[0].details, /References:/);
+ assert.equal(findings[1].title, 'r2');
+});
+
+test('transformOpengrep relativize uses a path boundary, not a bare prefix', () => {
+ const raw = {
+ results: [
+ { check_id: 'r', path: '/repo/app/src/x.js', start: { line: 1 }, extra: { severity: 'ERROR', message: 'm', metadata: {} } },
+ { check_id: 'r2', path: '/repo/app2/y.js', start: { line: 1 }, extra: { severity: 'ERROR', message: 'm', metadata: {} } },
+ ],
+ };
+ const findings = transformOpengrep(raw, '/repo/app');
+ const byTag = Object.fromEntries(findings.map((f) => [f.tag, f.location]));
+ assert.equal(byTag.r, 'src/x.js:1');
+ assert.equal(byTag.r2, '/repo/app2/y.js:1'); // sibling prefix stays absolute
+});
+
+// --- transformTrivy ------------------------------------------------------
+
+test('transformTrivy maps vulnerabilities, secrets, and licenses', () => {
+ const raw = {
+ Results: [
+ {
+ Target: '/proj/package-lock.json',
+ Vulnerabilities: [
+ { VulnerabilityID: 'CVE-1', PkgName: 'lodash', InstalledVersion: '1.0.0', FixedVersion: '1.0.1', Severity: 'HIGH', Title: 'Proto pollution' },
+ ],
+ },
+ {
+ Target: '/proj/.env',
+ Secrets: [{ RuleID: 'aws-key', Category: 'AWS', Severity: 'CRITICAL', Title: 'AWS key', StartLine: 3 }],
+ },
+ {
+ Target: '/proj',
+ Licenses: [{ Severity: 'MEDIUM', Category: 'restricted', PkgName: 'pkg', FilePath: '/proj/LICENSE', Name: 'GPL-3.0' }],
+ },
+ ],
+ };
+ const findings = transformTrivy(raw, '/proj');
+ assert.equal(findings.length, 3);
+
+ const vuln = findings.find((f) => f.category === 'vulnerability');
+ assert.equal(vuln.severity, 'high');
+ assert.equal(vuln.tag, 'CVE-1');
+ assert.equal(vuln.location, 'package-lock.json');
+ assert.match(vuln.fix, /Upgrade lodash to 1\.0\.1/);
+
+ const secret = findings.find((f) => f.category === 'secret');
+ assert.equal(secret.severity, 'critical');
+ assert.equal(secret.location, '.env:3');
+ assert.match(secret.fix, /rotate/i);
+
+ const license = findings.find((f) => f.category === 'license');
+ assert.equal(license.severity, 'medium');
+ assert.equal(license.tag, 'GPL-3.0');
+});
+
+test('transformTrivy omits the fix hint for a vulnerability with no FixedVersion', () => {
+ const raw = {
+ Results: [
+ { Target: 't', Vulnerabilities: [{ VulnerabilityID: 'CVE-2', PkgName: 'p', InstalledVersion: '1', Severity: 'LOW', Title: 'x' }] },
+ ],
+ };
+ const f = transformTrivy(raw, null)[0];
+ assert.equal(f.severity, 'low');
+ assert.equal(f.fix, null);
+});
+
+test('transformTrivy returns [] when Results is missing (empty "{}" fallback)', () => {
+ assert.deepEqual(transformTrivy({}, '/proj'), []);
+ assert.deepEqual(transformTrivy({ Results: null }, '/proj'), []);
+});
diff --git a/plugins/power-pages/skills/scan-code/SKILL.md b/plugins/power-pages/skills/scan-code/SKILL.md
new file mode 100644
index 000000000..b7174cc07
--- /dev/null
+++ b/plugins/power-pages/skills/scan-code/SKILL.md
@@ -0,0 +1,232 @@
+---
+name: scan-code
+description: >-
+ Scans a Power Pages site project for security issues in source code and
+ dependencies. Runs static analysis and dependency scanning, then surfaces
+ findings by category (code patterns, vulnerable packages, secrets, license
+ issues). Use when the user wants to review code for security problems,
+ check for vulnerable packages, find hard-coded secrets, run a code scan,
+ or asks "is my code safe?", "check my dependencies", "find security
+ issues in my source" — even if they say "audit my code" without
+ mentioning specific tools.
+user-invocable: true
+argument-hint: "[optional: --review <out-dir>]"
+allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList
+model: opus
+---
+
+> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.
+
+# Scan Code
+
+Scan a Power Pages site project's source files and dependencies for security issues. Runs opengrep (static analysis) and trivy (dependency/secret/license scanning), then surfaces findings.
+
+**Initial request:** $ARGUMENTS
+
+## Gotchas
+
+- **Both tools must be installed.** Run `check-tools.js` to verify. If either is missing, offer an agent-driven review fallback (see Step 1.2).
+- **Opengrep exits 1 when findings exist.** This is normal behavior, not an error — the script handles it.
+- **Large output.** Both tools can produce large JSON for big projects. The scripts normalize the output into a flat findings list.
+- **Trivy severity flag only affects vulnerability findings.** Secrets and license findings are always returned regardless of the `--severity` flag.
+- **Secrets are never shown in full — anywhere.** Whenever **you** read source directly (the agent-driven review) or present a finding, use your judgment to recognize any credential — API keys, tokens, passwords, connection strings, private keys, or any other secret shape (there is no fixed list). Never output its raw value **anywhere** — your context, the session, chat, logs, a summary, the report, or any other output — not even partially; where a value would otherwise be shown, replace it with a mask (e.g. `********`).
+
+## Workflow
+
+1. **Prerequisites** — Locate project, check tool availability
+2. **Choose scope** — What to scan and at what depth
+3. **Run scans** — Execute tools, capture results
+4. **Summarize** — Present findings, record usage, offer follow-ups
+
+## Task Tracking
+
+Create tasks in three groups. Mark each `in_progress` when starting, `completed` when done.
+
+| Group | When to create | Tasks |
+|-------|----------------|-------|
+| 1 | At start | Check prerequisites |
+| 2 | After prerequisites pass | Choose scope (skip in review mode) |
+| 3 | After scope is decided (or in review mode) | Run scans · Summarize (always) |
+
+---
+
+## 1. Prerequisites
+
+### 1.1 Locate the project, detect review mode
+
+Use `Glob` to find `**/powerpages.config.json`. If `$ARGUMENTS` contains `--review <out-dir>`, remember the output directory — Step 2 is skipped (run all checks at Advanced depth), and Step 4 writes JSON only.
+
+### 1.2 Check tool availability
+
+```bash
+node "${PLUGIN_ROOT}/skills/scan-code/scripts/check-tools.js"
+```
+
+If either tool is missing, tell the user which tool is missing. Then offer an agent-driven review as a fallback:
+
+**In review mode (non-interactive), do not offer the agent-driven review.** It needs an interactive opt-in, and the orchestrator expects a JSON file. Write `{ "status": "skipped", "reason": "<which tool> is not installed" }` to `<REVIEW_DIR>/scan-code.json` and stop.
+
+<!-- gate: scan-code:1.agent-review-fallback | category=plan | cancel-leaves=nothing -->
+
+> 🚦 **Gate (plan · scan-code:1.agent-review-fallback):** When a scanning tool is missing, offer the agent-driven review as a fallback before doing any work. It reads the source with `Glob`/`Read`/`Grep` and has high token consumption, so the user must opt in.
+>
+> **Trigger:** Step 1.2, only when `check-tools.js` reports a missing tool (interactive mode only — review mode never reaches here because it stops when tools are missing).
+> **Why we ask:** Auto-starting the agent-driven review burns a large amount of tokens without consent; the user may prefer to install the tool and re-run instead.
+> **Cancel leaves:** Nothing — no files read, no scan run.
+
+**Framing — all user-facing text (the warning, any `AskUserQuestion` option labels, and the summary): MUST NOT call this a "manual review".** It is agent-driven — describe it as *you reviewing the code yourself*, e.g., "I can look through your code directly and flag issues."
+
+Warn the user that this review reads many files and uses a large amount of tokens, then detect the git context:
+- **Feature branch** (not `main`, `master`, or equivalent): offer to review only the changes in the current branch (`git diff <main-branch>...HEAD`).
+- **Main/master branch or no git repo**: offer to review the entire project source.
+
+If the user accepts, use `Glob` + `Read` + `Grep` to review the relevant files for common security patterns (hard-coded secrets, unsafe API usage, missing input validation, exposed endpoints, etc.) and present findings. **Never surface a secret value anywhere** — never output a credential's raw value in any output (your context, the session, chat, logs, etc.), not even partially; where a value would otherwise be shown, replace it with a mask (e.g. `********`). Do not attempt to install the tools.
+
+---
+
+## 2. Choose scope
+
+Skip in **review mode** — run both tools at Advanced depth.
+
+### Scope selection
+
+Ask the following in order. Each is a **separate** `AskUserQuestion` call — do NOT combine. If the user's initial request already answers a question, skip it and move to the next.
+
+<!-- gate: scan-code:2.scope-choice | category=plan | cancel-leaves=nothing -->
+
+> 🚦 **Gate (plan · scan-code:2.scope-choice):** Choose what to scan — code, packages, or both — before running any tool. Determines which scanners run.
+>
+> **Trigger:** Phase 2 entry (interactive mode only — review mode scans everything at Advanced depth without asking). Skipped if the initial request already names the scope.
+> **Why we ask:** Auto-scanning everything can run tools the user did not want (e.g., a slow code pass when they only asked about packages); the wrong scope produces a report that misses what they cared about.
+> **Cancel leaves:** Nothing — no scanner has run.
+
+**Question 1 — What to check?**
+
+| Label | Description |
+|-------|-------------|
+| Everything | Check both code and packages. (Recommended) |
+| Code only | Check source files for security problems. |
+| Packages only | Check installed packages for known issues. |
+
+<!-- gate: scan-code:2.depth-choice | category=plan | cancel-leaves=nothing -->
+
+> 🚦 **Gate (plan · scan-code:2.depth-choice):** Choose how thorough the code check is. Only asked when code checking is included.
+>
+> **Trigger:** Phase 2, after the scope choice includes code (interactive mode only). Skipped if the initial request already names the depth or code checking was excluded.
+> **Why we ask:** The thorough option runs a deeper rule set that takes longer; auto-picking it can slow a large project unexpectedly, while auto-picking the quick option can silently skip weaknesses the user expected to catch.
+> **Cancel leaves:** Nothing — no scanner has run.
+
+**Question 2 — Only if code checking is included: How thorough?**
+
+| Label | Description |
+|-------|-------------|
+| Advanced | Covers common risks and deeper code weaknesses. (Recommended) |
+| Basic | Covers common risks only. |
+
+Depth mapping (internal, not shown to user): Advanced = `p/default,p/owasp-top-ten,p/cwe-top-25`. Basic = `p/default,p/owasp-top-ten`.
+
+### Custom rules
+
+Both tools accept custom rules. Do not proactively offer — only use when the user provides them.
+
+- **Opengrep**: `--rulesets` accepts comma-separated registry packs and local file paths. Custom rulesets are appended to the depth's defaults, not replacing them.
+- **Trivy**: `--secretConfig` for custom secret detection patterns, `--ignoreFile` for suppressing known findings, `--trivyConfig` for license classification and other settings, `--no-licenseFull` to skip source-level license scanning for faster runs.
+
+---
+
+## 3. Run scans
+
+Save each tool's **raw** JSON output to a temporary file. The transform script in Step 4 normalizes them.
+
+### Static analysis (opengrep)
+
+```bash
+node "${PLUGIN_ROOT}/skills/scan-code/scripts/run-opengrep.js" --projectRoot "<PROJECT_ROOT>" --rulesets "<comma-separated-rulesets>" > "<TEMP_DIR>/opengrep.json"
+```
+
+Pass the rulesets for the chosen depth (Basic or Advanced). Append any user-provided custom rulesets. Run with `run_in_background: true` for large projects.
+
+### Dependency / secret / license scanning (trivy)
+
+```bash
+node "${PLUGIN_ROOT}/skills/scan-code/scripts/run-trivy.js" --projectRoot "<PROJECT_ROOT>" > "<TEMP_DIR>/trivy.json"
+```
+
+`--licenseFull` is on by default — source code headers and LICENSE files are scanned alongside package metadata. Run with `run_in_background: true` for large projects.
+
+### Normalize
+
+```bash
+node "${PLUGIN_ROOT}/skills/scan-code/scripts/transform-scan-code.js" --opengrepFile "<TEMP_DIR>/opengrep.json" --trivyFile "<TEMP_DIR>/trivy.json" --projectRoot "<PROJECT_ROOT>"
+```
+
+Pass only the files for tools that actually ran. Stdout has the unified `{ status, findings }` shape.
+
+---
+
+## 4. Summarize
+
+### 4.1 Review mode
+
+In **review mode**, write the `transform-scan-code.js` stdout to `<REVIEW_DIR>/scan-code.json`. Then stop — the orchestrating skill handles presentation.
+
+### 4.2 Render HTML report
+
+Skip in **review mode**.
+
+Render uses the same shared template as the consolidated security review. First write the Step 3 Normalize stdout to `<TEMP_DIR>/scan-code.json`, then build a single-section review-data payload and render:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/build-review-data.js" \
+ --reportName "Code Scan" \
+ --inputDir "<TEMP_DIR>" \
+ --siteName "<SITE_NAME>" \
+ --goalLabel "Code & Packages scan" \
+ --scopeLabel "<SCOPE_LABEL>" \
+ --summary "<SUMMARY_TEXT>" \
+ --output "<TEMP_DIR>/data.json"
+
+node "${PLUGIN_ROOT}/scripts/render-review.js" \
+ --data "<TEMP_DIR>/data.json" \
+ --output "<PROJECT_ROOT>/docs/code-scan-<YYYY-MM-DD-HHMMSS>.html"
+```
+
+`<TEMP_DIR>` also holds the intermediate `opengrep.json`/`trivy.json` from Step 3 alongside `scan-code.json`; `build-review-data.js` reads only `scan-code.json` and ignores the rest. The filename **must** include the local timestamp (e.g., `code-scan-2026-05-14-053805.html`). Delete `<TEMP_DIR>` after the render succeeds. Open the rendered HTML in the browser.
+
+### 4.3 Present summary
+
+Skip in **review mode**.
+
+Plain-language summary: total findings, count by category (code patterns, vulnerable packages, secrets, licenses), and what the user should look at first.
+
+### 4.4 Record skill usage
+
+> Reference: `${PLUGIN_ROOT}/references/skill-tracking-reference.md`
+>
+> Use `--skillName "ScanCode"`.
+
+### 4.5 Offer follow-ups
+
+If findings map to other skills, suggest them:
+- Header / cookie issues → `/manage-headers`
+- WAF / firewall issues → `/manage-firewall`
+- Permission issues → `/audit-permissions` to review existing permissions, and/or `/create-webroles` to set up role-based access
+- Login or external identity issues → `/setup-auth`
+- Code-level issues (exposed debug pages, information leakage) → suggest a manual code fix
+
+If no meaningful follow-up exists, end the skill.
+
+---
+
+## Constraints
+
+- **Plain language** — MUST NOT use technical jargon with the user. Never use words like opengrep, trivy, OWASP, CWE, static analysis, SAST, or ruleset in user-facing text. Use everyday language like "check your code for security problems", "check your packages for known issues", "thorough check", "quick check". Explain the technical name only when the user asks. For the tool-missing fallback, MUST NOT call it a "manual review" — it is agent-driven; describe it as you reviewing the code yourself.
+- **Background long-running calls** — run both tools via `run_in_background: true` for large projects.
+- **Context-aware interactions** — recommendations MUST reflect the site's actual scan results. Do not present generic advice.
+- **Recommendations MUST NOT break the site** — when suggesting fixes for code findings, verify that the fix does not introduce regressions.
+- **NEVER recommend broadening security** — if a finding suggests tightening (e.g., removing a hard-coded secret), do not suggest keeping it for convenience.
+- **NEVER disclose a secret value** — Never output, log, store, or repeat a raw secret anywhere, not even partially or when a regex/grep matches it. Identify a secret finding by its type, file, and line — not its value. Masking (e.g. `********`) applies only where a secret value would otherwise be shown; you are not required to display it.
+
+## References
+
+- `references/commands.md` — script flags and response shapes. Read when constructing script invocations.
diff --git a/plugins/power-pages/skills/scan-code/references/commands.md b/plugins/power-pages/skills/scan-code/references/commands.md
new file mode 100644
index 000000000..0b34ed14e
--- /dev/null
+++ b/plugins/power-pages/skills/scan-code/references/commands.md
@@ -0,0 +1,93 @@
+# Scan Code — Commands
+
+Reference for the helper scripts under `scripts/`. All scripts output JSON to stdout and support `--help`.
+
+## Table of contents
+
+- [`check-tools.js`](#check-toolsjs)
+- [`run-opengrep.js`](#run-opengrepjs)
+- [`run-trivy.js`](#run-trivyjs)
+- [`transform-scan-code.js`](#transform-scan-codejs)
+
+---
+
+## `check-tools.js`
+
+Checks whether opengrep and trivy are installed and returns their versions.
+
+```bash
+node "${PLUGIN_ROOT}/skills/scan-code/scripts/check-tools.js"
+```
+
+Exit 0 = both available. Exit 1 = at least one missing. If missing, tell the user and stop.
+
+---
+
+## `run-opengrep.js`
+
+Runs opengrep static analysis and emits the tool's **raw** JSON to stdout. Use `transform-scan-code.js` to normalize.
+
+```bash
+node "${PLUGIN_ROOT}/skills/scan-code/scripts/run-opengrep.js" --projectRoot "<project-root>"
+```
+
+| Flag | Required | Default | Description |
+|------|----------|---------|-------------|
+| `--projectRoot` | Yes | — | Directory to scan. Must be a Power Pages site project root (`powerpages.config.json` or `.powerpages-site/`); any other directory is refused with exit 1. |
+| `--rulesets` | No | `p/default,p/owasp-top-ten` | Comma-separated list of rulesets. Accepts registry packs and local paths. |
+| `--include` | No | — | Optional glob narrowing the file set. |
+
+### Response (stdout)
+
+Raw opengrep JSON — the same shape opengrep produces on the command line. Pass the captured stdout to `transform-scan-code.js --opengrepFile` to convert it to the unified findings shape.
+
+---
+
+## `run-trivy.js`
+
+Runs trivy dependency/secret/license scanning and emits the tool's **raw** JSON to stdout. Use `transform-scan-code.js` to normalize.
+
+```bash
+node "${PLUGIN_ROOT}/skills/scan-code/scripts/run-trivy.js" --projectRoot "<project-root>"
+```
+
+| Flag | Required | Default | Description |
+|------|----------|---------|-------------|
+| `--projectRoot` | Yes | — | Directory to scan. Must be a Power Pages site project root (`powerpages.config.json` or `.powerpages-site/`); any other directory is refused with exit 1. |
+| `--severity` | No | `LOW,MEDIUM,HIGH,CRITICAL` | Severity floor for vulnerability findings. |
+| `--scanners` | No | `vuln,secret,license` | Comma-separated scanner list. |
+| `--secretConfig` | No | Auto-detected | Path to custom secret rules file. Auto-detects `trivy-secret.yaml` in the project root. |
+| `--ignoreFile` | No | Auto-detected | Path to ignore file. Auto-detects `.trivyignore.yaml` or `.trivyignore` in the project root. |
+| `--trivyConfig` | No | Auto-detected | Path to config file. Auto-detects `trivy.yaml` in the project root. |
+| `--no-licenseFull` | No | — | Disable source-level license scanning for faster runs. |
+
+### Response (stdout)
+
+Raw trivy JSON — the same shape trivy produces on the command line. Pass the captured stdout to `transform-scan-code.js --trivyFile` to convert it to the unified findings shape.
+
+---
+
+## `transform-scan-code.js`
+
+Reads raw opengrep and/or trivy JSON and emits the unified findings shape.
+
+```bash
+node "${PLUGIN_ROOT}/skills/scan-code/scripts/transform-scan-code.js" \
+ --opengrepFile "<opengrep-file>" \
+ --trivyFile "<trivy-file>" \
+ --projectRoot "<project-root>"
+```
+
+| Flag | Required | Description |
+|------|----------|-------------|
+| `--opengrepFile` | At least one of these two | Path to raw opengrep JSON output. |
+| `--trivyFile` | At least one of these two | Path to raw trivy JSON output. |
+| `--projectRoot` | No | Project root used to relativize file paths in `location`. |
+
+### Response (stdout)
+
+```json
+{ "status": "ok", "findings": [ ] }
+```
+
+Each finding: `{ id, severity, category?, confidence?, title, tag, location, details, fix? }`. `severity` is one of `critical|high|warning|medium|info|low|pass`. `category` is one of `vulnerability|secret|license` (trivy) or the opengrep rule category. `confidence` is opengrep-only.
diff --git a/plugins/power-pages/skills/scan-code/scripts/check-tools.js b/plugins/power-pages/skills/scan-code/scripts/check-tools.js
new file mode 100644
index 000000000..4dc1242d9
--- /dev/null
+++ b/plugins/power-pages/skills/scan-code/scripts/check-tools.js
@@ -0,0 +1,45 @@
+#!/usr/bin/env node
+
+const { execSync } = require('child_process');
+
+if (process.argv.includes('--help')) {
+ process.stdout.write(`check-tools.js — Detects whether opengrep and trivy are installed.
+
+Usage:
+ node check-tools.js
+
+No flags required.
+
+Exit codes:
+ 0 Both tools available
+ 1 At least one tool missing (see error field per tool)
+
+Output (stdout, JSON):
+ {
+ "opengrep": { "available": true, "version": "1.50.0", "error": null },
+ "trivy": { "available": false, "version": null, "error": "command not found" }
+ }
+`);
+ process.exit(0);
+}
+
+function probe(cmd, parseVersion) {
+ try {
+ // 60s timeout — first invocation can be slow (cold start, antivirus scan, etc.)
+ const out = execSync(cmd, { encoding: 'utf8', timeout: 60000, stdio: ['ignore', 'pipe', 'pipe'] });
+ return { available: true, version: parseVersion(out), error: null };
+ } catch (err) {
+ return { available: false, version: null, error: (err.stderr || err.message || '').toString().trim() };
+ }
+}
+
+const result = {
+ opengrep: probe('opengrep --version', (out) => (out.match(/[\d.]+/) || [null])[0]),
+ trivy: probe('trivy --version', (out) => {
+ const m = out.match(/Version:\s*([\d.]+)/i) || out.match(/[\d.]+/);
+ return m ? m[1] || m[0] : null;
+ }),
+};
+
+process.stdout.write(JSON.stringify(result, null, 2) + '\n');
+process.exit(result.opengrep.available && result.trivy.available ? 0 : 1);
diff --git a/plugins/power-pages/skills/scan-code/scripts/run-opengrep.js b/plugins/power-pages/skills/scan-code/scripts/run-opengrep.js
new file mode 100644
index 000000000..6a7f3510b
--- /dev/null
+++ b/plugins/power-pages/skills/scan-code/scripts/run-opengrep.js
@@ -0,0 +1,97 @@
+#!/usr/bin/env node
+
+const fs = require('fs');
+const path = require('path');
+const { spawnSync, execSync } = require('child_process');
+const { findProjectRoot } = require('../../../scripts/lib/validation-helpers');
+
+if (process.argv.includes('--help')) {
+ process.stdout.write(`run-opengrep.js — Runs opengrep and emits the raw JSON output.
+
+Usage:
+ node run-opengrep.js --projectRoot <path> [--rulesets <comma-separated>] [--include <glob>]
+
+Flags:
+ --projectRoot Directory to scan (required). Must be a Power Pages site project root
+ (has powerpages.config.json or .powerpages-site/); anything else is refused.
+ --rulesets Comma-separated list of rulesets (default: p/default,p/owasp-top-ten)
+ Each value is passed as a separate --config flag to opengrep.
+ Accepts registry packs (p/owasp-top-ten) and local paths (/path/to/rules.yml).
+ --include Optional glob narrowing the file set
+ --help Show this help message
+
+Exit codes:
+ 0 Success (raw opengrep JSON on stdout)
+ 1 Invocation error (missing --projectRoot, root not found, not a Power Pages site
+ project, or opengrep failed unexpectedly)
+
+Example:
+ node run-opengrep.js --projectRoot <project-root>
+ node run-opengrep.js --projectRoot <project-root> --rulesets <ruleset1>,<ruleset2>
+ node run-opengrep.js --projectRoot <project-root> --rulesets <registry-pack>,<local-rules-path>
+`);
+ process.exit(0);
+}
+
+function getArg(name, fallback = null) {
+ const idx = process.argv.indexOf('--' + name);
+ return idx !== -1 && idx + 1 < process.argv.length ? process.argv[idx + 1] : fallback;
+}
+
+const projectRoot = getArg('projectRoot');
+const rulesets = (getArg('rulesets', 'p/default,p/owasp-top-ten')).split(',').map(r => r.trim()).filter(Boolean);
+const include = getArg('include');
+
+if (!projectRoot) {
+ process.stderr.write('Usage: node run-opengrep.js --projectRoot <path> [--rulesets <comma-separated>]\n');
+ process.exit(1);
+}
+
+if (!fs.existsSync(projectRoot)) {
+ process.stderr.write(`Project root not found: ${projectRoot}\n`);
+ process.exit(1);
+}
+
+// Defensive: scan only a Power Pages site project root, never an arbitrary directory.
+if (findProjectRoot(projectRoot) !== path.resolve(projectRoot)) {
+ process.stderr.write(`Refusing to scan ${path.resolve(projectRoot)}: not a Power Pages site project (no powerpages.config.json or .powerpages-site/).\n`);
+ process.exit(1);
+}
+
+try {
+ // 60s timeout — first invocation can be slow (cold start, antivirus scan, etc.)
+ execSync('opengrep --version', { encoding: 'utf8', timeout: 60000 });
+} catch {
+ process.stderr.write('opengrep is not installed or not on PATH.\n');
+ process.exit(1);
+}
+
+const args = ['scan'];
+for (const rs of rulesets) {
+ args.push('--config', rs);
+}
+args.push('--json', '--quiet');
+
+try {
+ const helpText = execSync('opengrep scan --help', { encoding: 'utf8' });
+ if (/--metrics/.test(helpText)) args.push('--metrics', 'off');
+} catch { /* skip --metrics if help check fails */ }
+
+if (include) args.push('--include', include);
+args.push(projectRoot);
+
+// 64MB buffer — opengrep output can be large for big projects
+const proc = spawnSync('opengrep', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
+
+if (proc.error) {
+ process.stderr.write(`Failed to invoke opengrep: ${proc.error.message}\n`);
+ process.exit(1);
+}
+
+// opengrep exits 1 when findings are present; treat 0 and 1 as success.
+if (proc.status !== 0 && proc.status !== 1) {
+ process.stderr.write(`opengrep exited with status ${proc.status}: ${proc.stderr}\n`);
+ process.exit(1);
+}
+
+process.stdout.write(proc.stdout || '{}');
diff --git a/plugins/power-pages/skills/scan-code/scripts/run-trivy.js b/plugins/power-pages/skills/scan-code/scripts/run-trivy.js
new file mode 100644
index 000000000..b3f4d7aef
--- /dev/null
+++ b/plugins/power-pages/skills/scan-code/scripts/run-trivy.js
@@ -0,0 +1,119 @@
+#!/usr/bin/env node
+
+const path = require('path');
+const fs = require('fs');
+const { spawnSync, execSync } = require('child_process');
+const { findProjectRoot } = require('../../../scripts/lib/validation-helpers');
+
+if (process.argv.includes('--help')) {
+ process.stdout.write(`run-trivy.js — Runs trivy and emits the raw JSON output.
+
+Scans for vulnerabilities in dependencies, hard-coded secrets in source
+files, and license compliance issues in packages.
+
+Usage:
+ node run-trivy.js --projectRoot <path> [flags]
+
+Flags:
+ --projectRoot Directory to scan (required). Must be a Power Pages site project root
+ (has powerpages.config.json or .powerpages-site/); anything else is refused.
+ --severity Comma-separated severity floor (default: LOW,MEDIUM,HIGH,CRITICAL)
+ --scanners Comma-separated scanner list (default: vuln,secret,license)
+ --secretConfig Path to custom secret rules file (trivy-secret.yaml format)
+ --ignoreFile Path to .trivyignore or .trivyignore.yaml
+ --trivyConfig Path to trivy.yaml config file (license classification, etc.)
+ --no-licenseFull Disable source-level license scanning for faster runs
+ --help Show this help message
+
+Exit codes:
+ 0 Success (raw trivy JSON on stdout)
+ 1 Invocation error (missing --projectRoot, root not found, not a Power Pages site
+ project, or trivy failed unexpectedly)
+
+Examples:
+ node run-trivy.js --projectRoot <project-root>
+ node run-trivy.js --projectRoot <project-root> --severity <comma-separated-severities>
+ node run-trivy.js --projectRoot <project-root> --secretConfig <secret-config-file>
+ node run-trivy.js --projectRoot <project-root> --ignoreFile <ignore-file>
+`);
+ process.exit(0);
+}
+
+function getArg(name, fallback = null) {
+ const idx = process.argv.indexOf('--' + name);
+ return idx !== -1 && idx + 1 < process.argv.length ? process.argv[idx + 1] : fallback;
+}
+
+function hasFlag(name) {
+ return process.argv.includes('--' + name);
+}
+
+const projectRoot = getArg('projectRoot');
+
+function autoDetect(filename) {
+ if (!projectRoot) return null;
+ const p = path.join(projectRoot, filename);
+ return fs.existsSync(p) ? p : null;
+}
+
+const severity = getArg('severity', 'LOW,MEDIUM,HIGH,CRITICAL');
+const scanners = getArg('scanners', 'vuln,secret,license');
+const trivyConfig = getArg('trivyConfig') || autoDetect('trivy.yaml');
+const secretConfig = getArg('secretConfig') || autoDetect('trivy-secret.yaml');
+const ignoreFile = getArg('ignoreFile') || autoDetect('.trivyignore.yaml') || autoDetect('.trivyignore');
+const licenseFull = !hasFlag('no-licenseFull');
+
+if (!projectRoot) {
+ process.stderr.write('Usage: node run-trivy.js --projectRoot <path> [flags]\n');
+ process.exit(1);
+}
+
+if (!fs.existsSync(projectRoot)) {
+ process.stderr.write(`Project root not found: ${projectRoot}\n`);
+ process.exit(1);
+}
+
+// Defensive: scan only a Power Pages site project root, never an arbitrary directory.
+if (findProjectRoot(projectRoot) !== path.resolve(projectRoot)) {
+ process.stderr.write(`Refusing to scan ${path.resolve(projectRoot)}: not a Power Pages site project (no powerpages.config.json or .powerpages-site/).\n`);
+ process.exit(1);
+}
+
+try {
+ // 60s timeout — first invocation can be slow
+ execSync('trivy --version', { encoding: 'utf8', timeout: 60000 });
+} catch {
+ process.stderr.write('trivy is not installed or not on PATH.\n');
+ process.exit(1);
+}
+
+const args = [
+ 'fs',
+ '--scanners', scanners,
+ '--severity', severity,
+ '--pkg-types', 'library',
+ '--format', 'json',
+ '--quiet',
+ '--exit-code', '0',
+];
+
+if (secretConfig) args.push('--secret-config', secretConfig);
+if (ignoreFile) args.push('--ignorefile', ignoreFile);
+if (trivyConfig) args.push('--config', trivyConfig);
+if (licenseFull) args.push('--license-full');
+
+args.push(projectRoot);
+
+// 64MB buffer — trivy output can be large for projects with many dependencies
+const proc = spawnSync('trivy', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
+
+if (proc.error) {
+ process.stderr.write(`Failed to invoke trivy: ${proc.error.message}\n`);
+ process.exit(1);
+}
+if (proc.status !== 0) {
+ process.stderr.write(`trivy exited with status ${proc.status}: ${proc.stderr}\n`);
+ process.exit(1);
+}
+
+process.stdout.write(proc.stdout || '{}');
diff --git a/plugins/power-pages/skills/scan-code/scripts/transform-scan-code.js b/plugins/power-pages/skills/scan-code/scripts/transform-scan-code.js
new file mode 100644
index 000000000..7c8d7cc48
--- /dev/null
+++ b/plugins/power-pages/skills/scan-code/scripts/transform-scan-code.js
@@ -0,0 +1,229 @@
+#!/usr/bin/env node
+// Transforms raw opengrep and trivy JSON output into unified section findings.
+// Strict to the documented response shapes — no fallbacks for unseen variants.
+// Run with --help for flags.
+
+const fs = require('fs');
+const path = require('path');
+
+if (process.argv.includes('--help')) {
+ process.stdout.write(`transform-scan-code.js — Transform raw opengrep + trivy JSON into section findings.
+
+Usage:
+ node transform-scan-code.js [--opengrepFile <path>] [--trivyFile <path>] [--projectRoot <path>]
+
+Flags:
+ --opengrepFile Path to raw opengrep JSON output (optional — omit if opengrep was not run)
+ --trivyFile Path to raw trivy JSON output (optional — omit if trivy was not run)
+ --projectRoot Project root used to relativize file paths in locations (optional)
+ --help Show this help message
+
+At least one of --opengrepFile or --trivyFile must be provided.
+
+Exit codes:
+ 0 Success (unified JSON on stdout)
+ 1 Invocation error
+
+Examples:
+ node transform-scan-code.js --opengrepFile <opengrep-file> --trivyFile <trivy-file> --projectRoot <project-root>
+ node transform-scan-code.js --opengrepFile <opengrep-file> --projectRoot <project-root>
+ node transform-scan-code.js --trivyFile <trivy-file>
+`);
+ process.exit(0);
+}
+
+function getArg(name, fallback = null) {
+ const idx = process.argv.indexOf('--' + name);
+ return idx !== -1 && idx + 1 < process.argv.length ? process.argv[idx + 1] : fallback;
+}
+
+function readJson(filePath, label) {
+ if (!fs.existsSync(filePath)) {
+ process.stderr.write(`${label} not found: ${filePath}\n`);
+ process.exit(1);
+ }
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch (err) {
+ process.stderr.write(`Failed to parse ${label} (${filePath}): ${err.message}\n`);
+ process.exit(1);
+ }
+}
+
+const OPENGREP_SEVERITY_TO_BUCKET = {
+ ERROR: 'critical',
+ CRITICAL: 'critical',
+ HIGH: 'high',
+ WARNING: 'warning',
+ MEDIUM: 'medium',
+ INFO: 'info',
+ LOW: 'low',
+};
+
+const TRIVY_SEVERITY_TO_BUCKET = {
+ CRITICAL: 'critical',
+ HIGH: 'high',
+ MEDIUM: 'medium',
+ LOW: 'low',
+ UNKNOWN: 'info',
+};
+
+// Fallback so an unknown severity is still counted, never dropped from report totals.
+const SEVERITY_FALLBACK = 'warning';
+
+function normalizeSeverity(map, raw) {
+ if (typeof raw === 'string') {
+ const bucket = map[raw.trim().toUpperCase()];
+ if (bucket) return bucket;
+ }
+ return SEVERITY_FALLBACK;
+}
+
+function relativize(filePath, projectRoot) {
+ const normalized = filePath.replace(/\\/g, '/');
+ if (!projectRoot) return normalized;
+ const root = projectRoot.replace(/\\/g, '/');
+ // Path boundary so "/repo/app2" isn't treated as under root "/repo/app".
+ const rootWithSep = root.endsWith('/') ? root : root + '/';
+ return normalized === root || normalized.startsWith(rootWithSep)
+ ? path.posix.relative(root, normalized)
+ : normalized;
+}
+
+// Opengrep result shape (per opengrep1-4.json samples):
+// { check_id, path, start: { line }, extra: { severity, message, metadata: { category, confidence, references, cwe, vulnerability_class } } }
+//
+// Multiple results with the same check_id are grouped into a single finding (one finding per rule).
+// Locations are aggregated; the rule's shared message is shown once.
+function transformOpengrep(raw, projectRoot) {
+ const byCheckId = new Map();
+ // Tolerate missing `results` (run-opengrep.js "{}" fallback) — treat as no findings.
+ const results = Array.isArray(raw?.results) ? raw.results : [];
+ for (const r of results) {
+ if (!byCheckId.has(r.check_id)) byCheckId.set(r.check_id, []);
+ byCheckId.get(r.check_id).push(r);
+ }
+
+ const findings = [];
+ let counter = 1;
+ for (const [checkId, occurrences] of byCheckId) {
+ const first = occurrences[0];
+ // Some rules omit metadata/references; read defensively to avoid throwing.
+ const metadata = first.extra.metadata || {};
+ const vulnClass = metadata.vulnerability_class;
+ const title = Array.isArray(vulnClass) && vulnClass.length > 0 ? vulnClass[0] : checkId;
+ const locations = occurrences.map(r => `${relativize(r.path, projectRoot)}:${r.start.line}`);
+ const references = Array.isArray(metadata.references) ? metadata.references : [];
+
+ const detailLines = [first.extra.message];
+ detailLines.push('', `${occurrences.length} occurrence${occurrences.length === 1 ? '' : 's'}:`);
+ for (const loc of locations) detailLines.push(`- ${loc}`);
+ if (references.length > 0) {
+ detailLines.push('', 'References:');
+ for (const ref of references.slice(0, 3)) detailLines.push(`- ${ref}`);
+ }
+
+ findings.push({
+ id: `opengrep-${counter++}`,
+ severity: normalizeSeverity(OPENGREP_SEVERITY_TO_BUCKET, first.extra.severity),
+ category: metadata.category,
+ confidence: metadata.confidence,
+ title,
+ tag: checkId,
+ location: locations[0],
+ details: detailLines.join('\n'),
+ });
+ }
+ return findings;
+}
+
+// Trivy result shape (per trivy1-8.json samples):
+// Results[]: { Target, Class, Vulnerabilities?, Secrets?, Licenses? }
+// Vulnerability: { VulnerabilityID, PkgName, InstalledVersion, FixedVersion, Severity, Title }
+// Secret: { RuleID, Category, Severity, Title, StartLine, Match, Code }
+// License: { Severity, Category, PkgName, FilePath, Name }
+//
+// Read only safe metadata — never Match/Code — so secret values can't leak. Don't add them.
+function transformTrivy(raw, projectRoot) {
+ const findings = [];
+ let counter = 1;
+ // Tolerate missing `Results` (run-trivy.js "{}" fallback) — treat as no findings.
+ const results = Array.isArray(raw?.Results) ? raw.Results : [];
+ for (const target of results) {
+ const targetPath = relativize(target.Target, projectRoot);
+
+ if (target.Vulnerabilities) {
+ for (const v of target.Vulnerabilities) {
+ findings.push({
+ id: `trivy-${counter++}`,
+ severity: normalizeSeverity(TRIVY_SEVERITY_TO_BUCKET, v.Severity),
+ category: 'vulnerability',
+ title: `${v.PkgName}@${v.InstalledVersion}`,
+ tag: v.VulnerabilityID,
+ location: targetPath,
+ details: v.Title,
+ fix: v.FixedVersion ? `Upgrade ${v.PkgName} to ${v.FixedVersion}` : null,
+ });
+ }
+ }
+
+ if (target.Secrets) {
+ for (const s of target.Secrets) {
+ findings.push({
+ id: `trivy-${counter++}`,
+ severity: normalizeSeverity(TRIVY_SEVERITY_TO_BUCKET, s.Severity),
+ category: 'secret',
+ title: s.Title,
+ tag: s.RuleID,
+ location: `${targetPath}:${s.StartLine}`,
+ details: s.Category,
+ fix: 'Remove the secret from source code and rotate it immediately',
+ });
+ }
+ }
+
+ if (target.Licenses) {
+ for (const l of target.Licenses) {
+ findings.push({
+ id: `trivy-${counter++}`,
+ severity: normalizeSeverity(TRIVY_SEVERITY_TO_BUCKET, l.Severity),
+ category: 'license',
+ title: `${l.PkgName}: ${l.Name}`,
+ tag: l.Name,
+ location: relativize(l.FilePath, projectRoot),
+ details: `Category: ${l.Category}`,
+ });
+ }
+ }
+ }
+ return findings;
+}
+
+function main() {
+ const opengrepFile = getArg('opengrepFile');
+ const trivyFile = getArg('trivyFile');
+ const projectRoot = getArg('projectRoot');
+
+ if (!opengrepFile && !trivyFile) {
+ process.stderr.write('Provide at least one of --opengrepFile or --trivyFile.\n');
+ return 1;
+ }
+
+ const findings = [];
+
+ if (opengrepFile) {
+ findings.push(...transformOpengrep(readJson(opengrepFile, 'opengrep file'), projectRoot));
+ }
+ if (trivyFile) {
+ findings.push(...transformTrivy(readJson(trivyFile, 'trivy file'), projectRoot));
+ }
+
+ process.stdout.write(JSON.stringify({ status: 'ok', findings }) + '\n');
+ return 0;
+}
+
+module.exports = { transformOpengrep, transformTrivy };
+
+if (require.main === module) {
+ process.exit(main());
+}
diff --git a/plugins/power-pages/skills/security-review/SKILL.md b/plugins/power-pages/skills/security-review/SKILL.md
index 54a6fc1b0..1aa122ba8 100644
--- a/plugins/power-pages/skills/security-review/SKILL.md
+++ b/plugins/power-pages/skills/security-review/SKILL.md
@@ -2,14 +2,14 @@
name: security-review
description: >-
Runs a guided, end-to-end security review of a Power Pages site and
- consolidates every finding into one HTML report covering the live
- site, browser headers, firewall, authentication, and role-based
- permissions. Use when the user wants a full security review, a
- release-readiness check before publishing, an access-and-config
- check during development, live site monitoring, or asks open-ended
- questions like "review my site security", "is my site safe to ship",
- "do a security check", "monitor my site" — even if they do not name
- the individual checks.
+ consolidates every finding into one HTML report covering source code
+ and dependencies, the live site, browser headers, firewall,
+ authentication, and role-based permissions. Use when the user wants a
+ full security review, a release-readiness check before publishing, a
+ code-and-config check during development, live site monitoring, or
+ asks open-ended questions like "review my site security", "is my site
+ safe to ship", "do a security check", "monitor my site" — even if they
+ do not name the individual checks.
user-invocable: true
argument-hint: "[optional natural-language hint about the goal]"
allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, Skill, Agent
@@ -76,7 +76,7 @@ Use `Glob` to find `**/powerpages.config.json`. If none is found, tell the user
For the `monitor` and `release` goals (any goal that delegates to `scan-site` or `manage-firewall`), also confirm that `.powerpages-site/website.yml` exists. If it does not, the site has not been deployed yet — tell the user (in plain language) the site needs to be deployed once before a live security review can run, recommend `/deploy-site`, then stop. Do **not** try to identify the site by name or URL — different sites can share the same name.
-For the `access-config` goal, the deploy check is not required: authentication, web roles, and table permissions are read from local YAML alone.
+For the `code-config` goal, the deploy check is not required: source code, dependencies, authentication, web roles, and table permissions are read from local files alone.
### 1.2 Prepare a temporary working folder
@@ -96,7 +96,7 @@ The final HTML always lives at `<PROJECT_ROOT>/docs/security-review-<YYYY-MM-DD-
<!-- gate: security-review:2.1.goal | category=plan | cancel-leaves=nothing -->
-> 🚦 **Gate (plan · security-review:2.1.goal):** Capture the review goal — choice branches into one of three sub-skill sets (`access-config` / `release` / `monitor`).
+> 🚦 **Gate (plan · security-review:2.1.goal):** Capture the review goal — choice branches into one of three sub-skill sets (`code-config` / `release` / `monitor`).
>
> **Trigger:** Phase 2.1 entry, unless `$ARGUMENTS` already answers it.
> **Why we ask:** Auto-picking `release` runs ALL sub-skills (slow; possibly hits scan/firewall endpoints unnecessarily); auto-picking the wrong goal mis-scopes the review.
@@ -108,7 +108,7 @@ Ask the user with a single `AskUserQuestion` call. If the user's initial request
| Label | Description |
|-------|-------------|
-| Access & config | Check authentication, web roles, and table permissions. Works on local files only. |
+| Code & config | Check source code, dependencies, authentication, web roles, and table permissions. Works on local files only. |
| Release readiness | Full review before publishing — checks everything. (Recommended) |
| Deployed site | Check the live site for issues. Requires deployment. |
@@ -116,13 +116,13 @@ Goal mapping (internal):
| Label | Goal id | Skills |
|-------|---------|------------|
-| Access & config | `access-config` | audit-permissions, setup-auth (read-only) |
-| Release readiness | `release` | scan-site, manage-headers, manage-firewall, audit-permissions, setup-auth (read-only) |
+| Code & config | `code-config` | scan-code, audit-permissions, setup-auth (read-only) |
+| Release readiness | `release` | scan-code, scan-site, manage-headers, manage-firewall, audit-permissions, setup-auth (read-only) |
| Deployed site | `monitor` | scan-site |
### 2.2 Capture the chosen skill set
-Build a `selectedSkills` list based on the answer. Always include the read-only check of `setup-auth` for the `access-config` and `release` goals (it consists of reading existing YAML, not running the skill itself — see § 3.2 below). This is the **Access & Data Security Validation** component.
+Build a `selectedSkills` list based on the answer. Always include the read-only check of `setup-auth` for the `code-config` and `release` goals (it consists of reading existing YAML, not running the skill itself — see § 3.2 below). This is the **Access & Data Security Validation** component.
---
@@ -134,9 +134,9 @@ Spawn each selected skill as a background subagent via the `Agent` tool. Each su
Skills run as **parallel subagents** using the `Agent` tool.
-**Default — launch every Agent-eligible skill in one parallel batch.** Spawn all selected subagents in a single message with multiple `Agent` tool calls so they start concurrently. Each subagent runs with `run_in_background: true`. The Agent-eligible set is `scan-site`, `manage-headers`, `manage-firewall` — these all support `--review` mode. `scan-site` is the slowest (server-side scan, several minutes); the others typically finish within seconds.
+**Default — launch every Agent-eligible skill in one parallel batch.** Spawn all selected subagents in a single message with multiple `Agent` tool calls so they start concurrently. Each subagent runs with `run_in_background: true`. The Agent-eligible set is `scan-code`, `scan-site`, `manage-headers`, `manage-firewall` — these all support `--review` mode. `scan-site` (server-side scan, several minutes) and `scan-code` (local static analysis + dependency scan, up to minutes on large projects) are the slowest; the others typically finish within seconds.
-**Fallback — staggered launch.** If the harness rejects a parallel-batch call for any reason, launch `scan-site` first and then the remaining skills in a follow-up message. This is a tool-affordance fallback, not the preferred path.
+**Fallback — staggered launch.** If the harness rejects a parallel-batch call for any reason, launch `scan-code` and `scan-site` first (the long-running ones) and then the remaining skills in a follow-up message. This is a tool-affordance fallback, not the preferred path.
**Inline checks (run while subagents work).** `audit-permissions` and `setup-auth` do not support `--review` and MUST NOT be launched via `Agent` — handle them inline as described in § 3.2.
@@ -168,6 +168,7 @@ After all subagents complete, expect JSON files at `<SYSTEM_TEMP>/security-revie
```text
<SYSTEM_TEMP>/security-review/
+├── scan-code.json (when invoked)
├── scan-site.json
├── manage-headers.json
├── manage-firewall.json
@@ -182,6 +183,7 @@ Only findings that come from a tool that genuinely outputs severity may carry a
| Section | Source | Severity allowed? |
|---------|--------|-------------------|
+| `scan-code` | opengrep, trivy | Yes |
| `scan-site` | deep-scan (ZAP) | Yes |
| `manage-headers` | `transform-headers.js` (inventory) | **No** |
| `manage-firewall` | `transform-firewall.js` (inventory) | **No** |
diff --git a/plugins/power-pages/skills/security-review/references/flow.md b/plugins/power-pages/skills/security-review/references/flow.md
index fc605f8a3..c6e52b9cd 100644
--- a/plugins/power-pages/skills/security-review/references/flow.md
+++ b/plugins/power-pages/skills/security-review/references/flow.md
@@ -10,11 +10,11 @@ One question, three answers. The three goals match the most common reasons a use
| Goal | When to use it |
|------|-----------------|
-| Access & config | Frequent checks during development — pre-commit / pre-PR safety check. Covers Access & Data Security Validation (authentication, roles, table permissions) on local YAML. |
+| Code & config | Frequent checks during development — pre-commit / pre-PR safety check. Covers source code and dependency scanning plus Access & Data Security Validation (authentication, roles, table permissions) on local files. |
| Release readiness | Last comprehensive check before pushing to production. Adds live site scan, browser headers, and firewall on top of access checks. |
| Deployed site | Detect runtime issues from real user traffic on a deployed site. |
-Authentication and authorization checks (**Access & Data Security Validation**) are the focus of Access & config and are also bundled into Release readiness rather than being a separate goal. Splitting them into their own option created confusion about when to use them versus the other goals.
+Authentication and authorization checks (**Access & Data Security Validation**) are the focus of Code & config and are also bundled into Release readiness rather than being a separate goal. Splitting them into their own option created confusion about when to use them versus the other goals.
Why not start by asking the user which skills to run? Because most users — including engineers — do not know the skill names yet, and listing them upfront reads as menu-driven interrogation. Ask the *outcome* the user wants and let the skill pick the right skills.