@saasontools/strauss-kb 0.1.16 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -48,7 +48,7 @@ declare const kbVerifiedEventSchema: z.ZodObject<{
48
48
  * Symbolic on purpose. These are written while the code is still moving: a
49
49
  * `line: 379` recorded at minute five is wrong by minute forty, but
50
50
  * `OrderService.cancel` survives every edit that does not rename it. Once the
51
- * change settles, a resolution pass (`anchor-resolver.ts`) stamps `hash`,
51
+ * change settles, a resolution pass (`anchor-resolver/`) stamps `hash`,
52
52
  * `resolved_at`, and `lines`; drift detection later re-resolves and compares.
53
53
  *
54
54
  * `hash` is prefixed with the algorithm so a future one can coexist with
@@ -68,8 +68,16 @@ declare const kbAnchorSchema: z.ZodObject<{
68
68
  repo: z.ZodOptional<z.ZodString>;
69
69
  ref: z.ZodOptional<z.ZodString>;
70
70
  hash: z.ZodOptional<z.ZodString>;
71
+ hash_kind: z.ZodOptional<z.ZodEnum<{
72
+ raw: "raw";
73
+ ast: "ast";
74
+ }>>;
71
75
  resolved_at: z.ZodOptional<z.ZodString>;
72
76
  lines: z.ZodOptional<z.ZodNumber>;
77
+ resolver: z.ZodOptional<z.ZodEnum<{
78
+ "tree-sitter": "tree-sitter";
79
+ regex: "regex";
80
+ }>>;
73
81
  }, z.core.$strict>;
74
82
  /**
75
83
  * One typed causal edge, as the frontmatter stores it.
@@ -138,8 +146,16 @@ declare const kbRecordFrontmatterSchema: z.ZodObject<{
138
146
  repo: z.ZodOptional<z.ZodString>;
139
147
  ref: z.ZodOptional<z.ZodString>;
140
148
  hash: z.ZodOptional<z.ZodString>;
149
+ hash_kind: z.ZodOptional<z.ZodEnum<{
150
+ raw: "raw";
151
+ ast: "ast";
152
+ }>>;
141
153
  resolved_at: z.ZodOptional<z.ZodString>;
142
154
  lines: z.ZodOptional<z.ZodNumber>;
155
+ resolver: z.ZodOptional<z.ZodEnum<{
156
+ "tree-sitter": "tree-sitter";
157
+ regex: "regex";
158
+ }>>;
143
159
  }, z.core.$strict>>>;
144
160
  strauss_verify: z.ZodOptional<z.ZodArray<z.ZodString>>;
145
161
  strauss_links: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -202,12 +218,57 @@ type ResolvedSymbol = {
202
218
  startLine: number;
203
219
  endLine: number;
204
220
  };
221
+ /** Which resolver produced a span. Stamped on the anchor. */
222
+ type AnchorResolverName = "tree-sitter" | "regex";
223
+ /**
224
+ * A resolver's verdict. `abstain` ("not my language") and `symbol-not-found`
225
+ * ("nothing I recognize declares this") both pass the symbol down the chain;
226
+ * `symbol-ambiguous` and `resolver-unavailable` end it, because neither may be
227
+ * answered by a looser resolver guessing.
228
+ */
229
+ type ResolverAttempt = {
230
+ kind: "resolved";
231
+ span: ResolvedSymbol;
232
+ } | {
233
+ kind: "unresolved";
234
+ reason: "symbol-not-found" | "symbol-ambiguous" | "resolver-unavailable";
235
+ } | {
236
+ kind: "abstain";
237
+ };
205
238
  interface AnchorResolver {
206
239
  name: string;
207
- resolve(source: string, symbol: string): ResolvedSymbol | null;
240
+ /** Loads whatever these files need, before any `resolve` call. Optional. */
241
+ prepare?(files: readonly string[]): Promise<void>;
242
+ /** The richer verdict the chain uses; defaults to `resolve`. */
243
+ attempt?(source: string, symbol: string, file?: string): ResolverAttempt;
244
+ resolve(source: string, symbol: string, file?: string): ResolvedSymbol | null;
245
+ /**
246
+ * The span's normalised token stream — comments dropped, runs of whitespace
247
+ * collapsed — or `null` when this resolver cannot parse the text.
248
+ *
249
+ * Only a resolver that understands the language can offer one, which is why
250
+ * it is optional: a text heuristic normalising by guess would call two
251
+ * different programs equal.
252
+ */
253
+ normalize?(text: string, file?: string): string | null;
208
254
  }
255
+ /** A resolved span, and which resolver produced it. */
256
+ type AnchorResolution = {
257
+ ok: true;
258
+ span: ResolvedSymbol;
259
+ resolver?: AnchorResolverName;
260
+ /** The span's token stream, when the resolver that spanned it can parse. */
261
+ normalized?: string;
262
+ } | {
263
+ ok: false;
264
+ reason: AnchorUnresolvedReason;
265
+ };
209
266
  /** Why an anchor could not be compared. Never an error — always a finding. */
210
- type AnchorUnresolvedReason = "file-missing" | "symbol-not-found" | "outside-repo" | "file-too-large" | "file-unreadable"
267
+ type AnchorUnresolvedReason = "file-missing" | "symbol-not-found"
268
+ /** More than one definition carries the name, and guessing is not allowed. */
269
+ | "symbol-ambiguous"
270
+ /** The extension has a grammar, but it would not load. Never a throw. */
271
+ | "resolver-unavailable" | "outside-repo" | "file-too-large" | "file-unreadable"
211
272
  /** The remote could not be fetched, or `--offline` found nothing cached. */
212
273
  | "remote-unreachable"
213
274
  /** The anchor's `ref` is not on the remote any more. */
@@ -218,12 +279,37 @@ type AnchorUnresolvedReason = "file-missing" | "symbol-not-found" | "outside-rep
218
279
  | "ref-invalid"
219
280
  /** The anchor's `repo` is not a remote we will fetch from. */
220
281
  | "repo-invalid";
282
+ /**
283
+ * A hash that changed because a more precise resolver took over, not because
284
+ * the code did. Reported as drift so nothing is restamped silently, and
285
+ * accepted by `--rebaseline` like any other.
286
+ */
287
+ type AnchorDriftReason = "resolver-changed";
221
288
  /**
222
289
  * How a ref-pinned foreign anchor stands. `drifted-on-default` is the one a
223
290
  * working-tree anchor has no equivalent of: the evidence is still true at the
224
291
  * commit it was taken from, and the code has moved since.
225
292
  */
226
293
  type RemoteAnchorState = "matches-ref" | "drifted-from-ref" | "drifted-on-default";
294
+ /** What `hash` was taken over. Absent on an anchor means `raw`. */
295
+ type AnchorHashKind = "raw" | "ast";
296
+ /**
297
+ * How an anchor's code changed, once the bytes are known to differ.
298
+ *
299
+ * The classes a machine can settle, so a reader only sees the ones it cannot:
300
+ * `moved` and `cosmetic` are answered and closed, `gone` and `changed` are
301
+ * handed on. Deliberately shallow — whether the record's *claim* still holds
302
+ * is a reading, and no hash can stand in for one.
303
+ */
304
+ declare const KB_DRIFT_CLASSES: readonly ["moved", "cosmetic", "gone", "changed"];
305
+ type KbDriftClass = (typeof KB_DRIFT_CLASSES)[number];
306
+ /** Where a `moved` anchor's stored hash turned up. */
307
+ type KbDriftMovedTo = {
308
+ file: string;
309
+ symbol?: string;
310
+ startLine: number;
311
+ endLine: number;
312
+ };
227
313
  type KbAnchorDriftEntry = {
228
314
  file: string;
229
315
  symbol?: string;
@@ -232,10 +318,23 @@ type KbAnchorDriftEntry = {
232
318
  currentHash?: string;
233
319
  /** `null` when the anchor recorded no `lines` — size unknown, not zero. */
234
320
  diffSize: number | null;
235
- reason?: AnchorUnresolvedReason;
321
+ reason?: AnchorUnresolvedReason | AnchorDriftReason;
322
+ /** Which resolver produced `currentHash`. Absent for a whole-file anchor. */
323
+ resolver?: AnchorResolverName;
236
324
  /** Set only when the anchor was resolved against another repository. */
237
325
  repo?: string;
238
326
  remoteState?: RemoteAnchorState;
327
+ /** What the compared hashes were taken over. */
328
+ hashKind?: AnchorHashKind;
329
+ /**
330
+ * Provisional: `gone` or `changed`, the two a hash comparison alone can
331
+ * settle. `moved` and `cosmetic` cost a repository search and a git read, so
332
+ * `classifyDrift` refines this on the reassessment path rather than on every
333
+ * `load`.
334
+ */
335
+ class?: KbDriftClass;
336
+ /** Set by `classifyDrift` when the class is `moved`. */
337
+ movedTo?: KbDriftMovedTo;
239
338
  };
240
339
  type AnchorRead = {
241
340
  ok: true;
@@ -282,7 +381,10 @@ declare function readRemoteAnchors(wants: readonly RemoteWant[], options?: Remot
282
381
 
283
382
  type AnchorDriftOptions = {
284
383
  repoRoot?: string;
384
+ /** Single resolver, no chain. Convenience for tests. */
285
385
  resolver?: AnchorResolver;
386
+ /** The chain, tried in order. Defaults to tree-sitter then regex. */
387
+ resolvers?: readonly AnchorResolver[];
286
388
  concurrency?: number;
287
389
  /** Test seam: replaces the disk reader. */
288
390
  reader?: AnchorFileReader;
@@ -325,6 +427,69 @@ declare function anchorFilePath(repoRoot: string, file: string): string | null;
325
427
  */
326
428
  declare function isCanonicalRepoUrl(value: string): boolean;
327
429
 
430
+ declare const grammarManifestSchema: z.ZodObject<{
431
+ webTreeSitter: z.ZodString;
432
+ linguist: z.ZodObject<{
433
+ tag: z.ZodString;
434
+ commit: z.ZodString;
435
+ }, z.core.$strip>;
436
+ packs: z.ZodRecord<z.ZodString, z.ZodObject<{
437
+ package: z.ZodString;
438
+ wasm: z.ZodObject<{
439
+ url: z.ZodString;
440
+ sha256: z.ZodString;
441
+ bytes: z.ZodNumber;
442
+ }, z.core.$strip>;
443
+ tags: z.ZodArray<z.ZodObject<{
444
+ url: z.ZodString;
445
+ sha256: z.ZodString;
446
+ }, z.core.$strip>>;
447
+ license: z.ZodString;
448
+ extensions: z.ZodArray<z.ZodString>;
449
+ }, z.core.$strip>>;
450
+ }, z.core.$strip>;
451
+ type GrammarManifest = z.infer<typeof grammarManifestSchema>;
452
+ /** A grammar and the query that runs over it, both verified, both on disk. */
453
+ type Grammar = {
454
+ /** Path to the cached WASM. */
455
+ wasm: string;
456
+ /** The pack's tags parts as one query, or `undefined` where it declares none. */
457
+ query: string | undefined;
458
+ };
459
+ /** Where a grammar comes from and whether it may be fetched at all. */
460
+ type GrammarOptions = {
461
+ /** Cache root; defaults to `STRAUSS_KB_GRAMMARS_DIR` then `~/.strauss/grammars`. */
462
+ cacheRoot?: string;
463
+ /** Replaces the scheme and host of every manifest URL. For tests and mirrors. */
464
+ baseUrl?: string;
465
+ /** Cache only, never the network — what `--offline` passes down. */
466
+ offline?: boolean;
467
+ fetchTimeoutMs?: number;
468
+ /** Where the download lines go. Defaults to stderr, never stdout. */
469
+ log?: (line: string) => void;
470
+ };
471
+
472
+ /**
473
+ * The shipped `grammars/manifest.json`: the URL, hash and extensions of every
474
+ * language pack. Read once per process.
475
+ */
476
+ declare function grammarManifest(): GrammarManifest;
477
+
478
+ /** Where downloaded grammars live. Overridable so a test never writes to `$HOME`. */
479
+ declare function grammarsCacheRoot(override?: string): string;
480
+
481
+ /**
482
+ * Both halves of a verified pack (cached WASM path, tags query text), each
483
+ * downloaded once. `null` on any refused, disabled or mismatched part is what
484
+ * the resolver reports as `resolver-unavailable`; a miss is not remembered.
485
+ */
486
+ declare function ensureGrammar(language: string, options?: GrammarOptions): Promise<Grammar | null>;
487
+ /**
488
+ * One line per grammar this process could not use, for the doctor and
489
+ * anchor-resolve reports. The only place a repair is spelled out.
490
+ */
491
+ declare function grammarHints(): string[];
492
+
328
493
  /**
329
494
  * v1 heuristic resolver. A dotted symbol like `OrderService.cancel` matches on
330
495
  * its last segment, with the parent used to scope the search: a candidate
@@ -348,6 +513,25 @@ declare function hashAnchorText(text: string): string;
348
513
  * whole-file anchor's `lines` one larger than the file.
349
514
  */
350
515
  declare function resolveAnchor(source: string, anchor: KbAnchor, resolver?: AnchorResolver): ResolvedSymbol | null;
516
+ /**
517
+ * Walks the resolver chain: tree-sitter, then regex, then a whole-file span
518
+ * when the anchor names no symbol.
519
+ *
520
+ * `symbol-not-found` falls through (a tags query defines functions and types,
521
+ * not constants or fields) and the anchor records the resolver that answered.
522
+ * `symbol-ambiguous` and `resolver-unavailable` end the chain: one would be
523
+ * settled by guessing, the other would trade a precise span for a guessed one.
524
+ */
525
+ declare function resolveAnchorSpan(source: string, anchor: KbAnchor, resolvers?: readonly AnchorResolver[]): AnchorResolution;
526
+ /** Loads every chained resolver's per-language assets, once. */
527
+ declare function prepareResolvers(resolvers: readonly AnchorResolver[], files: readonly string[]): Promise<void>;
528
+ /**
529
+ * The read-path chain. A fresh tree-sitter resolver per call, so its parse
530
+ * cache lives exactly as long as the run that owns it. `offline` rides down to
531
+ * grammar loading: a run that may not reach the network uses the cache or
532
+ * reports `resolver-unavailable`.
533
+ */
534
+ declare function defaultAnchorResolvers(grammars?: GrammarOptions): AnchorResolver[];
351
535
 
352
536
  /**
353
537
  * Why a matched record must not be read as a plain answer.
@@ -415,6 +599,12 @@ type KbWarningAnchor = {
415
599
  /** Set only for an anchor resolved against another repository. */
416
600
  repo?: string;
417
601
  remoteState?: string;
602
+ /**
603
+ * `gone` or `changed` — what a hash comparison alone can settle. `moved` and
604
+ * `cosmetic` cost a repository search and a git read, so they are
605
+ * `kb_reassess`'s answer, not a read path's.
606
+ */
607
+ class?: KbDriftClass;
418
608
  };
419
609
  type KbStanding = "current" | "superseded" | "rejected" | "unsettled" | "open";
420
610
  type KbAdjudicated = {
@@ -830,6 +1020,15 @@ type KbStampResult = {
830
1020
  /** Newest `generated.at` across the base, or null when none carries one. */
831
1021
  newestAt: string | null;
832
1022
  records: KbRecordStamp[];
1023
+ /**
1024
+ * Records with at least one anchor whose code no longer matches its hash.
1025
+ *
1026
+ * Outside the digest, and deliberately: drift is a fact about the working
1027
+ * tree, not about the base's content, and folding it in would make a stamp
1028
+ * change every time someone checked out a branch. `null` when the drift pass
1029
+ * could not run — an unknown count, which is not zero.
1030
+ */
1031
+ drifted: number | null;
833
1032
  };
834
1033
  type KbWriteInput = {
835
1034
  type: string;
@@ -1001,11 +1200,16 @@ declare class KbStore {
1001
1200
  }): Promise<KbLoadResult>;
1002
1201
  /**
1003
1202
  * `load`'s digest without `load`'s bodies — the same records, adjudicated
1004
- * the same way, handed back as a stamp. Skips the anchor drift pass, which
1005
- * reads source files and only ever adds warnings: no warning reaches the
1006
- * digest, so the value is identical to the one `load` returns.
1203
+ * the same way, handed back as a stamp.
1204
+ *
1205
+ * Drift is counted but kept out of the digest, which is what lets the reload
1206
+ * hook ask one question and get two answers: whether the base moved, and
1207
+ * whether the code under it did. A `load` and a `stamp` of the same base
1208
+ * still agree on the digest, because no warning has ever reached it.
1007
1209
  */
1008
- stamp(bundlePath: string): Promise<KbStampResult>;
1210
+ stamp(bundlePath: string, options?: {
1211
+ repoRoot?: string;
1212
+ }): Promise<KbStampResult>;
1009
1213
  /** How a position was arrived at, as a timeline. See `trace.ts`. */
1010
1214
  trace(bundlePath: string, seedId: string, options?: KbTraceOptions): Promise<KbTraceStep[]>;
1011
1215
  /** Every record named in one line each. See `catalog.ts`. */
@@ -1237,6 +1441,85 @@ declare class KbInvalidConceptIdError extends BaseError {
1237
1441
  constructor(message: string, details: Record<string, string>);
1238
1442
  }
1239
1443
 
1444
+ /**
1445
+ * Grammar for a path, or `undefined` when the extension has none — or when the
1446
+ * pinned grammar release ships no tags query for it, so the regex heuristic
1447
+ * keeps those files, as before the resolver existed.
1448
+ */
1449
+ declare function languageForFile(file: string): string | undefined;
1450
+ /** Every language the resolver can resolve in: a grammar and a tags query. */
1451
+ declare function treeSitterLanguages(): string[];
1452
+
1453
+ type TreeSitterStats = {
1454
+ parses: number;
1455
+ cacheHits: number;
1456
+ };
1457
+ /** Where both halves of a pack come from, and whether they may be fetched. */
1458
+ type TreeSitterOptions = GrammarOptions;
1459
+ declare class TreeSitterResolver implements AnchorResolver {
1460
+ readonly name = "tree-sitter";
1461
+ private readonly grammars;
1462
+ private readonly loaded;
1463
+ private readonly trees;
1464
+ private parser;
1465
+ private initialized;
1466
+ /** Cache effectiveness, for tests and for the latency numbers. */
1467
+ readonly stats: TreeSitterStats;
1468
+ constructor(options?: TreeSitterOptions);
1469
+ /**
1470
+ * Loads the grammars these files need, once per language per process,
1471
+ * downloading each one on first use.
1472
+ *
1473
+ * A grammar that will not load is remembered as unavailable rather than
1474
+ * retried per anchor, and never throws: an unobtainable WASM is a finding.
1475
+ */
1476
+ prepare(files: readonly string[]): Promise<void>;
1477
+ /**
1478
+ * An unobtainable grammar, one this runtime refuses, and a query that will
1479
+ * not compile are three faults with three repairs; all are reported through
1480
+ * the grammars module so every hint has one home.
1481
+ */
1482
+ private load;
1483
+ /**
1484
+ * Abstains on an extension with no grammar so the regex resolver gets a
1485
+ * turn; reports `resolver-unavailable` when the grammar exists in principle
1486
+ * but could not be loaded, because falling back there would silently trade a
1487
+ * precise span for a guessed one.
1488
+ */
1489
+ attempt(source: string, symbol: string, file?: string): ResolverAttempt;
1490
+ resolve(source: string, symbol: string, file?: string): ResolvedSymbol | null;
1491
+ /** Parsed trees are keyed by content hash, so an unchanged file parses once. */
1492
+ private parse;
1493
+ /**
1494
+ * Every definition this file declares, as dotted symbol and span.
1495
+ *
1496
+ * The inverse of `attempt`: that asks "where is this name", this asks "what
1497
+ * names are here". `moved` needs the second — the stored hash has to be
1498
+ * looked for at every definition in the repository, and there is no name to
1499
+ * ask about, since the whole question is which name now carries that code.
1500
+ */
1501
+ spans(source: string, file: string): {
1502
+ symbol: string;
1503
+ span: ResolvedSymbol;
1504
+ }[];
1505
+ /**
1506
+ * The token stream of a span: every leaf the parser sees, comments dropped,
1507
+ * joined by single spaces.
1508
+ *
1509
+ * This is what makes a reformat not be drift. Hashing it rather than the raw
1510
+ * text means indentation, line breaks, trailing commas the formatter moved,
1511
+ * and every comment above or inside the definition are outside the hash —
1512
+ * and a renamed identifier or a changed literal is still inside it, because
1513
+ * those are leaves.
1514
+ *
1515
+ * `null` when the file has no grammar, the grammar would not load, or the
1516
+ * text will not parse: no normalisation is better than a guessed one.
1517
+ */
1518
+ normalize(text: string, file?: string): string | null;
1519
+ /** Drops cached trees. Grammars stay loaded — they are immutable. */
1520
+ reset(): void;
1521
+ }
1522
+
1240
1523
  /**
1241
1524
  * What each record type is for, and the shape of its body.
1242
1525
  *
@@ -1332,8 +1615,16 @@ declare const composeInputSchema: z.ZodObject<{
1332
1615
  repo: z.ZodOptional<z.ZodString>;
1333
1616
  ref: z.ZodOptional<z.ZodString>;
1334
1617
  hash: z.ZodOptional<z.ZodString>;
1618
+ hash_kind: z.ZodOptional<z.ZodEnum<{
1619
+ raw: "raw";
1620
+ ast: "ast";
1621
+ }>>;
1335
1622
  resolved_at: z.ZodOptional<z.ZodString>;
1336
1623
  lines: z.ZodOptional<z.ZodNumber>;
1624
+ resolver: z.ZodOptional<z.ZodEnum<{
1625
+ "tree-sitter": "tree-sitter";
1626
+ regex: "regex";
1627
+ }>>;
1337
1628
  }, z.core.$strict>>>;
1338
1629
  sources: z.ZodOptional<z.ZodArray<z.ZodObject<{
1339
1630
  id: z.ZodString;
@@ -1857,6 +2148,19 @@ type KbDoctorReport = {
1857
2148
  groups: KbDoctorGroup[];
1858
2149
  findingCount: number;
1859
2150
  healthy: boolean;
2151
+ /**
2152
+ * Anchors carrying a hash, by the resolver that produced it. A heuristic
2153
+ * span is weaker evidence than a parsed one, so a base still leaning on the
2154
+ * regex resolver is worth re-resolving. Not a finding: a regex-stamped
2155
+ * anchor is not broken.
2156
+ */
2157
+ anchorResolvers: KbAnchorResolverCounts;
2158
+ };
2159
+ type KbAnchorResolverCounts = {
2160
+ total: number;
2161
+ treeSitter: number;
2162
+ /** Includes anchors stamped before resolvers were named. */
2163
+ regex: number;
1860
2164
  };
1861
2165
  type KbDoctorOptions = {
1862
2166
  /** How far ahead `expiring` looks. */
@@ -1923,8 +2227,16 @@ declare const decisionInputSchema: z.ZodObject<{
1923
2227
  repo: z.ZodOptional<z.ZodString>;
1924
2228
  ref: z.ZodOptional<z.ZodString>;
1925
2229
  hash: z.ZodOptional<z.ZodString>;
2230
+ hash_kind: z.ZodOptional<z.ZodEnum<{
2231
+ raw: "raw";
2232
+ ast: "ast";
2233
+ }>>;
1926
2234
  resolved_at: z.ZodOptional<z.ZodString>;
1927
2235
  lines: z.ZodOptional<z.ZodNumber>;
2236
+ resolver: z.ZodOptional<z.ZodEnum<{
2237
+ "tree-sitter": "tree-sitter";
2238
+ regex: "regex";
2239
+ }>>;
1928
2240
  }, z.core.$strict>>>;
1929
2241
  verify: z.ZodOptional<z.ZodArray<z.ZodString>>;
1930
2242
  relatedConceptIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
@@ -2044,6 +2356,189 @@ type KbCommand<Shape extends z.ZodRawShape = z.ZodRawShape> = {
2044
2356
  declare const KB_COMMANDS: KbCommand[];
2045
2357
  declare const KB_COMMANDS_BY_NAME: Map<string, KbCommand>;
2046
2358
 
2359
+ /** Where a recovered file came from, so a packet can say how far back it looked. */
2360
+ type OldSourceOrigin =
2361
+ /** `git show <anchor.ref>:<file>` — the rev the record itself named. */
2362
+ {
2363
+ kind: "ref";
2364
+ ref: string;
2365
+ }
2366
+ /** The last commit touching the path before `resolved_at`. */
2367
+ | {
2368
+ kind: "history";
2369
+ ref: string;
2370
+ };
2371
+
2372
+ type MovedSearch = {
2373
+ /**
2374
+ * Where this anchor's stored hash turned up, or `undefined`.
2375
+ *
2376
+ * Shared across every anchor of a run: one `git ls-files`, one parse cache,
2377
+ * one set of loaded grammars. A `doctor --drifted` sweep over a base whose
2378
+ * records anchor into the same few languages parses each candidate once, not
2379
+ * once per drifted anchor.
2380
+ */
2381
+ find(anchor: KbAnchor): Promise<KbDriftMovedTo | undefined>;
2382
+ };
2383
+
2384
+ /**
2385
+ * Turning "the bytes changed" into one of four answers, two of which end the
2386
+ * matter.
2387
+ *
2388
+ * The order is not arbitrary: `moved` is asked first because it is the only
2389
+ * class that needs no history at all, and `cosmetic` second because it is the
2390
+ * only one that needs the old text. What survives both is what a reader has to
2391
+ * read — and the whole point of asking the cheap questions first is that most
2392
+ * drift never reaches them.
2393
+ *
2394
+ * Everything here is read-only. Rebaselining a `moved` anchor is a write, and
2395
+ * writes belong to the verb the caller named.
2396
+ */
2397
+ type ClassifiedAnchor = {
2398
+ anchor: KbAnchor;
2399
+ entry: KbAnchorDriftEntry;
2400
+ /** Resolved class. Never `undefined` — every reported anchor gets one. */
2401
+ class: KbDriftClass;
2402
+ /** The anchored text as it stands now. Absent when the class is `gone`. */
2403
+ newText?: string;
2404
+ /** The anchored text as it was, when history could produce it. */
2405
+ oldText?: string;
2406
+ oldOrigin?: OldSourceOrigin;
2407
+ };
2408
+ type ClassifyOptions = {
2409
+ /** Test seam: replaces the disk reader. */
2410
+ reader?: AnchorFileReader;
2411
+ /** Skip the history read. `cosmetic` cannot be reached without it. */
2412
+ withHistory?: boolean;
2413
+ /**
2414
+ * The run's shared `moved` search. A sweep classifying many records passes
2415
+ * one, so the repository is listed once and each candidate file is parsed
2416
+ * once for the whole sweep rather than once per record.
2417
+ */
2418
+ search?: MovedSearch;
2419
+ };
2420
+ /**
2421
+ * Refines one record's drift entries. Anchors that matched, or that name
2422
+ * another repository, are not drift and never appear.
2423
+ */
2424
+ declare function classifyDrift(repoRoot: string, record: KbRecord, entries: readonly KbAnchorDriftEntry[], options?: ClassifyOptions): Promise<ClassifiedAnchor[]>;
2425
+
2426
+ type UnifiedDiff = {
2427
+ /** `-`/`+`/` ` prefixed lines, with a `@@` header. */
2428
+ text: string;
2429
+ added: number;
2430
+ removed: number;
2431
+ /** Whether the cap cut it short. */
2432
+ truncated: boolean;
2433
+ };
2434
+ /**
2435
+ * One hunk, no context trimming: the two sides are already a symbol's span,
2436
+ * so the whole of both is the context a reader wants.
2437
+ *
2438
+ * The common subsequence is computed over line *hashes* through a simple
2439
+ * O(n·m) table. Spans are bounded by the anchor file cap, and a smarter
2440
+ * algorithm would be a second thing to be wrong about for a saving nobody can
2441
+ * measure at this size.
2442
+ */
2443
+ declare function unifiedDiff(before: string, after: string, options?: {
2444
+ maxLines?: number;
2445
+ oldLabel?: string;
2446
+ newLabel?: string;
2447
+ }): UnifiedDiff;
2448
+
2449
+ /**
2450
+ * What a reader needs in order to decide whether a record still holds, without
2451
+ * opening the repository.
2452
+ *
2453
+ * A drift finding today says two hashes disagree, which is not a thing anyone
2454
+ * can judge. The packet is the same finding with the three pieces judgment
2455
+ * actually takes: what the record claims, what the code did, and what depends
2456
+ * on the answer. It stops there — the reading itself is the reader's, and
2457
+ * every default below is a starting point the protocol expects to be argued
2458
+ * with.
2459
+ */
2460
+ type KbReassessDiff = {
2461
+ status: "ok";
2462
+ /** `ref` when the anchor pinned one, `history` when it was inferred. */
2463
+ source: "ref" | "history";
2464
+ /** The rev the old side was read at. */
2465
+ ref: string;
2466
+ unified: string;
2467
+ added: number;
2468
+ removed: number;
2469
+ truncated: boolean;
2470
+ }
2471
+ /** No committed text to diff against; see `readOldSource`. */
2472
+ | {
2473
+ status: "unrecoverable";
2474
+ };
2475
+ type KbReassessAnchor = {
2476
+ file: string;
2477
+ symbol?: string;
2478
+ class: KbDriftClass;
2479
+ reason?: string;
2480
+ storedHash: string;
2481
+ currentHash?: string;
2482
+ diffSize: number | null;
2483
+ movedTo?: KbDriftMovedTo;
2484
+ diff?: KbReassessDiff;
2485
+ };
2486
+ /**
2487
+ * What the type says about a record whose code changed under it.
2488
+ *
2489
+ * A `fact` is a claim about the world that the code was the evidence for, so
2490
+ * changed evidence presumptively unmakes it. A `decision` is a claim about a
2491
+ * choice, and the reasoning for a choice routinely outlives the code that
2492
+ * implemented it. Neither is a verdict — they are which way to lean while
2493
+ * reading, and naming the lean is what keeps it arguable.
2494
+ */
2495
+ type KbReassessDefault = "presumed-invalidated" | "rationale-may-survive" | "review";
2496
+ type KbReassessPacket = {
2497
+ conceptId: string;
2498
+ title: string | null;
2499
+ type: string;
2500
+ standing: KbStanding;
2501
+ /** What breaks if this record is wrong — the record's `why`, stored as `description`. */
2502
+ why: string | null;
2503
+ /** The type's claim section — the sentence being reassessed. */
2504
+ claim: {
2505
+ section: string;
2506
+ text: string;
2507
+ } | null;
2508
+ anchors: KbReassessAnchor[];
2509
+ /**
2510
+ * The record's dependants. A fact that stopped holding did not stop holding
2511
+ * alone, and a reader deciding about it is deciding about these too.
2512
+ */
2513
+ impact: {
2514
+ conceptId: string;
2515
+ title: string | null;
2516
+ standing: KbStanding;
2517
+ depth: number;
2518
+ }[];
2519
+ impactTruncated: boolean;
2520
+ default: KbReassessDefault;
2521
+ defaultNote: string;
2522
+ };
2523
+ type PacketOptions = ClassifyOptions & {
2524
+ /** Recover and render the old-vs-new span diff. Off by default: it reads git. */
2525
+ withDiff?: boolean;
2526
+ impact?: KbImpactResult;
2527
+ standing?: KbStanding;
2528
+ };
2529
+ /**
2530
+ * One record's packet, or `null` when nothing survived classification.
2531
+ *
2532
+ * A record whose every drifted anchor turned out to be `moved` or `cosmetic`
2533
+ * is a record with no reassessment work, and emitting an empty packet for it
2534
+ * would put it back in front of the reader the classification just cleared it
2535
+ * from.
2536
+ */
2537
+ declare function reassessPacket(repoRoot: string, record: KbRecord, entries: readonly KbAnchorDriftEntry[], options?: PacketOptions): Promise<{
2538
+ packet: KbReassessPacket | null;
2539
+ classified: ClassifiedAnchor[];
2540
+ }>;
2541
+
2047
2542
  /**
2048
2543
  * A knowledge base's own MCP server, over stdio.
2049
2544
  *
@@ -2176,4 +2671,4 @@ declare function parseMarkdownWithFrontmatter<S extends z.ZodType>(text: string,
2176
2671
  frontmatter: ReturnType<S["safeParse"]>;
2177
2672
  };
2178
2673
 
2179
- export { type AnchorResolver, BaseError, CONTEXT_BEGIN, CONTEXT_END, CONTEXT_PROFILES, type ComposeInput, type ComposeLink, type ComposedRecord, DECISION_TYPE, DEFAULT_AGING_DAYS, DEFAULT_EXPIRING_DAYS, DEFAULT_LOAD_BUDGET, DEFAULT_PACK_HOPS, DEFAULT_PACK_MAX_NODES, DEFAULT_TYPED_LINK_RELS, DEFAULT_UNVERIFIED_DAYS, type DecisionInput, type DiffFile, type DiffHunk, type DiffMatch, type ErrorDetails, type ErrorProps, ErrorTypes, Fault, INDEX_FILE, KB_CAUSAL_LINK_RELS, KB_COMMANDS, KB_COMMANDS_BY_NAME, KB_CONCEPT_ID_PATTERN, KB_CONFIDENCES, KB_DIR, KB_DOCTOR_CHECKS, KB_EDGE_KINDS, KB_LINK_RELS, KB_MATERIALITIES, KB_RECORD_STATUSES, KB_RECORD_TYPES, KB_SLUG_PATTERN, type KbActorStamp, type KbAdjudicated, type KbAnchor, type KbAnchorDriftEntry, type KbBacklink, type KbBacklinksResult, KbBaseFrozenError, type KbCatalogEntry, type KbCatalogResult, type KbCommand, type KbCommandContext, type KbContextBudgets, type KbContextOptions, type KbContextResult, type KbDoctorCheck, type KbDoctorFinding, type KbDoctorGroup, type KbDoctorOptions, type KbDoctorReport, type KbDoctorThresholds, type KbEdgeKind, type KbImpactOptions, type KbImpactResult, type KbImpactedRecord, type KbInboundEdge, KbInvalidConceptIdError, type KbLink, type KbLinkEdge, type KbLinkRel, type KbLinkRelSpec, type KbLoadResult, type KbLogEntry, type KbLogReadResult, type KbLogger, type KbMergedPin, type KbMergedPins, KbMissingFlagValueError, type KbNeighbour, KbPackBudgetExceededError, type KbPackOptions, type KbPackResult, type KbPackedRecord, type KbPin, type KbPinLayer, type KbPinOptions, type KbPinResult, type KbPinStatus, KbPinsMalformedError, type KbPinsManifest, type KbRecord, KbRecordAlreadyExistsError, type KbRecordFrontmatter, KbRecordNotFoundError, type KbRecordStatus, type KbRecordType, type KbRecordTypeSpec, type KbSearchLogger, KbSelfVerificationError, type KbSource, type KbStanding, KbStore, type KbSupersededStub, type KbSyncResult, type KbTraceEdge, type KbTraceOptions, type KbTraceStep, KbUnknownLinkRelError, type KbValidationProblem, type KbValidationSeverity, type KbVerifiedEvent, type KbWarning, KbWriteConflictError, type KbWriteInput, LINK_RELS, LOG_FILE, type MatchOptions, NO_DECISION_SLUG, PINS_FILE, PINS_LOCAL_FILE, PIN_LAYERS, type QmdModule, RECORD_TYPES, type RemoteAnchorState, type RemoteOptions, type RemoteRead, type ResolvedSymbol, SEARCH_INDEX_FILE, type SearchHit, type SearchOptions, type SymbolRange, TRACE_EDGES, adjudicate, anchorFilePath, assertBaseNotFrozen, backlinks, buildContext, catalog, composeDecisionRecord, composeInputSchema, composeLinkSchema, composeNoDecisionRecord, composeRecord, contextProfileBudgets, createKbMcpServer, decisionInputSchema, detectAnchorDrift, doctor, edgeNeighbours, hashAnchorText, impact, inboundIndex, indexIsStale, isCanonicalRepoUrl, isKbLinkRel, isKbRecordType, isNoDecisionRecord, kbActorStampSchema, kbAnchorSchema, kbConceptIdSchema, kbJsonSchemas, kbLinkSchema, kbLogEntrySchema, kbRecordFrontmatterSchema, kbSourceSchema, kbVerifiedEventSchema, listPins, loadQmd, matchToDiff, mergedContextBudgets, neighbours, pack, parseLog, parseMarkdownWithFrontmatter, pinBase, readMergedPins, readPinsLayer, readRemoteAnchors, regexResolver, renderCatalogLine, renderIndex, renderIndexLine, renderLogEntry, repoCacheDir, resolveAnchor, resolveHeads, resolveHits, resolvePinPath, runKbCli, runKbMcpServer, searchBase, selectDecisions, splitMarkdownFrontmatter, stringifyMarkdownWithFrontmatter, syncInstructions, toHookJson, trace, unpinBase, validateBundle };
2674
+ export { type AnchorResolution, type AnchorResolver, type AnchorResolverName, BaseError, CONTEXT_BEGIN, CONTEXT_END, CONTEXT_PROFILES, type ClassifiedAnchor, type ComposeInput, type ComposeLink, type ComposedRecord, DECISION_TYPE, DEFAULT_AGING_DAYS, DEFAULT_EXPIRING_DAYS, DEFAULT_LOAD_BUDGET, DEFAULT_PACK_HOPS, DEFAULT_PACK_MAX_NODES, DEFAULT_TYPED_LINK_RELS, DEFAULT_UNVERIFIED_DAYS, type DecisionInput, type DiffFile, type DiffHunk, type DiffMatch, type ErrorDetails, type ErrorProps, ErrorTypes, Fault, type Grammar, type GrammarManifest, type GrammarOptions, INDEX_FILE, KB_CAUSAL_LINK_RELS, KB_COMMANDS, KB_COMMANDS_BY_NAME, KB_CONCEPT_ID_PATTERN, KB_CONFIDENCES, KB_DIR, KB_DOCTOR_CHECKS, KB_EDGE_KINDS, KB_LINK_RELS, KB_MATERIALITIES, KB_RECORD_STATUSES, KB_RECORD_TYPES, KB_SLUG_PATTERN, type KbActorStamp, type KbAdjudicated, type KbAnchor, type KbAnchorDriftEntry, type KbBacklink, type KbBacklinksResult, KbBaseFrozenError, type KbCatalogEntry, type KbCatalogResult, type KbCommand, type KbCommandContext, type KbContextBudgets, type KbContextOptions, type KbContextResult, type KbDoctorCheck, type KbDoctorFinding, type KbDoctorGroup, type KbDoctorOptions, type KbDoctorReport, type KbDoctorThresholds, type KbEdgeKind, type KbImpactOptions, type KbImpactResult, type KbImpactedRecord, type KbInboundEdge, KbInvalidConceptIdError, type KbLink, type KbLinkEdge, type KbLinkRel, type KbLinkRelSpec, type KbLoadResult, type KbLogEntry, type KbLogReadResult, type KbLogger, type KbMergedPin, type KbMergedPins, KbMissingFlagValueError, type KbNeighbour, KbPackBudgetExceededError, type KbPackOptions, type KbPackResult, type KbPackedRecord, type KbPin, type KbPinLayer, type KbPinOptions, type KbPinResult, type KbPinStatus, KbPinsMalformedError, type KbPinsManifest, type KbReassessAnchor, type KbReassessDefault, type KbReassessDiff, type KbReassessPacket, type KbRecord, KbRecordAlreadyExistsError, type KbRecordFrontmatter, KbRecordNotFoundError, type KbRecordStatus, type KbRecordType, type KbRecordTypeSpec, type KbSearchLogger, KbSelfVerificationError, type KbSource, type KbStanding, KbStore, type KbSupersededStub, type KbSyncResult, type KbTraceEdge, type KbTraceOptions, type KbTraceStep, KbUnknownLinkRelError, type KbValidationProblem, type KbValidationSeverity, type KbVerifiedEvent, type KbWarning, KbWriteConflictError, type KbWriteInput, LINK_RELS, LOG_FILE, type MatchOptions, NO_DECISION_SLUG, PINS_FILE, PINS_LOCAL_FILE, PIN_LAYERS, type QmdModule, RECORD_TYPES, type RemoteAnchorState, type RemoteOptions, type RemoteRead, type ResolvedSymbol, type ResolverAttempt, SEARCH_INDEX_FILE, type SearchHit, type SearchOptions, type SymbolRange, TRACE_EDGES, TreeSitterResolver, adjudicate, anchorFilePath, assertBaseNotFrozen, backlinks, buildContext, catalog, classifyDrift, composeDecisionRecord, composeInputSchema, composeLinkSchema, composeNoDecisionRecord, composeRecord, contextProfileBudgets, createKbMcpServer, decisionInputSchema, defaultAnchorResolvers, detectAnchorDrift, doctor, edgeNeighbours, ensureGrammar, grammarHints, grammarManifest, grammarsCacheRoot, hashAnchorText, impact, inboundIndex, indexIsStale, isCanonicalRepoUrl, isKbLinkRel, isKbRecordType, isNoDecisionRecord, kbActorStampSchema, kbAnchorSchema, kbConceptIdSchema, kbJsonSchemas, kbLinkSchema, kbLogEntrySchema, kbRecordFrontmatterSchema, kbSourceSchema, kbVerifiedEventSchema, languageForFile, listPins, loadQmd, matchToDiff, mergedContextBudgets, neighbours, pack, parseLog, parseMarkdownWithFrontmatter, pinBase, prepareResolvers, readMergedPins, readPinsLayer, readRemoteAnchors, reassessPacket, regexResolver, renderCatalogLine, renderIndex, renderIndexLine, renderLogEntry, repoCacheDir, resolveAnchor, resolveAnchorSpan, resolveHeads, resolveHits, resolvePinPath, runKbCli, runKbMcpServer, searchBase, selectDecisions, splitMarkdownFrontmatter, stringifyMarkdownWithFrontmatter, syncInstructions, toHookJson, trace, treeSitterLanguages, unifiedDiff, unpinBase, validateBundle };