# @gitkraken/compose-tools 中文文档

规范地址：https://npmcn.com/package/%40gitkraken/compose-tools/

版本：0\.10\.0
npm 元数据更新时间：2026-11-06T17:44:15.614Z
中文译文更新时间：2026-11-16T11:43:45.316Z
软件包许可：SEE LICENSE IN LICENSE

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gitkraken/compose-tools
原文对照：https://npmcn.com/package/%40gitkraken/compose-tools/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：476 kB，160 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>= 22
- 运行依赖：1 个
- 首次发布：2026-04-23T22:39:42.727Z
- 最新版本发布：2026-11-06T17:44:15.420Z
- 近 30 天下载量：4457（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：13（近 12 个月 13 个）

## 中文简介

AI有动力的组织 git 改变为干净,原子承诺和分支.

## 安装

```sh
npm install @gitkraken/compose-tools
```

也可以使用：`pnpm add @gitkraken/compose-tools`、`yarn add @gitkraken/compose-tools`、`bun add @gitkraken/compose-tools`

## README

# @gitkraken/ 编译工具

人工智能驱动的改变组织。 使用一个杂乱的工作目录或一个充满互放式承诺的分支,并将其重组为名副其实的分支上的干净原子承诺——准备进行代码审查.

使用来自MCP服务器或编码代理驱动的CLI的作曲? [会 议 开 幕](https://npmcn.com/package/%40gitkraken/compose-tools/SESSION-FLOWS.md) 记录四个支持的交互流,并记录如何将每个交互流连接起来.

## 它会做什么

`compose()` 收集您的更改, 通过一个 AI 管道发送 diffs 来理解代码更改的逻辑结构, 并生成干净的承诺 分组关注。 根据配置的不同,它可以:

-   重写工作目录的相接/ 未相接/ 未被跟踪到原子的改变
-   将分支的承诺历史重组为逻辑分类的承诺
-   在分行中间重写相接范围的承诺,保留范围前后的承诺
-   分拆多个新分支的变化(每个分支机构一个)
-   分化分枝入叠加分枝以进行增量审查

`split()` 是一个有焦点的变体——它需要现有的多承诺分枝,将其分入一叠更小的分枝.

每个更改寄存器的操作返回一个 `undoId` 可以传递给 `undoCompose()` 以手术方式扭转记录的突变.

## 安装

```bash
pnpm add @gitkraken/compose-tools @gitkraken/shared-tools
```

库是运行时间不可知的——它从不直接执行git或AI呼叫. 消费者为自己的git和AI后端提供适配器.

## 执行端口

### `ComposeGitPort`

图书馆需要的水面 两种提供方式:

**最小-生 `exec` 只有这个.** CLI -git消费者的罚款.

```typescript
import type { ComposeGitPort } from '@gitkraken/compose-tools';

const git: ComposeGitPort = {
    exec: async (args, options) => {
        const result = await yourGitBackend.run(args, {
            cwd: '/path/to/repo',
            env: options?.env,
            stdin: options?.stdin,
            signal: options?.signal,
        });
        if (result.exitCode !== 0) throw new Error(`git ${args[0]} failed: ${result.stderr}`);
        return result.stdout;
    },
};
```

图书馆建立它需要的每一个 git 操作( diff, 写作- tree, 承诺- tree, 更新- ref, 藏取, 用于每个 ref等) `exec`。 。 。 .

**混合 -- -- `exec` 加上目标明确的高层行动.** 当您的后端有更好的执行时, 提供高级操作 。 图书馆更喜欢高层次的操作 而不是路由 `exec`。 。 。 .

```typescript
const git: ComposeGitPort = {
    exec: async (args, options) => { /* ... */ },

    // Consumer has a signing-aware commit creator; library should prefer it.
    commitTree: async (tree, parents, message, opts) => {
        return yourSigningCommitCreator({ tree, parents, message, signing: opts?.signing });
    },
};
```

**Libgit2-tyle——只有高层行动,没有 `exec`。 。 。 .** Libgit2支持的消费者实施其流动所使用的具体行动. 如果流量需要操作 消费者没有提供 `exec` 也不可用, 库扔 `ComposeGitPortMissingOpError` 命名缺失的操作.

高级别行动的全部清单载于 `ComposeGitOps` 类型; 最常被覆盖的是 `commitTree`, (中文(简体) ), `readTree`, (中文(简体) ), `writeTree`, (中文(简体) ), `applyPatchToIndex`, (中文(简体) ), `applyPatchToWorkdir`, (中文(简体) ), `diffTree`, (中文(简体) ), `stageAll`。 。 。 . `OpOptions` 当前是空的 —— git 操作无法在这个库中被取消 ; 它们总是运行到完成,以避免离开回波半模 。 取消只流入 AI 循环(参见 [`cancellation`](https://npmcn.com/package/%40gitkraken/compose-tools/#readme-cancellation) 页:1.

`stashPop` 接受一个 `StashPopOptions` 参数 `withIndex?: boolean` (图 `git stash pop --index`); 仅限行动消费者应尊崇 `withIndex` 在应用步骤的安全藏被弹出后保留用户的预置中转.

### `AiModelPort`

无国籍的文本生成——呼叫者传递每个呼叫的全部信息历史.

```typescript
import type { AiModelPort } from '@gitkraken/shared-tools';

const model: AiModelPort = {
    generate: async (params) => {
        const response = await yourLLM.chat({
            system: params.system,
            messages: params.messages,
            maxTokens: params.maxTokens,
            temperature: params.temperature,
            signal: params.signal,
        });
        return {
            text: response.text,
            usage: { inputTokens: response.inputTokens, outputTokens: response.outputTokens },
        };
    },
};
```

适配器不跟踪会话——会话状态由库内管理.

## 入境点

图书馆暴露出主工作流程的三种口味外加分拆和取消.

### `compose(input)` - 一通电话糖

运行规划并一起应用. 当消费者不需要浮出水面来审查计划时的理想.

```typescript
import { compose } from '@gitkraken/compose-tools';

const result = await compose({
    git,
    model,
    source: { type: 'workdir' },
    onProgress: (event) => console.log(event.phase, event.message),
});

// result.plan                  — AI's analysis, grouping, ordering
// result.commitShas            — { 'commit-1': 'abc123…', … }
// result.undoId                — pass to undoCompose() to reverse
// result.phases                — timing/usage/callIds per phase
// result.usage                 — aggregated token counts
// result.feedbackTargetCallId  — stable ID of the "decision" model call (for thumbs up/down events)
```

### `composePlan(input)` + 键 `applyComposePlan(input)` 二阶段

返回计划而不改变repo, 让用户审查/编辑, 然后应用 。 这是形状交互审查 UI 的使用(计划-审查表面-用户编辑-应用).

```typescript
import { composePlan, applyComposePlan } from '@gitkraken/compose-tools';

const planResult = await composePlan({
    git,
    model,
    source: { type: 'workdir' },
});

// Show planResult.plan + planResult.source.hunks to the user. They may
// reassign hunks between commits, reorder, edit messages, etc.

const userEditedPlan = /* user-edited version of planResult.plan */;

const applied = await applyComposePlan({
    git,
    applyPlan: {
        plan: userEditedPlan,
        source: planResult.source,     // the library's collected hunks
        snapshot: planResult.snapshot, // safety hash — verified at apply time
    },
});
```

`applyComposePlan` 重新验证工作目录匹配 `snapshot` 在变异之前。 如果在计划与应用之间漂移,它就会抛出 `ComposeWorkflowError('SAFETY_CHECK_FAILED')`。 。 。 .

### `split(input)`

将已有的分支分割成一叠更小的分支.

```typescript
import { split } from '@gitkraken/compose-tools';

const result = await split({
    git,
    model,
    branchName: 'feature/large-pr',
    baseBranch: 'main',
    onBeforeApply: async (plan) => {
        for (const p of plan.partitioning.partitions) console.log(`${p.branchName}: ${p.title}`);
        return true;
    },
});
```

要求该分支至少承诺2项。 原分行由分行取而代之.

### `undoCompose(input)`

见 [撤销](https://npmcn.com/package/%40gitkraken/compose-tools/#readme-undo) 见下文.

## 来源

| 来源 | 说明 |
| --- | --- |
| `{ type: 'workdir', stagedOnly?, noUntracked? }` | 收集了分级的,未分级的,和未跟踪的更改. `stagedOnly: true` 对指数的限制; `noUntracked: true` 跳过未跟踪的文件. |
| `{ type: 'branch', name, mergeTarget? }` | 收藏 `mergeBase(mergeTarget, name) → name` 作为综合diff. `mergeTarget` 默认为 `'main'`。 。 。 . |
| `{ type: 'commit-range', branch, from, to, includeWorkdir? }` | 收集相接区域 `branch` 作为单一的综合diff。 两者 `from` 财务报告和审定财务报表 `to` 为: **包容性** 他们把第一次和最后一次承诺都命名为重写。 对于单人承诺重构: `from = sha, to = sha`. Per-hunk的作者身份通过线程相撞而与每个承诺的历史相悖。 过 `includeWorkdir: { includeStaged?, includeUnstaged?, includeUntracked? }` 将范围与用户的工作变化结合起来,以一个构成输入; **每层默认为 `true`**这样 `{ includeStaged: true }` 组成整个工作目录——用 `false` 来保持它。 设定时, `to` 必须等于当前分支提示,而头部必须不可分离。 层排除通过 `includeStaged`编号 :`includeUnstaged` 保留而不是组成:其内容在应用程序重新设置工作树之前被捕获,之后作为未分阶段的更改重新应用。 将未分级编组的阶段排除在外,在有分级修改存在时被拒绝——未分级修改被分到指数上,因此被分级的被分级层没有一致性可以重放. |

## 目标

| 目标 | 说明 |
| --- | --- |
| `{ type: 'head' }` | 向当前分支提交 。 默认 `workdir` 来源. |
| `{ type: 'branch', name, preserveOriginal? }` | 创建单一的命名分支 . `preserveOriginal: true` 保留源分支/WIP; `false` 清理它(删除源分支 ref,或从工作树上清除承诺的WIP). |
| `{ type: 'auto', preserveOriginal? }` | 每个关注创建一分支,可选择分解为堆积子分支. 一样 `preserveOriginal` 语义为 `branch`默认 `branch`编号 :`commit-range` 来源. |
| `{ type: 'rewrite-range', branch, rangeFrom, rangeTo }` | 在 `branch` 在现场。 新的链条堆起 `parent(rangeFrom)`其小费是严格意义上 `rangeTo` 让他们的下游链子重新在新尖端上产生 `commit-tree`页:1 `rangeTo` 本身随源分支移动. |

### 源/目标配对矩阵

| 来源 | 头 | 分支 | 自动 | 重写范围 |
| --- | --- | --- | :-: | :-: |
| `workdir` | ✓ | ✓ | ✓ | ✗ |
| `branch` | ✗ | ✓ | ✓ | ✓ |
| `commit-range` | ✗ | ✓ | ✓ | ✓ |

无效的配对 `ComposeWorkflowInputError` 时间 `composePlan` 时间.

## 选项

### `depth`

控制了人工智能呼叫的数量和每个原因的深度.

| 深度 | 阶段 | 最好还是 |
| --- | --- | --- |
| `'quick'` | 单身 `compose-group` 呼叫( 轻便提示) | 小变化,快速反馈 |
| `'balanced'` (默认) | `compose-group` + 可选 `order` | 多数使用案例 |
| `'deep'` | `analyze` + 键 `group` + 键 `order` + 可选 `partition` 每个分支 | 大型复杂变化 |

### `strategy`

控制AI在分组和分出时间上的侵略性. 所有设置默认为 `'balanced'`。 。 。 .

```typescript
strategy: {
    grouping: {
        branchSplitting: 'conservative' | 'balanced' | 'aggressive',
        commitGranularity: 'consolidated' | 'balanced' | 'granular',
    },
    partition: {
        splitting: 'conservative' | 'balanced' | 'aggressive',
    },
}
```

-   `branchSplitting` 如何积极地将变化分成不同的分支
-   `commitGranularity` 如何是受优待的个人的罪过
-   `partition.splitting` ——如何猛烈地将分枝分出成堆积的分枝

### `onBeforeApply`

在任何突变之前先检查一下计划 返回时 `false` 以中止 —— 工作流程返回计划而不应用它.

```typescript
onBeforeApply: async (plan) => {
    console.log(`${plan.branches.length} branches, ${plan.allOrderedCommits.length} commits`);
    return true;
}
```

相当于打电话 `composePlan` - 需要糖的时候有用 `compose` 需要机会介入.

### `onBeforeModelCall` 编号 : `onAfterModelCall`

被唤作可观察钩. 唯信息——图书馆不解读回文.

```typescript
onBeforeModelCall: ({ phase, attempt, maxAttempts, callId, isRepair }) => {
    // phase: 'analyze' | 'group' | 'order' | 'partition' | 'compose-group' | 'quick-compose'
    // callId: stable UUID — correlates with onAfterModelCall and with result.feedbackTargetCallId
    // isRepair: true for a targeted missing-hunks repair call, which shares the `attempt` of the
    // response it repairs
},

onAfterModelCall: ({ phase, attempt, callId, success, durationMs, usage, error, promptVersion, repairs, isRepair }) => {
    // Fires on both success and error, after the response validator runs (durationMs still
    // measures only the model call). `repairs` lists the fixes applied to an accepted response,
    // see ValidationRepair: `duplicate-hunks` is deterministic and free, `missing-hunks` costs one
    // extra model call. `isRepair` as above. An exception thrown here is swallowed.
},
```

消费者通过这些方法建立自己的每声电话遥测。 库内没有内置遥测.

### `onBeforePrompt`

钩子——在每只钩子之前运行 `model.generate`返回 `false` 终止工作流程 `ComposeWorkflowError('CANCELLED')`,但一次失修电话除外(`isRepair: true`: 将那一个跳过修理,倒回普通的再试,它也穿过了这个大门. 用于大即时确认,成本警告,Org政策检查.

```typescript
onBeforePrompt: async ({ phase, attempt, tokenEstimate, charCount, messageCount, isRepair }) => {
    if (tokenEstimate > 20_000) {
        return await showUserConfirmation(`Large prompt (${tokenEstimate} tokens). Continue?`);
    }
    return true;
}
```

### `hunkFilter`

运行在源收集后和AI管道之前. 消费者不想让AI看到 用于AIIgnore globs, org 策略过滤等.

```typescript
hunkFilter: async (hunks) => hunks.filter(h => !isAiIgnored(h.fileName)),
```

过滤器必须保存原始 `index` 值(仅删除条目,不重新编号)。 库重建安全快照,只反映被过滤的子集,所以 `verifyResultingDiff` 仍然有正确的期望. `result.hunksFilteredCount` 告诉消费者有多少人被丢弃.

**`hunkFilter` 和两个阶段 `composePlan` 编号 : `applyComposePlan` 流程 :** `applyComposePlan` 接受相同的建议 `hunkFilter` 字段. **您必须在应用时通过等效过滤器** ——文库在漂移检查前重新应用到新收集的快克上,否则被缓存(被过滤)的快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克快克 对于将计划串行跨过程(如CLI保存到JSON工作流程)的消费者,在计划的同时记录滤波光谱——排除文件名列表,AIIgnore glob set等,并重建应用上的功能. 过滤器功能本身是不可序列的;其输入一般是.

### `redactHunkContent`

预设返回 `true` 给那些被AI提示蒙上面具的猎人 相配的猎人保持他们的 `fileName`, (中文(简体) ), `hunkHeader`, (中文(简体) ), `index`,行数,并重命名元数据——只有正文被替换为占位符. 应用路径仍然使用收藏中的真实内容.

```typescript
const aiExcluded = new Set(['secrets.env', 'config/keys.json']);
redactHunkContent: (h) => aiExcluded.has(h.fileName) || aiExcluded.has(h.originalFileName ?? h.fileName),
```

用于 `.aiexclude` 编号 : `.aiignore` 编号 : `.cursorignore`\- 风格的特征,即AI应该将一个汉克组合成一个 仅用文件名,而从未看到它的内容。 与 `hunkFilter`:被过滤出hunks被完全从计划中丢出(并且永远不会最终成为任何承诺),而被修改出hunks留在计划中并正常应用——只有AI提示隐藏了内容.

应用路径不观察 `redactHunkContent` (应用时没有AI运行),所以不需要在 `applyComposePlan` 投入。 每项任务投入`analyze`, (中文(简体) ), `group`, (中文(简体) ), `compose-group`, (中文(简体) ), `quick-compose`在运行任务时直接接受。 这个 `order` 财务报告和审定财务报表 `partition` 任务从不嵌入 hunk 内容, 因此上游是一个不在那里 .

### `signing`

生产GPG的签名承诺。 通常来源于 `git config commit.gpgsign` + 键 `user.signingkey`。 。 。 .

```typescript
signing: {
    enabled: true,
    signingKey: 'ABCD1234',     // optional — passed to commit-tree as -S<key>
    gpgProgram: '/usr/bin/gpg', // optional — sets GIT_GPG_PROGRAM env
}
```

### `authorAttribution`

当一个承诺的hunks来自多个原始作者时,如何选择主要作者(重编/承诺范围来源). 当没有hunks携带作者信息(例如workdir source)时被忽略了.

| 数值 | 行为 |
| --- | --- |
| `'plurality'` (默认) | 拥有最多猎犬的作者获胜;所有其他不同的作者成为 `Co-authored-by:` 拖车 |
| `'first-hunk'` | 使用第一个 hunk 的作者; 其他不同的作者成为 `Co-authored-by:` 拖车 |
| 函数 | 完全习惯——检查猎犬并归还主要身份(或 `undefined` 使用承诺创造者的身份。 联合作者仍然来自 其余作者的结合 |

### `cancellation`

标准 `AbortSignal`,但范围故意狭窄:已转发 **只进入 AI 循环** ——每个 `model.generate` 呼叫和快门钩。 Git 操作( 收集、 快照验证、 应用、 取消显示的持久性) 运行到完成, 不论是否 `cancellation` 被中止; 飞行中取消 git op 冒着半毫米重播的风险, 所以设计上只有 AI 环是可以被取消的.

在 AI-loop 中止时,工作流程会翻译本地 `AbortError` 输入 `ComposeWorkflowError('CANCELLED')` 所以消费者只需检查工作流程域形状即可.

```typescript
const controller = new AbortController();
const result = await compose({ git, model, cancellation: controller.signal });
// later: controller.abort() — interrupts the next AI call; any git op already in
// flight finishes normally, then the workflow throws ComposeWorkflowError('CANCELLED').
```

`applyComposePlan`, (中文(简体) ), `undoCompose`, (中文(简体) ), `validateUndoCompose`,以及 `listUndoIds` 对 **没有** 接受 `cancellation` ——它们只配有,并跑到完成.

### `applyCommitIds`

只应用列出的计划传输ID. 不属于清单上的洪克人——加上任何从名单上掉下来的洪克人 `hunkFilter` ——在工作树上成为未承诺的剩余部分(被修改为有轨文件,被修改为新文件;当来源包括WIP时,索引状态不被保留).

```typescript
applyCommitIds: undefined                     // default — apply the entire plan
applyCommitIds: ['commit-1', 'commit-3']      // apply only these two commits, in plan order
```

列表被解释为一组:顺序无关紧要(计划本身的顺序被保留),但每个ID必须出现在其中 `plan.allOrderedCommits` - 不明的编号 `ComposeWorkflowInputError`。 。 。 .

何时 `applyCommitIds` (或 `hunkFilter`)被设定,目标重写已存在的承诺(`rewrite-range`,或 `branch`编号 :`auto` 与 `preserveOriginal: false`在一个 `branch`编号 :`commit-range` 源, 库中还需要 HEAD 在一个分支上( 非分解) , 并指向源的尖端( 分支尖端或范围) `to`) (中文(简体) ). 所剩的补丁被实现到重写分行上方,作为未分级的WIP. 其他来源/目标组合不设总部限制.

结果包括: `appliedCommitIds` (SHA实际写作)和 `unappliedHunkIndices` (hunk指数 留下的部分应用).

### `stashLabel`

当工作树脏了, 应用步骤创建的安全存储自定义消息 。 默认为 `compose backup`。 。 。 .

```typescript
stashLabel: `myapp-compose-${new Date().toISOString()}`
```

应用步骤总是通过工作目录状态隐藏 `git stash push --include-untracked` 变异前,然后弹出回来。 如果应用后的流行点击冲突,结果包括 `stashConflict: { stashLabel, conflictedFiles }` ——应用成功,所命名的藏品被保留,消费者表面回收UX(典型模式:扫描) `git stash list` 用于在下一个模式输入上设置一个稳定的前缀,以检测在程序死亡后被遗弃的藏匿物。 如果弹出未跳过或没有冲突,则结果包括 `stashNotRestored: { stashLabel, stashSha, reason }` ——藏入处被保留在原地(当它仍然存在时),所以它持有的WIP仍然可以收回.

### `maxTokens`

传送到每个 `model.generate` 呼叫在管道中。 默认为 `runAiLoop`16384 (英语).

将其倒置在结构化输出(如分析"每个猎人"的注解)会溢出JSON中段的非常大的diff上. 当发生这种情况时,验证器会用一个 `Response tail: …` 对模型输出的最后300个字符进行预览,因此很明显,反应是被截断而不是变形.

```typescript
const result = await compose({ git, model, maxTokens: 32_000 });
```

`maxTokens` 每项单独任务也都得到接受(`analyze`, (中文(简体) ), `group`, (中文(简体) ), `compose-group`, (中文(简体) ), `order`, (中文(简体) ), `partition`, (中文(简体) ), `quick-compose`)为同因.

### `session` (工作流程)

传出 a `ComposeSession` 从先前运行跳过已完成的AI阶段。 每项任务都检查自己的条目 `completedSteps`;如果存在,任务返回缓存结果而不是引用模型.

当用户TOS-在相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相.

```typescript
// First attempt — aborted between analyze and group
const first = await composePlan({ git, model, depth: 'deep', ... });

// Retry with the session — analyze is skipped, group/order/partition run fresh
const second = await composePlan({ git, model, depth: 'deep', session: first.session, ... });
```

一项恢复执行的任务无助于使用,也无助于调用数据——该阶段的遥测反映了最初的运行.

一个阶段 `callIds` 每个尝试有一个条目 加上每个缺失的猎犬修复, 所以可以比 `attempts`。 。 。 .

### `promptOverrides`

每任务即时覆盖消费者,提供自己的即时模板服务(服务器驱动的模板,供应商专用模板,org调用措辞).

```typescript
import type { ComposeTaskName, PromptOverride } from '@gitkraken/compose-tools';

promptOverrides: {
    group: {
        system: myCustomGroupSystemPrompt,      // replaces the built-in system prompt entirely
        userPrefix: 'Additional context:\n...', // prepended to the user prompt
        userSuffix: '\nReminder: prefer short subjects.', // appended
    },
    order: {
        userSuffix: myOrderingHints,
    },
}
```

任务名称 : `'analyze' | 'group' | 'compose-group' | 'order' | 'partition' | 'quick-compose'`。 。 。 .

库仍然运行同样的验证器 与模型响应,所以替换 `system` 迅速必须保存任务预期的输出契约( JSON 形状在内) `<output>` 标记,hunk索引限制等).

### `context`

可选的问题 / PR URL 浮出承诺消息中 .

```typescript
context: { issueUrl: 'https://github.com/org/repo/issues/42', pullRequestUrl: '...' }
```

### `instructions`

Free-form自然语言指导被传入AI.

```typescript
instructions: 'Separate the refactoring from the feature work. Put all test changes in their own commit.'
```

### `maxRetries`

当AI输出失败验证时, 每任务重试计数 。 默认 `3`。 。 。 .

### `conventions` 编号 : `conventionAuthor`

取代自动侦测的信息传输公约。 默认情况下, 最近的库样本会从 repo 中执行 。 设定 `conventionAuthor` 以到样本只从特定作者中执行(当当前用户的样式应驱动它时需要手动).

## 结果元数据

每个顶级切入点返回一个带有这些共同字段的对象:

| 外地 | 开始 | 含义 |
| --- | --- | --- |
| `plan` | 所有路径 | AI的完整分析 / 分组 / 命令 / 分支 |
| `snapshot` | 所有路径 | 藏品的安全散列指纹——携带以应用时间 |
| `source` | 所有路径 | `{ type, hunks, commitMessages?, branchName?, baseBranch? }` ——"人工智能"操作的猎人 |
| `session` | 所有路径 | 接通随后的复会电话 |
| `phases` | 所有路径 | `PhaseDetail[]` 与 `{ name, durationMs, attempts, usage?, modelId?, promptVersion?, callIds?, repairs? }` 每一阶段; `callIds` 可超过数 `attempts` 由修理电话 |
| `usage` | 所有路径 | 合计 `{ inputTokens, outputTokens, ... }` 所有AI的电话 |
| `diffStats` | 糖/计划 | `{ fileCount, hunkCount, addedLines, removedLines }` |
| `feedbackTargetCallId` | 当AI运行时 | callId of the last 验证的模型响应(在一次缺失-hunks修复后,它完成的响应,而不是修复呼叫)——在拇指上下回馈事件上盖上此章 |
| `hunksFilteredCount` | 何时 `hunkFilter` 运行 | 丢弃过滤器的次数 |
| `commitShas` | 应用路径 | `{ commitId: sha }` 为每个任务绘制地图 |
| `undoId` | 应用路径 | 传到 `undoCompose()` 倒转 |
| `partitions` 编号 : `partitionGroups` | 通过分区应用路径 | 应用分区信息 |
| `appliedCommitIds` | 应用路径 | 计划承诺 身份实际上写。 与 `plan.allOrderedCommits.map(c => c.id)` 完全应用; 当 `applyCommitIds` 已经设定. |
| `unappliedHunkIndices` | 应用路径 | 计划未涵盖的洪克指数 `appliedCommitIds`。空到可以完全应用. |
| `stashConflict` | 应用路径 | `{ stashLabel, conflictedFiles }` 设定应用后隐藏的弹出冲突。 应用本身成功;所命名的藏品被保存,供消费者回收UX. |
| `stashNotRestored` | 应用路径 | `{ stashLabel, stashSha, reason }` 当应用后隐藏的弹出被跳过或失败而不发生冲突时设置( q)`stash-ref-not-found`, (中文(简体) ), `untracked-restore-failed`,或 `pop-failed`) (中文(简体) ). 应用成功; 隐藏项被保留( 当它仍然存在时) , 因此它持有的 WIP 仍然可以恢复 . |

## 撤销

每个更改寄存器的操作返回一个 `undoId`。撤销系统是 **手术** ——它只倒置被记录的git突变,而不是恢复一个完整的寄存器快照.

### 撤消操作

```typescript
import { undoCompose } from '@gitkraken/compose-tools';

const undoResult = await undoCompose({
    git,
    undoId: result.undoId,
    onProgress: (step) => console.log(step),
});

// undoResult.deletedBranches   — branches removed (reversed a creation)
// undoResult.recreatedBranches — branches restored (reversed a deletion)
// undoResult.restoredBranches  — branches moved back to their pre-operation SHA
// undoResult.restoredHead      — whether HEAD was restored
// undoResult.restoredWorkdir   — whether the working directory was restored
// undoResult.warnings          — non-fatal issues encountered
```

### 安全检查

取消系统在执行前验证安全性 。 在下列情况下,法院拒绝继续审理:

-   **肮脏的工作目录** ——未承诺的变动有风险. 永远不能强迫.
-   **分会有新的承诺** ——行动所创建的分会自此被修改. 可强制使用 `force: true`。 。 。 .
-   **总部SHA无法联系** ——行动前总部承诺不再可以达到(如垃圾收集后).
-   **未找到的表态** ——撤销的ID与所储存的货单不符.

### 干线验证

```typescript
import { validateUndoCompose } from '@gitkraken/compose-tools';

const validation = await validateUndoCompose({ git, undoId: result.undoId });

if (!validation.safe) {
    for (const blocker of validation.blockers) console.error(`Blocked: ${blocker.type} — ${blocker.message}`);
}
for (const warning of validation.warnings) console.warn(`Warning: ${warning.type} — ${warning.message}`);
```

### 强制撤消

```typescript
await undoCompose({ git, undoId, force: true });
```

降级"部门有新的承诺" 阻塞器警告。 等值为 `force: { branchHasNewCommits: true }`。 。 。 .

对于更细的控制,通过对象表:

```typescript
await undoCompose({
    git,
    undoId,
    force: { branchHasNewCommits: true, dirtyWorkdir: true },
});
```

`dirtyWorkdir: true` 允许尽管未承诺的更改仍继续撤消 `reset --hard`因此,任何在工作树上 被打出。 仅当脏态是已知的操作被撤销的文物时使用(例如,在消费者选择回滚的应用成功后藏出失败的流行),而呼叫者已经确认与用户的工作损失. `head_sha_unreachable` 财务报告和审定财务报表 `manifest_not_found` 无论旗帜如何,永远无法强制.

### 列出所有已撤销的ID

```typescript
import { listUndoIds } from '@gitkraken/compose-tools';

const ids = await listUndoIds(git);
```

特征作为基特对象持续存在 `refs/undo/<id>` ——它们在分支操作中幸存下来,并在一个倒数执行时自动被清理.

## 个人任务职能

AI管道由可堆肥的任务功能所建. 单独调用它们进行自定义的工作流程.

| 函数 | 目的 |
| --- | --- |
| `analyze(input)` | 确定逻辑问题、依赖性,并按顺序进行约束 |
| `group(input)` | 组合成分行并进行 |
| `order(input)` | 确定每个分支内的最佳承诺顺序 |
| `partition(input)` | 将分支分解为堆叠的子分支 |
| `composeGroup(input)` | 组合分析 + 组合在单一AI呼叫中(由 `balanced` 编号 : `quick` 深处) |
| `quickCompose(input)` | 完全管道(分析+组+订单+可选分区) |

每个任务接受一个可选 `session` 保持 AI 对话上下文(或从缓存恢复) `completedSteps`),并返回输出中更新的会话。 每个任务也接受 `promptOverride`, (中文(简体) ), `maxTokens`, (中文(简体) ), `onBeforeModelCall`, (中文(简体) ), `onAfterModelCall`, (中文(简体) ), `onBeforePrompt`,以及 `cancellation` 与顶级入口相同的行为.

## 处理错误

| 错误 | 代码 |
| --- | --- |
| `GitError` | `NO_CHANGES`, (中文(简体) ), `BRANCH_NOT_FOUND`, (中文(简体) ), `OPERATION_FAILED`, (中文(简体) ), `SAFETY_CHECK_FAILED` |
| `ComposeWorkflowError` | `SAFETY_CHECK_FAILED` (工作目录在计划与适用之间更改), `INTERNAL`, (中文(简体) ), `CANCELLED` |
| `ComposeWorkflowInputError` | 无效的工作流程输入( 缺少) `model`,不兼容源/目标组合等) |
| `TaskInputError` | 无效的任务输入 |
| `AIError` | AI 输出在所有重试后都失败了 。 代码 : `VALIDATION_EXHAUSTED` |
| `ComposeGitPortMissingOpError` | 流动需要一个 `ComposeGitOps` 消费者不提供的方法 `exec` 也没有可用的。 有过 `.op` (缺失业务名称)和 `.hint`。 。 。 . |

```typescript
import { compose, GitError, ComposeWorkflowError, AIError } from '@gitkraken/compose-tools';

try {
    await compose({ git, model });
} catch (error) {
    if (error instanceof GitError && error.code === 'NO_CHANGES') {
        console.log('Nothing to compose');
    } else if (error instanceof AIError) {
        console.error('AI could not produce valid output after retries');
    } else if (error instanceof ComposeWorkflowError && error.code === 'CANCELLED') {
        console.log('Operation cancelled');
    } else if (error instanceof ComposeWorkflowError) {
        console.error(`Workflow failed: ${error.code} — ${error.message}`);
    }
}
```

## 进展跟踪

每个顶级入口都接受 `onProgress` 接受歧视的回调 `ComposeProgressEvent`。每个事件带有默认值 `message`,一个亲属 `weight` (用于进度栏数学)和相位特定有效载荷.

```typescript
import { compose, defaultPhaseMessages } from '@gitkraken/compose-tools';

const result = await compose({
    git,
    model,
    onProgress: (event) => {
        // event.phase:   'collecting' | 'compose-grouping' | 'analyzing' | 'grouping' |
        //                'ordering' | 'partitioning' | 'verifying' | 'applying'
        // event.message: default English label — use directly or map to localized copy
        // event.weight:  approximate relative duration for progress math
        // event.event:   ProgressEvent with { type, attempt, maxAttempts, errors? } (AI phases)
        // event.detail:  phase-specific string (non-AI phases)
        // event.branch:  only for 'partitioning', names the branch being subdivided
        // event.stats:   only for 'collecting'; set on the post-collection emit
        //                with { fileCount, hunkCount, addedLines, removedLines }
    },
});

// defaultPhaseMessages is exported for consumers who want to remap phase labels
// for localization without losing the weights.
```

完成后, `result.phases` 具备每个阶段的时间和用途:

```typescript
for (const phase of result.phases) {
    console.log(`${phase.name}: ${phase.durationMs}ms, ${phase.attempts} attempts`);
    if (phase.usage) console.log(`  ${phase.usage.inputTokens} in, ${phase.usage.outputTokens} out`);
    if (phase.callIds) console.log(`  call IDs: ${phase.callIds.join(', ')}`);
}

console.log(`Total tokens: ${result.usage.inputTokens} in, ${result.usage.outputTokens} out`);
```

## 捐款

此套件遵循了 monrepo 的标准工具 – 见 root [捐款额](https://npmcn.com/package/CONTRIBUTING.md)。本地命令:

```bash
pnpm --filter @gitkraken/compose-tools build
pnpm --filter @gitkraken/compose-tools typecheck
pnpm --filter @gitkraken/compose-tools test
```

## 常见问题

### @gitkraken/compose-tools 是什么？

AI有动力的组织 git 改变为干净,原子承诺和分支\.

### 如何安装 @gitkraken/compose-tools？

在项目目录运行 npm install @gitkraken/compose-tools，或使用 pnpm add / yarn add / bun add。

### @gitkraken/compose-tools 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @gitkraken/compose-tools 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @gitkraken/compose-tools 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>= 22。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @gitkraken/compose-tools 可以商用吗？

@gitkraken/compose-tools 使用 SEE LICENSE IN LICENSE 许可。许可条款写在包内的独立文件中，请阅读该文件确认可否商用。以上为概括，不构成法律意见，请以许可原文为准。

### @gitkraken/compose-tools 的下载量有多少？

根据 npm 官方下载统计，@gitkraken/compose-tools 在 2026/10/17 – 2026/11/15 这 30 天内被下载 4,457 次，日均约 149 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gitkraken/compose-tools 还在维护吗？

最新版本 0\.10\.0 发布于 2026/11/07（9 天前）；至今共发布 13 个版本，其中过去 12 个月发布了 13 个；首次发布于 2026/04/24。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

