@gitkraken/conflict-tools 0.2.4-beta.9 → 0.4.0

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +55 -7
  2. package/README.md +308 -59
  3. package/dist/errors/conflict.d.ts +1 -1
  4. package/dist/extraction/extract.d.ts +15 -1
  5. package/dist/extraction/extract.js +1 -1
  6. package/dist/extraction/parser.js +5 -5
  7. package/dist/git/port-dispatch.d.ts +14 -2
  8. package/dist/git/port-dispatch.js +1 -3
  9. package/dist/index.d.ts +6 -6
  10. package/dist/index.js +1 -1
  11. package/dist/ports/git.d.ts +20 -1
  12. package/dist/ports/parser.d.ts +27 -6
  13. package/dist/ports/validator.d.ts +29 -0
  14. package/dist/ports/validator.js +1 -0
  15. package/dist/reference-integrity/detect.d.ts +39 -4
  16. package/dist/reference-integrity/detect.js +2 -2
  17. package/dist/reference-integrity/snapshot.d.ts +28 -6
  18. package/dist/reference-integrity/snapshot.js +1 -1
  19. package/dist/resolution/detect-code-loss.d.ts +23 -0
  20. package/dist/resolution/detect-code-loss.js +1 -0
  21. package/dist/resolver/apply-resolutions.js +1 -1
  22. package/dist/resolver/deps.d.ts +1 -1
  23. package/dist/resolver/fix-loop.d.ts +67 -0
  24. package/dist/resolver/fix-loop.js +2 -0
  25. package/dist/resolver/mechanical.d.ts +25 -0
  26. package/dist/resolver/mechanical.js +1 -0
  27. package/dist/resolver/model-budget.d.ts +26 -0
  28. package/dist/resolver/model-budget.js +1 -0
  29. package/dist/resolver/parse-response.d.ts +9 -1
  30. package/dist/resolver/parse-response.js +1 -1
  31. package/dist/resolver/prompt.d.ts +13 -2
  32. package/dist/resolver/prompt.js +27 -7
  33. package/dist/resolver/refine-pass.d.ts +8 -0
  34. package/dist/resolver/refine-pass.js +1 -1
  35. package/dist/resolver/rename-choice.d.ts +15 -0
  36. package/dist/resolver/rename-choice.js +1 -0
  37. package/dist/resolver/rename-group.d.ts +22 -0
  38. package/dist/resolver/rename-group.js +1 -0
  39. package/dist/resolver/resolve-conflict.d.ts +7 -1
  40. package/dist/resolver/resolve-conflict.js +1 -1
  41. package/dist/resolver/resolve-conflicts.js +1 -1
  42. package/dist/resolver/summarize-operation.js +1 -1
  43. package/dist/resolver/validate.js +1 -1
  44. package/dist/types/events.d.ts +30 -3
  45. package/dist/types/findings.d.ts +25 -15
  46. package/dist/types/resolution.d.ts +17 -1
  47. package/dist/types/step.d.ts +47 -5
  48. package/dist/types/summary.d.ts +17 -10
  49. package/dist/validation/findings.d.ts +9 -0
  50. package/dist/validation/findings.js +1 -0
  51. package/dist/validation/markers.d.ts +11 -0
  52. package/dist/{ports/verify.js → validation/markers.js} +1 -1
  53. package/package.json +1 -1
  54. package/dist/ports/verify.d.ts +0 -30
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 writes results back to the working tree.
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`
@@ -30,10 +40,20 @@ A bag of optional high-level git ops, plus an optional raw `exec` fallback. Prov
30
40
  import type { ConflictGitPort } from '@gitkraken/conflict-tools';
31
41
 
32
42
  const git: ConflictGitPort = {
33
- exec: async (args, options) => simpleGit.raw(...args),
43
+ exec: async (args, options) => {
44
+ const result = await yourGitBackend.run(args, {
45
+ cwd: '/path/to/repo',
46
+ env: options?.env,
47
+ stdin: options?.stdin,
48
+ signal: options?.signal,
49
+ });
50
+ return result.stdout;
51
+ },
34
52
  };
35
53
  ```
36
54
 
55
+ Forward every option, not just `args`. `signal` is how the library cancels an in-flight operation, and `stdin` is how it feeds a path list to a `--stdin` command — an adapter that drops it leaves git waiting on a pipe that never closes.
56
+
37
57
  High-level ops the library dispatches through:
38
58
 
39
59
  | Op | Purpose |
@@ -42,6 +62,7 @@ High-level ops the library dispatches through:
42
62
  | `showFile(ref, path, opts?)` | Read file content at a specific ref. Supports `startLine`/`endLine` |
43
63
  | `unmergedEntries()` | List files git considers unresolved |
44
64
  | `mergeBase(a, b)` | Common ancestor between two refs |
65
+ | `changedFiles(from, to)` | Paths changed between two refs (name-only). Used to discover the merge's incoming/auto-merged set for detection |
45
66
  | `blame(path, opts?)` | Line-level authorship. Supports `startLine`/`endLine` (maps to `git blame -L`) |
46
67
  | `grep(pattern, opts?)` | Content search across the tree. Supports `maxResults` |
47
68
  | `diff(from, to, opts?)` | Unified diff between refs, optionally scoped to a path |
@@ -73,29 +94,68 @@ const model: ConflictModelPort = {
73
94
 
74
95
  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
96
 
76
- ### `ResolutionVerifier` (optional)
97
+ ### `ParserPort` (optional — enables detection)
77
98
 
78
- A pluggable post-resolution check. The library ships a `defaultVerifier` that scans the assembled content for residual conflict markers. During the AI loop, a failed verification triggers a retry with feedback — the model gets a chance to self-correct.
99
+ 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.
79
100
 
80
101
  ```typescript
81
- import { defaultVerifier } from '@gitkraken/conflict-tools';
82
- import type { ResolutionVerifier } from '@gitkraken/conflict-tools';
83
-
84
- // Use the built-in (checks for residual <<<<<<< / ======= / >>>>>>>)
85
- const verifier = defaultVerifier;
86
-
87
- // Or provide your own (e.g. run a linter, compile check)
88
- const custom: ResolutionVerifier = {
89
- verify: async (filePath, content) => {
90
- const errors = await lint(content);
91
- return errors.length === 0
92
- ? { valid: true }
93
- : { valid: false, feedback: errors.join('\n') };
102
+ import type { ParserPort, SourceOverlay, ParsedFile } from '@gitkraken/conflict-tools';
103
+
104
+ const parser: ParserPort = {
105
+ async analyze(sources: SourceOverlay): Promise<ReadonlyMap<string, ParsedFile>> {
106
+ // tree-sitter (merge-mate) or a language server (GitLens/GKD), overlaying `sources`.
107
+ // Return one ParsedFile per input path.
94
108
  },
95
109
  };
96
110
  ```
97
111
 
98
- Pass the verifier via `deps.verifier` to `resolveConflict` or `resolveConflicts`.
112
+ Four properties define the contract:
113
+
114
+ - **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.
115
+ - **Language-agnostic.** A file type the backend has no grammar for comes back `supported: false` with empty facts; the detector skips it (and reports `partial-unsupported-language`) rather than emitting false findings. A file it *does* handle but cannot parse is `supported: true` with the failure in `syntaxErrors` — that is a finding, not a coverage gap, and conflating the two would let a broken merge result read as clean.
116
+ - **Precision-declaring.** A tree-sitter backend and a language-server backend differ in how completely they resolve references, and the port asks them to say so via `capabilities`. A backend without `crossFileResolution` reports every import as unresolved on both parents *and* the result, so no cross-file break can ever surface — detection reports `partial-no-cross-file-resolution` instead of letting that empty result pass as a clean cross-file check.
117
+ - **Never called concurrently.** The package awaits each `analyze` before issuing the next, so a single-instance backend is never asked to hold two versions of the same path at once. Implementations need no internal locking.
118
+
119
+ `ParsedFile`:
120
+
121
+ | Field | Meaning |
122
+ |---|---|
123
+ | `supported` | `false` when the backend has no grammar for this file type at all — the detector skips it |
124
+ | `language` | Backend's language id; meaningful only when `supported` |
125
+ | `definitions` | `SymbolDefinition[]` — top-level defs (`name`, `kind?`, 1-indexed `line`) |
126
+ | `references` | `SymbolReference[]` — `name`, `line`, `column?`, `resolved` (did it resolve within the overlay), `target?` |
127
+ | `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 |
128
+ | `syntaxErrors` | `SyntaxIssue[]` — `line`, `message` |
129
+
130
+ Pass via `deps.parser`. When absent, detection is skipped and the report says so (`skipped-no-parser`) — never a silent clean.
131
+
132
+ ### `Validator` (optional)
133
+
134
+ The consumer's validation port. Plug in any checks — syntax, real import resolution, types, lint, project rules. It runs **post-refine over an overlay** and returns `ValidatorFinding[]`.
135
+
136
+ The overlay is currently **always a single file**: the package validates one file at a time, right after that file's refine. `SourceOverlay` is the parameter type so a whole-set call can be added later without a breaking change, but no such call site exists yet — do not write a validator that only works across files.
137
+
138
+ ```typescript
139
+ import type { Validator, ValidatorFinding } from '@gitkraken/conflict-tools';
140
+
141
+ const validator: Validator = {
142
+ async validate(sources) {
143
+ const findings: ValidatorFinding[] = [];
144
+ for (const [file, content] of sources) {
145
+ for (const err of await typecheck(file, content)) {
146
+ findings.push({ category: 'type-error', severity: 'error', file, line: err.line, message: err.message });
147
+ }
148
+ }
149
+ return findings;
150
+ },
151
+ };
152
+ ```
153
+
154
+ **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 never destroys the resolution — it is kept intact and the failure is reported. On the resolve/report path that report is a `validation:failed` event; inside the opt-in fix phase a validator throw folds into the phase's per-file isolation and surfaces as `fix:failed` (like any per-file throw there), so telemetry that must catch every validator failure should watch both. `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.
155
+
156
+ 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.)
157
+
158
+ Pass via `deps.validator` to `resolveConflict` or `resolveConflicts`.
99
159
 
100
160
  ## Entry points
101
161
 
@@ -130,19 +190,25 @@ import { resolveConflict } from '@gitkraken/conflict-tools';
130
190
  const resolution = await resolveConflict(conflict, context, {
131
191
  model,
132
192
  git,
193
+ validator, // optional — advisory per-file checks
133
194
  config: { maxSteps: 15, temperature: 0 },
134
195
  onProgress: (event) => console.log(event),
135
196
  });
136
197
 
137
198
  // resolution.content — resolved file content (markers replaced)
138
- // resolution.strategy — 'ai' | 'take-ours' | 'take-theirs' | 'deleted' | 'skipped'
139
- // resolution.confidence — 0..1, from the AI's own self-assessment
199
+ // resolution.strategy — 'ai' | 'take-ours' | 'take-theirs' | 'deleted' | 'skipped' | 'mechanical'
200
+ // resolution.confidence — 0..1, from the AI's own self-assessment (capped at 0.9 if refined)
140
201
  // resolution.description — one-or-two sentence rationale, from the AI
202
+ // resolution.findings? — advisory per-file findings from the validator port (post-refine)
141
203
  // resolution.chunks? — per-marker decisions (for observability and validation)
204
+ // resolution.edits? — IntraFileEditOp[] applied during refine (absent if refine did not run)
142
205
  // resolution.metrics? — { inputTokens, outputTokens, stepCount, toolCallCount, ... }
206
+ // resolution.rawSignals? — policy-free measurements for the consumer's own assessment
143
207
  ```
144
208
 
145
- `ResolutionContext` carries optional hints the AI can use:
209
+ `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.
210
+
211
+ `ResolutionContext` carries optional hints the AI can use, plus the refs detection compares against:
146
212
 
147
213
  ```typescript
148
214
  interface ResolutionContext {
@@ -150,21 +216,25 @@ interface ResolutionContext {
150
216
  prDescription?: string;
151
217
  previousResolutions?: Resolution[];
152
218
  fileNeighbors?: string[];
219
+ /** Auto-merged files beyond the conflict set. Usually unset — detection discovers this from refs. */
220
+ touchedFiles?: string[];
153
221
  refs?: { ours: string; theirs: string; base?: string };
222
+ /** Parent tips for detection's before/after comparison, when they differ from `refs`. */
223
+ detectionRefs?: { ours: string; theirs: string; base?: string };
154
224
  threeWayDiff?: { oursDiff: string; theirsDiff: string };
225
+ /** Whole-file free-text guidance, rendered as a top-level <user-guidance> block. */
226
+ userGuidance?: string;
155
227
  metadata?: Record<string, unknown>;
156
228
  }
157
229
  ```
158
230
 
159
231
  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
232
 
161
- ### Phase 2 refine pass
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.
233
+ `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
234
 
165
- `ResolverConfig.refineMaxSteps?: number` controls how many model turns Phase 2 is allowed. Defaults to 5.
235
+ #### Refine edits
166
236
 
167
- `Resolution.edits?: IntraFileEditOp[]` carries the list of edit operations that were successfully applied during Phase 2. Absent when Phase 2 did not run or all edits were discarded.
237
+ 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
238
 
169
239
  `IntraFileEditOp` is a discriminated union on `kind`:
170
240
 
@@ -176,12 +246,14 @@ After Phase 1 resolves conflict markers, the AI may return `followUpInstructions
176
246
  ### `resolveConflicts(deps, context?) + applyResolutions(resolutions, deps)` — batch
177
247
 
178
248
  ```typescript
179
- import { resolveConflicts, applyResolutions } from '@gitkraken/conflict-tools';
249
+ import { resolveConflicts, applyResolutions, summarizeOperation } from '@gitkraken/conflict-tools';
180
250
 
181
251
  const step = await resolveConflicts(
182
252
  {
183
253
  model,
184
254
  git,
255
+ parser, // optional — supply to enable set-level detection (stage 3)
256
+ validator, // optional — advisory per-file checks
185
257
  config: {
186
258
  rules: [
187
259
  { match: ['*.lock', 'pnpm-lock.yaml'], strategy: 'take-theirs' },
@@ -199,17 +271,58 @@ const step = await resolveConflicts(
199
271
 
200
272
  // step.resolutions[] — successful resolutions
201
273
  // step.errors[] — { filePath, error } for files that failed (no fallback or AI exhausted)
202
- // step.skipped?[] — { filePath, reason } for files that were excluded or had no markers
203
-
204
- await applyResolutions(step.resolutions, { git });
274
+ // step.skipped?[] — { filePath, reason, entryReason?, stages? } for files that were excluded,
275
+ // had no markers, or were left to a human (see the skip reasons below)
276
+ // step.detection — DetectionReport over the whole touched set; ALWAYS present. Read `checks`
277
+ // (or digest.detectionComplete) to tell whether detection actually ran —
278
+ // without a parser it is a present, empty report with `skipped-no-parser`.
279
+
280
+ // Gate on the verdict, not on raw confidence — see below.
281
+ const { digest } = await summarizeOperation(step);
282
+ if (digest.verdict === 'clean') {
283
+ await applyResolutions(step.resolutions, { git });
284
+ }
205
285
  // Resolutions are written via writeFile, checkoutFile, or removeFile and staged.
206
286
  ```
207
287
 
288
+ #### Skip reasons
289
+
290
+ `StepResult.skipped` holds the unmerged entries the resolver produced no resolution for. `reason` stays a plain `string` so a new value never breaks a consumer's compile; `entryReason` (git's own unmerged reason) and `stages` (which index stages hold the path, and at what mode) carry the git-level detail.
291
+
292
+ | `reason` | Meaning |
293
+ |---|---|
294
+ | `'excluded'` | A `rules` entry with `strategy: 'skip'` matched the path |
295
+ | `'no-markers'` | The file carries no conflict markers and is not a delete-modify, and nothing explains why |
296
+ | `'unmergeable'` | No markers, but both index stages hold content and git did not merge them — the content is binary, or a `merge` gitattribute told git not to merge the path; a side must be chosen |
297
+ | `'submodule'` | A gitlink stage: no content to read or write |
298
+ | `'rename-choice'` | A rename/rename set the model was asked about and could not settle — tried and failed, as opposed to never attempted |
299
+
300
+ #### Rename/rename and `retiredPaths`
301
+
302
+ When both sides rename the same file to different names, git leaves three unmerged paths — the base name at stage 1 alone, and each destination at its own side's stage — and nothing in the index says which name should survive. Both destinations carry the identical blob, so only the name is undecided. `resolveConflicts` asks the model to choose, then expresses the whole set as **one** resolution on the surviving path:
303
+
304
+ ```typescript
305
+ {
306
+ filePath: 'src/settings.ts', // the surviving name
307
+ strategy: 'ai', // 'mechanical' when neither side edited the content
308
+ retiredPaths: ['src/options.ts', 'src/config.ts'], // discarded destination, then the base path
309
+ // ...
310
+ }
311
+ ```
312
+
313
+ `applyResolutions` removes every `retiredPaths` entry with `removeFile` and never stages it, so the index is left with no unmerged entry for the set and the operation can be committed. `strategy` stays orthogonal to the name decision: `'ai'` when the model merged conflict markers into the survivor, `'mechanical'` when git had already settled the content and the file is staged as it lies (so a symlink's target is never rewritten).
314
+
315
+ A consumer that calls `applyResolutions` needs no change. A consumer with its own apply loop must honour `retiredPaths` — ignoring it leaves those paths unmerged, which git then refuses to commit.
316
+
317
+ The group is only formed from an unambiguous set: exactly one stage-1-only entry, exactly two lone-side entries at matching modes, neither a gitlink, both destinations holding identical content, and the effective strategy `'ai'` for all three paths. The content check is not a second reading of the stage signature — a stage-1-only entry is equally git's both-deleted signature, so the stages can only say a pairing is *possible*. A genuine rename/rename always passes it (git records one blob on stages 2 and 3, so both working-tree files match down to the marker labels), while an unrelated base beside two unrelated one-sided adds does not — and retiring a path is destructive. Caller instructions win: a rule with a non-`ai` strategy, or a non-`ai` `defaultStrategy`, on any of the three paths withholds the grouping and leaves the per-path handling in place. An explicit `{ strategy: 'ai' }` rule does **not** withhold it — asking for AI resolution is asking for the name decision too, and it matches how an `'ai'` rule already defers to the stage signature for every other path. When the model fails to name a survivor, no resolution is produced and all three paths land in `skipped` with `reason: 'rename-choice'`.
318
+
208
319
  `StepConfig` extends `ResolverConfig` with batch-only fields:
209
320
 
210
321
  - `rules` — array of `FileRule` objects. Each rule has a `match` (glob pattern or array of patterns) and a `strategy`. First matching rule wins. Patterns without `/` match on basename; patterns with `/` match on full path.
211
322
  - `defaultStrategy` — strategy for files not matching any rule. Defaults to `'ai'`.
212
- - `fallbackStrategy` — when AI fails for a file, fall back to `'take-ours'` or `'take-theirs'` instead of recording an error.
323
+ - `fix`, `fixLoopMaxIterations`, `crossFileMaxIterations`, `maxModelCalls` — the fix phase and its bounds. See [Fix phase](#fix-phase-opt-in). All four are batch-only because the fix phase is what enforces them.
324
+ - `fallbackStrategy` — when AI fails for a file, fall back to `'take-ours'` or `'take-theirs'` instead of recording an error. **Guarded against code loss, and the guard stops every text conflict.** The fallback is applied with `git checkout --ours/--theirs`, which replaces the whole file with one stage, so it discards the other side plus anything git auto-merged outside the conflict markers. On rebase "ours" is everything integrated so far, so a blind take-theirs can wipe it. The file is recorded as a `CODE_LOSS_RISK` error with a `resolution:failed` event instead of completing silently. The one case that still applies is a delete-modify conflict resolved toward the side that keeps content. Set `allowLossyFallback` to apply the fallback regardless.
325
+ - `allowLossyFallback` — opt back into the pre-guard behavior: apply `fallbackStrategy` wholesale even when it would discard integrated work. Off by default.
213
326
 
214
327
  Available strategies for rules and `defaultStrategy`:
215
328
 
@@ -221,7 +334,122 @@ Available strategies for rules and `defaultStrategy`:
221
334
  | `'deleted'` | Remove the file entirely |
222
335
  | `'skip'` | Skip the file (no resolution produced) |
223
336
 
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.
337
+ 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.
338
+
339
+ ## Detection & verdict
340
+
341
+ ### `detect(resolutions, context, deps)`
342
+
343
+ 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.
344
+
345
+ ```typescript
346
+ import { detect } from '@gitkraken/conflict-tools';
347
+
348
+ const report = await detect(step.resolutions, { refs }, { git, parser });
349
+ ```
350
+
351
+ `DetectDeps` is `{ git; parser?; signal?; excludePaths? }`. `excludePaths` (a `ReadonlySet<string>`) keeps paths out of scope — pass the files you skipped or failed to resolve, since those still carry conflict markers on disk and the parser would report the marker text as syntax errors. It flags:
352
+
353
+ - references that resolved in a pre-merge parent (ours/theirs) but no longer resolve in the merged result (`broken-reference`, with `provenance`),
354
+ - duplicate definitions and syntax errors across the whole analyzed scope — the resolved files *and* the auto-merged/incoming ones (`duplicate-definition`, `syntax-error`). Duplicates are diffed against the parents, so a legal same-name declaration that already existed (a TS overload, `interface`/`namespace` merging) is not reported; only a duplicate the merge introduced is,
355
+ - the resolver's emergency fallback taking one side wholesale and discarding a substantial diff (`dropped-side`).
356
+
357
+ 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.
358
+
359
+ `DetectionReport`:
360
+
361
+ ```typescript
362
+ interface DetectionReport {
363
+ findings: Finding[];
364
+ checks: { referenceIntegrity: CheckStatus; structural: CheckStatus };
365
+ /** Honest coverage — present only when the reference check ran. */
366
+ scope?: { inScope: number; readable: number; truncated: boolean; incomingDiscovered: boolean };
367
+ }
368
+ ```
369
+
370
+ `Finding`:
371
+
372
+ | Field | Meaning |
373
+ |---|---|
374
+ | `category` | Open string. The package emits `FindingCategory`; a consumer validator may add its own |
375
+ | `severity` | `'error'` \| `'warning'` |
376
+ | `tier` | `'file'` (intra-file) or `'project'` (cross-file) — the fix phase routes each tier differently |
377
+ | `location` | `{ file; line; symbol? }` |
378
+ | `provenance?` | For `broken-reference`: the pre-merge side (`'ours'`/`'theirs'`) that still resolved it, and where |
379
+ | `message` | Human-readable description |
380
+
381
+ `FindingCategory` (the well-known values the package itself emits):
382
+
383
+ | Category | Meaning |
384
+ |---|---|
385
+ | `broken-reference` | A symbol resolved in a pre-merge parent but no longer resolves in the merged result |
386
+ | `duplicate-definition` | The same symbol is defined twice in a resolved file (advisory `warning` — the detector cannot tell a genuine redefinition from legal overloads / declaration merging) |
387
+ | `syntax-error` | The parser reported a syntax error in a resolved file |
388
+ | `dropped-side` | The resolver's emergency fallback took one side wholesale, discarding a substantial diff (a deliberate rule/default take is not flagged) |
389
+
390
+ `CheckStatus` tells "ran, clean" apart from "did not run" — so an empty `findings` array is never mistaken for a clean result:
391
+
392
+ | Status | Meaning |
393
+ |---|---|
394
+ | `ran` | The check ran to completion |
395
+ | `skipped-no-parser` | No `ParserPort` supplied |
396
+ | `skipped-no-refs` | No refs, so the before/after comparison was impossible (structural checks still ran) |
397
+ | `skipped-unreadable-source` | Refs were present but the parent snapshots came back empty (unreadable source) |
398
+ | `partial-unsupported-language` | The check ran, but some files in scope were a file type the backend has no grammar for |
399
+ | `partial-no-cross-file-resolution` | The backend declared it does not resolve references across files, so cross-file breaks were structurally out of reach |
400
+ | `errored` | The parser was present but threw |
401
+
402
+ ### `summarizeOperation` / `buildOperationDigest`
403
+
404
+ `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.
405
+
406
+ ```typescript
407
+ import { buildOperationDigest } from '@gitkraken/conflict-tools';
408
+
409
+ const digest = buildOperationDigest(step);
410
+ // digest.verdict — 'clean' | 'needs-review' | 'blocked'
411
+ // digest.detectionComplete — did every detection check run to completion
412
+ // digest.findingCount — total detection findings
413
+ // digest.needsReview — ReviewItem[] (findings first, then lowest confidence first)
414
+ // digest.minConfidence — lowest file confidence, or null
415
+ // digest.byStrategy — resolution count per strategy
416
+ ```
417
+
418
+ `OperationVerdict`:
419
+
420
+ - `blocked` — at least one error-severity finding exists (the build is known-broken).
421
+ - `needs-review` — confidence is low, detection did not fully run, a resolution errored, or a warning finding exists.
422
+ - `clean` — none of the above.
423
+
424
+ **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.
425
+
426
+ A `ReviewItem` distinguishes a low-confidence flag from a finding: `reason: 'low-confidence' | 'finding' | 'unresolved'` (`'unresolved'` marks an unmerged entry the tool left untouched — any skip but a deliberate `'excluded'` one, an `'unmergeable'` entry say — which keeps the operation off `clean`), with `confidence?` (absent for a file flagged purely by a finding or as unresolved, e.g. an auto-merged file with no resolution of its own) and `findingCategories?` (present when `reason` is `'finding'`).
427
+
428
+ ## Fix phase (opt-in)
429
+
430
+ 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.
431
+
432
+ When enabled:
433
+
434
+ - **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.
435
+ - **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. The refine is seeded with the defining file's current definitions (names, kind, line — a token-cheap list, not its text) so it can spot a renamed or moved symbol behind the broken use, even though the refine tool cannot read other files. A file is routed when it has a write channel: an AI resolution, or an AI-unanimous whole-side take (relabelled to `ai` when the fix edit lands). A deliberate rule/default take and an emergency fallback take are not routed, and a break landing on an untouched auto-merged file (no resolution to carry the edit) is reported but not auto-fixed.
436
+
437
+ Whatever the fix phase cannot fix stays in the findings, so the verdict always reflects the post-fix state. Two invariants hold throughout: a fix that reintroduces conflict markers is discarded rather than written, and a round that leaves *more* error findings than it started with is discarded too — the better content is kept, so the phase can never ship a file worse than the one it was handed.
438
+
439
+ Failures are isolated per file: a parser, validator, or model throw on one file leaves that file at its pre-fix resolution, emits `fix:failed` with its `filePath`, and the phase continues with the rest. Only a user abort propagates.
440
+
441
+ Without `ResolutionContext.refs` (or `detectionRefs`) the per-file stage still runs on what needs no parent content — syntax errors and validator findings — while cross-file routing is skipped, since it is driven by the whole-set before/after report.
442
+
443
+ `StepConfig` fix-phase fields:
444
+
445
+ | Field | Default | Effect |
446
+ |---|---|---|
447
+ | `fix` | `false` | Opt in to the fix phase. Off → report-only |
448
+ | `fixLoopMaxIterations` | `3` | Max per-file fix iterations (refine → re-detect the file) |
449
+ | `crossFileMaxIterations` | `2` | Max cross-file fix rounds (route project-level breaks → re-detect the set) |
450
+ | `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 |
451
+
452
+ The fix phase is **fault-isolated** at two levels. A throw on one file (parser, validator, or model) leaves that file at its pre-fix resolution, emits `fix:failed` with its `filePath`, and the phase moves on — detection still runs over the set. A throw that escapes the whole phase does not reject the operation either: the resolutions computed so far (possibly partially fixed, since the phase mutates them as it goes) are kept, both detection checks are reported as `errored`, and `fix:failed` is emitted without a `filePath`. A user abort always propagates and cancels the operation.
225
453
 
226
454
  ## Consumer examples
227
455
 
@@ -241,8 +469,9 @@ if (conflict) {
241
469
  ### GitLens / GKD — batch "resolve all" (user-driven)
242
470
 
243
471
  ```typescript
244
- const step = await resolveConflicts({ git, model, onProgress: webview.post });
245
- const approved = await reviewDialog(step.resolutions);
472
+ const step = await resolveConflicts({ git, model, parser, onProgress: webview.post }, { refs });
473
+ const { digest } = await summarizeOperation(step);
474
+ const approved = await reviewDialog(step.resolutions, step.detection, digest.verdict);
246
475
  await applyResolutions(approved, { git });
247
476
  // User clicks "continue rebase" themselves.
248
477
  ```
@@ -256,13 +485,18 @@ for (const commit of commits) {
256
485
  if (result.exitCode === 0) continue;
257
486
 
258
487
  const step = await resolveConflicts({
259
- git, model,
488
+ git, model, parser,
260
489
  config: {
261
490
  rules: [{ match: '*.lock', strategy: 'take-theirs' }],
262
491
  fallbackStrategy: 'take-ours',
492
+ fix: true, // attempt to fix detected breaks before reporting
263
493
  },
264
494
  onProgress: emit,
265
- });
495
+ }, { refs });
496
+
497
+ const { digest } = await summarizeOperation(step);
498
+ if (digest.verdict === 'blocked') { await escalateToHuman(step); break; }
499
+
266
500
  await applyResolutions(step.resolutions, { git });
267
501
  await git.exec(['rebase', '--continue']);
268
502
  }
@@ -282,27 +516,34 @@ score(resolution, goldenFile);
282
516
 
283
517
  | Event | When |
284
518
  |---|---|
285
- | `conflict:found` | A conflict file has been parsed |
519
+ | `conflict:found` | A conflict file has been parsed (`conflictType`, `markerCount`) |
286
520
  | `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. Includes `reason` (why the AI called it) |
292
- | `resolver:step-usage` | Token usage for one model call |
293
- | `resolver:completed` | The resolver finished a single file |
294
- | `resolver:response` | Phase 1 produced its final response |
295
- | `resolver:tool-result` | A Phase 1 tool returned content |
296
- | `refine:started` | Phase 2 has begun |
297
- | `refine:skipped` | Phase 2 was not run (no follow-ups) |
298
- | `refine:tool-call` | Phase 2 model invoked `edit_file_lines` |
299
- | `refine:tool-result` | Phase 2 tool returned feedback |
300
- | `refine:final-text` | Phase 2 model emitted final description |
301
- | `refine:completed` | Phase 2 finished successfully (includes `appliedCount`) |
302
- | `refine:failed` | Phase 2 threw before completing |
303
- | `edit:discarded` | An edit batch was rejected (introduced markers) |
304
-
305
- Note: `refine:tool-result.appliedCount` reports edits applied to an in-progress buffer per turn. The final disposition is signaled by `refine:completed` / `edit:discarded` / `refine:failed` — only edits that survive residual-marker validation appear in `Resolution.edits`.
521
+ | `conflict:skipped` | The resolver produced no resolution for an unmerged path — see [Skip reasons](#skip-reasons) (`reason`, `entryReason?`) |
522
+ | `resolution:applied` | A resolution was produced for a file (`strategy`, `confidence?`, `description?`) |
523
+ | `resolution:fallback` | AI failed; fallback strategy applied (`error`, `cause?`) |
524
+ | `resolution:failed` | AI failed and no fallback configured (`error`) |
525
+ | `resolver:tool-call` | The AI invoked a tool during resolve (`tool`, `args`, `stepNumber`, `reason?`) |
526
+ | `resolver:step-usage` | Token usage for one resolve model call (`stepNumber`, `usage`) |
527
+ | `resolver:completed` | The resolver finished a single file (`stepCount`) |
528
+ | `resolver:response` | The resolve stage produced its final structured response (`chunks`, `confidence`, `description`, `strategy?`, `followUpInstructions?`) |
529
+ | `resolver:tool-result` | A resolve-stage tool returned content (`tool`, `stepNumber`, `content`) |
530
+ | `refine:started` | The refine pass has begun |
531
+ | `refine:skipped` | Refine was not run (`reason`, e.g. no follow-ups) |
532
+ | `refine:tool-call` | Refine model invoked `edit_file_lines` (`stepNumber`, `ops`) |
533
+ | `refine:tool-result` | A refine tool returned feedback (`stepNumber`, `appliedCount`, `isError`, `feedback`) |
534
+ | `refine:final-text` | Refine model emitted its final description (`text`) |
535
+ | `refine:completed` | Refine finished successfully (`appliedCount`) |
536
+ | `refine:failed` | Refine threw before completing (`reason`) |
537
+ | `refine:bailed` | Refine bailed early after consecutive apply errors, keeping edits that landed (`reason`) |
538
+ | `refine:discarded` | A refine/fix edit batch was rejected — it reintroduced conflict markers, or (in the fix phase) it introduced an error the file did not have (`reason` says which) |
539
+ | `refine:touched-user-region` | Refine modified a user-resolved marker region (`markerIndexes`) |
540
+ | `fix:started` | The fix loop began fixing a file (`findingCount`) |
541
+ | `fix:completed` | The fix loop finished evaluating a file (`iterations`, `remainingFindings`) — emitted even for a clean file (iterations 0, remainingFindings 0). `iterations: 0` means "evaluated, spent no model call" |
542
+ | `fix:failed` | A non-abort error in the opt-in fix phase (`filePath?`, `reason`). With `filePath`: that one file threw and was left at its pre-fix resolution while the phase carried on — detection still runs. Without `filePath`: the whole phase threw before it could report, so both checks are forced to `errored` |
543
+ | `fix:budget-exhausted` | The global `maxModelCalls` budget was spent (`spent`, `limit`); the fix phase stopped and left the remainder in findings |
544
+ | `validation:failed` | The consumer validator threw; reported and swallowed, resolution kept (`reason`) |
545
+
546
+ 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
547
 
307
548
  Operation-level events (rebase started, step completed, etc.) are the consumer's responsibility — the library has no opinion about the surrounding workflow.
308
549
 
@@ -311,6 +552,7 @@ Operation-level events (rebase started, step completed, etc.) are the consumer's
311
552
  | Error | Codes | When |
312
553
  |---|---|---|
313
554
  | `ConflictError` | `PARSE_FAILED` | Conflict extraction failed |
555
+ | `ConflictError` | `CODE_LOSS_RISK` | A wholesale `fallbackStrategy` would have discarded integrated work; the fallback was not applied |
314
556
  | `AIError` | `VALIDATION_EXHAUSTED`, `INCOMPLETE_RESOLUTION` | Model could not produce a valid resolution after retries |
315
557
  | `ConflictGitPortMissingOpError` | — | A required git op is missing and no `exec` fallback was provided |
316
558
 
@@ -328,7 +570,14 @@ try {
328
570
  }
329
571
  ```
330
572
 
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.
573
+ In the batch entry point, errors do not throw; the loop continues with the next file. Where they land depends on the fallback:
574
+
575
+ - No `fallbackStrategy`: the error goes to `step.errors`.
576
+ - `fallbackStrategy` set, text conflict: the code-loss guard stops it, so a `CODE_LOSS_RISK` error goes to `step.errors` with a `resolution:failed` event. This is the common path, not the exception.
577
+ - `fallbackStrategy` set, delete-modify resolved toward the side that keeps content: downgraded to a `resolution:fallback` event, with the resolution in `step.resolutions`.
578
+ - `allowLossyFallback: true`: the guard is off, so every fallback takes the `resolution:fallback` path.
579
+
580
+ 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
581
 
333
582
  ## Semver policy
334
583
 
@@ -1,5 +1,5 @@
1
1
  //#region src/errors/conflict.d.ts
2
- type ConflictErrorCode = 'PARSE_FAILED';
2
+ type ConflictErrorCode = 'PARSE_FAILED' | 'CODE_LOSS_RISK';
3
3
  declare class ConflictError extends Error {
4
4
  readonly code: ConflictErrorCode;
5
5
  constructor(code: ConflictErrorCode, message: string, options?: {
@@ -2,9 +2,23 @@ import { ConflictGitPort } from "../ports/git.js";
2
2
  import { Conflict } from "../types/conflict.js";
3
3
 
4
4
  //#region src/extraction/extract.d.ts
5
+ interface ExtractedConflict {
6
+ conflict: Conflict | null;
7
+ /** The working-tree content the marker scan read, so a caller facing a `null` conflict can decide
8
+ * binary-ness without reading the file a second time. Empty only on the `deleted-by-them`/`deleted-by-us`
9
+ * branch when the file is already gone from the deleted side; on the marker-scan branch (the only one
10
+ * that can return a `null` conflict) a failed read throws instead of producing empty content. */
11
+ rawContent: string;
12
+ }
13
+ /** Sibling of {@link extractConflict} that also surfaces the content it read, so a caller handling a
14
+ * `null` conflict (no markers) can classify it further — e.g. binary-ness — without a second read. */
15
+ declare function extractConflictWithSource(filePath: string, deps: {
16
+ git: ConflictGitPort;
17
+ signal?: AbortSignal;
18
+ }, reason?: string): Promise<ExtractedConflict>;
5
19
  declare function extractConflict(filePath: string, deps: {
6
20
  git: ConflictGitPort;
7
21
  signal?: AbortSignal;
8
22
  }, reason?: string): Promise<Conflict | null>;
9
23
  //#endregion
10
- export { extractConflict };
24
+ export { ExtractedConflict, extractConflict, extractConflictWithSource };
@@ -1 +1 @@
1
- import{readFile as e}from"../git/port-dispatch.js";import{parseConflictMarkers as t}from"./parser.js";async function n(n,r,i){if(i===`deleted-by-them`||i===`deleted-by-us`){let t=i===`deleted-by-them`?`theirs`:`ours`,a=``;try{a=await e(r.git,n,{signal:r.signal})}catch{}return{filePath:n,markers:[],type:`delete-modify`,rawContent:a,deletedBy:t}}let a=await e(r.git,n,{signal:r.signal}),o=t(a);return o.length===0?null:{filePath:n,markers:o,type:`text`,rawContent:a}}export{n as extractConflict};
1
+ import{readFile as e}from"../git/port-dispatch.js";import{parseConflictMarkers as t}from"./parser.js";async function n(n,r,i){if(i===`deleted-by-them`||i===`deleted-by-us`){let t=i===`deleted-by-them`?`theirs`:`ours`,a=``;try{a=await e(r.git,n,{signal:r.signal})}catch{}return{conflict:{filePath:n,markers:[],type:`delete-modify`,rawContent:a,deletedBy:t},rawContent:a}}let a=await e(r.git,n,{signal:r.signal}),o=t(a);return o.length===0?{conflict:null,rawContent:a}:{conflict:{filePath:n,markers:o,type:`text`,rawContent:a},rawContent:a}}async function r(e,t,r){return(await n(e,t,r)).conflict}export{r as extractConflict,n as extractConflictWithSource};
@@ -1,5 +1,5 @@
1
- import{ConflictError as e}from"../errors/conflict.js";const t=`<<<<<<<`,n=`|||||||`,r=`=======`,i=`>>>>>>>`;function a(a,l=3){let u=a.split(`
2
- `),d=[],f=0;for(;f<u.length;){let a=u[f];if(a===void 0||!o(a,t)){f++;continue}let p=f,m=s(a,t);f++;let h=[],g=null,_=null;for(;f<u.length;){let i=u[f];if(i===void 0)break;if(o(i,t))throw new e(`PARSE_FAILED`,`Nested conflict marker at line ${f+1}`);if(o(i,n)){_=s(i,n),f++,g=[];break}if(o(i,r)){f++;break}h.push(i),f++}if(f>=u.length)throw new e(`PARSE_FAILED`,`Unterminated conflict marker starting at line ${p+1}`);if(g!==null){for(;f<u.length;){let n=u[f];if(n===void 0)break;if(o(n,t))throw new e(`PARSE_FAILED`,`Nested conflict marker at line ${f+1}`);if(o(n,r)){f++;break}g.push(n),f++}if(f>=u.length)throw new e(`PARSE_FAILED`,`Unterminated conflict marker starting at line ${p+1}`)}let v=[];for(;f<u.length;){let n=u[f];if(n===void 0)break;if(o(n,t))throw new e(`PARSE_FAILED`,`Nested conflict marker at line ${f+1}`);if(o(n,i))break;v.push(n),f++}if(f>=u.length)throw new e(`PARSE_FAILED`,`Unterminated conflict marker starting at line ${p+1}`);let y=f,b=u[f],x=b===void 0?``:s(b,i);f++;let S=d[d.length-1],C=S?S.endLine+1:0,w=Math.max(C,p-l),T=u.slice(w,p).join(`
3
- `);d.push({startLine:p,endLine:y,ours:c(h),base:g===null?null:c(g),theirs:c(v),oursLabel:m,theirsLabel:x,baseLabel:_,contextBefore:T,contextAfter:``})}for(let e=0;e<d.length;e++){let t=d[e];if(!t)continue;let n=d[e+1],r=n?n.startLine:u.length,i=Math.min(r,t.endLine+1+l);d[e]={...t,contextAfter:u.slice(t.endLine+1,i).join(`
4
- `)}}return d}function o(e,t){return e.startsWith(t)&&(e.length===t.length||e[t.length]===` `)}function s(e,t){return e.slice(t.length).trim()}function c(e){return e.join(`
5
- `)}export{a as parseConflictMarkers};
1
+ import{ConflictError as e}from"../errors/conflict.js";function t(t,o=3){let s=t.split(`
2
+ `),c=[],l=0;for(;l<s.length;){let t=s[l],u=t===void 0?0:n(t,`<`);if(t===void 0||u===0){l++;continue}let d=l,f=i(t,u);l++;let p=[],m=null,h=null;for(;l<s.length;){let t=s[l];if(t===void 0)break;if(r(t,`<`,u))throw new e(`PARSE_FAILED`,`Nested conflict marker at line ${l+1}`);if(r(t,`|`,u)){h=i(t,u),l++,m=[];break}if(r(t,`=`,u)){l++;break}p.push(t),l++}if(l>=s.length)throw new e(`PARSE_FAILED`,`Unterminated conflict marker starting at line ${d+1}`);if(m!==null){for(;l<s.length;){let t=s[l];if(t===void 0)break;if(r(t,`<`,u))throw new e(`PARSE_FAILED`,`Nested conflict marker at line ${l+1}`);if(r(t,`=`,u)){l++;break}m.push(t),l++}if(l>=s.length)throw new e(`PARSE_FAILED`,`Unterminated conflict marker starting at line ${d+1}`)}let g=[];for(;l<s.length;){let t=s[l];if(t===void 0)break;if(r(t,`<`,u))throw new e(`PARSE_FAILED`,`Nested conflict marker at line ${l+1}`);if(r(t,`>`,u))break;g.push(t),l++}if(l>=s.length)throw new e(`PARSE_FAILED`,`Unterminated conflict marker starting at line ${d+1}`);let _=l,v=s[l],y=v===void 0?``:i(v,u);l++;let b=c[c.length-1],x=b?b.endLine+1:0,S=Math.max(x,d-o),C=s.slice(S,d).join(`
3
+ `);c.push({startLine:d,endLine:_,ours:a(p),base:m===null?null:a(m),theirs:a(g),oursLabel:f,theirsLabel:y,baseLabel:h,contextBefore:C,contextAfter:``})}for(let e=0;e<c.length;e++){let t=c[e];if(!t)continue;let n=c[e+1],r=n?n.startLine:s.length,i=Math.min(r,t.endLine+1+o);c[e]={...t,contextAfter:s.slice(t.endLine+1,i).join(`
4
+ `)}}return c}function n(e,t){let n=0;for(;e[n]===t;)n++;return n<7||e.length>n&&e[n]!==` `?0:n}function r(e,t,r){return n(e,t)===r}function i(e,t){return e.slice(t).trim()}function a(e){return e.join(`
5
+ `)}export{t as parseConflictMarkers};