@maind-dev/mcp-bridge 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -202,7 +202,7 @@ var BRIDGE_VERSION;
202
202
  var init_version = __esm({
203
203
  "src/version.ts"() {
204
204
  "use strict";
205
- BRIDGE_VERSION = "0.26.0";
205
+ BRIDGE_VERSION = "0.27.0";
206
206
  }
207
207
  });
208
208
 
@@ -319,10 +319,79 @@ var init_bridge_entry = __esm({
319
319
  }
320
320
  });
321
321
 
322
+ // src/install/atomic-write.ts
323
+ import * as fs2 from "node:fs/promises";
324
+ import * as path4 from "node:path";
325
+ async function readFileSafe(filepath) {
326
+ try {
327
+ return await fs2.readFile(filepath, "utf8");
328
+ } catch (err) {
329
+ if (isNoEnt(err)) return null;
330
+ throw err;
331
+ }
332
+ }
333
+ async function ensureDir2(dir) {
334
+ await fs2.mkdir(dir, { recursive: true });
335
+ }
336
+ async function atomicWriteFile(filepath, content, mode) {
337
+ const dir = path4.dirname(filepath);
338
+ await ensureDir2(dir);
339
+ const tmp = path4.join(
340
+ dir,
341
+ `.maind-install-${process.pid}-${Date.now()}.tmp`
342
+ );
343
+ await fs2.writeFile(tmp, content, { encoding: "utf8", mode });
344
+ try {
345
+ await fs2.rename(tmp, filepath);
346
+ } catch (err) {
347
+ if (isWindowsRenameFailure(err)) {
348
+ try {
349
+ await fs2.copyFile(tmp, filepath);
350
+ await fs2.unlink(tmp).catch(() => {
351
+ });
352
+ if (mode !== void 0) {
353
+ await fs2.chmod(filepath, mode).catch(() => {
354
+ });
355
+ }
356
+ return;
357
+ } catch (fallbackErr) {
358
+ await fs2.unlink(tmp).catch(() => {
359
+ });
360
+ throw fallbackErr;
361
+ }
362
+ }
363
+ await fs2.unlink(tmp).catch(() => {
364
+ });
365
+ throw err;
366
+ }
367
+ }
368
+ async function hasLinePrefix(filepath, prefix) {
369
+ const content = await readFileSafe(filepath);
370
+ if (content === null) return false;
371
+ const lines2 = content.split(/\r?\n/);
372
+ return lines2.some((l) => l.startsWith(prefix));
373
+ }
374
+ function isNoEnt(err) {
375
+ return isNodeError(err) && err.code === "ENOENT";
376
+ }
377
+ function isWindowsRenameFailure(err) {
378
+ if (!isNodeError(err)) return false;
379
+ if (process.platform !== "win32") return false;
380
+ return err.code === "EEXIST" || err.code === "EPERM" || err.code === "EACCES";
381
+ }
382
+ function isNodeError(err) {
383
+ return typeof err === "object" && err !== null && "code" in err;
384
+ }
385
+ var init_atomic_write = __esm({
386
+ "src/install/atomic-write.ts"() {
387
+ "use strict";
388
+ }
389
+ });
390
+
322
391
  // src/install/hook-wiring.ts
323
392
  import { existsSync as existsSync2 } from "node:fs";
324
393
  import * as path6 from "node:path";
325
- function inspectHookWiring(raw, deps = {}) {
394
+ function inspectHookWiring(raw, deps = {}, hooks = MANAGED_SUBCOMMAND_HOOKS) {
326
395
  const fileExists = deps.fileExists ?? existsSync2;
327
396
  const expectedCommand = deps.expectedCommand ?? defaultExpectedCommand;
328
397
  let settings = {};
@@ -333,7 +402,7 @@ function inspectHookWiring(raw, deps = {}) {
333
402
  } catch {
334
403
  }
335
404
  }
336
- return MANAGED_SUBCOMMAND_HOOKS.map((hook) => {
405
+ return hooks.map((hook) => {
337
406
  const base = { event: hook.event, subcommand: hook.subcommand };
338
407
  const command = findCommand(settings, hook.event, hook.subcommand);
339
408
  if (command === null) {
@@ -444,7 +513,7 @@ function tokenize(command) {
444
513
  function isObject3(v) {
445
514
  return typeof v === "object" && v !== null && !Array.isArray(v);
446
515
  }
447
- var MANAGED_SUBCOMMAND_HOOKS;
516
+ var MANAGED_SUBCOMMAND_HOOKS, GUARD_SUBCOMMAND_HOOKS;
448
517
  var init_hook_wiring = __esm({
449
518
  "src/install/hook-wiring.ts"() {
450
519
  "use strict";
@@ -488,90 +557,330 @@ var init_hook_wiring = __esm({
488
557
  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."
489
558
  }
490
559
  ];
560
+ GUARD_SUBCOMMAND_HOOKS = [
561
+ {
562
+ event: "SessionStart",
563
+ subcommand: "guard-inject",
564
+ label: "Guard inject hook",
565
+ timeout: 10,
566
+ consentDescription: "It runs 'maind-mcp-bridge guard-inject' when a session starts (ADR-284 guard). UNLIKE every other hook, this one talks to the maind server: it fetches your session briefing from mcp.maind.dev \u2014 sending your API key, device id, project key, and the client family 'claude-code'; never file contents, never paths \u2014 and injects the result into the session context, so the briefing no longer depends on the model remembering to ask. Cache-first (~12h), so most session starts add no network call. Inactive (exit 0, no output) while guard mode is off."
567
+ },
568
+ {
569
+ event: "PreToolUse",
570
+ subcommand: "guard-gate",
571
+ label: "Guard gate hook",
572
+ timeout: 5,
573
+ matcher: "Edit|Write",
574
+ consentDescription: "It runs 'maind-mcp-bridge guard-gate' before the Edit and Write tools, and before those only. It reads the tool NAME and the session id \u2014 never the tool's arguments, never file contents \u2014 and checks LOCALLY whether this session has been briefed (injection or a maind consultation call). Warn mode (default) adds one reminder line for the model and never blocks; block mode (explicit opt-in via 'guard mode block') may DENY an un-briefed edit, naming the reason and a logged override command. Inactive while guard mode is off."
575
+ },
576
+ {
577
+ event: "Stop",
578
+ subcommand: "guard-stop",
579
+ label: "Guard stop hook",
580
+ timeout: 5,
581
+ consentDescription: "It runs 'maind-mcp-bridge guard-stop' when the session tries to finish. Only with the strict stop-gate enabled ('guard_stop_gate': true \u2014 off by default) and edits made without a review_changes run, it blocks the FIRST stop attempt with a reason so the review can happen; it never blocks twice. Reads only local state; nothing leaves the machine. Inactive while guard mode is off."
582
+ }
583
+ ];
491
584
  }
492
585
  });
493
586
 
494
- // src/bridge-config.ts
495
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
496
- import { join as join8 } from "node:path";
497
- function bridgeConfigPath() {
498
- return join8(configDir(), "config.json");
499
- }
500
- function readBridgeConfig() {
587
+ // src/install/hook-merge.ts
588
+ import * as path7 from "node:path";
589
+ import * as readline2 from "node:readline";
590
+ async function mergeClaudeHook(opts, spec) {
591
+ const settingsPath = path7.join(opts.homeDir, ".claude", "settings.json");
592
+ const targetKey = spec.targetKey;
593
+ if (opts.skip) {
594
+ return { target: targetKey, action: "skip", status: "skipped", detail: "--no-hook" };
595
+ }
596
+ let raw;
501
597
  try {
502
- const file = bridgeConfigPath();
503
- if (!existsSync3(file)) return null;
504
- const raw = JSON.parse(readFileSync3(file, "utf8"));
505
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
506
- return null;
598
+ raw = await readFileSafe(settingsPath);
599
+ } catch (err) {
600
+ return { target: targetKey, action: "merge", status: "failed", detail: `read: ${errMessage(err)}` };
601
+ }
602
+ let settings;
603
+ let action = "create";
604
+ if (raw === null || raw.trim().length === 0) {
605
+ settings = {};
606
+ } else {
607
+ action = "merge";
608
+ try {
609
+ const parsed = JSON.parse(raw);
610
+ if (!isObject4(parsed)) {
611
+ return {
612
+ target: targetKey,
613
+ action: "merge",
614
+ status: "failed",
615
+ detail: "existing settings.json is not a JSON object"
616
+ };
617
+ }
618
+ settings = parsed;
619
+ } catch (err) {
620
+ return { target: targetKey, action: "merge", status: "failed", detail: `parse: ${errMessage(err)}` };
507
621
  }
508
- const o = raw;
509
- const config = {};
510
- if (typeof o.auto_announce === "boolean") {
511
- config.auto_announce = o.auto_announce;
622
+ }
623
+ const existing = findExistingHookCommand(settings, spec.event, spec.matchPattern);
624
+ if (existing !== null) {
625
+ return { target: targetKey, action: "skip", status: "skipped", detail: spec.skipDetail(existing) };
626
+ }
627
+ if (!opts.full) {
628
+ if (!opts.isInteractive) {
629
+ return {
630
+ target: targetKey,
631
+ action: "skip",
632
+ status: "skipped",
633
+ detail: "consent-required: pass --full to write the hook non-interactively"
634
+ };
512
635
  }
513
- if (typeof o.machine_label === "string") {
514
- config.machine_label = o.machine_label;
636
+ if (opts.dryRun) {
637
+ return {
638
+ target: targetKey,
639
+ action: "merge",
640
+ status: action === "create" ? "would-create" : "would-merge",
641
+ detail: `${settingsPath} (would prompt for consent in real run)`
642
+ };
515
643
  }
516
- if (typeof o.auto_working_paths === "boolean") {
517
- config.auto_working_paths = o.auto_working_paths;
644
+ const consent = await promptYesNo(
645
+ opts.out,
646
+ `
647
+ Merge a ${spec.event} hook into ${settingsPath}?
648
+ ${spec.consentDescription}
649
+ [Y/n]: `
650
+ );
651
+ if (!consent) {
652
+ return { target: targetKey, action: "skip", status: "skipped", detail: "user declined" };
518
653
  }
519
- return config;
520
- } catch {
521
- return null;
522
654
  }
523
- }
524
- var init_bridge_config = __esm({
525
- "src/bridge-config.ts"() {
526
- "use strict";
527
- init_device_id();
655
+ const newHookGroup = {
656
+ ...spec.matcher === void 0 ? {} : { matcher: spec.matcher },
657
+ hooks: [{ type: "command", command: spec.command, timeout: spec.timeout }]
658
+ };
659
+ const existingGroups = settings.hooks?.[spec.event] ?? [];
660
+ const nextSettings = {
661
+ ...settings,
662
+ hooks: {
663
+ ...settings.hooks ?? {},
664
+ [spec.event]: [...existingGroups, newHookGroup]
665
+ }
666
+ };
667
+ const nextRaw = JSON.stringify(nextSettings, null, 2) + "\n";
668
+ if (opts.dryRun) {
669
+ return {
670
+ target: targetKey,
671
+ action: action === "create" ? "write" : "merge",
672
+ status: action === "create" ? "would-create" : "would-merge",
673
+ detail: settingsPath
674
+ };
528
675
  }
529
- });
530
-
531
- // ../../packages/code-index/build/parse/keys.js
532
- function moduleKey(filePath) {
533
- return `${filePath}#<module>`;
534
- }
535
- function symbolKey(filePath, qualifiedName, kind) {
536
- return `${filePath}#${qualifiedName}:${kind}`;
537
- }
538
- var init_keys = __esm({
539
- "../../packages/code-index/build/parse/keys.js"() {
540
- "use strict";
676
+ try {
677
+ await atomicWriteFile(settingsPath, nextRaw, 384);
678
+ } catch (err) {
679
+ return { target: targetKey, action: "merge", status: "failed", detail: `write: ${errMessage(err)}` };
541
680
  }
542
- });
543
-
544
- // ../../packages/code-index/build/parse/types.js
545
- function languageForPath(filePath) {
546
- const lower = filePath.toLowerCase();
547
- if (lower.endsWith(".tsx"))
548
- return "tsx";
549
- if (lower.endsWith(".ts") || lower.endsWith(".mts") || lower.endsWith(".cts"))
550
- return "typescript";
551
- if (lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs"))
552
- return "javascript";
553
- if (lower.endsWith(".py") || lower.endsWith(".pyi"))
554
- return "python";
555
- return null;
681
+ return {
682
+ target: targetKey,
683
+ action: action === "create" ? "write" : "merge",
684
+ status: action === "create" ? "created" : "merged",
685
+ detail: settingsPath
686
+ };
556
687
  }
557
- function isSkippablePath(filePath) {
558
- return filePath.toLowerCase().endsWith(".d.ts");
688
+ async function mergeSessionStartHook(opts) {
689
+ const reminderPath = path7.join(opts.homeDir, REMINDER_FILE_REL);
690
+ return mergeClaudeHook(opts, {
691
+ event: "SessionStart",
692
+ command: `cat ${reminderPath}`,
693
+ timeout: 5,
694
+ matchPattern: /maind-session-start-reminder\.md/,
695
+ targetKey: "hook:~/.claude/settings.json",
696
+ skipDetail: () => "SessionStart hook already references the reminder file",
697
+ consentDescription: `It 'cat's ${REMINDER_FILE_REL} into every new Claude Code session.`
698
+ });
559
699
  }
560
- var init_types = __esm({
561
- "../../packages/code-index/build/parse/types.js"() {
562
- "use strict";
563
- }
564
- });
565
-
566
- // ../../packages/code-index/build/embed/recipe.js
567
- function nodeEmbedText(n) {
568
- return [`${n.kind} ${n.qualifiedName}`, n.signature ?? "", n.doc ?? "", n.filePath].filter((s) => s.length > 0).join("\n").slice(0, MAX_CHARS);
700
+ function targetKeyFor(hook) {
701
+ return `hook(${hook.subcommand}):~/.claude/settings.json`;
569
702
  }
570
- var MAX_CHARS;
571
- var init_recipe = __esm({
572
- "../../packages/code-index/build/embed/recipe.js"() {
573
- "use strict";
574
- MAX_CHARS = 1e3;
703
+ async function mergeSubcommandHook(opts, spec) {
704
+ const launch = opts.launch ?? resolveBridgeLaunch({
705
+ entryPath: currentBridgeEntry(),
706
+ nodePath: process.execPath,
707
+ extraArgs: [spec.subcommand],
708
+ isElectron: process.versions.electron !== void 0
709
+ });
710
+ const command = launchToShellCommand(launch);
711
+ return mergeClaudeHook(opts, {
712
+ event: spec.event,
713
+ command,
714
+ timeout: spec.timeout,
715
+ matcher: spec.matcher,
716
+ matchPattern: new RegExp(spec.subcommand),
717
+ targetKey: targetKeyFor(spec),
718
+ skipDetail: (existing) => {
719
+ const wired = `${spec.label} already runs maind ${spec.subcommand}`;
720
+ if (isLegacyHookForm(existing)) {
721
+ return `${wired}, but via the retired @maind/claude-code-hook \u2014 the bridge now owns that subcommand and that package is not published. Replace its command with: ${command}`;
722
+ }
723
+ if (isNpxForm(existing)) {
724
+ return `${wired}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${command}`;
725
+ }
726
+ return wired;
727
+ },
728
+ consentDescription: spec.consentDescription
729
+ });
730
+ }
731
+ function managed(subcommand) {
732
+ const hook = MANAGED_SUBCOMMAND_HOOKS.find((h) => h.subcommand === subcommand);
733
+ if (!hook) throw new Error(`no managed hook for subcommand ${subcommand}`);
734
+ return hook;
735
+ }
736
+ async function mergeStopHook(opts) {
737
+ return mergeSubcommandHook(opts, managed("on-session-end"));
738
+ }
739
+ async function mergeSessionStartMetricsHook(opts) {
740
+ return mergeSubcommandHook(opts, managed("on-session-start"));
741
+ }
742
+ async function mergeToolUseHook(opts) {
743
+ return mergeSubcommandHook(opts, managed("on-tool-use"));
744
+ }
745
+ async function mergeFileWriteHook(opts) {
746
+ return mergeSubcommandHook(opts, managed("on-file-write"));
747
+ }
748
+ async function mergeFileEditHook(opts) {
749
+ return mergeSubcommandHook(opts, managed("on-file-edit"));
750
+ }
751
+ function findExistingHookCommand(settings, event, pattern) {
752
+ const groups = settings.hooks?.[event];
753
+ if (!Array.isArray(groups)) return null;
754
+ for (const group of groups) {
755
+ if (!isObject4(group)) continue;
756
+ const hooks = group.hooks;
757
+ if (!Array.isArray(hooks)) continue;
758
+ for (const hook of hooks) {
759
+ if (!isObject4(hook)) continue;
760
+ const cmd = hook.command;
761
+ if (typeof cmd === "string" && pattern.test(cmd)) return cmd;
762
+ }
763
+ }
764
+ return null;
765
+ }
766
+ async function promptYesNo(out2, prompt) {
767
+ out2.write(prompt);
768
+ const rl = readline2.createInterface({
769
+ input: process.stdin,
770
+ output: out2,
771
+ terminal: true
772
+ });
773
+ const answer = await new Promise((resolve3) => {
774
+ rl.question("", (input) => resolve3(input.trim().toLowerCase()));
775
+ });
776
+ rl.close();
777
+ if (answer === "" || answer === "y" || answer === "yes") return true;
778
+ return false;
779
+ }
780
+ function isObject4(v) {
781
+ return typeof v === "object" && v !== null && !Array.isArray(v);
782
+ }
783
+ function errMessage(err) {
784
+ return err instanceof Error ? err.message : String(err);
785
+ }
786
+ var REMINDER_FILE_REL;
787
+ var init_hook_merge = __esm({
788
+ "src/install/hook-merge.ts"() {
789
+ "use strict";
790
+ init_atomic_write();
791
+ init_bridge_entry();
792
+ init_hook_wiring();
793
+ REMINDER_FILE_REL = ".claude/maind-session-start-reminder.md";
794
+ }
795
+ });
796
+
797
+ // src/bridge-config.ts
798
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
799
+ import { join as join8 } from "node:path";
800
+ function bridgeConfigPath() {
801
+ return join8(configDir(), "config.json");
802
+ }
803
+ function readBridgeConfig() {
804
+ try {
805
+ const file = bridgeConfigPath();
806
+ if (!existsSync3(file)) return null;
807
+ const raw = JSON.parse(readFileSync3(file, "utf8"));
808
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
809
+ return null;
810
+ }
811
+ const o = raw;
812
+ const config = {};
813
+ if (typeof o.auto_announce === "boolean") {
814
+ config.auto_announce = o.auto_announce;
815
+ }
816
+ if (typeof o.machine_label === "string") {
817
+ config.machine_label = o.machine_label;
818
+ }
819
+ if (typeof o.auto_working_paths === "boolean") {
820
+ config.auto_working_paths = o.auto_working_paths;
821
+ }
822
+ if (o.guard_mode === "off" || o.guard_mode === "warn" || o.guard_mode === "block") {
823
+ config.guard_mode = o.guard_mode;
824
+ }
825
+ if (typeof o.guard_stop_gate === "boolean") {
826
+ config.guard_stop_gate = o.guard_stop_gate;
827
+ }
828
+ return config;
829
+ } catch {
830
+ return null;
831
+ }
832
+ }
833
+ var init_bridge_config = __esm({
834
+ "src/bridge-config.ts"() {
835
+ "use strict";
836
+ init_device_id();
837
+ }
838
+ });
839
+
840
+ // ../../packages/code-index/build/parse/keys.js
841
+ function moduleKey(filePath) {
842
+ return `${filePath}#<module>`;
843
+ }
844
+ function symbolKey(filePath, qualifiedName, kind) {
845
+ return `${filePath}#${qualifiedName}:${kind}`;
846
+ }
847
+ var init_keys = __esm({
848
+ "../../packages/code-index/build/parse/keys.js"() {
849
+ "use strict";
850
+ }
851
+ });
852
+
853
+ // ../../packages/code-index/build/parse/types.js
854
+ function languageForPath(filePath) {
855
+ const lower = filePath.toLowerCase();
856
+ if (lower.endsWith(".tsx"))
857
+ return "tsx";
858
+ if (lower.endsWith(".ts") || lower.endsWith(".mts") || lower.endsWith(".cts"))
859
+ return "typescript";
860
+ if (lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs"))
861
+ return "javascript";
862
+ if (lower.endsWith(".py") || lower.endsWith(".pyi"))
863
+ return "python";
864
+ return null;
865
+ }
866
+ function isSkippablePath(filePath) {
867
+ return filePath.toLowerCase().endsWith(".d.ts");
868
+ }
869
+ var init_types = __esm({
870
+ "../../packages/code-index/build/parse/types.js"() {
871
+ "use strict";
872
+ }
873
+ });
874
+
875
+ // ../../packages/code-index/build/embed/recipe.js
876
+ function nodeEmbedText(n) {
877
+ return [`${n.kind} ${n.qualifiedName}`, n.signature ?? "", n.doc ?? "", n.filePath].filter((s) => s.length > 0).join("\n").slice(0, MAX_CHARS);
878
+ }
879
+ var MAX_CHARS;
880
+ var init_recipe = __esm({
881
+ "../../packages/code-index/build/embed/recipe.js"() {
882
+ "use strict";
883
+ MAX_CHARS = 1e3;
575
884
  }
576
885
  });
577
886
 
@@ -3717,6 +4026,30 @@ var init_hook_input = __esm({
3717
4026
  }
3718
4027
  });
3719
4028
 
4029
+ // src/hooks/payloads.ts
4030
+ function denyPayload(reason) {
4031
+ return JSON.stringify({
4032
+ hookSpecificOutput: {
4033
+ hookEventName: "PreToolUse",
4034
+ permissionDecision: "deny",
4035
+ permissionDecisionReason: reason
4036
+ }
4037
+ });
4038
+ }
4039
+ function advisoryPayload(context) {
4040
+ return JSON.stringify({
4041
+ hookSpecificOutput: {
4042
+ hookEventName: "PreToolUse",
4043
+ additionalContext: context
4044
+ }
4045
+ });
4046
+ }
4047
+ var init_payloads = __esm({
4048
+ "src/hooks/payloads.ts"() {
4049
+ "use strict";
4050
+ }
4051
+ });
4052
+
3720
4053
  // src/hooks/state.ts
3721
4054
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, rename as rename2 } from "node:fs/promises";
3722
4055
  import { existsSync as existsSync9 } from "node:fs";
@@ -3735,7 +4068,8 @@ async function loadState() {
3735
4068
  sessions: parsed.sessions ?? {},
3736
4069
  pending_metrics: Array.isArray(parsed.pending_metrics) ? parsed.pending_metrics : [],
3737
4070
  thresholds: parsed.thresholds,
3738
- thresholds_synced_at: parsed.thresholds_synced_at
4071
+ thresholds_synced_at: parsed.thresholds_synced_at,
4072
+ recently_closed: parsed.recently_closed
3739
4073
  };
3740
4074
  } catch (err) {
3741
4075
  process.stderr.write(
@@ -3773,6 +4107,7 @@ var init_state = __esm({
3773
4107
  // src/hooks/index.ts
3774
4108
  var hooks_exports = {};
3775
4109
  __export(hooks_exports, {
4110
+ closeTrackedSession: () => closeTrackedSession,
3776
4111
  effectiveConfig: () => effectiveConfig,
3777
4112
  grandparentPid: () => grandparentPid,
3778
4113
  runFlush: () => runFlush,
@@ -3789,6 +4124,46 @@ import { existsSync as existsSync10, readFileSync as readFileSync8, realpathSync
3789
4124
  import { writeFile as writeFile3 } from "node:fs/promises";
3790
4125
  import { homedir as homedir6 } from "node:os";
3791
4126
  import { basename, dirname as dirname5, isAbsolute as isAbsolute3, join as join16, relative as relative2 } from "node:path";
4127
+ function pruneTombstones(tombstones, nowMs) {
4128
+ const pruned = {};
4129
+ for (const [id, ts] of Object.entries(tombstones)) {
4130
+ const parsed = Date.parse(ts);
4131
+ if (!Number.isNaN(parsed) && nowMs - parsed < TOMBSTONE_TTL_MS) pruned[id] = ts;
4132
+ }
4133
+ return pruned;
4134
+ }
4135
+ function closeTrackedSession(state, id, nowMs = Date.now()) {
4136
+ const session = state.sessions[id];
4137
+ if (!session) return false;
4138
+ const closedAt = state.recently_closed?.[id];
4139
+ const recentlyClosed = typeof closedAt === "string" && nowMs - Date.parse(closedAt) < TOMBSTONE_TTL_MS;
4140
+ if (!recentlyClosed) {
4141
+ const durationMs = nowMs - new Date(session.started_at).getTime();
4142
+ state.pending_metrics.push(
4143
+ {
4144
+ session_id: id,
4145
+ metric_key: "session_duration_ms",
4146
+ metric_value: Math.max(0, durationMs)
4147
+ },
4148
+ {
4149
+ session_id: id,
4150
+ metric_key: "tool_call_count",
4151
+ metric_value: session.tool_call_count
4152
+ },
4153
+ {
4154
+ session_id: id,
4155
+ metric_key: "lessons_consulted",
4156
+ metric_value: session.lessons_consulted
4157
+ }
4158
+ );
4159
+ }
4160
+ delete state.sessions[id];
4161
+ state.recently_closed = pruneTombstones(
4162
+ { ...state.recently_closed, [id]: new Date(nowMs).toISOString() },
4163
+ nowMs
4164
+ );
4165
+ return !recentlyClosed;
4166
+ }
3792
4167
  function effectiveConfig(state) {
3793
4168
  if (state.config) return state.config;
3794
4169
  const key = readApiKey();
@@ -3875,6 +4250,14 @@ async function runOnToolUse() {
3875
4250
  if (tool.includes("search_lessons") || tool.includes("get_session_briefing") || tool.includes("get_lesson")) {
3876
4251
  session.lessons_consulted += 1;
3877
4252
  }
4253
+ if (tool.includes("maind")) {
4254
+ if (tool.includes("search_lessons") || tool.includes("get_session_briefing") || tool.includes("get_lesson") || tool.includes("get_conventions") || tool.includes("activate_skill") || tool.includes("suggest_skills") || tool.includes("codebase_change_briefing")) {
4255
+ session.consultations = (session.consultations ?? 0) + 1;
4256
+ }
4257
+ if (tool.includes("review_changes")) {
4258
+ session.reviews_ran = (session.reviews_ran ?? 0) + 1;
4259
+ }
4260
+ }
3878
4261
  const transcriptPath = input.transcript_path;
3879
4262
  if (typeof transcriptPath === "string" && transcriptPath && !session.transcript_path) {
3880
4263
  session.transcript_path = transcriptPath;
@@ -3904,15 +4287,6 @@ function realpathOfUnwritten(p) {
3904
4287
  }
3905
4288
  }
3906
4289
  }
3907
- function denyPayload(reason) {
3908
- return JSON.stringify({
3909
- hookSpecificOutput: {
3910
- hookEventName: "PreToolUse",
3911
- permissionDecision: "deny",
3912
- permissionDecisionReason: reason
3913
- }
3914
- });
3915
- }
3916
4290
  function denyReason(verdict, ns) {
3917
4291
  const holders = verdict.sightings.map((s) => ` - ${s.path} (${s.where})`).join("\n");
3918
4292
  return `${ns.prefix}${verdict.number} is already taken:
@@ -3942,14 +4316,6 @@ async function runOnFileWrite() {
3942
4316
  return 0;
3943
4317
  }
3944
4318
  }
3945
- function advisoryPayload(context) {
3946
- return JSON.stringify({
3947
- hookSpecificOutput: {
3948
- hookEventName: "PreToolUse",
3949
- additionalContext: context
3950
- }
3951
- });
3952
- }
3953
4319
  async function runOnFileEdit() {
3954
4320
  try {
3955
4321
  const input = await readHookInput();
@@ -4048,27 +4414,8 @@ async function runSessionEndMetrics(sessionId) {
4048
4414
  const config = effectiveConfig(state);
4049
4415
  if (config === null) return;
4050
4416
  const id = sessionId ?? Object.keys(state.sessions)[0];
4051
- const session = id ? state.sessions[id] : void 0;
4052
- if (session) {
4053
- const durationMs = Date.now() - new Date(session.started_at).getTime();
4054
- state.pending_metrics.push(
4055
- {
4056
- session_id: id,
4057
- metric_key: "session_duration_ms",
4058
- metric_value: Math.max(0, durationMs)
4059
- },
4060
- {
4061
- session_id: id,
4062
- metric_key: "tool_call_count",
4063
- metric_value: session.tool_call_count
4064
- },
4065
- {
4066
- session_id: id,
4067
- metric_key: "lessons_consulted",
4068
- metric_value: session.lessons_consulted
4069
- }
4070
- );
4071
- delete state.sessions[id];
4417
+ if (id && state.sessions[id]) {
4418
+ closeTrackedSession(state, id);
4072
4419
  await saveState(state);
4073
4420
  }
4074
4421
  await flushPending(config, STOP_FLUSH_TIMEOUT_MS);
@@ -4237,7 +4584,7 @@ function sessionIdOf(input) {
4237
4584
  const id = typeof input.session_id === "string" ? input.session_id.trim() : "";
4238
4585
  return id.length > 0 ? id : null;
4239
4586
  }
4240
- var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS, WIRING_REMEDY;
4587
+ var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS, TOMBSTONE_TTL_MS, WIRING_REMEDY;
4241
4588
  var init_hooks2 = __esm({
4242
4589
  "src/hooks/index.ts"() {
4243
4590
  "use strict";
@@ -4251,10 +4598,12 @@ var init_hooks2 = __esm({
4251
4598
  init_api();
4252
4599
  init_edit_guard();
4253
4600
  init_hook_input();
4601
+ init_payloads();
4254
4602
  init_state();
4255
4603
  DEFAULT_THRESHOLDS_ENDPOINT = process.env.MAIND_THRESHOLDS_ENDPOINT ?? "https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds";
4256
4604
  STOP_FLUSH_TIMEOUT_MS = 1500;
4257
4605
  MANUAL_FLUSH_TIMEOUT_MS = 1e4;
4606
+ TOMBSTONE_TTL_MS = 24 * 60 * 60 * 1e3;
4258
4607
  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.";
4259
4608
  }
4260
4609
  });
@@ -4264,115 +4613,909 @@ function resolveConnection(e) {
4264
4613
  if (e.ownSnapshotAgeMs !== null && e.ownSnapshotAgeMs <= SNAPSHOT_EVIDENCE_MAX_AGE_MS) {
4265
4614
  return "connected";
4266
4615
  }
4267
- if (e.sawMaindCall) return "connected";
4268
- if (e.presenceUsable) return "not_connected";
4269
- return "unknown";
4616
+ if (e.sawMaindCall) return "connected";
4617
+ if (e.presenceUsable) return "not_connected";
4618
+ return "unknown";
4619
+ }
4620
+ var SNAPSHOT_EVIDENCE_MAX_AGE_MS;
4621
+ var init_connection = __esm({
4622
+ "src/session-end/connection.ts"() {
4623
+ "use strict";
4624
+ SNAPSHOT_EVIDENCE_MAX_AGE_MS = 30 * 6e4;
4625
+ }
4626
+ });
4627
+
4628
+ // src/session-end/index.ts
4629
+ var session_end_exports = {};
4630
+ __export(session_end_exports, {
4631
+ runOnSessionEnd: () => runOnSessionEnd
4632
+ });
4633
+ function connectionVerdict(sawMaindCall, nowMs) {
4634
+ try {
4635
+ const projectKey = computeProjectKey();
4636
+ const presenceUsable = projectKey !== null && !autoAnnounceDisabled(process.env, readBridgeConfig());
4637
+ let ownSnapshotAgeMs = null;
4638
+ if (projectKey !== null) {
4639
+ const own = selectOwnSnapshot(readSnapshots(projectKey), {
4640
+ grandparentPid: grandparentPid(),
4641
+ cwd: process.cwd()
4642
+ });
4643
+ if (own) {
4644
+ const written = Date.parse(own.snap.written_at);
4645
+ ownSnapshotAgeMs = Number.isFinite(written) ? Math.max(0, nowMs - written) : null;
4646
+ }
4647
+ }
4648
+ return resolveConnection({ ownSnapshotAgeMs, sawMaindCall, presenceUsable });
4649
+ } catch {
4650
+ return sawMaindCall ? "connected" : "unknown";
4651
+ }
4652
+ }
4653
+ function presenceSessionId() {
4654
+ const raw = (process.env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
4655
+ 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;
4656
+ }
4657
+ async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
4658
+ const post = fetch(INGEST_ENDPOINT, {
4659
+ method: "POST",
4660
+ headers: {
4661
+ "content-type": "application/json",
4662
+ authorization: `Bearer ${apiKey}`,
4663
+ "x-maind-device-id": deviceId,
4664
+ "x-maind-bridge-version": BRIDGE_VERSION
4665
+ },
4666
+ body: JSON.stringify(body)
4667
+ }).then(() => void 0).catch(() => void 0);
4668
+ const timeout = new Promise((resolve3) => setTimeout(resolve3, timeoutMs));
4669
+ await Promise.race([post, timeout]);
4670
+ }
4671
+ async function runOnSessionEnd() {
4672
+ const apiKey = readApiKey();
4673
+ if (!apiKey) return 0;
4674
+ const input = await readHookInput();
4675
+ const sessionId = typeof input.session_id === "string" && input.session_id ? input.session_id : null;
4676
+ const transcriptPath = transcriptPathOf(input);
4677
+ if (transcriptPath) {
4678
+ try {
4679
+ const [analytics, span] = await Promise.all([
4680
+ analyzeSession(transcriptPath),
4681
+ analyzeSpan(transcriptPath)
4682
+ ]);
4683
+ if (sessionId) {
4684
+ analytics.session_id = sessionId;
4685
+ span.session_id = sessionId;
4686
+ }
4687
+ analytics.maind_connected = connectionVerdict(
4688
+ analytics.maind_connected === "connected",
4689
+ Date.now()
4690
+ );
4691
+ if (analytics.session_id) {
4692
+ const body = ingestBody(analytics, span, {
4693
+ client_session_id: presenceSessionId(),
4694
+ client: "claude-code"
4695
+ });
4696
+ await postWithTimeout(apiKey, ensureDeviceId(), body, 1500);
4697
+ }
4698
+ } catch (err) {
4699
+ process.stderr.write(
4700
+ `[maind-mcp-bridge] session-end ingest failed: ${err instanceof Error ? err.message : String(err)}
4701
+ `
4702
+ );
4703
+ }
4704
+ }
4705
+ await runSessionEndMetrics(sessionId);
4706
+ return 0;
4707
+ }
4708
+ var INGEST_ENDPOINT;
4709
+ var init_session_end = __esm({
4710
+ "src/session-end/index.ts"() {
4711
+ "use strict";
4712
+ init_dist();
4713
+ init_bridge_config();
4714
+ init_device_id();
4715
+ init_api();
4716
+ init_edit_guard();
4717
+ init_hook_input();
4718
+ init_hooks2();
4719
+ init_presence();
4720
+ init_presence_snapshot();
4721
+ init_project_key();
4722
+ init_version();
4723
+ init_connection();
4724
+ INGEST_ENDPOINT = DEFAULT_INGEST_ENDPOINT;
4725
+ }
4726
+ });
4727
+
4728
+ // src/guard/config.ts
4729
+ function resolveGuardConfig(env = process.env, cfg = readBridgeConfig()) {
4730
+ const fromEnv = env.MAIND_GUARD;
4731
+ const mode = fromEnv === "off" || fromEnv === "warn" || fromEnv === "block" ? fromEnv : cfg?.guard_mode ?? "off";
4732
+ return { mode, stopGate: cfg?.guard_stop_gate === true };
4733
+ }
4734
+ async function writeGuardConfig(patch, configPath = bridgeConfigPath()) {
4735
+ let existing = {};
4736
+ try {
4737
+ const raw = await readFileSafe(configPath);
4738
+ if (raw !== null && raw.trim().length > 0) {
4739
+ const parsed = JSON.parse(raw);
4740
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
4741
+ existing = parsed;
4742
+ }
4743
+ }
4744
+ } catch {
4745
+ }
4746
+ const next = { ...existing, ...patch };
4747
+ await atomicWriteFile(configPath, JSON.stringify(next, null, 2) + "\n", 384);
4748
+ }
4749
+ var init_config = __esm({
4750
+ "src/guard/config.ts"() {
4751
+ "use strict";
4752
+ init_bridge_config();
4753
+ init_atomic_write();
4754
+ }
4755
+ });
4756
+
4757
+ // src/guard/install.ts
4758
+ function parseGuardInstallFlags(argv) {
4759
+ const flags = {
4760
+ mode: "warn",
4761
+ // ADR-284: warn is the default; block is opt-in
4762
+ stopGate: false,
4763
+ full: false,
4764
+ dryRun: false
4765
+ };
4766
+ for (let i = 0; i < argv.length; i++) {
4767
+ const a = argv[i];
4768
+ switch (a) {
4769
+ case "--mode": {
4770
+ const v = argv[++i];
4771
+ if (v !== "warn" && v !== "block") return null;
4772
+ flags.mode = v;
4773
+ break;
4774
+ }
4775
+ case "--stop-gate":
4776
+ flags.stopGate = true;
4777
+ break;
4778
+ case "--full":
4779
+ case "--yes":
4780
+ flags.full = true;
4781
+ break;
4782
+ case "--dry-run":
4783
+ flags.dryRun = true;
4784
+ break;
4785
+ default:
4786
+ return null;
4787
+ }
4788
+ }
4789
+ return flags;
4790
+ }
4791
+ async function runGuardInstall(argv, homeDir, out2 = process.stdout) {
4792
+ const flags = parseGuardInstallFlags(argv);
4793
+ if (flags === null) {
4794
+ out2.write(
4795
+ "usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]\n"
4796
+ );
4797
+ return 1;
4798
+ }
4799
+ const opts = {
4800
+ homeDir,
4801
+ isInteractive: process.stdin.isTTY === true,
4802
+ full: flags.full,
4803
+ skip: false,
4804
+ dryRun: flags.dryRun,
4805
+ out: out2
4806
+ };
4807
+ const results = [];
4808
+ for (const hook of GUARD_SUBCOMMAND_HOOKS) {
4809
+ results.push(await mergeSubcommandHook(opts, hook));
4810
+ }
4811
+ for (const r of results) {
4812
+ out2.write(` ${r.status.padEnd(12)} ${r.target}${r.detail ? ` \u2014 ${r.detail}` : ""}
4813
+ `);
4814
+ }
4815
+ const declined = results.some((r) => r.detail === "user declined");
4816
+ const failed3 = results.some((r) => r.status === "failed");
4817
+ if (flags.dryRun) {
4818
+ out2.write(
4819
+ `
4820
+ [dry-run] would set guard_mode=${flags.mode}` + (flags.stopGate ? " + guard_stop_gate=true" : "") + " in the bridge config.\n"
4821
+ );
4822
+ return 0;
4823
+ }
4824
+ await writeGuardConfig({
4825
+ guard_mode: flags.mode,
4826
+ ...flags.stopGate ? { guard_stop_gate: true } : {}
4827
+ });
4828
+ out2.write(
4829
+ `
4830
+ Guard mode: ${flags.mode}` + (flags.stopGate ? " (+ strict stop-gate)" : "") + "\n flip: maind-mcp-bridge guard mode <warn|block>\n disable: maind-mcp-bridge guard off (hooks stay wired, become no-ops)\n check: maind-mcp-bridge guard status\nTakes effect for NEW Claude Code sessions (hooks are read at session start).\n"
4831
+ );
4832
+ if (declined) {
4833
+ out2.write(
4834
+ "Note: at least one hook was declined \u2014 the guard runs with what was consented.\n"
4835
+ );
4836
+ }
4837
+ return failed3 ? 1 : 0;
4838
+ }
4839
+ var init_install = __esm({
4840
+ "src/guard/install.ts"() {
4841
+ "use strict";
4842
+ init_hook_wiring();
4843
+ init_hook_merge();
4844
+ init_config();
4845
+ }
4846
+ });
4847
+
4848
+ // src/guard/session-file.ts
4849
+ import { existsSync as existsSync11 } from "node:fs";
4850
+ import { mkdir as mkdir3, readFile as readFile3, readdir, rename as rename3, stat as stat2, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
4851
+ import { join as join17 } from "node:path";
4852
+ function sessionFile(sessionId) {
4853
+ return join17(GUARD_SESSIONS_DIR, sessionId.replace(/[^a-zA-Z0-9._-]/g, "_") + ".json");
4854
+ }
4855
+ async function loadGuardSession(sessionId) {
4856
+ try {
4857
+ const file = sessionFile(sessionId);
4858
+ if (!existsSync11(file)) return {};
4859
+ const parsed = JSON.parse(await readFile3(file, "utf8"));
4860
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
4861
+ return parsed;
4862
+ }
4863
+ return {};
4864
+ } catch {
4865
+ return {};
4866
+ }
4867
+ }
4868
+ async function saveGuardSession(sessionId, state) {
4869
+ await mkdir3(GUARD_SESSIONS_DIR, { recursive: true, mode: 448 });
4870
+ const file = sessionFile(sessionId);
4871
+ const tmp = `${file}.tmp`;
4872
+ await writeFile4(tmp, JSON.stringify({ ...state, updated_at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2), {
4873
+ mode: 384
4874
+ });
4875
+ await rename3(tmp, file);
4876
+ }
4877
+ async function sweepOldGuardSessions(maxAgeMs = 7 * 24 * 60 * 60 * 1e3, nowMs = Date.now()) {
4878
+ try {
4879
+ if (!existsSync11(GUARD_SESSIONS_DIR)) return;
4880
+ for (const name of await readdir(GUARD_SESSIONS_DIR)) {
4881
+ if (!name.endsWith(".json")) continue;
4882
+ const file = join17(GUARD_SESSIONS_DIR, name);
4883
+ try {
4884
+ const s = await stat2(file);
4885
+ if (nowMs - s.mtimeMs > maxAgeMs) await unlink2(file);
4886
+ } catch {
4887
+ }
4888
+ }
4889
+ } catch {
4890
+ }
4891
+ }
4892
+ var GUARD_DIR, GUARD_SESSIONS_DIR;
4893
+ var init_session_file = __esm({
4894
+ "src/guard/session-file.ts"() {
4895
+ "use strict";
4896
+ init_state();
4897
+ GUARD_DIR = join17(STATE_DIR, "guard");
4898
+ GUARD_SESSIONS_DIR = join17(GUARD_DIR, "sessions");
4899
+ }
4900
+ });
4901
+
4902
+ // src/guard/log.ts
4903
+ import { existsSync as existsSync12 } from "node:fs";
4904
+ import { appendFile, mkdir as mkdir4, open } from "node:fs/promises";
4905
+ import { join as join18 } from "node:path";
4906
+ async function appendGuardEvent(event) {
4907
+ try {
4908
+ await mkdir4(GUARD_DIR, { recursive: true, mode: 448 });
4909
+ const line = JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...event }) + "\n";
4910
+ await appendFile(GUARD_EVENTS_FILE, line, { mode: 384 });
4911
+ } catch {
4912
+ }
4913
+ }
4914
+ async function readGuardEventCounts(tailBytes = 256 * 1024) {
4915
+ const counts = {
4916
+ inject_ok: 0,
4917
+ inject_fail: 0,
4918
+ warn: 0,
4919
+ deny: 0,
4920
+ override: 0,
4921
+ stop_block: 0
4922
+ };
4923
+ try {
4924
+ if (!existsSync12(GUARD_EVENTS_FILE)) return counts;
4925
+ const fh = await open(GUARD_EVENTS_FILE, "r");
4926
+ try {
4927
+ const size = (await fh.stat()).size;
4928
+ const start = Math.max(0, size - tailBytes);
4929
+ const buf = Buffer.alloc(size - start);
4930
+ await fh.read(buf, 0, buf.length, start);
4931
+ const text = buf.toString("utf8");
4932
+ const lines2 = text.split("\n");
4933
+ for (const line of start > 0 ? lines2.slice(1) : lines2) {
4934
+ if (!line.trim()) continue;
4935
+ try {
4936
+ const parsed = JSON.parse(line);
4937
+ if (typeof parsed.event === "string" && parsed.event in counts) {
4938
+ counts[parsed.event] += 1;
4939
+ }
4940
+ } catch {
4941
+ }
4942
+ }
4943
+ } finally {
4944
+ await fh.close();
4945
+ }
4946
+ } catch {
4947
+ }
4948
+ return counts;
4949
+ }
4950
+ var GUARD_EVENTS_FILE;
4951
+ var init_log = __esm({
4952
+ "src/guard/log.ts"() {
4953
+ "use strict";
4954
+ init_session_file();
4955
+ GUARD_EVENTS_FILE = join18(GUARD_DIR, "events.jsonl");
4956
+ }
4957
+ });
4958
+
4959
+ // src/guard/cli.ts
4960
+ var cli_exports = {};
4961
+ __export(cli_exports, {
4962
+ runGuard: () => runGuard
4963
+ });
4964
+ import { existsSync as existsSync13, readFileSync as readFileSync9 } from "node:fs";
4965
+ import { homedir as homedir7 } from "node:os";
4966
+ import { join as join19 } from "node:path";
4967
+ async function runGuard(argv) {
4968
+ const verb = argv[0];
4969
+ const rest = argv.slice(1);
4970
+ switch (verb) {
4971
+ case "install":
4972
+ return runGuardInstall(rest, homedir7());
4973
+ case "status":
4974
+ return runGuardStatus();
4975
+ case "mode": {
4976
+ const v = rest[0];
4977
+ if (v !== "warn" && v !== "block") {
4978
+ process.stdout.write("usage: maind-mcp-bridge guard mode <warn|block>\n");
4979
+ return 1;
4980
+ }
4981
+ await writeGuardConfig({ guard_mode: v });
4982
+ process.stdout.write(
4983
+ `guard mode set to '${v}' \u2014 takes effect for new sessions.
4984
+ `
4985
+ );
4986
+ return 0;
4987
+ }
4988
+ case "off":
4989
+ await writeGuardConfig({ guard_mode: "off" });
4990
+ process.stdout.write(
4991
+ "guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.\n"
4992
+ );
4993
+ return 0;
4994
+ case "stop-gate": {
4995
+ const v = rest[0];
4996
+ if (v !== "on" && v !== "off") {
4997
+ process.stdout.write("usage: maind-mcp-bridge guard stop-gate <on|off>\n");
4998
+ return 1;
4999
+ }
5000
+ await writeGuardConfig({ guard_stop_gate: v === "on" });
5001
+ process.stdout.write(`strict stop-gate ${v === "on" ? "enabled" : "disabled"}.
5002
+ `);
5003
+ return 0;
5004
+ }
5005
+ case "skip":
5006
+ return runGuardSkip(rest);
5007
+ default:
5008
+ process.stdout.write(USAGE);
5009
+ return verb === void 0 || verb === "--help" || verb === "-h" ? 0 : 1;
5010
+ }
5011
+ }
5012
+ async function runGuardSkip(argv) {
5013
+ let sessionId = null;
5014
+ let reason = null;
5015
+ for (let i = 0; i < argv.length; i++) {
5016
+ if (argv[i] === "--session") sessionId = argv[++i] ?? null;
5017
+ else if (argv[i] === "--reason") reason = argv[++i] ?? null;
5018
+ }
5019
+ if (!sessionId || !reason || reason.trim().length === 0) {
5020
+ process.stdout.write(
5021
+ 'usage: maind-mcp-bridge guard skip --session <id> --reason "<why consultation is unnecessary here>"\n'
5022
+ );
5023
+ return 1;
5024
+ }
5025
+ const trimmed = reason.trim().slice(0, 500);
5026
+ const session = await loadGuardSession(sessionId);
5027
+ await saveGuardSession(sessionId, { ...session, override_reason: trimmed });
5028
+ await appendGuardEvent({
5029
+ event: "override",
5030
+ session_id: sessionId,
5031
+ reason: trimmed,
5032
+ cwd: process.cwd()
5033
+ });
5034
+ process.stdout.write(
5035
+ `override recorded for session ${sessionId} \u2014 the gate opens on the next attempt.
5036
+ logged (auditable) in ${GUARD_EVENTS_FILE}
5037
+ `
5038
+ );
5039
+ return 0;
5040
+ }
5041
+ async function runGuardStatus() {
5042
+ const config = resolveGuardConfig();
5043
+ const settingsPath = join19(homedir7(), ".claude", "settings.json");
5044
+ let raw = null;
5045
+ try {
5046
+ if (existsSync13(settingsPath)) raw = readFileSync9(settingsPath, "utf8");
5047
+ } catch {
5048
+ }
5049
+ const wiring = inspectHookWiring(raw, {}, GUARD_SUBCOMMAND_HOOKS);
5050
+ const events = await readGuardEventCounts();
5051
+ process.stdout.write(
5052
+ JSON.stringify(
5053
+ {
5054
+ mode: config.mode,
5055
+ stop_gate: config.stopGate,
5056
+ mode_source: process.env.MAIND_GUARD ? "env:MAIND_GUARD" : "config.json",
5057
+ hook_wiring: wiring.map((f) => ({
5058
+ event: f.event,
5059
+ subcommand: f.subcommand,
5060
+ status: f.status,
5061
+ detail: f.detail
5062
+ })),
5063
+ events,
5064
+ events_file: GUARD_EVENTS_FILE
5065
+ },
5066
+ null,
5067
+ 2
5068
+ ) + "\n"
5069
+ );
5070
+ const missing = wiring.filter((f) => f.status !== "ok");
5071
+ if (config.mode === "off") {
5072
+ process.stderr.write(
5073
+ "\n[maind] guard is OFF \u2014 enable with `guard install` (first time) or `guard mode warn|block`.\n"
5074
+ );
5075
+ }
5076
+ if (missing.length > 0 && config.mode !== "off") {
5077
+ process.stderr.write("\n[maind] guard hook wiring is incomplete:\n");
5078
+ for (const f of missing) process.stderr.write(` \u2022 ${f.detail}
5079
+ `);
5080
+ if (missing.some((f) => f.remedy === "run-install")) {
5081
+ process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n");
5082
+ }
5083
+ }
5084
+ return 0;
5085
+ }
5086
+ var USAGE;
5087
+ var init_cli = __esm({
5088
+ "src/guard/cli.ts"() {
5089
+ "use strict";
5090
+ init_hook_wiring();
5091
+ init_config();
5092
+ init_install();
5093
+ init_log();
5094
+ init_session_file();
5095
+ USAGE = [
5096
+ "usage: maind-mcp-bridge guard <verb>",
5097
+ "",
5098
+ " install [--mode warn|block] [--stop-gate] [--full] [--dry-run]",
5099
+ " wire the guard hooks (consent per hook, append-only) + set the mode",
5100
+ " status mode, hook wiring, and local event counts",
5101
+ " mode <warn|block>",
5102
+ " flip enforcement hardness (config-only; settings.json untouched)",
5103
+ " off disable the guard (hooks stay wired, become no-ops)",
5104
+ " stop-gate <on|off>",
5105
+ " toggle the strict completion gate (review before finish)",
5106
+ ' skip --session <id> --reason "<why>"',
5107
+ " record a logged override for one session (block-gate exit valve)",
5108
+ ""
5109
+ ].join("\n");
5110
+ }
5111
+ });
5112
+
5113
+ // src/guard/mcp-client.ts
5114
+ async function fetchSessionBriefing(opts) {
5115
+ const mcpUrl = opts.mcpUrl ?? process.env.MAIND_MCP_URL ?? DEFAULT_MCP_URL3;
5116
+ const controller = new AbortController();
5117
+ const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 3e3);
5118
+ try {
5119
+ const base = {
5120
+ "content-type": "application/json",
5121
+ accept: "application/json, text/event-stream",
5122
+ authorization: `Bearer ${opts.apiKey}`,
5123
+ // The guard acts on behalf of a Claude Code session — attribute it so.
5124
+ "x-maind-client-family": "claude-code",
5125
+ "x-maind-client-version": opts.bridgeVersion,
5126
+ "x-maind-bridge-version": opts.bridgeVersion
5127
+ };
5128
+ if (opts.deviceId) base["x-maind-device-id"] = opts.deviceId;
5129
+ if (opts.projectKey) base["x-maind-project-key"] = opts.projectKey;
5130
+ const init = await fetch(mcpUrl, {
5131
+ method: "POST",
5132
+ headers: base,
5133
+ signal: controller.signal,
5134
+ body: JSON.stringify({
5135
+ jsonrpc: "2.0",
5136
+ id: "guard-init",
5137
+ method: "initialize",
5138
+ params: {
5139
+ protocolVersion: MCP_PROTOCOL_VERSION,
5140
+ capabilities: {},
5141
+ clientInfo: { name: "maind-mcp-bridge-guard", version: opts.bridgeVersion }
5142
+ }
5143
+ })
5144
+ });
5145
+ const sessionId = init.headers.get("mcp-session-id");
5146
+ await init.text().catch(() => "");
5147
+ if (!init.ok || !sessionId) return null;
5148
+ const withSession = { ...base, "mcp-session-id": sessionId };
5149
+ await fetch(mcpUrl, {
5150
+ method: "POST",
5151
+ headers: withSession,
5152
+ signal: controller.signal,
5153
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
5154
+ }).then((r) => r.text().catch(() => "")).catch(() => "");
5155
+ const call = await fetch(mcpUrl, {
5156
+ method: "POST",
5157
+ headers: withSession,
5158
+ signal: controller.signal,
5159
+ body: JSON.stringify({
5160
+ jsonrpc: "2.0",
5161
+ id: "guard-briefing",
5162
+ method: "tools/call",
5163
+ params: {
5164
+ name: "get_session_briefing",
5165
+ arguments: { tools: ["claude-code"] }
5166
+ }
5167
+ })
5168
+ });
5169
+ if (!call.ok) return null;
5170
+ const contentType = call.headers.get("content-type") ?? "";
5171
+ const raw = contentType.startsWith("text/event-stream") ? await readSseMessage(call) : await call.text();
5172
+ if (raw.trim().length === 0) return null;
5173
+ const message = JSON.parse(raw);
5174
+ if (message.error || message.result?.isError) return null;
5175
+ const text = message.result?.content?.find(
5176
+ (c) => c.type === "text" && typeof c.text === "string"
5177
+ )?.text;
5178
+ return typeof text === "string" && text.trim().length > 0 ? text : null;
5179
+ } catch {
5180
+ return null;
5181
+ } finally {
5182
+ clearTimeout(timer);
5183
+ }
5184
+ }
5185
+ async function readSseMessage(response) {
5186
+ if (!response.body) return "";
5187
+ const reader = response.body.getReader();
5188
+ const decoder = new TextDecoder();
5189
+ let buffer = "";
5190
+ let dataLines = [];
5191
+ let lastPayload = "";
5192
+ const flush = () => {
5193
+ if (dataLines.length === 0) return;
5194
+ const payload = dataLines.join("\n").trim();
5195
+ dataLines = [];
5196
+ if (payload.length > 0) lastPayload = payload;
5197
+ };
5198
+ while (true) {
5199
+ const { value, done } = await reader.read();
5200
+ if (done) break;
5201
+ buffer += decoder.decode(value, { stream: true });
5202
+ let nl;
5203
+ while ((nl = buffer.indexOf("\n")) !== -1) {
5204
+ const rawLine = buffer.slice(0, nl);
5205
+ buffer = buffer.slice(nl + 1);
5206
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
5207
+ if (line === "") {
5208
+ flush();
5209
+ continue;
5210
+ }
5211
+ if (line.startsWith(":")) continue;
5212
+ if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^\s/, ""));
5213
+ }
5214
+ }
5215
+ flush();
5216
+ return lastPayload;
4270
5217
  }
4271
- var SNAPSHOT_EVIDENCE_MAX_AGE_MS;
4272
- var init_connection = __esm({
4273
- "src/session-end/connection.ts"() {
5218
+ var DEFAULT_MCP_URL3, MCP_PROTOCOL_VERSION;
5219
+ var init_mcp_client = __esm({
5220
+ "src/guard/mcp-client.ts"() {
4274
5221
  "use strict";
4275
- SNAPSHOT_EVIDENCE_MAX_AGE_MS = 30 * 6e4;
5222
+ DEFAULT_MCP_URL3 = "https://mcp.maind.dev/mcp";
5223
+ MCP_PROTOCOL_VERSION = "2025-06-18";
4276
5224
  }
4277
5225
  });
4278
5226
 
4279
- // src/session-end/index.ts
4280
- var session_end_exports = {};
4281
- __export(session_end_exports, {
4282
- runOnSessionEnd: () => runOnSessionEnd
5227
+ // src/guard/inject.ts
5228
+ var inject_exports = {};
5229
+ __export(inject_exports, {
5230
+ BRIEFING_CACHE_FILE: () => BRIEFING_CACHE_FILE,
5231
+ formatInjection: () => formatInjection,
5232
+ resolveBriefingInjection: () => resolveBriefingInjection,
5233
+ runGuardInject: () => runGuardInject
4283
5234
  });
4284
- function connectionVerdict(sawMaindCall, nowMs) {
5235
+ import { existsSync as existsSync14 } from "node:fs";
5236
+ import { mkdir as mkdir5, readFile as readFile4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
5237
+ import { dirname as dirname6, join as join20 } from "node:path";
5238
+ async function resolveBriefingInjection(projectKey, apiKey, deps = {}) {
5239
+ const nowMs = deps.nowMs ?? Date.now();
5240
+ const cacheFile = deps.cacheFile ?? BRIEFING_CACHE_FILE;
5241
+ const fetcher = deps.fetcher ?? fetchSessionBriefing;
5242
+ const cache = await readCache(cacheFile);
5243
+ const fresh = cache !== null && nowMs - Date.parse(cache.fetched_at) < CACHE_TTL_MS && cache.project_key === projectKey;
5244
+ if (fresh) return { text: cache.text, via: "cache" };
5245
+ const fetched = await fetcher({
5246
+ apiKey,
5247
+ deviceId: safeDeviceId(),
5248
+ projectKey,
5249
+ bridgeVersion: BRIDGE_VERSION,
5250
+ timeoutMs: FETCH_BUDGET_MS
5251
+ });
5252
+ if (fetched !== null) {
5253
+ await writeCache(cacheFile, {
5254
+ fetched_at: new Date(nowMs).toISOString(),
5255
+ project_key: projectKey,
5256
+ text: fetched
5257
+ });
5258
+ return { text: fetched, via: "fetch" };
5259
+ }
5260
+ if (cache !== null) return { text: cache.text, via: "stale-cache" };
5261
+ return { text: null, via: "none" };
5262
+ }
5263
+ async function runGuardInject() {
4285
5264
  try {
5265
+ const guard = resolveGuardConfig();
5266
+ if (guard.mode === "off") return 0;
5267
+ const input = await readHookInput();
5268
+ const sessionId = typeof input.session_id === "string" && input.session_id.trim().length > 0 ? input.session_id.trim() : null;
5269
+ if (sessionId === null) return 0;
5270
+ await sweepOldGuardSessions();
5271
+ const source = typeof input.source === "string" ? input.source : "startup";
5272
+ if (source === "resume" || source === "compact") {
5273
+ const state2 = await loadGuardSession(sessionId);
5274
+ await saveGuardSession(sessionId, { ...state2, carryover: true });
5275
+ return 0;
5276
+ }
5277
+ const apiKey = readApiKey();
5278
+ if (apiKey === null) return 0;
5279
+ const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
4286
5280
  const projectKey = computeProjectKey();
4287
- const presenceUsable = projectKey !== null && !autoAnnounceDisabled(process.env, readBridgeConfig());
4288
- let ownSnapshotAgeMs = null;
4289
- if (projectKey !== null) {
4290
- const own = selectOwnSnapshot(readSnapshots(projectKey), {
4291
- grandparentPid: grandparentPid(),
4292
- cwd: process.cwd()
5281
+ const result = await resolveBriefingInjection(projectKey, apiKey);
5282
+ const state = await loadGuardSession(sessionId);
5283
+ if (result.text === null) {
5284
+ await saveGuardSession(sessionId, { ...state, inject_failed: true });
5285
+ await appendGuardEvent({
5286
+ event: "inject_fail",
5287
+ session_id: sessionId,
5288
+ cwd,
5289
+ project_key: projectKey ?? void 0
4293
5290
  });
4294
- if (own) {
4295
- const written = Date.parse(own.snap.written_at);
4296
- ownSnapshotAgeMs = Number.isFinite(written) ? Math.max(0, nowMs - written) : null;
4297
- }
5291
+ process.stderr.write(
5292
+ "[maind] guard: briefing fetch failed and no cache \u2014 session starts unbriefed; the model should call get_session_briefing itself.\n"
5293
+ );
5294
+ return 0;
4298
5295
  }
4299
- return resolveConnection({ ownSnapshotAgeMs, sawMaindCall, presenceUsable });
5296
+ process.stdout.write(formatInjection(result.text, result.via));
5297
+ await saveGuardSession(sessionId, { ...state, injected: true });
5298
+ await appendGuardEvent({
5299
+ event: "inject_ok",
5300
+ session_id: sessionId,
5301
+ cwd,
5302
+ project_key: projectKey ?? void 0,
5303
+ detail: result.via
5304
+ });
5305
+ return 0;
4300
5306
  } catch {
4301
- return sawMaindCall ? "connected" : "unknown";
5307
+ return 0;
4302
5308
  }
4303
5309
  }
4304
- function presenceSessionId() {
4305
- const raw = (process.env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
4306
- 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;
5310
+ function formatInjection(text, via) {
5311
+ const staleNote = via === "stale-cache" ? " \u2014 served from local cache, server unreachable" : "";
5312
+ let body = text;
5313
+ if (Buffer.byteLength(body, "utf8") > MAX_INJECT_BYTES) {
5314
+ body = body.slice(0, MAX_INJECT_BYTES) + "\n\u2026 [maind guard: briefing truncated at 10KB]";
5315
+ }
5316
+ return `[maind guard] Session briefing, injected deterministically (ADR-284)${staleNote} \u2014 the session-start get_session_briefing consultation is satisfied by this block:
5317
+
5318
+ ` + body + "\n";
4307
5319
  }
4308
- async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
4309
- const post = fetch(INGEST_ENDPOINT, {
4310
- method: "POST",
4311
- headers: {
4312
- "content-type": "application/json",
4313
- authorization: `Bearer ${apiKey}`,
4314
- "x-maind-device-id": deviceId,
4315
- "x-maind-bridge-version": BRIDGE_VERSION
4316
- },
4317
- body: JSON.stringify(body)
4318
- }).then(() => void 0).catch(() => void 0);
4319
- const timeout = new Promise((resolve3) => setTimeout(resolve3, timeoutMs));
4320
- await Promise.race([post, timeout]);
5320
+ async function readCache(file) {
5321
+ try {
5322
+ if (!existsSync14(file)) return null;
5323
+ const parsed = JSON.parse(await readFile4(file, "utf8"));
5324
+ if (typeof parsed.fetched_at !== "string" || typeof parsed.text !== "string") return null;
5325
+ if (Number.isNaN(Date.parse(parsed.fetched_at))) return null;
5326
+ return {
5327
+ fetched_at: parsed.fetched_at,
5328
+ project_key: typeof parsed.project_key === "string" ? parsed.project_key : null,
5329
+ text: parsed.text
5330
+ };
5331
+ } catch {
5332
+ return null;
5333
+ }
4321
5334
  }
4322
- async function runOnSessionEnd() {
4323
- const apiKey = readApiKey();
4324
- if (!apiKey) return 0;
4325
- const input = await readHookInput();
4326
- const sessionId = typeof input.session_id === "string" && input.session_id ? input.session_id : null;
4327
- const transcriptPath = transcriptPathOf(input);
4328
- if (transcriptPath) {
4329
- try {
4330
- const [analytics, span] = await Promise.all([
4331
- analyzeSession(transcriptPath),
4332
- analyzeSpan(transcriptPath)
4333
- ]);
4334
- if (sessionId) {
4335
- analytics.session_id = sessionId;
4336
- span.session_id = sessionId;
4337
- }
4338
- analytics.maind_connected = connectionVerdict(
4339
- analytics.maind_connected === "connected",
4340
- Date.now()
4341
- );
4342
- if (analytics.session_id) {
4343
- const body = ingestBody(analytics, span, {
4344
- client_session_id: presenceSessionId(),
4345
- client: "claude-code"
4346
- });
4347
- await postWithTimeout(apiKey, ensureDeviceId(), body, 1500);
4348
- }
4349
- } catch (err) {
4350
- process.stderr.write(
4351
- `[maind-mcp-bridge] session-end ingest failed: ${err instanceof Error ? err.message : String(err)}
4352
- `
4353
- );
4354
- }
5335
+ async function writeCache(file, cache) {
5336
+ try {
5337
+ await mkdir5(dirname6(file), { recursive: true, mode: 448 });
5338
+ const tmp = `${file}.tmp`;
5339
+ await writeFile5(tmp, JSON.stringify(cache, null, 2), { mode: 384 });
5340
+ await rename4(tmp, file);
5341
+ } catch {
4355
5342
  }
4356
- await runSessionEndMetrics(sessionId);
4357
- return 0;
4358
5343
  }
4359
- var INGEST_ENDPOINT;
4360
- var init_session_end = __esm({
4361
- "src/session-end/index.ts"() {
5344
+ function safeDeviceId() {
5345
+ try {
5346
+ return ensureDeviceId();
5347
+ } catch {
5348
+ return null;
5349
+ }
5350
+ }
5351
+ var BRIEFING_CACHE_FILE, CACHE_TTL_MS, FETCH_BUDGET_MS, MAX_INJECT_BYTES;
5352
+ var init_inject = __esm({
5353
+ "src/guard/inject.ts"() {
4362
5354
  "use strict";
4363
- init_dist();
4364
- init_bridge_config();
4365
5355
  init_device_id();
4366
- init_api();
4367
- init_edit_guard();
4368
5356
  init_hook_input();
4369
- init_hooks2();
4370
- init_presence();
4371
- init_presence_snapshot();
4372
5357
  init_project_key();
4373
5358
  init_version();
4374
- init_connection();
4375
- INGEST_ENDPOINT = DEFAULT_INGEST_ENDPOINT;
5359
+ init_config();
5360
+ init_log();
5361
+ init_session_file();
5362
+ init_mcp_client();
5363
+ BRIEFING_CACHE_FILE = join20(GUARD_DIR, "briefing-cache.json");
5364
+ CACHE_TTL_MS = 12 * 60 * 60 * 1e3;
5365
+ FETCH_BUDGET_MS = 3e3;
5366
+ MAX_INJECT_BYTES = 10 * 1024;
5367
+ }
5368
+ });
5369
+
5370
+ // src/guard/gate.ts
5371
+ var gate_exports = {};
5372
+ __export(gate_exports, {
5373
+ decideGate: () => decideGate,
5374
+ runGuardGate: () => runGuardGate
5375
+ });
5376
+ function decideGate(input) {
5377
+ const { mode, session } = input;
5378
+ if (mode === "off") return { kind: "allow" };
5379
+ const consulted = session.injected === true || session.carryover === true || typeof session.override_reason === "string" || input.consultations > 0;
5380
+ if (consulted) return { kind: "allow" };
5381
+ if (mode === "warn") {
5382
+ if (session.warned === true) return { kind: "allow" };
5383
+ return { kind: "warn", context: warnText(session) };
5384
+ }
5385
+ if ((session.deny_count ?? 0) >= DENY_CAP) {
5386
+ if (session.warned === true) return { kind: "allow" };
5387
+ return {
5388
+ kind: "warn",
5389
+ context: "[maind guard] Block-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. " + warnText(session)
5390
+ };
5391
+ }
5392
+ return { kind: "deny", reason: denyText(input.sessionId, session) };
5393
+ }
5394
+ function warnText(session) {
5395
+ const injectNote = session.inject_failed === true ? "The automatic briefing injection FAILED for this session (server unreachable or not paired) \u2014 call get_session_briefing yourself to close the gap." : "No maind consultation has happened in this session yet.";
5396
+ return `[maind guard | warn] ${injectNote} The project mandates session-start consultation (proc/maind-consultation-triggers): call get_session_briefing, or search_lessons with the task's key terms, before substantive edits. This reminder appears once per session.`;
5397
+ }
5398
+ function denyText(sessionId, session) {
5399
+ const injectNote = session.inject_failed === true ? "the automatic briefing injection failed for this session, so the consultation is still open" : "no maind consultation has happened in this session";
5400
+ return `[maind guard | block] Edit denied \u2014 ${injectNote} (mandated by proc/maind-consultation-triggers). Two exits:
5401
+ 1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
5402
+ 2. Override (logged): run \`maind-mcp-bridge guard skip --session ${sessionId} --reason "<why consultation is unnecessary here>"\` and retry.
5403
+ After ${DENY_CAP} denies this gate downgrades itself to warn.`;
5404
+ }
5405
+ async function runGuardGate() {
5406
+ try {
5407
+ const guard = resolveGuardConfig();
5408
+ if (guard.mode === "off") return 0;
5409
+ const input = await readHookInput();
5410
+ const tool = (input.tool_name ?? "").toString();
5411
+ if (tool !== "Edit" && tool !== "Write") return 0;
5412
+ const sessionId = typeof input.session_id === "string" && input.session_id.trim().length > 0 ? input.session_id.trim() : null;
5413
+ if (sessionId === null) return 0;
5414
+ const session = await loadGuardSession(sessionId);
5415
+ const core = (await loadState()).sessions[sessionId];
5416
+ const consultations = (core?.consultations ?? 0) + (core?.lessons_consulted ?? 0);
5417
+ const decision = decideGate({ mode: guard.mode, session, consultations, sessionId });
5418
+ const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
5419
+ const projectKey = computeProjectKey() ?? void 0;
5420
+ if (decision.kind === "deny") {
5421
+ process.stdout.write(denyPayload(decision.reason));
5422
+ await saveGuardSession(sessionId, {
5423
+ ...session,
5424
+ deny_count: (session.deny_count ?? 0) + 1
5425
+ });
5426
+ await appendGuardEvent({
5427
+ event: "deny",
5428
+ session_id: sessionId,
5429
+ cwd,
5430
+ project_key: projectKey
5431
+ });
5432
+ return 0;
5433
+ }
5434
+ if (decision.kind === "warn") {
5435
+ process.stdout.write(advisoryPayload(decision.context));
5436
+ await saveGuardSession(sessionId, {
5437
+ ...session,
5438
+ warned: true,
5439
+ edits_seen: (session.edits_seen ?? 0) + 1
5440
+ });
5441
+ await appendGuardEvent({
5442
+ event: "warn",
5443
+ session_id: sessionId,
5444
+ cwd,
5445
+ project_key: projectKey
5446
+ });
5447
+ return 0;
5448
+ }
5449
+ await saveGuardSession(sessionId, {
5450
+ ...session,
5451
+ edits_seen: (session.edits_seen ?? 0) + 1
5452
+ });
5453
+ return 0;
5454
+ } catch {
5455
+ return 0;
5456
+ }
5457
+ }
5458
+ var DENY_CAP;
5459
+ var init_gate = __esm({
5460
+ "src/guard/gate.ts"() {
5461
+ "use strict";
5462
+ init_hook_input();
5463
+ init_payloads();
5464
+ init_state();
5465
+ init_project_key();
5466
+ init_config();
5467
+ init_log();
5468
+ init_session_file();
5469
+ DENY_CAP = 3;
5470
+ }
5471
+ });
5472
+
5473
+ // src/guard/stop.ts
5474
+ var stop_exports = {};
5475
+ __export(stop_exports, {
5476
+ decideStopGate: () => decideStopGate,
5477
+ runGuardStop: () => runGuardStop
5478
+ });
5479
+ function decideStopGate(input) {
5480
+ return {
5481
+ block: input.enabled && input.editsSeen > 0 && input.reviewsRan === 0 && !input.stopHookActive && !input.alreadyBlocked
5482
+ };
5483
+ }
5484
+ async function runGuardStop() {
5485
+ try {
5486
+ const guard = resolveGuardConfig();
5487
+ if (guard.mode === "off" || !guard.stopGate) return 0;
5488
+ const input = await readHookInput();
5489
+ const sessionId = typeof input.session_id === "string" && input.session_id.trim().length > 0 ? input.session_id.trim() : null;
5490
+ if (sessionId === null) return 0;
5491
+ const session = await loadGuardSession(sessionId);
5492
+ const core = (await loadState()).sessions[sessionId];
5493
+ const decision = decideStopGate({
5494
+ enabled: true,
5495
+ editsSeen: session.edits_seen ?? 0,
5496
+ reviewsRan: core?.reviews_ran ?? 0,
5497
+ stopHookActive: input.stop_hook_active === true,
5498
+ alreadyBlocked: session.stop_blocked === true
5499
+ });
5500
+ if (!decision.block) return 0;
5501
+ process.stdout.write(JSON.stringify({ decision: "block", reason: STOP_REASON }));
5502
+ await saveGuardSession(sessionId, { ...session, stop_blocked: true });
5503
+ await appendGuardEvent({ event: "stop_block", session_id: sessionId });
5504
+ return 0;
5505
+ } catch {
5506
+ return 0;
5507
+ }
5508
+ }
5509
+ var STOP_REASON;
5510
+ var init_stop = __esm({
5511
+ "src/guard/stop.ts"() {
5512
+ "use strict";
5513
+ init_hook_input();
5514
+ init_state();
5515
+ init_config();
5516
+ init_log();
5517
+ init_session_file();
5518
+ STOP_REASON = "[maind guard] Stop gate (strict, opt-in): this session edited files but review_changes never ran. Run the review over the edit batches \u2014 codebase_review_changes, then review_changes with its review_args (or `maind review` from the CLI) \u2014 report the findings, then finish. This gate blocks only once.";
4376
5519
  }
4377
5520
  });
4378
5521
 
@@ -5519,109 +6662,46 @@ function getClientTargets(ctx) {
5519
6662
  {
5520
6663
  key: "windsurf",
5521
6664
  label: "Windsurf (~/.codeium/windsurf/mcp_config.json)",
5522
- clientFamilyEnv: "windsurf",
5523
- scope: "user",
5524
- path: path3.join(ctx.homeDir, ".codeium", "windsurf", "mcp_config.json"),
5525
- kind: "json"
5526
- },
5527
- {
5528
- key: "codex-cli",
5529
- label: "Codex CLI (~/.codex/config.toml)",
5530
- clientFamilyEnv: "codex",
5531
- scope: "user",
5532
- path: path3.join(ctx.homeDir, ".codex", "config.toml"),
5533
- kind: "toml"
5534
- }
5535
- ];
5536
- return targets;
5537
- }
5538
- function filterTargetsByFamily(targets, family) {
5539
- if (family === null) return targets;
5540
- return targets.filter((t) => t.clientFamilyEnv === family);
5541
- }
5542
- function makeDefaultContext(args) {
5543
- return {
5544
- projectRoot: args.projectRoot,
5545
- homeDir: args.homeDir,
5546
- platform: args.platform,
5547
- xdgConfigHome: nonEmpty(args.env.XDG_CONFIG_HOME),
5548
- appData: nonEmpty(args.env.APPDATA)
5549
- };
5550
- }
5551
- function nonEmpty(v) {
5552
- if (v === void 0) return null;
5553
- const trimmed = v.trim();
5554
- return trimmed.length > 0 ? trimmed : null;
5555
- }
5556
-
5557
- // src/install/index.ts
5558
- init_bridge_entry();
5559
-
5560
- // src/install/atomic-write.ts
5561
- import * as fs2 from "node:fs/promises";
5562
- import * as path4 from "node:path";
5563
- async function readFileSafe(filepath) {
5564
- try {
5565
- return await fs2.readFile(filepath, "utf8");
5566
- } catch (err) {
5567
- if (isNoEnt(err)) return null;
5568
- throw err;
5569
- }
5570
- }
5571
- async function ensureDir2(dir) {
5572
- await fs2.mkdir(dir, { recursive: true });
5573
- }
5574
- async function atomicWriteFile(filepath, content, mode) {
5575
- const dir = path4.dirname(filepath);
5576
- await ensureDir2(dir);
5577
- const tmp = path4.join(
5578
- dir,
5579
- `.maind-install-${process.pid}-${Date.now()}.tmp`
5580
- );
5581
- await fs2.writeFile(tmp, content, { encoding: "utf8", mode });
5582
- try {
5583
- await fs2.rename(tmp, filepath);
5584
- } catch (err) {
5585
- if (isWindowsRenameFailure(err)) {
5586
- try {
5587
- await fs2.copyFile(tmp, filepath);
5588
- await fs2.unlink(tmp).catch(() => {
5589
- });
5590
- if (mode !== void 0) {
5591
- await fs2.chmod(filepath, mode).catch(() => {
5592
- });
5593
- }
5594
- return;
5595
- } catch (fallbackErr) {
5596
- await fs2.unlink(tmp).catch(() => {
5597
- });
5598
- throw fallbackErr;
5599
- }
6665
+ clientFamilyEnv: "windsurf",
6666
+ scope: "user",
6667
+ path: path3.join(ctx.homeDir, ".codeium", "windsurf", "mcp_config.json"),
6668
+ kind: "json"
6669
+ },
6670
+ {
6671
+ key: "codex-cli",
6672
+ label: "Codex CLI (~/.codex/config.toml)",
6673
+ clientFamilyEnv: "codex",
6674
+ scope: "user",
6675
+ path: path3.join(ctx.homeDir, ".codex", "config.toml"),
6676
+ kind: "toml"
5600
6677
  }
5601
- await fs2.unlink(tmp).catch(() => {
5602
- });
5603
- throw err;
5604
- }
5605
- }
5606
- async function hasLinePrefix(filepath, prefix) {
5607
- const content = await readFileSafe(filepath);
5608
- if (content === null) return false;
5609
- const lines2 = content.split(/\r?\n/);
5610
- return lines2.some((l) => l.startsWith(prefix));
6678
+ ];
6679
+ return targets;
5611
6680
  }
5612
- function isNoEnt(err) {
5613
- return isNodeError(err) && err.code === "ENOENT";
6681
+ function filterTargetsByFamily(targets, family) {
6682
+ if (family === null) return targets;
6683
+ return targets.filter((t) => t.clientFamilyEnv === family);
5614
6684
  }
5615
- function isWindowsRenameFailure(err) {
5616
- if (!isNodeError(err)) return false;
5617
- if (process.platform !== "win32") return false;
5618
- return err.code === "EEXIST" || err.code === "EPERM" || err.code === "EACCES";
6685
+ function makeDefaultContext(args) {
6686
+ return {
6687
+ projectRoot: args.projectRoot,
6688
+ homeDir: args.homeDir,
6689
+ platform: args.platform,
6690
+ xdgConfigHome: nonEmpty(args.env.XDG_CONFIG_HOME),
6691
+ appData: nonEmpty(args.env.APPDATA)
6692
+ };
5619
6693
  }
5620
- function isNodeError(err) {
5621
- return typeof err === "object" && err !== null && "code" in err;
6694
+ function nonEmpty(v) {
6695
+ if (v === void 0) return null;
6696
+ const trimmed = v.trim();
6697
+ return trimmed.length > 0 ? trimmed : null;
5622
6698
  }
5623
6699
 
6700
+ // src/install/index.ts
6701
+ init_bridge_entry();
6702
+
5624
6703
  // src/install/json-merge.ts
6704
+ init_atomic_write();
5625
6705
  var MAIND_SERVER_KEY = "maind";
5626
6706
  async function mergeJsonConfig(target, serverEntry, dryRun = false) {
5627
6707
  if (target.kind !== "json") {
@@ -5752,6 +6832,7 @@ function failed(target, phase, err) {
5752
6832
  }
5753
6833
 
5754
6834
  // src/install/toml-merge.ts
6835
+ init_atomic_write();
5755
6836
  import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
5756
6837
  async function mergeTomlConfig(target, serverEntry, dryRun = false) {
5757
6838
  if (target.kind !== "toml") {
@@ -6578,6 +7659,7 @@ const tools = await mcp.getTools();
6578
7659
  var SNIPPET_TEMPLATES = buildSnippetTemplates(DEFAULT_MCP_ENDPOINT);
6579
7660
 
6580
7661
  // src/install/preamble.ts
7662
+ init_atomic_write();
6581
7663
  var PREAMBLE_HEADER_PREFIX = "## maind MCP integration";
6582
7664
  function buildPreambleTargets(ctx) {
6583
7665
  return [
@@ -6670,211 +7752,12 @@ function ensureTrailingBlankLine(content) {
6670
7752
  return content + "\n\n";
6671
7753
  }
6672
7754
 
6673
- // src/install/hook-merge.ts
6674
- import * as path7 from "node:path";
6675
- import * as readline2 from "node:readline";
6676
- init_bridge_entry();
6677
- init_hook_wiring();
6678
- var REMINDER_FILE_REL = ".claude/maind-session-start-reminder.md";
6679
- async function mergeClaudeHook(opts, spec) {
6680
- const settingsPath = path7.join(opts.homeDir, ".claude", "settings.json");
6681
- const targetKey = spec.targetKey;
6682
- if (opts.skip) {
6683
- return { target: targetKey, action: "skip", status: "skipped", detail: "--no-hook" };
6684
- }
6685
- let raw;
6686
- try {
6687
- raw = await readFileSafe(settingsPath);
6688
- } catch (err) {
6689
- return { target: targetKey, action: "merge", status: "failed", detail: `read: ${errMessage(err)}` };
6690
- }
6691
- let settings;
6692
- let action = "create";
6693
- if (raw === null || raw.trim().length === 0) {
6694
- settings = {};
6695
- } else {
6696
- action = "merge";
6697
- try {
6698
- const parsed = JSON.parse(raw);
6699
- if (!isObject4(parsed)) {
6700
- return {
6701
- target: targetKey,
6702
- action: "merge",
6703
- status: "failed",
6704
- detail: "existing settings.json is not a JSON object"
6705
- };
6706
- }
6707
- settings = parsed;
6708
- } catch (err) {
6709
- return { target: targetKey, action: "merge", status: "failed", detail: `parse: ${errMessage(err)}` };
6710
- }
6711
- }
6712
- const existing = findExistingHookCommand(settings, spec.event, spec.matchPattern);
6713
- if (existing !== null) {
6714
- return { target: targetKey, action: "skip", status: "skipped", detail: spec.skipDetail(existing) };
6715
- }
6716
- if (!opts.full) {
6717
- if (!opts.isInteractive) {
6718
- return {
6719
- target: targetKey,
6720
- action: "skip",
6721
- status: "skipped",
6722
- detail: "consent-required: pass --full to write the hook non-interactively"
6723
- };
6724
- }
6725
- if (opts.dryRun) {
6726
- return {
6727
- target: targetKey,
6728
- action: "merge",
6729
- status: action === "create" ? "would-create" : "would-merge",
6730
- detail: `${settingsPath} (would prompt for consent in real run)`
6731
- };
6732
- }
6733
- const consent = await promptYesNo(
6734
- opts.out,
6735
- `
6736
- Merge a ${spec.event} hook into ${settingsPath}?
6737
- ${spec.consentDescription}
6738
- [Y/n]: `
6739
- );
6740
- if (!consent) {
6741
- return { target: targetKey, action: "skip", status: "skipped", detail: "user declined" };
6742
- }
6743
- }
6744
- const newHookGroup = {
6745
- ...spec.matcher === void 0 ? {} : { matcher: spec.matcher },
6746
- hooks: [{ type: "command", command: spec.command, timeout: spec.timeout }]
6747
- };
6748
- const existingGroups = settings.hooks?.[spec.event] ?? [];
6749
- const nextSettings = {
6750
- ...settings,
6751
- hooks: {
6752
- ...settings.hooks ?? {},
6753
- [spec.event]: [...existingGroups, newHookGroup]
6754
- }
6755
- };
6756
- const nextRaw = JSON.stringify(nextSettings, null, 2) + "\n";
6757
- if (opts.dryRun) {
6758
- return {
6759
- target: targetKey,
6760
- action: action === "create" ? "write" : "merge",
6761
- status: action === "create" ? "would-create" : "would-merge",
6762
- detail: settingsPath
6763
- };
6764
- }
6765
- try {
6766
- await atomicWriteFile(settingsPath, nextRaw, 384);
6767
- } catch (err) {
6768
- return { target: targetKey, action: "merge", status: "failed", detail: `write: ${errMessage(err)}` };
6769
- }
6770
- return {
6771
- target: targetKey,
6772
- action: action === "create" ? "write" : "merge",
6773
- status: action === "create" ? "created" : "merged",
6774
- detail: settingsPath
6775
- };
6776
- }
6777
- async function mergeSessionStartHook(opts) {
6778
- const reminderPath = path7.join(opts.homeDir, REMINDER_FILE_REL);
6779
- return mergeClaudeHook(opts, {
6780
- event: "SessionStart",
6781
- command: `cat ${reminderPath}`,
6782
- timeout: 5,
6783
- matchPattern: /maind-session-start-reminder\.md/,
6784
- targetKey: "hook:~/.claude/settings.json",
6785
- skipDetail: () => "SessionStart hook already references the reminder file",
6786
- consentDescription: `It 'cat's ${REMINDER_FILE_REL} into every new Claude Code session.`
6787
- });
6788
- }
6789
- function targetKeyFor(hook) {
6790
- return `hook(${hook.subcommand}):~/.claude/settings.json`;
6791
- }
6792
- async function mergeSubcommandHook(opts, spec) {
6793
- const launch = opts.launch ?? resolveBridgeLaunch({
6794
- entryPath: currentBridgeEntry(),
6795
- nodePath: process.execPath,
6796
- extraArgs: [spec.subcommand],
6797
- isElectron: process.versions.electron !== void 0
6798
- });
6799
- const command = launchToShellCommand(launch);
6800
- return mergeClaudeHook(opts, {
6801
- event: spec.event,
6802
- command,
6803
- timeout: spec.timeout,
6804
- matcher: spec.matcher,
6805
- matchPattern: new RegExp(spec.subcommand),
6806
- targetKey: targetKeyFor(spec),
6807
- skipDetail: (existing) => {
6808
- const wired = `${spec.label} already runs maind ${spec.subcommand}`;
6809
- if (isLegacyHookForm(existing)) {
6810
- return `${wired}, but via the retired @maind/claude-code-hook \u2014 the bridge now owns that subcommand and that package is not published. Replace its command with: ${command}`;
6811
- }
6812
- if (isNpxForm(existing)) {
6813
- return `${wired}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${command}`;
6814
- }
6815
- return wired;
6816
- },
6817
- consentDescription: spec.consentDescription
6818
- });
6819
- }
6820
- function managed(subcommand) {
6821
- const hook = MANAGED_SUBCOMMAND_HOOKS.find((h) => h.subcommand === subcommand);
6822
- if (!hook) throw new Error(`no managed hook for subcommand ${subcommand}`);
6823
- return hook;
6824
- }
6825
- async function mergeStopHook(opts) {
6826
- return mergeSubcommandHook(opts, managed("on-session-end"));
6827
- }
6828
- async function mergeSessionStartMetricsHook(opts) {
6829
- return mergeSubcommandHook(opts, managed("on-session-start"));
6830
- }
6831
- async function mergeToolUseHook(opts) {
6832
- return mergeSubcommandHook(opts, managed("on-tool-use"));
6833
- }
6834
- async function mergeFileWriteHook(opts) {
6835
- return mergeSubcommandHook(opts, managed("on-file-write"));
6836
- }
6837
- async function mergeFileEditHook(opts) {
6838
- return mergeSubcommandHook(opts, managed("on-file-edit"));
6839
- }
6840
- function findExistingHookCommand(settings, event, pattern) {
6841
- const groups = settings.hooks?.[event];
6842
- if (!Array.isArray(groups)) return null;
6843
- for (const group of groups) {
6844
- if (!isObject4(group)) continue;
6845
- const hooks = group.hooks;
6846
- if (!Array.isArray(hooks)) continue;
6847
- for (const hook of hooks) {
6848
- if (!isObject4(hook)) continue;
6849
- const cmd = hook.command;
6850
- if (typeof cmd === "string" && pattern.test(cmd)) return cmd;
6851
- }
6852
- }
6853
- return null;
6854
- }
6855
- async function promptYesNo(out2, prompt) {
6856
- out2.write(prompt);
6857
- const rl = readline2.createInterface({
6858
- input: process.stdin,
6859
- output: out2,
6860
- terminal: true
6861
- });
6862
- const answer = await new Promise((resolve3) => {
6863
- rl.question("", (input) => resolve3(input.trim().toLowerCase()));
6864
- });
6865
- rl.close();
6866
- if (answer === "" || answer === "y" || answer === "yes") return true;
6867
- return false;
6868
- }
6869
- function isObject4(v) {
6870
- return typeof v === "object" && v !== null && !Array.isArray(v);
6871
- }
6872
- function errMessage(err) {
6873
- return err instanceof Error ? err.message : String(err);
6874
- }
7755
+ // src/install/index.ts
7756
+ init_hook_merge();
6875
7757
 
6876
7758
  // src/install/working-paths-consent.ts
6877
7759
  init_bridge_config();
7760
+ init_atomic_write();
6878
7761
  import * as readline3 from "node:readline";
6879
7762
  var TARGET_KEY = "config:auto_working_paths";
6880
7763
  var WORKING_PATHS_CONSENT_PROMPT = '\nEnable presence enrichment (auto working_paths)?\nWith this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your\nlocally changed files (from `git status`, max 8, re-derived at most every 45s)\nin its presence announce \u2014 so your own parallel sessions can warn each other\nbefore editing the same area. Directory names only: never file contents, never\nabsolute paths. Server-side these paths are account-private (org members never\nsee them) and revocable any time on the dashboard consent page or via\n{"auto_working_paths": false} in the bridge config.\n[y/N]: ';
@@ -8599,18 +9482,18 @@ async function dispatchLocalTool(engine, name, args) {
8599
9482
  dirs: Array.isArray(args.dirs) ? args.dirs.filter((d) => typeof d === "string") : void 0,
8600
9483
  minFiles
8601
9484
  });
8602
- const open = report.findings.filter((f) => f.status === "open");
9485
+ const open2 = report.findings.filter((f) => f.status === "open");
8603
9486
  const preexisting = report.findings.filter(
8604
9487
  (f) => f.status === "info"
8605
9488
  );
8606
9489
  return {
8607
9490
  ok: report.ok,
8608
- open_count: open.length,
9491
+ open_count: open2.length,
8609
9492
  preexisting_count: preexisting.length,
8610
9493
  // Nur die blockierenden Findings vollständig; der Bestand als Zahl plus
8611
9494
  // Nummern, damit ein Repo mit alten Doppelungen die Antwort nicht flutet
8612
9495
  // und der Agent das Handlungsrelevante zuerst liest.
8613
- findings: open,
9496
+ findings: open2,
8614
9497
  preexisting: preexisting.map(
8615
9498
  (f) => `${f.namespace.prefix}${f.number}`
8616
9499
  ),
@@ -8620,7 +9503,7 @@ async function dispatchLocalTool(engine, name, args) {
8620
9503
  file_count: ns.fileCount
8621
9504
  })),
8622
9505
  skipped: report.facts.skipped,
8623
- 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.`
9506
+ 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.`
8624
9507
  };
8625
9508
  }
8626
9509
  case "codebase_search": {
@@ -9048,6 +9931,23 @@ async function main() {
9048
9931
  const { runOnSessionEnd: runOnSessionEnd2 } = await Promise.resolve().then(() => (init_session_end(), session_end_exports));
9049
9932
  process.exit(await runOnSessionEnd2());
9050
9933
  }
9934
+ if (firstPositional === "guard") {
9935
+ const guardIndex = process.argv.indexOf("guard");
9936
+ const { runGuard: runGuard2 } = await Promise.resolve().then(() => (init_cli(), cli_exports));
9937
+ process.exit(await runGuard2(process.argv.slice(guardIndex + 1)));
9938
+ }
9939
+ if (firstPositional === "guard-inject") {
9940
+ const { runGuardInject: runGuardInject2 } = await Promise.resolve().then(() => (init_inject(), inject_exports));
9941
+ process.exit(await runGuardInject2());
9942
+ }
9943
+ if (firstPositional === "guard-gate") {
9944
+ const { runGuardGate: runGuardGate2 } = await Promise.resolve().then(() => (init_gate(), gate_exports));
9945
+ process.exit(await runGuardGate2());
9946
+ }
9947
+ if (firstPositional === "guard-stop") {
9948
+ const { runGuardStop: runGuardStop2 } = await Promise.resolve().then(() => (init_stop(), stop_exports));
9949
+ process.exit(await runGuardStop2());
9950
+ }
9051
9951
  if (firstPositional !== void 0 && isHookSubcommand(firstPositional)) {
9052
9952
  const hooks = await Promise.resolve().then(() => (init_hooks2(), hooks_exports));
9053
9953
  const run = {
@@ -9179,6 +10079,13 @@ function printHelp() {
9179
10079
  " flush post queued Tier-3 metrics now",
9180
10080
  " status show pairing, queued metrics and active thresholds",
9181
10081
  "",
10082
+ "Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:",
10083
+ " guard install wire the guard hook pack (consent per hook) + set mode",
10084
+ " guard status mode, guard-hook wiring, local enforcement-event counts",
10085
+ " guard mode <warn|block> | guard off | guard stop-gate <on|off>",
10086
+ ' guard skip --session <id> --reason "\u2026" logged override (block-gate exit)',
10087
+ " (hook subcommands, wired by `guard install`: guard-inject, guard-gate, guard-stop)",
10088
+ "",
9182
10089
  "Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent",
9183
10090
  "Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.",
9184
10091
  "",