@aburi/diff 0.3.0 → 0.5.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.
package/dist/index.d.mts CHANGED
@@ -1,19 +1,17 @@
1
- import { CallEdge, SerializeOptions } from "@aburi/core";
1
+ import { CallEdge, IntegrityViolation, SerializeOptions } from "@aburi/core";
2
2
  import { Component, ComponentDiff, Dependency, DependencyDiff, DependencyEndpoint, DependencyUnknown, DiffResult, IR, IRRef, MatchRationale, NotComparedFile, RelativePath, Signature, SkipReason, SliceRecord, Summary, Symbol, SymbolChange, SymbolDelta, SymbolId } from "@aburi/types";
3
3
 
4
4
  //#region src/components.d.ts
5
5
  /**
6
- * `docs/design/diff-algorithm.md` §6.1 — Component diff. Assumes `components[].id` is unique on each side (ir-schema.md §14
7
- * #2) and does not check it: `buildDiff` establishes that before calling, and a caller
8
- * reaching this export directly owns the obligation, because the lookup map here is
9
- * last-write-wins and a repeat is lost rather than reported.
6
+ * `docs/design/diff-algorithm.md` — Component diff. Assumes `components[].id` is unique
7
+ * on each side (ir-schema.md #2) and does not check it: `buildDiff` establishes that, and
8
+ * a caller reaching this export directly owns the obligation, because the lookup map here is
9
+ * last-write-wins.
10
10
  *
11
- * Component identity is `id`; when a Component is present in both
12
- * base and head with the same id, the three delta booleans describe which axes actually
13
- * moved (roots reshuffle, public API globs, or framework hint list). `modified` deltas
14
- * are intentionally absent from this diff (diff-algorithm.md §5.2.3): fields are reported as before/after
15
- * pairs via the `changed[]` entries so consumers can render them without stringifying
16
- * arrays.
11
+ * Any field that differs makes a Component `changed` — the whole object is compared, not the
12
+ * three axes the delta names, so a `changed[]` entry with all three booleans `false` is a
13
+ * well-formed answer meaning "something else about this component moved". `modified` deltas
14
+ * are intentionally absent: fields are reported as before/after pairs.
17
15
  */
18
16
  declare function diffComponents(base: readonly Component[], head: readonly Component[]): ComponentDiff;
19
17
  /**
@@ -23,58 +21,40 @@ declare function diffComponents(base: readonly Component[], head: readonly Compo
23
21
  * `symbolFiles` is keyed on the endpoint id exactly as `dependencies[]` spells it, and its
24
22
  * values come from `symbols[].source.file` — the same space `stats.skippedFiles[].path` is in,
25
23
  * and the same space `buildDiff` classifies Symbols by. Reading the file out of the id's path
26
- * segment instead would introduce a second answer to "which file is this endpoint in", and
27
- * nothing in the schema forces the two to agree; a Symbol reported `unknown` while its edges
28
- * stayed `removed` is precisely the inconsistency this exists to remove.
29
- *
30
- * A Component endpoint is absent from the map, which is how it stays out of the reclassification
31
- * without a special case: a Component is an aggregate over roots and has no file to lose.
24
+ * segment instead would be a second answer to "which file is this endpoint in" that nothing
25
+ * forces to agree with the first. A Component endpoint is absent from the map, which keeps it
26
+ * out of the reclassification without a special case: an aggregate over roots has no file to
27
+ * lose.
32
28
  */
33
29
  interface DependencySideView {
34
30
  /**
35
- * `source.file` of every Symbol this document holds, by the id an endpoint would name it
36
- * with. Keyed by `DependencyEndpoint` rather than `SymbolId` because that is the question
37
- * being asked: the lookup happens with an endpoint whose kind is not yet known, and "absent"
38
- * is the answer for a Component id. Demanding the kind up front would move that decision to
39
- * the caller, where it would need a second Symbol-id silhouette test to make.
31
+ * `source.file` of every Symbol this document holds, keyed by `DependencyEndpoint` rather
32
+ * than `SymbolId` because the lookup happens with an endpoint whose kind is not yet known,
33
+ * and "absent" is the answer for a Component id.
40
34
  */
41
35
  symbolFiles: ReadonlyMap<DependencyEndpoint, RelativePath>;
42
- /**
43
- * Files this document never analysed, by path, with the reason it gave. `RelativePath` on
44
- * both sides of the file space is what states the bridge these two maps exist to make — one
45
- * map's values are the other's keys — though the alias is unbranded, so it is intent rather
46
- * than enforcement.
47
- */
36
+ /** Files this document never analysed, by path, with the reason it gave. */
48
37
  lostFiles: ReadonlyMap<RelativePath, SkipReason>;
49
38
  }
50
39
  /**
51
- * Build a side view from a document. The only construction site there is.
52
- *
53
- * `buildDiff` reads `lostFiles` for its own Symbol classification too, from this same object,
54
- * so "a Symbol reported unknown and the edges it took with it cannot disagree about which file
55
- * went missing" is a property of the wiring rather than a claim in a comment.
56
- *
57
- * Exported because `DependencySideView` is public and `diffDependencies` requires one: without
58
- * a factory a caller would have to reproduce the `symbols[].source.file` keying and the
59
- * `stats.skippedFiles` read, and the likeliest outcome of that is a caller who gets it wrong.
40
+ * Build a side view from a document. Exported because `DependencySideView` is public and
41
+ * `diffDependencies` requires one; `buildDiff` reads `lostFiles` for its own Symbol
42
+ * classification from this same object.
60
43
  */
61
44
  declare function dependencySideView(ir: IR): DependencySideView;
62
45
  /**
63
- * `docs/design/diff-algorithm.md` §6.2 — Dependency diff. Identity is the composite
64
- * `(from, to, via)` triple; direction and effect changes are surfaced as an added + removed
65
- * pair so `modified` is not part of the schema (§6.2 tail). Uniqueness of that triple is the caller's obligation on the same
66
- * terms as `diffComponents` above — a repeat here is indistinguishable in the output from
67
- * the flip it encodes.
46
+ * `docs/design/diff-algorithm.md` — Dependency diff. Identity is the composite
47
+ * `(from, to, via)` triple; direction and effect changes surface as an added + removed pair so
48
+ * `modified` is not part of the schema. Uniqueness of the triple is the caller's
49
+ * obligation on the same terms as `diffComponents`.
68
50
  *
69
- * `sides` is what separates a deletion from a loss (`docs/design/diff-algorithm.md` §6.2.1).
70
- * It is required rather than optional: omitting it would classify every edge into a lost file
71
- * as a deletion again — silently, and while still writing `unknown: []`, which this schema
72
- * defines as "nothing was unknown" rather than "nobody looked". A caller with no skip list to
73
- * offer says so by passing a side view whose `lostFiles` is empty, which is the honest spelling
74
- * of an IR written before `stats.skippedFiles` existed.
51
+ * `sides` separates a deletion from a loss and is required rather than optional:
52
+ * omitting it would silently classify every edge into a lost file as a deletion while still
53
+ * writing `unknown: []`, which the schema defines as "nothing was unknown". A caller with no
54
+ * skip list passes a side view whose `lostFiles` is empty.
75
55
  *
76
- * The return type declares `unknown` present, where the schema leaves it optional for documents
77
- * that predate the field. A reader may find it missing; this function always writes it.
56
+ * The return type declares `unknown` present, where the schema leaves it optional for
57
+ * documents that predate the field.
78
58
  */
79
59
  declare function diffDependencies(base: readonly Dependency[], head: readonly Dependency[], sides: {
80
60
  base: DependencySideView;
@@ -89,18 +69,21 @@ declare const MAX_LINE_FUZZ = 10;
89
69
  declare const MIN_LINE_FUZZ = 0;
90
70
  interface DeltaOptions {
91
71
  /**
92
- * §5.2.1 line fuzz for rule/call identity. Must be an integer in
72
+ * Line fuzz for pairing an edited rule/call/decorator with its predecessor
73
+ * (diff-algorithm.md); an unchanged one pairs however far it moved. Must be an integer in
93
74
  * `[MIN_LINE_FUZZ, MAX_LINE_FUZZ]` (`0..10`); anything outside — or a non-finite value —
94
- * throws `DiffError({ code: "invalid-line-fuzz" })`. Setting `0` disables fuzz; omitting
95
- * the field falls back to `DEFAULT_LINE_FUZZ` (2).
75
+ * throws `DiffError({ code: "invalid-line-fuzz" })`. Setting `0` pairs an edit only with an
76
+ * element on the same line, and does not stop an unchanged element from pairing; omitting the
77
+ * field falls back to `DEFAULT_LINE_FUZZ` (2).
96
78
  */
97
79
  lineFuzz?: number;
98
80
  }
99
81
  /**
100
- * §5 — Compute the full per-Symbol delta between two paired Symbols. The three axis
101
- * booleans (`apiChanged` / `logicChanged` / `syntaxChanged`) come from fingerprint
102
- * comparison; the array deltas (`rules` / `effects` / `calls` / `decorators`) come from
103
- * identity-preserving diff with configurable line fuzz.
82
+ * The full per-Symbol delta between two paired Symbols (diff-algorithm.md). The axis booleans
83
+ * come from fingerprint comparison; the array deltas from identity-preserving pairing, with line
84
+ * fuzz deciding only how far an edited element may sit from the one it replaced.
85
+ * `confidenceChanged` is always written, `false` included, so a reader can tell it from a diff
86
+ * that predates the field.
104
87
  */
105
88
  declare function computeSymbolDelta(base: Symbol, head: Symbol, options?: DeltaOptions): SymbolDelta;
106
89
  //#endregion
@@ -118,10 +101,10 @@ interface SymbolPair {
118
101
  /** Optional map returned by git for stage 2 (`old path` → `new path`). */
119
102
  type GitRenameMap = ReadonlyMap<string, string>;
120
103
  /**
121
- * §3.1 — segments Symbols with identical `id` into paired matches. Runs first because it
122
- * is the highest-confidence signal (no heuristics, just hash lookup).
104
+ * Stage 1 (diff-algorithm.md) — segments Symbols with identical `id` into paired matches.
105
+ * Runs first because it is the highest-confidence signal (no heuristics, just hash lookup).
123
106
  *
124
- * Assumes `id` is unique on each side (ir-schema.md §14 #1) and does not check it:
107
+ * Assumes `id` is unique on each side (ir-schema.md #1) and does not check it:
125
108
  * `buildDiff` establishes that before calling, and a caller reaching this export directly
126
109
  * owns the obligation. A repeat on the head side loses all but the last entry to the lookup
127
110
  * map and then removes every one of them from `remainingHead`; a repeat on the base side
@@ -134,10 +117,10 @@ declare function matchStageId(base: readonly Symbol[], head: readonly Symbol[]):
134
117
  remainingHead: Symbol[];
135
118
  };
136
119
  /**
137
- * §3.2 — git rename detection. When a rename map is available (typical of ref-driven
138
- * scans), rewrite the base id with the head-side file path and look for a hit. Two base
139
- * files renamed onto one target predict the same head id, so the claimants are collected
140
- * before one is chosen.
120
+ * Stage 2 (diff-algorithm.md) — git rename detection. When a rename map is available
121
+ * (typical of ref-driven scans), rewrite the base id with the head-side file path and look
122
+ * for a hit. Two base files renamed onto one target predict the same head id, so the
123
+ * claimants are collected before one is chosen.
141
124
  *
142
125
  * The rewriter only touches the `file` portion of the id — the `<language>:` prefix and
143
126
  * the trailing `#<qualified-name>` segment stay unchanged so a moved file with the same
@@ -150,14 +133,19 @@ declare function matchStageGitRename(remainingBase: readonly Symbol[], remaining
150
133
  remainingHead: Symbol[];
151
134
  };
152
135
  /**
153
- * §3.3 — group both sides by `fingerprint.logic` and pair within each group. Two branches:
136
+ * Stage 3 (diff-algorithm.md) — group both sides by kind and `fingerprint.logic` and pair
137
+ * within each group. Two branches:
154
138
  * - single base candidate → paired with `logic-fingerprint`, no similarity test
155
139
  * - several → `nameSimilarity` disambiguates at ≥ 0.85; a group that cannot reach it is left
156
140
  * whole for stage 4 to re-evaluate
157
141
  *
158
- * Dropped symbols are excluded (§3.3 tail) — their logic fingerprint is the sentinel
142
+ * Dropped symbols are excluded — their logic fingerprint is the sentinel
159
143
  * `"000000000000"` and would collide with every other dropped Symbol in the workspace.
160
144
  * They flow to the stage-4.5 weak matcher instead.
145
+ *
146
+ * A logic value that names nothing (`logicNamesNothing`) is shared the same way, but by
147
+ * Symbols that are kept: its group forms and pairs, on names alone and without the first
148
+ * branch. See `pairWithinLogicGroup`.
161
149
  */
162
150
  declare function matchStageLogicFingerprint(remainingBase: readonly Symbol[], remainingHead: readonly Symbol[]): {
163
151
  matched: SymbolPair[];
@@ -165,39 +153,15 @@ declare function matchStageLogicFingerprint(remainingBase: readonly Symbol[], re
165
153
  remainingHead: Symbol[];
166
154
  };
167
155
  /**
168
- * §3.4 — name + signature similarity with `(kind, signatureNullness)` bucket pre-filter.
169
- * `signatureNullness` distinguishes symbols with no signature (`interface`, `type`,
170
- * `class`) from callable ones so that a class body is never paired against a function.
171
- *
172
- * §3.4.6's owner gate runs before the score: a pair whose owners are not the same class, or
173
- * one a rename of the other, is not the same Symbol however well the rest agrees, and no
174
- * weight small enough to leave the name axis meaning something can outvote a matching member
175
- * name and signature.
176
- *
177
- * The composite score, over the pairs that clear it:
156
+ * Stage 4 (diff-algorithm.md) — name + signature similarity with a `(kind, signatureNullness)`
157
+ * bucket pre-filter, so a class body is never paired against a function. The owner gate runs
158
+ * before the score; over the pairs that clear it:
178
159
  * 0.5 * memberSimilarity + 0.3 * signatureSimilarity + 0.2 * OWNER_AXIS_SATISFIED
179
- *
180
- * `memberSimilarity` reads the last segment, not the whole qualified name: the gate has
181
- * already settled the owner, and reading it again on the name axis charges for it twice —
182
- * which is what kept a renamed class from ever pairing (§3.4.6).
183
- *
184
- * §3.4.3 threshold table, applied per head by the token count of its last name segment:
185
- * - 1 token → 1.0 (an exact match on both remaining axes)
186
- * - 2 tokens → 0.95 (strict, avoids `getUser` vs `getUsers`)
187
- * - default → 0.85
188
- *
189
- * §3.4.3 also names two Symbols the stage does not read at all, because for them the score is
190
- * high on evidence it does not have rather than on a resemblance: one whose signature is
191
- * null, since `signatureSimilarity(null, null)` is 1.0 and the bucket key restricts it to
192
- * candidates that are equally signature-less; and one whose qualified name carries a single
193
- * distinct token, since that is the whole of what its identity amounts to. Neither can be
194
- * expressed as a threshold — the second wants a bar above the top of the scale.
195
- *
196
- * Every pairing in a bucket that clears its head’s threshold becomes a candidate, and the
197
- * candidates are settled in score order rather than one head at a time — see
198
- * `acceptInScoreOrder`. That doubles the pairings scored, from a bucket that shrank as heads
199
- * consumed it to the full bucket every time; `createNameScorer` more than pays for it by
200
- * tokenising each distinct name once per pass instead of once per comparison.
160
+ * `memberSimilarity` reads the last segment only, since the gate has settled the owner and
161
+ * reading it again would charge twice. Thresholds are per head, see `thresholdFor`; the two
162
+ * Symbols the stage does not read at all are explained at `saysEnoughToPair`. Candidates are
163
+ * settled in score order (`acceptInScoreOrder`), and `createNameScorer` pays for the full
164
+ * bucket being scored by tokenising each name once per pass.
201
165
  */
202
166
  declare function matchStageNameSignature(remainingBase: readonly Symbol[], remainingHead: readonly Symbol[]): {
203
167
  matched: SymbolPair[];
@@ -205,32 +169,18 @@ declare function matchStageNameSignature(remainingBase: readonly Symbol[], remai
205
169
  remainingHead: Symbol[];
206
170
  };
207
171
  /**
208
- * §3.4.5 — dropped-only weak matcher. For dropped Symbols the fingerprint is zeroed, so the
209
- * only signals left are the trailing segment of the qualified name and the file basename.
210
- * Either one alone is enough to pair, which is deliberately lax: §3.4.5 accepts a
211
- * false-positive risk because dropped Symbols sit outside the IR's main review surface.
172
+ * Stage 4.5 (diff-algorithm.md) — dropped-only weak matcher. With the fingerprint zeroed, the only
173
+ * signals left are the last segment of the qualified name and the file basename, and either alone
174
+ * pairs — deliberately lax, since dropped Symbols sit outside the main review surface.
212
175
  *
213
- * What it does not accept is a signal that identifies nothing. A basename hit on `index.ts`
214
- * — the most common filename in a TypeScript monorepo — paired every dropped Symbol of one
215
- * kind under one with every other, at a score they all tied on, and the results landed in
176
+ * What it does not accept is a signal that identifies nothing: a basename hit on `index.ts`
177
+ * paired every dropped Symbol of one kind with every other and landed them in
216
178
  * `summary.moved`, which `--fail-on moved` gates on. So a half counts only when exactly one
217
- * dropped base and one dropped head carry that key: such a key names a pair, where a key
218
- * several Symbols carry names a group, and a group is not a pairing.
219
- *
220
- * That makes the candidates the identifying keys themselves — at most one pairing each,
221
- * two axes, so at most `2 × min(base, head)` of them rather than the cross-product a shared
222
- * basename used to produce.
223
- *
224
- * "Exactly one" is counted over the Symbols this stage is handed, not over every dropped
225
- * Symbol in the Document — stages 1 and 2 have already taken theirs, and a key they emptied
226
- * out identifies again. That is the intended reading, since the question is which leftover a
227
- * key picks out, but it is also how a shared `index.ts` comes back: three dropped classes
228
- * under one, two of them matched by id, and the basename identifies the two that are left.
229
- *
230
- * It also leaves nothing for §3.4.5's 0.5-per-half scale to rank, so §3.8's sweep is the
231
- * wrong instrument: it settles conflicts by score, and with none to settle by it would drop
232
- * one identified pairing for another over nothing but the id it sorts under. `bestPairing`
233
- * takes a maximum matching instead.
179
+ * dropped base and one dropped head carry that key — counted over the Symbols this stage is
180
+ * handed, since a key the earlier stages emptied out identifies again. The candidates are
181
+ * then the identifying keys themselves, at most `2 × min(base, head)` of them, all worth the
182
+ * same; the score-ordered sweep would settle a conflict on nothing but id order, so
183
+ * `bestPairing` takes a maximum matching instead.
234
184
  */
235
185
  declare function matchStageDroppedWeak(remainingBase: readonly Symbol[], remainingHead: readonly Symbol[]): {
236
186
  matched: SymbolPair[];
@@ -240,12 +190,9 @@ declare function matchStageDroppedWeak(remainingBase: readonly Symbol[], remaini
240
190
  //#endregion
241
191
  //#region src/diff.d.ts
242
192
  /**
243
- * The two counters `buildDiff` always writes, narrowed off `Summary`'s optionals.
244
- *
245
- * They are optional on the wire so a diff written before they existed stays valid, and that
246
- * optionality is about *documents*, not about this function — a caller holding a value it just
247
- * built should not have to re-decide what "absent" would have meant. Same reason
248
- * `diffDependencies` declares its `unknown` array present.
193
+ * The two counters `buildDiff` always writes. They are optional on `Summary` only so a diff
194
+ * written before they existed stays valid; a caller holding a freshly built value should not
195
+ * have to re-decide what "absent" means.
249
196
  */
250
197
  interface UnknownCounters {
251
198
  unknown: number;
@@ -264,73 +211,64 @@ interface DiffInput {
264
211
  };
265
212
  /** Optional stage-2 rename table. When null/undefined stage 2 is skipped. */
266
213
  gitRenames?: GitRenameMap | null;
267
- /** Passed through to computeSymbolDelta (§5.2.1 line fuzz). */
214
+ /** Passed through to computeSymbolDelta (line fuzz, diff-algorithm.md). */
268
215
  delta?: DeltaOptions;
269
216
  }
270
217
  /**
271
218
  * Top-level entry: run the 5-stage matcher, classify each pair, produce array deltas,
272
219
  * fold in Component / Dependency diffs, and assemble the `aburi.diff.v1` JSON projection.
273
- * The function is pure; write-to-disk is delegated to `writeCanonicalDiff` so callers can
274
- * pipe the result through additional steps (Markdown projection, `--fail-on` gate) before
275
- * serialisation.
220
+ * Pure; `writeCanonicalDiff` serialises, so callers can run the Markdown projection or the
221
+ * `--fail-on` gate over the result first.
276
222
  */
277
223
  declare function buildDiff(input: DiffInput): DiffResult & {
278
224
  notCompared: NotComparedFile[];
279
225
  summary: Summary & UnknownCounters;
280
226
  };
281
227
  /**
282
- * The files a document's scan never analysed, by path, with why.
283
- *
284
- * `stats.skippedFiles` is Class B: absent means the writer predates the field, not that
285
- * nothing was lost. An empty map is the honest answer either way — with no enumeration
286
- * there is no absence this function can explain, and guessing from
287
- * `totalFiles > parsedFiles` would attach a reason to whichever Symbols happened to be
288
- * missing. The CLI says so on stderr instead; a diff cannot invent the list.
289
- */
290
- /**
291
- * Byte-deterministic serialiser for a DiffResult. Delegates to `@aburi/core`
292
- * `serializeCanonical` so the sort order, NFC normalisation, and codepoint key sort are
293
- * shared with the IR side.
228
+ * Byte-deterministic serialiser for a DiffResult, sharing `@aburi/core`'s canonical sort
229
+ * order, NFC normalisation and key sort with the IR side.
294
230
  */
295
231
  declare function writeCanonicalDiff(diff: DiffResult, options?: SerializeOptions): string;
296
232
  //#endregion
297
233
  //#region src/errors.d.ts
234
+ type DiffErrorCode = /** `base.$schema` and `head.$schema` disagree (diff-algorithm.md). */"schema-mismatch"
298
235
  /**
299
- * Coded error class for every @aburi/diff failure. Consumers branch on `code` without
300
- * parsing message text. Codes are stable and additions are non-breaking; renames are not.
236
+ * `DeltaOptions.lineFuzz` was not an integer in the documented [0, 10] range
237
+ * (diff-algorithm.md).
301
238
  */
302
- type DiffErrorCode = /** `base.$schema` and `head.$schema` disagree; a diff across schema versions cannot be trusted (§9.1). */"schema-mismatch" /** `config.diff.lineFuzz` was outside the documented [0, 10] range (diff-algorithm.md §5.2.1). */ | "invalid-line-fuzz"
239
+ | "invalid-line-fuzz"
303
240
  /**
304
- * `baseIR` or `headIR` failed the top-level shape check that `buildDiff` enforces
305
- * before touching any Symbol. Missing / non-array `symbols`, `components`,
306
- * `dependencies`, or an absent `$schema` — anything that would otherwise crash with a
307
- * cryptic `TypeError: undefined is not iterable` deep in a matching stage.
241
+ * `baseIR` or `headIR` is not a Document of the shape `aburi.ir.v1` requires (invariant #20,
242
+ * `checkDocumentShape`), or its `$schema` is empty. Not the semantic invariants — see
243
+ * `assertDiffable`.
308
244
  */
309
245
  | "ir-shape-invalid"
310
246
  /**
311
247
  * `baseIR` or `headIR` repeats an identity the diff keys on: a `symbols[].id`, a
312
248
  * `components[].id`, or a `dependencies[]` `(from, to, via)` triple. Distinct from
313
249
  * `ir-shape-invalid` because the Document is well-formed — the collision changes the
314
- * answer rather than preventing one, and ir-schema.md §14 #1 / #2 / #13 already forbid it.
250
+ * answer rather than preventing one (ir-schema.md #1 / #2 / #13).
315
251
  */
316
252
  | "ir-identity-collision"
317
253
  /**
318
- * A `SliceRecord` broke the derivation invariant of slice-view.md §7.1 / §8.2:
319
- * `members[]` empty, `members[]` not in strictly ascending order, or `id` not
320
- * equal to `"slice:" + members[0]`. The last two compare one property against
321
- * another and so have no JSON Schema equivalent; the pass checks them itself
322
- * (§7.4). Raised only by an Aburi bug, never by user input — see
323
- * `SliceRecordViolation.kind` for which clause broke.
254
+ * A `SliceRecord` broke the derivation invariant of slice-view.md. Raised only by
255
+ * an Aburi bug, never by user input — see `SliceRecordViolation.kind` for which clause broke.
324
256
  */
325
257
  | "slice-invariant-violated";
326
258
  interface DiffErrorDetail {
327
259
  code: DiffErrorCode;
328
260
  /** Offending value (schema id, fuzz value, etc.) when applicable. */
329
261
  value?: string;
262
+ /**
263
+ * Populated only for `ir-shape-invalid`, one entry per breach of invariant #20, so a caller
264
+ * repairing a hand-assembled Document sees every breach rather than the first.
265
+ */
266
+ violations?: readonly IntegrityViolation[];
330
267
  }
331
268
  declare class DiffError extends Error {
332
269
  readonly code: DiffErrorCode;
333
270
  readonly value: string | undefined;
271
+ readonly violations: readonly IntegrityViolation[] | undefined;
334
272
  constructor(message: string, detail: DiffErrorDetail, options?: {
335
273
  cause?: unknown;
336
274
  });
@@ -338,117 +276,107 @@ declare class DiffError extends Error {
338
276
  //#endregion
339
277
  //#region src/signature.d.ts
340
278
  /**
341
- * §3.4.2 signatureSimilarity — averaged type-similarity across `inputs`, `outputs`, and
342
- * `throws`. Follows diff-algorithm.md §3.4.2:
343
- * - null + null → 1.0 (both symbols are signature-less; nothing to compare)
344
- * - null + non-null (either side) → 0.0
345
- * - both non-null: mean of three subscores
346
- *
347
- * Subscores:
348
- * - inputs: ordered type-string equality rate (`i-th type equal` counts as 1, else 0)
349
- * - outputs: same shape, but outputs is an array of type strings
350
- * - throws: unordered set intersection over union
351
- *
352
- * Empty subarrays on both sides count as 1.0 (they are trivially equal); on one side only
353
- * they count as 0.0 (asymmetric information).
279
+ * signatureSimilarity (diff-algorithm.md) — mean of three subscores over `inputs` (ordered
280
+ * type equality rate), `outputs` (same) and `throws` (Jaccard). Two null signatures score
281
+ * 1.0, one null scores 0.0. Empty on both sides counts as 1.0, empty on one side as 0.0.
354
282
  */
355
283
  declare function signatureSimilarity(base: Signature | null | undefined, head: Signature | null | undefined): number;
356
284
  //#endregion
357
285
  //#region src/similarity.d.ts
358
286
  /**
359
287
  * String similarity utilities dedicated to the diff engine. Kept in one file so the
360
- * name/signature/owner formulas are auditable side by side against diff-algorithm.md §3.4.
288
+ * name/signature/owner formulas are auditable side by side against diff-algorithm.md.
361
289
  */
362
290
  /**
363
- * Tokenise a qualified name into normalised lowercase word segments. Splits on:
364
- * - camelCase / PascalCase boundaries (`fooBar` → `foo`, `Bar`)
365
- * - snake_case underscores (`foo_bar` → `foo`, `bar`)
366
- * - dotted namespaces (`ns.Class` → `ns`, `Class`)
367
- * - `::` static-method separator (`Class::method` → `Class`, `method`)
368
- * - runs of digits (`get2Users` → `get`, `2`, `Users`)
369
- *
370
- * The result is de-duplicated so `InvoiceService.createInvoice` collapses to
371
- * `["invoice", "service", "create"]` — Jaccard similarity relies on set semantics, so
372
- * repeated tokens must not double-count.
291
+ * Tokenise a qualified name into de-duplicated lowercase word segments, splitting on camel /
292
+ * Pascal boundaries, `_`, `.`, `::` and digit runs: `InvoiceService.createInvoice` →
293
+ * `["invoice", "service", "create"]`. De-duplicated because Jaccard relies on set semantics.
373
294
  *
374
- * **The camel boundary is ASCII.** `isCamelBoundary` compares code points against `a`–`z`,
375
- * `A`–`Z` and `0`–`9`, so a name written in a script with no ASCII case boundary and no
376
- * separator comes back whole: `获取用户信息` and `ユーザー情報を取得する` are one token each,
377
- * and so is `получитьПользователя` — its camel hump does not register. A separator still
378
- * splits (`ユーザー.取得` gives two), and a mixed name splits on its ASCII half.
295
+ * The input is normalised to NFC first, so a name spelled with combining marks tokenises as
296
+ * the name it is: `ガ` written U+30AB U+3099 is the same one token as U+30AC, and a Hangul
297
+ * syllable written as conjoining jamo is the same one token as its precomposed block.
379
298
  *
380
- * That makes the token count a poor measure of how much such a name says, which matters
381
- * wherever a count is read as a proxy for that — see §3.4.3's admissibility rule.
299
+ * The camel boundary is Unicode case, not the ASCII ranges, so `получитьПользователя` splits
300
+ * at its hump the way `getUser` does. What no case rule can split is a script that has no
301
+ * case at all: `ユーザー情報を取得する` and `获取用户信息` come back whole however much they
302
+ * say. That is a fact about the writing system rather than about the name, which is why the
303
+ * token count is not what diff-algorithm.md §3.4.3 asks how much a name says — see
304
+ * `nameEvidence`.
382
305
  */
383
306
  declare function tokenizeName(input: string): string[];
384
307
  /**
385
- * Jaccard similarity between two token multisets. Formula: |A ∩ B| / |A ∪ B|.
386
- * Empty on both sides returns 1.0 (both are "no tokens", which are equivalent for the
387
- * purpose of §3.4.1). Empty on one side only returns 0.0.
308
+ * How much a qualified name says, counted in words.
309
+ *
310
+ * The distinct-token count is this number for every name the tokeniser can segment, and every
311
+ * caller wanting *granularity* — how coarse a Jaccard over these tokens will be — should keep
312
+ * reading that count instead. This answers the different question diff-algorithm.md §3.4.3
313
+ * asks: could two unrelated Symbols carry this name by coincidence? One word could be carried
314
+ * twice; a phrase could not.
315
+ *
316
+ * A token of a cased or alphabetic script is one word, so it is worth 1 — `main`, `handler`
317
+ * and `initialize` alike, however long they run, because length is not what makes a word
318
+ * coincidental. A run of a script that writes no word boundary cannot be segmented, so it is
319
+ * counted instead: its characters divided by the longest a single word of that script runs,
320
+ * which is a floor on the number of words in it. `获取用户信息` is six Han characters, so it
321
+ * says at least two words and is admitted; `ハンドラー` is five kana, so it says at least
322
+ * one, which is what `handler` says and not enough to pair on.
323
+ *
324
+ * Characters are counted once each, the way tokens are — `取得取得` says what `取得` says,
325
+ * as `getGet` says what `get` says. Combining marks are not counted: after NFC they are the
326
+ * remainder of a character that did not compose, not a word.
327
+ *
328
+ * The number is a floor rather than a count, so it is fractional where a run is: `取得` is
329
+ * two thirds of a word, `getUser` is exactly 2.
388
330
  */
389
- declare function jaccard(a: readonly string[], b: readonly string[]): number;
331
+ declare function nameEvidence(qname: string): number;
390
332
  /**
391
- * Jaccard over the tokens of two strings. Part of the module's surface rather than an
392
- * internal shortcut: the two formulas below go through a token table they share for one
393
- * matching pass, so this has no caller inside this file.
333
+ * Jaccard similarity |A ∩ B| / |A ∪ B| over two token lists. Empty on both sides is 1.0
334
+ * (both are "no tokens", equivalent for nameSimilarity); empty on one side only is 0.0.
394
335
  */
336
+ declare function jaccard(a: readonly string[], b: readonly string[]): number;
337
+ /** Jaccard over the tokens of two strings. Public surface only; nothing in this file calls it. */
395
338
  declare function jaccardTokens(a: string, b: string): number;
396
- /**
397
- * §3.4.1 — Jaccard over the tokens of the full qualified name. The last segment is not
398
- * given extra weight; the entire path contributes uniformly because the intersection is
399
- * what the score should reward.
400
- */
339
+ /** The member name; read by the weak matcher and the threshold lookup. */
340
+ declare function lastSegment(qname: string): string;
341
+ /** Jaccard over the tokens of the full qualified name, every segment weighted alike. */
401
342
  declare function nameSimilarity(baseName: string, headName: string): number;
402
343
  /**
403
- * §3.4.1 — Jaccard over the tokens of the **last segment**: the member name with its owner
404
- * removed. What §3.4's composite reads, because §3.4.6 decides the owner separately and
405
- * reading it on both axes charges for it twice.
344
+ * Jaccard over the tokens of the **last segment** only. What stage 4's composite reads, because the
345
+ * owner gate decides the owner separately and reading it on both axes charges twice.
406
346
  */
407
347
  declare function memberSimilarity(baseName: string, headName: string): number;
408
348
  /**
409
- * §3.4.6 (R-8) — whether two Symbols are close enough in *scope* to be the same Symbol: the
410
- * same owner, or one whose owner was renamed. A gate rather than a score, because grading the
411
- * owner cannot do what R-8 asks. `UserRepo.findById` and `AdminRepo.findById` agree on their
412
- * member name and their signature, so a shared `Repo` token at weight 0.2 carries them to
413
- * 0.8667 against a 0.85 threshold — while `UsersRepository.findById`, which *is* the rename,
414
- * shares no owner token and scores 0.8000. The collision outscores the rename, and raising the
415
- * weight only moves both: at 0.3 two three-token class names sharing two tokens land on
416
- * exactly 0.85.
349
+ * The owner gate (diff-algorithm.md, R-8) — whether two Symbols are close enough in *scope* to be
350
+ * the same Symbol: the same owner, or one whose owner was renamed. A gate rather than a score,
351
+ * because grading the owner cannot do what R-8 asks. `UserRepo.findById` and `AdminRepo.findById`
352
+ * agree on their member name and their signature, so a shared `Repo` token at weight 0.2 carries
353
+ * them to 0.8667 against a 0.85 threshold — while `UsersRepository.findById`, which *is* the
354
+ * rename, shares no owner token and scores 0.8000. The collision outscores the rename, and
355
+ * raising the weight only moves both: at 0.3 two three-token class names sharing two tokens land
356
+ * on exactly 0.85.
417
357
  *
418
- * Owner extraction:
419
- * - `Class::method` → `Class`
420
- * - `A.B.C.method` → `A.B.C`
421
- * - `topLevel` → `` (empty)
422
- *
423
- * Two empty owners are compatible: top-level Symbols share the one outer scope. One empty and
424
- * one not are never compatible — the two live at different depths.
425
- *
426
- * Otherwise the owners must correspond segment for segment, and within a segment every token
427
- * on each side must find a distinct partner on the other under `sameWord`. Both sides must be
428
- * covered, so `UserRepo` and `UserRepoV2` are two classes rather than one renamed — an added
429
- * token is as much evidence of a sibling as of a rename, and R-8's business is refusing the
430
- * collision.
358
+ * Two empty owners are compatible (top-level Symbols share the outer scope); one empty and one
359
+ * not never are. Otherwise the owners must correspond segment for segment, every token on each
360
+ * side finding a distinct partner under `sameWord`.
431
361
  */
432
362
  declare function ownersAreCompatible(baseName: string, headName: string): boolean;
433
- /** §3.4.1 tail note — used by drop-4.5 weak matcher and threshold lookup. */
434
- declare function lastSegment(qname: string): string;
435
363
  //#endregion
436
364
  //#region src/slice.d.ts
437
- /** The three inputs of the Slice View pass — docs/design/slice-view.md §3. */
365
+ /** The three inputs of the Slice View pass — docs/design/slice-view.md. */
438
366
  interface SliceInput {
439
367
  /** SymbolChange records produced by `buildDiff` (pre-sort is not required). */
440
368
  changes: readonly SymbolChange[];
441
369
  /**
442
370
  * Resolved call edges from the base IR. Typically produced by
443
371
  * `reconstructCallEdgesFromIR(baseIR)` inside `buildDiff` — Slice View
444
- * consumes only resolved edges (§5.4), never `Symbol.calls[]` directly.
372
+ * consumes only resolved edges, never `Symbol.calls[]` directly.
445
373
  */
446
374
  baseCallEdges: readonly CallEdge[];
447
375
  /** Resolved call edges from the head IR (same source rule as base). */
448
376
  headCallEdges: readonly CallEdge[];
449
377
  }
450
378
  /**
451
- * Slice View clustering pass — docs/design/slice-view.md §2, §4–§8.
379
+ * Slice View clustering pass — docs/design/slice-view.md.
452
380
  *
453
381
  * Groups the changed-Symbol set of a diff into weakly-connected components
454
382
  * over the union of base and head call edges. Emits a `SliceRecord[]` whose
@@ -459,16 +387,16 @@ interface SliceInput {
459
387
  * Determinism, idempotence, input-order insensitivity, and locality are all
460
388
  * guaranteed — see `computeWeaklyConnectedComponents` in `@aburi/core`.
461
389
  *
462
- * Returns `[]` when no SymbolChange is Node-eligible per §4.1; callers should
390
+ * Returns `[]` when no SymbolChange is Node-eligible; callers should
463
391
  * still serialise the empty array — the Markdown projection omits the section
464
- * (§9.4 / §12.5) but the JSON always emits the key so consumers never
465
- * distinguish "field absent" from "no slices" (§11.2).
392
+ * but the JSON always emits the key so consumers never
393
+ * distinguish "field absent" from "no slices".
466
394
  *
467
- * Every returned record has passed `assertSliceRecordInvariant` (§7.4).
395
+ * Every returned record has passed `assertSliceRecordInvariant`.
468
396
  */
469
397
  declare function computeSlices(input: SliceInput): SliceRecord[];
470
398
  /**
471
- * §7.1 — the anchor of a Slice: its lexicographically smallest member.
399
+ * The anchor of a Slice: its lexicographically smallest member.
472
400
  *
473
401
  * Answers from `members[0]`. `id` is derived from the anchor, so
474
402
  * reconstructing the anchor by stripping the `"slice:"` prefix is circular at
@@ -478,8 +406,8 @@ declare function computeSlices(input: SliceInput): SliceRecord[];
478
406
  * this; consumers that need a label keep using `id` directly.
479
407
  */
480
408
  declare function sliceAnchor(record: SliceRecord): SymbolId;
481
- /** Which clause of the §7.1 / §8.2 invariant a `SliceRecord` broke. */
482
- type SliceViolationKind = /** Not a `SliceRecord` at all: not an object, or `id` / `members` of the wrong type. */"malformed-shape" /** `members[]` has no entries, so the Slice has no anchor (§11.1). */ | "members-empty" /** `members[]` is not in strictly ascending order, so `members[0]` need not be the smallest (§8.2, §11.1). */ | "members-unordered" /** `id` is not `"slice:" + members[0]` (§7.1). */ | "id-not-derived" /** The anchor is itself in a reserved id namespace, so `id` would read as a doubled prefix (§7.5). */ | "anchor-in-reserved-namespace";
409
+ /** Which clause of the slice-view.md derivation invariant a `SliceRecord` broke. */
410
+ type SliceViolationKind = /** Not a `SliceRecord` at all: not an object, or `id` / `members` of the wrong type. */"malformed-shape" /** `members[]` has no entries, so the Slice has no anchor. */ | "members-empty" /** `members[]` is not in strictly ascending order, so `members[0]` need not be the smallest. */ | "members-unordered" /** `id` is not `"slice:" + members[0]`. */ | "id-not-derived" /** The anchor is itself in a reserved id namespace, so `id` would read as a doubled prefix. */ | "anchor-in-reserved-namespace";
483
411
  interface SliceRecordViolation {
484
412
  kind: SliceViolationKind;
485
413
  /** The offending record's `id` when it has a usable one, else a short stand-in. */
@@ -488,12 +416,12 @@ interface SliceRecordViolation {
488
416
  message: string;
489
417
  }
490
418
  /**
491
- * Report which clause of the §7.1 / §8.2 invariant a value breaks, or `null`
419
+ * Report which clause of the slice-view.md derivation invariant a value breaks, or `null`
492
420
  * when it is a well-formed `SliceRecord`. Non-throwing counterpart of
493
421
  * `assertSliceRecordInvariant`: the pass wants an exception, a schema
494
422
  * validator wants a verdict it can turn into its own error.
495
423
  *
496
- * Takes `unknown` rather than `SliceRecord` deliberately. §7.4 layer 2 points
424
+ * Takes `unknown` rather than `SliceRecord` deliberately. Enforcement layer 2 points
497
425
  * this at documents written by third-party or older producers — data that has
498
426
  * not been type-checked by definition — so anything that assumed a well-typed
499
427
  * argument would crash on exactly the input it exists to reject.
@@ -509,21 +437,21 @@ declare function assertSliceRecordInvariant(record: SliceRecord): void;
509
437
  //#region src/status.d.ts
510
438
  type SymbolStatus = "unchanged" | "moved" | "changed" | "moved+changed" | "dropped-toggled";
511
439
  /**
512
- * §4 — determine which of the five statuses a matched pair falls into. `dropped-toggled`
513
- * has absolute priority: whenever `dropped` differs between base and head, every other
514
- * signal is ignored because the underlying fingerprint change is a consequence of the
515
- * drop-rule flip, not a genuine code edit (§4.1 rationale).
440
+ * Which of the five statuses a matched pair falls into (diff-algorithm.md). `dropped-toggled`
441
+ * has absolute priority: a fingerprint change under a drop-rule flip is a consequence of the
442
+ * flip, not a code edit.
443
+ *
444
+ * `pathChanged` covers both file relocation and in-file rename: any id mismatch means the
445
+ * identifier moved, which DF9 ("method rename (same file, same logic) → moved") relies on.
446
+ * Stage-1 pairs match by exact id, so only stage-2+ pairings can take the id branch.
516
447
  *
517
- * "pathChanged" catches both physical file relocation AND in-file rename: any Symbol id
518
- * mismatch between base and head means the identifier moved, and DF9 ("method rename
519
- * (same file, same logic) → moved") relies on this. Stage-1 pairs cannot trigger the id branch
520
- * (they match by exact id), so this only affects stage-2+ pairings where the pair was
521
- * discovered via fingerprint or name/signature similarity.
448
+ * A confidence change is a change although no fingerprint reads it: the same code classified
449
+ * less surely is something a reviewer has to see, and `unchanged` is never reported. A dropped
450
+ * pair keeps its `unchanged`: a dropped Symbol is outside what the diff asks a reviewer to read.
522
451
  */
523
452
  declare function classifyStatus(base: Symbol, head: Symbol): SymbolStatus;
524
- /** Direction of a `dropped-toggled` transition (§7.1 SymbolDroppedToggled). */
453
+ /** Direction of a `dropped-toggled` transition (SymbolDroppedToggled, diff-algorithm.md). */
525
454
  type DropDirection = "to-dropped" | "to-kept";
526
455
  declare function dropDirection(head: Symbol): DropDirection;
527
456
  //#endregion
528
- export { DEFAULT_LINE_FUZZ, type DeltaOptions, type DependencySideView, DiffError, type DiffErrorCode, type DiffErrorDetail, type DiffInput, type DropDirection, type GitRenameMap, MAX_LINE_FUZZ, MIN_LINE_FUZZ, type SliceInput, type SliceRecordViolation, type SliceViolationKind, type SymbolPair, type SymbolStatus, assertSliceRecordInvariant, buildDiff, classifyStatus, computeSlices, computeSymbolDelta, dependencySideView, diffComponents, diffDependencies, dropDirection, jaccard, jaccardTokens, lastSegment, matchStageDroppedWeak, matchStageGitRename, matchStageId, matchStageLogicFingerprint, matchStageNameSignature, memberSimilarity, nameSimilarity, ownersAreCompatible, signatureSimilarity, sliceAnchor, sliceRecordViolation, tokenizeName, writeCanonicalDiff };
529
- //# sourceMappingURL=index.d.mts.map
457
+ export { DEFAULT_LINE_FUZZ, type DeltaOptions, type DependencySideView, DiffError, type DiffErrorCode, type DiffErrorDetail, type DiffInput, type DropDirection, type GitRenameMap, MAX_LINE_FUZZ, MIN_LINE_FUZZ, type SliceInput, type SliceRecordViolation, type SliceViolationKind, type SymbolPair, type SymbolStatus, assertSliceRecordInvariant, buildDiff, classifyStatus, computeSlices, computeSymbolDelta, dependencySideView, diffComponents, diffDependencies, dropDirection, jaccard, jaccardTokens, lastSegment, matchStageDroppedWeak, matchStageGitRename, matchStageId, matchStageLogicFingerprint, matchStageNameSignature, memberSimilarity, nameEvidence, nameSimilarity, ownersAreCompatible, signatureSimilarity, sliceAnchor, sliceRecordViolation, tokenizeName, writeCanonicalDiff };