静态代码分析工具

GoGuard是一款高性能的静态代码分析引擎,用于在运行时之前捕获nil/null解引用、未处理的错误、并发风险、资源泄漏和安全漏洞。

  • by NextStat
  • Rust
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 NextStat/GoGuard

使用说明

GoGuard

Go+TypeScript的数学数据流安全。

GoGuard是一个高性能的静态分析引擎,可以在运行前捕获nil/null解引用、未处理的错误、并发危险、资源泄漏和安全漏洞。

使用Rust分析核心构建,通过FlatBuffers桥(Go→ IR → Rust),GoGuard通过模型上下文协议(MCP)支持快速增量分析和AI代理工作流。

开源。麻省理工学院/阿帕奇-2.0。

创建者: NexStat项目.


目录


为什么选择GoGuard?

Go的编译器可以捕获语法和类型错误,但允许出现一整类运行时恐慌和微妙的错误:

问题 示例 发生了什么
无指针解引用 user, _ := GetUser(id); fmt.Println(user.Name) 恐慌 运行时
默认忽略错误 os.Open("/etc/passwd") Bug永远隐藏
数据竞争 go func() { count++ }() 间歇性腐败
Goroutine泄漏 go func() { for { ... } }() 内存泄漏,OOM
资源泄漏 f, _ := os.Open(path) --没有 defer f.Close() 文件描述符耗尽
SQL注入 db.Query("SELECT * FROM users WHERE id=" + input) 安全漏洞

GoGuard可以使用Go的SSA表单上的抽象解释(定点正向数据流分析)静态地捕捉这些问题。结果是保守的:目标是尽量减少假阴性和假阳性,但也有权衡。

主要特点

  • 22条分析规则 跨越6个类别(无、错误、并发、所有权、穷尽性、污染)
  • 快速增量分析 --电源由 莎莎舞 SHA-256桥接缓存
  • 差异感知模式 --仅分析受git更改影响的包
  • 人工智能原生 --用于Claude Code、Cursor、Windsurf、Codex、Zed、OpenCode的一流MCP服务器
  • 自动修复编排器 --自主分析→ fix → 构建→ test → 重复循环
  • 代码模式 --代理编写JavaScript来查询IR、调用图和诊断
  • SARIF输出 --与GitHub安全选项卡、CodeQL、SonarQube集成
  • 零拷贝FlatBuffers桥接器 --去吧 go/ssa 进行解析,Rust进行分析
  • 开发包 --非MCP代理的子流程包装器

安装

来源(需要Rust+Go)

# Clone
git clone https://github.com/NextStat/GoGuard.git
cd GoGuard

# Build Rust core
cargo build --release

# Build Go bridge
cd goguard-go-bridge && go build -o goguard-go-bridge && cd ..

# Install both binaries
cp target/release/goguard /usr/local/bin/
cp goguard-go-bridge/goguard-go-bridge /usr/local/bin/

来自GitHub发布

从下载适用于您平台的预构建二进制文件 发布:

# macOS (Apple Silicon)
curl -sSL https://github.com/NextStat/GoGuard/releases/latest/download/goguard-darwin-arm64.tar.gz | tar xz
sudo mv goguard goguard-go-bridge /usr/local/bin/

# macOS (Intel)
curl -sSL https://github.com/NextStat/GoGuard/releases/latest/download/goguard-darwin-amd64.tar.gz | tar xz
sudo mv goguard goguard-go-bridge /usr/local/bin/

# Linux (x86_64)
curl -sSL https://github.com/NextStat/GoGuard/releases/latest/download/goguard-linux-amd64.tar.gz | tar xz
sudo mv goguard goguard-go-bridge /usr/local/bin/

自我更新

goguard update

验证安装

goguard --version
# goguard 0.1.0 (abc1234)

先决条件: 必须安装Go工具链(1.22+)。GoGuard使用 go/packages 在引擎盖下通过桥接二进制。


快速开始

# Navigate to any Go project
cd ~/my-go-project

# Initialize GoGuard (creates goguard.toml + AGENTS.md + CLAUDE.md + Agent Skills)
goguard init

# Analyze your code
goguard check ./...

# See what changed since last commit
goguard check --diff ./...

# Get a detailed explanation of any rule
goguard explain NIL001

# Auto-fix all critical issues (with test verification)
goguard auto-fix --severity critical --test

# Output SARIF for CI/GitHub Security tab
goguard check --format sarif ./... > results.sarif

输出示例:

  ⚠ NIL001 handler.go:18:22 — nil pointer dereference
    user may be nil (from GetUser return)
    confidence: 0.95

  ✗ ERR001 server.go:42:5 — error return value not checked
    db.Close() returns error, which is ignored

  ⚠ TAINT001 api.go:55:12 — SQL injection
    tainted data flows from r.URL.Query().Get("id") to db.Query()

Found 3 issues (1 critical, 1 error, 1 warning) in 0.14s

CLI参考

goguard check

分析Go包的安全问题。

goguard check [OPTIONS] [PACKAGES...]

论据:

参数 默认值 描述
PACKAGES ./... Go包进行分析

选项:

标志 默认值 描述
--diff off 仅分析已更改的包 .go git工作树中的文件
--format <FMT> human 输出格式: human, json, sarif, markdown (或 md)
--severity <SEV> (all) 要报告的最低严重程度: info, warning, error, critical
--max-diagnostics <N> 100 要报告的最大诊断数(0=无限制)
--strict-params off 将可忽略的参数视为MaybeNil(更多发现可能会增加误报)
--no-cache off 禁用网桥缓存
--cache-dir <DIR> auto 覆盖网桥缓存目录
--no-color 关闭 禁用彩色输出

示例:

# Analyze entire project
goguard check ./...

# Only critical issues, JSON output
goguard check --severity critical --format json ./...

# CI pipeline — SARIF for GitHub Security tab
goguard check --format sarif ./... > results.sarif

# Diff-aware (only changed packages) — perfect for pre-commit hooks
goguard check --diff ./...

# Analyze a specific package
goguard check ./internal/handler

# Strict nil checking (catches more bugs, may have false positives)
goguard check --strict-params ./...

# Markdown output for AI agents
goguard check --format md ./...

退出代码:

代码 含义
0 未发现问题
1 发现的问题
2 使用错误

goguard auto-fix

自主修复循环:分析→ 生成修复程序→ 应用→ go build → go test → 重复。

goguard auto-fix [OPTIONS] [PACKAGES...]

选项:

标志 默认值 描述
--severity <SEV> error 要修复的最小严重性
--max-iterations <N> 10 最大修复循环迭代次数
--max-fixes <N> 50 要应用的最大修复数
--max-time-secs <N> 300 时间预算(秒)(0=无限制)
--test 关闭 运行 go test 每次迭代后
--dry-run off 预览修复而不应用
-v, --verbose off 显示详细进度

示例:

# Fix all critical issues, verify with tests
goguard auto-fix --severity critical --test

# Preview what would be fixed (no changes)
goguard auto-fix --dry-run

# Quick mode — fix up to 5 issues, no tests, 60s budget
goguard auto-fix --max-fixes 5 --max-time-secs 60

# Fix a specific package
goguard auto-fix ./internal/handler

# Verbose output to see each iteration
goguard auto-fix -v --test

它是如何工作的:

  1. 分析项目
  2. 优先诊断(关键→ 错误→ 警告,尊重依赖顺序)
  3. 生成并应用修复(代码编辑)
  4. 跑 go build ./... --失败时,回滚修复并跳过
  5. 可选运行 go test ./... --关于失败、回滚和跳过
  6. 重复,直到预算用尽或没有更多可解决的问题

输出示例:

Iteration 1/10: analyzing...
  Fixed NIL001 handler.go:18 — added nil check
  go build: OK
  go test: OK (47 pass, 0 fail, 3 skip)

Iteration 2/10: analyzing...
  Fixed ERR001 server.go:42 — added error handling
  go build: OK
  go test: OK

Result: 2 fixes applied, 0 skipped
  Before: { critical: 3, error: 5, warning: 8 }
  After:  { critical: 1, error: 4, warning: 8 }
  Build: pass | Tests: 47 pass, 0 fail
  Time: 12.4s

goguard fix

为特定诊断生成并可选择应用修复程序。

goguard fix <DIAGNOSTIC_ID> [OPTIONS]

选项:

标志 描述
--apply 将修复程序直接写入磁盘
--patch 输出统一差分(管道至 patch -p0)
--verify 申请确认修复工程后重新分析

示例:

# Show the fix (preview)
goguard fix "NIL001-handler.go:18"

# Apply and verify
goguard fix "NIL001-handler.go:18" --apply --verify

# Generate a patch file
goguard fix "NIL001-handler.go:18" --patch > fix.patch
patch -p0 < fix.patch

goguard explain

打印任何规则的详细说明,包括示例和修复。

goguard explain <RULE>

示例:

goguard explain NIL001
goguard explain ERR001
goguard explain TAINT001
goguard explain OWN004

输出示例:

NIL001: Nil pointer dereference

A value that may be nil is used in a context that would cause a
runtime panic (field access, method call, index, etc.).

Example:
  user, _ := GetUser(id)
  fmt.Println(user.Name) // user may be nil

Fix: Check for nil before use:
  if user != nil {
      fmt.Println(user.Name)
  }

goguard query

根据分析结果运行GoGuard QL查询。支持交互式REPL模式。

goguard query [OPTIONS] [EXPRESSION]

选项:

标志 描述
--repl 交互模式——分析一次,运行多个查询
--project-dir <DIR> 项目目录(默认:当前)

示例:

# Single query
goguard query 'diagnostics where severity == "critical"'

# Interactive REPL
goguard query --repl

# Inside the REPL:
> diagnostics where severity == "critical"
> diagnostics where rule == "NIL001"
> count
> callers of "(*Server).handleRequest"
> taint paths from "http.Request" to "database/sql"
> help
> quit

GoGuard QL语法:

查询 描述
diagnostics 列出所有诊断
diagnostics where severity == "critical" 按严重程度筛选
diagnostics where rule == "NIL001" 按规则筛选
diagnostics where file contains "handler" 按文件名筛选
count 统计当前诊断
callers of "pkg.FuncName" 在调用图中显示调用者
taint paths from "source" to "sink" 追踪污染传播
help 显示所有命令

goguard init

在当前项目中初始化GoGuard(一次性设置)。

创建:

  • goguard.toml
  • AGENTS.md (若缺失)
  • CLAUDE.md (若缺失)
  • 由安装的第一方代理指导(SKILL.md+光标规则+Windsurf工作流) goguard init
goguard init

如果 goguard.toml 已经存在, goguard init 退出时出错(它不会覆盖)。 对于现有项目,使用 goguard skills install 和 goguard update-agents-md.

看 配置 对于所有选项。


goguard skills install

在项目中安装(或更新)第一方代理技能。

goguard skills install [--project-dir <DIR>] [--targets <LIST>] [--update true|false]
  • --targets 是一个逗号分隔的列表: github, claude, opencode, agents, windsurf,或 all.
  • 默认目标为 claude,opencode,agents.

示例:

# Update/reinstall skills in default locations
goguard skills install --update

# Also install into Windsurf + visible repo tree
goguard skills install --targets cursor,windsurf,github --update

goguard setup

打印即可复制您的AI工具或编辑器的MCP/LSP配置。

goguard setup <TARGET>

支持的目标: claude-code, cursor, windsurf, codex, zed, opencode, vscode

# Print config for Claude Code
goguard setup claude-code

# Print config for Cursor
goguard setup cursor

看 AI代理集成 有关完整的设置说明。


goguard serve

将GoGuard作为长时间运行的服务器(MCP或LSP)启动。

goguard serve [OPTIONS]
标志 描述
--mcp 以MCP服务器启动(适用于AI代理)
--lsp 以LSP服务器启动(适用于编辑器)
# MCP server (usually called by the AI tool, not directly)
goguard serve --mcp

# LSP server
goguard serve --lsp

goguard update

自更新GoGuard至GitHub发布的最新版本。

goguard update

goguard update-agents-md

更新或创建项目中的GoGuard部分 AGENTS.md 文件,为AI代理提供有关项目分析结果和约定的上下文。

goguard update-agents-md [--path AGENTS.md]

goguard sdk

用于非MCP集成的SDK生成和CLI工具接口。

# Generate Python SDK
goguard sdk generate python

# Call an MCP tool via CLI (for SDK integration)
goguard sdk call <TOOL> --params '<JSON>' [--project-dir <DIR>]

示例:

# Analyze via SDK call
goguard sdk call goguard_analyze --params '{"packages": ["./..."]}'

# Explain a rule
goguard sdk call goguard_explain --params '{"rule": "NIL001"}'

# Fix a diagnostic
goguard sdk call goguard_fix --params '{"diagnostic_id": "NIL001-handler.go:18"}'

配置

goguard.toml 参考

GoGuard正在寻找 goguard.toml 在当前目录中,并向上遍历父目录。创建一个 goguard init.

[goguard]
# Minimum severity to report: "info", "warning", "error", "critical"
severity_threshold = "warning"

# Skip files starting with "// Code generated" (default: true)
skip_generated = true

# Maximum diagnostics to report (0 = unlimited)
# max_diagnostics = 0

# Bridge cache directory (auto-detected if omitted)
# cache_dir = "~/.cache/goguard/bridge-cache"

# Maximum cached bridge outputs to retain
# max_cache_entries = 20

# Disable bridge caching entirely
# no_cache = false


# ───────────────────────────────────────────────
# Nil Safety
# ───────────────────────────────────────────────
[rules.nil]
enabled = true

# Strict parameter mode (default: false).
# When false: all pointer parameters are assumed NonNil (fewer reports, may miss bugs).
# When true:  nilable parameters start as MaybeNil. GoGuard then applies entrypoint
#             models for known frameworks (net/http, gin, echo, fiber, grpc, testing)
#             to seed handler params back to NonNil — so framework handlers stay clean,
#             but internal functions that receive nil pointers are caught.
# strict_params = false

# User-provided nil models.
# Tell GoGuard whether specific functions return nil or not.
# Values: "nonnull" (never returns nil), "nilable" (can return nil)
# For multi-return functions, append #<index>: "os.Open#0" = the *File return.
[rules.nil.models]
# "mycompany/internal/db.GetDB" = "nonnull"
# "mycompany/internal/cache.Get#0" = "nilable"
# "context.WithCancel#0" = "nonnull"


# ───────────────────────────────────────────────
# Error Checking
# ───────────────────────────────────────────────
[rules.errcheck]
enabled = true
# Glob patterns for functions whose error returns can be safely ignored
ignore = ["fmt.Print*", "fmt.Fprint*"]


# ───────────────────────────────────────────────
# Concurrency Analysis
# ───────────────────────────────────────────────
[rules.concurrency]
enabled = true


# ───────────────────────────────────────────────
# Resource Lifecycle / Ownership
# ───────────────────────────────────────────────
[rules.ownership]
enabled = true


# ───────────────────────────────────────────────
# Exhaustiveness Checking
# ───────────────────────────────────────────────
[rules.exhaustive]
enabled = true


# ───────────────────────────────────────────────
# Taint Analysis (Security)
# ───────────────────────────────────────────────
[rules.taint]
enabled = true

无模型

Nil模型让你告诉GoGuard它无法分析的函数(外部包、C绑定等)的Nil返回行为。

[rules.nil.models]
# Single-return: function never returns nil
"mycompany/pkg.NewClient" = "nonnull"

# Multi-return: the *File at index 0 is never nil when err==nil
# (GoGuard already handles the Go error convention for stdlib,
#  but for your own code you may need to specify)
"mycompany/pkg.Open#0" = "nonnull"

# Explicitly mark a function as possibly returning nil
"mycompany/pkg.FindUser#0" = "nilable"

内置stdlib模型 (无需配置):

GoGuard附带了用于常见stdlib功能的模型,包括 context.Background(), context.TODO(), context.WithCancel(), context.WithTimeout(), context.WithValue(), bytes.NewBuffer(), bytes.NewBufferString(), strings.NewReader(), errors.New(), fmt.Errorf(), json.NewEncoder(), json.NewDecoder()以及更多。

内联注释

在下一行或同一行中抑制特定诊断:

//goguard:nonnull
user := GetUser(id) // GoGuard will treat this as non-nil

result := riskyCall() //goguard:nonnull

注: 注释通过从磁盘读取Go源文件来工作。文件路径必须可以从工作目录解析。


分析规则

无安全性

规则 严重性 描述
NIL001 关键 无指针引用。 在可能导致运行时恐慌的上下文中使用可能为nil的值(字段访问、方法调用、索引、切片)。
NIL002 关键 未检查的类型断言。 x.(string) 如果没有逗号,ok模式会在断言失败时恐慌。
NIL004 警告/严重 无地图访问权限。 从nil映射读取返回零值(警告)。写一个无映射恐慌(关键)。
NIL006 关键 无通道操作。 在nil通道上发送或接收会永远阻塞,导致goroutine死锁。

NIL001——无指针引用:

// ✗ BAD: user may be nil
user, _ := GetUser(id)
fmt.Println(user.Name) // ← NIL001: nil pointer dereference

// ✓ GOOD: nil check before use
user, err := GetUser(id)
if err != nil {
    return err
}
fmt.Println(user.Name) // safe

NIL002——未检查的类型断言:

// ✗ BAD: panics if x is not a string
s := x.(string) // ← NIL002

// ✓ GOOD: comma-ok pattern
s, ok := x.(string)
if !ok {
    return errors.New("not a string")
}

NIL004-无地图访问:

// ✗ BAD: writing to nil map panics
var m map[string]int
m["key"] = 42 // ← NIL004: panic

// ✓ GOOD: initialize the map
m := make(map[string]int)
m["key"] = 42

错误检查

规则 严重性 描述
ERR001 错误 未检查错误返回值。 函数返回错误,但该返回被丢弃。
ERR002 警告 分配给空白标识符时出错。 该错误被明确地丢弃 _.
// ✗ BAD: error completely ignored
os.Open("/tmp/file") // ← ERR001

// ✗ BAD: error explicitly discarded
f, _ := os.Open("/tmp/file") // ← ERR002

// ✓ GOOD: error properly checked
f, err := os.Open("/tmp/file")
if err != nil {
    return fmt.Errorf("opening file: %w", err)
}
defer f.Close()

忽略特定功能:

[rules.errcheck]
ignore = ["fmt.Print*", "fmt.Fprint*", "(*log.Logger).Print*"]

并发

数据竞争

规则 严重性 描述
赛马001 错误 goroutine中的共享变量访问。 封闭作用域中的变量在不同步的情况下在goroutine中访问。
赛马002 错误 Goroutine捕获循环变量。 goroutine通过引用捕获循环变量——所有goroutine都会看到最终值。
// ✗ BAD: data race on count
count := 0
go func() { count++ }() // ← RACE001

// ✓ GOOD: use atomic
var count int64
go func() { atomic.AddInt64(&count, 1) }()
// ✗ BAD: all goroutines see the last item
for _, v := range items {
    go func() { process(v) }() // ← RACE002
}

// ✓ GOOD: pass as argument
for _, v := range items {
    go func(v Item) { process(v) }(v)
}

Goroutine泄漏

规则 严重性 描述
泄漏001 警告 Goroutine可能永远不会终止。 没有可见的终止路径(没有上下文、没有通道关闭、没有返回)。
泄漏002 警告 频道已创建,但从未使用过。 一个频道被分配了 make() 但从未发送或接收。
// ✗ BAD: goroutine runs forever
go func() { // ← LEAK001
    for {
        doWork()
    }
}()

// ✓ GOOD: use context for cancellation
go func(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            return
        default:
            doWork()
        }
    }
}(ctx)

渠道问题

规则 严重性 描述
CHAN001 关键 在可能关闭的频道上发送。 运行时出现恐慌。
CHAN002 警告 选择无默认案例。 可能无限期封锁。

资源生命周期

规则 严重性 描述
OWN001 错误 资源已打开,但从未关闭。 文件、连接等泄漏。
下载002 关键 关闭后使用。 之后使用的资源 Close().
拥有003 关键 双重关闭。 资源关闭不止一次——可能会恐慌。
下载004 警告 资源关闭未推迟。 如果代码在打开和关闭之间出现恐慌,资源就会泄漏。
// ✗ BAD: f is never closed (OWN001)
f, err := os.Open(path)
if err != nil { return err }
data, _ := io.ReadAll(f)

// ✗ BAD: not using defer (OWN004)
f, err := os.Open(path)
if err != nil { return err }
data, _ := io.ReadAll(f)
f.Close() // if ReadAll panics, f leaks

// ✓ GOOD
f, err := os.Open(path)
if err != nil { return err }
defer f.Close()
data, _ := io.ReadAll(f)

精疲力竭

规则 严重性 描述
EXH001 警告 类型开关缺少接口实现器。 并非所有实现接口的类型都涵盖在内。
EXH002 警告 枚举开关缺少常数值。 并非所有枚举常量都会被处理。
EXH003 资讯 非穷举开关中缺少默认情况。
type Shape interface { Area() float64 }
type Circle struct { ... }
type Square struct { ... }
type Triangle struct { ... } // new type added

// ✗ BAD: Triangle not handled (EXH001)
switch s := shape.(type) {
case *Circle:  ...
case *Square:  ...
}

// ✓ GOOD: exhaustive or explicit default
switch s := shape.(type) {
case *Circle:   ...
case *Square:   ...
case *Triangle: ...
}

污点跟踪分析技术

规则 严重性 描述
污点001 关键 SQL注入。 受污染的数据流向SQL查询。
污点002 关键 指令注入。 受污染的数据流 exec.Command.
污点003 错误 路径遍历。 受污染的数据流向文件路径操作。
污点004 错误 跨站脚本(XSS)。 受污染的数据流到HTML输出。
// ✗ BAD: SQL injection (TAINT001)
id := r.URL.Query().Get("id")
db.Query("SELECT * FROM users WHERE id=" + id)

// ✓ GOOD: parameterized query
id := r.URL.Query().Get("id")
db.Query("SELECT * FROM users WHERE id=$1", id)
// ✗ BAD: command injection (TAINT002)
cmd := exec.Command("sh", "-c", userInput)

// ✓ GOOD: pass as separate arguments
cmd := exec.Command("grep", "-r", userInput, "/safe/dir")
// ✗ BAD: path traversal (TAINT003)
path := filepath.Join("/uploads", userInput)
os.ReadFile(path) // userInput = "../../etc/passwd"

// ✓ GOOD: validate the resolved path
path := filepath.Join("/uploads", filepath.Clean(userInput))
if !strings.HasPrefix(path, "/uploads/") {
    return errors.New("invalid path")
}

人工智能代理集成(MCP)

GoGuard公开了一个功能齐全的MCP(模型上下文协议)服务器。AI编码代理可以分析代码、获取解释、应用修复程序和运行查询——所有这些都是通过编程实现的。

克劳德代码

# Print the config snippet
goguard setup claude-code

增添 .mcp.json 在您的项目目录中(或 ~/.claude.json 全球):

{
  "mcpServers": {
    "goguard": {
      "command": "/usr/local/bin/goguard",
      "args": ["serve", "--mcp"]
    }
  }
}

光标

goguard setup cursor

增添 .cursor/mcp.json:

{
  "mcpServers": {
    "goguard": {
      "command": "/usr/local/bin/goguard",
      "args": ["serve", "--mcp"]
    }
  }
}

帆板运动

goguard setup windsurf

增添 ~/.codeium/windsurf/mcp_config.json:

{
  "mcpServers": {
    "goguard": {
      "command": "/usr/local/bin/goguard",
      "args": ["serve", "--mcp"]
    }
  }
}

法典

goguard setup codex

增添 ~/.codex/config.toml:

[mcp_servers.goguard]
command = "/usr/local/bin/goguard"
args = ["serve", "--mcp"]

泽德

goguard setup zed

增添 ~/.config/zed/settings.json:

{
  "context_servers": {
    "goguard": {
      "command": "/usr/local/bin/goguard",
      "args": ["serve", "--mcp"]
    }
  }
}

开源代码

goguard setup opencode

增添 opencode.json:

{
  "mcp": {
    "goguard": {
      "type": "local",
      "command": ["/usr/local/bin/goguard", "serve", "--mcp"],
      "enabled": true
    }
  }
}

VS代码(LSP)

goguard setup vscode

GoGuard还可以作为LSP服务器运行,用于标准编辑器集成:

{
  "goguard.path": "/usr/local/bin/goguard",
  "goguard.lsp.enabled": true,
  "goguard.lsp.args": ["serve", "--lsp"]
}

MCP工具参考

当作为MCP服务器连接时,GoGuard向AI代理公开以下工具:

工具 说明
goguard_analyze 对包运行分析。返回轻量级的“骨架”诊断(每个约50个令牌)以保留上下文窗口。
goguard_explain 获取特定诊断的完整详细信息(解释、代码上下文、爆炸半径)。
goguard_fix 生成并可选择应用修复程序。默认情况下自动验证。
goguard_verify 重新分析特定文件以确认修复工作
goguard_batch 按依赖关系顺序为多个诊断应用修复程序,最后验证一次。
goguard_rules 列出所有可用的分析规则及其说明。
goguard_query 根据分析结果运行GoGuard QL查询。
goguard_search 探索GoGuard的API、规则目录、IR模式和示例。代理人的“说明书”。
goguard_execute 根据分析数据(调用图、诊断、IR)运行JavaScript代码。代码模式。
goguard_autofix 带有进度通知的长时间运行的自动修复循环。
goguard_snapshot 保存/比较/差异分析快照(之前/之后)。
goguard_teach 教GoGuard函数的nil返回行为(通过启发的用户模型)。

骨架与完整输出:

goguard_analyze 默认情况下返回轻量级骨架(每个诊断约50个令牌),保留代理的上下文窗口:

{
  "id": "NIL001-handler.go:18",
  "rule": "NIL001",
  "severity": "critical",
  "title": "nil pointer dereference",
  "location": {"file": "handler.go", "line": 18, "column": 22},
  "fix_available": true
}

然后,代理人打电话来 goguard_explain 或 goguard_fix 仅用于它想要调查的诊断——避免上下文窗口膨胀。


开发包

对于不使用MCP的AI代理(例如基于Python的CodeAct代理),GoGuard提供了一个基于子流程的Python SDK。

安装

pip install goguard

用法

from goguard import GoGuard

g = GoGuard("/path/to/go/project")

# Analyze
result = g.analyze(severity="error")
for d in result.diagnostics:
    print(f"{d.rule} {d.location.file}:{d.location.line} — {d.title}")

# Get full details
detail = g.explain(result.diagnostics[0].id)

# Fix a diagnostic
fix = g.fix(result.diagnostics[0].id)
fix.apply()  # writes to disk

# Auto-fix all errors
report = g.auto_fix(severity="error", dry_run=True)
print(f"Would fix {report.fixes_applied} issues")

# Run JavaScript against analysis data (Code Mode)
result = g.execute("goguard.diagnostics().length")
print(result.output)

# Query with GoGuard QL
result = g.query('diagnostics where severity == "critical"')

API 参考

方法 返回 描述
analyze() AnalysisResult 运行静态分析
explain(id) dict 完整的诊断详细信息
fix(id) FixResult 生成并验证修复
batch(...) BatchResult 批量修复多个诊断
auto_fix(...) AutoFixResult 全自动修复编排器
snapshot(...) dict 保存/比较分析快照
rules(...) list[Rule] 列出可用规则
search(code) SearchResult 通过JavaScript探索API
execute(code) ExecuteResult 对分析数据运行JS
query(expr) QueryResult GoGuard QL或JavaScript查询

建筑

┌──────────────────────────────────────────────────┐
│  goguard-go-bridge  (Go, "Fat Bridge")           │
│                                                  │
│  go/packages.Load() → go/types → go/ssa          │
│      ↓                                           │
│  SSA + CFG + Call Graph + Interface Table         │
│      ↓                                           │
│  Serialize → FlatBuffers IR                       │
└───────────────────┬──────────────────────────────┘
                    │ stdio
                    ▼
┌──────────────────────────────────────────────────┐
│  goguard  (Rust, analysis core)                  │
│                                                  │
│  Decode IR → Salsa DB                             │
│      ↓                                           │
│  Analysis passes:                                │
│    • Nil lattice (forward dataflow, fixpoint)    │
│    • Errcheck (error variable tracking)          │
│    • Concurrency (goroutine + shared state)      │
│    • Ownership (resource state machine)          │
│    • Exhaustiveness (enum/interface coverage)    │
│    • Taint (source → sink propagation)           │
│      ↓                                           │
│  Diagnostics → Formatters (human/JSON/SARIF/MD)  │
│      ↓                                           │
│  Output: CLI / MCP server / LSP server / Pipe    │
└──────────────────────────────────────────────────┘

为什么是两种语言?

  • 走 处理Go最擅长的一切:解析Go代码、类型检查、SSA构造。我们使用Go官方 go/packages 和 go/ssa --这场战斗在数百万个Go项目上进行了测试。
  • 锈 处理Rust最擅长的一切:并行数据流分析、增量缓存(Salsa)、丰富的诊断(ariadne)、LSP/MCP服务器基础设施(tower LSP、rmcp)。

这 FlatBuffers电桥 高效地连接它们:Go构建类型化程序图,Rust对其进行分析。


贡献

我们欢迎社区捐款!请阅读我们的 贡献.md 了解详情。

文档

  • 配置指南 --满 goguard.toml 引用、内联注释、CI/CD示例
  • 分析规则 --所有22条具有严重性的规则,Go代码示例,修复模式
  • MCP集成 --Claude Code、Cursor、Windsurf、Codex、Zed、OpenCode、VS Code的设置;带参数的MCP工具

快速启动:

# Run Rust tests
cargo test --workspace

# Run Go bridge tests
cd goguard-go-bridge && go test ./...

# Check formatting and lints
cargo fmt --check
cargo clippy -- -D warnings

许可证

双重许可 麻省理工学院 或 Apache 2.0,由您选择。