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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ dsh plugin --profile web add github:gsnowdrift/dsh-java-ops
| 日志 | 实时日志分级着色、搜索过滤、放大、Esc 退出;每次启动/重启清空上一轮 |
| SQL | 三组权限(读/写/删)+ 可选高风险确认、结果 500 行 / 10s 超时、执行记录留 3 天 |
| 接口调用 | `java_ops_http_request` 发任意方法请求;面板「接口」页维护请求头预设(可按行启用/停用),调用自动带上;下部分列出时间、方法、URL、耗时、状态码,可点开看请求头、响应头与响应体 |
| Java 代码校验 | Checkstyle 改完 Java 文件自动跑并把结果附到编辑结果;PMD 本轮结束自动跑;SpotBugs 在 `git commit` 前做门禁(有发现就拦,可在面板关掉) |

| 凭据 | 数据库密码只进 DSH credentials,不落 JSON、不回显 |

## 工具
Expand Down
11 changes: 11 additions & 0 deletions docs/DETAIL.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,17 @@ PID 来源:`ctx.subprocess` 的句柄在 Windows 上不一定给出 pid,服
- 阈值语义:`warn` 保留 warning 及以上,`error` 只留 error,`all` 全留;Google / Sun 规则集默认输出 `[WARNING]`,选 `error` 会得到 0 条。
- PMD(约 60 MB)与 SpotBugs(约 30 MB)尚未在本机实测下载与执行。

## 自动触发(2026-11-21)

三个检查器各挂一个钩子,不需要手动跑:

- **Checkstyle — 改完马上跑**:`tools/post-execute` 钩子识别所有写文件工具(`write` / `edit` / `str_replace_editor` / `insert` 等)写入 `.java` 的动作,跑一次 Checkstyle 并把 findings 追加到该次编辑结果里(`str_replace_editor` 的 `view` 命令不算编辑)。
- **PMD — 每轮结束**:本轮改过 Java 文件时,`agent/turn-stopping` 触发一次 PMD;结果写进 `state.lint.lastRun`,面板与 `java_ops_lint {action:"run"}` 可查看。钩子 fire-and-forget,不会拖慢收尾。
- **SpotBugs — 提交前门禁**:`tools/pre-execute` 检测到 shell 工具执行 `git commit` 时跑一次 SpotBugs;有 findings 或检查器报错就 `deny` 这次提交(理由里列出前 8 条),修完或到面板关掉 SpotBugs 再重试。只有拼写得出的 `git commit` 会被拦(`script_path` 里藏的提交看不到);检查器未启用/未安装/无源码目录时不拦。

这是唯一一处「强制」:未通过不让提交。其余两个只报告不阻断。


## 尚未实现

SQL 执行已接通 MySQL(连接配置 + 读写删授权 + 无 WHERE 拦截 + 确认弹窗 + 记录落 `sqlLog`);接口调用已接通(请求头预设 + 调用记录)。仍待补:PostgreSQL 适配器、JDBC 桥(Oracle / SQLServer / 达梦 / 金仓)、Gradle 构建、DDL、表结构浏览、结果集分页与取消。见 `docs/decision-map.md`。
92 changes: 83 additions & 9 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1078,6 +1078,9 @@ const lintRuns = new Map()
// 后台跑就没有 HTTP 错误码可看,失败原因要自己带出去
const lintErrors = new Map()

// Java edits seen in the current turn, consumed by the turn-end PMD hook.
const javaEditSessions = new Set()

function lintRunOf(root) {
return lintRuns.get(root)
}
Expand Down Expand Up @@ -2736,26 +2739,56 @@ const PREFERENCE_TEXT = [
'- Call java_ops_http_request instead of curl or fetch when calling an API: the headers saved in the panel are applied automatically and the call is recorded.',
'- Use java_ops_service_* for starting, stopping and restarting Java services; never run `mvn spring-boot:run` or `java -jar` by hand for a registered service.',
'- Use java_ops_sql_query instead of a database CLI for MySQL checks; it enforces the panel permissions.',
'- The panel can enable three Java checkers (Checkstyle, PMD, SpotBugs). Checkstyle runs automatically after each Java edit and its findings arrive with the edit result; run java_ops_lint {action:"run"} for pmd when a feature is finished and spotbugs before committing. Skip a checker when the panel shows it is not enabled.',
'- The panel can enable three Java checkers (Checkstyle, PMD, SpotBugs). Checkstyle runs automatically after each Java edit and its findings arrive with the edit result; PMD runs automatically at the end of a turn in which Java was edited; SpotBugs gates `git commit` when it is enabled. If a commit is blocked, fix the reported findings or disable that checker in the panel, then retry.',
].join('\n')

// Every built-in tool that can change a file. Matching on the tool name alone is
// not enough: str_replace_editor also handles the read-only `view` command.
const JAVA_WRITE_TOOLS = new Set([
'write', 'edit', 'insert', 'undo_last_edit',
'str_replace_editor',
'ops_write_file', 'ops_edit_file',
])

function editedJavaPath(exec) {
if (!JAVA_WRITE_TOOLS.has(exec.name)) return ''
const args = exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {}
if (exec.name === 'str_replace_editor' && args.command === 'view') return ''
for (const key of ['file_path', 'path', 'filePath', 'target']) {
if (typeof args[key] === 'string' && args[key].toLowerCase().endsWith('.java')) return args[key]
}
return ''
}

// Only shell tools can run `git commit`; every other tool goes straight through the gate.
// ponytail: detects the command text only; a commit hidden behind script_path is not seen.
const SHELL_TOOLS = new Set(['bash', 'ops_bash', 'execute_terminal_command', 'run_code'])

function gitCommitCommand(exec) {
if (!SHELL_TOOLS.has(exec.name)) return false
const args = exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {}
for (const key of ['command', 'cmd', 'script', 'code']) {
if (typeof args[key] === 'string' && /\bgit\s+commit\b/.test(args[key])) return true
}
return false
}

export function apply(ctx) {
ctxRef = ctx

// A Java edit is followed by the enabled checkers. The findings are appended to the
// edit result itself, so the model reads them before it plans the next change.
// Checkstyle runs right after each Java edit so the model sees style findings before
// its next change. PMD and SpotBugs have their own triggers (turn end / commit gate).
ctx.effect(() =>
ctx.on('tools/post-execute', async (exec, result, next) => {
const decision = await next()
try {
if (decision.kind !== 'accept') return decision
if (exec.name !== 'write' && exec.name !== 'edit') return decision
const args = exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {}
const target = typeof args.file_path === 'string' ? args.file_path : typeof args.path === 'string' ? args.path : ''
if (!target.toLowerCase().endsWith('.java')) return decision
const target = editedJavaPath(exec)
if (!target) return decision
const root = rootOfPath(target)
if (!root) return decision
const run = await runLintChecks(ctx, root, {})
if (exec.agent?.id) javaEditSessions.add(exec.agent.id)
const run = await runLintChecks(ctx, root, { tool: 'checkstyle' })
const failed = Object.values(run.tools).some((info) => info.ok === false)
if (run.total === 0 && !failed) return decision
const report = lintReportText(root, run, 1)
Expand All @@ -2768,6 +2801,47 @@ export function apply(ctx) {
}),
)

// PMD at turn end = "feature finished". Fire and forget: turn-stopping is serial and
// awaited, so running ~6s of checks inline would stall every turn close. The report
// lands in state.lint.lastRun and the panel/tool can read it afterwards.
ctx.effect(() =>
ctx.on('agent/turn-stopping', function (payload) {
// Scope-filtered dispatch also exposes the agent as `this`; prefer the payload.
const agent = payload?.agent ?? this
const sessionId = agent?.id
if (!sessionId || !javaEditSessions.delete(sessionId)) return
const root = workspaceFromSession(ctx, sessionId)
if (!root) return
void runLintChecks(ctx, root, { tool: 'pmd' }).catch(() => {})
}),
)

// SpotBugs before commit is the one real gate: it inspects compiled classes, so it
// only blocks when the checker is enabled and actually reports findings/errors.
ctx.effect(() =>
ctx.on('tools/pre-execute', async (exec, next) => {
if (!gitCommitCommand(exec)) return next()
const root = workspaceFromSession(ctx, exec.agent?.id)
if (!root) return next()
try {
const run = await runLintChecks(ctx, root, { tool: 'spotbugs' })
if (run.total === 0 && !Object.values(run.tools).some((i) => i.ok === false)) return next()
const failed = Object.entries(run.tools)
.filter(([, info]) => info.ok === false)
.map(([tool, info]) => `${tool}: ${info.error}`)
const reason = [
`[java-ops] SpotBugs gate failed (${run.total} findings). Fix them or disable SpotBugs in the panel, then re-run git commit.`,
...run.findings.slice(0, 8).map((f) => `- ${f.file}:${f.line} ${f.message} [${f.rule ?? f.tool}]`),
...(failed.length ? [`Checker errors: ${failed.join('; ')}`] : []),
].join('\n')
return { kind: 'deny', reason }
} catch {
// checker not enabled / not installed / no source dirs: do not block the commit
return next()
}
}),
)


ctx.effect(() => {
const systemPrompt = typeof ctx.get === 'function' ? ctx.get('systemPrompt') : undefined
Expand Down Expand Up @@ -3014,7 +3088,7 @@ export function apply(ctx) {
{
name: 'java_ops_lint',
description:
'Java code checks (Checkstyle / PMD / SpotBugs) for this workspace. action=list shows what is installed and enabled, install downloads the tool package from its GitHub release, check asks for the newest version, save updates the per-workspace settings. action=run executes the enabled checkers: use checkstyle after editing Java files, pmd once a feature is done, spotbugs before committing.',
'Java code checks (Checkstyle / PMD / SpotBugs) for this workspace. action=list shows what is installed and enabled, install downloads the tool package from its GitHub release, check asks for the newest version, save updates the per-workspace settings. action=run runs the enabled checkers on demand; the panel also runs checkstyle after each Java edit, pmd at turn end, and spotbugs as a git commit gate.',
action: 'lint',
parameters: {
action: {
Expand Down