面向 Codex/Claude Code 等代理/脚本,提供稳定、可预期的调用方式。
建议调用流程(new-branch 模式)
diffk init --mode=new-branch --source <branch> --install-hooks --no-upstream --if-missing --dirty commit --snapshot-message "Warmup snapshot" --output json- 若当前分支与
--source不同且工作区脏,将返回DIRTY_WORKTREE(code 13),可改用--dirty=stash再试。
- 若当前分支与
- 对每次变更:
- 可选
diffk stage --stdin --check-only预检补丁;成功后再执行diffk stage --stdin与diffk commit --title "AI: ..."。
- 可选
- 完成:
diffk squash --message "Squash: AI session summary" --output json、diffk merge --to <branch> --strategy=squash --output json、diffk end --output json。- 若需自定义快照提交消息:
--snapshot-message或--snapshot-message-file仅在自动快照发生时生效(dirty=commit或stash pop后)
- 若需自定义快照提交消息:
JSON 契约与错误处理
- 顶层:
version|command|code|status|data|error;错误含error.message、error.hint、error.errorCode。 - 常见
errorCode:NO_SESSION(code 12)、SESSION_EXISTS(11)、DIRTY_WORKTREE(13)、LOCKED(14)、NOTHING_TO_COMMIT(15)、CONFLICT(10)、PATCH_APPLY_FAILED(41)、NOT_GIT(20)。
- 建议状态机:
- ensure session(
init --if-missing)→ 2) stage/commit 循环(处理 15/41)→ 3) squash → 4) merge(处理 10)→ 5) end。
- ensure session(
稳定性开关
--debug输出底层 git 调用(stderr),用于快速定位环境问题。--timeout <ms>控制命令超时;默认 30000。- 并发锁:命令内部获取
.git/diffkeeper/lock,并发时返回LOCKED(code 14),可线性重试;如遇崩溃残留,可人工删除锁文件(确认无活动 diffk 进程)。
gitignore 建议
- 建议仓库根目录提供
.gitignore,因为init --dirty commit的自动快照与常规commit都会遵循.gitignore。缺失时容易误提交构建产物与缓存。
实践示例(伪代码)
init := run(`diffk init --mode=new-branch --source main --if-missing --dirty commit --output json`)
if init.errorCode == 'DIRTY_WORKTREE' {
run(`diffk init --mode=new-branch --source main --if-missing --dirty stash --output json`)
}
if patch != '' {
chk := run(`diffk stage --stdin --check-only --output json`, stdin=patch)
if chk.code == 0 { run(`diffk stage --stdin --output json`, stdin=patch) }
}
run(`diffk commit --title "AI: update" --output json`)
run(`diffk squash --message "Squash: session" --output json`)
merge := run(`diffk merge --to main --strategy=squash --output json`)
if merge.errorCode == 'CONFLICT' { /* 提醒用户手动解决冲突 */ }
run(`diffk end --output json`)
注意
- 避免在操作中切换/修改同一仓库的其他工具并行运行(锁会阻止并发)。
- Windows 支持尽量保证;若使用 Git Bash/WSL 兼容性最佳。