@maind-dev/mcp-bridge 0.38.0 → 0.39.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/build/index.js CHANGED
@@ -202,7 +202,7 @@ var BRIDGE_VERSION;
202
202
  var init_version = __esm({
203
203
  "src/version.ts"() {
204
204
  "use strict";
205
- BRIDGE_VERSION = "0.38.0";
205
+ BRIDGE_VERSION = "0.39.0";
206
206
  }
207
207
  });
208
208
 
@@ -2281,6 +2281,698 @@ var init_number_collisions = __esm({
2281
2281
  }
2282
2282
  });
2283
2283
 
2284
+ // ../../packages/code-index/build/repo-health/spec-drift.js
2285
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
2286
+ import { posix as posix5 } from "node:path";
2287
+ function endOfString(src, i) {
2288
+ const quote = src[i];
2289
+ let j = i + 1;
2290
+ while (j < src.length) {
2291
+ const c = src[j];
2292
+ if (c === "\\") {
2293
+ j += 2;
2294
+ continue;
2295
+ }
2296
+ if (c === quote)
2297
+ return j + 1;
2298
+ j++;
2299
+ }
2300
+ return src.length;
2301
+ }
2302
+ function skipComment(src, i) {
2303
+ if (src.startsWith("//", i)) {
2304
+ const nl = src.indexOf("\n", i);
2305
+ return nl === -1 ? src.length : nl + 1;
2306
+ }
2307
+ if (src.startsWith("/*", i)) {
2308
+ const end = src.indexOf("*/", i + 2);
2309
+ return end === -1 ? src.length : end + 2;
2310
+ }
2311
+ return i + 1;
2312
+ }
2313
+ function isQuote(c) {
2314
+ return c === '"' || c === "'" || c === "`";
2315
+ }
2316
+ function isCommentStart(src, i) {
2317
+ return src[i] === "/" && (src[i + 1] === "/" || src[i + 1] === "*");
2318
+ }
2319
+ function sliceBalanced(src, start) {
2320
+ const open2 = src[start];
2321
+ if (open2 !== "[" && open2 !== "{")
2322
+ return null;
2323
+ let depth = 0;
2324
+ let i = start;
2325
+ while (i < src.length) {
2326
+ const c = src[i];
2327
+ if (isQuote(c)) {
2328
+ i = endOfString(src, i);
2329
+ continue;
2330
+ }
2331
+ if (isCommentStart(src, i)) {
2332
+ i = skipComment(src, i);
2333
+ continue;
2334
+ }
2335
+ if (c === "[" || c === "{")
2336
+ depth++;
2337
+ else if (c === "]" || c === "}") {
2338
+ depth--;
2339
+ if (depth === 0)
2340
+ return src.slice(start, i + 1);
2341
+ }
2342
+ i++;
2343
+ }
2344
+ return null;
2345
+ }
2346
+ function stripLeadingTrivia(s) {
2347
+ let i = 0;
2348
+ for (; ; ) {
2349
+ while (i < s.length && /\s/.test(s[i]))
2350
+ i++;
2351
+ if (isCommentStart(s, i)) {
2352
+ i = skipComment(s, i);
2353
+ continue;
2354
+ }
2355
+ break;
2356
+ }
2357
+ return s.slice(i);
2358
+ }
2359
+ function splitTopLevel(inner) {
2360
+ const parts = [];
2361
+ let depth = 0;
2362
+ let start = 0;
2363
+ let i = 0;
2364
+ while (i < inner.length) {
2365
+ const c = inner[i];
2366
+ if (isQuote(c)) {
2367
+ i = endOfString(inner, i);
2368
+ continue;
2369
+ }
2370
+ if (isCommentStart(inner, i)) {
2371
+ i = skipComment(inner, i);
2372
+ continue;
2373
+ }
2374
+ if (c === "[" || c === "{" || c === "(")
2375
+ depth++;
2376
+ else if (c === "]" || c === "}" || c === ")")
2377
+ depth--;
2378
+ else if (c === "," && depth === 0) {
2379
+ parts.push(inner.slice(start, i));
2380
+ start = i + 1;
2381
+ }
2382
+ i++;
2383
+ }
2384
+ parts.push(inner.slice(start));
2385
+ return parts.map((p) => stripLeadingTrivia(p).trim()).filter((p) => p.length > 0);
2386
+ }
2387
+ function readStringLiteral(text) {
2388
+ const end = endOfString(text, 0);
2389
+ const raw = text.slice(1, end - 1);
2390
+ return raw.replace(/\\(.)/g, (_, c) => c === "n" ? "\n" : c === "r" ? "\r" : c === "t" ? " " : c);
2391
+ }
2392
+ function escapeRe(s) {
2393
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2394
+ }
2395
+ function findSymbolArray(src, symbol) {
2396
+ const re = new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${escapeRe(symbol)}\b`, "m");
2397
+ const m = re.exec(src);
2398
+ if (!m)
2399
+ return null;
2400
+ let i = m.index + m[0].length;
2401
+ let assigned = false;
2402
+ while (i < src.length) {
2403
+ const c = src[i];
2404
+ if (isQuote(c)) {
2405
+ i = endOfString(src, i);
2406
+ continue;
2407
+ }
2408
+ if (isCommentStart(src, i)) {
2409
+ i = skipComment(src, i);
2410
+ continue;
2411
+ }
2412
+ if (!assigned) {
2413
+ if (c === "=" && src[i + 1] !== "=" && !"=!<>".includes(src[i - 1] ?? " ")) {
2414
+ assigned = true;
2415
+ } else if (c === ";") {
2416
+ return null;
2417
+ }
2418
+ i++;
2419
+ continue;
2420
+ }
2421
+ if (c === "[")
2422
+ return sliceBalanced(src, i);
2423
+ if (c === ";")
2424
+ return null;
2425
+ i++;
2426
+ }
2427
+ return null;
2428
+ }
2429
+ function parseObjectFields(objText) {
2430
+ const out2 = {};
2431
+ if (!objText.startsWith("{"))
2432
+ return out2;
2433
+ for (const part of splitTopLevel(objText.slice(1, -1))) {
2434
+ const m = /^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(part);
2435
+ if (!m)
2436
+ continue;
2437
+ const name = m[2] ?? m[3];
2438
+ const value = m[4].trim();
2439
+ if (isQuote(value[0] ?? ""))
2440
+ out2[name] = readStringLiteral(value);
2441
+ }
2442
+ return out2;
2443
+ }
2444
+ function objectFieldRaw(objText, field) {
2445
+ if (!objText.startsWith("{"))
2446
+ return null;
2447
+ for (const part of splitTopLevel(objText.slice(1, -1))) {
2448
+ const m = /^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(part);
2449
+ if (!m)
2450
+ continue;
2451
+ if ((m[2] ?? m[3]) === field)
2452
+ return m[4].trim();
2453
+ }
2454
+ return null;
2455
+ }
2456
+ function pickFields(all, declared) {
2457
+ if (!declared)
2458
+ return { ...all };
2459
+ const out2 = {};
2460
+ for (const name of declared)
2461
+ out2[name] = all[name] ?? "";
2462
+ return out2;
2463
+ }
2464
+ function makeOrdinals() {
2465
+ const counters = /* @__PURE__ */ new Map();
2466
+ return (orderPath) => {
2467
+ const k = orderPath.join("\0");
2468
+ const n = counters.get(k) ?? 0;
2469
+ counters.set(k, n + 1);
2470
+ return n;
2471
+ };
2472
+ }
2473
+ function extractObjectArray(src, decl) {
2474
+ const arr = findSymbolArray(src, decl.symbol);
2475
+ if (arr === null) {
2476
+ return {
2477
+ records: [],
2478
+ error: `no array literal assigned to \`${decl.symbol}\` in ${decl.path}`,
2479
+ dropped: 0
2480
+ };
2481
+ }
2482
+ const nextOrdinal = makeOrdinals();
2483
+ const records = [];
2484
+ let dropped = 0;
2485
+ for (const part of splitTopLevel(arr.slice(1, -1))) {
2486
+ if (!part.startsWith("{")) {
2487
+ dropped++;
2488
+ continue;
2489
+ }
2490
+ const all = parseObjectFields(part);
2491
+ const key = all[decl.key_field];
2492
+ if (!key) {
2493
+ dropped++;
2494
+ continue;
2495
+ }
2496
+ const orderPath = (decl.partition_by ?? []).map((f) => all[f] ?? "");
2497
+ records.push({ key, fields: pickFields(all, decl.fields), orderPath, ordinal: nextOrdinal(orderPath) });
2498
+ }
2499
+ if (records.length === 0) {
2500
+ return {
2501
+ records: [],
2502
+ error: `\`${decl.symbol}\` in ${decl.path} yielded no parsable records`,
2503
+ dropped
2504
+ };
2505
+ }
2506
+ return { records, error: null, dropped };
2507
+ }
2508
+ function extractNestedList(src, decl) {
2509
+ const arr = findSymbolArray(src, decl.symbol);
2510
+ if (arr === null) {
2511
+ return {
2512
+ records: [],
2513
+ error: `no array literal assigned to \`${decl.symbol}\` in ${decl.path}`,
2514
+ dropped: 0
2515
+ };
2516
+ }
2517
+ if (decl.levels.length === 0) {
2518
+ return { records: [], error: `contract declares no levels for \`${decl.symbol}\``, dropped: 0 };
2519
+ }
2520
+ const nextOrdinal = makeOrdinals();
2521
+ const records = [];
2522
+ let dropped = 0;
2523
+ const walk2 = (arrayText, depth, inherited) => {
2524
+ const level = decl.levels[depth];
2525
+ const isLeaf = depth === decl.levels.length - 1;
2526
+ for (const element of splitTopLevel(arrayText.slice(1, -1))) {
2527
+ const own = { ...inherited };
2528
+ let childText = null;
2529
+ if (level.shape === "object") {
2530
+ if (!element.startsWith("{")) {
2531
+ dropped++;
2532
+ continue;
2533
+ }
2534
+ const all = parseObjectFields(element);
2535
+ for (const [out2, from] of Object.entries(level.fields ?? {})) {
2536
+ own[out2] = all[String(from)] ?? "";
2537
+ }
2538
+ if (!isLeaf && typeof level.children === "string") {
2539
+ const raw = objectFieldRaw(element, level.children);
2540
+ childText = raw && raw.startsWith("[") ? sliceBalanced(raw, 0) : null;
2541
+ }
2542
+ } else {
2543
+ if (!element.startsWith("[")) {
2544
+ dropped++;
2545
+ continue;
2546
+ }
2547
+ const parts = splitTopLevel(element.slice(1, -1));
2548
+ for (const [out2, from] of Object.entries(level.fields ?? {})) {
2549
+ const at = parts[Number(from)];
2550
+ own[out2] = at !== void 0 && isQuote(at[0] ?? "") ? readStringLiteral(at) : "";
2551
+ }
2552
+ if (!isLeaf && typeof level.children === "number") {
2553
+ const at = parts[level.children];
2554
+ childText = at !== void 0 && at.startsWith("[") ? sliceBalanced(at, 0) : null;
2555
+ }
2556
+ }
2557
+ if (isLeaf) {
2558
+ const key = own[decl.key_field];
2559
+ if (!key) {
2560
+ dropped++;
2561
+ continue;
2562
+ }
2563
+ const orderPath = (decl.partition_by ?? []).map((f) => own[f] ?? "");
2564
+ records.push({
2565
+ key,
2566
+ fields: pickFields(own, decl.fields),
2567
+ orderPath,
2568
+ ordinal: nextOrdinal(orderPath)
2569
+ });
2570
+ continue;
2571
+ }
2572
+ if (childText !== null)
2573
+ walk2(childText, depth + 1, own);
2574
+ }
2575
+ };
2576
+ walk2(arr, 0, {});
2577
+ if (records.length === 0) {
2578
+ return {
2579
+ records: [],
2580
+ error: `\`${decl.symbol}\` in ${decl.path} yielded no parsable records`,
2581
+ dropped
2582
+ };
2583
+ }
2584
+ return { records, error: null, dropped };
2585
+ }
2586
+ function extractRecords(src, decl) {
2587
+ return decl.extractor === "object-array" ? extractObjectArray(src, decl) : extractNestedList(src, decl);
2588
+ }
2589
+ function isGrounded(key, decl, files) {
2590
+ let slug = key;
2591
+ if (decl.strip_prefix && slug.startsWith(decl.strip_prefix)) {
2592
+ slug = slug.slice(decl.strip_prefix.length);
2593
+ }
2594
+ return decl.templates.some((t) => files.has(t.replace("{key}", slug).replace(/\/{2,}/g, "/")));
2595
+ }
2596
+ function findingId(contract, dimension, key) {
2597
+ return `spec.drift:${contract}#${dimension}:${key}`;
2598
+ }
2599
+ function partitionOf(r) {
2600
+ return r.orderPath.join(" / ") || "(flat)";
2601
+ }
2602
+ function compareContract(contract, spec, impl, files) {
2603
+ const out2 = [];
2604
+ const push = (dimension, status, key, title, detail, hint) => {
2605
+ out2.push({ id: findingId(contract.id, dimension, key), contract: contract.id, dimension, status, key, title, detail, hint });
2606
+ };
2607
+ const implByKey = new Map(impl.map((r) => [r.key, r]));
2608
+ const specByKey = new Map(spec.map((r) => [r.key, r]));
2609
+ for (const s of spec) {
2610
+ const i = implByKey.get(s.key);
2611
+ if (!i) {
2612
+ push("coverage", "open", s.key, `${s.key} is declared by the specification but missing from the implementation`, `Partition ${partitionOf(s)}, position ${s.ordinal + 1}. The specification is the reference; add it or record an exception with a reason.`, "On a contradiction the specification wins \u2014 read it rather than a summary of it.");
2613
+ continue;
2614
+ }
2615
+ for (const field of contract.compare_fields ?? []) {
2616
+ const want = s.fields[field] ?? "";
2617
+ const got = i.fields[field] ?? "";
2618
+ if (want !== got) {
2619
+ push("fields", "open", `${s.key}.${field}`, `${s.key}: ${field} is "${got || "\u2014"}", the specification says "${want || "\u2014"}"`, `Field \`${field}\` disagrees between the two sides.`);
2620
+ }
2621
+ }
2622
+ }
2623
+ const partitions = /* @__PURE__ */ new Map();
2624
+ for (const s of spec) {
2625
+ const k = s.orderPath.join("\0");
2626
+ const bucket = partitions.get(k);
2627
+ if (bucket)
2628
+ bucket.push(s);
2629
+ else
2630
+ partitions.set(k, [s]);
2631
+ }
2632
+ for (const [pk, specPart] of partitions) {
2633
+ const specOrder = specPart.filter((s) => implByKey.has(s.key)).map((s) => s.key);
2634
+ const implOrder = impl.filter((r) => r.orderPath.join("\0") === pk).filter((r) => specByKey.has(r.key)).map((r) => r.key);
2635
+ const common = new Set(implOrder);
2636
+ const expected = specOrder.filter((k) => common.has(k));
2637
+ if (implOrder.join("|") !== expected.join("|")) {
2638
+ const label = pk.split("\0").join(" / ") || "(flat)";
2639
+ push("order", "open", label, `Partition ${label}: sequence differs from the specification`, `implementation: ${implOrder.join(" \u2192 ")}
2640
+ specification: ${expected.join(" \u2192 ")}`, "Order is declared explicitly by the specification and is not derivable from a flat list.");
2641
+ }
2642
+ }
2643
+ for (const i of impl) {
2644
+ if (specByKey.has(i.key))
2645
+ continue;
2646
+ push("extra", "warn", i.key, `${i.key} is in the implementation but not declared by the specification`, `Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.`);
2647
+ }
2648
+ if (contract.grounding) {
2649
+ for (const key of /* @__PURE__ */ new Set([...implByKey.keys(), ...specByKey.keys()])) {
2650
+ if (isGrounded(key, contract.grounding, files))
2651
+ continue;
2652
+ const inImpl = implByKey.has(key);
2653
+ push("unrealized", inImpl ? "open" : "warn", key, inImpl ? `${key} is referenced by the implementation but has no artefact` : `${key} is declared by the specification but not built yet`, inImpl ? `No file matches ${contract.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.` : `The specification is ahead of the code here. Legitimate, but it should be named.`);
2654
+ }
2655
+ }
2656
+ return out2;
2657
+ }
2658
+ function checkAssertions(contract, counts, texts) {
2659
+ const out2 = [];
2660
+ for (const a of contract.assertions ?? []) {
2661
+ const text = texts.get(a.path);
2662
+ if (!text)
2663
+ continue;
2664
+ const at = text.indexOf(a.prefix);
2665
+ if (at === -1)
2666
+ continue;
2667
+ const m = /^\s*(\d+)/.exec(text.slice(at + a.prefix.length));
2668
+ if (!m)
2669
+ continue;
2670
+ const found = Number(m[1]);
2671
+ const want = counts[a.counts];
2672
+ if (found === want)
2673
+ continue;
2674
+ out2.push({
2675
+ id: `spec.drift:${contract.id}#assertion:${a.path}`,
2676
+ contract: contract.id,
2677
+ dimension: "assertion",
2678
+ status: "warn",
2679
+ key: a.path,
2680
+ title: `${a.path} states ${found} where the ${a.counts} side has ${want}`,
2681
+ detail: `Counted after "${a.prefix}". ${a.reason}`,
2682
+ hint: "Prose only \u2014 nothing behaves differently because of this number."
2683
+ });
2684
+ }
2685
+ return out2;
2686
+ }
2687
+ function unreadable(contractId, detail) {
2688
+ return {
2689
+ // Own id namespace, and the text deliberately never says "drift": a broken
2690
+ // pointer means WE COULD NOT MEASURE, which is a different fact from
2691
+ // "the two sides disagree". Conflating them is how a gate earns a
2692
+ // reputation for crying wolf and gets switched off.
2693
+ id: `contract.unreadable:${contractId}`,
2694
+ contract: contractId,
2695
+ dimension: "contract",
2696
+ status: "open",
2697
+ key: null,
2698
+ title: `Contract "${contractId}" could not be evaluated`,
2699
+ detail,
2700
+ hint: "This is NOT a drift finding. An anchor moved, or a declared file is gone \u2014 repair the contract in the manifest, then re-run. Nothing has been compared for this contract."
2701
+ };
2702
+ }
2703
+ function computeSpecDrift(facts, opts = {}) {
2704
+ const abstain = (reason) => ({
2705
+ ok: false,
2706
+ verdict: "no_opinion",
2707
+ reason,
2708
+ findings: [],
2709
+ contracts: []
2710
+ });
2711
+ if (!facts.isRepo)
2712
+ return abstain("not a git work tree");
2713
+ if (!facts.manifest) {
2714
+ return abstain(facts.manifestError ?? `no contract could be read from ${facts.manifestPath}`);
2715
+ }
2716
+ const selected = opts.contracts?.length ? facts.manifest.contracts.filter((c) => opts.contracts.includes(c.id)) : facts.manifest.contracts;
2717
+ if (selected.length === 0) {
2718
+ return abstain(opts.contracts?.length ? `no contract in ${facts.manifestPath} matches ${opts.contracts.map((c) => `"${c}"`).join(", ")} \u2014 nothing was compared` : `${facts.manifestPath} declares no contract \u2014 nothing was compared`);
2719
+ }
2720
+ const runOnce = (sources) => {
2721
+ const findings2 = [];
2722
+ const contracts = [];
2723
+ for (const contract of selected) {
2724
+ const specText = sources.get(contract.spec.path);
2725
+ const implText = sources.get(contract.impl.path);
2726
+ if (specText == null || implText == null) {
2727
+ const missing = specText == null ? contract.spec.path : contract.impl.path;
2728
+ findings2.push(unreadable(contract.id, `Declared file could not be read: ${missing}`));
2729
+ contracts.push({ id: contract.id, measured: false, specRecords: 0, implRecords: 0, partial: false });
2730
+ continue;
2731
+ }
2732
+ const specRes = extractRecords(specText, contract.spec);
2733
+ const implRes = extractRecords(implText, contract.impl);
2734
+ if (specRes.error || implRes.error) {
2735
+ findings2.push(unreadable(contract.id, specRes.error ?? implRes.error ?? "unknown"));
2736
+ contracts.push({ id: contract.id, measured: false, specRecords: 0, implRecords: 0, partial: false });
2737
+ continue;
2738
+ }
2739
+ const partial = specRes.dropped > 0 || implRes.dropped > 0;
2740
+ contracts.push({
2741
+ id: contract.id,
2742
+ measured: true,
2743
+ specRecords: specRes.records.length,
2744
+ implRecords: implRes.records.length,
2745
+ partial
2746
+ });
2747
+ if (partial) {
2748
+ findings2.push({
2749
+ id: `contract.partial:${contract.id}`,
2750
+ contract: contract.id,
2751
+ dimension: "contract",
2752
+ status: "warn",
2753
+ key: null,
2754
+ title: `Contract "${contract.id}" was measured incompletely`,
2755
+ detail: `${specRes.dropped} specification and ${implRes.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,
2756
+ hint: "Not a drift finding. Check whether the declared shape still matches the file."
2757
+ });
2758
+ }
2759
+ findings2.push(...compareContract(contract, specRes.records, implRes.records, facts.files));
2760
+ findings2.push(...checkAssertions(contract, { spec: specRes.records.length, impl: implRes.records.length }, sources));
2761
+ }
2762
+ return { findings: findings2, contracts };
2763
+ };
2764
+ const current = runOnce(facts.sources);
2765
+ const baselineIds = /* @__PURE__ */ new Set();
2766
+ if (opts.includeBaseline !== false && facts.baseRef && facts.baselineSources.size > 0) {
2767
+ for (const f of runOnce(facts.baselineSources).findings) {
2768
+ if (!f.id.startsWith("contract.unreadable:"))
2769
+ baselineIds.add(f.id);
2770
+ }
2771
+ }
2772
+ const exceptionByKey = /* @__PURE__ */ new Map();
2773
+ for (const c of selected) {
2774
+ for (const e of c.exceptions ?? [])
2775
+ exceptionByKey.set(findingId(c.id, e.dimension, e.key), e);
2776
+ }
2777
+ const findings = current.findings.map((f) => {
2778
+ const exception = exceptionByKey.get(f.id);
2779
+ if (exception) {
2780
+ return { ...f, status: "info", exceptionReason: exception.reason };
2781
+ }
2782
+ if (baselineIds.has(f.id)) {
2783
+ return {
2784
+ ...f,
2785
+ status: "info",
2786
+ detail: `${f.detail}
2787
+ Pre-existing at ${facts.baseRef} \u2014 inventory, not introduced by this branch.`
2788
+ };
2789
+ }
2790
+ return f;
2791
+ });
2792
+ findings.sort((a, b) => STATUS_ORDER2[a.status] - STATUS_ORDER2[b.status] || a.id.localeCompare(b.id));
2793
+ const drifted = findings.some((f) => f.status === "open");
2794
+ return {
2795
+ ok: !drifted,
2796
+ verdict: drifted ? "drifted" : "aligned",
2797
+ reason: null,
2798
+ findings,
2799
+ contracts: current.contracts
2800
+ };
2801
+ }
2802
+ function trimOrNull3(s) {
2803
+ const t = s?.trim();
2804
+ return t ? t : null;
2805
+ }
2806
+ function parseManifest(raw) {
2807
+ let parsed;
2808
+ try {
2809
+ parsed = JSON.parse(raw);
2810
+ } catch (e) {
2811
+ return { manifest: null, error: `manifest is not valid JSON: ${e.message}` };
2812
+ }
2813
+ const obj = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
2814
+ const str2 = (v) => typeof v === "string" ? v : "";
2815
+ const root = obj(parsed);
2816
+ if (!root || !Array.isArray(root.contracts)) {
2817
+ return { manifest: null, error: "manifest has no `contracts` array" };
2818
+ }
2819
+ const bad = (error) => ({ manifest: null, error });
2820
+ for (const [ix, raw2] of root.contracts.entries()) {
2821
+ const c = obj(raw2);
2822
+ const id = str2(c?.id);
2823
+ const where = id ? `contract "${id}"` : `contract #${ix + 1}`;
2824
+ if (!c)
2825
+ return bad(`${where}: not an object`);
2826
+ if (!id)
2827
+ return bad(`${where}: \`id\` is missing`);
2828
+ if (!str2(c.reason)) {
2829
+ return bad(`${where}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);
2830
+ }
2831
+ for (const side of ["spec", "impl"]) {
2832
+ const d = obj(c[side]);
2833
+ if (!d)
2834
+ return bad(`${where}: \`${side}\` is missing`);
2835
+ const extractor = str2(d.extractor);
2836
+ if (!extractor)
2837
+ return bad(`${where}: \`${side}.extractor\` is missing`);
2838
+ if (extractor !== "object-array" && extractor !== "nested-literal-list") {
2839
+ return bad(`${where}: unknown \`${side}.extractor\` "${extractor}"`);
2840
+ }
2841
+ if (!str2(d.path) || !str2(d.symbol) || !str2(d.key_field)) {
2842
+ return bad(`${where}: \`${side}\` needs \`path\`, \`symbol\` and \`key_field\``);
2843
+ }
2844
+ if (extractor === "nested-literal-list" && !Array.isArray(d.levels)) {
2845
+ return bad(`${where}: \`${side}\` is a nested-literal-list and needs \`levels\``);
2846
+ }
2847
+ }
2848
+ for (const rawE of Array.isArray(c.exceptions) ? c.exceptions : []) {
2849
+ const e = obj(rawE);
2850
+ if (!e || !str2(e.reason)) {
2851
+ return bad(`${where}: exception for "${str2(e?.key) || "?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`);
2852
+ }
2853
+ }
2854
+ }
2855
+ return { manifest: root, error: null };
2856
+ }
2857
+ function resolveDefaultBranch3(repoRoot) {
2858
+ const sym = trimOrNull3(runGit(repoRoot, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]));
2859
+ if (sym) {
2860
+ const m = /refs\/remotes\/origin\/(.+)$/.exec(sym);
2861
+ if (m)
2862
+ return m[1];
2863
+ }
2864
+ for (const cand of ["main", "master"]) {
2865
+ if (runGit(repoRoot, ["rev-parse", "--verify", "--quiet", `origin/${cand}`]) !== null)
2866
+ return cand;
2867
+ }
2868
+ return null;
2869
+ }
2870
+ function declaredPaths(manifest) {
2871
+ const out2 = /* @__PURE__ */ new Set();
2872
+ for (const c of manifest.contracts) {
2873
+ out2.add(c.spec.path);
2874
+ out2.add(c.impl.path);
2875
+ for (const a of c.assertions ?? [])
2876
+ out2.add(a.path);
2877
+ }
2878
+ return [...out2];
2879
+ }
2880
+ async function gatherSpecDriftFacts(repoRoot, opts = {}) {
2881
+ const join28 = (a, b) => posix5.join(a, b);
2882
+ const manifestPath = opts.manifestPath ?? DEFAULT_MANIFEST_RELPATH;
2883
+ const skipped = [];
2884
+ const empty = {
2885
+ isRepo: false,
2886
+ manifestPath,
2887
+ manifest: null,
2888
+ manifestError: null,
2889
+ sources: /* @__PURE__ */ new Map(),
2890
+ baselineSources: /* @__PURE__ */ new Map(),
2891
+ baseRef: null,
2892
+ files: /* @__PURE__ */ new Set(),
2893
+ skipped
2894
+ };
2895
+ if (trimOrNull3(runGit(repoRoot, ["rev-parse", "--is-inside-work-tree"])) !== "true") {
2896
+ return { ...empty, manifestError: "not a git work tree" };
2897
+ }
2898
+ const abs = join28(repoRoot, manifestPath);
2899
+ if (!existsSync6(abs)) {
2900
+ return {
2901
+ ...empty,
2902
+ isRepo: true,
2903
+ manifestError: `no manifest at ${manifestPath} \u2014 nothing is declared, so nothing is asserted`
2904
+ };
2905
+ }
2906
+ let manifest = null;
2907
+ let manifestError = null;
2908
+ try {
2909
+ ({ manifest, error: manifestError } = parseManifest(readFileSync5(abs, "utf8")));
2910
+ } catch (e) {
2911
+ manifestError = `manifest at ${manifestPath} could not be read: ${e.message}`;
2912
+ }
2913
+ if (!manifest) {
2914
+ return { ...empty, isRepo: true, manifestError };
2915
+ }
2916
+ const sources = /* @__PURE__ */ new Map();
2917
+ for (const p of declaredPaths(manifest)) {
2918
+ try {
2919
+ sources.set(p, readFileSync5(join28(repoRoot, p), "utf8"));
2920
+ } catch {
2921
+ sources.set(p, null);
2922
+ skipped.push(`declared file unreadable in the working tree: ${p}`);
2923
+ }
2924
+ }
2925
+ const files = /* @__PURE__ */ new Set();
2926
+ const listed = runGit(repoRoot, ["ls-files", "-z"]);
2927
+ if (listed === null)
2928
+ skipped.push("could not list tracked files \u2014 grounding is skipped");
2929
+ else
2930
+ for (const f of listed.split("\0"))
2931
+ if (f)
2932
+ files.add(f);
2933
+ let baseRef = null;
2934
+ const baselineSources = /* @__PURE__ */ new Map();
2935
+ if (opts.includeBaseline !== false) {
2936
+ const defaultBranch = resolveDefaultBranch3(repoRoot);
2937
+ if (!defaultBranch) {
2938
+ skipped.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");
2939
+ } else {
2940
+ baseRef = trimOrNull3(runGit(repoRoot, ["merge-base", `origin/${defaultBranch}`, "HEAD"]));
2941
+ if (!baseRef) {
2942
+ skipped.push(`no merge-base with origin/${defaultBranch} \u2014 every finding reported as new`);
2943
+ } else {
2944
+ for (const p of sources.keys()) {
2945
+ baselineSources.set(p, runGit(repoRoot, ["show", `${baseRef}:${p}`]));
2946
+ }
2947
+ }
2948
+ }
2949
+ }
2950
+ return {
2951
+ isRepo: true,
2952
+ manifestPath,
2953
+ manifest,
2954
+ manifestError: null,
2955
+ sources,
2956
+ baselineSources,
2957
+ baseRef,
2958
+ files,
2959
+ skipped
2960
+ };
2961
+ }
2962
+ async function checkSpecDrift(repoRoot, opts = {}) {
2963
+ const facts = await gatherSpecDriftFacts(repoRoot, opts);
2964
+ return { ...computeSpecDrift(facts, opts), facts };
2965
+ }
2966
+ var DEFAULT_MANIFEST_RELPATH, STATUS_ORDER2;
2967
+ var init_spec_drift = __esm({
2968
+ "../../packages/code-index/build/repo-health/spec-drift.js"() {
2969
+ "use strict";
2970
+ init_discover();
2971
+ DEFAULT_MANIFEST_RELPATH = ".maind/spec-contracts.json";
2972
+ STATUS_ORDER2 = { open: 0, warn: 1, info: 2, passed: 3 };
2973
+ }
2974
+ });
2975
+
2284
2976
  // ../../packages/code-index/build/review/risk-rules.js
2285
2977
  var RISK_RULES;
2286
2978
  var init_risk_rules = __esm({
@@ -2471,8 +3163,8 @@ var init_identifiers = __esm({
2471
3163
  });
2472
3164
 
2473
3165
  // ../../packages/code-index/build/query/engine.js
2474
- import { readFileSync as readFileSync5 } from "node:fs";
2475
- import { posix as posix5 } from "node:path";
3166
+ import { readFileSync as readFileSync6 } from "node:fs";
3167
+ import { posix as posix6 } from "node:path";
2476
3168
  function toHit(n) {
2477
3169
  return {
2478
3170
  nodeKey: n.nodeKey,
@@ -2533,6 +3225,7 @@ var init_engine = __esm({
2533
3225
  init_history();
2534
3226
  init_divergence();
2535
3227
  init_number_collisions();
3228
+ init_spec_drift();
2536
3229
  init_risk_scan();
2537
3230
  init_schema();
2538
3231
  init_identifiers();
@@ -2753,7 +3446,7 @@ var init_engine = __esm({
2753
3446
  return null;
2754
3447
  let source = "";
2755
3448
  try {
2756
- const full = readFileSync5(posix5.join(this.repoRoot, n.filePath), "utf8");
3449
+ const full = readFileSync6(posix6.join(this.repoRoot, n.filePath), "utf8");
2757
3450
  source = full.slice(n.startByte, n.endByte);
2758
3451
  } catch {
2759
3452
  return null;
@@ -2830,6 +3523,9 @@ var init_engine = __esm({
2830
3523
  async checkNumberForPath(proposedPath, opts = {}) {
2831
3524
  return checkNumberForPath(this.repoRoot, proposedPath, opts);
2832
3525
  }
3526
+ async checkSpecDrift(opts = {}) {
3527
+ return checkSpecDrift(this.repoRoot, opts);
3528
+ }
2833
3529
  async reviewChanges(opts = {}) {
2834
3530
  await this.store.init();
2835
3531
  const rawPaths = enumerateChangedPaths(this.repoRoot, opts);
@@ -2893,7 +3589,7 @@ var init_engine = __esm({
2893
3589
  }
2894
3590
  readRepoFile(relPath) {
2895
3591
  try {
2896
- return readFileSync5(posix5.join(this.repoRoot, relPath), "utf8");
3592
+ return readFileSync6(posix6.join(this.repoRoot, relPath), "utf8");
2897
3593
  } catch {
2898
3594
  return null;
2899
3595
  }
@@ -2926,6 +3622,7 @@ var init_build = __esm({
2926
3622
  init_divergence();
2927
3623
  init_hooks();
2928
3624
  init_number_collisions();
3625
+ init_spec_drift();
2929
3626
  init_types();
2930
3627
  init_types2();
2931
3628
  init_schema();
@@ -3171,7 +3868,7 @@ var init_presence = __esm({
3171
3868
  import {
3172
3869
  mkdirSync as mkdirSync4,
3173
3870
  readdirSync as readdirSync4,
3174
- readFileSync as readFileSync7,
3871
+ readFileSync as readFileSync8,
3175
3872
  renameSync as renameSync2,
3176
3873
  statSync as statSync3,
3177
3874
  unlinkSync,
@@ -3275,7 +3972,7 @@ function readSnapshots(projectKey, baseDir = presenceSnapshotBaseDir()) {
3275
3972
  if (!name.endsWith(".json")) continue;
3276
3973
  try {
3277
3974
  const raw = JSON.parse(
3278
- readFileSync7(join14(dir, name), "utf8")
3975
+ readFileSync8(join14(dir, name), "utf8")
3279
3976
  );
3280
3977
  const snap = parseSnapshot(raw);
3281
3978
  if (snap) out2.push(snap);
@@ -3325,10 +4022,10 @@ var init_presence_snapshot = __esm({
3325
4022
  import { execFileSync as execFileSync7 } from "node:child_process";
3326
4023
  import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
3327
4024
  import {
3328
- existsSync as existsSync7,
4025
+ existsSync as existsSync8,
3329
4026
  mkdirSync as mkdirSync5,
3330
4027
  readdirSync as readdirSync5,
3331
- readFileSync as readFileSync8,
4028
+ readFileSync as readFileSync9,
3332
4029
  renameSync as renameSync3,
3333
4030
  statSync as statSync4,
3334
4031
  unlinkSync as unlinkSync2,
@@ -3394,12 +4091,12 @@ function pruneIdentityDir(dir, nowMs) {
3394
4091
  function readAgentIdentityFile(opts) {
3395
4092
  const file = join15(opts.dir, `${opts.agentPid}.json`);
3396
4093
  try {
3397
- if (!existsSync7(file)) return null;
4094
+ if (!existsSync8(file)) return null;
3398
4095
  const st = statSync4(file);
3399
4096
  if (st.mtimeMs < opts.bridgeStartMs - IDENTITY_MAX_AGE_SLACK_MS) {
3400
4097
  return null;
3401
4098
  }
3402
- const parsed = JSON.parse(readFileSync8(file, "utf8"));
4099
+ const parsed = JSON.parse(readFileSync9(file, "utf8"));
3403
4100
  if (typeof parsed !== "object" || parsed === null) return null;
3404
4101
  const o = parsed;
3405
4102
  if (o.v !== 1) return null;
@@ -3548,11 +4245,11 @@ var init_types4 = __esm({
3548
4245
  });
3549
4246
 
3550
4247
  // ../../packages/claude-code-telemetry/dist/transcript.js
3551
- import { createReadStream, existsSync as existsSync8 } from "node:fs";
4248
+ import { createReadStream, existsSync as existsSync9 } from "node:fs";
3552
4249
  import { stat } from "node:fs/promises";
3553
4250
  import { createInterface as createInterface5 } from "node:readline";
3554
4251
  async function summariseTranscript(path8) {
3555
- if (!path8 || !existsSync8(path8))
4252
+ if (!path8 || !existsSync9(path8))
3556
4253
  return null;
3557
4254
  let stats;
3558
4255
  try {
@@ -3637,7 +4334,7 @@ var init_effort = __esm({
3637
4334
  });
3638
4335
 
3639
4336
  // ../../packages/claude-code-telemetry/dist/session-analysis.js
3640
- import { createReadStream as createReadStream2, existsSync as existsSync9 } from "node:fs";
4337
+ import { createReadStream as createReadStream2, existsSync as existsSync10 } from "node:fs";
3641
4338
  import { createInterface as createInterface6 } from "node:readline";
3642
4339
  function num2(v) {
3643
4340
  return typeof v === "number" && Number.isFinite(v) ? v : 0;
@@ -3744,7 +4441,7 @@ function emptyAnalysis(sessionId) {
3744
4441
  }
3745
4442
  async function analyzeSession(path8) {
3746
4443
  const a = emptyAnalysis("");
3747
- if (!path8 || !existsSync9(path8))
4444
+ if (!path8 || !existsSync10(path8))
3748
4445
  return a;
3749
4446
  const reactions = [];
3750
4447
  const modelMix = /* @__PURE__ */ new Map();
@@ -3940,7 +4637,7 @@ var init_ingest = __esm({
3940
4637
  });
3941
4638
 
3942
4639
  // ../../packages/claude-code-telemetry/dist/session-span.js
3943
- import { createReadStream as createReadStream3, existsSync as existsSync10 } from "node:fs";
4640
+ import { createReadStream as createReadStream3, existsSync as existsSync11 } from "node:fs";
3944
4641
  import { createInterface as createInterface7 } from "node:readline";
3945
4642
  function asBlocks2(content) {
3946
4643
  if (typeof content === "string")
@@ -3992,7 +4689,7 @@ function classify2(parsed) {
3992
4689
  }
3993
4690
  async function analyzeSpan(path8) {
3994
4691
  const s = emptySpan("");
3995
- if (!path8 || !existsSync10(path8))
4692
+ if (!path8 || !existsSync11(path8))
3996
4693
  return s;
3997
4694
  let firstMs = null;
3998
4695
  let lastMs = 0;
@@ -4359,14 +5056,14 @@ var init_payloads = __esm({
4359
5056
 
4360
5057
  // src/hooks/state.ts
4361
5058
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, rename as rename2 } from "node:fs/promises";
4362
- import { existsSync as existsSync11 } from "node:fs";
5059
+ import { existsSync as existsSync12 } from "node:fs";
4363
5060
  import { homedir as homedir6 } from "node:os";
4364
5061
  import { join as join17 } from "node:path";
4365
5062
  function emptyState() {
4366
5063
  return { config: null, sessions: {}, pending_metrics: [] };
4367
5064
  }
4368
5065
  async function loadState() {
4369
- if (!existsSync11(STATE_FILE)) return emptyState();
5066
+ if (!existsSync12(STATE_FILE)) return emptyState();
4370
5067
  try {
4371
5068
  const raw = await readFile2(STATE_FILE, "utf-8");
4372
5069
  const parsed = JSON.parse(raw);
@@ -4387,7 +5084,7 @@ async function loadState() {
4387
5084
  }
4388
5085
  }
4389
5086
  async function saveState(state) {
4390
- if (!existsSync11(STATE_DIR)) {
5087
+ if (!existsSync12(STATE_DIR)) {
4391
5088
  await mkdir2(STATE_DIR, { recursive: true, mode: 448 });
4392
5089
  }
4393
5090
  const tmp = `${STATE_FILE}.tmp`;
@@ -4428,7 +5125,7 @@ __export(hooks_exports, {
4428
5125
  runSyncConfig: () => runSyncConfig
4429
5126
  });
4430
5127
  import { execFileSync as execFileSync8 } from "node:child_process";
4431
- import { existsSync as existsSync12, readFileSync as readFileSync9, realpathSync as realpathSync2 } from "node:fs";
5128
+ import { existsSync as existsSync13, readFileSync as readFileSync10, realpathSync as realpathSync2 } from "node:fs";
4432
5129
  import { writeFile as writeFile3 } from "node:fs/promises";
4433
5130
  import { homedir as homedir7 } from "node:os";
4434
5131
  import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute4, join as join18, relative as relative3 } from "node:path";
@@ -4557,7 +5254,7 @@ async function runOnSessionStart() {
4557
5254
  function readSettingsRaw() {
4558
5255
  try {
4559
5256
  const p = join18(homedir7(), ".claude", "settings.json");
4560
- return existsSync12(p) ? readFileSync9(p, "utf8") : null;
5257
+ return existsSync13(p) ? readFileSync10(p, "utf8") : null;
4561
5258
  } catch {
4562
5259
  return null;
4563
5260
  }
@@ -4653,7 +5350,7 @@ async function runOnFileWrite() {
4653
5350
  if (!filePath) return 0;
4654
5351
  const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
4655
5352
  const abs = isAbsolute4(filePath) ? filePath : join18(cwd, filePath);
4656
- if (existsSync12(abs)) return 0;
5353
+ if (existsSync13(abs)) return 0;
4657
5354
  const repoRoot = resolveRepoRoot(cwd);
4658
5355
  const rel = relative3(repoRoot, realpathOfUnwritten(abs));
4659
5356
  if (rel.length === 0 || rel.startsWith("..") || isAbsolute4(rel)) return 0;
@@ -4684,7 +5381,7 @@ async function runOnFileEdit() {
4684
5381
  });
4685
5382
  if (own === null) return 0;
4686
5383
  const repoRoot = resolveRepoRoot(cwd);
4687
- const real = existsSync12(abs) ? realpathSync2(abs) : realpathOfUnwritten(abs);
5384
+ const real = existsSync13(abs) ? realpathSync2(abs) : realpathOfUnwritten(abs);
4688
5385
  const rel = relative3(repoRoot, real).replace(/\\/g, "/");
4689
5386
  if (rel.length === 0 || rel.startsWith("..") || isAbsolute4(rel)) return 0;
4690
5387
  const advice = adviseOnPath(own.snap, rel, {
@@ -4859,7 +5556,7 @@ function readHookWiring() {
4859
5556
  const settingsPath = join18(homedir7(), ".claude", "settings.json");
4860
5557
  let raw = null;
4861
5558
  try {
4862
- if (existsSync12(settingsPath)) raw = readFileSync9(settingsPath, "utf8");
5559
+ if (existsSync13(settingsPath)) raw = readFileSync10(settingsPath, "utf8");
4863
5560
  } catch {
4864
5561
  }
4865
5562
  return { settingsPath, findings: inspectHookWiring(raw) };
@@ -5223,7 +5920,7 @@ var init_install = __esm({
5223
5920
  });
5224
5921
 
5225
5922
  // src/guard/session-file.ts
5226
- import { existsSync as existsSync13 } from "node:fs";
5923
+ import { existsSync as existsSync14 } from "node:fs";
5227
5924
  import { mkdir as mkdir3, readFile as readFile3, readdir, rename as rename3, stat as stat2, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
5228
5925
  import { join as join19 } from "node:path";
5229
5926
  function sessionFile(sessionId) {
@@ -5232,7 +5929,7 @@ function sessionFile(sessionId) {
5232
5929
  async function loadGuardSession(sessionId) {
5233
5930
  try {
5234
5931
  const file = sessionFile(sessionId);
5235
- if (!existsSync13(file)) return {};
5932
+ if (!existsSync14(file)) return {};
5236
5933
  const parsed = JSON.parse(await readFile3(file, "utf8"));
5237
5934
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
5238
5935
  return parsed;
@@ -5253,7 +5950,7 @@ async function saveGuardSession(sessionId, state) {
5253
5950
  }
5254
5951
  async function sweepOldGuardSessions(maxAgeMs = 7 * 24 * 60 * 60 * 1e3, nowMs = Date.now()) {
5255
5952
  try {
5256
- if (!existsSync13(GUARD_SESSIONS_DIR)) return;
5953
+ if (!existsSync14(GUARD_SESSIONS_DIR)) return;
5257
5954
  for (const name of await readdir(GUARD_SESSIONS_DIR)) {
5258
5955
  if (!name.endsWith(".json")) continue;
5259
5956
  const file = join19(GUARD_SESSIONS_DIR, name);
@@ -5277,7 +5974,7 @@ var init_session_file = __esm({
5277
5974
  });
5278
5975
 
5279
5976
  // src/guard/log.ts
5280
- import { existsSync as existsSync14 } from "node:fs";
5977
+ import { existsSync as existsSync15 } from "node:fs";
5281
5978
  import { appendFile, mkdir as mkdir4, open } from "node:fs/promises";
5282
5979
  import { join as join20 } from "node:path";
5283
5980
  async function appendGuardEvent(event) {
@@ -5301,7 +5998,7 @@ async function readGuardEventCounts(tailBytes = 256 * 1024) {
5301
5998
  cross_session_deny: 0
5302
5999
  };
5303
6000
  try {
5304
- if (!existsSync14(GUARD_EVENTS_FILE)) return counts;
6001
+ if (!existsSync15(GUARD_EVENTS_FILE)) return counts;
5305
6002
  const fh = await open(GUARD_EVENTS_FILE, "r");
5306
6003
  try {
5307
6004
  const size = (await fh.stat()).size;
@@ -5341,7 +6038,7 @@ var cli_exports = {};
5341
6038
  __export(cli_exports, {
5342
6039
  runGuard: () => runGuard
5343
6040
  });
5344
- import { existsSync as existsSync15, readFileSync as readFileSync10 } from "node:fs";
6041
+ import { existsSync as existsSync16, readFileSync as readFileSync11 } from "node:fs";
5345
6042
  import { homedir as homedir8 } from "node:os";
5346
6043
  import { join as join21 } from "node:path";
5347
6044
  async function runGuard(argv) {
@@ -5423,7 +6120,7 @@ async function runGuardStatus() {
5423
6120
  const settingsPath = join21(homedir8(), ".claude", "settings.json");
5424
6121
  let raw = null;
5425
6122
  try {
5426
- if (existsSync15(settingsPath)) raw = readFileSync10(settingsPath, "utf8");
6123
+ if (existsSync16(settingsPath)) raw = readFileSync11(settingsPath, "utf8");
5427
6124
  } catch {
5428
6125
  }
5429
6126
  const wiring = inspectHookWiring(raw, {}, GUARD_SUBCOMMAND_HOOKS);
@@ -5615,7 +6312,7 @@ __export(inject_exports, {
5615
6312
  resolveBriefingInjection: () => resolveBriefingInjection,
5616
6313
  runGuardInject: () => runGuardInject
5617
6314
  });
5618
- import { existsSync as existsSync16 } from "node:fs";
6315
+ import { existsSync as existsSync17 } from "node:fs";
5619
6316
  import { mkdir as mkdir5, readFile as readFile4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
5620
6317
  import { dirname as dirname7, join as join22 } from "node:path";
5621
6318
  async function resolveBriefingInjection(projectKey, apiKey, deps = {}) {
@@ -5702,7 +6399,7 @@ function formatInjection(text, via) {
5702
6399
  }
5703
6400
  async function readCache(file) {
5704
6401
  try {
5705
- if (!existsSync16(file)) return null;
6402
+ if (!existsSync17(file)) return null;
5706
6403
  const parsed = JSON.parse(await readFile4(file, "utf8"));
5707
6404
  if (typeof parsed.fetched_at !== "string" || typeof parsed.text !== "string") return null;
5708
6405
  if (Number.isNaN(Date.parse(parsed.fetched_at))) return null;
@@ -6195,7 +6892,7 @@ var init_policy = __esm({
6195
6892
  });
6196
6893
 
6197
6894
  // src/gateway/policy-cache.ts
6198
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync11, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "node:fs";
6895
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync12, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "node:fs";
6199
6896
  import { homedir as homedir10 } from "node:os";
6200
6897
  import { dirname as dirname8, join as join24 } from "node:path";
6201
6898
  function policyCachePath() {
@@ -6220,7 +6917,7 @@ function writePolicyCache(identity, rules, nowIso = (/* @__PURE__ */ new Date())
6220
6917
  }
6221
6918
  function readPolicyCache(identity) {
6222
6919
  try {
6223
- const raw = readFileSync11(policyCachePath(), "utf8");
6920
+ const raw = readFileSync12(policyCachePath(), "utf8");
6224
6921
  const parsed = JSON.parse(raw);
6225
6922
  if (parsed.version !== CACHE_VERSION2 || parsed.mcp_url !== identity.mcpUrl || parsed.key_fp !== identity.keyFp || typeof parsed.cached_at !== "string" || !Array.isArray(parsed.rules)) {
6226
6923
  return null;
@@ -6367,7 +7064,7 @@ __export(install_exports, {
6367
7064
  runGatewayInstall: () => runGatewayInstall,
6368
7065
  runGatewayUninstall: () => runGatewayUninstall
6369
7066
  });
6370
- import { existsSync as existsSync17, readFileSync as readFileSync12 } from "node:fs";
7067
+ import { existsSync as existsSync18, readFileSync as readFileSync13 } from "node:fs";
6371
7068
  import { homedir as homedir11 } from "node:os";
6372
7069
  import { join as join25 } from "node:path";
6373
7070
  import { createInterface as createInterface8 } from "node:readline";
@@ -6413,8 +7110,8 @@ function loadConfig(path8) {
6413
7110
  }
6414
7111
  function readFileSafeSync(path8) {
6415
7112
  try {
6416
- if (!existsSync17(path8)) return null;
6417
- return readFileSync12(path8, "utf8");
7113
+ if (!existsSync18(path8)) return null;
7114
+ return readFileSync13(path8, "utf8");
6418
7115
  } catch {
6419
7116
  return null;
6420
7117
  }
@@ -9578,13 +10275,13 @@ function parseNodeMajor(version) {
9578
10275
 
9579
10276
  // src/local-tools/engine.ts
9580
10277
  import { execFileSync as execFileSync6 } from "node:child_process";
9581
- import { existsSync as existsSync6, realpathSync } from "node:fs";
10278
+ import { existsSync as existsSync7, realpathSync } from "node:fs";
9582
10279
  import { createRequire as createRequire3 } from "node:module";
9583
10280
  import { basename, dirname as dirname5, isAbsolute as isAbsolute3, join as join12, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
9584
10281
 
9585
10282
  // ../../packages/code-index/build/node.js
9586
10283
  import { mkdirSync as mkdirSync3 } from "node:fs";
9587
- import { posix as posix6 } from "node:path";
10284
+ import { posix as posix7 } from "node:path";
9588
10285
 
9589
10286
  // ../../packages/code-index/build/parse/tree-sitter/parser.js
9590
10287
  init_keys();
@@ -10357,8 +11054,8 @@ init_schema();
10357
11054
  // ../../packages/code-index/build/node.js
10358
11055
  var DEFAULT_DB_RELPATH = ".maind/code-index.sqlite";
10359
11056
  function createNodeCodeIndex(opts) {
10360
- const dbPath2 = opts.dbPath ?? posix6.join(opts.repoRoot, DEFAULT_DB_RELPATH);
10361
- mkdirSync3(posix6.dirname(dbPath2), { recursive: true });
11057
+ const dbPath2 = opts.dbPath ?? posix7.join(opts.repoRoot, DEFAULT_DB_RELPATH);
11058
+ mkdirSync3(posix7.dirname(dbPath2), { recursive: true });
10362
11059
  const store = new NodeSqliteStore(dbPath2);
10363
11060
  const parser = new TreeSitterParser();
10364
11061
  return new CodeIndexEngine({
@@ -10409,7 +11106,7 @@ function resolveRepoRootForPath(proposedPath, fallbackRoot = resolveRepoRoot2(),
10409
11106
  const candidates = isAbsolute3(proposedPath) ? [proposedPath] : [resolve3(fallbackRoot, proposedPath), resolve3(cwd, proposedPath)];
10410
11107
  for (const candidate of candidates) {
10411
11108
  const dir = dirname5(candidate);
10412
- if (!existsSync6(dir)) continue;
11109
+ if (!existsSync7(dir)) continue;
10413
11110
  let realDir;
10414
11111
  try {
10415
11112
  realDir = realpathSync(dir);
@@ -10427,7 +11124,7 @@ function resolveRepoRootForPath(proposedPath, fallbackRoot = resolveRepoRoot2(),
10427
11124
  function resolveRepoRootForDir(dirPath, fallbackRoot = resolveRepoRoot2(), cwd = process.cwd()) {
10428
11125
  const candidates = isAbsolute3(dirPath) ? [dirPath] : [resolve3(fallbackRoot, dirPath), resolve3(cwd, dirPath)];
10429
11126
  for (const candidate of candidates) {
10430
- if (!existsSync6(candidate)) continue;
11127
+ if (!existsSync7(candidate)) continue;
10431
11128
  let real;
10432
11129
  try {
10433
11130
  real = realpathSync(candidate);
@@ -10660,7 +11357,7 @@ Finished in ${wallClockSec}s. Restart your MCP client so it picks up the new ser
10660
11357
  }
10661
11358
 
10662
11359
  // src/local-tools/savings.ts
10663
- import { readFileSync as readFileSync6 } from "node:fs";
11360
+ import { readFileSync as readFileSync7 } from "node:fs";
10664
11361
  import { join as join13 } from "node:path";
10665
11362
 
10666
11363
  // src/local-tools/token-estimate.ts
@@ -10693,7 +11390,7 @@ var SavingsAggregator = class {
10693
11390
  };
10694
11391
  function readFileCapped(absPath) {
10695
11392
  try {
10696
- const content = readFileSync6(absPath, "utf8");
11393
+ const content = readFileSync7(absPath, "utf8");
10697
11394
  return content.length > MAX_FILE_BYTES ? content.slice(0, MAX_FILE_BYTES) : content;
10698
11395
  } catch {
10699
11396
  return "";
@@ -10917,6 +11614,28 @@ var LOCAL_TOOLS = [
10917
11614
  }
10918
11615
  }
10919
11616
  }
11617
+ },
11618
+ {
11619
+ name: "check_spec_drift",
11620
+ description: "Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",
11621
+ inputSchema: {
11622
+ type: "object",
11623
+ properties: {
11624
+ manifest: {
11625
+ type: "string",
11626
+ description: 'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'
11627
+ },
11628
+ contracts: {
11629
+ type: "array",
11630
+ items: { type: "string" },
11631
+ description: "Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."
11632
+ },
11633
+ include_baseline: {
11634
+ type: "boolean",
11635
+ description: "Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."
11636
+ }
11637
+ }
11638
+ }
10920
11639
  }
10921
11640
  ];
10922
11641
  var LOCAL_TOOL_NAMES = new Set(LOCAL_TOOLS.map((t) => t.name));
@@ -11121,6 +11840,50 @@ async function dispatchLocalTool(engine, name, args) {
11121
11840
  hint: (report.ok ? report.facts.namespaces.length === 0 ? "No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold." : "No number introduced by this branch is taken elsewhere." : `${open2.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`) + " Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."
11122
11841
  };
11123
11842
  }
11843
+ case "check_spec_drift": {
11844
+ const report = await engine.checkSpecDrift({
11845
+ manifestPath: str(args.manifest),
11846
+ contracts: Array.isArray(args.contracts) ? args.contracts.filter((c) => typeof c === "string") : void 0,
11847
+ includeBaseline: args.include_baseline !== false
11848
+ });
11849
+ const of = (s) => report.findings.filter((f) => f.status === s);
11850
+ const open2 = of("open");
11851
+ const warn = of("warn");
11852
+ const info = of("info");
11853
+ const base = {
11854
+ manifest: report.facts.manifestPath,
11855
+ base_ref: report.facts.baseRef,
11856
+ skipped: report.facts.skipped
11857
+ };
11858
+ if (report.verdict === "no_opinion") {
11859
+ return {
11860
+ ...base,
11861
+ ok: false,
11862
+ verdict: "no_opinion",
11863
+ reason: report.reason,
11864
+ contracts: [],
11865
+ findings: [],
11866
+ hint: `No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${report.reason ?? "no contract could be read"}. Declare the pairs in ${report.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`
11867
+ };
11868
+ }
11869
+ const coverageNote = "Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.";
11870
+ const unreadable2 = open2.filter((f) => f.id.startsWith("contract.unreadable:"));
11871
+ return {
11872
+ ...base,
11873
+ ok: report.ok,
11874
+ verdict: report.verdict,
11875
+ contracts: report.contracts,
11876
+ open_count: open2.length,
11877
+ warn_count: warn.length,
11878
+ preexisting_count: info.length,
11879
+ findings: [...open2, ...warn],
11880
+ // Inventory as a count plus ids, so an adopting repo with a large
11881
+ // backlog does not drown the answer it actually asked for.
11882
+ preexisting: info.map((f) => f.id),
11883
+ coverage_note: coverageNote,
11884
+ hint: (report.ok ? "The declared entries agree." : unreadable2.length > 0 ? `${unreadable2.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${open2.length - unreadable2.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.` : `${open2.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`) + " " + coverageNote
11885
+ };
11886
+ }
11124
11887
  case "codebase_search": {
11125
11888
  const query = str(args.query);
11126
11889
  if (!query) throw new Error("codebase_search requires a 'query' string");