Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 97 additions & 5 deletions docs/GUARDLINK_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,107 @@ Append after severity: `cwe:CWE-89`, `owasp:A03:2021`, `capec:CAPEC-66`, `attack
| Proprietary algorithm | `@shield:begin` ... `@shield:end` |
| Unsure which annotation | `@comment -- "describe what you see"` |

## Commands
## CLI Commands

```bash
guardlink validate . # Check for errors
guardlink report . # Generate threat-model.md
guardlink status . # Coverage summary
guardlink suggest <file> # Get annotation suggestions
# Core
guardlink init [dir] # Initialize .guardlink/ and agent instruction files
guardlink parse [dir] # Parse annotations → ThreatModel JSON
guardlink status [dir] # Risk grade + coverage summary
guardlink validate [dir] [--strict] # Syntax errors, dangling refs, unmitigated exposures

# Reports & Export
guardlink report [dir] # Generate threat-model.md + optional JSON
guardlink dashboard [dir] # Interactive HTML dashboard with Mermaid diagrams
guardlink sarif [dir] [-o file] # SARIF 2.1.0 for GitHub Advanced Security / VS Code
guardlink diff [ref] # Compare threat model against a git ref (default: HEAD~1)

# AI-Powered Analysis
guardlink threat-report <fw|prompt> # AI threat report (see frameworks below)
guardlink threat-reports # List saved threat reports
guardlink annotate <prompt> # Launch coding agent to add annotations
guardlink config <show|set|clear> # Manage LLM provider / CLI agent configuration

# Interactive
guardlink tui [dir] # Interactive TUI: slash commands + AI chat
guardlink mcp # Start MCP server (stdio) for Claude Code, Cursor, etc.
guardlink gal # Display GAL annotation language quick reference
```

## Threat Report Frameworks

```bash
guardlink threat-report stride # STRIDE (Spoofing, Tampering, Repudiation, Info Disclosure, DoS, Elevation)
guardlink threat-report dread # DREAD risk scoring
guardlink threat-report pasta # PASTA (Process for Attack Simulation and Threat Analysis)
guardlink threat-report attacker # Attacker-centric (personas, kill chains, attack trees)
guardlink threat-report rapid # RAPID threat model
guardlink threat-report general # General-purpose comprehensive analysis
guardlink threat-report "<custom>" # Custom prompt — any free-text analysis instructions
```

## AI Agent Flags

All AI commands (`threat-report`, `annotate`) support:

```bash
--claude-code # Run via Claude Code CLI (inline)
--codex # Run via Codex CLI (inline)
--gemini # Run via Gemini CLI (inline)
--cursor # Open Cursor IDE with prompt on clipboard
--windsurf # Open Windsurf IDE with prompt on clipboard
--clipboard # Copy prompt to clipboard only
```

Additional `threat-report` flags:

```bash
--thinking # Enable extended thinking / reasoning mode
--web-search # Enable web search grounding (OpenAI Responses API)
--provider <p> # Direct API: anthropic, openai, openrouter, deepseek
--model <m> # Override model name
```

## TUI Commands

Run `guardlink tui` for the interactive terminal interface:

```
/init [name] Initialize project
/parse Parse annotations, build threat model
/status Risk grade + summary stats
/validate Check for errors + dangling refs
/exposures [--all] List open exposures by severity (--asset --severity --threat --file)
/show <n> Detail view + code context for exposure
/scan Coverage scanner — find unannotated symbols
/assets Asset tree with threat/control counts
/files Annotated file tree with exposure counts
/view <file> Show all annotations in a file with code context
/threat-report <fw> AI threat report (frameworks above or custom text)
/threat-reports List saved reports
/annotate <prompt> Launch coding agent to annotate codebase
/model Set AI provider (API or CLI agent)
/report Generate markdown + JSON report
/dashboard Generate HTML dashboard + open browser
/diff [ref] Compare model vs git ref (default: HEAD~1)
/sarif [-o file] Export SARIF 2.1.0
/gal GAL annotation language guide
(freeform text) Chat about your threat model with AI
```

## Critical Syntax Rules

1. **@boundary requires TWO assets**: `@boundary between #A and #B` or `@boundary #A | #B`.
2. **@flows is ONE source → ONE target per line**: `@flows <source> -> <target> via <mechanism>`.
3. **@exposes / @mitigates require defined #id refs**: Every `#id` must have a definition in `.guardlink/definitions.*`.
4. **Severity in square brackets**: `[P0]` `[P1]` `[P2]` `[P3]` or `[critical]` `[high]` `[medium]` `[low]`. Goes AFTER the threat ref.
5. **Descriptions in double quotes after --**: `-- "description text here"`.
6. **IDs use parentheses in definitions, hash in references**: Define `(#sqli)`, reference `#sqli`.
7. **Asset references**: Use `#id` or `Dotted.Path` — no spaces or special chars.
8. **External refs space-separated after severity**: `cwe:CWE-89 owasp:A03:2021 capec:CAPEC-66`.
9. **@comment always needs -- and quotes**: `@comment -- "your note here"`.
10. **One annotation per comment line.** Do NOT put two @verbs on the same line.

## MCP Tools

When connected via `.mcp.json`, use:
Expand Down
57 changes: 55 additions & 2 deletions docs/SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -866,7 +866,57 @@ A conforming GuardLink tool may expose a Model Context Protocol (MCP) server wit

MCP integration enables real-time threat model awareness during coding sessions. Tools should support project-scoped MCP configuration (e.g., `.mcp.json` for Claude Code) so that the MCP server can be committed to the repository and automatically available to all developers.

### 8.3. `@shield` Compliance
### 8.3. AI-Powered Threat Analysis

A conforming Level 4 implementation may provide AI-driven threat analysis that takes the parsed ThreatModel as input and produces structured reports using established threat modeling frameworks:

| Framework | Description |
|-----------|-------------|
| STRIDE | Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege |
| DREAD | Risk scoring: Damage, Reproducibility, Exploitability, Affected Users, Discoverability |
| PASTA | Process for Attack Simulation and Threat Analysis — seven-stage methodology |
| Attacker-centric | Persona-based analysis with kill chains, attack trees, and adversary motivation |
| RAPID | Risk Assessment Process for Informed Decision-making |
| General | Comprehensive analysis combining multiple frameworks as appropriate for the codebase |

The analysis workflow:
1. The tool serializes the ThreatModel (assets, threats, controls, flows, boundaries, exposures) into a prompt
2. Project context (README, package manifest, directory structure) is included for architecture understanding
3. Code snippets from annotated locations are extracted to provide real implementation context
4. The prompt is sent to an LLM (via direct API or CLI agent) with framework-specific system instructions
5. The AI reads the actual source files, cross-references annotations with code, and produces a structured report
6. Reports are saved as timestamped markdown files in `.guardlink/threat-reports/`

Analysis can be performed through multiple execution paths:
- **Direct API**: Streaming LLM calls via Anthropic, OpenAI, OpenRouter, DeepSeek, or Ollama
- **CLI Agents**: Inline execution via Claude Code, Codex CLI, or Gemini CLI (the agent reads the codebase directly)
- **IDE Agents**: Prompt copied to clipboard for Cursor, Windsurf, or other IDE-integrated assistants

Additional analysis capabilities:
- **Extended thinking / reasoning mode**: Enables chain-of-thought reasoning for deeper analysis
- **Web search grounding**: Augments analysis with real-time CVE, advisory, and vulnerability data
- **Custom prompts**: Free-text analysis instructions for domain-specific or mixed-framework analysis

### 8.4. Interactive Dashboard

A conforming implementation may generate an interactive HTML dashboard that visualizes the threat model. The dashboard should include:
- Risk grade and severity breakdown
- Asset graph with threat/control relationships
- Mermaid-based data flow diagrams generated from `@flows` and `@boundary` annotations
- Exposure triage view with severity filtering
- Annotation coverage statistics
- Integrated AI threat report summaries (loaded from `.guardlink/threat-reports/`)

### 8.5. Interactive TUI

A conforming implementation may provide an interactive terminal interface (TUI) that combines:
- Slash commands for all CLI operations (`/parse`, `/status`, `/validate`, `/exposures`, etc.)
- Freeform AI chat for conversational threat model exploration
- Exposure triage workflow (`/exposures` → `/show <n>` for detail + code context)
- Coverage scanning (`/scan`) to identify unannotated security-relevant symbols
- Integrated AI provider configuration (`/model`) supporting both direct API and CLI agent modes

### 8.6. `@shield` Compliance

AI tools claiming GuardLink Level 4 conformance (§9) must implement `@shield` exclusion as defined in §3.4. This is a compliance requirement for GuardLink-aware AI integrations. Code marked with `@shield` contains content the developer has explicitly decided should not be processed by external AI systems.

Expand Down Expand Up @@ -905,9 +955,12 @@ A Level 3 conforming implementation (includes Level 2) additionally:
### Level 4: AI-Integrated

A Level 4 conforming implementation (includes Level 3) additionally:
- Respects `@shield` exclusion markers (§3.4, §8.3)
- Respects `@shield` exclusion markers (§3.4, §8.6)
- Provides MCP server integration (§8.2) or equivalent
- Supports AI-assisted annotation generation
- May provide AI-powered threat analysis with framework-specific reports (§8.3)
- May provide interactive dashboard visualization (§8.4)
- May provide interactive TUI with exposure triage and AI chat (§8.5)

### Conformance Testing

Expand Down
32 changes: 28 additions & 4 deletions src/agents/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,21 @@ interface SavedConfig {
apiKey?: string;
aiMode?: 'cli-agent' | 'api';
cliAgent?: string;
/** Enable extended thinking (Anthropic) / reasoning (DeepSeek) */
extendedThinking?: boolean;
/** Enable web search grounding (OpenAI Responses API) */
webSearch?: boolean;
/** Response format: 'text' or 'json' */
responseFormat?: 'text' | 'json';
}

const DEFAULT_MODELS: Record<LLMProvider, string> = {
anthropic: 'claude-sonnet-4-5-20250929',
openai: 'gpt-4o',
openrouter: 'anthropic/claude-sonnet-4-5-20250929',
anthropic: 'claude-sonnet-4-6',
openai: 'gpt-5.2',
google: 'gemini-2.5-flash',
openrouter: 'anthropic/claude-sonnet-4-6',
deepseek: 'deepseek-chat',
ollama: 'llama3.2',
};

const CONFIG_FILE = 'config.json';
Expand Down Expand Up @@ -87,7 +95,7 @@ export function resolveConfig(
const provider = flags.provider as LLMProvider;
return {
provider,
model: flags.model || DEFAULT_MODELS[provider] || 'gpt-4o',
model: flags.model || DEFAULT_MODELS[provider] || 'gpt-5.2',
apiKey: flags.apiKey,
};
}
Expand Down Expand Up @@ -118,6 +126,7 @@ export function resolveConfig(
provider: projectCfg.provider,
model: flags?.model || projectCfg.model || DEFAULT_MODELS[projectCfg.provider],
apiKey: projectCfg.apiKey,
...savedConfigExtras(projectCfg),
};
}

Expand All @@ -128,17 +137,29 @@ export function resolveConfig(
provider: globalCfg.provider,
model: flags?.model || globalCfg.model || DEFAULT_MODELS[globalCfg.provider],
apiKey: globalCfg.apiKey,
...savedConfigExtras(globalCfg),
};
}

return null;
}

/** Extract optional LLM config extras from saved config */
function savedConfigExtras(cfg: SavedConfig): Partial<LLMConfig> {
const extras: Partial<LLMConfig> = {};
if (cfg.extendedThinking) extras.extendedThinking = true;
if (cfg.webSearch) extras.webSearch = true;
if (cfg.responseFormat) extras.responseFormat = cfg.responseFormat;
return extras;
}

/** Resolve from provider-specific env vars (ANTHROPIC_API_KEY, etc.) */
function resolveFromEnv(modelOverride?: string): LLMConfig | null {
const checks: [string, LLMProvider][] = [
['ANTHROPIC_API_KEY', 'anthropic'],
['OPENAI_API_KEY', 'openai'],
['GOOGLE_API_KEY', 'google'],
['GEMINI_API_KEY', 'google'],
['OPENROUTER_API_KEY', 'openrouter'],
['DEEPSEEK_API_KEY', 'deepseek'],
];
Expand All @@ -160,6 +181,7 @@ function detectProviderFromKey(key: string): LLMProvider | null {
if (key.startsWith('sk-ant-')) return 'anthropic';
if (key.startsWith('sk-or-')) return 'openrouter';
if (key.startsWith('sk-')) return 'openai'; // OpenAI uses sk- prefix
if (key.startsWith('AIza')) return 'google'; // Google API keys start with AIza
return null; // Can't detect — need GUARDLINK_LLM_PROVIDER
}

Expand Down Expand Up @@ -203,6 +225,8 @@ export function describeConfigSource(
if (process.env.GUARDLINK_LLM_KEY) return 'GUARDLINK_LLM_KEY env var';
if (process.env.ANTHROPIC_API_KEY) return 'ANTHROPIC_API_KEY env var';
if (process.env.OPENAI_API_KEY) return 'OPENAI_API_KEY env var';
if (process.env.GOOGLE_API_KEY) return 'GOOGLE_API_KEY env var';
if (process.env.GEMINI_API_KEY) return 'GEMINI_API_KEY env var';
if (process.env.OPENROUTER_API_KEY) return 'OPENROUTER_API_KEY env var';
if (process.env.DEEPSEEK_API_KEY) return 'DEEPSEEK_API_KEY env var';
const pc = readJsonFile(projectConfigPath(root));
Expand Down
3 changes: 2 additions & 1 deletion src/agents/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,6 @@ export function agentFromOpts(opts: Record<string, any>): AgentEntry | null {
return null;
}

export { launchAgentForeground, launchAgentIDE, launchAgent, copyToClipboard } from './launcher.js';
export { launchAgentForeground, launchAgentIDE, launchAgent, launchAgentInline, copyToClipboard } from './launcher.js';
export type { InlineResult } from './launcher.js';
export { buildAnnotatePrompt } from './prompts.js';
Loading