@aburi/diff 0.3.0 → 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.
package/src/slice.ts DELETED
@@ -1,327 +0,0 @@
1
- import { type CallEdge, computeWeaklyConnectedComponents, RESERVED_LANGUAGE_IDS } from "@aburi/core"
2
- import type { SliceId, SliceRecord, SymbolChange, SymbolId } from "@aburi/types"
3
- import { DiffError } from "./errors"
4
-
5
- /** The three inputs of the Slice View pass — docs/design/slice-view.md §3. */
6
- export interface SliceInput {
7
- /** SymbolChange records produced by `buildDiff` (pre-sort is not required). */
8
- changes: readonly SymbolChange[]
9
- /**
10
- * Resolved call edges from the base IR. Typically produced by
11
- * `reconstructCallEdgesFromIR(baseIR)` inside `buildDiff` — Slice View
12
- * consumes only resolved edges (§5.4), never `Symbol.calls[]` directly.
13
- */
14
- baseCallEdges: readonly CallEdge[]
15
- /** Resolved call edges from the head IR (same source rule as base). */
16
- headCallEdges: readonly CallEdge[]
17
- }
18
-
19
- /**
20
- * Slice View clustering pass — docs/design/slice-view.md §2, §4–§8.
21
- *
22
- * Groups the changed-Symbol set of a diff into weakly-connected components
23
- * over the union of base and head call edges. Emits a `SliceRecord[]` whose
24
- * cluster ids are `"slice:" + <smallest-member Symbol id>`, both `slices[]`
25
- * and each `members[]` sorted ascending.
26
- *
27
- * Pure function: `(changes, baseCallEdges, headCallEdges)` → `SliceRecord[]`.
28
- * Determinism, idempotence, input-order insensitivity, and locality are all
29
- * guaranteed — see `computeWeaklyConnectedComponents` in `@aburi/core`.
30
- *
31
- * Returns `[]` when no SymbolChange is Node-eligible per §4.1; callers should
32
- * still serialise the empty array — the Markdown projection omits the section
33
- * (§9.4 / §12.5) but the JSON always emits the key so consumers never
34
- * distinguish "field absent" from "no slices" (§11.2).
35
- *
36
- * Every returned record has passed `assertSliceRecordInvariant` (§7.4).
37
- */
38
- export function computeSlices(input: SliceInput): SliceRecord[] {
39
- const nodeIds = collectNodeIds(input.changes)
40
- if (nodeIds.length === 0) return []
41
-
42
- const nodeIdSet = new Set<SymbolId>(nodeIds)
43
- const edges = collectEdges(input.baseCallEdges, input.headCallEdges, nodeIdSet)
44
-
45
- const components = computeWeaklyConnectedComponents<SymbolId>(nodeIds, edges, (id) => id)
46
-
47
- return components.map(makeSliceRecord)
48
- }
49
-
50
- const SLICE_ID_PREFIX = "slice:"
51
-
52
- /**
53
- * §7.1 — the single place production code derives a Slice id. Everything else
54
- * in `src/` either receives an id or renders one. (Tests spell the prefix out
55
- * literally on purpose: an expectation written in terms of the function under
56
- * test would agree with it no matter what it produced.)
57
- *
58
- * The cast is the one place a `SliceId` comes into existence. `SliceId` and
59
- * `SymbolId` are separate brands precisely so this concatenation cannot be
60
- * open-coded anywhere else: a bare `"slice:" + x` evaluates to `string`, which
61
- * `SliceRecord.id` no longer accepts.
62
- */
63
- function sliceIdFor(anchor: SymbolId): SliceId {
64
- return `${SLICE_ID_PREFIX}${anchor}` as SliceId
65
- }
66
-
67
- /**
68
- * Build one SliceRecord from an ascending-sorted component and check its own
69
- * post-condition before letting it out (§7.4 layer 1).
70
- *
71
- * The check is not defending against untrusted input — this function builds
72
- * the id itself, so the derivation clause is true by construction here and
73
- * only the two clauses about `members` can actually fire. Those are the point:
74
- * `members[0]` is the anchor only because `computeWeaklyConnectedComponents`
75
- * returns each component sorted ascending, a guarantee that lives one layer
76
- * down and is invisible from this file. If it ever stops holding, the diff
77
- * would otherwise keep emitting well-formed-looking SliceRecords naming the
78
- * wrong anchor. Here it fails instead.
79
- */
80
- function makeSliceRecord(members: readonly SymbolId[]): SliceRecord {
81
- const anchor = members[0]
82
- if (anchor === undefined) {
83
- throw new DiffError(
84
- "computeSlices: the clustering utility returned an empty component; every weakly-connected " +
85
- "component contains at least the node that seeded it (slice-view.md §6).",
86
- { code: "slice-invariant-violated" },
87
- )
88
- }
89
- const record: SliceRecord = { id: sliceIdFor(anchor), members: [...members] }
90
- assertSliceRecordInvariant(record)
91
- return record
92
- }
93
-
94
- /**
95
- * §7.1 — the anchor of a Slice: its lexicographically smallest member.
96
- *
97
- * Answers from `members[0]`. `id` is derived from the anchor, so
98
- * reconstructing the anchor by stripping the `"slice:"` prefix is circular at
99
- * best and, for a record that broke the derivation, silently wrong: it would
100
- * name a Symbol that is not in the Slice. `id` is read here only to name the
101
- * offending record in the error message. Consumers that need the anchor call
102
- * this; consumers that need a label keep using `id` directly.
103
- */
104
- export function sliceAnchor(record: SliceRecord): SymbolId {
105
- const anchor = record.members[0]
106
- if (anchor === undefined) {
107
- const violation = emptyMembersViolation(record.id)
108
- throw new DiffError(violation.message, {
109
- code: "slice-invariant-violated",
110
- value: violation.subject,
111
- })
112
- }
113
- return anchor
114
- }
115
-
116
- /** Which clause of the §7.1 / §8.2 invariant a `SliceRecord` broke. */
117
- export type SliceViolationKind =
118
- /** Not a `SliceRecord` at all: not an object, or `id` / `members` of the wrong type. */
119
- | "malformed-shape"
120
- /** `members[]` has no entries, so the Slice has no anchor (§11.1). */
121
- | "members-empty"
122
- /** `members[]` is not in strictly ascending order, so `members[0]` need not be the smallest (§8.2, §11.1). */
123
- | "members-unordered"
124
- /** `id` is not `"slice:" + members[0]` (§7.1). */
125
- | "id-not-derived"
126
- /** The anchor is itself in a reserved id namespace, so `id` would read as a doubled prefix (§7.5). */
127
- | "anchor-in-reserved-namespace"
128
-
129
- export interface SliceRecordViolation {
130
- kind: SliceViolationKind
131
- /** The offending record's `id` when it has a usable one, else a short stand-in. */
132
- subject: string
133
- /** Human-facing explanation, suitable for an error message or a validator error. */
134
- message: string
135
- }
136
-
137
- /**
138
- * Report which clause of the §7.1 / §8.2 invariant a value breaks, or `null`
139
- * when it is a well-formed `SliceRecord`. Non-throwing counterpart of
140
- * `assertSliceRecordInvariant`: the pass wants an exception, a schema
141
- * validator wants a verdict it can turn into its own error.
142
- *
143
- * Takes `unknown` rather than `SliceRecord` deliberately. §7.4 layer 2 points
144
- * this at documents written by third-party or older producers — data that has
145
- * not been type-checked by definition — so anything that assumed a well-typed
146
- * argument would crash on exactly the input it exists to reject.
147
- */
148
- export function sliceRecordViolation(value: unknown): SliceRecordViolation | null {
149
- if (typeof value !== "object" || value === null) {
150
- return {
151
- kind: "malformed-shape",
152
- subject: "<not an object>",
153
- message: `Expected a SliceRecord object; got ${value === null ? "null" : typeof value}.`,
154
- }
155
- }
156
- const { id, members } = value as { id?: unknown; members?: unknown }
157
- const subject = typeof id === "string" ? id : "<missing id>"
158
- if (typeof id !== "string") {
159
- return {
160
- kind: "malformed-shape",
161
- subject,
162
- message: `SliceRecord ${subject}: id must be a string; got ${typeof id}.`,
163
- }
164
- }
165
- if (!Array.isArray(members) || members.some((member) => typeof member !== "string")) {
166
- return {
167
- kind: "malformed-shape",
168
- subject,
169
- message: `SliceRecord ${subject}: members must be an array of strings.`,
170
- }
171
- }
172
-
173
- const anchor = members[0]
174
- if (anchor === undefined) return emptyMembersViolation(subject)
175
- // A Symbol id in the `slice:` namespace derives to `slice:slice:…`, which is
176
- // self-consistent — it passes the derivation clause below — but names an id no reader can
177
- // tell from a Slice id. `makeSymbolId` refuses to build such a Symbol id and
178
- // `checkIRIntegrity` #16 rejects one read from disk, but `buildDiff` is public API and
179
- // runs no integrity check, so the doubled prefix is caught here too.
180
- const reservedAnchor = reservedNamespaceOf(anchor)
181
- if (reservedAnchor !== null) {
182
- return {
183
- kind: "anchor-in-reserved-namespace",
184
- subject,
185
- message:
186
- `SliceRecord anchor "${anchor}" uses the reserved language token "${reservedAnchor}", ` +
187
- `so its Slice id would repeat the prefix (ir-schema.md §3.5, slice-view.md §7.5).`,
188
- }
189
- }
190
- for (let i = 1; i < members.length; i++) {
191
- const previous = members[i - 1] as string
192
- const current = members[i] as string
193
- if (previous < current) continue
194
- return {
195
- kind: "members-unordered",
196
- subject,
197
- message:
198
- `SliceRecord ${subject}: members[] is not in strictly ascending order at index ${i} ` +
199
- `("${current}" follows "${previous}"), so members[0] is not necessarily the anchor ` +
200
- `(slice-view.md §8.2 for the order, §11.1 for uniqueness).`,
201
- }
202
- }
203
- // The one place outside `sliceIdFor` that asserts an id brand, and the reason this
204
- // function takes `unknown`: the anchor has been checked to be a string and nothing more.
205
- // Whether it is a well-formed Symbol id is not this check's question — a record whose
206
- // members are gibberish still has to be told apart from one whose id disagrees with them.
207
- const expected = sliceIdFor(anchor as SymbolId)
208
- if (id !== expected) {
209
- return {
210
- kind: "id-not-derived",
211
- subject,
212
- message:
213
- `SliceRecord id "${id}" is not derived from the anchor "${anchor}"; ` +
214
- `expected "${expected}" (slice-view.md §7.1).`,
215
- }
216
- }
217
- return null
218
- }
219
-
220
- /** The reserved token an id opens with, or `null`. Shares the list `@aburi/core` enforces. */
221
- function reservedNamespaceOf(id: string): string | null {
222
- const colon = id.indexOf(":")
223
- if (colon < 0) return null
224
- const token = id.slice(0, colon)
225
- return RESERVED_LANGUAGE_IDS.has(token) ? token : null
226
- }
227
-
228
- /** Single source of the empty-`members[]` wording, shared with `sliceAnchor`. */
229
- function emptyMembersViolation(subject: string): SliceRecordViolation {
230
- return {
231
- kind: "members-empty",
232
- subject,
233
- message:
234
- `SliceRecord ${subject}: members[] is empty, so the Slice has no anchor ` +
235
- `(slice-view.md §11.1 requires at least one member).`,
236
- }
237
- }
238
-
239
- /**
240
- * Throwing form of `sliceRecordViolation`. Raised as a coded `DiffError` so
241
- * callers branch on `code` rather than parsing the message; which clause broke
242
- * is `SliceRecordViolation.kind`, for callers that need to tell them apart.
243
- */
244
- export function assertSliceRecordInvariant(record: SliceRecord): void {
245
- const violation = sliceRecordViolation(record)
246
- if (violation === null) return
247
- throw new DiffError(violation.message, {
248
- code: "slice-invariant-violated",
249
- value: violation.subject,
250
- })
251
- }
252
-
253
- /**
254
- * §4.1 Node selection: keep every SymbolChange whose status is
255
- * added / removed / changed / moved+changed / dropped-toggled. The identity
256
- * is the head-side Symbol id where present (added / changed / moved+changed /
257
- * dropped-toggled), the base-side id for removed. Pure moved and unchanged
258
- * (already stripped upstream) are excluded — §4.1 / §4.3.
259
- *
260
- * The returned array is deliberately not deduplicated: a well-formed
261
- * SymbolChange list from `buildDiff` never mentions the same Symbol id
262
- * twice, and Union-Find would coalesce any accidental duplicate anyway.
263
- */
264
- function collectNodeIds(changes: readonly SymbolChange[]): SymbolId[] {
265
- const ids: SymbolId[] = []
266
- for (const change of changes) {
267
- const id = nodeIdOf(change)
268
- if (id === null) continue
269
- ids.push(id)
270
- }
271
- return ids
272
- }
273
-
274
- function nodeIdOf(change: SymbolChange): SymbolId | null {
275
- switch (change.status) {
276
- case "added":
277
- return change.symbol.id
278
- case "removed":
279
- // §4.1 — removed uses base-side id because there is no head symbol.
280
- return change.symbol.id
281
- case "unknown":
282
- // The one side that exists carries the id, as for added / removed. An unknown entry
283
- // is a thing a reviewer has to look at, so it belongs in the cluster its neighbours
284
- // are in — a Symbol whose file went missing is most useful read beside the callers
285
- // that still reference it.
286
- return change.symbol.id
287
- case "changed":
288
- case "moved+changed":
289
- case "dropped-toggled":
290
- return change.after.id
291
- case "moved":
292
- // §4.3 — pure moved is not a Node and is not used for bridging either.
293
- return null
294
- }
295
- // Exhaustive: if SymbolChange grows a new status the compile error above
296
- // fires before this fallback is reachable.
297
- }
298
-
299
- /**
300
- * §5.1 Edge selection: union of base and head, restricted to edges whose
301
- * BOTH endpoints are Nodes, canonicalised to `(u, v)` with `u < v` (self-
302
- * loops implicitly dropped). Multi-edges collapse naturally inside the WCC
303
- * primitive — no explicit dedup needed.
304
- *
305
- * The union is the load-bearing rule of §5.3: a controller that called an
306
- * old service in base and a new service in head needs both edges to land
307
- * all three Symbols in a single Slice.
308
- */
309
- function collectEdges(
310
- baseEdges: readonly CallEdge[],
311
- headEdges: readonly CallEdge[],
312
- nodeIds: ReadonlySet<SymbolId>,
313
- ): [SymbolId, SymbolId][] {
314
- const pairs: [SymbolId, SymbolId][] = []
315
- for (const edge of baseEdges) appendEdgeIfBothNodes(edge, nodeIds, pairs)
316
- for (const edge of headEdges) appendEdgeIfBothNodes(edge, nodeIds, pairs)
317
- return pairs
318
- }
319
-
320
- function appendEdgeIfBothNodes(
321
- edge: CallEdge,
322
- nodeIds: ReadonlySet<SymbolId>,
323
- out: [SymbolId, SymbolId][],
324
- ): void {
325
- if (!nodeIds.has(edge.from) || !nodeIds.has(edge.to)) return
326
- out.push([edge.from, edge.to])
327
- }
package/src/status.ts DELETED
@@ -1,36 +0,0 @@
1
- import type { Symbol as IRSymbol } from "@aburi/types"
2
-
3
- export type SymbolStatus = "unchanged" | "moved" | "changed" | "moved+changed" | "dropped-toggled"
4
-
5
- /**
6
- * §4 — determine which of the five statuses a matched pair falls into. `dropped-toggled`
7
- * has absolute priority: whenever `dropped` differs between base and head, every other
8
- * signal is ignored because the underlying fingerprint change is a consequence of the
9
- * drop-rule flip, not a genuine code edit (§4.1 rationale).
10
- *
11
- * "pathChanged" catches both physical file relocation AND in-file rename: any Symbol id
12
- * mismatch between base and head means the identifier moved, and DF9 ("method rename
13
- * (same file, same logic) → moved") relies on this. Stage-1 pairs cannot trigger the id branch
14
- * (they match by exact id), so this only affects stage-2+ pairings where the pair was
15
- * discovered via fingerprint or name/signature similarity.
16
- */
17
- export function classifyStatus(base: IRSymbol, head: IRSymbol): SymbolStatus {
18
- const droppedToggled = base.dropped !== head.dropped
19
- if (droppedToggled) return "dropped-toggled"
20
- const pathChanged = base.source.file !== head.source.file || base.id !== head.id
21
- const fingerprintChanged =
22
- base.fingerprint.api !== head.fingerprint.api ||
23
- base.fingerprint.logic !== head.fingerprint.logic ||
24
- base.fingerprint.syntax !== head.fingerprint.syntax
25
- if (pathChanged && fingerprintChanged) return "moved+changed"
26
- if (pathChanged) return "moved"
27
- if (fingerprintChanged) return "changed"
28
- return "unchanged"
29
- }
30
-
31
- /** Direction of a `dropped-toggled` transition (§7.1 SymbolDroppedToggled). */
32
- export type DropDirection = "to-dropped" | "to-kept"
33
-
34
- export function dropDirection(head: IRSymbol): DropDirection {
35
- return head.dropped ? "to-dropped" : "to-kept"
36
- }