@maind-dev/mcp-bridge 0.14.0 → 0.17.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
@@ -27,9 +27,9 @@ function configDir() {
27
27
  const xdg = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.length > 0 ? env.XDG_CONFIG_HOME : join2(home, ".config");
28
28
  return join2(xdg, "maind");
29
29
  }
30
- function ensureDir(path6) {
31
- if (existsSync(path6)) return;
32
- mkdirSync2(path6, { recursive: true, mode: 448 });
30
+ function ensureDir(path7) {
31
+ if (existsSync(path7)) return;
32
+ mkdirSync2(path7, { recursive: true, mode: 448 });
33
33
  }
34
34
  function ensureDeviceId() {
35
35
  const dir = configDir();
@@ -97,7 +97,7 @@ var BRIDGE_VERSION;
97
97
  var init_version = __esm({
98
98
  "src/version.ts"() {
99
99
  "use strict";
100
- BRIDGE_VERSION = "0.14.0";
100
+ BRIDGE_VERSION = "0.17.0";
101
101
  }
102
102
  });
103
103
 
@@ -109,6 +109,54 @@ var init_types = __esm({
109
109
  });
110
110
 
111
111
  // ../../packages/claude-code-telemetry/dist/transcript.js
112
+ import { createReadStream, existsSync as existsSync5 } from "node:fs";
113
+ import { stat } from "node:fs/promises";
114
+ import { createInterface as createInterface4 } from "node:readline";
115
+ async function summariseTranscript(path7) {
116
+ if (!path7 || !existsSync5(path7))
117
+ return null;
118
+ let stats;
119
+ try {
120
+ stats = await stat(path7);
121
+ } catch {
122
+ return null;
123
+ }
124
+ let input = 0;
125
+ let output = 0;
126
+ let lines2 = 0;
127
+ return await new Promise((resolve2) => {
128
+ const stream = createReadStream(path7, { encoding: "utf-8" });
129
+ const rl = createInterface4({ input: stream });
130
+ rl.on("line", (line) => {
131
+ const trimmed = line.trim();
132
+ if (!trimmed)
133
+ return;
134
+ lines2++;
135
+ try {
136
+ const parsed = JSON.parse(trimmed);
137
+ const usage = parsed.message?.usage;
138
+ if (!usage)
139
+ return;
140
+ if (typeof usage.input_tokens === "number")
141
+ input += usage.input_tokens;
142
+ if (typeof usage.output_tokens === "number")
143
+ output += usage.output_tokens;
144
+ } catch {
145
+ }
146
+ });
147
+ rl.on("close", () => {
148
+ resolve2({
149
+ input_tokens: input,
150
+ output_tokens: output,
151
+ total_tokens: input + output,
152
+ lines_seen: lines2,
153
+ last_modified_ms: stats.mtimeMs
154
+ });
155
+ });
156
+ rl.on("error", () => resolve2(null));
157
+ stream.on("error", () => resolve2(null));
158
+ });
159
+ }
112
160
  var init_transcript = __esm({
113
161
  "../../packages/claude-code-telemetry/dist/transcript.js"() {
114
162
  "use strict";
@@ -150,8 +198,8 @@ var init_effort = __esm({
150
198
  });
151
199
 
152
200
  // ../../packages/claude-code-telemetry/dist/session-analysis.js
153
- import { createReadStream, existsSync as existsSync4 } from "node:fs";
154
- import { createInterface as createInterface4 } from "node:readline";
201
+ import { createReadStream as createReadStream2, existsSync as existsSync6 } from "node:fs";
202
+ import { createInterface as createInterface5 } from "node:readline";
155
203
  function num2(v) {
156
204
  return typeof v === "number" && Number.isFinite(v) ? v : 0;
157
205
  }
@@ -226,17 +274,17 @@ function emptyAnalysis(sessionId) {
226
274
  lines_seen: 0
227
275
  };
228
276
  }
229
- async function analyzeSession(path6) {
277
+ async function analyzeSession(path7) {
230
278
  const a = emptyAnalysis("");
231
- if (!path6 || !existsSync4(path6))
279
+ if (!path7 || !existsSync6(path7))
232
280
  return a;
233
281
  const reactions = [];
234
282
  let effort = null;
235
283
  let priorAssistantWorked = false;
236
284
  let prevUserText = null;
237
285
  await new Promise((resolve2) => {
238
- const stream = createReadStream(path6, { encoding: "utf-8" });
239
- const rl = createInterface4({ input: stream });
286
+ const stream = createReadStream2(path7, { encoding: "utf-8" });
287
+ const rl = createInterface5({ input: stream });
240
288
  const processLine = (line) => {
241
289
  const trimmed = line.trim();
242
290
  if (!trimmed)
@@ -425,42 +473,439 @@ var init_dist = __esm({
425
473
  }
426
474
  });
427
475
 
428
- // src/session-end/index.ts
429
- var session_end_exports = {};
430
- __export(session_end_exports, {
431
- runOnSessionEnd: () => runOnSessionEnd
476
+ // src/hooks/api.ts
477
+ function ingestHeaders(apiKey) {
478
+ return {
479
+ "content-type": "application/json",
480
+ authorization: `Bearer ${apiKey}`,
481
+ "x-maind-device-id": ensureDeviceId()
482
+ };
483
+ }
484
+ async function postMetrics(endpoint, apiKey, metrics) {
485
+ if (metrics.length === 0) return { ok: true, inserted: 0 };
486
+ try {
487
+ const res = await fetch(endpoint, {
488
+ method: "POST",
489
+ headers: ingestHeaders(apiKey),
490
+ body: JSON.stringify({ metrics })
491
+ });
492
+ if (!res.ok) {
493
+ const text = await res.text().catch(() => "");
494
+ return {
495
+ ok: false,
496
+ inserted: 0,
497
+ status: res.status,
498
+ error: text.slice(0, 500)
499
+ };
500
+ }
501
+ const json = await res.json().catch(() => null);
502
+ return {
503
+ ok: true,
504
+ inserted: json?.inserted_metrics ?? metrics.length,
505
+ status: res.status
506
+ };
507
+ } catch (err) {
508
+ return {
509
+ ok: false,
510
+ inserted: 0,
511
+ error: err instanceof Error ? err.message : String(err)
512
+ };
513
+ }
514
+ }
515
+ var DEFAULT_INGEST_ENDPOINT;
516
+ var init_api = __esm({
517
+ "src/hooks/api.ts"() {
518
+ "use strict";
519
+ init_device_id();
520
+ DEFAULT_INGEST_ENDPOINT = process.env.MAIND_ENDPOINT ?? "https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";
521
+ }
432
522
  });
523
+
524
+ // src/hooks/hook-input.ts
433
525
  async function readHookInput() {
434
526
  if (process.stdin.isTTY) return {};
435
527
  const chunks = [];
436
528
  return await new Promise((resolve2) => {
437
529
  let settled = false;
438
- const timer = setTimeout(() => {
439
- if (!settled) {
440
- settled = true;
441
- resolve2({});
442
- }
443
- }, 200);
444
- process.stdin.on("data", (c) => chunks.push(c));
445
- process.stdin.on("end", () => {
530
+ const settle = (value) => {
446
531
  if (settled) return;
447
532
  settled = true;
448
533
  clearTimeout(timer);
534
+ resolve2(value);
535
+ };
536
+ const timer = setTimeout(() => settle({}), STDIN_TIMEOUT_MS);
537
+ process.stdin.on("data", (c) => chunks.push(c));
538
+ process.stdin.on("end", () => {
449
539
  try {
450
540
  const text = Buffer.concat(chunks).toString("utf-8").trim();
451
- resolve2(text ? JSON.parse(text) : {});
541
+ settle(text ? JSON.parse(text) : {});
452
542
  } catch {
453
- resolve2({});
543
+ settle({});
454
544
  }
455
545
  });
456
- process.stdin.on("error", () => {
457
- if (settled) return;
458
- settled = true;
459
- clearTimeout(timer);
460
- resolve2({});
461
- });
546
+ process.stdin.on("error", () => settle({}));
462
547
  });
463
548
  }
549
+ function transcriptPathOf(input) {
550
+ return typeof input.transcript_path === "string" ? input.transcript_path : "";
551
+ }
552
+ var STDIN_TIMEOUT_MS;
553
+ var init_hook_input = __esm({
554
+ "src/hooks/hook-input.ts"() {
555
+ "use strict";
556
+ STDIN_TIMEOUT_MS = 200;
557
+ }
558
+ });
559
+
560
+ // src/hooks/state.ts
561
+ import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, rename as rename2 } from "node:fs/promises";
562
+ import { existsSync as existsSync7 } from "node:fs";
563
+ import { homedir as homedir4 } from "node:os";
564
+ import { join as join13 } from "node:path";
565
+ function emptyState() {
566
+ return { config: null, sessions: {}, pending_metrics: [] };
567
+ }
568
+ async function loadState() {
569
+ if (!existsSync7(STATE_FILE)) return emptyState();
570
+ try {
571
+ const raw = await readFile2(STATE_FILE, "utf-8");
572
+ const parsed = JSON.parse(raw);
573
+ return {
574
+ config: parsed.config ?? null,
575
+ sessions: parsed.sessions ?? {},
576
+ pending_metrics: Array.isArray(parsed.pending_metrics) ? parsed.pending_metrics : [],
577
+ thresholds: parsed.thresholds,
578
+ thresholds_synced_at: parsed.thresholds_synced_at
579
+ };
580
+ } catch (err) {
581
+ process.stderr.write(
582
+ `[maind-mcp-bridge] state.json corrupt, resetting: ${err instanceof Error ? err.message : String(err)}
583
+ `
584
+ );
585
+ return emptyState();
586
+ }
587
+ }
588
+ async function saveState(state) {
589
+ if (!existsSync7(STATE_DIR)) {
590
+ await mkdir2(STATE_DIR, { recursive: true, mode: 448 });
591
+ }
592
+ const tmp = `${STATE_FILE}.tmp`;
593
+ await writeFile2(tmp, JSON.stringify(state, null, 2), { mode: 384 });
594
+ await rename2(tmp, STATE_FILE);
595
+ }
596
+ function resolveThresholds(state) {
597
+ return state.thresholds ?? state.config?.thresholds ?? DEFAULT_THRESHOLDS;
598
+ }
599
+ var STATE_DIR, STATE_FILE, DEFAULT_THRESHOLDS;
600
+ var init_state = __esm({
601
+ "src/hooks/state.ts"() {
602
+ "use strict";
603
+ STATE_DIR = join13(homedir4(), ".maind");
604
+ STATE_FILE = join13(STATE_DIR, "state.json");
605
+ DEFAULT_THRESHOLDS = {
606
+ warn_at_pct: 60,
607
+ handoff_at_pct: 85,
608
+ model_token_limit: 2e5
609
+ };
610
+ }
611
+ });
612
+
613
+ // src/hooks/index.ts
614
+ var hooks_exports = {};
615
+ __export(hooks_exports, {
616
+ effectiveConfig: () => effectiveConfig,
617
+ runFlush: () => runFlush,
618
+ runHookStatus: () => runHookStatus,
619
+ runOnSessionStart: () => runOnSessionStart,
620
+ runOnToolUse: () => runOnToolUse,
621
+ runSessionEndMetrics: () => runSessionEndMetrics,
622
+ runSyncConfig: () => runSyncConfig
623
+ });
624
+ import { writeFile as writeFile3 } from "node:fs/promises";
625
+ import { join as join14 } from "node:path";
626
+ function effectiveConfig(state) {
627
+ if (state.config) return state.config;
628
+ const key = readApiKey();
629
+ if (key === null) return null;
630
+ return { api_key: key, endpoint: DEFAULT_INGEST_ENDPOINT };
631
+ }
632
+ function getOrCreateSession(state, sessionId) {
633
+ let session = state.sessions[sessionId];
634
+ if (!session) {
635
+ session = {
636
+ session_id: sessionId,
637
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
638
+ tool_call_count: 0,
639
+ lessons_consulted: 0
640
+ };
641
+ state.sessions[sessionId] = session;
642
+ }
643
+ return session;
644
+ }
645
+ async function runOnSessionStart() {
646
+ const state = await loadState();
647
+ if (effectiveConfig(state) === null) return 0;
648
+ const input = await readHookInput();
649
+ const sessionId = sessionIdOf(input);
650
+ if (sessionId === null) return 0;
651
+ getOrCreateSession(state, sessionId);
652
+ await saveState(state);
653
+ return 0;
654
+ }
655
+ async function runOnToolUse() {
656
+ const state = await loadState();
657
+ if (effectiveConfig(state) === null) return 0;
658
+ const input = await readHookInput();
659
+ const sessionId = sessionIdOf(input) ?? "unknown";
660
+ const session = getOrCreateSession(state, sessionId);
661
+ session.tool_call_count += 1;
662
+ const tool = (input.tool_name ?? "").toString();
663
+ if (tool.includes("search_lessons") || tool.includes("get_session_briefing") || tool.includes("get_lesson")) {
664
+ session.lessons_consulted += 1;
665
+ }
666
+ const transcriptPath = input.transcript_path;
667
+ if (typeof transcriptPath === "string" && transcriptPath && !session.transcript_path) {
668
+ session.transcript_path = transcriptPath;
669
+ }
670
+ if (session.transcript_path) {
671
+ const summary = await summariseTranscript(session.transcript_path);
672
+ if (summary) {
673
+ session.token_count = summary.total_tokens;
674
+ await maybeEmitAdvisory(state, session);
675
+ }
676
+ }
677
+ await saveState(state);
678
+ return 0;
679
+ }
680
+ async function maybeEmitAdvisory(state, session) {
681
+ const t = resolveThresholds(state);
682
+ const tokens = session.token_count ?? 0;
683
+ if (t.model_token_limit <= 0) return;
684
+ const ratio = tokens / t.model_token_limit;
685
+ let status = "ok";
686
+ if (ratio >= t.handoff_at_pct / 100) status = "handoff_recommended";
687
+ else if (ratio >= t.warn_at_pct / 100) status = "warn";
688
+ if (session.last_advisory_status === status) return;
689
+ session.last_advisory_status = status;
690
+ if (status === "ok") return;
691
+ const pct = Math.round(ratio * 100);
692
+ const payload = {
693
+ session_id: session.session_id,
694
+ status,
695
+ tokens,
696
+ ratio: Number(ratio.toFixed(3)),
697
+ pct,
698
+ thresholds: t,
699
+ suggested_next: status === "handoff_recommended" ? "use_generate_handoff_brief" : "wrap_up_current_subtask",
700
+ emitted_at: (/* @__PURE__ */ new Date()).toISOString()
701
+ };
702
+ try {
703
+ await writeFile3(
704
+ join14(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
705
+ JSON.stringify(payload, null, 2)
706
+ );
707
+ } catch (err) {
708
+ process.stderr.write(
709
+ `[maind-mcp-bridge] failed to write advisory marker: ${err instanceof Error ? err.message : String(err)}
710
+ `
711
+ );
712
+ }
713
+ if (status === "warn") {
714
+ process.stderr.write(
715
+ `[maind] \u26A0 Token usage at ~${pct}% (warn threshold ${t.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
716
+ `
717
+ );
718
+ } else {
719
+ process.stderr.write(
720
+ `[maind] \u26D4 Token usage at ~${pct}% (handoff threshold ${t.handoff_at_pct}%). Strongly consider compiling a HANDOFF brief and starting a fresh session \u2014 call recommend_handoff or generate_handoff_brief.
721
+ `
722
+ );
723
+ }
724
+ }
725
+ async function runSessionEndMetrics(sessionId) {
726
+ try {
727
+ const state = await loadState();
728
+ const config = effectiveConfig(state);
729
+ if (config === null) return;
730
+ const id = sessionId ?? Object.keys(state.sessions)[0];
731
+ const session = id ? state.sessions[id] : void 0;
732
+ if (session) {
733
+ const durationMs = Date.now() - new Date(session.started_at).getTime();
734
+ state.pending_metrics.push(
735
+ {
736
+ session_id: id,
737
+ metric_key: "session_duration_ms",
738
+ metric_value: Math.max(0, durationMs)
739
+ },
740
+ {
741
+ session_id: id,
742
+ metric_key: "tool_call_count",
743
+ metric_value: session.tool_call_count
744
+ },
745
+ {
746
+ session_id: id,
747
+ metric_key: "lessons_consulted",
748
+ metric_value: session.lessons_consulted
749
+ }
750
+ );
751
+ delete state.sessions[id];
752
+ await saveState(state);
753
+ }
754
+ await flushPending(config, STOP_FLUSH_TIMEOUT_MS);
755
+ } catch (err) {
756
+ process.stderr.write(
757
+ `[maind-mcp-bridge] session metrics failed: ${err instanceof Error ? err.message : String(err)}
758
+ `
759
+ );
760
+ }
761
+ }
762
+ async function runFlush() {
763
+ const state = await loadState();
764
+ const config = effectiveConfig(state);
765
+ if (config === null) {
766
+ process.stderr.write(
767
+ "[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"
768
+ );
769
+ return 1;
770
+ }
771
+ const result = await flushPending(config, MANUAL_FLUSH_TIMEOUT_MS);
772
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
773
+ return result.ok ? 0 : 1;
774
+ }
775
+ async function flushPending(config, timeoutMs) {
776
+ const state = await loadState();
777
+ if (state.pending_metrics.length === 0) {
778
+ return { ok: true, flushed: 0, remaining: 0 };
779
+ }
780
+ const batch = state.pending_metrics.slice(0, 100);
781
+ const post = postMetrics(config.endpoint, config.api_key, batch);
782
+ const timeout = new Promise(
783
+ (resolve2) => setTimeout(() => resolve2({ ok: false, inserted: 0, error: "timeout" }), timeoutMs)
784
+ );
785
+ const result = await Promise.race([post, timeout]);
786
+ if (result.ok) {
787
+ const fresh = await loadState();
788
+ fresh.pending_metrics = fresh.pending_metrics.slice(batch.length);
789
+ await saveState(fresh);
790
+ return { ok: true, flushed: batch.length, remaining: fresh.pending_metrics.length };
791
+ }
792
+ return {
793
+ ok: false,
794
+ flushed: 0,
795
+ remaining: state.pending_metrics.length,
796
+ error: result.error
797
+ };
798
+ }
799
+ async function runHookStatus() {
800
+ const state = await loadState();
801
+ const config = effectiveConfig(state);
802
+ process.stdout.write(
803
+ JSON.stringify(
804
+ {
805
+ paired: config !== null,
806
+ source: state.config ? "maind-hook init (legacy)" : "bridge credential",
807
+ endpoint: config?.endpoint ?? null,
808
+ api_key_prefix: config ? config.api_key.slice(0, 12) + "\u2026" : null,
809
+ open_sessions: Object.keys(state.sessions).length,
810
+ pending_metrics: state.pending_metrics.length,
811
+ thresholds: resolveThresholds(state),
812
+ thresholds_synced_at: state.thresholds_synced_at ?? state.config?.thresholds_synced_at ?? null
813
+ },
814
+ null,
815
+ 2
816
+ ) + "\n"
817
+ );
818
+ return 0;
819
+ }
820
+ async function runSyncConfig() {
821
+ const state = await loadState();
822
+ const config = effectiveConfig(state);
823
+ if (config === null) {
824
+ process.stderr.write(
825
+ "[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"
826
+ );
827
+ return 1;
828
+ }
829
+ const endpoint = config.thresholds_endpoint ?? DEFAULT_THRESHOLDS_ENDPOINT;
830
+ let res;
831
+ try {
832
+ res = await fetch(endpoint, {
833
+ method: "POST",
834
+ headers: {
835
+ "content-type": "application/json",
836
+ authorization: `Bearer ${config.api_key}`
837
+ }
838
+ });
839
+ } catch (err) {
840
+ process.stderr.write(
841
+ `[maind-mcp-bridge] sync-config network error: ${err instanceof Error ? err.message : String(err)}
842
+ `
843
+ );
844
+ return 1;
845
+ }
846
+ if (!res.ok) {
847
+ process.stderr.write(
848
+ `[maind-mcp-bridge] sync-config HTTP ${res.status} ${res.statusText}
849
+ `
850
+ );
851
+ const body2 = await res.text().catch(() => "");
852
+ if (body2) process.stderr.write(body2.slice(0, 500) + "\n");
853
+ return 1;
854
+ }
855
+ let body;
856
+ try {
857
+ body = await res.json();
858
+ } catch {
859
+ process.stderr.write("[maind-mcp-bridge] sync-config: invalid JSON response\n");
860
+ return 1;
861
+ }
862
+ const t = body;
863
+ if (typeof t.warn_at_pct !== "number" || typeof t.handoff_at_pct !== "number" || typeof t.model_token_limit !== "number") {
864
+ process.stderr.write(
865
+ "[maind-mcp-bridge] sync-config: response missing expected fields\n"
866
+ );
867
+ return 1;
868
+ }
869
+ state.thresholds = {
870
+ warn_at_pct: t.warn_at_pct,
871
+ handoff_at_pct: t.handoff_at_pct,
872
+ model_token_limit: t.model_token_limit
873
+ };
874
+ state.thresholds_synced_at = (/* @__PURE__ */ new Date()).toISOString();
875
+ await saveState(state);
876
+ process.stdout.write(
877
+ JSON.stringify(
878
+ { ok: true, thresholds: state.thresholds, synced_at: state.thresholds_synced_at },
879
+ null,
880
+ 2
881
+ ) + "\n"
882
+ );
883
+ return 0;
884
+ }
885
+ function sessionIdOf(input) {
886
+ const id = typeof input.session_id === "string" ? input.session_id.trim() : "";
887
+ return id.length > 0 ? id : null;
888
+ }
889
+ var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS;
890
+ var init_hooks = __esm({
891
+ "src/hooks/index.ts"() {
892
+ "use strict";
893
+ init_dist();
894
+ init_device_id();
895
+ init_api();
896
+ init_hook_input();
897
+ init_state();
898
+ DEFAULT_THRESHOLDS_ENDPOINT = process.env.MAIND_THRESHOLDS_ENDPOINT ?? "https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds";
899
+ STOP_FLUSH_TIMEOUT_MS = 1500;
900
+ MANUAL_FLUSH_TIMEOUT_MS = 1e4;
901
+ }
902
+ });
903
+
904
+ // src/session-end/index.ts
905
+ var session_end_exports = {};
906
+ __export(session_end_exports, {
907
+ runOnSessionEnd: () => runOnSessionEnd
908
+ });
464
909
  async function postWithTimeout(apiKey, deviceId, analytics, timeoutMs) {
465
910
  const post = fetch(INGEST_ENDPOINT, {
466
911
  method: "POST",
@@ -479,21 +924,23 @@ async function runOnSessionEnd() {
479
924
  const apiKey = readApiKey();
480
925
  if (!apiKey) return 0;
481
926
  const input = await readHookInput();
482
- const transcriptPath = typeof input.transcript_path === "string" ? input.transcript_path : "";
483
- if (!transcriptPath) return 0;
484
- try {
485
- const analytics = await analyzeSession(transcriptPath);
486
- if (typeof input.session_id === "string" && input.session_id) {
487
- analytics.session_id = input.session_id;
488
- }
489
- if (!analytics.session_id) return 0;
490
- await postWithTimeout(apiKey, ensureDeviceId(), analytics, 1500);
491
- } catch (err) {
492
- process.stderr.write(
493
- `[maind-mcp-bridge] session-analytics failed: ${err instanceof Error ? err.message : String(err)}
927
+ const sessionId = typeof input.session_id === "string" && input.session_id ? input.session_id : null;
928
+ const transcriptPath = transcriptPathOf(input);
929
+ if (transcriptPath) {
930
+ try {
931
+ const analytics = await analyzeSession(transcriptPath);
932
+ if (sessionId) analytics.session_id = sessionId;
933
+ if (analytics.session_id) {
934
+ await postWithTimeout(apiKey, ensureDeviceId(), analytics, 1500);
935
+ }
936
+ } catch (err) {
937
+ process.stderr.write(
938
+ `[maind-mcp-bridge] session-analytics failed: ${err instanceof Error ? err.message : String(err)}
494
939
  `
495
- );
940
+ );
941
+ }
496
942
  }
943
+ await runSessionEndMetrics(sessionId);
497
944
  return 0;
498
945
  }
499
946
  var INGEST_ENDPOINT;
@@ -502,8 +949,11 @@ var init_session_end = __esm({
502
949
  "use strict";
503
950
  init_dist();
504
951
  init_device_id();
952
+ init_api();
953
+ init_hook_input();
954
+ init_hooks();
505
955
  init_version();
506
- INGEST_ENDPOINT = process.env.MAIND_ENDPOINT ?? "https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";
956
+ INGEST_ENDPOINT = DEFAULT_INGEST_ENDPOINT;
507
957
  }
508
958
  });
509
959
 
@@ -1251,7 +1701,7 @@ function sleep(ms) {
1251
1701
  return new Promise((resolve2) => setTimeout(resolve2, ms));
1252
1702
  }
1253
1703
  function printAuthInstructions(start) {
1254
- const lines = [
1704
+ const lines2 = [
1255
1705
  "",
1256
1706
  " \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510",
1257
1707
  " \u2502 \u2502",
@@ -1267,7 +1717,7 @@ function printAuthInstructions(start) {
1267
1717
  " \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",
1268
1718
  ""
1269
1719
  ];
1270
- process.stderr.write(lines.join("\n") + "\n");
1720
+ process.stderr.write(lines2.join("\n") + "\n");
1271
1721
  }
1272
1722
  function pad(s, width) {
1273
1723
  if (s.length >= width) return s.slice(0, width);
@@ -1454,9 +1904,9 @@ function printInstallHelp() {
1454
1904
  "",
1455
1905
  "Common flags:",
1456
1906
  " --project-root <path> Override project-root detection (default: walk up from cwd)",
1457
- " --full Non-interactive full setup (includes ~/.claude/settings.json hook)",
1907
+ " --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)",
1458
1908
  " --no-preamble Skip the 5 preamble files (MCP-config + pairing only)",
1459
- " --no-hook Never write the SessionStart hook (overrides --full for hook)",
1909
+ " --no-hook Never write the Claude Code hooks (overrides --full for hooks)",
1460
1910
  " --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)",
1461
1911
  " --token <jwt> Use a pre-issued one-click token instead of browser pairing",
1462
1912
  " --client <family> Install only for one client family (claude-code, cursor, ...)",
@@ -1543,17 +1993,17 @@ var InstallReport = class {
1543
1993
  );
1544
1994
  const pad2 = (s, w) => s + " ".repeat(Math.max(0, w - s.length));
1545
1995
  const sep2 = `| ${"-".repeat(targetWidth)} | ${"-".repeat(actionWidth)} | ${"-".repeat(statusWidth)} | ${"-".repeat(detailWidth)} |`;
1546
- const lines = [];
1547
- lines.push(
1996
+ const lines2 = [];
1997
+ lines2.push(
1548
1998
  `| ${pad2(headers[0], targetWidth)} | ${pad2(headers[1], actionWidth)} | ${pad2(headers[2], statusWidth)} | ${pad2(headers[3], detailWidth)} |`
1549
1999
  );
1550
- lines.push(sep2);
2000
+ lines2.push(sep2);
1551
2001
  for (const r of this.results) {
1552
- lines.push(
2002
+ lines2.push(
1553
2003
  `| ${pad2(r.target, targetWidth)} | ${pad2(r.action, actionWidth)} | ${pad2(r.status, statusWidth)} | ${pad2(r.detail ?? "", detailWidth)} |`
1554
2004
  );
1555
2005
  }
1556
- return lines.join("\n") + "\n";
2006
+ return lines2.join("\n") + "\n";
1557
2007
  }
1558
2008
  print(stream) {
1559
2009
  const s = this.summary();
@@ -1658,12 +2108,79 @@ Which one should receive the MCP config and preamble files? [1-${candidates.leng
1658
2108
  }
1659
2109
 
1660
2110
  // src/install/client-targets.ts
1661
- import * as path2 from "node:path";
2111
+ import * as path3 from "node:path";
2112
+
2113
+ // src/install/bridge-entry.ts
2114
+ import path2 from "node:path";
2115
+ import { fileURLToPath } from "node:url";
2116
+ var NPX_PACKAGE = "@maind-dev/mcp-bridge";
2117
+ function isEphemeralEntry(entryPath, sep2 = path2.sep) {
2118
+ return entryPath.split(sep2).includes("_npx");
2119
+ }
2120
+ function resolveBridgeLaunch(opts) {
2121
+ const extra = opts.extraArgs ?? [];
2122
+ const npx = (reason) => ({
2123
+ command: "npx",
2124
+ args: ["-y", NPX_PACKAGE, ...extra],
2125
+ env: {},
2126
+ fallbackReason: reason
2127
+ });
2128
+ if (opts.entryPath === null) {
2129
+ return npx("bridge entry path could not be resolved");
2130
+ }
2131
+ if (isEphemeralEntry(opts.entryPath, opts.sep)) {
2132
+ return npx("bridge is running from the npx cache (install it globally to pin a path)");
2133
+ }
2134
+ if (!opts.nodePath) {
2135
+ return npx("node executable path unavailable");
2136
+ }
2137
+ return {
2138
+ command: opts.nodePath,
2139
+ args: [opts.entryPath, ...extra],
2140
+ env: opts.isElectron ? { ELECTRON_RUN_AS_NODE: "1" } : {},
2141
+ fallbackReason: null
2142
+ };
2143
+ }
2144
+ function currentBridgeEntry() {
2145
+ try {
2146
+ const here = fileURLToPath(import.meta.url);
2147
+ return here.endsWith(".js") ? here : null;
2148
+ } catch {
2149
+ return null;
2150
+ }
2151
+ }
2152
+ function launchToShellCommand(launch) {
2153
+ const assignments = Object.entries(launch.env).map(
2154
+ ([k, v]) => `${k}=${shellQuote(v)}`
2155
+ );
2156
+ return [...assignments, launch.command, ...launch.args].map((part, i) => i < assignments.length ? part : shellQuote(part)).join(" ");
2157
+ }
2158
+ function isNpxForm(command) {
2159
+ return /(^|\s)npx(\s|$)/.test(command) && command.includes(NPX_PACKAGE);
2160
+ }
2161
+ function isLegacyHookForm(command) {
2162
+ return /(^|[\s/])maind-hook(\s|$)/.test(command);
2163
+ }
2164
+ function shellQuote(value) {
2165
+ if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(value)) return value;
2166
+ return `'${value.replace(/'/g, `'\\''`)}'`;
2167
+ }
2168
+
2169
+ // src/install/client-targets.ts
1662
2170
  function buildMaindServerEntry(opts) {
2171
+ const launch = opts.launch ?? resolveBridgeLaunch({
2172
+ entryPath: currentBridgeEntry(),
2173
+ nodePath: process.execPath,
2174
+ isElectron: process.versions.electron !== void 0
2175
+ });
1663
2176
  return {
1664
- command: "npx",
1665
- args: ["-y", "@maind-dev/mcp-bridge"],
2177
+ command: launch.command,
2178
+ args: launch.args,
1666
2179
  env: {
2180
+ // launch.env first: it carries interpreter requirements (ELECTRON_RUN_AS_NODE),
2181
+ // and the maind settings below must stay authoritative over anything a
2182
+ // future launch flavour might name the same way.
2183
+ ...launch.env,
1667
2184
  MAIND_CLIENT_FAMILY: opts.clientFamily,
1668
2185
  MAIND_MCP_URL: opts.mcpUrl
1669
2186
  }
@@ -1672,7 +2189,7 @@ function buildMaindServerEntry(opts) {
1672
2189
  function claudeDesktopConfigPath(ctx) {
1673
2190
  switch (ctx.platform) {
1674
2191
  case "darwin":
1675
- return path2.join(
2192
+ return path3.join(
1676
2193
  ctx.homeDir,
1677
2194
  "Library",
1678
2195
  "Application Support",
@@ -1680,12 +2197,12 @@ function claudeDesktopConfigPath(ctx) {
1680
2197
  "claude_desktop_config.json"
1681
2198
  );
1682
2199
  case "win32": {
1683
- const appData = ctx.appData ?? path2.join(ctx.homeDir, "AppData", "Roaming");
1684
- return path2.join(appData, "Claude", "claude_desktop_config.json");
2200
+ const appData = ctx.appData ?? path3.join(ctx.homeDir, "AppData", "Roaming");
2201
+ return path3.join(appData, "Claude", "claude_desktop_config.json");
1685
2202
  }
1686
2203
  default: {
1687
- const xdg = ctx.xdgConfigHome ?? path2.join(ctx.homeDir, ".config");
1688
- return path2.join(xdg, "Claude", "claude_desktop_config.json");
2204
+ const xdg = ctx.xdgConfigHome ?? path3.join(ctx.homeDir, ".config");
2205
+ return path3.join(xdg, "Claude", "claude_desktop_config.json");
1689
2206
  }
1690
2207
  }
1691
2208
  }
@@ -1696,7 +2213,7 @@ function getClientTargets(ctx) {
1696
2213
  label: "Claude Code (project-scoped .mcp.json)",
1697
2214
  clientFamilyEnv: "claude-code",
1698
2215
  scope: "project",
1699
- path: path2.join(ctx.projectRoot, ".mcp.json"),
2216
+ path: path3.join(ctx.projectRoot, ".mcp.json"),
1700
2217
  kind: "json"
1701
2218
  },
1702
2219
  {
@@ -1704,7 +2221,7 @@ function getClientTargets(ctx) {
1704
2221
  label: "Claude Code (user-scoped ~/.claude.json)",
1705
2222
  clientFamilyEnv: "claude-code",
1706
2223
  scope: "user",
1707
- path: path2.join(ctx.homeDir, ".claude.json"),
2224
+ path: path3.join(ctx.homeDir, ".claude.json"),
1708
2225
  kind: "json"
1709
2226
  },
1710
2227
  {
@@ -1720,7 +2237,7 @@ function getClientTargets(ctx) {
1720
2237
  label: "Cursor (~/.cursor/mcp.json)",
1721
2238
  clientFamilyEnv: "cursor",
1722
2239
  scope: "user",
1723
- path: path2.join(ctx.homeDir, ".cursor", "mcp.json"),
2240
+ path: path3.join(ctx.homeDir, ".cursor", "mcp.json"),
1724
2241
  kind: "json"
1725
2242
  },
1726
2243
  {
@@ -1728,7 +2245,7 @@ function getClientTargets(ctx) {
1728
2245
  label: "Windsurf (~/.codeium/windsurf/mcp_config.json)",
1729
2246
  clientFamilyEnv: "windsurf",
1730
2247
  scope: "user",
1731
- path: path2.join(ctx.homeDir, ".codeium", "windsurf", "mcp_config.json"),
2248
+ path: path3.join(ctx.homeDir, ".codeium", "windsurf", "mcp_config.json"),
1732
2249
  kind: "json"
1733
2250
  },
1734
2251
  {
@@ -1736,7 +2253,7 @@ function getClientTargets(ctx) {
1736
2253
  label: "Codex CLI (~/.codex/config.toml)",
1737
2254
  clientFamilyEnv: "codex",
1738
2255
  scope: "user",
1739
- path: path2.join(ctx.homeDir, ".codex", "config.toml"),
2256
+ path: path3.join(ctx.homeDir, ".codex", "config.toml"),
1740
2257
  kind: "toml"
1741
2258
  }
1742
2259
  ];
@@ -1763,7 +2280,7 @@ function nonEmpty(v) {
1763
2280
 
1764
2281
  // src/install/atomic-write.ts
1765
2282
  import * as fs2 from "node:fs/promises";
1766
- import * as path3 from "node:path";
2283
+ import * as path4 from "node:path";
1767
2284
  async function readFileSafe(filepath) {
1768
2285
  try {
1769
2286
  return await fs2.readFile(filepath, "utf8");
@@ -1776,9 +2293,9 @@ async function ensureDir2(dir) {
1776
2293
  await fs2.mkdir(dir, { recursive: true });
1777
2294
  }
1778
2295
  async function atomicWriteFile(filepath, content, mode) {
1779
- const dir = path3.dirname(filepath);
2296
+ const dir = path4.dirname(filepath);
1780
2297
  await ensureDir2(dir);
1781
- const tmp = path3.join(
2298
+ const tmp = path4.join(
1782
2299
  dir,
1783
2300
  `.maind-install-${process.pid}-${Date.now()}.tmp`
1784
2301
  );
@@ -1810,8 +2327,8 @@ async function atomicWriteFile(filepath, content, mode) {
1810
2327
  async function hasLinePrefix(filepath, prefix) {
1811
2328
  const content = await readFileSafe(filepath);
1812
2329
  if (content === null) return false;
1813
- const lines = content.split(/\r?\n/);
1814
- return lines.some((l) => l.startsWith(prefix));
2330
+ const lines2 = content.split(/\r?\n/);
2331
+ return lines2.some((l) => l.startsWith(prefix));
1815
2332
  }
1816
2333
  function isNoEnt(err) {
1817
2334
  return isNodeError(err) && err.code === "ENOENT";
@@ -2067,7 +2584,7 @@ function failed2(target, phase, err) {
2067
2584
  }
2068
2585
 
2069
2586
  // src/install/preamble.ts
2070
- import * as path4 from "node:path";
2587
+ import * as path5 from "node:path";
2071
2588
 
2072
2589
  // ../../packages/integration-snippets/build/index.js
2073
2590
  var STACK_PLACEHOLDER_TOKEN = "__STACK__";
@@ -2774,32 +3291,32 @@ function buildPreambleTargets(ctx) {
2774
3291
  return [
2775
3292
  {
2776
3293
  key: "preamble:CLAUDE.md",
2777
- path: path4.join(ctx.projectRoot, "CLAUDE.md"),
3294
+ path: path5.join(ctx.projectRoot, "CLAUDE.md"),
2778
3295
  mayNeedParentDir: false
2779
3296
  },
2780
3297
  {
2781
3298
  key: "preamble:AGENTS.md",
2782
- path: path4.join(ctx.projectRoot, "AGENTS.md"),
3299
+ path: path5.join(ctx.projectRoot, "AGENTS.md"),
2783
3300
  mayNeedParentDir: false
2784
3301
  },
2785
3302
  {
2786
3303
  key: "preamble:.github/copilot-instructions.md",
2787
- path: path4.join(ctx.projectRoot, ".github", "copilot-instructions.md"),
3304
+ path: path5.join(ctx.projectRoot, ".github", "copilot-instructions.md"),
2788
3305
  mayNeedParentDir: true
2789
3306
  },
2790
3307
  {
2791
3308
  key: "preamble:.cursorrules",
2792
- path: path4.join(ctx.projectRoot, ".cursorrules"),
3309
+ path: path5.join(ctx.projectRoot, ".cursorrules"),
2793
3310
  mayNeedParentDir: false
2794
3311
  },
2795
3312
  {
2796
3313
  key: "preamble:.windsurfrules",
2797
- path: path4.join(ctx.projectRoot, ".windsurfrules"),
3314
+ path: path5.join(ctx.projectRoot, ".windsurfrules"),
2798
3315
  mayNeedParentDir: false
2799
3316
  },
2800
3317
  {
2801
3318
  key: "preamble:~/.claude/maind-session-start-reminder.md",
2802
- path: path4.join(ctx.homeDir, ".claude", "maind-session-start-reminder.md"),
3319
+ path: path5.join(ctx.homeDir, ".claude", "maind-session-start-reminder.md"),
2803
3320
  mayNeedParentDir: true
2804
3321
  }
2805
3322
  ];
@@ -2815,7 +3332,7 @@ async function writePreambleFiles(ctx, dryRun = false) {
2815
3332
  async function writeOnePreambleFile(target, dryRun) {
2816
3333
  try {
2817
3334
  if (target.mayNeedParentDir && !dryRun) {
2818
- await ensureDir2(path4.dirname(target.path));
3335
+ await ensureDir2(path5.dirname(target.path));
2819
3336
  }
2820
3337
  const alreadyPresent = await hasLinePrefix(target.path, PREAMBLE_HEADER_PREFIX);
2821
3338
  if (alreadyPresent) {
@@ -2862,11 +3379,11 @@ function ensureTrailingBlankLine(content) {
2862
3379
  }
2863
3380
 
2864
3381
  // src/install/hook-merge.ts
2865
- import * as path5 from "node:path";
3382
+ import * as path6 from "node:path";
2866
3383
  import * as readline2 from "node:readline";
2867
3384
  var REMINDER_FILE_REL = ".claude/maind-session-start-reminder.md";
2868
3385
  async function mergeClaudeHook(opts, spec) {
2869
- const settingsPath = path5.join(opts.homeDir, ".claude", "settings.json");
3386
+ const settingsPath = path6.join(opts.homeDir, ".claude", "settings.json");
2870
3387
  const targetKey = spec.targetKey;
2871
3388
  if (opts.skip) {
2872
3389
  return { target: targetKey, action: "skip", status: "skipped", detail: "--no-hook" };
@@ -2898,8 +3415,9 @@ async function mergeClaudeHook(opts, spec) {
2898
3415
  return { target: targetKey, action: "merge", status: "failed", detail: `parse: ${errMessage(err)}` };
2899
3416
  }
2900
3417
  }
2901
- if (existingHookReferences(settings, spec.event, spec.matchPattern)) {
2902
- return { target: targetKey, action: "skip", status: "skipped", detail: spec.skipDetailWhenPresent };
3418
+ const existing = findExistingHookCommand(settings, spec.event, spec.matchPattern);
3419
+ if (existing !== null) {
3420
+ return { target: targetKey, action: "skip", status: "skipped", detail: spec.skipDetail(existing) };
2903
3421
  }
2904
3422
  if (!opts.full) {
2905
3423
  if (!opts.isInteractive) {
@@ -2962,33 +3480,77 @@ ${spec.consentDescription}
2962
3480
  };
2963
3481
  }
2964
3482
  async function mergeSessionStartHook(opts) {
2965
- const reminderPath = path5.join(opts.homeDir, REMINDER_FILE_REL);
3483
+ const reminderPath = path6.join(opts.homeDir, REMINDER_FILE_REL);
2966
3484
  return mergeClaudeHook(opts, {
2967
3485
  event: "SessionStart",
2968
3486
  command: `cat ${reminderPath}`,
2969
3487
  timeout: 5,
2970
3488
  matchPattern: /maind-session-start-reminder\.md/,
2971
3489
  targetKey: "hook:~/.claude/settings.json",
2972
- skipDetailWhenPresent: "SessionStart hook already references the reminder file",
3490
+ skipDetail: () => "SessionStart hook already references the reminder file",
2973
3491
  consentDescription: `It 'cat's ${REMINDER_FILE_REL} into every new Claude Code session.`
2974
3492
  });
2975
3493
  }
2976
- async function mergeStopHook(opts) {
3494
+ async function mergeSubcommandHook(opts, spec) {
3495
+ const launch = opts.launch ?? resolveBridgeLaunch({
3496
+ entryPath: currentBridgeEntry(),
3497
+ nodePath: process.execPath,
3498
+ extraArgs: [spec.subcommand],
3499
+ isElectron: process.versions.electron !== void 0
3500
+ });
3501
+ const command = launchToShellCommand(launch);
2977
3502
  return mergeClaudeHook(opts, {
3503
+ event: spec.event,
3504
+ command,
3505
+ timeout: spec.timeout,
3506
+ matchPattern: new RegExp(spec.subcommand),
3507
+ targetKey: spec.targetKey,
3508
+ skipDetail: (existing) => {
3509
+ const wired = `${spec.label} already runs maind ${spec.subcommand}`;
3510
+ if (isLegacyHookForm(existing)) {
3511
+ return `${wired}, but via the retired \`maind-hook\` binary \u2014 the bridge now owns that subcommand and \`maind-hook\` is no longer published. Replace its command with: ${command}`;
3512
+ }
3513
+ if (isNpxForm(existing)) {
3514
+ return `${wired}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${command}`;
3515
+ }
3516
+ return wired;
3517
+ },
3518
+ consentDescription: spec.consentDescription
3519
+ });
3520
+ }
3521
+ async function mergeStopHook(opts) {
3522
+ return mergeSubcommandHook(opts, {
2978
3523
  event: "Stop",
2979
- command: "npx -y @maind-dev/mcp-bridge on-session-end",
3524
+ subcommand: "on-session-end",
2980
3525
  timeout: 10,
2981
- // Match any on-session-end command so we never double-wire (also covers a
2982
- // hand-wired node-path hook the user may already have).
2983
- matchPattern: /on-session-end/,
2984
3526
  targetKey: "hook(stop):~/.claude/settings.json",
2985
- skipDetailWhenPresent: "Stop hook already runs maind on-session-end",
2986
- consentDescription: "It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end. Gated by Tier-3 consent server-side."
3527
+ label: "Stop hook",
3528
+ consentDescription: "It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end, and flushes the session's Tier-3 counters. Gated by Tier-3 consent server-side."
2987
3529
  });
2988
3530
  }
2989
- function existingHookReferences(settings, event, pattern) {
3531
+ async function mergeSessionStartMetricsHook(opts) {
3532
+ return mergeSubcommandHook(opts, {
3533
+ event: "SessionStart",
3534
+ subcommand: "on-session-start",
3535
+ timeout: 5,
3536
+ targetKey: "hook(session-start):~/.claude/settings.json",
3537
+ label: "SessionStart hook",
3538
+ consentDescription: "It runs 'maind-mcp-bridge on-session-start' \u2014 opens a tracked session so duration and tool-call counts can be measured. Writes only to ~/.maind/state.json; nothing leaves the machine here."
3539
+ });
3540
+ }
3541
+ async function mergeToolUseHook(opts) {
3542
+ return mergeSubcommandHook(opts, {
3543
+ event: "PreToolUse",
3544
+ subcommand: "on-tool-use",
3545
+ timeout: 5,
3546
+ targetKey: "hook(pre-tool-use):~/.claude/settings.json",
3547
+ label: "PreToolUse hook",
3548
+ consentDescription: "It runs 'maind-mcp-bridge on-tool-use' before every tool call \u2014 counts calls, and warns you on stderr when the session's token usage crosses your handoff thresholds (ADR-039). Only the tool NAME is read, never its arguments."
3549
+ });
3550
+ }
3551
+ function findExistingHookCommand(settings, event, pattern) {
2990
3552
  const groups = settings.hooks?.[event];
2991
- if (!Array.isArray(groups)) return false;
3553
+ if (!Array.isArray(groups)) return null;
2992
3554
  for (const group of groups) {
2993
3555
  if (!isObject3(group)) continue;
2994
3556
  const hooks = group.hooks;
@@ -2996,10 +3558,10 @@ function existingHookReferences(settings, event, pattern) {
2996
3558
  for (const hook of hooks) {
2997
3559
  if (!isObject3(hook)) continue;
2998
3560
  const cmd = hook.command;
2999
- if (typeof cmd === "string" && pattern.test(cmd)) return true;
3561
+ if (typeof cmd === "string" && pattern.test(cmd)) return cmd;
3000
3562
  }
3001
3563
  }
3002
- return false;
3564
+ return null;
3003
3565
  }
3004
3566
  async function promptYesNo(out, prompt) {
3005
3567
  out.write(prompt);
@@ -3328,6 +3890,8 @@ Skipping remaining steps.
3328
3890
  out: process.stdout
3329
3891
  };
3330
3892
  report.add(await mergeSessionStartHook(hookOpts));
3893
+ report.add(await mergeSessionStartMetricsHook(hookOpts));
3894
+ report.add(await mergeToolUseHook(hookOpts));
3331
3895
  report.add(await mergeStopHook(hookOpts));
3332
3896
  if (!flags.dryRun) {
3333
3897
  await postInstallTelemetry({
@@ -3369,7 +3933,7 @@ import { execFileSync as execFileSync5 } from "node:child_process";
3369
3933
 
3370
3934
  // ../../packages/code-index/build/node.js
3371
3935
  import { mkdirSync as mkdirSync3 } from "node:fs";
3372
- import { posix as posix5 } from "node:path";
3936
+ import { posix as posix6 } from "node:path";
3373
3937
 
3374
3938
  // ../../packages/code-index/build/parse/tree-sitter/parser.js
3375
3939
  import { join as join9 } from "node:path";
@@ -3777,7 +4341,7 @@ var TreeSitterParser = class {
3777
4341
 
3778
4342
  // ../../packages/code-index/build/query/engine.js
3779
4343
  import { readFileSync as readFileSync4 } from "node:fs";
3780
- import { posix as posix4 } from "node:path";
4344
+ import { posix as posix5 } from "node:path";
3781
4345
 
3782
4346
  // ../../packages/code-index/build/embed/recipe.js
3783
4347
  var MAX_CHARS = 1e3;
@@ -3937,12 +4501,12 @@ function toPosix(p) {
3937
4501
  function classify(paths) {
3938
4502
  const out = [];
3939
4503
  for (const raw of paths) {
3940
- const path6 = toPosix(raw).trim();
3941
- if (!path6 || isSkippablePath(path6))
4504
+ const path7 = toPosix(raw).trim();
4505
+ if (!path7 || isSkippablePath(path7))
3942
4506
  continue;
3943
- const language = languageForPath(path6);
4507
+ const language = languageForPath(path7);
3944
4508
  if (language)
3945
- out.push({ path: path6, language });
4509
+ out.push({ path: path7, language });
3946
4510
  }
3947
4511
  return out;
3948
4512
  }
@@ -4264,18 +4828,18 @@ function readFileHistory(repoRoot, paths, opts = {}) {
4264
4828
  const cleanPaths = paths.map((p) => p.trim()).filter((p) => p.length > 0 && !p.startsWith(":"));
4265
4829
  const scoped = cleanPaths.slice(0, MAX_HISTORY_PATHS);
4266
4830
  const history = [];
4267
- for (const path6 of scoped) {
4831
+ for (const path7 of scoped) {
4268
4832
  const raw = runGit(repoRoot, [
4269
4833
  "log",
4270
4834
  "-n",
4271
4835
  String(window),
4272
4836
  LOG_FORMAT,
4273
4837
  "--",
4274
- path6
4838
+ path7
4275
4839
  ]);
4276
4840
  const commits = raw === null ? [] : splitRecords(raw).map(parseHistoryRecord).filter((c) => c !== null);
4277
4841
  history.push({
4278
- path: path6,
4842
+ path: path7,
4279
4843
  lastCommits: commits.slice(0, limit),
4280
4844
  ownership: includeOwnership ? { topAuthors: aggregateOwnership(commits), commitsInWindow: commits.length } : null
4281
4845
  });
@@ -4297,11 +4861,11 @@ function readFileHistory(repoRoot, paths, opts = {}) {
4297
4861
  const commits = [];
4298
4862
  if (raw !== null) {
4299
4863
  for (const record of splitRecords(raw)) {
4300
- const lines = record.split("\n");
4301
- const head = parseHistoryRecord(lines[0] ?? "");
4864
+ const lines2 = record.split("\n");
4865
+ const head = parseHistoryRecord(lines2[0] ?? "");
4302
4866
  if (!head)
4303
4867
  continue;
4304
- const filesTouched = lines.slice(1).filter((l) => l.trim().length > 0).length;
4868
+ const filesTouched = lines2.slice(1).filter((l) => l.trim().length > 0).length;
4305
4869
  commits.push({
4306
4870
  sha: head.sha,
4307
4871
  dateIso: head.dateIso,
@@ -4677,6 +5241,259 @@ async function checkDivergence(repoRoot, opts = {}) {
4677
5241
  return { ok: isHealthy(findings), findings, facts };
4678
5242
  }
4679
5243
 
5244
+ // ../../packages/code-index/build/repo-health/number-collisions.js
5245
+ import { existsSync as existsSync3, readdirSync as readdirSync2 } from "node:fs";
5246
+ import { posix as posix4 } from "node:path";
5247
+ var NUMBERED_RE = /^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/;
5248
+ var DEFAULT_MIN_FILES = 5;
5249
+ var DEFAULT_MIN_DISTINCT_RATIO = 0.8;
5250
+ function isCounterNamespace(numbers, opts = {}) {
5251
+ const minFiles = opts.minFiles ?? DEFAULT_MIN_FILES;
5252
+ if (numbers.length < minFiles)
5253
+ return false;
5254
+ const distinct = new Set(numbers).size;
5255
+ return distinct / numbers.length >= (opts.minDistinctRatio ?? DEFAULT_MIN_DISTINCT_RATIO);
5256
+ }
5257
+ function namespaceKey(ns) {
5258
+ return `${ns.dir}#${ns.prefix}`;
5259
+ }
5260
+ function parseNumbered(fileName) {
5261
+ const m = NUMBERED_RE.exec(fileName);
5262
+ if (!m?.groups)
5263
+ return null;
5264
+ return { prefix: m.groups.prefix ?? "", number: m.groups.num };
5265
+ }
5266
+ function computeNumberCollisions(facts) {
5267
+ const out = [];
5268
+ if (!facts.isRepo)
5269
+ return out;
5270
+ const added = new Set(facts.addedPaths);
5271
+ for (const ns of facts.namespaces) {
5272
+ const key = namespaceKey(ns);
5273
+ const byNumber = facts.sightingsByNamespace.get(key);
5274
+ if (!byNumber)
5275
+ continue;
5276
+ const taken = new Set(byNumber.keys());
5277
+ for (const [number, sightings] of byNumber) {
5278
+ const paths = [...new Set(sightings.map((s) => s.path))];
5279
+ if (paths.length < 2)
5280
+ continue;
5281
+ const ownPath = paths.find((p) => added.has(p));
5282
+ const others = paths.filter((p) => p !== ownPath);
5283
+ const label = `${ns.prefix}${number}`;
5284
+ out.push(ownPath ? {
5285
+ id: `number.collision:${key}#${number}`,
5286
+ status: "open",
5287
+ namespace: ns,
5288
+ number,
5289
+ title: `${label} is already taken`,
5290
+ detail: `This branch adds ${ownPath}, but ${label} already exists as ${others.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${label} stop being unambiguous.`,
5291
+ ownPath,
5292
+ sightings: sightings.filter((s) => s.path !== ownPath),
5293
+ suggestion: `${ns.prefix}${suggestNextNumber(taken, number)}`,
5294
+ hint: `Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history.`
5295
+ } : {
5296
+ id: `number.collision:${key}#${number}`,
5297
+ status: "info",
5298
+ namespace: ns,
5299
+ number,
5300
+ title: `${label} is used more than once (pre-existing)`,
5301
+ detail: `${label} is carried by ${paths.length} files: ${paths.join(", ")}.`,
5302
+ sightings,
5303
+ hint: "Not introduced by this branch \u2014 inventory, not a blocker."
5304
+ });
5305
+ }
5306
+ }
5307
+ const order = { open: 0, warn: 1, info: 2, passed: 3 };
5308
+ return out.sort((a, b) => order[a.status] - order[b.status] || a.id.localeCompare(b.id));
5309
+ }
5310
+ function isCollisionFree(findings) {
5311
+ return !findings.some((f) => f.status === "open");
5312
+ }
5313
+ function suggestNextNumber(taken, like) {
5314
+ let max = 0;
5315
+ for (const t of taken) {
5316
+ const n = Number(t);
5317
+ if (Number.isFinite(n))
5318
+ max = Math.max(max, n);
5319
+ }
5320
+ return String(max + 1).padStart(like.length, "0");
5321
+ }
5322
+ function trimOrNull2(s) {
5323
+ const t = s?.trim();
5324
+ return t ? t : null;
5325
+ }
5326
+ function lines(out) {
5327
+ return out ? out.split("\n").filter(Boolean) : [];
5328
+ }
5329
+ function resolveDefaultBranch2(repoRoot) {
5330
+ const sym = trimOrNull2(runGit(repoRoot, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]));
5331
+ if (sym) {
5332
+ const m = /refs\/remotes\/origin\/(.+)$/.exec(sym);
5333
+ if (m)
5334
+ return m[1];
5335
+ }
5336
+ for (const cand of ["main", "master"]) {
5337
+ if (runGit(repoRoot, ["rev-parse", "--verify", "--quiet", `origin/${cand}`]) !== null) {
5338
+ return cand;
5339
+ }
5340
+ }
5341
+ return null;
5342
+ }
5343
+ function detectNamespaces(repoRoot, opts = {}) {
5344
+ const minFiles = opts.minFiles ?? DEFAULT_MIN_FILES;
5345
+ const args = ["ls-files", "-z", "--"];
5346
+ args.push(...opts.dirs?.length ? opts.dirs : ["."]);
5347
+ const raw = runGit(repoRoot, args);
5348
+ if (raw === null)
5349
+ return [];
5350
+ const candidates = /* @__PURE__ */ new Map();
5351
+ for (const path7 of raw.split("\0").filter(Boolean)) {
5352
+ const dir = posix4.dirname(path7);
5353
+ const parsed = parseNumbered(posix4.basename(path7));
5354
+ if (!parsed)
5355
+ continue;
5356
+ const key = `${dir}#${parsed.prefix}`;
5357
+ const existing = candidates.get(key);
5358
+ if (existing)
5359
+ existing.numbers.push(parsed.number);
5360
+ else
5361
+ candidates.set(key, { dir, prefix: parsed.prefix, numbers: [parsed.number] });
5362
+ }
5363
+ return [...candidates.values()].filter((c) => isCounterNamespace(c.numbers, { ...opts, minFiles })).map((c) => ({
5364
+ dir: c.dir,
5365
+ prefix: c.prefix,
5366
+ fileCount: c.numbers.length,
5367
+ distinctRatio: new Set(c.numbers).size / c.numbers.length
5368
+ })).sort((a, b) => namespaceKey(a).localeCompare(namespaceKey(b)));
5369
+ }
5370
+ async function gatherNumberCollisionFacts(repoRoot, opts = {}) {
5371
+ const skipped = [];
5372
+ const inside = trimOrNull2(runGit(repoRoot, ["rev-parse", "--is-inside-work-tree"]));
5373
+ if (inside !== "true") {
5374
+ return {
5375
+ isRepo: false,
5376
+ defaultBranch: null,
5377
+ namespaces: [],
5378
+ sightingsByNamespace: /* @__PURE__ */ new Map(),
5379
+ addedPaths: [],
5380
+ skipped: ["not a git work tree"]
5381
+ };
5382
+ }
5383
+ const namespaces = detectNamespaces(repoRoot, opts);
5384
+ const nsByKey = new Map(namespaces.map((ns) => [namespaceKey(ns), ns]));
5385
+ const dirs = [...new Set(namespaces.map((ns) => ns.dir))];
5386
+ const sightingsByNamespace = /* @__PURE__ */ new Map();
5387
+ const record = (path7, kind, where) => {
5388
+ const dir = posix4.dirname(path7);
5389
+ const parsed = parseNumbered(posix4.basename(path7));
5390
+ if (!parsed)
5391
+ return;
5392
+ const key = `${dir}#${parsed.prefix}`;
5393
+ if (!nsByKey.has(key))
5394
+ return;
5395
+ const byNumber = sightingsByNamespace.get(key) ?? /* @__PURE__ */ new Map();
5396
+ const list = byNumber.get(parsed.number) ?? [];
5397
+ list.push({ kind, where, path: path7 });
5398
+ byNumber.set(parsed.number, list);
5399
+ sightingsByNamespace.set(key, byNumber);
5400
+ };
5401
+ const scanTree = (ref, kind, where) => {
5402
+ if (dirs.length === 0)
5403
+ return;
5404
+ const out = runGit(repoRoot, ["ls-tree", "-r", "--name-only", ref, "--", ...dirs]);
5405
+ if (out === null) {
5406
+ skipped.push(`could not read ${where}`);
5407
+ return;
5408
+ }
5409
+ for (const path7 of lines(out))
5410
+ record(path7, kind, where);
5411
+ };
5412
+ for (const dir of dirs) {
5413
+ const abs = posix4.join(repoRoot, dir);
5414
+ if (!existsSync3(abs))
5415
+ continue;
5416
+ try {
5417
+ for (const file of readdirSync2(abs))
5418
+ record(`${dir}/${file}`, "self", "this worktree");
5419
+ } catch {
5420
+ skipped.push(`could not read ${dir}`);
5421
+ }
5422
+ }
5423
+ const defaultBranch = resolveDefaultBranch2(repoRoot);
5424
+ if (defaultBranch) {
5425
+ scanTree(`origin/${defaultBranch}`, "default_branch", `origin/${defaultBranch}`);
5426
+ } else {
5427
+ skipped.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped");
5428
+ }
5429
+ const currentBranch = trimOrNull2(runGit(repoRoot, ["rev-parse", "--abbrev-ref", "HEAD"]));
5430
+ for (const branch of lines(runGit(repoRoot, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]))) {
5431
+ if (branch === currentBranch)
5432
+ continue;
5433
+ scanTree(branch, "branch", `Branch ${branch}`);
5434
+ }
5435
+ if (opts.includeWorktrees !== false) {
5436
+ const selfRoot = trimOrNull2(runGit(repoRoot, ["rev-parse", "--show-toplevel"]));
5437
+ for (const line of lines(runGit(repoRoot, ["worktree", "list", "--porcelain"]))) {
5438
+ if (!line.startsWith("worktree "))
5439
+ continue;
5440
+ const root = line.slice("worktree ".length).trim();
5441
+ if (!root || root === selfRoot || !existsSync3(root))
5442
+ continue;
5443
+ for (const dir of dirs) {
5444
+ const abs = posix4.join(root, dir);
5445
+ if (!existsSync3(abs))
5446
+ continue;
5447
+ try {
5448
+ for (const file of readdirSync2(abs)) {
5449
+ record(`${dir}/${file}`, "worktree", `Worktree ${root}`);
5450
+ }
5451
+ } catch {
5452
+ skipped.push(`could not read ${dir} in ${root}`);
5453
+ }
5454
+ }
5455
+ }
5456
+ }
5457
+ let addedPaths = [];
5458
+ if (defaultBranch && dirs.length > 0) {
5459
+ const diff = runGit(repoRoot, [
5460
+ "diff",
5461
+ "--name-only",
5462
+ "--diff-filter=A",
5463
+ `origin/${defaultBranch}...HEAD`,
5464
+ "--",
5465
+ ...dirs
5466
+ ]);
5467
+ if (diff === null) {
5468
+ skipped.push("could not diff against the default branch \u2014 everything reported as info");
5469
+ } else {
5470
+ addedPaths = lines(diff);
5471
+ }
5472
+ const untracked = runGit(repoRoot, [
5473
+ "ls-files",
5474
+ "--others",
5475
+ "--exclude-standard",
5476
+ "--",
5477
+ ...dirs
5478
+ ]);
5479
+ if (untracked !== null)
5480
+ addedPaths = [...addedPaths, ...lines(untracked)];
5481
+ }
5482
+ return {
5483
+ isRepo: true,
5484
+ defaultBranch,
5485
+ namespaces,
5486
+ sightingsByNamespace,
5487
+ addedPaths,
5488
+ skipped
5489
+ };
5490
+ }
5491
+ async function checkNumberCollisions(repoRoot, opts = {}) {
5492
+ const facts = await gatherNumberCollisionFacts(repoRoot, opts);
5493
+ const findings = computeNumberCollisions(facts);
5494
+ return { ok: isCollisionFree(findings), findings, facts };
5495
+ }
5496
+
4680
5497
  // ../../packages/code-index/build/review/risk-rules.js
4681
5498
  var RISK_RULES = [
4682
5499
  {
@@ -4715,11 +5532,11 @@ var RISK_RULES = [
4715
5532
  // ../../packages/code-index/build/review/risk-scan.js
4716
5533
  function scanRiskFlags(input) {
4717
5534
  const flags = /* @__PURE__ */ new Set();
4718
- for (const [path6, status] of input.paths) {
5535
+ for (const [path7, status] of input.paths) {
4719
5536
  for (const rule of RISK_RULES) {
4720
5537
  if (flags.has(rule.flag))
4721
5538
  continue;
4722
- if (!rule.path.test(path6))
5539
+ if (!rule.path.test(path7))
4723
5540
  continue;
4724
5541
  if (rule.onlyWhenAdded && status !== "added")
4725
5542
  continue;
@@ -4727,19 +5544,19 @@ function scanRiskFlags(input) {
4727
5544
  flags.add(rule.flag);
4728
5545
  continue;
4729
5546
  }
4730
- const text = contentForPath(path6, input);
5547
+ const text = contentForPath(path7, input);
4731
5548
  if (text !== null && rule.content.test(text))
4732
5549
  flags.add(rule.flag);
4733
5550
  }
4734
5551
  }
4735
5552
  return [...flags].sort();
4736
5553
  }
4737
- function contentForPath(path6, input) {
4738
- const hunks = input.hunks.get(path6);
5554
+ function contentForPath(path7, input) {
5555
+ const hunks = input.hunks.get(path7);
4739
5556
  if (hunks && !hunks.wholeFile && !hunks.degraded) {
4740
5557
  return hunks.addedLines.join("\n");
4741
5558
  }
4742
- return input.readUntracked(path6);
5559
+ return input.readUntracked(path7);
4743
5560
  }
4744
5561
 
4745
5562
  // ../../packages/code-index/build/store/schema.js
@@ -5063,7 +5880,7 @@ var CodeIndexEngine = class {
5063
5880
  return null;
5064
5881
  let source = "";
5065
5882
  try {
5066
- const full = readFileSync4(posix4.join(this.repoRoot, n.filePath), "utf8");
5883
+ const full = readFileSync4(posix5.join(this.repoRoot, n.filePath), "utf8");
5067
5884
  source = full.slice(n.startByte, n.endByte);
5068
5885
  } catch {
5069
5886
  return null;
@@ -5134,6 +5951,9 @@ var CodeIndexEngine = class {
5134
5951
  async checkDivergence(opts = {}) {
5135
5952
  return checkDivergence(this.repoRoot, opts);
5136
5953
  }
5954
+ async checkNumberCollisions(opts = {}) {
5955
+ return checkNumberCollisions(this.repoRoot, opts);
5956
+ }
5137
5957
  async reviewChanges(opts = {}) {
5138
5958
  await this.store.init();
5139
5959
  const rawPaths = enumerateChangedPaths(this.repoRoot, opts);
@@ -5197,7 +6017,7 @@ var CodeIndexEngine = class {
5197
6017
  }
5198
6018
  readRepoFile(relPath) {
5199
6019
  try {
5200
- return readFileSync4(posix4.join(this.repoRoot, relPath), "utf8");
6020
+ return readFileSync4(posix5.join(this.repoRoot, relPath), "utf8");
5201
6021
  } catch {
5202
6022
  return null;
5203
6023
  }
@@ -5306,8 +6126,8 @@ var NodeSqliteStore = class {
5306
6126
  indexedAt: r.indexed_at
5307
6127
  }));
5308
6128
  }
5309
- async getFile(path6) {
5310
- const r = this.db.prepare("SELECT * FROM files WHERE path = ?").get(path6);
6129
+ async getFile(path7) {
6130
+ const r = this.db.prepare("SELECT * FROM files WHERE path = ?").get(path7);
5311
6131
  if (!r)
5312
6132
  return null;
5313
6133
  return {
@@ -5335,10 +6155,10 @@ var NodeSqliteStore = class {
5335
6155
  });
5336
6156
  tx();
5337
6157
  }
5338
- async deleteFile(path6) {
6158
+ async deleteFile(path7) {
5339
6159
  const tx = this.db.transaction(() => {
5340
- this.deleteFileGraph(path6);
5341
- this.db.prepare("DELETE FROM files WHERE path = ?").run(path6);
6160
+ this.deleteFileGraph(path7);
6161
+ this.db.prepare("DELETE FROM files WHERE path = ?").run(path7);
5342
6162
  });
5343
6163
  tx();
5344
6164
  }
@@ -5366,8 +6186,8 @@ var NodeSqliteStore = class {
5366
6186
  const r = this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(nodeKey);
5367
6187
  return r ? toNodeRow(r) : null;
5368
6188
  }
5369
- async getNodesByFile(path6) {
5370
- const rows = this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(path6);
6189
+ async getNodesByFile(path7) {
6190
+ const rows = this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(path7);
5371
6191
  return rows.map(toNodeRow);
5372
6192
  }
5373
6193
  async getNodesByKinds(kinds) {
@@ -5483,8 +6303,8 @@ var NodeSqliteStore = class {
5483
6303
  }));
5484
6304
  }
5485
6305
  // ── internal helpers ──
5486
- deleteFileGraph(path6) {
5487
- const keys = this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(path6).map((r) => r.node_key);
6306
+ deleteFileGraph(path7) {
6307
+ const keys = this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(path7).map((r) => r.node_key);
5488
6308
  const delEdge = this.db.prepare("DELETE FROM edges WHERE src_key = ?");
5489
6309
  const delFts = this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");
5490
6310
  for (let i = 0; i < keys.length; i += CHUNK) {
@@ -5493,7 +6313,7 @@ var NodeSqliteStore = class {
5493
6313
  delFts.run(k);
5494
6314
  }
5495
6315
  }
5496
- this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(path6);
6316
+ this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(path7);
5497
6317
  }
5498
6318
  _insNode = null;
5499
6319
  insertNodeStmt() {
@@ -5531,8 +6351,8 @@ var NodeSqliteStore = class {
5531
6351
  // ../../packages/code-index/build/node.js
5532
6352
  var DEFAULT_DB_RELPATH = ".maind/code-index.sqlite";
5533
6353
  function createNodeCodeIndex(opts) {
5534
- const dbPath = opts.dbPath ?? posix5.join(opts.repoRoot, DEFAULT_DB_RELPATH);
5535
- mkdirSync3(posix5.dirname(dbPath), { recursive: true });
6354
+ const dbPath = opts.dbPath ?? posix6.join(opts.repoRoot, DEFAULT_DB_RELPATH);
6355
+ mkdirSync3(posix6.dirname(dbPath), { recursive: true });
5536
6356
  const store = new NodeSqliteStore(dbPath);
5537
6357
  const parser = new TreeSitterParser();
5538
6358
  return new CodeIndexEngine({
@@ -5801,6 +6621,24 @@ var LOCAL_TOOLS = [
5801
6621
  }
5802
6622
  }
5803
6623
  }
6624
+ },
6625
+ {
6626
+ name: "check_number_collisions",
6627
+ description: "Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference.",
6628
+ inputSchema: {
6629
+ type: "object",
6630
+ properties: {
6631
+ dirs: {
6632
+ type: "array",
6633
+ items: { type: "string" },
6634
+ description: "Restrict detection to these repo-relative directories (default: whole repo)."
6635
+ },
6636
+ min_files: {
6637
+ type: "number",
6638
+ description: "How many files must share a prefix before it counts as a namespace (default 5). Lower it to cover a young series that is still below the threshold."
6639
+ }
6640
+ }
6641
+ }
5804
6642
  }
5805
6643
  ];
5806
6644
  var LOCAL_TOOL_NAMES = new Set(LOCAL_TOOLS.map((t) => t.name));
@@ -5861,6 +6699,35 @@ async function dispatchLocalTool(engine, name, args) {
5861
6699
  hint: report.ok ? "No silent divergence detected \u2014 safe to proceed." : `${openCount} blocking (open) + ${warnCount} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`
5862
6700
  };
5863
6701
  }
6702
+ case "check_number_collisions": {
6703
+ const report = await engine.checkNumberCollisions({
6704
+ dirs: Array.isArray(args.dirs) ? args.dirs.filter((d) => typeof d === "string") : void 0,
6705
+ minFiles: typeof args.min_files === "number" ? args.min_files : void 0
6706
+ });
6707
+ const open = report.findings.filter((f) => f.status === "open");
6708
+ const preexisting = report.findings.filter(
6709
+ (f) => f.status === "info"
6710
+ );
6711
+ return {
6712
+ ok: report.ok,
6713
+ open_count: open.length,
6714
+ preexisting_count: preexisting.length,
6715
+ // Nur die blockierenden Findings vollständig; der Bestand als Zahl plus
6716
+ // Nummern, damit ein Repo mit alten Doppelungen die Antwort nicht flutet
6717
+ // und der Agent das Handlungsrelevante zuerst liest.
6718
+ findings: open,
6719
+ preexisting: preexisting.map(
6720
+ (f) => `${f.namespace.prefix}${f.number}`
6721
+ ),
6722
+ namespaces: report.facts.namespaces.map((ns) => ({
6723
+ dir: ns.dir,
6724
+ prefix: ns.prefix,
6725
+ file_count: ns.fileCount
6726
+ })),
6727
+ skipped: report.facts.skipped,
6728
+ 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." : `${open.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`
6729
+ };
6730
+ }
5864
6731
  case "codebase_search": {
5865
6732
  const query = str(args.query);
5866
6733
  if (!query) throw new Error("codebase_search requires a 'query' string");
@@ -6192,7 +7059,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
6192
7059
 
6193
7060
  // src/bridge-config.ts
6194
7061
  init_device_id();
6195
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "node:fs";
7062
+ import { existsSync as existsSync4, readFileSync as readFileSync6 } from "node:fs";
6196
7063
  import { join as join11 } from "node:path";
6197
7064
  function bridgeConfigPath() {
6198
7065
  return join11(configDir(), "config.json");
@@ -6200,7 +7067,7 @@ function bridgeConfigPath() {
6200
7067
  function readBridgeConfig() {
6201
7068
  try {
6202
7069
  const file = bridgeConfigPath();
6203
- if (!existsSync3(file)) return null;
7070
+ if (!existsSync4(file)) return null;
6204
7071
  const raw = JSON.parse(readFileSync6(file, "utf8"));
6205
7072
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
6206
7073
  return null;
@@ -6364,6 +7231,16 @@ function normalizeMachineLabel(raw) {
6364
7231
 
6365
7232
  // src/index.ts
6366
7233
  var MAX_REAUTH_ATTEMPTS = 1;
7234
+ var HOOK_SUBCOMMANDS = [
7235
+ "on-session-start",
7236
+ "on-tool-use",
7237
+ "sync-config",
7238
+ "flush",
7239
+ "status"
7240
+ ];
7241
+ function isHookSubcommand(value) {
7242
+ return HOOK_SUBCOMMANDS.includes(value);
7243
+ }
6367
7244
  var SAVINGS_FLUSH_INTERVAL_MS = 6e4;
6368
7245
  async function ensureApiKey() {
6369
7246
  const fromEnv = (process.env.MAIND_API_KEY ?? "").trim();
@@ -6407,6 +7284,17 @@ async function main() {
6407
7284
  const { runOnSessionEnd: runOnSessionEnd2 } = await Promise.resolve().then(() => (init_session_end(), session_end_exports));
6408
7285
  process.exit(await runOnSessionEnd2());
6409
7286
  }
7287
+ if (firstPositional !== void 0 && isHookSubcommand(firstPositional)) {
7288
+ const hooks = await Promise.resolve().then(() => (init_hooks(), hooks_exports));
7289
+ const run = {
7290
+ "on-session-start": hooks.runOnSessionStart,
7291
+ "on-tool-use": hooks.runOnToolUse,
7292
+ "sync-config": hooks.runSyncConfig,
7293
+ flush: hooks.runFlush,
7294
+ status: hooks.runHookStatus
7295
+ }[firstPositional];
7296
+ process.exit(await run());
7297
+ }
6410
7298
  if (process.argv.includes("--version") || process.argv.includes("-v")) {
6411
7299
  process.stdout.write(BRIDGE_VERSION + "\n");
6412
7300
  process.exit(0);
@@ -6503,7 +7391,7 @@ function printHelp() {
6503
7391
  "",
6504
7392
  "Usage:",
6505
7393
  " npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)",
6506
- " npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble, hook)",
7394
+ " npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble, hooks)",
6507
7395
  " npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow",
6508
7396
  " npx -y @maind-dev/mcp-bridge --version",
6509
7397
  " npx -y @maind-dev/mcp-bridge --help",
@@ -6511,6 +7399,19 @@ function printHelp() {
6511
7399
  "Run `install --help` for full setup flags:",
6512
7400
  " npx -y @maind-dev/mcp-bridge install --help",
6513
7401
  "",
7402
+ "Claude Code hook subcommands (wired by `install`; run them by hand only for",
7403
+ "diagnostics). They read the hook payload on stdin and use the bridge's own",
7404
+ "paired credential \u2014 no separate init:",
7405
+ " on-session-start open a tracked session (Tier-3 flat metrics)",
7406
+ " on-tool-use bump counters + evaluate the ADR-039 context advisory",
7407
+ " on-session-end session analytics + close/flush the tracked session",
7408
+ " sync-config pull your context thresholds from the server (ADR-039)",
7409
+ " flush post queued Tier-3 metrics now",
7410
+ " status show pairing, queued metrics and active thresholds",
7411
+ "",
7412
+ "Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent",
7413
+ "Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.",
7414
+ "",
6514
7415
  "Environment overrides (rarely needed):",
6515
7416
  " MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)",
6516
7417
  " MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)",