@gitkraken/conflict-tools 0.2.4-beta.17 → 0.2.4-beta.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +3 -0
- package/README.md +241 -54
- package/dist/ports/model.d.ts +7 -0
- package/dist/resolver/fix-loop.d.ts +10 -0
- package/dist/resolver/fix-loop.js +0 -0
- package/dist/resolver/model-budget.d.ts +20 -0
- package/dist/resolver/model-budget.js +1 -0
- package/dist/resolver/resolve-conflicts.js +0 -0
- package/dist/types/events.d.ts +8 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
|
|
|
9
9
|
|
|
10
10
|
### Added
|
|
11
11
|
|
|
12
|
+
- `ResolverConfig.maxModelCalls` — an optional global model-call budget for the whole operation. When set and the budget is spent, the opt-in fix phase stops attempting further fixes and leaves the remainder in the findings (so the verdict still reflects the true post-fix state), emitting a new `fix:budget-exhausted` progress event (`{ spent, limit }`). When unset, the fix phase is not budget-limited.
|
|
13
|
+
- `fix:failed` progress event (`{ filePath?, reason }`) — emitted when the opt-in fix phase throws a non-abort error, so a consumer can observe the graceful degradation rather than only seeing the checks flip to `errored`.
|
|
12
14
|
- Cross-file fixes in the fix phase (opt-in `ResolverConfig.fix`). After per-file convergence, a project-tier broken reference (an import/cross-file use whose target stopped resolving) is routed to the refine of its **use-site** file: the finding becomes a fix instruction, and the whole set is re-detected, up to `crossFileMaxIterations` rounds (default 2). Each cross-file fix is a single refine pass plus a mandatory per-file re-validation; the final whole-set detection also re-checks per-file for files a cross-file fix touched. **Limitation:** only use-site files that have an AI resolution are routed — a cross-file break landing on an auto-merged file (no resolution to carry the edit) is reported but not auto-fixed yet (needs a patches channel). The definition side, if broken, arrives as its own finding on its own file. Report-only (fix off) is unchanged.
|
|
13
15
|
- Per-file fix loop (opt-in via `ResolverConfig.fix`, default `false`). When enabled, an AI-resolved (`strategy: 'ai'`) text file that carries error-severity per-file findings is routed back through refine: the findings become fix instructions, the file is re-analyzed after each edit, and the loop repeats until the file is clean, a round makes no progress, or `fixLoopMaxIterations` (default 3) is reached. Whatever it cannot fix stays in the findings, so the verdict reflects the post-fix state. The no-markers invariant holds (a fix that reintroduces markers is discarded). New progress events `fix:started` / `fix:completed`. Report-only (fix off) is unchanged. Deferred for the opt-in fix path: rebase per-step-ref/transient discipline, parser/validator call caching, cross-file fixes, and a full finding-lifecycle model (double-counting is handled here by fingerprint dedup when folding findings into the report).
|
|
14
16
|
- `collectFileFindings` — a per-file detection unit (structural + intra-file broken references + consumer validator issues, all `tier: 'file'`) over already-loaded parent snapshots; the fix loop re-runs it after each edit. `detect()` remains the authoritative whole-set report.
|
|
@@ -30,6 +32,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
|
|
|
30
32
|
|
|
31
33
|
### Fixed
|
|
32
34
|
|
|
35
|
+
- The opt-in fix phase is now fault-isolated. A parser, validator, or model throw inside the fix phase no longer rejects the whole operation: the pre-fix resolutions are kept, both detection checks are reported as `errored` (so the verdict is `needs-review`, never a false `clean`), and the throw is surfaced via `fix:failed`. A user abort still propagates and cancels the operation.
|
|
33
36
|
- `OperationDigest.verdict` can now reach `clean` on a real repository. `detectionComplete` treated `partial-unsupported-language` as "did not run", so any operation whose scope contained a non-code file (package.json, README, lockfiles — always present in a real merge) forced `verdict: 'needs-review'` even with zero findings and full confidence. Since `--fix` gates auto-apply on `verdict === 'clean'`, this made auto-apply effectively unreachable. A check now counts as complete when it ran, including when some scope files were an unsupported language (they carry no references to break); only a check that could not run at all — no parser, no refs, an unreadable parent snapshot, or a thrown parser — leaves detection incomplete.
|
|
34
37
|
- A non-abort error in the refine pass no longer destroys the pre-refine resolution. Previously the refine `catch` rethrew, bubbling to `resolveOne` and degrading a good resolve-stage result into a take-side fallback (confidence 0) — the same class of failure as a throwing validator, one stage later. The pre-refine resolution is now kept, its confidence capped (the enhancement did not complete), and the error reported via `refine:failed`. A user abort still cancels (rethrown past the fallback).
|
|
35
38
|
- A throwing consumer validator no longer destroys a good resolution. The post-refine `validator.validate()` call is now guarded: a validator error is reported via a new `validation:failed` progress event and the resolution is kept intact, instead of bubbling to `resolveOne` and degrading a successful AI resolve into a whole-file take-side fallback (confidence 0) — the exact dropped-side loss the tool guards against. The validator stays advisory.
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @gitkraken/conflict-tools
|
|
2
2
|
|
|
3
|
-
AI-powered git conflict resolution. Parses conflict markers (including delete-modify conflicts), resolves them with an agentic AI loop that has access to git context (blame, grep, diff, log, show, file content), and
|
|
3
|
+
AI-powered git conflict resolution. Parses conflict markers (including delete-modify conflicts), resolves them with an agentic AI loop that has access to git context (blame, grep, diff, log, show, file content), refines the result with targeted intra-file edits, then runs deterministic reference-integrity detection over the whole touched set and produces an honest verdict. Results are written back to the working tree by the consumer.
|
|
4
4
|
|
|
5
5
|
## What it does
|
|
6
6
|
|
|
@@ -8,9 +8,9 @@ Three entry points, each serving a different consumer need:
|
|
|
8
8
|
|
|
9
9
|
- `extractConflict()` — parses conflict markers from a single file and returns a structured representation. Handles both text conflicts (with markers) and delete-modify conflicts (one side deleted, the other modified). No AI, no resolution.
|
|
10
10
|
|
|
11
|
-
- `resolveConflict()` — takes one `Conflict` and an optional `ResolutionContext`, runs the AI tool-use loop, returns a `Resolution` with resolved content, confidence, and metrics. The single-file workhorse.
|
|
11
|
+
- `resolveConflict()` — takes one `Conflict` and an optional `ResolutionContext`, runs the AI tool-use loop and per-file refine, returns a `Resolution` with resolved content, confidence, and metrics. The single-file workhorse.
|
|
12
12
|
|
|
13
|
-
- `resolveConflicts() + applyResolutions()` — batch-resolve every currently unmerged file in the working tree, then write and stage results. Supports pattern-based routing: skip files, apply take-ours/take-theirs, or route to AI per glob pattern. The library does NOT orchestrate `git rebase`/`merge`/`cherry-pick` — the consumer drives the operation lifecycle.
|
|
13
|
+
- `resolveConflicts() + applyResolutions()` — batch-resolve every currently unmerged file in the working tree, run set-level detection, then write and stage results. Supports pattern-based routing: skip files, apply take-ours/take-theirs, or route to AI per glob pattern. The library does NOT orchestrate `git rebase`/`merge`/`cherry-pick` — the consumer drives the operation lifecycle.
|
|
14
14
|
|
|
15
15
|
The library never calls `git` or an AI provider directly. Consumers supply adapters via ports.
|
|
16
16
|
|
|
@@ -20,6 +20,16 @@ The library never calls `git` or an AI provider directly. Consumers supply adapt
|
|
|
20
20
|
pnpm add @gitkraken/conflict-tools
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
+
## Pipeline
|
|
24
|
+
|
|
25
|
+
An operation runs in three stages. **Report-only is the default**, and the stage shape is identical whether or not the opt-in fix phase is enabled — the fix phase only adds edit attempts, it does not change the flow.
|
|
26
|
+
|
|
27
|
+
1. **Resolve** — the agentic AI tool-use loop replaces conflict markers, self-assessing a confidence per marker. The *only* blocking gate is residual conflict markers (checked built-in, language-agnostic): a candidate that still contains markers is rejected and retried. No other check gates this stage — parser, validator, and detection are all downstream and advisory.
|
|
28
|
+
2. **Refine** (per file) — when the resolver returns `followUpInstructions` (targeted edits it could not express as a whole-chunk decision), a second agentic loop applies them via the `edit_file_lines` tool. A refine that reintroduces markers is discarded; a refined file's confidence is capped at 0.9.
|
|
29
|
+
3. **Detection** (set level) — after every file is resolved, deterministic reference-integrity detection runs over the whole touched set: per-file structural checks (syntax errors, duplicate definitions, intra-file broken references) on the resolved *and* the auto-merged/incoming files, plus cross-file broken-reference checks. Report-only — it never mutates state or fails the operation. It produces the `DetectionReport` attached to `StepResult.detection`, which drives the verdict.
|
|
30
|
+
|
|
31
|
+
The opt-in **fix phase** (`config.fix: true`) sits between refine and the final detection report: it re-detects, routes the error-severity findings back through refine (per-file convergence, then cross-file routing), and only then emits the final report. What it cannot fix stays in the findings, so the verdict always reflects the post-fix state. See [Fix phase](#fix-phase-opt-in).
|
|
32
|
+
|
|
23
33
|
## Ports
|
|
24
34
|
|
|
25
35
|
### `ConflictGitPort`
|
|
@@ -42,6 +52,7 @@ High-level ops the library dispatches through:
|
|
|
42
52
|
| `showFile(ref, path, opts?)` | Read file content at a specific ref. Supports `startLine`/`endLine` |
|
|
43
53
|
| `unmergedEntries()` | List files git considers unresolved |
|
|
44
54
|
| `mergeBase(a, b)` | Common ancestor between two refs |
|
|
55
|
+
| `changedFiles(from, to)` | Paths changed between two refs (name-only). Used to discover the merge's incoming/auto-merged set for detection |
|
|
45
56
|
| `blame(path, opts?)` | Line-level authorship. Supports `startLine`/`endLine` (maps to `git blame -L`) |
|
|
46
57
|
| `grep(pattern, opts?)` | Content search across the tree. Supports `maxResults` |
|
|
47
58
|
| `diff(from, to, opts?)` | Unified diff between refs, optionally scoped to a path |
|
|
@@ -73,29 +84,64 @@ const model: ConflictModelPort = {
|
|
|
73
84
|
|
|
74
85
|
The shape of `tools`, `toolCalls`, and `toolResults` follows abstract types (`ToolDefinition`, `ToolCall`, `ToolResult`) so consumers can adapt any SDK. The library does not require streaming or any provider-specific feature.
|
|
75
86
|
|
|
76
|
-
### `
|
|
87
|
+
### `ParserPort` (optional — enables detection)
|
|
88
|
+
|
|
89
|
+
A **facts-in** port. Given a content overlay, it returns per-file parse facts — definitions, references (each with a `resolved` flag), optional bindings, and syntax errors. The *package* derives findings from those facts; the port itself never classifies anything as a conflict or a break.
|
|
90
|
+
|
|
91
|
+
```typescript
|
|
92
|
+
import type { ParserPort, SourceOverlay, ParsedFile } from '@gitkraken/conflict-tools';
|
|
93
|
+
|
|
94
|
+
const parser: ParserPort = {
|
|
95
|
+
async analyze(sources: SourceOverlay): Promise<ReadonlyMap<string, ParsedFile>> {
|
|
96
|
+
// tree-sitter (merge-mate) or a language server (GitLens/GKD), overlaying `sources`.
|
|
97
|
+
// Return one ParsedFile per input path.
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Three properties define the contract:
|
|
103
|
+
|
|
104
|
+
- **Content-in overlay, no FS access.** `analyze(sources)` sees exactly the `SourceOverlay` contents (a `ReadonlyMap<path, content>`) and never reads the filesystem itself. This is what lets the package hand it pre-merge parent snapshots *and* the post-merge result and diff the two. A tree-sitter backend sees only these files; a language server may resolve against its workspace with these contents overlaid on top.
|
|
105
|
+
- **Language-agnostic.** A file the backend cannot parse comes back with `language: 'unsupported'` and empty facts; the detector skips it (and reports `partial-unsupported-language`) rather than emitting false findings.
|
|
106
|
+
- **Precision-abstracting.** A tree-sitter backend and a language-server backend differ in how completely they resolve references — the port hides that difference behind the same shape.
|
|
107
|
+
|
|
108
|
+
`ParsedFile`:
|
|
109
|
+
|
|
110
|
+
| Field | Meaning |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `language` | Backend's language id; `'unsupported'` means "skip this file" |
|
|
113
|
+
| `definitions` | `SymbolDefinition[]` — top-level defs (`name`, `kind?`, 1-indexed `line`) |
|
|
114
|
+
| `references` | `SymbolReference[]` — `name`, `line`, `column?`, `resolved` (did it resolve within the overlay), `target?` |
|
|
115
|
+
| `bindings?` | Optional names bound at *any* scope (module-level and nested). Populating it lets detection catch a reference broken by removing a nested binding. A backend that only surfaces top-level `definitions` may omit it |
|
|
116
|
+
| `syntaxErrors` | `SyntaxIssue[]` — `line`, `message` |
|
|
117
|
+
|
|
118
|
+
Pass via `deps.parser`. When absent, detection is skipped and the report says so (`skipped-no-parser`) — never a silent clean.
|
|
77
119
|
|
|
78
|
-
|
|
120
|
+
### `Validator` (optional)
|
|
121
|
+
|
|
122
|
+
The consumer's validation port. Plug in any checks — syntax, real import resolution, types, lint, project rules. It runs **post-refine over an overlay** (one file for per-file validation, or the whole touched set for cross-file) and returns `ValidatorFinding[]`.
|
|
79
123
|
|
|
80
124
|
```typescript
|
|
81
|
-
import {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
const
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
return
|
|
92
|
-
? { valid: true }
|
|
93
|
-
: { valid: false, feedback: errors.join('\n') };
|
|
125
|
+
import type { Validator, ValidatorFinding } from '@gitkraken/conflict-tools';
|
|
126
|
+
|
|
127
|
+
const validator: Validator = {
|
|
128
|
+
async validate(sources) {
|
|
129
|
+
const findings: ValidatorFinding[] = [];
|
|
130
|
+
for (const [file, content] of sources) {
|
|
131
|
+
for (const err of await typecheck(file, content)) {
|
|
132
|
+
findings.push({ category: 'type-error', severity: 'error', file, line: err.line, message: err.message });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return findings;
|
|
94
136
|
},
|
|
95
137
|
};
|
|
96
138
|
```
|
|
97
139
|
|
|
98
|
-
|
|
140
|
+
**Advisory, never blocking.** Its findings fold into the operation's detection findings and the verdict; a validator finding never triggers a re-resolve, and a *throwing* validator is caught (reported via `validation:failed`) and the resolution is kept intact. `ValidatorFinding.category` is an open string (e.g. `'type-error'`, `'lint:no-console'`) so consumer categories flow through alongside the package's own `FindingCategory` values.
|
|
141
|
+
|
|
142
|
+
The one blocking gate — **residual conflict markers** — is *not* this port's job. It is checked built-in and language-agnostic inside the resolve loop. (This was the old `defaultVerifier`; it is now internal. `defaultVerifier`, `ResolutionVerifier`, and `VerificationResult` are no longer exported.)
|
|
143
|
+
|
|
144
|
+
Pass via `deps.validator` to `resolveConflict` or `resolveConflicts`.
|
|
99
145
|
|
|
100
146
|
## Entry points
|
|
101
147
|
|
|
@@ -130,19 +176,25 @@ import { resolveConflict } from '@gitkraken/conflict-tools';
|
|
|
130
176
|
const resolution = await resolveConflict(conflict, context, {
|
|
131
177
|
model,
|
|
132
178
|
git,
|
|
179
|
+
validator, // optional — advisory per-file checks
|
|
133
180
|
config: { maxSteps: 15, temperature: 0 },
|
|
134
181
|
onProgress: (event) => console.log(event),
|
|
135
182
|
});
|
|
136
183
|
|
|
137
184
|
// resolution.content — resolved file content (markers replaced)
|
|
138
185
|
// resolution.strategy — 'ai' | 'take-ours' | 'take-theirs' | 'deleted' | 'skipped'
|
|
139
|
-
// resolution.confidence — 0..1, from the AI's own self-assessment
|
|
186
|
+
// resolution.confidence — 0..1, from the AI's own self-assessment (capped at 0.9 if refined)
|
|
140
187
|
// resolution.description — one-or-two sentence rationale, from the AI
|
|
188
|
+
// resolution.findings? — advisory per-file findings from the validator port (post-refine)
|
|
141
189
|
// resolution.chunks? — per-marker decisions (for observability and validation)
|
|
190
|
+
// resolution.edits? — IntraFileEditOp[] applied during refine (absent if refine did not run)
|
|
142
191
|
// resolution.metrics? — { inputTokens, outputTokens, stepCount, toolCallCount, ... }
|
|
192
|
+
// resolution.rawSignals? — policy-free measurements for the consumer's own assessment
|
|
143
193
|
```
|
|
144
194
|
|
|
145
|
-
`
|
|
195
|
+
`resolveConflict` runs stages 1–2 (resolve + refine) for a single file. Set-level detection (stage 3) is only run by the batch entry point, since it needs the whole touched set; use `detect()` directly if you want detection for a single-file flow.
|
|
196
|
+
|
|
197
|
+
`ResolutionContext` carries optional hints the AI can use, plus the refs detection compares against:
|
|
146
198
|
|
|
147
199
|
```typescript
|
|
148
200
|
interface ResolutionContext {
|
|
@@ -150,21 +202,25 @@ interface ResolutionContext {
|
|
|
150
202
|
prDescription?: string;
|
|
151
203
|
previousResolutions?: Resolution[];
|
|
152
204
|
fileNeighbors?: string[];
|
|
205
|
+
/** Auto-merged files beyond the conflict set. Usually unset — detection discovers this from refs. */
|
|
206
|
+
touchedFiles?: string[];
|
|
153
207
|
refs?: { ours: string; theirs: string; base?: string };
|
|
208
|
+
/** Parent tips for detection's before/after comparison, when they differ from `refs`. */
|
|
209
|
+
detectionRefs?: { ours: string; theirs: string; base?: string };
|
|
154
210
|
threeWayDiff?: { oursDiff: string; theirsDiff: string };
|
|
211
|
+
/** Whole-file free-text guidance, rendered as a top-level <user-guidance> block. */
|
|
212
|
+
userGuidance?: string;
|
|
155
213
|
metadata?: Record<string, unknown>;
|
|
156
214
|
}
|
|
157
215
|
```
|
|
158
216
|
|
|
159
217
|
When `refs` is provided, the library computes `git diff base..ours -- file` and `git diff base..theirs -- file` automatically and includes both in the prompt. This typically lets the AI resolve without any tool calls. Consumers that already have these diffs cached can pass `threeWayDiff` directly to skip the computation.
|
|
160
218
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
After Phase 1 resolves conflict markers, the AI may return `followUpInstructions: string[]` on the resolution — a list of targeted edits it could not express as a whole-chunk decision (for example, re-applying a partial change from the incoming branch). When `followUpInstructions` is non-empty, `resolveConflict` automatically runs a second agentic loop (Phase 2) that applies those edits via the `edit_file_lines` tool.
|
|
219
|
+
`refs` drives the resolver's three-way diff; `detectionRefs` (falling back to `refs`) drives detection's before/after comparison. They differ in a rebase — where `refs` is the in-flight per-step state while detection needs the two stable pre-merge branch tips — and coincide in a plain merge, so `detectionRefs` is usually left unset.
|
|
164
220
|
|
|
165
|
-
|
|
221
|
+
#### Refine edits
|
|
166
222
|
|
|
167
|
-
`Resolution.edits?: IntraFileEditOp[]`
|
|
223
|
+
The refine pass (stage 2) applies edits the resolver could not express as whole-chunk decisions — for example, re-applying a partial change from the incoming branch. `ResolverConfig.refineMaxSteps` (default 5) bounds its model turns. `Resolution.edits?: IntraFileEditOp[]` lists the operations that survived (absent when refine did not run or all edits were discarded).
|
|
168
224
|
|
|
169
225
|
`IntraFileEditOp` is a discriminated union on `kind`:
|
|
170
226
|
|
|
@@ -176,12 +232,14 @@ After Phase 1 resolves conflict markers, the AI may return `followUpInstructions
|
|
|
176
232
|
### `resolveConflicts(deps, context?) + applyResolutions(resolutions, deps)` — batch
|
|
177
233
|
|
|
178
234
|
```typescript
|
|
179
|
-
import { resolveConflicts, applyResolutions } from '@gitkraken/conflict-tools';
|
|
235
|
+
import { resolveConflicts, applyResolutions, summarizeOperation } from '@gitkraken/conflict-tools';
|
|
180
236
|
|
|
181
237
|
const step = await resolveConflicts(
|
|
182
238
|
{
|
|
183
239
|
model,
|
|
184
240
|
git,
|
|
241
|
+
parser, // optional — supply to enable set-level detection (stage 3)
|
|
242
|
+
validator, // optional — advisory per-file checks
|
|
185
243
|
config: {
|
|
186
244
|
rules: [
|
|
187
245
|
{ match: ['*.lock', 'pnpm-lock.yaml'], strategy: 'take-theirs' },
|
|
@@ -200,8 +258,13 @@ const step = await resolveConflicts(
|
|
|
200
258
|
// step.resolutions[] — successful resolutions
|
|
201
259
|
// step.errors[] — { filePath, error } for files that failed (no fallback or AI exhausted)
|
|
202
260
|
// step.skipped?[] — { filePath, reason } for files that were excluded or had no markers
|
|
261
|
+
// step.detection? — DetectionReport over the whole touched set (present when a parser was supplied)
|
|
203
262
|
|
|
204
|
-
|
|
263
|
+
// Gate on the verdict, not on raw confidence — see below.
|
|
264
|
+
const { digest } = await summarizeOperation(step);
|
|
265
|
+
if (digest.verdict === 'clean') {
|
|
266
|
+
await applyResolutions(step.resolutions, { git });
|
|
267
|
+
}
|
|
205
268
|
// Resolutions are written via writeFile, checkoutFile, or removeFile and staged.
|
|
206
269
|
```
|
|
207
270
|
|
|
@@ -221,7 +284,117 @@ Available strategies for rules and `defaultStrategy`:
|
|
|
221
284
|
| `'deleted'` | Remove the file entirely |
|
|
222
285
|
| `'skip'` | Skip the file (no resolution produced) |
|
|
223
286
|
|
|
224
|
-
The function inspects the working tree once (via `unmergedEntries`), processes each conflict sequentially, and returns. It does not call `git rebase --continue` or any other operation command — that is the consumer's job.
|
|
287
|
+
The function inspects the working tree once (via `unmergedEntries`), processes each conflict sequentially, runs detection over the touched set, and returns. It does not call `git rebase --continue` or any other operation command — that is the consumer's job.
|
|
288
|
+
|
|
289
|
+
## Detection & verdict
|
|
290
|
+
|
|
291
|
+
### `detect(resolutions, context, deps)`
|
|
292
|
+
|
|
293
|
+
Deterministic, report-only post-resolution detection. It never mutates state or fails the operation. `resolveConflicts` calls it for you and attaches the result to `StepResult.detection`; call it directly for a single-file or custom flow.
|
|
294
|
+
|
|
295
|
+
```typescript
|
|
296
|
+
import { detect } from '@gitkraken/conflict-tools';
|
|
297
|
+
|
|
298
|
+
const report = await detect(step.resolutions, { refs }, { git, parser });
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
`DetectDeps` is `{ git; parser?; signal? }`. It flags:
|
|
302
|
+
|
|
303
|
+
- references that resolved in a pre-merge parent (ours/theirs) but no longer resolve in the merged result (`broken-reference`, with `provenance`),
|
|
304
|
+
- duplicate definitions and syntax errors in the resolved files (`duplicate-definition`, `syntax-error`),
|
|
305
|
+
- a whole-side take that discarded a substantial diff from the other side (`dropped-side`).
|
|
306
|
+
|
|
307
|
+
The scope includes the resolved files *and* the merge's auto-merged/incoming set (discovered from `refs` via `changedFiles`/`mergeBase`, or overridden by `context.touchedFiles`), so a dangling reference in a cleanly-merged file is still caught.
|
|
308
|
+
|
|
309
|
+
`DetectionReport`:
|
|
310
|
+
|
|
311
|
+
```typescript
|
|
312
|
+
interface DetectionReport {
|
|
313
|
+
findings: Finding[];
|
|
314
|
+
checks: { referenceIntegrity: CheckStatus; structural: CheckStatus };
|
|
315
|
+
/** Honest coverage — present only when the reference check ran. */
|
|
316
|
+
scope?: { analyzed: number; readable: number; truncated: boolean };
|
|
317
|
+
}
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
`Finding`:
|
|
321
|
+
|
|
322
|
+
| Field | Meaning |
|
|
323
|
+
|---|---|
|
|
324
|
+
| `category` | Open string. The package emits `FindingCategory`; a consumer validator may add its own |
|
|
325
|
+
| `severity` | `'error'` \| `'warning'` |
|
|
326
|
+
| `tier` | `'file'` (intra-file) or `'project'` (cross-file) — the fix phase routes each tier differently |
|
|
327
|
+
| `location` | `{ file; line; symbol? }` |
|
|
328
|
+
| `provenance?` | For `broken-reference`: the pre-merge side (`'ours'`/`'theirs'`) that still resolved it, and where |
|
|
329
|
+
| `message` | Human-readable description |
|
|
330
|
+
|
|
331
|
+
`FindingCategory` (the well-known values the package itself emits):
|
|
332
|
+
|
|
333
|
+
| Category | Meaning |
|
|
334
|
+
|---|---|
|
|
335
|
+
| `broken-reference` | A symbol resolved in a pre-merge parent but no longer resolves in the merged result |
|
|
336
|
+
| `duplicate-definition` | The same symbol is defined twice in a resolved file |
|
|
337
|
+
| `syntax-error` | The parser reported a syntax error in a resolved file |
|
|
338
|
+
| `dropped-side` | A whole-side take discarded a substantial diff from the discarded side |
|
|
339
|
+
|
|
340
|
+
`CheckStatus` tells "ran, clean" apart from "did not run" — so an empty `findings` array is never mistaken for a clean result:
|
|
341
|
+
|
|
342
|
+
| Status | Meaning |
|
|
343
|
+
|---|---|
|
|
344
|
+
| `ran` | The check ran to completion |
|
|
345
|
+
| `skipped-no-parser` | No `ParserPort` supplied |
|
|
346
|
+
| `skipped-no-refs` | No refs, so the before/after comparison was impossible (structural checks still ran) |
|
|
347
|
+
| `skipped-unreadable-source` | Refs were present but the parent snapshots came back empty (unreadable source) |
|
|
348
|
+
| `partial-unsupported-language` | The check ran, but some files in scope were an unsupported language |
|
|
349
|
+
| `errored` | The parser was present but threw |
|
|
350
|
+
|
|
351
|
+
### `summarizeOperation` / `buildOperationDigest`
|
|
352
|
+
|
|
353
|
+
`buildOperationDigest(result, reviewThreshold?)` is a pure, model-free rollup of a `StepResult` that folds in `detection`. `summarizeOperation(result, opts?)` returns `{ digest, prose?, usage? }` — always the digest, plus a prose narrative when `opts.model` is supplied.
|
|
354
|
+
|
|
355
|
+
```typescript
|
|
356
|
+
import { buildOperationDigest } from '@gitkraken/conflict-tools';
|
|
357
|
+
|
|
358
|
+
const digest = buildOperationDigest(step);
|
|
359
|
+
// digest.verdict — 'clean' | 'needs-review' | 'blocked'
|
|
360
|
+
// digest.detectionComplete — did every detection check run to completion
|
|
361
|
+
// digest.findingCount — total detection findings
|
|
362
|
+
// digest.needsReview — ReviewItem[] (findings first, then lowest confidence first)
|
|
363
|
+
// digest.minConfidence — lowest file confidence, or null
|
|
364
|
+
// digest.byStrategy — resolution count per strategy
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
`OperationVerdict`:
|
|
368
|
+
|
|
369
|
+
- `blocked` — at least one error-severity finding exists (the build is known-broken).
|
|
370
|
+
- `needs-review` — confidence is low, detection did not fully run, a resolution errored, or a warning finding exists.
|
|
371
|
+
- `clean` — none of the above.
|
|
372
|
+
|
|
373
|
+
**Gate auto-apply on the verdict, not on confidence.** A refined or fixed file has its confidence capped at 0.9 — so a "confidence must be 1.0" gate would reject exactly the files the tool improved. `verdict === 'clean'` is the honest signal. And an *absent* verdict must NOT be read as clean: if you never ran detection (no parser) or never summarized, `detectionComplete` is `false` and empty findings mean "we didn't look," not "nothing's wrong." Only `verdict === 'clean'` is clean.
|
|
374
|
+
|
|
375
|
+
A `ReviewItem` distinguishes a low-confidence flag from a finding: `reason: 'low-confidence' | 'finding'`, with `confidence?` (absent for a file flagged purely by a finding, e.g. an auto-merged file with no resolution of its own) and `findingCategories?` (present when `reason` is `'finding'`).
|
|
376
|
+
|
|
377
|
+
## Fix phase (opt-in)
|
|
378
|
+
|
|
379
|
+
By default the pipeline is **report-only**: detection findings land in `StepResult.detection` and the verdict, and the consumer decides what to do. Set `config.fix: true` to have the library attempt to fix error-severity findings before emitting the final report. The pipeline shape is identical in both modes — the fix phase only inserts edit attempts between refine and the final detection.
|
|
380
|
+
|
|
381
|
+
When enabled:
|
|
382
|
+
|
|
383
|
+
- **Per-file convergence** — an AI-resolved (`strategy: 'ai'`) text file carrying error-severity per-file findings is routed back through refine; the file is re-analyzed after each edit and the loop repeats until it is clean, a round makes no progress, or `fixLoopMaxIterations` (default 3) is reached.
|
|
384
|
+
- **Cross-file routing** — a `tier: 'project'` broken reference (an import/cross-file use whose target stopped resolving) is routed to the refine of its *use-site* file, and the whole set is re-detected, up to `crossFileMaxIterations` (default 2) rounds. Only use-site files that have an AI resolution are routed; a break landing on an auto-merged file (no resolution to carry the edit) is reported but not auto-fixed.
|
|
385
|
+
|
|
386
|
+
Whatever the fix phase cannot fix stays in the findings, so the verdict always reflects the post-fix state. The no-markers invariant holds throughout: a fix that reintroduces conflict markers is discarded rather than written.
|
|
387
|
+
|
|
388
|
+
`ResolverConfig` fix-phase fields:
|
|
389
|
+
|
|
390
|
+
| Field | Default | Effect |
|
|
391
|
+
|---|---|---|
|
|
392
|
+
| `fix` | `false` | Opt in to the fix phase. Off → report-only |
|
|
393
|
+
| `fixLoopMaxIterations` | `3` | Max per-file fix iterations (refine → re-detect the file) |
|
|
394
|
+
| `crossFileMaxIterations` | `2` | Max cross-file fix rounds (route project-level breaks → re-detect the set) |
|
|
395
|
+
| `maxModelCalls` | unset | Global model-call budget for the whole operation. When set and the budget is spent, the fix phase stops attempting further fixes and leaves the remainder in the findings, emitting `fix:budget-exhausted`. When unset, the fix phase is not budget-limited |
|
|
396
|
+
|
|
397
|
+
The fix phase is **fault-isolated**: a parser, validator, or model throw inside it does not reject the whole operation. The resolutions computed so far (possibly partially fixed, since the fix phase mutates them as it goes) are kept, both detection checks are reported as `errored`, and a `fix:failed` event is emitted (a user abort still propagates and cancels the operation).
|
|
225
398
|
|
|
226
399
|
## Consumer examples
|
|
227
400
|
|
|
@@ -241,8 +414,9 @@ if (conflict) {
|
|
|
241
414
|
### GitLens / GKD — batch "resolve all" (user-driven)
|
|
242
415
|
|
|
243
416
|
```typescript
|
|
244
|
-
const step = await resolveConflicts({ git, model, onProgress: webview.post });
|
|
245
|
-
const
|
|
417
|
+
const step = await resolveConflicts({ git, model, parser, onProgress: webview.post }, { refs });
|
|
418
|
+
const { digest } = await summarizeOperation(step);
|
|
419
|
+
const approved = await reviewDialog(step.resolutions, step.detection, digest.verdict);
|
|
246
420
|
await applyResolutions(approved, { git });
|
|
247
421
|
// User clicks "continue rebase" themselves.
|
|
248
422
|
```
|
|
@@ -256,13 +430,18 @@ for (const commit of commits) {
|
|
|
256
430
|
if (result.exitCode === 0) continue;
|
|
257
431
|
|
|
258
432
|
const step = await resolveConflicts({
|
|
259
|
-
git, model,
|
|
433
|
+
git, model, parser,
|
|
260
434
|
config: {
|
|
261
435
|
rules: [{ match: '*.lock', strategy: 'take-theirs' }],
|
|
262
436
|
fallbackStrategy: 'take-ours',
|
|
437
|
+
fix: true, // attempt to fix detected breaks before reporting
|
|
263
438
|
},
|
|
264
439
|
onProgress: emit,
|
|
265
|
-
});
|
|
440
|
+
}, { refs });
|
|
441
|
+
|
|
442
|
+
const { digest } = await summarizeOperation(step);
|
|
443
|
+
if (digest.verdict === 'blocked') { await escalateToHuman(step); break; }
|
|
444
|
+
|
|
266
445
|
await applyResolutions(step.resolutions, { git });
|
|
267
446
|
await git.exec(['rebase', '--continue']);
|
|
268
447
|
}
|
|
@@ -282,27 +461,35 @@ score(resolution, goldenFile);
|
|
|
282
461
|
|
|
283
462
|
| Event | When |
|
|
284
463
|
|---|---|
|
|
285
|
-
| `conflict:found` | A conflict file has been parsed |
|
|
464
|
+
| `conflict:found` | A conflict file has been parsed (`conflictType`, `markerCount`) |
|
|
286
465
|
| `conflict:excluded` | A file was skipped by a rule with `strategy: 'skip'` |
|
|
287
|
-
| `conflict:skipped` | A file had no conflict markers and no delete-modify reason |
|
|
288
|
-
| `resolution:applied` | A resolution was produced for a file |
|
|
289
|
-
| `resolution:fallback` | AI failed; fallback strategy applied |
|
|
290
|
-
| `resolution:failed` | AI failed and no fallback configured |
|
|
291
|
-
| `resolver:tool-call` | The AI invoked a tool
|
|
292
|
-
| `resolver:step-usage` | Token usage for one model call |
|
|
293
|
-
| `resolver:completed` | The resolver finished a single file |
|
|
294
|
-
| `resolver:response` |
|
|
295
|
-
| `resolver:tool-result` | A
|
|
296
|
-
| `refine:started` |
|
|
297
|
-
| `refine:skipped` |
|
|
298
|
-
| `refine:tool-call` |
|
|
299
|
-
| `refine:tool-result` |
|
|
300
|
-
| `refine:final-text` |
|
|
301
|
-
| `refine:completed` |
|
|
302
|
-
| `refine:failed` |
|
|
303
|
-
| `
|
|
304
|
-
|
|
305
|
-
|
|
466
|
+
| `conflict:skipped` | A file had no conflict markers and no delete-modify reason (`reason`, `entryReason?`) |
|
|
467
|
+
| `resolution:applied` | A resolution was produced for a file (`strategy`, `confidence?`, `description?`) |
|
|
468
|
+
| `resolution:fallback` | AI failed; fallback strategy applied (`error`, `cause?`) |
|
|
469
|
+
| `resolution:failed` | AI failed and no fallback configured (`error`) |
|
|
470
|
+
| `resolver:tool-call` | The AI invoked a tool during resolve (`tool`, `args`, `stepNumber`, `reason?`) |
|
|
471
|
+
| `resolver:step-usage` | Token usage for one resolve model call (`stepNumber`, `usage`) |
|
|
472
|
+
| `resolver:completed` | The resolver finished a single file (`stepCount`) |
|
|
473
|
+
| `resolver:response` | The resolve stage produced its final structured response (`chunks`, `confidence`, `description`, `strategy?`, `followUpInstructions?`) |
|
|
474
|
+
| `resolver:tool-result` | A resolve-stage tool returned content (`tool`, `stepNumber`, `content`) |
|
|
475
|
+
| `refine:started` | The refine pass has begun |
|
|
476
|
+
| `refine:skipped` | Refine was not run (`reason`, e.g. no follow-ups) |
|
|
477
|
+
| `refine:tool-call` | Refine model invoked `edit_file_lines` (`stepNumber`, `ops`) |
|
|
478
|
+
| `refine:tool-result` | A refine tool returned feedback (`stepNumber`, `appliedCount`, `isError`, `feedback`) |
|
|
479
|
+
| `refine:final-text` | Refine model emitted its final description (`text`) |
|
|
480
|
+
| `refine:completed` | Refine finished successfully (`appliedCount`) |
|
|
481
|
+
| `refine:failed` | Refine threw before completing (`reason`) |
|
|
482
|
+
| `refine:bailed` | Refine bailed early after consecutive apply errors, keeping edits that landed (`reason`) |
|
|
483
|
+
| `refine:discarded` | A refine/fix edit batch was rejected because it reintroduced conflict markers (`reason`) |
|
|
484
|
+
| `refine:touched-user-region` | Refine modified a user-resolved marker region (`markerIndexes`) |
|
|
485
|
+
| `fix:started` | The fix loop began fixing a file (`findingCount`) |
|
|
486
|
+
| `fix:completed` | The fix loop finished evaluating a file (`iterations`, `remaining`) — emitted even for a clean file (iterations 0, remaining 0) |
|
|
487
|
+
| `fix:failed` | The opt-in fix phase threw a non-abort error (`filePath?`, `reason`); the operation degrades gracefully — pre-fix resolutions are kept and both checks are reported as `errored` |
|
|
488
|
+
| `fix:budget-exhausted` | The global `maxModelCalls` budget was spent (`spent`, `limit`); the fix phase stopped and left the remainder in findings |
|
|
489
|
+
| `validation:failed` | The consumer validator threw; reported and swallowed, resolution kept (`reason`) |
|
|
490
|
+
| `verification:issues` | Advisory verification issues attached to a resolution (`issues`) |
|
|
491
|
+
|
|
492
|
+
Note: `refine:tool-result.appliedCount` reports edits applied to an in-progress buffer per turn. The final disposition is signaled by `refine:completed` / `refine:discarded` / `refine:failed` — only edits that survive residual-marker validation appear in `Resolution.edits`.
|
|
306
493
|
|
|
307
494
|
Operation-level events (rebase started, step completed, etc.) are the consumer's responsibility — the library has no opinion about the surrounding workflow.
|
|
308
495
|
|
|
@@ -328,7 +515,7 @@ try {
|
|
|
328
515
|
}
|
|
329
516
|
```
|
|
330
517
|
|
|
331
|
-
In the batch entry point, errors that have a configured fallback do not throw — they are downgraded to `resolution:fallback` events, and the resulting resolutions appear in `step.resolutions`. Errors without a fallback land in `step.errors` and the loop continues with the next file.
|
|
518
|
+
In the batch entry point, errors that have a configured fallback do not throw — they are downgraded to `resolution:fallback` events, and the resulting resolutions appear in `step.resolutions`. Errors without a fallback land in `step.errors` and the loop continues with the next file. The advisory stages (refine, validator, detection, fix phase) are fault-isolated — a non-abort throw there is reported and swallowed rather than destroying a good resolution. A user abort (`signal.aborted`) always propagates and cancels the operation.
|
|
332
519
|
|
|
333
520
|
## Semver policy
|
|
334
521
|
|
package/dist/ports/model.d.ts
CHANGED
|
@@ -44,6 +44,13 @@ interface ResolverConfig {
|
|
|
44
44
|
/** Max cross-file fix rounds (route project-level breaks to their use-site file → re-detect the whole
|
|
45
45
|
* set) when `fix` is on. Default 2. */
|
|
46
46
|
crossFileMaxIterations?: number;
|
|
47
|
+
/** Global cap on `model.generate` calls for the whole operation (resolve + refine + fix). Default
|
|
48
|
+
* `undefined` = unlimited. Primarily a backstop for the fix phase's multiplicative worst case
|
|
49
|
+
* (files × fixLoopMaxIterations + crossFileMaxIterations × routable calls). When spent, the fix
|
|
50
|
+
* phase stops attempting further fixes and leaves the remainder in findings — it never aborts the
|
|
51
|
+
* operation. The resolve loop is not gated by this (it is already bounded by `maxSteps`); its calls
|
|
52
|
+
* still count toward the cap. */
|
|
53
|
+
maxModelCalls?: number;
|
|
47
54
|
}
|
|
48
55
|
//#endregion
|
|
49
56
|
export { ConflictModelMessage, ConflictModelParams, ConflictModelPort, ConflictModelResult, ResolverConfig };
|
|
@@ -5,6 +5,7 @@ import { ConflictModelPort, ResolverConfig } from "../ports/model.js";
|
|
|
5
5
|
import { ParserPort } from "../ports/parser.js";
|
|
6
6
|
import { Validator } from "../ports/verify.js";
|
|
7
7
|
import { ConflictProgressEvent } from "../types/events.js";
|
|
8
|
+
import { ModelBudget } from "./model-budget.js";
|
|
8
9
|
|
|
9
10
|
//#region src/resolver/fix-loop.d.ts
|
|
10
11
|
interface FixLoopDeps {
|
|
@@ -14,6 +15,12 @@ interface FixLoopDeps {
|
|
|
14
15
|
config?: ResolverConfig;
|
|
15
16
|
onProgress?: (event: ConflictProgressEvent) => void;
|
|
16
17
|
signal?: AbortSignal;
|
|
18
|
+
/** Global model-call budget for the operation. When exhausted, the loop stops before any further
|
|
19
|
+
* model call and leaves the remaining findings unfixed. Absent = unlimited. */
|
|
20
|
+
budget?: ModelBudget;
|
|
21
|
+
/** Invoked the first time the budget stops work. The caller dedupes so the operation emits a single
|
|
22
|
+
* `fix:budget-exhausted`, whether the stop happens here or in the cross-file stage. */
|
|
23
|
+
onBudgetExhausted?: () => void;
|
|
17
24
|
}
|
|
18
25
|
/**
|
|
19
26
|
* Per-file convergence loop (opt-in `config.fix`). Re-detects the file's per-file findings, feeds the
|
|
@@ -34,6 +41,9 @@ interface FixPhaseDeps {
|
|
|
34
41
|
config?: ResolverConfig;
|
|
35
42
|
onProgress?: (event: ConflictProgressEvent) => void;
|
|
36
43
|
signal?: AbortSignal;
|
|
44
|
+
/** Global model-call budget for the operation. When exhausted, both fix stages stop before any
|
|
45
|
+
* further model call, leaving the remainder in the report. Absent = unlimited. */
|
|
46
|
+
budget?: ModelBudget;
|
|
37
47
|
}
|
|
38
48
|
/**
|
|
39
49
|
* The fix phase (opt-in). Stage 2: per-file convergence over each AI resolution ({@link runFixLoop}).
|
|
Binary file
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ConflictModelPort } from "../ports/model.js";
|
|
2
|
+
|
|
3
|
+
//#region src/resolver/model-budget.d.ts
|
|
4
|
+
/** A shared, per-operation counter of `model.generate` calls. Created once per {@link resolveConflicts}
|
|
5
|
+
* run; the wrapped model increments the counter but never blocks — enforcement is the caller's job via
|
|
6
|
+
* {@link ModelBudget.exhausted}, checked before fix-phase model calls only. Counting instead of throwing
|
|
7
|
+
* is deliberate: a throw inside the resolve loop would be caught by the fallback path and degrade a good
|
|
8
|
+
* resolution into a whole-side take — the exact data loss this package guards against. */
|
|
9
|
+
interface ModelBudget {
|
|
10
|
+
/** Wrap a model so every `generate` call increments this budget's shared counter, then delegates to
|
|
11
|
+
* the real model unchanged. Multiple wraps share one counter. */
|
|
12
|
+
wrap(model: ConflictModelPort): ConflictModelPort;
|
|
13
|
+
spent(): number;
|
|
14
|
+
/** Calls left before the cap. `Infinity` when the budget is unlimited (`max` undefined). */
|
|
15
|
+
remaining(): number;
|
|
16
|
+
exhausted(): boolean;
|
|
17
|
+
}
|
|
18
|
+
declare function createModelBudget(max?: number): ModelBudget;
|
|
19
|
+
//#endregion
|
|
20
|
+
export { ModelBudget, createModelBudget };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){let t=0,n=()=>e===void 0?1/0:e-t;return{wrap(e){return{generate:n=>(t++,e.generate(n))}},spent:()=>t,remaining:n,exhausted:()=>n()<=0}}export{e as createModelBudget};
|
|
Binary file
|
package/dist/types/events.d.ts
CHANGED
|
@@ -108,6 +108,14 @@ type ConflictProgressEvent = {
|
|
|
108
108
|
filePath: string;
|
|
109
109
|
iterations: number;
|
|
110
110
|
remaining: number;
|
|
111
|
+
} | {
|
|
112
|
+
type: 'fix:failed';
|
|
113
|
+
filePath?: string;
|
|
114
|
+
reason: string;
|
|
115
|
+
} | {
|
|
116
|
+
type: 'fix:budget-exhausted';
|
|
117
|
+
spent: number;
|
|
118
|
+
limit: number;
|
|
111
119
|
} | {
|
|
112
120
|
type: 'verification:issues';
|
|
113
121
|
filePath: string;
|