@maind-dev/mcp-bridge 0.37.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.
Files changed (3) hide show
  1. package/build/index.js +1175 -108
  2. package/build/meta.json +1 -1
  3. package/package.json +15 -16
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.37.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();
@@ -2970,6 +3667,18 @@ function normalizeMachineLabel(raw) {
2970
3667
  const v = raw.trim().slice(0, 100);
2971
3668
  return v.length > 0 ? v : null;
2972
3669
  }
3670
+ function staticIdentity(env, id) {
3671
+ let current = id;
3672
+ const fromEnv = (env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
3673
+ const source = UUID_RE2.test(fromEnv) && fromEnv === id ? "env" : "random";
3674
+ return {
3675
+ current: () => ({ id: current, source, aliases: [] }),
3676
+ tryUpgrade: () => false,
3677
+ adopt: (canon) => {
3678
+ if (UUID_RE2.test(canon)) current = canon.trim().toLowerCase();
3679
+ }
3680
+ };
3681
+ }
2973
3682
  var REFRESH_THROTTLE_MS, TTL_MINUTES, BACKOFF_BASE_MS, BACKOFF_CAP_MS, END_TIMEOUT_MS, UUID_RE2, PresenceAnnouncer;
2974
3683
  var init_presence = __esm({
2975
3684
  "src/presence.ts"() {
@@ -2993,8 +3702,8 @@ var init_presence = __esm({
2993
3702
  workingPathsEnabled;
2994
3703
  deriveWorkingPaths;
2995
3704
  snapshot;
3705
+ identity;
2996
3706
  lastBranch = null;
2997
- sessionId;
2998
3707
  lastAnnounceAt = 0;
2999
3708
  inFlight = false;
3000
3709
  consecutiveFailures = 0;
@@ -3013,7 +3722,11 @@ var init_presence = __esm({
3013
3722
  this.workingPathsEnabled = autoWorkingPathsEnabled(env, config);
3014
3723
  this.deriveWorkingPaths = deps.deriveWorkingPaths ?? null;
3015
3724
  this.snapshot = deps.snapshot ?? null;
3016
- this.sessionId = resolveClientSessionId(env);
3725
+ this.identity = deps.identity ?? staticIdentity(env, resolveClientSessionId(env));
3726
+ }
3727
+ /** Aktuelle (kanonische) Session-ID — kann per Upgrade/Adoption wechseln. */
3728
+ get sessionId() {
3729
+ return this.identity.current().id;
3017
3730
  }
3018
3731
  get isEnabled() {
3019
3732
  return this.enabled;
@@ -3082,9 +3795,14 @@ var init_presence = __esm({
3082
3795
  }
3083
3796
  async send(status) {
3084
3797
  if (this.projectKey === null) return;
3798
+ try {
3799
+ if (status === "active") this.identity.tryUpgrade();
3800
+ } catch {
3801
+ }
3802
+ const ident = this.identity.current();
3085
3803
  const args = {
3086
3804
  project_key: this.projectKey,
3087
- session_id: this.sessionId,
3805
+ session_id: ident.id,
3088
3806
  status,
3089
3807
  ttl_minutes: TTL_MINUTES,
3090
3808
  // Self-declaration (migration 20260801120000). The server CANNOT derive
@@ -3100,6 +3818,8 @@ var init_presence = __esm({
3100
3818
  announce_source: "bridge"
3101
3819
  };
3102
3820
  if (status === "active") {
3821
+ args.identity_source = ident.source;
3822
+ if (ident.aliases.length > 0) args.also_known_as = ident.aliases;
3103
3823
  const branch = await this.gitBranch();
3104
3824
  if (branch) args.branch = branch;
3105
3825
  this.lastBranch = branch;
@@ -3113,6 +3833,15 @@ var init_presence = __esm({
3113
3833
  }
3114
3834
  }
3115
3835
  const payload = await this.postToolCall("announce_session", args);
3836
+ if (status === "active" && payload !== null && typeof payload === "object") {
3837
+ const p = payload;
3838
+ if (p.ok === true && typeof p.session_id === "string") {
3839
+ try {
3840
+ this.identity.adopt(p.session_id);
3841
+ } catch {
3842
+ }
3843
+ }
3844
+ }
3116
3845
  if (this.snapshot) {
3117
3846
  try {
3118
3847
  if (status === "ended") {
@@ -3139,7 +3868,7 @@ var init_presence = __esm({
3139
3868
  import {
3140
3869
  mkdirSync as mkdirSync4,
3141
3870
  readdirSync as readdirSync4,
3142
- readFileSync as readFileSync7,
3871
+ readFileSync as readFileSync8,
3143
3872
  renameSync as renameSync2,
3144
3873
  statSync as statSync3,
3145
3874
  unlinkSync,
@@ -3243,7 +3972,7 @@ function readSnapshots(projectKey, baseDir = presenceSnapshotBaseDir()) {
3243
3972
  if (!name.endsWith(".json")) continue;
3244
3973
  try {
3245
3974
  const raw = JSON.parse(
3246
- readFileSync7(join14(dir, name), "utf8")
3975
+ readFileSync8(join14(dir, name), "utf8")
3247
3976
  );
3248
3977
  const snap = parseSnapshot(raw);
3249
3978
  if (snap) out2.push(snap);
@@ -3289,6 +4018,225 @@ var init_presence_snapshot = __esm({
3289
4018
  }
3290
4019
  });
3291
4020
 
4021
+ // src/session-identity.ts
4022
+ import { execFileSync as execFileSync7 } from "node:child_process";
4023
+ import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
4024
+ import {
4025
+ existsSync as existsSync8,
4026
+ mkdirSync as mkdirSync5,
4027
+ readdirSync as readdirSync5,
4028
+ readFileSync as readFileSync9,
4029
+ renameSync as renameSync3,
4030
+ statSync as statSync4,
4031
+ unlinkSync as unlinkSync2,
4032
+ writeFileSync as writeFileSync4
4033
+ } from "node:fs";
4034
+ import { homedir as homedir4 } from "node:os";
4035
+ import { basename as basename2, join as join15 } from "node:path";
4036
+ function identityDirPath(baseDir) {
4037
+ return join15(baseDir ?? join15(homedir4(), ".maind", "presence"), "identity");
4038
+ }
4039
+ function transcriptStemOf(transcriptPath, sessionId) {
4040
+ if (transcriptPath) {
4041
+ const stem = basename2(transcriptPath).replace(/\.jsonl$/i, "");
4042
+ if (UUID_RE3.test(stem)) return stem.toLowerCase();
4043
+ }
4044
+ if (sessionId && UUID_RE3.test(sessionId)) return sessionId.toLowerCase();
4045
+ return null;
4046
+ }
4047
+ function writeAgentIdentityFile(opts) {
4048
+ const now = opts.nowMs ?? Date.now();
4049
+ mkdirSync5(opts.dir, { recursive: true, mode: 448 });
4050
+ const file = join15(opts.dir, `${opts.agentPid}.json`);
4051
+ const tmp = `${file}.tmp-${process.pid}`;
4052
+ const payload = {
4053
+ v: 1,
4054
+ session_id: opts.sessionId,
4055
+ transcript_stem: opts.transcriptStem,
4056
+ cwd: opts.cwd,
4057
+ agent_pid: opts.agentPid,
4058
+ written_at: new Date(now).toISOString()
4059
+ };
4060
+ writeFileSync4(tmp, JSON.stringify(payload, null, 2) + "\n", { mode: 384 });
4061
+ renameSync3(tmp, file);
4062
+ pruneIdentityDir(opts.dir, now);
4063
+ }
4064
+ function identityFileStale(dir, agentPid, maxAgeMs, nowMs = Date.now()) {
4065
+ try {
4066
+ const st = statSync4(join15(dir, `${agentPid}.json`));
4067
+ return nowMs - st.mtimeMs > maxAgeMs;
4068
+ } catch {
4069
+ return true;
4070
+ }
4071
+ }
4072
+ function deleteAgentIdentityFile(dir, agentPid) {
4073
+ try {
4074
+ unlinkSync2(join15(dir, `${agentPid}.json`));
4075
+ } catch {
4076
+ }
4077
+ }
4078
+ function pruneIdentityDir(dir, nowMs) {
4079
+ try {
4080
+ for (const f of readdirSync5(dir)) {
4081
+ if (!f.endsWith(".json")) continue;
4082
+ try {
4083
+ const st = statSync4(join15(dir, f));
4084
+ if (nowMs - st.mtimeMs > IDENTITY_TTL_MS) unlinkSync2(join15(dir, f));
4085
+ } catch {
4086
+ }
4087
+ }
4088
+ } catch {
4089
+ }
4090
+ }
4091
+ function readAgentIdentityFile(opts) {
4092
+ const file = join15(opts.dir, `${opts.agentPid}.json`);
4093
+ try {
4094
+ if (!existsSync8(file)) return null;
4095
+ const st = statSync4(file);
4096
+ if (st.mtimeMs < opts.bridgeStartMs - IDENTITY_MAX_AGE_SLACK_MS) {
4097
+ return null;
4098
+ }
4099
+ const parsed = JSON.parse(readFileSync9(file, "utf8"));
4100
+ if (typeof parsed !== "object" || parsed === null) return null;
4101
+ const o = parsed;
4102
+ if (o.v !== 1) return null;
4103
+ if (typeof o.transcript_stem !== "string" || !UUID_RE3.test(o.transcript_stem)) {
4104
+ return null;
4105
+ }
4106
+ if (typeof o.session_id !== "string" || typeof o.cwd !== "string") return null;
4107
+ if (o.agent_pid !== opts.agentPid) return null;
4108
+ if (normDir(o.cwd) !== normDir(opts.cwd)) return null;
4109
+ return o;
4110
+ } catch {
4111
+ return null;
4112
+ }
4113
+ }
4114
+ function normDir(p) {
4115
+ return p.replace(/\/+$/, "");
4116
+ }
4117
+ function uuidV5(name, namespace) {
4118
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
4119
+ const hash = createHash5("sha1").update(ns).update(name, "utf8").digest();
4120
+ const b = Buffer.from(hash.subarray(0, 16));
4121
+ b[6] = b[6] & 15 | 80;
4122
+ b[8] = b[8] & 63 | 128;
4123
+ const h = b.toString("hex");
4124
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
4125
+ }
4126
+ function processStartTime(pid) {
4127
+ if (process.platform === "win32") return null;
4128
+ try {
4129
+ const out2 = execFileSync7("ps", ["-o", "lstart=", "-p", String(pid)], {
4130
+ timeout: 1e3,
4131
+ encoding: "utf8"
4132
+ }).trim().replace(/\s+/g, " ");
4133
+ return out2.length > 0 ? out2 : null;
4134
+ } catch {
4135
+ return null;
4136
+ }
4137
+ }
4138
+ function defaultDeviceId() {
4139
+ try {
4140
+ return ensureDeviceId();
4141
+ } catch {
4142
+ return null;
4143
+ }
4144
+ }
4145
+ var UUID_RE3, MAX_ALIASES, IDENTITY_TTL_MS, IDENTITY_MAX_AGE_SLACK_MS, MAIND_SESSION_NAMESPACE, SessionIdentityManager;
4146
+ var init_session_identity = __esm({
4147
+ "src/session-identity.ts"() {
4148
+ "use strict";
4149
+ init_device_id();
4150
+ UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4151
+ MAX_ALIASES = 8;
4152
+ IDENTITY_TTL_MS = 48 * 60 * 6e4;
4153
+ IDENTITY_MAX_AGE_SLACK_MS = 6e4;
4154
+ MAIND_SESSION_NAMESPACE = "9f3c72da-2f10-4b8f-9c31-ad291c0de291";
4155
+ SessionIdentityManager = class {
4156
+ env;
4157
+ agentPid;
4158
+ cwd;
4159
+ dir;
4160
+ bridgeStartMs;
4161
+ nowMs;
4162
+ envId;
4163
+ id;
4164
+ source;
4165
+ aliases = [];
4166
+ constructor(deps) {
4167
+ this.env = deps.env ?? process.env;
4168
+ this.agentPid = deps.agentPid ?? process.ppid;
4169
+ this.cwd = deps.cwd ?? process.cwd();
4170
+ this.dir = deps.identityDir ?? identityDirPath();
4171
+ this.bridgeStartMs = deps.bridgeStartMs ?? Date.now();
4172
+ this.nowMs = deps.nowMs ?? Date.now;
4173
+ const rawEnv = (this.env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
4174
+ this.envId = UUID_RE3.test(rawEnv) ? rawEnv : null;
4175
+ const stem = this.readStem();
4176
+ if (stem !== null) {
4177
+ this.id = stem;
4178
+ this.source = "client_native";
4179
+ if (this.envId && this.envId !== stem) this.aliases = [this.envId];
4180
+ return;
4181
+ }
4182
+ if (this.envId !== null) {
4183
+ this.id = this.envId;
4184
+ this.source = "env";
4185
+ return;
4186
+ }
4187
+ const device = (deps.deviceId ?? defaultDeviceId)();
4188
+ const start = (deps.ppidStart ?? processStartTime)(this.agentPid);
4189
+ if (device !== null && start !== null && deps.projectKey !== null) {
4190
+ this.id = uuidV5(
4191
+ `${device}|${this.agentPid}|${start}|${deps.projectKey}`,
4192
+ MAIND_SESSION_NAMESPACE
4193
+ );
4194
+ this.source = "derived";
4195
+ return;
4196
+ }
4197
+ this.id = randomUUID3();
4198
+ this.source = "random";
4199
+ }
4200
+ current() {
4201
+ return { id: this.id, source: this.source, aliases: [...this.aliases] };
4202
+ }
4203
+ tryUpgrade() {
4204
+ if (this.source === "client_native") return false;
4205
+ const stem = this.readStem();
4206
+ if (stem === null || stem === this.id) return false;
4207
+ const prev = this.id;
4208
+ this.id = stem;
4209
+ this.source = "client_native";
4210
+ this.pushAlias(prev);
4211
+ if (this.envId !== null) this.pushAlias(this.envId);
4212
+ return true;
4213
+ }
4214
+ adopt(canonicalId) {
4215
+ const canon = canonicalId.trim().toLowerCase();
4216
+ if (!UUID_RE3.test(canon) || canon === this.id) return;
4217
+ const prev = this.id;
4218
+ this.id = canon;
4219
+ this.pushAlias(prev);
4220
+ }
4221
+ pushAlias(id) {
4222
+ if (id === this.id || this.aliases.includes(id)) return;
4223
+ this.aliases.push(id);
4224
+ if (this.aliases.length > MAX_ALIASES) this.aliases.shift();
4225
+ }
4226
+ readStem() {
4227
+ const f = readAgentIdentityFile({
4228
+ dir: this.dir,
4229
+ agentPid: this.agentPid,
4230
+ cwd: this.cwd,
4231
+ bridgeStartMs: this.bridgeStartMs,
4232
+ nowMs: this.nowMs()
4233
+ });
4234
+ return f === null ? null : f.transcript_stem.toLowerCase();
4235
+ }
4236
+ };
4237
+ }
4238
+ });
4239
+
3292
4240
  // ../../packages/claude-code-telemetry/dist/types.js
3293
4241
  var init_types4 = __esm({
3294
4242
  "../../packages/claude-code-telemetry/dist/types.js"() {
@@ -3297,11 +4245,11 @@ var init_types4 = __esm({
3297
4245
  });
3298
4246
 
3299
4247
  // ../../packages/claude-code-telemetry/dist/transcript.js
3300
- import { createReadStream, existsSync as existsSync7 } from "node:fs";
4248
+ import { createReadStream, existsSync as existsSync9 } from "node:fs";
3301
4249
  import { stat } from "node:fs/promises";
3302
4250
  import { createInterface as createInterface5 } from "node:readline";
3303
4251
  async function summariseTranscript(path8) {
3304
- if (!path8 || !existsSync7(path8))
4252
+ if (!path8 || !existsSync9(path8))
3305
4253
  return null;
3306
4254
  let stats;
3307
4255
  try {
@@ -3386,7 +4334,7 @@ var init_effort = __esm({
3386
4334
  });
3387
4335
 
3388
4336
  // ../../packages/claude-code-telemetry/dist/session-analysis.js
3389
- import { createReadStream as createReadStream2, existsSync as existsSync8 } from "node:fs";
4337
+ import { createReadStream as createReadStream2, existsSync as existsSync10 } from "node:fs";
3390
4338
  import { createInterface as createInterface6 } from "node:readline";
3391
4339
  function num2(v) {
3392
4340
  return typeof v === "number" && Number.isFinite(v) ? v : 0;
@@ -3493,7 +4441,7 @@ function emptyAnalysis(sessionId) {
3493
4441
  }
3494
4442
  async function analyzeSession(path8) {
3495
4443
  const a = emptyAnalysis("");
3496
- if (!path8 || !existsSync8(path8))
4444
+ if (!path8 || !existsSync10(path8))
3497
4445
  return a;
3498
4446
  const reactions = [];
3499
4447
  const modelMix = /* @__PURE__ */ new Map();
@@ -3689,7 +4637,7 @@ var init_ingest = __esm({
3689
4637
  });
3690
4638
 
3691
4639
  // ../../packages/claude-code-telemetry/dist/session-span.js
3692
- import { createReadStream as createReadStream3, existsSync as existsSync9 } from "node:fs";
4640
+ import { createReadStream as createReadStream3, existsSync as existsSync11 } from "node:fs";
3693
4641
  import { createInterface as createInterface7 } from "node:readline";
3694
4642
  function asBlocks2(content) {
3695
4643
  if (typeof content === "string")
@@ -3741,7 +4689,7 @@ function classify2(parsed) {
3741
4689
  }
3742
4690
  async function analyzeSpan(path8) {
3743
4691
  const s = emptySpan("");
3744
- if (!path8 || !existsSync9(path8))
4692
+ if (!path8 || !existsSync11(path8))
3745
4693
  return s;
3746
4694
  let firstMs = null;
3747
4695
  let lastMs = 0;
@@ -3853,14 +4801,14 @@ var init_windows = __esm({
3853
4801
  });
3854
4802
 
3855
4803
  // ../../packages/claude-code-telemetry/dist/projects.js
3856
- import { homedir as homedir4 } from "node:os";
3857
- import { join as join15 } from "node:path";
4804
+ import { homedir as homedir5 } from "node:os";
4805
+ import { join as join16 } from "node:path";
3858
4806
  var HOME, DEFAULT_PROJECTS_DIR;
3859
4807
  var init_projects = __esm({
3860
4808
  "../../packages/claude-code-telemetry/dist/projects.js"() {
3861
4809
  "use strict";
3862
- HOME = homedir4();
3863
- DEFAULT_PROJECTS_DIR = join15(HOME, ".claude", "projects");
4810
+ HOME = homedir5();
4811
+ DEFAULT_PROJECTS_DIR = join16(HOME, ".claude", "projects");
3864
4812
  }
3865
4813
  });
3866
4814
 
@@ -4108,14 +5056,14 @@ var init_payloads = __esm({
4108
5056
 
4109
5057
  // src/hooks/state.ts
4110
5058
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, rename as rename2 } from "node:fs/promises";
4111
- import { existsSync as existsSync10 } from "node:fs";
4112
- import { homedir as homedir5 } from "node:os";
4113
- import { join as join16 } from "node:path";
5059
+ import { existsSync as existsSync12 } from "node:fs";
5060
+ import { homedir as homedir6 } from "node:os";
5061
+ import { join as join17 } from "node:path";
4114
5062
  function emptyState() {
4115
5063
  return { config: null, sessions: {}, pending_metrics: [] };
4116
5064
  }
4117
5065
  async function loadState() {
4118
- if (!existsSync10(STATE_FILE)) return emptyState();
5066
+ if (!existsSync12(STATE_FILE)) return emptyState();
4119
5067
  try {
4120
5068
  const raw = await readFile2(STATE_FILE, "utf-8");
4121
5069
  const parsed = JSON.parse(raw);
@@ -4136,7 +5084,7 @@ async function loadState() {
4136
5084
  }
4137
5085
  }
4138
5086
  async function saveState(state) {
4139
- if (!existsSync10(STATE_DIR)) {
5087
+ if (!existsSync12(STATE_DIR)) {
4140
5088
  await mkdir2(STATE_DIR, { recursive: true, mode: 448 });
4141
5089
  }
4142
5090
  const tmp = `${STATE_FILE}.tmp`;
@@ -4150,8 +5098,8 @@ var STATE_DIR, STATE_FILE, DEFAULT_THRESHOLDS;
4150
5098
  var init_state = __esm({
4151
5099
  "src/hooks/state.ts"() {
4152
5100
  "use strict";
4153
- STATE_DIR = join16(homedir5(), ".maind");
4154
- STATE_FILE = join16(STATE_DIR, "state.json");
5101
+ STATE_DIR = join17(homedir6(), ".maind");
5102
+ STATE_FILE = join17(STATE_DIR, "state.json");
4155
5103
  DEFAULT_THRESHOLDS = {
4156
5104
  warn_at_pct: 60,
4157
5105
  handoff_at_pct: 85,
@@ -4176,11 +5124,11 @@ __export(hooks_exports, {
4176
5124
  runSessionEndMetrics: () => runSessionEndMetrics,
4177
5125
  runSyncConfig: () => runSyncConfig
4178
5126
  });
4179
- import { execFileSync as execFileSync7 } from "node:child_process";
4180
- import { existsSync as existsSync11, readFileSync as readFileSync8, realpathSync as realpathSync2 } from "node:fs";
5127
+ import { execFileSync as execFileSync8 } from "node:child_process";
5128
+ import { existsSync as existsSync13, readFileSync as readFileSync10, realpathSync as realpathSync2 } from "node:fs";
4181
5129
  import { writeFile as writeFile3 } from "node:fs/promises";
4182
- import { homedir as homedir6 } from "node:os";
4183
- import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute4, join as join17, relative as relative3 } from "node:path";
5130
+ import { homedir as homedir7 } from "node:os";
5131
+ import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute4, join as join18, relative as relative3 } from "node:path";
4184
5132
  function recordGuardSignals(state, sessionId, toolName, nowMs = Date.now()) {
4185
5133
  if (!toolName.includes("maind")) return;
4186
5134
  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");
@@ -4263,6 +5211,10 @@ async function runOnSessionStart() {
4263
5211
  if (sessionId === null) return 0;
4264
5212
  getOrCreateSession(state, sessionId);
4265
5213
  await saveState(state);
5214
+ try {
5215
+ writeIdentitySideChannel(input, sessionId);
5216
+ } catch {
5217
+ }
4266
5218
  try {
4267
5219
  const projectKey = computeProjectKey();
4268
5220
  if (projectKey !== null) {
@@ -4301,16 +5253,29 @@ async function runOnSessionStart() {
4301
5253
  }
4302
5254
  function readSettingsRaw() {
4303
5255
  try {
4304
- const p = join17(homedir6(), ".claude", "settings.json");
4305
- return existsSync11(p) ? readFileSync8(p, "utf8") : null;
5256
+ const p = join18(homedir7(), ".claude", "settings.json");
5257
+ return existsSync13(p) ? readFileSync10(p, "utf8") : null;
4306
5258
  } catch {
4307
5259
  return null;
4308
5260
  }
4309
5261
  }
5262
+ function writeIdentitySideChannel(input, sessionId, knownAgentPid) {
5263
+ const agentPid = knownAgentPid ?? grandparentPid();
5264
+ if (agentPid === null || agentPid === void 0) return;
5265
+ const stem = transcriptStemOf(transcriptPathOf(input) || null, sessionId);
5266
+ if (stem === null) return;
5267
+ writeAgentIdentityFile({
5268
+ dir: identityDirPath(),
5269
+ agentPid,
5270
+ sessionId,
5271
+ transcriptStem: stem,
5272
+ cwd: typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd()
5273
+ });
5274
+ }
4310
5275
  function grandparentPid() {
4311
5276
  try {
4312
5277
  if (process.platform === "win32") return null;
4313
- const out2 = execFileSync7("ps", ["-o", "ppid=", "-p", String(process.ppid)], {
5278
+ const out2 = execFileSync8("ps", ["-o", "ppid=", "-p", String(process.ppid)], {
4314
5279
  timeout: 1e3,
4315
5280
  encoding: "utf8"
4316
5281
  });
@@ -4327,6 +5292,13 @@ async function runOnToolUse() {
4327
5292
  const sessionId = sessionIdOf(input) ?? "unknown";
4328
5293
  const session = getOrCreateSession(state, sessionId);
4329
5294
  session.tool_call_count += 1;
5295
+ try {
5296
+ const agentPid = grandparentPid();
5297
+ if (sessionId !== "unknown" && agentPid !== null && identityFileStale(identityDirPath(), agentPid, IDENTITY_REFRESH_MS)) {
5298
+ writeIdentitySideChannel(input, sessionId, agentPid);
5299
+ }
5300
+ } catch {
5301
+ }
4330
5302
  const tool = (input.tool_name ?? "").toString();
4331
5303
  if (tool.includes("search_lessons") || tool.includes("get_session_briefing") || tool.includes("get_lesson")) {
4332
5304
  session.lessons_consulted += 1;
@@ -4348,15 +5320,15 @@ async function runOnToolUse() {
4348
5320
  }
4349
5321
  function realpathOfUnwritten(p) {
4350
5322
  let head = dirname6(p);
4351
- const tail = [basename2(p)];
5323
+ const tail = [basename3(p)];
4352
5324
  for (; ; ) {
4353
5325
  try {
4354
5326
  const real = realpathSync2(head);
4355
- return join17(real, ...tail.reverse());
5327
+ return join18(real, ...tail.reverse());
4356
5328
  } catch {
4357
5329
  const parent = dirname6(head);
4358
5330
  if (parent === head) return p;
4359
- tail.push(basename2(head));
5331
+ tail.push(basename3(head));
4360
5332
  head = parent;
4361
5333
  }
4362
5334
  }
@@ -4377,8 +5349,8 @@ async function runOnFileWrite() {
4377
5349
  const filePath = toolFilePathOf(input);
4378
5350
  if (!filePath) return 0;
4379
5351
  const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
4380
- const abs = isAbsolute4(filePath) ? filePath : join17(cwd, filePath);
4381
- if (existsSync11(abs)) return 0;
5352
+ const abs = isAbsolute4(filePath) ? filePath : join18(cwd, filePath);
5353
+ if (existsSync13(abs)) return 0;
4382
5354
  const repoRoot = resolveRepoRoot(cwd);
4383
5355
  const rel = relative3(repoRoot, realpathOfUnwritten(abs));
4384
5356
  if (rel.length === 0 || rel.startsWith("..") || isAbsolute4(rel)) return 0;
@@ -4398,7 +5370,7 @@ async function runOnFileEdit() {
4398
5370
  const filePath = toolFilePathOf(input);
4399
5371
  if (!filePath) return 0;
4400
5372
  const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
4401
- const abs = isAbsolute4(filePath) ? filePath : join17(cwd, filePath);
5373
+ const abs = isAbsolute4(filePath) ? filePath : join18(cwd, filePath);
4402
5374
  const projectKey = computeProjectKey();
4403
5375
  if (projectKey === null) return 0;
4404
5376
  const snaps = readSnapshots(projectKey);
@@ -4409,7 +5381,7 @@ async function runOnFileEdit() {
4409
5381
  });
4410
5382
  if (own === null) return 0;
4411
5383
  const repoRoot = resolveRepoRoot(cwd);
4412
- const real = existsSync11(abs) ? realpathSync2(abs) : realpathOfUnwritten(abs);
5384
+ const real = existsSync13(abs) ? realpathSync2(abs) : realpathOfUnwritten(abs);
4413
5385
  const rel = relative3(repoRoot, real).replace(/\\/g, "/");
4414
5386
  if (rel.length === 0 || rel.startsWith("..") || isAbsolute4(rel)) return 0;
4415
5387
  const advice = adviseOnPath(own.snap, rel, {
@@ -4426,7 +5398,7 @@ async function runOnFileEdit() {
4426
5398
  }
4427
5399
  function currentGitBranch(cwd) {
4428
5400
  try {
4429
- const out2 = execFileSync7("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
5401
+ const out2 = execFileSync8("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
4430
5402
  cwd,
4431
5403
  timeout: 1e3,
4432
5404
  encoding: "utf8"
@@ -4461,7 +5433,7 @@ async function maybeEmitAdvisory(state, session) {
4461
5433
  };
4462
5434
  try {
4463
5435
  await writeFile3(
4464
- join17(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
5436
+ join18(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
4465
5437
  JSON.stringify(payload, null, 2)
4466
5438
  );
4467
5439
  } catch (err) {
@@ -4581,10 +5553,10 @@ async function runHookStatus() {
4581
5553
  return 0;
4582
5554
  }
4583
5555
  function readHookWiring() {
4584
- const settingsPath = join17(homedir6(), ".claude", "settings.json");
5556
+ const settingsPath = join18(homedir7(), ".claude", "settings.json");
4585
5557
  let raw = null;
4586
5558
  try {
4587
- if (existsSync11(settingsPath)) raw = readFileSync8(settingsPath, "utf8");
5559
+ if (existsSync13(settingsPath)) raw = readFileSync10(settingsPath, "utf8");
4588
5560
  } catch {
4589
5561
  }
4590
5562
  return { settingsPath, findings: inspectHookWiring(raw) };
@@ -4658,7 +5630,7 @@ function sessionIdOf(input) {
4658
5630
  const id = typeof input.session_id === "string" ? input.session_id.trim() : "";
4659
5631
  return id.length > 0 ? id : null;
4660
5632
  }
4661
- var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS, STATE_GC_TTL_MS, WIRING_REMEDY;
5633
+ var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS, STATE_GC_TTL_MS, IDENTITY_REFRESH_MS, WIRING_REMEDY;
4662
5634
  var init_hooks2 = __esm({
4663
5635
  "src/hooks/index.ts"() {
4664
5636
  "use strict";
@@ -4671,6 +5643,7 @@ var init_hooks2 = __esm({
4671
5643
  init_project_key();
4672
5644
  init_api();
4673
5645
  init_edit_guard();
5646
+ init_session_identity();
4674
5647
  init_hook_input();
4675
5648
  init_payloads();
4676
5649
  init_state();
@@ -4678,6 +5651,7 @@ var init_hooks2 = __esm({
4678
5651
  STOP_FLUSH_TIMEOUT_MS = 1500;
4679
5652
  MANUAL_FLUSH_TIMEOUT_MS = 1e4;
4680
5653
  STATE_GC_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
5654
+ IDENTITY_REFRESH_MS = 6e4;
4681
5655
  WIRING_REMEDY = "Re-run `maind-mcp-bridge install` to add the missing hooks \u2014 it is append-only and idempotent: it adds only what is absent, asks consent per hook, and never rewrites an entry you already have.";
4682
5656
  }
4683
5657
  });
@@ -4725,8 +5699,21 @@ function connectionVerdict(sawMaindCall, nowMs) {
4725
5699
  }
4726
5700
  }
4727
5701
  function presenceSessionId() {
5702
+ const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5703
+ try {
5704
+ const pk = computeProjectKey();
5705
+ if (pk !== null) {
5706
+ const own = selectOwnSnapshot(readSnapshots(pk), {
5707
+ grandparentPid: grandparentPid(),
5708
+ cwd: process.cwd()
5709
+ });
5710
+ const id = own?.snap.own_session_id ?? null;
5711
+ if (id !== null && uuidRe.test(id)) return id.toLowerCase();
5712
+ }
5713
+ } catch {
5714
+ }
4728
5715
  const raw = (process.env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
4729
- return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(raw) ? raw : null;
5716
+ return uuidRe.test(raw) ? raw : null;
4730
5717
  }
4731
5718
  async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
4732
5719
  const post = fetch(INGEST_ENDPOINT, {
@@ -4743,6 +5730,13 @@ async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
4743
5730
  await Promise.race([post, timeout]);
4744
5731
  }
4745
5732
  async function runOnSessionEnd() {
5733
+ try {
5734
+ const agentPid = grandparentPid();
5735
+ if (agentPid !== null) {
5736
+ deleteAgentIdentityFile(identityDirPath(), agentPid);
5737
+ }
5738
+ } catch {
5739
+ }
4746
5740
  const apiKey = readApiKey();
4747
5741
  if (!apiKey) return 0;
4748
5742
  const input = await readHookInput();
@@ -4798,6 +5792,7 @@ var init_session_end = __esm({
4798
5792
  init_presence();
4799
5793
  init_presence_snapshot();
4800
5794
  init_project_key();
5795
+ init_session_identity();
4801
5796
  init_version();
4802
5797
  init_connection();
4803
5798
  INGEST_ENDPOINT = DEFAULT_INGEST_ENDPOINT;
@@ -4925,16 +5920,16 @@ var init_install = __esm({
4925
5920
  });
4926
5921
 
4927
5922
  // src/guard/session-file.ts
4928
- import { existsSync as existsSync12 } from "node:fs";
5923
+ import { existsSync as existsSync14 } from "node:fs";
4929
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";
4930
- import { join as join18 } from "node:path";
5925
+ import { join as join19 } from "node:path";
4931
5926
  function sessionFile(sessionId) {
4932
- return join18(GUARD_SESSIONS_DIR, sessionId.replace(/[^a-zA-Z0-9._-]/g, "_") + ".json");
5927
+ return join19(GUARD_SESSIONS_DIR, sessionId.replace(/[^a-zA-Z0-9._-]/g, "_") + ".json");
4933
5928
  }
4934
5929
  async function loadGuardSession(sessionId) {
4935
5930
  try {
4936
5931
  const file = sessionFile(sessionId);
4937
- if (!existsSync12(file)) return {};
5932
+ if (!existsSync14(file)) return {};
4938
5933
  const parsed = JSON.parse(await readFile3(file, "utf8"));
4939
5934
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
4940
5935
  return parsed;
@@ -4955,10 +5950,10 @@ async function saveGuardSession(sessionId, state) {
4955
5950
  }
4956
5951
  async function sweepOldGuardSessions(maxAgeMs = 7 * 24 * 60 * 60 * 1e3, nowMs = Date.now()) {
4957
5952
  try {
4958
- if (!existsSync12(GUARD_SESSIONS_DIR)) return;
5953
+ if (!existsSync14(GUARD_SESSIONS_DIR)) return;
4959
5954
  for (const name of await readdir(GUARD_SESSIONS_DIR)) {
4960
5955
  if (!name.endsWith(".json")) continue;
4961
- const file = join18(GUARD_SESSIONS_DIR, name);
5956
+ const file = join19(GUARD_SESSIONS_DIR, name);
4962
5957
  try {
4963
5958
  const s = await stat2(file);
4964
5959
  if (nowMs - s.mtimeMs > maxAgeMs) await unlink2(file);
@@ -4973,15 +5968,15 @@ var init_session_file = __esm({
4973
5968
  "src/guard/session-file.ts"() {
4974
5969
  "use strict";
4975
5970
  init_state();
4976
- GUARD_DIR = join18(STATE_DIR, "guard");
4977
- GUARD_SESSIONS_DIR = join18(GUARD_DIR, "sessions");
5971
+ GUARD_DIR = join19(STATE_DIR, "guard");
5972
+ GUARD_SESSIONS_DIR = join19(GUARD_DIR, "sessions");
4978
5973
  }
4979
5974
  });
4980
5975
 
4981
5976
  // src/guard/log.ts
4982
- import { existsSync as existsSync13 } from "node:fs";
5977
+ import { existsSync as existsSync15 } from "node:fs";
4983
5978
  import { appendFile, mkdir as mkdir4, open } from "node:fs/promises";
4984
- import { join as join19 } from "node:path";
5979
+ import { join as join20 } from "node:path";
4985
5980
  async function appendGuardEvent(event) {
4986
5981
  try {
4987
5982
  await mkdir4(GUARD_DIR, { recursive: true, mode: 448 });
@@ -5003,7 +5998,7 @@ async function readGuardEventCounts(tailBytes = 256 * 1024) {
5003
5998
  cross_session_deny: 0
5004
5999
  };
5005
6000
  try {
5006
- if (!existsSync13(GUARD_EVENTS_FILE)) return counts;
6001
+ if (!existsSync15(GUARD_EVENTS_FILE)) return counts;
5007
6002
  const fh = await open(GUARD_EVENTS_FILE, "r");
5008
6003
  try {
5009
6004
  const size = (await fh.stat()).size;
@@ -5034,7 +6029,7 @@ var init_log = __esm({
5034
6029
  "src/guard/log.ts"() {
5035
6030
  "use strict";
5036
6031
  init_session_file();
5037
- GUARD_EVENTS_FILE = join19(GUARD_DIR, "events.jsonl");
6032
+ GUARD_EVENTS_FILE = join20(GUARD_DIR, "events.jsonl");
5038
6033
  }
5039
6034
  });
5040
6035
 
@@ -5043,15 +6038,15 @@ var cli_exports = {};
5043
6038
  __export(cli_exports, {
5044
6039
  runGuard: () => runGuard
5045
6040
  });
5046
- import { existsSync as existsSync14, readFileSync as readFileSync9 } from "node:fs";
5047
- import { homedir as homedir7 } from "node:os";
5048
- import { join as join20 } from "node:path";
6041
+ import { existsSync as existsSync16, readFileSync as readFileSync11 } from "node:fs";
6042
+ import { homedir as homedir8 } from "node:os";
6043
+ import { join as join21 } from "node:path";
5049
6044
  async function runGuard(argv) {
5050
6045
  const verb = argv[0];
5051
6046
  const rest = argv.slice(1);
5052
6047
  switch (verb) {
5053
6048
  case "install":
5054
- return runGuardInstall(rest, homedir7());
6049
+ return runGuardInstall(rest, homedir8());
5055
6050
  case "status":
5056
6051
  return runGuardStatus();
5057
6052
  case "mode": {
@@ -5122,10 +6117,10 @@ logged (auditable) in ${GUARD_EVENTS_FILE}
5122
6117
  }
5123
6118
  async function runGuardStatus() {
5124
6119
  const config = resolveGuardConfig();
5125
- const settingsPath = join20(homedir7(), ".claude", "settings.json");
6120
+ const settingsPath = join21(homedir8(), ".claude", "settings.json");
5126
6121
  let raw = null;
5127
6122
  try {
5128
- if (existsSync14(settingsPath)) raw = readFileSync9(settingsPath, "utf8");
6123
+ if (existsSync16(settingsPath)) raw = readFileSync11(settingsPath, "utf8");
5129
6124
  } catch {
5130
6125
  }
5131
6126
  const wiring = inspectHookWiring(raw, {}, GUARD_SUBCOMMAND_HOOKS);
@@ -5317,9 +6312,9 @@ __export(inject_exports, {
5317
6312
  resolveBriefingInjection: () => resolveBriefingInjection,
5318
6313
  runGuardInject: () => runGuardInject
5319
6314
  });
5320
- import { existsSync as existsSync15 } from "node:fs";
6315
+ import { existsSync as existsSync17 } from "node:fs";
5321
6316
  import { mkdir as mkdir5, readFile as readFile4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
5322
- import { dirname as dirname7, join as join21 } from "node:path";
6317
+ import { dirname as dirname7, join as join22 } from "node:path";
5323
6318
  async function resolveBriefingInjection(projectKey, apiKey, deps = {}) {
5324
6319
  const nowMs = deps.nowMs ?? Date.now();
5325
6320
  const cacheFile = deps.cacheFile ?? BRIEFING_CACHE_FILE;
@@ -5404,7 +6399,7 @@ function formatInjection(text, via) {
5404
6399
  }
5405
6400
  async function readCache(file) {
5406
6401
  try {
5407
- if (!existsSync15(file)) return null;
6402
+ if (!existsSync17(file)) return null;
5408
6403
  const parsed = JSON.parse(await readFile4(file, "utf8"));
5409
6404
  if (typeof parsed.fetched_at !== "string" || typeof parsed.text !== "string") return null;
5410
6405
  if (Number.isNaN(Date.parse(parsed.fetched_at))) return null;
@@ -5445,7 +6440,7 @@ var init_inject = __esm({
5445
6440
  init_log();
5446
6441
  init_session_file();
5447
6442
  init_mcp_client();
5448
- BRIEFING_CACHE_FILE = join21(GUARD_DIR, "briefing-cache.json");
6443
+ BRIEFING_CACHE_FILE = join22(GUARD_DIR, "briefing-cache.json");
5449
6444
  CACHE_TTL_MS = 12 * 60 * 60 * 1e3;
5450
6445
  FETCH_BUDGET_MS = 3e3;
5451
6446
  MAX_INJECT_BYTES = 10 * 1024;
@@ -5674,8 +6669,8 @@ var init_frames = __esm({
5674
6669
 
5675
6670
  // src/gateway/attest.ts
5676
6671
  import { appendFile as appendFile2, mkdir as mkdir6, readFile as readFile5, rename as rename5, writeFile as writeFile6 } from "node:fs/promises";
5677
- import { homedir as homedir8 } from "node:os";
5678
- import { join as join22 } from "node:path";
6672
+ import { homedir as homedir9 } from "node:os";
6673
+ import { join as join23 } from "node:path";
5679
6674
  function aggregateWindow(events, mode, serverLabel, projectKey) {
5680
6675
  if (mode === "off" || events.length === 0) return null;
5681
6676
  const counts = {};
@@ -5709,7 +6704,7 @@ function aggregateWindow(events, mode, serverLabel, projectKey) {
5709
6704
  };
5710
6705
  }
5711
6706
  function attestSpoolPath() {
5712
- return join22(homedir8(), ".maind", "gateway", "attest-spool.jsonl");
6707
+ return join23(homedir9(), ".maind", "gateway", "attest-spool.jsonl");
5713
6708
  }
5714
6709
  async function postAttestation(payload) {
5715
6710
  const apiKey = readApiKey();
@@ -5732,7 +6727,7 @@ async function postAttestation(payload) {
5732
6727
  }
5733
6728
  async function spoolAttestation(payload) {
5734
6729
  try {
5735
- await mkdir6(join22(homedir8(), ".maind", "gateway"), { recursive: true });
6730
+ await mkdir6(join23(homedir9(), ".maind", "gateway"), { recursive: true });
5736
6731
  await appendFile2(attestSpoolPath(), JSON.stringify(payload) + "\n", { mode: 384 });
5737
6732
  await capSpool();
5738
6733
  } catch {
@@ -5897,11 +6892,11 @@ var init_policy = __esm({
5897
6892
  });
5898
6893
 
5899
6894
  // src/gateway/policy-cache.ts
5900
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync10, renameSync as renameSync3, writeFileSync as writeFileSync4 } from "node:fs";
5901
- import { homedir as homedir9 } from "node:os";
5902
- import { dirname as dirname8, join as join23 } from "node:path";
6895
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync12, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "node:fs";
6896
+ import { homedir as homedir10 } from "node:os";
6897
+ import { dirname as dirname8, join as join24 } from "node:path";
5903
6898
  function policyCachePath() {
5904
- return join23(homedir9(), ".maind", "gateway", "policy-cache.json");
6899
+ return join24(homedir10(), ".maind", "gateway", "policy-cache.json");
5905
6900
  }
5906
6901
  function writePolicyCache(identity, rules, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
5907
6902
  try {
@@ -5913,16 +6908,16 @@ function writePolicyCache(identity, rules, nowIso = (/* @__PURE__ */ new Date())
5913
6908
  rules
5914
6909
  };
5915
6910
  const target = policyCachePath();
5916
- mkdirSync5(dirname8(target), { recursive: true });
6911
+ mkdirSync6(dirname8(target), { recursive: true });
5917
6912
  const tmp = `${target}.${process.pid}.tmp`;
5918
- writeFileSync4(tmp, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 384 });
5919
- renameSync3(tmp, target);
6913
+ writeFileSync5(tmp, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 384 });
6914
+ renameSync4(tmp, target);
5920
6915
  } catch {
5921
6916
  }
5922
6917
  }
5923
6918
  function readPolicyCache(identity) {
5924
6919
  try {
5925
- const raw = readFileSync10(policyCachePath(), "utf8");
6920
+ const raw = readFileSync12(policyCachePath(), "utf8");
5926
6921
  const parsed = JSON.parse(raw);
5927
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)) {
5928
6923
  return null;
@@ -6069,9 +7064,9 @@ __export(install_exports, {
6069
7064
  runGatewayInstall: () => runGatewayInstall,
6070
7065
  runGatewayUninstall: () => runGatewayUninstall
6071
7066
  });
6072
- import { existsSync as existsSync16, readFileSync as readFileSync11 } from "node:fs";
6073
- import { homedir as homedir10 } from "node:os";
6074
- import { join as join24 } from "node:path";
7067
+ import { existsSync as existsSync18, readFileSync as readFileSync13 } from "node:fs";
7068
+ import { homedir as homedir11 } from "node:os";
7069
+ import { join as join25 } from "node:path";
6075
7070
  import { createInterface as createInterface8 } from "node:readline";
6076
7071
  function parseFlags(argv) {
6077
7072
  const f = { yes: false, dryRun: false };
@@ -6084,8 +7079,8 @@ function parseFlags(argv) {
6084
7079
  }
6085
7080
  function targets() {
6086
7081
  return [
6087
- { label: "Claude Code (project .mcp.json)", path: join24(process.cwd(), ".mcp.json") },
6088
- { label: "Claude Code (user ~/.claude.json)", path: join24(homedir10(), ".claude.json") }
7082
+ { label: "Claude Code (project .mcp.json)", path: join25(process.cwd(), ".mcp.json") },
7083
+ { label: "Claude Code (user ~/.claude.json)", path: join25(homedir11(), ".claude.json") }
6089
7084
  ];
6090
7085
  }
6091
7086
  async function confirm(question) {
@@ -6115,8 +7110,8 @@ function loadConfig(path8) {
6115
7110
  }
6116
7111
  function readFileSafeSync(path8) {
6117
7112
  try {
6118
- if (!existsSync16(path8)) return null;
6119
- return readFileSync11(path8, "utf8");
7113
+ if (!existsSync18(path8)) return null;
7114
+ return readFileSync13(path8, "utf8");
6120
7115
  } catch {
6121
7116
  return null;
6122
7117
  }
@@ -6345,16 +7340,16 @@ __export(run_exports, {
6345
7340
  });
6346
7341
  import { spawn as spawn2 } from "node:child_process";
6347
7342
  import { appendFile as appendFile3, mkdir as mkdir7 } from "node:fs/promises";
6348
- import { homedir as homedir11 } from "node:os";
6349
- import { basename as basename3, join as join25 } from "node:path";
7343
+ import { homedir as homedir12 } from "node:os";
7344
+ import { basename as basename4, join as join26 } from "node:path";
6350
7345
  import { createInterface as createInterface9 } from "node:readline";
6351
7346
  function gatewayEventsFile() {
6352
- return join25(homedir11(), ".maind", "gateway", "events.jsonl");
7347
+ return join26(homedir12(), ".maind", "gateway", "events.jsonl");
6353
7348
  }
6354
7349
  async function logEvent(e) {
6355
7350
  try {
6356
7351
  const file = gatewayEventsFile();
6357
- await mkdir7(join25(homedir11(), ".maind", "gateway"), { recursive: true });
7352
+ await mkdir7(join26(homedir12(), ".maind", "gateway"), { recursive: true });
6358
7353
  await appendFile3(file, JSON.stringify(e) + "\n", { mode: 384 });
6359
7354
  } catch {
6360
7355
  }
@@ -6407,7 +7402,7 @@ async function runGateway(argv) {
6407
7402
  return 2;
6408
7403
  }
6409
7404
  const { denyTools, label, command, args } = parsed;
6410
- const serverLabel = label ?? basename3(command);
7405
+ const serverLabel = label ?? basename4(command);
6411
7406
  const mode = resolveGatewayMode();
6412
7407
  let policyRules = mode === "off" ? [] : readPolicyCache(policyIdentity())?.rules ?? [];
6413
7408
  if (mode !== "off") {
@@ -6541,10 +7536,10 @@ __export(cross_session_exports, {
6541
7536
  staleReason: () => staleReason
6542
7537
  });
6543
7538
  import { mkdir as mkdir8, readFile as readFile6, readdir as readdir2, stat as stat3, unlink as unlink3, writeFile as writeFile7 } from "node:fs/promises";
6544
- import { homedir as homedir12 } from "node:os";
6545
- import { join as join26 } from "node:path";
7539
+ import { homedir as homedir13 } from "node:os";
7540
+ import { join as join27 } from "node:path";
6546
7541
  function crossSessionDir() {
6547
- return join26(homedir12(), ".maind", "cross-session");
7542
+ return join27(homedir13(), ".maind", "cross-session");
6548
7543
  }
6549
7544
  function parseSessionDb(raw) {
6550
7545
  const empty = { files: {}, warned: {} };
@@ -6586,7 +7581,7 @@ function staleReason(path8, v) {
6586
7581
  async function dbPath(sessionId) {
6587
7582
  const dir = crossSessionDir();
6588
7583
  await mkdir8(dir, { recursive: true });
6589
- return join26(dir, `${sessionId}.json`);
7584
+ return join27(dir, `${sessionId}.json`);
6590
7585
  }
6591
7586
  async function loadDb(sessionId, now) {
6592
7587
  try {
@@ -6607,7 +7602,7 @@ async function sweepStaleSessionFiles(now) {
6607
7602
  const dir = crossSessionDir();
6608
7603
  for (const name of await readdir2(dir)) {
6609
7604
  if (!name.endsWith(".json")) continue;
6610
- const p = join26(dir, name);
7605
+ const p = join27(dir, name);
6611
7606
  const s = await stat3(p).catch(() => null);
6612
7607
  if (s && now - s.mtimeMs > TTL_MS) await unlink3(p).catch(() => {
6613
7608
  });
@@ -6692,7 +7687,7 @@ var init_cross_session = __esm({
6692
7687
  });
6693
7688
 
6694
7689
  // src/index.ts
6695
- import { randomUUID as randomUUID3 } from "node:crypto";
7690
+ import { randomUUID as randomUUID4 } from "node:crypto";
6696
7691
 
6697
7692
  // src/forward.ts
6698
7693
  import { createInterface } from "node:readline";
@@ -9280,13 +10275,13 @@ function parseNodeMajor(version) {
9280
10275
 
9281
10276
  // src/local-tools/engine.ts
9282
10277
  import { execFileSync as execFileSync6 } from "node:child_process";
9283
- import { existsSync as existsSync6, realpathSync } from "node:fs";
10278
+ import { existsSync as existsSync7, realpathSync } from "node:fs";
9284
10279
  import { createRequire as createRequire3 } from "node:module";
9285
10280
  import { basename, dirname as dirname5, isAbsolute as isAbsolute3, join as join12, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
9286
10281
 
9287
10282
  // ../../packages/code-index/build/node.js
9288
10283
  import { mkdirSync as mkdirSync3 } from "node:fs";
9289
- import { posix as posix6 } from "node:path";
10284
+ import { posix as posix7 } from "node:path";
9290
10285
 
9291
10286
  // ../../packages/code-index/build/parse/tree-sitter/parser.js
9292
10287
  init_keys();
@@ -10059,8 +11054,8 @@ init_schema();
10059
11054
  // ../../packages/code-index/build/node.js
10060
11055
  var DEFAULT_DB_RELPATH = ".maind/code-index.sqlite";
10061
11056
  function createNodeCodeIndex(opts) {
10062
- const dbPath2 = opts.dbPath ?? posix6.join(opts.repoRoot, DEFAULT_DB_RELPATH);
10063
- 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 });
10064
11059
  const store = new NodeSqliteStore(dbPath2);
10065
11060
  const parser = new TreeSitterParser();
10066
11061
  return new CodeIndexEngine({
@@ -10111,7 +11106,7 @@ function resolveRepoRootForPath(proposedPath, fallbackRoot = resolveRepoRoot2(),
10111
11106
  const candidates = isAbsolute3(proposedPath) ? [proposedPath] : [resolve3(fallbackRoot, proposedPath), resolve3(cwd, proposedPath)];
10112
11107
  for (const candidate of candidates) {
10113
11108
  const dir = dirname5(candidate);
10114
- if (!existsSync6(dir)) continue;
11109
+ if (!existsSync7(dir)) continue;
10115
11110
  let realDir;
10116
11111
  try {
10117
11112
  realDir = realpathSync(dir);
@@ -10129,7 +11124,7 @@ function resolveRepoRootForPath(proposedPath, fallbackRoot = resolveRepoRoot2(),
10129
11124
  function resolveRepoRootForDir(dirPath, fallbackRoot = resolveRepoRoot2(), cwd = process.cwd()) {
10130
11125
  const candidates = isAbsolute3(dirPath) ? [dirPath] : [resolve3(fallbackRoot, dirPath), resolve3(cwd, dirPath)];
10131
11126
  for (const candidate of candidates) {
10132
- if (!existsSync6(candidate)) continue;
11127
+ if (!existsSync7(candidate)) continue;
10133
11128
  let real;
10134
11129
  try {
10135
11130
  real = realpathSync(candidate);
@@ -10362,7 +11357,7 @@ Finished in ${wallClockSec}s. Restart your MCP client so it picks up the new ser
10362
11357
  }
10363
11358
 
10364
11359
  // src/local-tools/savings.ts
10365
- import { readFileSync as readFileSync6 } from "node:fs";
11360
+ import { readFileSync as readFileSync7 } from "node:fs";
10366
11361
  import { join as join13 } from "node:path";
10367
11362
 
10368
11363
  // src/local-tools/token-estimate.ts
@@ -10395,7 +11390,7 @@ var SavingsAggregator = class {
10395
11390
  };
10396
11391
  function readFileCapped(absPath) {
10397
11392
  try {
10398
- const content = readFileSync6(absPath, "utf8");
11393
+ const content = readFileSync7(absPath, "utf8");
10399
11394
  return content.length > MAX_FILE_BYTES ? content.slice(0, MAX_FILE_BYTES) : content;
10400
11395
  } catch {
10401
11396
  return "";
@@ -10619,6 +11614,28 @@ var LOCAL_TOOLS = [
10619
11614
  }
10620
11615
  }
10621
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
+ }
10622
11639
  }
10623
11640
  ];
10624
11641
  var LOCAL_TOOL_NAMES = new Set(LOCAL_TOOLS.map((t) => t.name));
@@ -10823,6 +11840,50 @@ async function dispatchLocalTool(engine, name, args) {
10823
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."
10824
11841
  };
10825
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
+ }
10826
11887
  case "codebase_search": {
10827
11888
  const query = str(args.query);
10828
11889
  if (!query) throw new Error("codebase_search requires a 'query' string");
@@ -11152,6 +12213,7 @@ async function postSavingsMetric(input) {
11152
12213
  // src/index.ts
11153
12214
  init_presence();
11154
12215
  init_presence_snapshot();
12216
+ init_session_identity();
11155
12217
 
11156
12218
  // src/working-paths.ts
11157
12219
  import { execFile as execFile2 } from "node:child_process";
@@ -11312,7 +12374,7 @@ async function main() {
11312
12374
  const savingsEnabled = process.env.MAIND_DISABLE_CODEBASE_TOOLS !== "1" && process.env.MAIND_DISABLE_SAVINGS_METRICS !== "1";
11313
12375
  const aggregator = savingsEnabled ? new SavingsAggregator() : null;
11314
12376
  const localRouter = process.env.MAIND_DISABLE_CODEBASE_TOOLS === "1" ? null : new LocalToolRouter(void 0, aggregator);
11315
- const savingsSessionId = `bridge-${randomUUID3()}`;
12377
+ const savingsSessionId = `bridge-${randomUUID4()}`;
11316
12378
  const flushSavings = async () => {
11317
12379
  if (!aggregator) return;
11318
12380
  const delta = aggregator.takePending();
@@ -11332,6 +12394,11 @@ async function main() {
11332
12394
  let currentForwarder = null;
11333
12395
  const presence = new PresenceAnnouncer({
11334
12396
  projectKey,
12397
+ // ADR-291 L1: abgeleitete Identität statt Würfeln — Kette Stem (Hook-
12398
+ // Seitenkanal) → MAIND_SESSION_ID → UUIDv5(device|ppid|Startzeit|repo)
12399
+ // → random. Der Announcer prüft den Seitenkanal vor jedem Announce und
12400
+ // meldet frühere Namen als also_known_as (L3a-Merge-Beweis).
12401
+ identity: new SessionIdentityManager({ projectKey }),
11335
12402
  postToolCall: (name, args) => {
11336
12403
  if (currentForwarder === null) {
11337
12404
  return Promise.reject(new Error("presence: no active forwarder"));