@maind-dev/mcp-bridge 0.38.0 → 0.40.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.40.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 join29 = (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 = join29(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(join29(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
  }
@@ -2914,6 +3610,157 @@ var init_types3 = __esm({
2914
3610
  }
2915
3611
  });
2916
3612
 
3613
+ // ../../packages/code-index/build/repo-health/theme-class-drift.js
3614
+ import { readFileSync as readFileSync8 } from "node:fs";
3615
+ import { join as join14 } from "node:path";
3616
+ function extractTokens(css) {
3617
+ const tokens = /* @__PURE__ */ new Set();
3618
+ for (const m of css.matchAll(TOKEN_DECL_RE))
3619
+ tokens.add(m[1]);
3620
+ return tokens;
3621
+ }
3622
+ function deriveNamespaces(tokens) {
3623
+ return new Set([...tokens].map((t) => t.split("-")[0]));
3624
+ }
3625
+ function stripCommentLines(content) {
3626
+ return content.split("\n").map((line) => {
3627
+ const t = line.trimStart();
3628
+ return t.startsWith("//") || t.startsWith("*") || t.startsWith("/*") ? "" : line;
3629
+ }).join("\n");
3630
+ }
3631
+ function evaluateThemeClasses(facts) {
3632
+ const namespaces = deriveNamespaces(facts.tokens);
3633
+ const findings = [];
3634
+ for (const { path: path8, content: raw } of facts.sources) {
3635
+ const content = stripCommentLines(raw);
3636
+ const seen = /* @__PURE__ */ new Set();
3637
+ for (const m of content.matchAll(CLASS_RE)) {
3638
+ const candidate = m[2];
3639
+ const namespace = candidate.split("-")[0];
3640
+ if (!namespaces.has(namespace))
3641
+ continue;
3642
+ if (facts.tokens.has(candidate))
3643
+ continue;
3644
+ const klass = `${m[1]}-${candidate}`;
3645
+ if (seen.has(klass))
3646
+ continue;
3647
+ seen.add(klass);
3648
+ findings.push({ file: path8, klass, token: candidate, namespace });
3649
+ }
3650
+ }
3651
+ return findings;
3652
+ }
3653
+ function deriveThemeClassVerdict(tokenCount, findingCount) {
3654
+ if (tokenCount === 0)
3655
+ return "no_opinion";
3656
+ return findingCount === 0 ? "clean" : "drift";
3657
+ }
3658
+ function isScannableSource(path8) {
3659
+ if (/\.(test|spec)\.[jt]sx?$/.test(path8))
3660
+ return false;
3661
+ if (/(^|\/)__(tests|mocks)__\//.test(path8))
3662
+ return false;
3663
+ return true;
3664
+ }
3665
+ function listTracked(repoRoot, patterns) {
3666
+ const out2 = runGit(repoRoot, ["ls-files", "--", ...patterns]);
3667
+ if (out2 === null)
3668
+ return [];
3669
+ return out2.split("\n").filter(Boolean);
3670
+ }
3671
+ function checkThemeClassDrift(repoRoot, opts = {}) {
3672
+ const maxBytes = opts.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
3673
+ const tokens = /* @__PURE__ */ new Set();
3674
+ for (const rel of listTracked(repoRoot, ["*.css"])) {
3675
+ const css = safeRead(join14(repoRoot, rel), maxBytes);
3676
+ if (css === null)
3677
+ continue;
3678
+ for (const t of extractTokens(css))
3679
+ tokens.add(t);
3680
+ }
3681
+ if (tokens.size === 0) {
3682
+ return {
3683
+ ok: false,
3684
+ verdict: "no_opinion",
3685
+ tokenCount: 0,
3686
+ namespaceCount: 0,
3687
+ findings: [],
3688
+ scannedFiles: 0
3689
+ };
3690
+ }
3691
+ const sourcePatterns = opts.dirs !== void 0 && opts.dirs.length > 0 ? opts.dirs.flatMap((d) => SOURCE_PATTERNS.map((p) => `${d.replace(/\/+$/, "")}/**/${p}`)) : SOURCE_PATTERNS;
3692
+ const sources = [];
3693
+ for (const rel of listTracked(repoRoot, sourcePatterns)) {
3694
+ if (!isScannableSource(rel))
3695
+ continue;
3696
+ const content = safeRead(join14(repoRoot, rel), maxBytes);
3697
+ if (content === null)
3698
+ continue;
3699
+ sources.push({ path: rel, content });
3700
+ }
3701
+ const findings = evaluateThemeClasses({ tokens, sources });
3702
+ const verdict = deriveThemeClassVerdict(tokens.size, findings.length);
3703
+ return {
3704
+ ok: verdict === "clean",
3705
+ verdict,
3706
+ tokenCount: tokens.size,
3707
+ namespaceCount: deriveNamespaces(tokens).size,
3708
+ findings,
3709
+ scannedFiles: sources.length
3710
+ };
3711
+ }
3712
+ function safeRead(absPath, maxBytes) {
3713
+ try {
3714
+ const content = readFileSync8(absPath, "utf8");
3715
+ return content.length > maxBytes ? null : content;
3716
+ } catch {
3717
+ return null;
3718
+ }
3719
+ }
3720
+ var COLOR_PREFIXES, TOKEN_DECL_RE, CLASS_RE, SOURCE_PATTERNS, DEFAULT_MAX_FILE_BYTES;
3721
+ var init_theme_class_drift = __esm({
3722
+ "../../packages/code-index/build/repo-health/theme-class-drift.js"() {
3723
+ "use strict";
3724
+ init_discover();
3725
+ COLOR_PREFIXES = [
3726
+ "bg",
3727
+ "text",
3728
+ "border",
3729
+ "border-x",
3730
+ "border-y",
3731
+ "border-t",
3732
+ "border-r",
3733
+ "border-b",
3734
+ "border-l",
3735
+ "divide",
3736
+ "outline",
3737
+ "ring",
3738
+ "ring-offset",
3739
+ "fill",
3740
+ "stroke",
3741
+ "accent",
3742
+ "caret",
3743
+ "decoration",
3744
+ "placeholder",
3745
+ "shadow",
3746
+ "from",
3747
+ "via",
3748
+ "to"
3749
+ ];
3750
+ TOKEN_DECL_RE = /--(?:color|background-image)-([a-z0-9-]+)\s*:/g;
3751
+ CLASS_RE = new RegExp(
3752
+ // Before the class: line start, whitespace, quotes, or the `:` of a variant
3753
+ // prefix (dark:, hover:, supports-[…]: …).
3754
+ String.raw`(?:^|[\s"'\`:])!?(` + COLOR_PREFIXES.join("|") + // `(?!-)`: a real class name never ends at a hyphen — this is what keeps
3755
+ // prose (`bg-brand-<hue>`) and interpolation (`bg-brand-${x}`) out.
3756
+ String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,
3757
+ "g"
3758
+ );
3759
+ SOURCE_PATTERNS = ["*.ts", "*.tsx", "*.js", "*.jsx"];
3760
+ DEFAULT_MAX_FILE_BYTES = 15e5;
3761
+ }
3762
+ });
3763
+
2917
3764
  // ../../packages/code-index/build/index.js
2918
3765
  var CODE_INDEX_VERSION;
2919
3766
  var init_build = __esm({
@@ -2926,6 +3773,8 @@ var init_build = __esm({
2926
3773
  init_divergence();
2927
3774
  init_hooks();
2928
3775
  init_number_collisions();
3776
+ init_theme_class_drift();
3777
+ init_spec_drift();
2929
3778
  init_types();
2930
3779
  init_types2();
2931
3780
  init_schema();
@@ -3171,19 +4020,19 @@ var init_presence = __esm({
3171
4020
  import {
3172
4021
  mkdirSync as mkdirSync4,
3173
4022
  readdirSync as readdirSync4,
3174
- readFileSync as readFileSync7,
4023
+ readFileSync as readFileSync9,
3175
4024
  renameSync as renameSync2,
3176
4025
  statSync as statSync3,
3177
4026
  unlinkSync,
3178
4027
  writeFileSync as writeFileSync3
3179
4028
  } from "node:fs";
3180
4029
  import { homedir as homedir3 } from "node:os";
3181
- import { join as join14 } from "node:path";
4030
+ import { join as join15 } from "node:path";
3182
4031
  function presenceSnapshotBaseDir() {
3183
- return join14(homedir3(), ".maind", "presence");
4032
+ return join15(homedir3(), ".maind", "presence");
3184
4033
  }
3185
4034
  function projectDir(baseDir, projectKey) {
3186
- return join14(baseDir, projectKey);
4035
+ return join15(baseDir, projectKey);
3187
4036
  }
3188
4037
  function createSnapshotStore(opts) {
3189
4038
  const baseDir = opts.baseDir ?? presenceSnapshotBaseDir();
@@ -3212,7 +4061,7 @@ function createSnapshotStore(opts) {
3212
4061
  conflicts: Array.isArray(p.conflicts) ? p.conflicts : []
3213
4062
  };
3214
4063
  mkdirSync4(dir, { recursive: true, mode: 448 });
3215
- ownFile = join14(dir, `${meta.sessionId}.json`);
4064
+ ownFile = join15(dir, `${meta.sessionId}.json`);
3216
4065
  const tmp = `${ownFile}.tmp-${pid}`;
3217
4066
  writeFileSync3(tmp, JSON.stringify(snapshot), { mode: 384 });
3218
4067
  renameSync2(tmp, ownFile);
@@ -3242,7 +4091,7 @@ function createSnapshotStore(opts) {
3242
4091
  announce_error: errorCode
3243
4092
  };
3244
4093
  mkdirSync4(dir, { recursive: true, mode: 448 });
3245
- ownFile = join14(dir, `${meta.sessionId}.json`);
4094
+ ownFile = join15(dir, `${meta.sessionId}.json`);
3246
4095
  const tmp = `${ownFile}.tmp-${pid}`;
3247
4096
  writeFileSync3(tmp, JSON.stringify(snapshot), { mode: 384 });
3248
4097
  renameSync2(tmp, ownFile);
@@ -3256,7 +4105,7 @@ function pruneStale(dir, nowMs, keep) {
3256
4105
  try {
3257
4106
  for (const name of readdirSync4(dir)) {
3258
4107
  if (!name.endsWith(".json")) continue;
3259
- const file = join14(dir, name);
4108
+ const file = join15(dir, name);
3260
4109
  if (file === keep) continue;
3261
4110
  try {
3262
4111
  const age = nowMs - statSync3(file).mtimeMs;
@@ -3275,7 +4124,7 @@ function readSnapshots(projectKey, baseDir = presenceSnapshotBaseDir()) {
3275
4124
  if (!name.endsWith(".json")) continue;
3276
4125
  try {
3277
4126
  const raw = JSON.parse(
3278
- readFileSync7(join14(dir, name), "utf8")
4127
+ readFileSync9(join15(dir, name), "utf8")
3279
4128
  );
3280
4129
  const snap = parseSnapshot(raw);
3281
4130
  if (snap) out2.push(snap);
@@ -3325,19 +4174,19 @@ var init_presence_snapshot = __esm({
3325
4174
  import { execFileSync as execFileSync7 } from "node:child_process";
3326
4175
  import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
3327
4176
  import {
3328
- existsSync as existsSync7,
4177
+ existsSync as existsSync8,
3329
4178
  mkdirSync as mkdirSync5,
3330
4179
  readdirSync as readdirSync5,
3331
- readFileSync as readFileSync8,
4180
+ readFileSync as readFileSync10,
3332
4181
  renameSync as renameSync3,
3333
4182
  statSync as statSync4,
3334
4183
  unlinkSync as unlinkSync2,
3335
4184
  writeFileSync as writeFileSync4
3336
4185
  } from "node:fs";
3337
4186
  import { homedir as homedir4 } from "node:os";
3338
- import { basename as basename2, join as join15 } from "node:path";
4187
+ import { basename as basename2, join as join16 } from "node:path";
3339
4188
  function identityDirPath(baseDir) {
3340
- return join15(baseDir ?? join15(homedir4(), ".maind", "presence"), "identity");
4189
+ return join16(baseDir ?? join16(homedir4(), ".maind", "presence"), "identity");
3341
4190
  }
3342
4191
  function transcriptStemOf(transcriptPath, sessionId) {
3343
4192
  if (transcriptPath) {
@@ -3350,7 +4199,7 @@ function transcriptStemOf(transcriptPath, sessionId) {
3350
4199
  function writeAgentIdentityFile(opts) {
3351
4200
  const now = opts.nowMs ?? Date.now();
3352
4201
  mkdirSync5(opts.dir, { recursive: true, mode: 448 });
3353
- const file = join15(opts.dir, `${opts.agentPid}.json`);
4202
+ const file = join16(opts.dir, `${opts.agentPid}.json`);
3354
4203
  const tmp = `${file}.tmp-${process.pid}`;
3355
4204
  const payload = {
3356
4205
  v: 1,
@@ -3366,7 +4215,7 @@ function writeAgentIdentityFile(opts) {
3366
4215
  }
3367
4216
  function identityFileStale(dir, agentPid, maxAgeMs, nowMs = Date.now()) {
3368
4217
  try {
3369
- const st = statSync4(join15(dir, `${agentPid}.json`));
4218
+ const st = statSync4(join16(dir, `${agentPid}.json`));
3370
4219
  return nowMs - st.mtimeMs > maxAgeMs;
3371
4220
  } catch {
3372
4221
  return true;
@@ -3374,7 +4223,7 @@ function identityFileStale(dir, agentPid, maxAgeMs, nowMs = Date.now()) {
3374
4223
  }
3375
4224
  function deleteAgentIdentityFile(dir, agentPid) {
3376
4225
  try {
3377
- unlinkSync2(join15(dir, `${agentPid}.json`));
4226
+ unlinkSync2(join16(dir, `${agentPid}.json`));
3378
4227
  } catch {
3379
4228
  }
3380
4229
  }
@@ -3383,8 +4232,8 @@ function pruneIdentityDir(dir, nowMs) {
3383
4232
  for (const f of readdirSync5(dir)) {
3384
4233
  if (!f.endsWith(".json")) continue;
3385
4234
  try {
3386
- const st = statSync4(join15(dir, f));
3387
- if (nowMs - st.mtimeMs > IDENTITY_TTL_MS) unlinkSync2(join15(dir, f));
4235
+ const st = statSync4(join16(dir, f));
4236
+ if (nowMs - st.mtimeMs > IDENTITY_TTL_MS) unlinkSync2(join16(dir, f));
3388
4237
  } catch {
3389
4238
  }
3390
4239
  }
@@ -3392,14 +4241,14 @@ function pruneIdentityDir(dir, nowMs) {
3392
4241
  }
3393
4242
  }
3394
4243
  function readAgentIdentityFile(opts) {
3395
- const file = join15(opts.dir, `${opts.agentPid}.json`);
4244
+ const file = join16(opts.dir, `${opts.agentPid}.json`);
3396
4245
  try {
3397
- if (!existsSync7(file)) return null;
4246
+ if (!existsSync8(file)) return null;
3398
4247
  const st = statSync4(file);
3399
4248
  if (st.mtimeMs < opts.bridgeStartMs - IDENTITY_MAX_AGE_SLACK_MS) {
3400
4249
  return null;
3401
4250
  }
3402
- const parsed = JSON.parse(readFileSync8(file, "utf8"));
4251
+ const parsed = JSON.parse(readFileSync10(file, "utf8"));
3403
4252
  if (typeof parsed !== "object" || parsed === null) return null;
3404
4253
  const o = parsed;
3405
4254
  if (o.v !== 1) return null;
@@ -3548,11 +4397,11 @@ var init_types4 = __esm({
3548
4397
  });
3549
4398
 
3550
4399
  // ../../packages/claude-code-telemetry/dist/transcript.js
3551
- import { createReadStream, existsSync as existsSync8 } from "node:fs";
4400
+ import { createReadStream, existsSync as existsSync9 } from "node:fs";
3552
4401
  import { stat } from "node:fs/promises";
3553
4402
  import { createInterface as createInterface5 } from "node:readline";
3554
4403
  async function summariseTranscript(path8) {
3555
- if (!path8 || !existsSync8(path8))
4404
+ if (!path8 || !existsSync9(path8))
3556
4405
  return null;
3557
4406
  let stats;
3558
4407
  try {
@@ -3637,7 +4486,7 @@ var init_effort = __esm({
3637
4486
  });
3638
4487
 
3639
4488
  // ../../packages/claude-code-telemetry/dist/session-analysis.js
3640
- import { createReadStream as createReadStream2, existsSync as existsSync9 } from "node:fs";
4489
+ import { createReadStream as createReadStream2, existsSync as existsSync10 } from "node:fs";
3641
4490
  import { createInterface as createInterface6 } from "node:readline";
3642
4491
  function num2(v) {
3643
4492
  return typeof v === "number" && Number.isFinite(v) ? v : 0;
@@ -3744,7 +4593,7 @@ function emptyAnalysis(sessionId) {
3744
4593
  }
3745
4594
  async function analyzeSession(path8) {
3746
4595
  const a = emptyAnalysis("");
3747
- if (!path8 || !existsSync9(path8))
4596
+ if (!path8 || !existsSync10(path8))
3748
4597
  return a;
3749
4598
  const reactions = [];
3750
4599
  const modelMix = /* @__PURE__ */ new Map();
@@ -3940,7 +4789,7 @@ var init_ingest = __esm({
3940
4789
  });
3941
4790
 
3942
4791
  // ../../packages/claude-code-telemetry/dist/session-span.js
3943
- import { createReadStream as createReadStream3, existsSync as existsSync10 } from "node:fs";
4792
+ import { createReadStream as createReadStream3, existsSync as existsSync11 } from "node:fs";
3944
4793
  import { createInterface as createInterface7 } from "node:readline";
3945
4794
  function asBlocks2(content) {
3946
4795
  if (typeof content === "string")
@@ -3992,7 +4841,7 @@ function classify2(parsed) {
3992
4841
  }
3993
4842
  async function analyzeSpan(path8) {
3994
4843
  const s = emptySpan("");
3995
- if (!path8 || !existsSync10(path8))
4844
+ if (!path8 || !existsSync11(path8))
3996
4845
  return s;
3997
4846
  let firstMs = null;
3998
4847
  let lastMs = 0;
@@ -4105,13 +4954,13 @@ var init_windows = __esm({
4105
4954
 
4106
4955
  // ../../packages/claude-code-telemetry/dist/projects.js
4107
4956
  import { homedir as homedir5 } from "node:os";
4108
- import { join as join16 } from "node:path";
4957
+ import { join as join17 } from "node:path";
4109
4958
  var HOME, DEFAULT_PROJECTS_DIR;
4110
4959
  var init_projects = __esm({
4111
4960
  "../../packages/claude-code-telemetry/dist/projects.js"() {
4112
4961
  "use strict";
4113
4962
  HOME = homedir5();
4114
- DEFAULT_PROJECTS_DIR = join16(HOME, ".claude", "projects");
4963
+ DEFAULT_PROJECTS_DIR = join17(HOME, ".claude", "projects");
4115
4964
  }
4116
4965
  });
4117
4966
 
@@ -4359,14 +5208,14 @@ var init_payloads = __esm({
4359
5208
 
4360
5209
  // src/hooks/state.ts
4361
5210
  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";
5211
+ import { existsSync as existsSync12 } from "node:fs";
4363
5212
  import { homedir as homedir6 } from "node:os";
4364
- import { join as join17 } from "node:path";
5213
+ import { join as join18 } from "node:path";
4365
5214
  function emptyState() {
4366
5215
  return { config: null, sessions: {}, pending_metrics: [] };
4367
5216
  }
4368
5217
  async function loadState() {
4369
- if (!existsSync11(STATE_FILE)) return emptyState();
5218
+ if (!existsSync12(STATE_FILE)) return emptyState();
4370
5219
  try {
4371
5220
  const raw = await readFile2(STATE_FILE, "utf-8");
4372
5221
  const parsed = JSON.parse(raw);
@@ -4387,7 +5236,7 @@ async function loadState() {
4387
5236
  }
4388
5237
  }
4389
5238
  async function saveState(state) {
4390
- if (!existsSync11(STATE_DIR)) {
5239
+ if (!existsSync12(STATE_DIR)) {
4391
5240
  await mkdir2(STATE_DIR, { recursive: true, mode: 448 });
4392
5241
  }
4393
5242
  const tmp = `${STATE_FILE}.tmp`;
@@ -4401,8 +5250,8 @@ var STATE_DIR, STATE_FILE, DEFAULT_THRESHOLDS;
4401
5250
  var init_state = __esm({
4402
5251
  "src/hooks/state.ts"() {
4403
5252
  "use strict";
4404
- STATE_DIR = join17(homedir6(), ".maind");
4405
- STATE_FILE = join17(STATE_DIR, "state.json");
5253
+ STATE_DIR = join18(homedir6(), ".maind");
5254
+ STATE_FILE = join18(STATE_DIR, "state.json");
4406
5255
  DEFAULT_THRESHOLDS = {
4407
5256
  warn_at_pct: 60,
4408
5257
  handoff_at_pct: 85,
@@ -4428,10 +5277,10 @@ __export(hooks_exports, {
4428
5277
  runSyncConfig: () => runSyncConfig
4429
5278
  });
4430
5279
  import { execFileSync as execFileSync8 } from "node:child_process";
4431
- import { existsSync as existsSync12, readFileSync as readFileSync9, realpathSync as realpathSync2 } from "node:fs";
5280
+ import { existsSync as existsSync13, readFileSync as readFileSync11, realpathSync as realpathSync2 } from "node:fs";
4432
5281
  import { writeFile as writeFile3 } from "node:fs/promises";
4433
5282
  import { homedir as homedir7 } from "node:os";
4434
- import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute4, join as join18, relative as relative3 } from "node:path";
5283
+ import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute4, join as join19, relative as relative3 } from "node:path";
4435
5284
  function recordGuardSignals(state, sessionId, toolName, nowMs = Date.now()) {
4436
5285
  if (!toolName.includes("maind")) return;
4437
5286
  const consulted = toolName.includes("search_lessons") || toolName.includes("get_session_briefing") || toolName.includes("get_lesson") || toolName.includes("get_conventions") || toolName.includes("activate_skill") || toolName.includes("suggest_skills") || toolName.includes("codebase_change_briefing");
@@ -4556,8 +5405,8 @@ async function runOnSessionStart() {
4556
5405
  }
4557
5406
  function readSettingsRaw() {
4558
5407
  try {
4559
- const p = join18(homedir7(), ".claude", "settings.json");
4560
- return existsSync12(p) ? readFileSync9(p, "utf8") : null;
5408
+ const p = join19(homedir7(), ".claude", "settings.json");
5409
+ return existsSync13(p) ? readFileSync11(p, "utf8") : null;
4561
5410
  } catch {
4562
5411
  return null;
4563
5412
  }
@@ -4627,7 +5476,7 @@ function realpathOfUnwritten(p) {
4627
5476
  for (; ; ) {
4628
5477
  try {
4629
5478
  const real = realpathSync2(head);
4630
- return join18(real, ...tail.reverse());
5479
+ return join19(real, ...tail.reverse());
4631
5480
  } catch {
4632
5481
  const parent = dirname6(head);
4633
5482
  if (parent === head) return p;
@@ -4652,8 +5501,8 @@ async function runOnFileWrite() {
4652
5501
  const filePath = toolFilePathOf(input);
4653
5502
  if (!filePath) return 0;
4654
5503
  const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
4655
- const abs = isAbsolute4(filePath) ? filePath : join18(cwd, filePath);
4656
- if (existsSync12(abs)) return 0;
5504
+ const abs = isAbsolute4(filePath) ? filePath : join19(cwd, filePath);
5505
+ if (existsSync13(abs)) return 0;
4657
5506
  const repoRoot = resolveRepoRoot(cwd);
4658
5507
  const rel = relative3(repoRoot, realpathOfUnwritten(abs));
4659
5508
  if (rel.length === 0 || rel.startsWith("..") || isAbsolute4(rel)) return 0;
@@ -4673,7 +5522,7 @@ async function runOnFileEdit() {
4673
5522
  const filePath = toolFilePathOf(input);
4674
5523
  if (!filePath) return 0;
4675
5524
  const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
4676
- const abs = isAbsolute4(filePath) ? filePath : join18(cwd, filePath);
5525
+ const abs = isAbsolute4(filePath) ? filePath : join19(cwd, filePath);
4677
5526
  const projectKey = computeProjectKey();
4678
5527
  if (projectKey === null) return 0;
4679
5528
  const snaps = readSnapshots(projectKey);
@@ -4684,7 +5533,7 @@ async function runOnFileEdit() {
4684
5533
  });
4685
5534
  if (own === null) return 0;
4686
5535
  const repoRoot = resolveRepoRoot(cwd);
4687
- const real = existsSync12(abs) ? realpathSync2(abs) : realpathOfUnwritten(abs);
5536
+ const real = existsSync13(abs) ? realpathSync2(abs) : realpathOfUnwritten(abs);
4688
5537
  const rel = relative3(repoRoot, real).replace(/\\/g, "/");
4689
5538
  if (rel.length === 0 || rel.startsWith("..") || isAbsolute4(rel)) return 0;
4690
5539
  const advice = adviseOnPath(own.snap, rel, {
@@ -4736,7 +5585,7 @@ async function maybeEmitAdvisory(state, session) {
4736
5585
  };
4737
5586
  try {
4738
5587
  await writeFile3(
4739
- join18(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
5588
+ join19(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
4740
5589
  JSON.stringify(payload, null, 2)
4741
5590
  );
4742
5591
  } catch (err) {
@@ -4856,10 +5705,10 @@ async function runHookStatus() {
4856
5705
  return 0;
4857
5706
  }
4858
5707
  function readHookWiring() {
4859
- const settingsPath = join18(homedir7(), ".claude", "settings.json");
5708
+ const settingsPath = join19(homedir7(), ".claude", "settings.json");
4860
5709
  let raw = null;
4861
5710
  try {
4862
- if (existsSync12(settingsPath)) raw = readFileSync9(settingsPath, "utf8");
5711
+ if (existsSync13(settingsPath)) raw = readFileSync11(settingsPath, "utf8");
4863
5712
  } catch {
4864
5713
  }
4865
5714
  return { settingsPath, findings: inspectHookWiring(raw) };
@@ -5223,16 +6072,16 @@ var init_install = __esm({
5223
6072
  });
5224
6073
 
5225
6074
  // src/guard/session-file.ts
5226
- import { existsSync as existsSync13 } from "node:fs";
6075
+ import { existsSync as existsSync14 } from "node:fs";
5227
6076
  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
- import { join as join19 } from "node:path";
6077
+ import { join as join20 } from "node:path";
5229
6078
  function sessionFile(sessionId) {
5230
- return join19(GUARD_SESSIONS_DIR, sessionId.replace(/[^a-zA-Z0-9._-]/g, "_") + ".json");
6079
+ return join20(GUARD_SESSIONS_DIR, sessionId.replace(/[^a-zA-Z0-9._-]/g, "_") + ".json");
5231
6080
  }
5232
6081
  async function loadGuardSession(sessionId) {
5233
6082
  try {
5234
6083
  const file = sessionFile(sessionId);
5235
- if (!existsSync13(file)) return {};
6084
+ if (!existsSync14(file)) return {};
5236
6085
  const parsed = JSON.parse(await readFile3(file, "utf8"));
5237
6086
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
5238
6087
  return parsed;
@@ -5253,10 +6102,10 @@ async function saveGuardSession(sessionId, state) {
5253
6102
  }
5254
6103
  async function sweepOldGuardSessions(maxAgeMs = 7 * 24 * 60 * 60 * 1e3, nowMs = Date.now()) {
5255
6104
  try {
5256
- if (!existsSync13(GUARD_SESSIONS_DIR)) return;
6105
+ if (!existsSync14(GUARD_SESSIONS_DIR)) return;
5257
6106
  for (const name of await readdir(GUARD_SESSIONS_DIR)) {
5258
6107
  if (!name.endsWith(".json")) continue;
5259
- const file = join19(GUARD_SESSIONS_DIR, name);
6108
+ const file = join20(GUARD_SESSIONS_DIR, name);
5260
6109
  try {
5261
6110
  const s = await stat2(file);
5262
6111
  if (nowMs - s.mtimeMs > maxAgeMs) await unlink2(file);
@@ -5271,15 +6120,15 @@ var init_session_file = __esm({
5271
6120
  "src/guard/session-file.ts"() {
5272
6121
  "use strict";
5273
6122
  init_state();
5274
- GUARD_DIR = join19(STATE_DIR, "guard");
5275
- GUARD_SESSIONS_DIR = join19(GUARD_DIR, "sessions");
6123
+ GUARD_DIR = join20(STATE_DIR, "guard");
6124
+ GUARD_SESSIONS_DIR = join20(GUARD_DIR, "sessions");
5276
6125
  }
5277
6126
  });
5278
6127
 
5279
6128
  // src/guard/log.ts
5280
- import { existsSync as existsSync14 } from "node:fs";
6129
+ import { existsSync as existsSync15 } from "node:fs";
5281
6130
  import { appendFile, mkdir as mkdir4, open } from "node:fs/promises";
5282
- import { join as join20 } from "node:path";
6131
+ import { join as join21 } from "node:path";
5283
6132
  async function appendGuardEvent(event) {
5284
6133
  try {
5285
6134
  await mkdir4(GUARD_DIR, { recursive: true, mode: 448 });
@@ -5301,7 +6150,7 @@ async function readGuardEventCounts(tailBytes = 256 * 1024) {
5301
6150
  cross_session_deny: 0
5302
6151
  };
5303
6152
  try {
5304
- if (!existsSync14(GUARD_EVENTS_FILE)) return counts;
6153
+ if (!existsSync15(GUARD_EVENTS_FILE)) return counts;
5305
6154
  const fh = await open(GUARD_EVENTS_FILE, "r");
5306
6155
  try {
5307
6156
  const size = (await fh.stat()).size;
@@ -5332,7 +6181,7 @@ var init_log = __esm({
5332
6181
  "src/guard/log.ts"() {
5333
6182
  "use strict";
5334
6183
  init_session_file();
5335
- GUARD_EVENTS_FILE = join20(GUARD_DIR, "events.jsonl");
6184
+ GUARD_EVENTS_FILE = join21(GUARD_DIR, "events.jsonl");
5336
6185
  }
5337
6186
  });
5338
6187
 
@@ -5341,9 +6190,9 @@ var cli_exports = {};
5341
6190
  __export(cli_exports, {
5342
6191
  runGuard: () => runGuard
5343
6192
  });
5344
- import { existsSync as existsSync15, readFileSync as readFileSync10 } from "node:fs";
6193
+ import { existsSync as existsSync16, readFileSync as readFileSync12 } from "node:fs";
5345
6194
  import { homedir as homedir8 } from "node:os";
5346
- import { join as join21 } from "node:path";
6195
+ import { join as join22 } from "node:path";
5347
6196
  async function runGuard(argv) {
5348
6197
  const verb = argv[0];
5349
6198
  const rest = argv.slice(1);
@@ -5420,10 +6269,10 @@ logged (auditable) in ${GUARD_EVENTS_FILE}
5420
6269
  }
5421
6270
  async function runGuardStatus() {
5422
6271
  const config = resolveGuardConfig();
5423
- const settingsPath = join21(homedir8(), ".claude", "settings.json");
6272
+ const settingsPath = join22(homedir8(), ".claude", "settings.json");
5424
6273
  let raw = null;
5425
6274
  try {
5426
- if (existsSync15(settingsPath)) raw = readFileSync10(settingsPath, "utf8");
6275
+ if (existsSync16(settingsPath)) raw = readFileSync12(settingsPath, "utf8");
5427
6276
  } catch {
5428
6277
  }
5429
6278
  const wiring = inspectHookWiring(raw, {}, GUARD_SUBCOMMAND_HOOKS);
@@ -5615,9 +6464,9 @@ __export(inject_exports, {
5615
6464
  resolveBriefingInjection: () => resolveBriefingInjection,
5616
6465
  runGuardInject: () => runGuardInject
5617
6466
  });
5618
- import { existsSync as existsSync16 } from "node:fs";
6467
+ import { existsSync as existsSync17 } from "node:fs";
5619
6468
  import { mkdir as mkdir5, readFile as readFile4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
5620
- import { dirname as dirname7, join as join22 } from "node:path";
6469
+ import { dirname as dirname7, join as join23 } from "node:path";
5621
6470
  async function resolveBriefingInjection(projectKey, apiKey, deps = {}) {
5622
6471
  const nowMs = deps.nowMs ?? Date.now();
5623
6472
  const cacheFile = deps.cacheFile ?? BRIEFING_CACHE_FILE;
@@ -5702,7 +6551,7 @@ function formatInjection(text, via) {
5702
6551
  }
5703
6552
  async function readCache(file) {
5704
6553
  try {
5705
- if (!existsSync16(file)) return null;
6554
+ if (!existsSync17(file)) return null;
5706
6555
  const parsed = JSON.parse(await readFile4(file, "utf8"));
5707
6556
  if (typeof parsed.fetched_at !== "string" || typeof parsed.text !== "string") return null;
5708
6557
  if (Number.isNaN(Date.parse(parsed.fetched_at))) return null;
@@ -5743,7 +6592,7 @@ var init_inject = __esm({
5743
6592
  init_log();
5744
6593
  init_session_file();
5745
6594
  init_mcp_client();
5746
- BRIEFING_CACHE_FILE = join22(GUARD_DIR, "briefing-cache.json");
6595
+ BRIEFING_CACHE_FILE = join23(GUARD_DIR, "briefing-cache.json");
5747
6596
  CACHE_TTL_MS = 12 * 60 * 60 * 1e3;
5748
6597
  FETCH_BUDGET_MS = 3e3;
5749
6598
  MAX_INJECT_BYTES = 10 * 1024;
@@ -5973,7 +6822,7 @@ var init_frames = __esm({
5973
6822
  // src/gateway/attest.ts
5974
6823
  import { appendFile as appendFile2, mkdir as mkdir6, readFile as readFile5, rename as rename5, writeFile as writeFile6 } from "node:fs/promises";
5975
6824
  import { homedir as homedir9 } from "node:os";
5976
- import { join as join23 } from "node:path";
6825
+ import { join as join24 } from "node:path";
5977
6826
  function aggregateWindow(events, mode, serverLabel, projectKey) {
5978
6827
  if (mode === "off" || events.length === 0) return null;
5979
6828
  const counts = {};
@@ -6007,7 +6856,7 @@ function aggregateWindow(events, mode, serverLabel, projectKey) {
6007
6856
  };
6008
6857
  }
6009
6858
  function attestSpoolPath() {
6010
- return join23(homedir9(), ".maind", "gateway", "attest-spool.jsonl");
6859
+ return join24(homedir9(), ".maind", "gateway", "attest-spool.jsonl");
6011
6860
  }
6012
6861
  async function postAttestation(payload) {
6013
6862
  const apiKey = readApiKey();
@@ -6030,7 +6879,7 @@ async function postAttestation(payload) {
6030
6879
  }
6031
6880
  async function spoolAttestation(payload) {
6032
6881
  try {
6033
- await mkdir6(join23(homedir9(), ".maind", "gateway"), { recursive: true });
6882
+ await mkdir6(join24(homedir9(), ".maind", "gateway"), { recursive: true });
6034
6883
  await appendFile2(attestSpoolPath(), JSON.stringify(payload) + "\n", { mode: 384 });
6035
6884
  await capSpool();
6036
6885
  } catch {
@@ -6195,11 +7044,11 @@ var init_policy = __esm({
6195
7044
  });
6196
7045
 
6197
7046
  // src/gateway/policy-cache.ts
6198
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync11, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "node:fs";
7047
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync13, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "node:fs";
6199
7048
  import { homedir as homedir10 } from "node:os";
6200
- import { dirname as dirname8, join as join24 } from "node:path";
7049
+ import { dirname as dirname8, join as join25 } from "node:path";
6201
7050
  function policyCachePath() {
6202
- return join24(homedir10(), ".maind", "gateway", "policy-cache.json");
7051
+ return join25(homedir10(), ".maind", "gateway", "policy-cache.json");
6203
7052
  }
6204
7053
  function writePolicyCache(identity, rules, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
6205
7054
  try {
@@ -6220,7 +7069,7 @@ function writePolicyCache(identity, rules, nowIso = (/* @__PURE__ */ new Date())
6220
7069
  }
6221
7070
  function readPolicyCache(identity) {
6222
7071
  try {
6223
- const raw = readFileSync11(policyCachePath(), "utf8");
7072
+ const raw = readFileSync13(policyCachePath(), "utf8");
6224
7073
  const parsed = JSON.parse(raw);
6225
7074
  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
7075
  return null;
@@ -6367,9 +7216,9 @@ __export(install_exports, {
6367
7216
  runGatewayInstall: () => runGatewayInstall,
6368
7217
  runGatewayUninstall: () => runGatewayUninstall
6369
7218
  });
6370
- import { existsSync as existsSync17, readFileSync as readFileSync12 } from "node:fs";
7219
+ import { existsSync as existsSync18, readFileSync as readFileSync14 } from "node:fs";
6371
7220
  import { homedir as homedir11 } from "node:os";
6372
- import { join as join25 } from "node:path";
7221
+ import { join as join26 } from "node:path";
6373
7222
  import { createInterface as createInterface8 } from "node:readline";
6374
7223
  function parseFlags(argv) {
6375
7224
  const f = { yes: false, dryRun: false };
@@ -6382,8 +7231,8 @@ function parseFlags(argv) {
6382
7231
  }
6383
7232
  function targets() {
6384
7233
  return [
6385
- { label: "Claude Code (project .mcp.json)", path: join25(process.cwd(), ".mcp.json") },
6386
- { label: "Claude Code (user ~/.claude.json)", path: join25(homedir11(), ".claude.json") }
7234
+ { label: "Claude Code (project .mcp.json)", path: join26(process.cwd(), ".mcp.json") },
7235
+ { label: "Claude Code (user ~/.claude.json)", path: join26(homedir11(), ".claude.json") }
6387
7236
  ];
6388
7237
  }
6389
7238
  async function confirm(question) {
@@ -6413,8 +7262,8 @@ function loadConfig(path8) {
6413
7262
  }
6414
7263
  function readFileSafeSync(path8) {
6415
7264
  try {
6416
- if (!existsSync17(path8)) return null;
6417
- return readFileSync12(path8, "utf8");
7265
+ if (!existsSync18(path8)) return null;
7266
+ return readFileSync14(path8, "utf8");
6418
7267
  } catch {
6419
7268
  return null;
6420
7269
  }
@@ -6644,15 +7493,15 @@ __export(run_exports, {
6644
7493
  import { spawn as spawn2 } from "node:child_process";
6645
7494
  import { appendFile as appendFile3, mkdir as mkdir7 } from "node:fs/promises";
6646
7495
  import { homedir as homedir12 } from "node:os";
6647
- import { basename as basename4, join as join26 } from "node:path";
7496
+ import { basename as basename4, join as join27 } from "node:path";
6648
7497
  import { createInterface as createInterface9 } from "node:readline";
6649
7498
  function gatewayEventsFile() {
6650
- return join26(homedir12(), ".maind", "gateway", "events.jsonl");
7499
+ return join27(homedir12(), ".maind", "gateway", "events.jsonl");
6651
7500
  }
6652
7501
  async function logEvent(e) {
6653
7502
  try {
6654
7503
  const file = gatewayEventsFile();
6655
- await mkdir7(join26(homedir12(), ".maind", "gateway"), { recursive: true });
7504
+ await mkdir7(join27(homedir12(), ".maind", "gateway"), { recursive: true });
6656
7505
  await appendFile3(file, JSON.stringify(e) + "\n", { mode: 384 });
6657
7506
  } catch {
6658
7507
  }
@@ -6840,9 +7689,9 @@ __export(cross_session_exports, {
6840
7689
  });
6841
7690
  import { mkdir as mkdir8, readFile as readFile6, readdir as readdir2, stat as stat3, unlink as unlink3, writeFile as writeFile7 } from "node:fs/promises";
6842
7691
  import { homedir as homedir13 } from "node:os";
6843
- import { join as join27 } from "node:path";
7692
+ import { join as join28 } from "node:path";
6844
7693
  function crossSessionDir() {
6845
- return join27(homedir13(), ".maind", "cross-session");
7694
+ return join28(homedir13(), ".maind", "cross-session");
6846
7695
  }
6847
7696
  function parseSessionDb(raw) {
6848
7697
  const empty = { files: {}, warned: {} };
@@ -6884,7 +7733,7 @@ function staleReason(path8, v) {
6884
7733
  async function dbPath(sessionId) {
6885
7734
  const dir = crossSessionDir();
6886
7735
  await mkdir8(dir, { recursive: true });
6887
- return join27(dir, `${sessionId}.json`);
7736
+ return join28(dir, `${sessionId}.json`);
6888
7737
  }
6889
7738
  async function loadDb(sessionId, now) {
6890
7739
  try {
@@ -6905,7 +7754,7 @@ async function sweepStaleSessionFiles(now) {
6905
7754
  const dir = crossSessionDir();
6906
7755
  for (const name of await readdir2(dir)) {
6907
7756
  if (!name.endsWith(".json")) continue;
6908
- const p = join27(dir, name);
7757
+ const p = join28(dir, name);
6909
7758
  const s = await stat3(p).catch(() => null);
6910
7759
  if (s && now - s.mtimeMs > TTL_MS) await unlink3(p).catch(() => {
6911
7760
  });
@@ -9578,13 +10427,13 @@ function parseNodeMajor(version) {
9578
10427
 
9579
10428
  // src/local-tools/engine.ts
9580
10429
  import { execFileSync as execFileSync6 } from "node:child_process";
9581
- import { existsSync as existsSync6, realpathSync } from "node:fs";
10430
+ import { existsSync as existsSync7, realpathSync } from "node:fs";
9582
10431
  import { createRequire as createRequire3 } from "node:module";
9583
10432
  import { basename, dirname as dirname5, isAbsolute as isAbsolute3, join as join12, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
9584
10433
 
9585
10434
  // ../../packages/code-index/build/node.js
9586
10435
  import { mkdirSync as mkdirSync3 } from "node:fs";
9587
- import { posix as posix6 } from "node:path";
10436
+ import { posix as posix7 } from "node:path";
9588
10437
 
9589
10438
  // ../../packages/code-index/build/parse/tree-sitter/parser.js
9590
10439
  init_keys();
@@ -10357,8 +11206,8 @@ init_schema();
10357
11206
  // ../../packages/code-index/build/node.js
10358
11207
  var DEFAULT_DB_RELPATH = ".maind/code-index.sqlite";
10359
11208
  function createNodeCodeIndex(opts) {
10360
- const dbPath2 = opts.dbPath ?? posix6.join(opts.repoRoot, DEFAULT_DB_RELPATH);
10361
- mkdirSync3(posix6.dirname(dbPath2), { recursive: true });
11209
+ const dbPath2 = opts.dbPath ?? posix7.join(opts.repoRoot, DEFAULT_DB_RELPATH);
11210
+ mkdirSync3(posix7.dirname(dbPath2), { recursive: true });
10362
11211
  const store = new NodeSqliteStore(dbPath2);
10363
11212
  const parser = new TreeSitterParser();
10364
11213
  return new CodeIndexEngine({
@@ -10409,7 +11258,7 @@ function resolveRepoRootForPath(proposedPath, fallbackRoot = resolveRepoRoot2(),
10409
11258
  const candidates = isAbsolute3(proposedPath) ? [proposedPath] : [resolve3(fallbackRoot, proposedPath), resolve3(cwd, proposedPath)];
10410
11259
  for (const candidate of candidates) {
10411
11260
  const dir = dirname5(candidate);
10412
- if (!existsSync6(dir)) continue;
11261
+ if (!existsSync7(dir)) continue;
10413
11262
  let realDir;
10414
11263
  try {
10415
11264
  realDir = realpathSync(dir);
@@ -10427,7 +11276,7 @@ function resolveRepoRootForPath(proposedPath, fallbackRoot = resolveRepoRoot2(),
10427
11276
  function resolveRepoRootForDir(dirPath, fallbackRoot = resolveRepoRoot2(), cwd = process.cwd()) {
10428
11277
  const candidates = isAbsolute3(dirPath) ? [dirPath] : [resolve3(fallbackRoot, dirPath), resolve3(cwd, dirPath)];
10429
11278
  for (const candidate of candidates) {
10430
- if (!existsSync6(candidate)) continue;
11279
+ if (!existsSync7(candidate)) continue;
10431
11280
  let real;
10432
11281
  try {
10433
11282
  real = realpathSync(candidate);
@@ -10660,7 +11509,7 @@ Finished in ${wallClockSec}s. Restart your MCP client so it picks up the new ser
10660
11509
  }
10661
11510
 
10662
11511
  // src/local-tools/savings.ts
10663
- import { readFileSync as readFileSync6 } from "node:fs";
11512
+ import { readFileSync as readFileSync7 } from "node:fs";
10664
11513
  import { join as join13 } from "node:path";
10665
11514
 
10666
11515
  // src/local-tools/token-estimate.ts
@@ -10693,7 +11542,7 @@ var SavingsAggregator = class {
10693
11542
  };
10694
11543
  function readFileCapped(absPath) {
10695
11544
  try {
10696
- const content = readFileSync6(absPath, "utf8");
11545
+ const content = readFileSync7(absPath, "utf8");
10697
11546
  return content.length > MAX_FILE_BYTES ? content.slice(0, MAX_FILE_BYTES) : content;
10698
11547
  } catch {
10699
11548
  return "";
@@ -10917,6 +11766,41 @@ var LOCAL_TOOLS = [
10917
11766
  }
10918
11767
  }
10919
11768
  }
11769
+ },
11770
+ {
11771
+ name: "check_spec_drift",
11772
+ 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.",
11773
+ inputSchema: {
11774
+ type: "object",
11775
+ properties: {
11776
+ manifest: {
11777
+ type: "string",
11778
+ 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`.'
11779
+ },
11780
+ contracts: {
11781
+ type: "array",
11782
+ items: { type: "string" },
11783
+ description: "Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."
11784
+ },
11785
+ include_baseline: {
11786
+ type: "boolean",
11787
+ 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."
11788
+ }
11789
+ }
11790
+ }
11791
+ },
11792
+ {
11793
+ name: "check_theme_class_drift",
11794
+ description: "Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness.",
11795
+ inputSchema: {
11796
+ type: "object",
11797
+ properties: {
11798
+ dir: {
11799
+ type: "string",
11800
+ description: 'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'
11801
+ }
11802
+ }
11803
+ }
10920
11804
  }
10921
11805
  ];
10922
11806
  var LOCAL_TOOL_NAMES = new Set(LOCAL_TOOLS.map((t) => t.name));
@@ -11121,6 +12005,104 @@ async function dispatchLocalTool(engine, name, args) {
11121
12005
  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
12006
  };
11123
12007
  }
12008
+ case "check_spec_drift": {
12009
+ const report = await engine.checkSpecDrift({
12010
+ manifestPath: str(args.manifest),
12011
+ contracts: Array.isArray(args.contracts) ? args.contracts.filter((c) => typeof c === "string") : void 0,
12012
+ includeBaseline: args.include_baseline !== false
12013
+ });
12014
+ const of = (s) => report.findings.filter((f) => f.status === s);
12015
+ const open2 = of("open");
12016
+ const warn = of("warn");
12017
+ const info = of("info");
12018
+ const base = {
12019
+ manifest: report.facts.manifestPath,
12020
+ base_ref: report.facts.baseRef,
12021
+ skipped: report.facts.skipped
12022
+ };
12023
+ if (report.verdict === "no_opinion") {
12024
+ return {
12025
+ ...base,
12026
+ ok: false,
12027
+ verdict: "no_opinion",
12028
+ reason: report.reason,
12029
+ contracts: [],
12030
+ findings: [],
12031
+ 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.`
12032
+ };
12033
+ }
12034
+ 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.";
12035
+ const unreadable2 = open2.filter((f) => f.id.startsWith("contract.unreadable:"));
12036
+ return {
12037
+ ...base,
12038
+ ok: report.ok,
12039
+ verdict: report.verdict,
12040
+ contracts: report.contracts,
12041
+ open_count: open2.length,
12042
+ warn_count: warn.length,
12043
+ preexisting_count: info.length,
12044
+ findings: [...open2, ...warn],
12045
+ // Inventory as a count plus ids, so an adopting repo with a large
12046
+ // backlog does not drown the answer it actually asked for.
12047
+ preexisting: info.map((f) => f.id),
12048
+ coverage_note: coverageNote,
12049
+ 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
12050
+ };
12051
+ }
12052
+ case "check_theme_class_drift": {
12053
+ const dir = str(args.dir);
12054
+ let repoRoot;
12055
+ let scanDirs;
12056
+ if (dir !== void 0) {
12057
+ const anchored = resolveRepoRootForDir(dir);
12058
+ if (anchored === null) {
12059
+ return {
12060
+ ok: false,
12061
+ verdict: "no_opinion",
12062
+ reason: "dir_not_found",
12063
+ repo_root: null,
12064
+ token_count: null,
12065
+ findings: [],
12066
+ hint: "No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."
12067
+ };
12068
+ }
12069
+ repoRoot = anchored.repoRoot;
12070
+ scanDirs = anchored.repoRelDir === "" ? void 0 : [anchored.repoRelDir];
12071
+ } else {
12072
+ repoRoot = resolveRepoRoot2();
12073
+ scanDirs = void 0;
12074
+ }
12075
+ const report = checkThemeClassDrift(repoRoot, { dirs: scanDirs });
12076
+ if (report.verdict === "no_opinion") {
12077
+ return {
12078
+ ok: false,
12079
+ verdict: "no_opinion",
12080
+ reason: "no_theme_tokens",
12081
+ repo_root: repoRoot,
12082
+ token_count: 0,
12083
+ findings: [],
12084
+ hint: "No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."
12085
+ };
12086
+ }
12087
+ const coverage = "Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness).";
12088
+ return {
12089
+ ok: report.ok,
12090
+ verdict: report.verdict,
12091
+ // Ausweis des tatsächlich gescannten Repos: verschachtelte Checkouts
12092
+ // darin sind eigene Repositories und werden hier NICHT erfasst.
12093
+ repo_root: repoRoot,
12094
+ token_count: report.tokenCount,
12095
+ namespace_count: report.namespaceCount,
12096
+ scanned_files: report.scannedFiles,
12097
+ findings: report.findings.map((f) => ({
12098
+ file: f.file,
12099
+ class: f.klass,
12100
+ missing_token: f.token,
12101
+ namespace: f.namespace
12102
+ })),
12103
+ hint: (report.ok ? `All house-namespace classes are covered (${report.tokenCount} tokens, ${report.namespaceCount} namespaces).` : `${report.findings.length} dead class(es): each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`) + " " + coverage
12104
+ };
12105
+ }
11124
12106
  case "codebase_search": {
11125
12107
  const query = str(args.query);
11126
12108
  if (!query) throw new Error("codebase_search requires a 'query' string");