@maind-dev/mcp-bridge 0.26.0 → 0.27.1
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 +1418 -503
- package/build/meta.json +1 -1
- package/package.json +1 -1
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.
|
|
205
|
+
BRIDGE_VERSION = "0.27.1";
|
|
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
|
|
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/
|
|
495
|
-
import
|
|
496
|
-
import
|
|
497
|
-
function
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
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
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
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
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
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 (
|
|
514
|
-
|
|
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
|
-
|
|
517
|
-
|
|
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
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
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
|
-
|
|
532
|
-
|
|
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
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
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
|
|
558
|
-
|
|
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
|
-
|
|
561
|
-
|
|
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
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
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
|
+
guard_signals: parsed.guard_signals
|
|
3739
4073
|
};
|
|
3740
4074
|
} catch (err) {
|
|
3741
4075
|
process.stderr.write(
|
|
@@ -3773,8 +4107,10 @@ 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,
|
|
4113
|
+
recordGuardSignals: () => recordGuardSignals,
|
|
3778
4114
|
runFlush: () => runFlush,
|
|
3779
4115
|
runHookStatus: () => runHookStatus,
|
|
3780
4116
|
runOnFileEdit: () => runOnFileEdit,
|
|
@@ -3789,6 +4125,61 @@ import { existsSync as existsSync10, readFileSync as readFileSync8, realpathSync
|
|
|
3789
4125
|
import { writeFile as writeFile3 } from "node:fs/promises";
|
|
3790
4126
|
import { homedir as homedir6 } from "node:os";
|
|
3791
4127
|
import { basename, dirname as dirname5, isAbsolute as isAbsolute3, join as join16, relative as relative2 } from "node:path";
|
|
4128
|
+
function recordGuardSignals(state, sessionId, toolName, nowMs = Date.now()) {
|
|
4129
|
+
if (!toolName.includes("maind")) return;
|
|
4130
|
+
const consulted = toolName.includes("search_lessons") || toolName.includes("get_session_briefing") || toolName.includes("get_lesson") || toolName.includes("get_conventions") || toolName.includes("activate_skill") || toolName.includes("suggest_skills") || toolName.includes("codebase_change_briefing");
|
|
4131
|
+
const reviewed = toolName.includes("review_changes");
|
|
4132
|
+
if (!consulted && !reviewed) return;
|
|
4133
|
+
const signals = state.guard_signals ?? {};
|
|
4134
|
+
const entry = signals[sessionId] ?? {};
|
|
4135
|
+
const ts = new Date(nowMs).toISOString();
|
|
4136
|
+
if (consulted) entry.consulted_at = ts;
|
|
4137
|
+
if (reviewed) entry.reviewed_at = ts;
|
|
4138
|
+
signals[sessionId] = entry;
|
|
4139
|
+
state.guard_signals = signals;
|
|
4140
|
+
}
|
|
4141
|
+
function closeTrackedSession(state, id, nowMs = Date.now()) {
|
|
4142
|
+
gcState(state, nowMs);
|
|
4143
|
+
const session = state.sessions[id];
|
|
4144
|
+
if (!session) return false;
|
|
4145
|
+
const durationMs = nowMs - new Date(session.started_at).getTime();
|
|
4146
|
+
state.pending_metrics.push(
|
|
4147
|
+
{
|
|
4148
|
+
session_id: id,
|
|
4149
|
+
metric_key: "session_duration_ms",
|
|
4150
|
+
metric_value: Math.max(0, durationMs)
|
|
4151
|
+
},
|
|
4152
|
+
{
|
|
4153
|
+
session_id: id,
|
|
4154
|
+
metric_key: "tool_call_count",
|
|
4155
|
+
metric_value: session.tool_call_count
|
|
4156
|
+
},
|
|
4157
|
+
{
|
|
4158
|
+
session_id: id,
|
|
4159
|
+
metric_key: "lessons_consulted",
|
|
4160
|
+
metric_value: session.lessons_consulted
|
|
4161
|
+
}
|
|
4162
|
+
);
|
|
4163
|
+
delete state.sessions[id];
|
|
4164
|
+
return true;
|
|
4165
|
+
}
|
|
4166
|
+
function gcState(state, nowMs) {
|
|
4167
|
+
if (state.guard_signals) {
|
|
4168
|
+
for (const [sid, sig] of Object.entries(state.guard_signals)) {
|
|
4169
|
+
const newest = Math.max(
|
|
4170
|
+
Date.parse(sig.consulted_at ?? "") || 0,
|
|
4171
|
+
Date.parse(sig.reviewed_at ?? "") || 0
|
|
4172
|
+
);
|
|
4173
|
+
if (nowMs - newest > STATE_GC_TTL_MS) delete state.guard_signals[sid];
|
|
4174
|
+
}
|
|
4175
|
+
}
|
|
4176
|
+
for (const [sid, session] of Object.entries(state.sessions)) {
|
|
4177
|
+
const started = Date.parse(session.started_at);
|
|
4178
|
+
if (!Number.isNaN(started) && nowMs - started > STATE_GC_TTL_MS) {
|
|
4179
|
+
delete state.sessions[sid];
|
|
4180
|
+
}
|
|
4181
|
+
}
|
|
4182
|
+
}
|
|
3792
4183
|
function effectiveConfig(state) {
|
|
3793
4184
|
if (state.config) return state.config;
|
|
3794
4185
|
const key = readApiKey();
|
|
@@ -3875,6 +4266,7 @@ async function runOnToolUse() {
|
|
|
3875
4266
|
if (tool.includes("search_lessons") || tool.includes("get_session_briefing") || tool.includes("get_lesson")) {
|
|
3876
4267
|
session.lessons_consulted += 1;
|
|
3877
4268
|
}
|
|
4269
|
+
recordGuardSignals(state, sessionId, tool);
|
|
3878
4270
|
const transcriptPath = input.transcript_path;
|
|
3879
4271
|
if (typeof transcriptPath === "string" && transcriptPath && !session.transcript_path) {
|
|
3880
4272
|
session.transcript_path = transcriptPath;
|
|
@@ -3904,15 +4296,6 @@ function realpathOfUnwritten(p) {
|
|
|
3904
4296
|
}
|
|
3905
4297
|
}
|
|
3906
4298
|
}
|
|
3907
|
-
function denyPayload(reason) {
|
|
3908
|
-
return JSON.stringify({
|
|
3909
|
-
hookSpecificOutput: {
|
|
3910
|
-
hookEventName: "PreToolUse",
|
|
3911
|
-
permissionDecision: "deny",
|
|
3912
|
-
permissionDecisionReason: reason
|
|
3913
|
-
}
|
|
3914
|
-
});
|
|
3915
|
-
}
|
|
3916
4299
|
function denyReason(verdict, ns) {
|
|
3917
4300
|
const holders = verdict.sightings.map((s) => ` - ${s.path} (${s.where})`).join("\n");
|
|
3918
4301
|
return `${ns.prefix}${verdict.number} is already taken:
|
|
@@ -3942,14 +4325,6 @@ async function runOnFileWrite() {
|
|
|
3942
4325
|
return 0;
|
|
3943
4326
|
}
|
|
3944
4327
|
}
|
|
3945
|
-
function advisoryPayload(context) {
|
|
3946
|
-
return JSON.stringify({
|
|
3947
|
-
hookSpecificOutput: {
|
|
3948
|
-
hookEventName: "PreToolUse",
|
|
3949
|
-
additionalContext: context
|
|
3950
|
-
}
|
|
3951
|
-
});
|
|
3952
|
-
}
|
|
3953
4328
|
async function runOnFileEdit() {
|
|
3954
4329
|
try {
|
|
3955
4330
|
const input = await readHookInput();
|
|
@@ -4048,27 +4423,8 @@ async function runSessionEndMetrics(sessionId) {
|
|
|
4048
4423
|
const config = effectiveConfig(state);
|
|
4049
4424
|
if (config === null) return;
|
|
4050
4425
|
const id = sessionId ?? Object.keys(state.sessions)[0];
|
|
4051
|
-
|
|
4052
|
-
|
|
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];
|
|
4426
|
+
if (id && state.sessions[id]) {
|
|
4427
|
+
closeTrackedSession(state, id);
|
|
4072
4428
|
await saveState(state);
|
|
4073
4429
|
}
|
|
4074
4430
|
await flushPending(config, STOP_FLUSH_TIMEOUT_MS);
|
|
@@ -4237,7 +4593,7 @@ function sessionIdOf(input) {
|
|
|
4237
4593
|
const id = typeof input.session_id === "string" ? input.session_id.trim() : "";
|
|
4238
4594
|
return id.length > 0 ? id : null;
|
|
4239
4595
|
}
|
|
4240
|
-
var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS, WIRING_REMEDY;
|
|
4596
|
+
var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS, STATE_GC_TTL_MS, WIRING_REMEDY;
|
|
4241
4597
|
var init_hooks2 = __esm({
|
|
4242
4598
|
"src/hooks/index.ts"() {
|
|
4243
4599
|
"use strict";
|
|
@@ -4251,10 +4607,12 @@ var init_hooks2 = __esm({
|
|
|
4251
4607
|
init_api();
|
|
4252
4608
|
init_edit_guard();
|
|
4253
4609
|
init_hook_input();
|
|
4610
|
+
init_payloads();
|
|
4254
4611
|
init_state();
|
|
4255
4612
|
DEFAULT_THRESHOLDS_ENDPOINT = process.env.MAIND_THRESHOLDS_ENDPOINT ?? "https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds";
|
|
4256
4613
|
STOP_FLUSH_TIMEOUT_MS = 1500;
|
|
4257
4614
|
MANUAL_FLUSH_TIMEOUT_MS = 1e4;
|
|
4615
|
+
STATE_GC_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
4258
4616
|
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
4617
|
}
|
|
4260
4618
|
});
|
|
@@ -4264,115 +4622,908 @@ function resolveConnection(e) {
|
|
|
4264
4622
|
if (e.ownSnapshotAgeMs !== null && e.ownSnapshotAgeMs <= SNAPSHOT_EVIDENCE_MAX_AGE_MS) {
|
|
4265
4623
|
return "connected";
|
|
4266
4624
|
}
|
|
4267
|
-
if (e.sawMaindCall) return "connected";
|
|
4268
|
-
if (e.presenceUsable) return "not_connected";
|
|
4269
|
-
return "unknown";
|
|
4625
|
+
if (e.sawMaindCall) return "connected";
|
|
4626
|
+
if (e.presenceUsable) return "not_connected";
|
|
4627
|
+
return "unknown";
|
|
4628
|
+
}
|
|
4629
|
+
var SNAPSHOT_EVIDENCE_MAX_AGE_MS;
|
|
4630
|
+
var init_connection = __esm({
|
|
4631
|
+
"src/session-end/connection.ts"() {
|
|
4632
|
+
"use strict";
|
|
4633
|
+
SNAPSHOT_EVIDENCE_MAX_AGE_MS = 30 * 6e4;
|
|
4634
|
+
}
|
|
4635
|
+
});
|
|
4636
|
+
|
|
4637
|
+
// src/session-end/index.ts
|
|
4638
|
+
var session_end_exports = {};
|
|
4639
|
+
__export(session_end_exports, {
|
|
4640
|
+
runOnSessionEnd: () => runOnSessionEnd
|
|
4641
|
+
});
|
|
4642
|
+
function connectionVerdict(sawMaindCall, nowMs) {
|
|
4643
|
+
try {
|
|
4644
|
+
const projectKey = computeProjectKey();
|
|
4645
|
+
const presenceUsable = projectKey !== null && !autoAnnounceDisabled(process.env, readBridgeConfig());
|
|
4646
|
+
let ownSnapshotAgeMs = null;
|
|
4647
|
+
if (projectKey !== null) {
|
|
4648
|
+
const own = selectOwnSnapshot(readSnapshots(projectKey), {
|
|
4649
|
+
grandparentPid: grandparentPid(),
|
|
4650
|
+
cwd: process.cwd()
|
|
4651
|
+
});
|
|
4652
|
+
if (own) {
|
|
4653
|
+
const written = Date.parse(own.snap.written_at);
|
|
4654
|
+
ownSnapshotAgeMs = Number.isFinite(written) ? Math.max(0, nowMs - written) : null;
|
|
4655
|
+
}
|
|
4656
|
+
}
|
|
4657
|
+
return resolveConnection({ ownSnapshotAgeMs, sawMaindCall, presenceUsable });
|
|
4658
|
+
} catch {
|
|
4659
|
+
return sawMaindCall ? "connected" : "unknown";
|
|
4660
|
+
}
|
|
4661
|
+
}
|
|
4662
|
+
function presenceSessionId() {
|
|
4663
|
+
const raw = (process.env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
|
|
4664
|
+
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;
|
|
4665
|
+
}
|
|
4666
|
+
async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
|
|
4667
|
+
const post = fetch(INGEST_ENDPOINT, {
|
|
4668
|
+
method: "POST",
|
|
4669
|
+
headers: {
|
|
4670
|
+
"content-type": "application/json",
|
|
4671
|
+
authorization: `Bearer ${apiKey}`,
|
|
4672
|
+
"x-maind-device-id": deviceId,
|
|
4673
|
+
"x-maind-bridge-version": BRIDGE_VERSION
|
|
4674
|
+
},
|
|
4675
|
+
body: JSON.stringify(body)
|
|
4676
|
+
}).then(() => void 0).catch(() => void 0);
|
|
4677
|
+
const timeout = new Promise((resolve3) => setTimeout(resolve3, timeoutMs));
|
|
4678
|
+
await Promise.race([post, timeout]);
|
|
4679
|
+
}
|
|
4680
|
+
async function runOnSessionEnd() {
|
|
4681
|
+
const apiKey = readApiKey();
|
|
4682
|
+
if (!apiKey) return 0;
|
|
4683
|
+
const input = await readHookInput();
|
|
4684
|
+
const sessionId = typeof input.session_id === "string" && input.session_id ? input.session_id : null;
|
|
4685
|
+
const transcriptPath = transcriptPathOf(input);
|
|
4686
|
+
if (transcriptPath) {
|
|
4687
|
+
try {
|
|
4688
|
+
const [analytics, span] = await Promise.all([
|
|
4689
|
+
analyzeSession(transcriptPath),
|
|
4690
|
+
analyzeSpan(transcriptPath)
|
|
4691
|
+
]);
|
|
4692
|
+
if (sessionId) {
|
|
4693
|
+
analytics.session_id = sessionId;
|
|
4694
|
+
span.session_id = sessionId;
|
|
4695
|
+
}
|
|
4696
|
+
analytics.maind_connected = connectionVerdict(
|
|
4697
|
+
analytics.maind_connected === "connected",
|
|
4698
|
+
Date.now()
|
|
4699
|
+
);
|
|
4700
|
+
if (analytics.session_id) {
|
|
4701
|
+
const body = ingestBody(analytics, span, {
|
|
4702
|
+
client_session_id: presenceSessionId(),
|
|
4703
|
+
client: "claude-code"
|
|
4704
|
+
});
|
|
4705
|
+
await postWithTimeout(apiKey, ensureDeviceId(), body, 1500);
|
|
4706
|
+
}
|
|
4707
|
+
} catch (err) {
|
|
4708
|
+
process.stderr.write(
|
|
4709
|
+
`[maind-mcp-bridge] session-end ingest failed: ${err instanceof Error ? err.message : String(err)}
|
|
4710
|
+
`
|
|
4711
|
+
);
|
|
4712
|
+
}
|
|
4713
|
+
}
|
|
4714
|
+
await runSessionEndMetrics(sessionId);
|
|
4715
|
+
return 0;
|
|
4716
|
+
}
|
|
4717
|
+
var INGEST_ENDPOINT;
|
|
4718
|
+
var init_session_end = __esm({
|
|
4719
|
+
"src/session-end/index.ts"() {
|
|
4720
|
+
"use strict";
|
|
4721
|
+
init_dist();
|
|
4722
|
+
init_bridge_config();
|
|
4723
|
+
init_device_id();
|
|
4724
|
+
init_api();
|
|
4725
|
+
init_edit_guard();
|
|
4726
|
+
init_hook_input();
|
|
4727
|
+
init_hooks2();
|
|
4728
|
+
init_presence();
|
|
4729
|
+
init_presence_snapshot();
|
|
4730
|
+
init_project_key();
|
|
4731
|
+
init_version();
|
|
4732
|
+
init_connection();
|
|
4733
|
+
INGEST_ENDPOINT = DEFAULT_INGEST_ENDPOINT;
|
|
4734
|
+
}
|
|
4735
|
+
});
|
|
4736
|
+
|
|
4737
|
+
// src/guard/config.ts
|
|
4738
|
+
function resolveGuardConfig(env = process.env, cfg = readBridgeConfig()) {
|
|
4739
|
+
const fromEnv = env.MAIND_GUARD;
|
|
4740
|
+
const mode = fromEnv === "off" || fromEnv === "warn" || fromEnv === "block" ? fromEnv : cfg?.guard_mode ?? "off";
|
|
4741
|
+
return { mode, stopGate: cfg?.guard_stop_gate === true };
|
|
4742
|
+
}
|
|
4743
|
+
async function writeGuardConfig(patch, configPath = bridgeConfigPath()) {
|
|
4744
|
+
let existing = {};
|
|
4745
|
+
try {
|
|
4746
|
+
const raw = await readFileSafe(configPath);
|
|
4747
|
+
if (raw !== null && raw.trim().length > 0) {
|
|
4748
|
+
const parsed = JSON.parse(raw);
|
|
4749
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
4750
|
+
existing = parsed;
|
|
4751
|
+
}
|
|
4752
|
+
}
|
|
4753
|
+
} catch {
|
|
4754
|
+
}
|
|
4755
|
+
const next = { ...existing, ...patch };
|
|
4756
|
+
await atomicWriteFile(configPath, JSON.stringify(next, null, 2) + "\n", 384);
|
|
4757
|
+
}
|
|
4758
|
+
var init_config = __esm({
|
|
4759
|
+
"src/guard/config.ts"() {
|
|
4760
|
+
"use strict";
|
|
4761
|
+
init_bridge_config();
|
|
4762
|
+
init_atomic_write();
|
|
4763
|
+
}
|
|
4764
|
+
});
|
|
4765
|
+
|
|
4766
|
+
// src/guard/install.ts
|
|
4767
|
+
function parseGuardInstallFlags(argv) {
|
|
4768
|
+
const flags = {
|
|
4769
|
+
mode: "warn",
|
|
4770
|
+
// ADR-284: warn is the default; block is opt-in
|
|
4771
|
+
stopGate: false,
|
|
4772
|
+
full: false,
|
|
4773
|
+
dryRun: false
|
|
4774
|
+
};
|
|
4775
|
+
for (let i = 0; i < argv.length; i++) {
|
|
4776
|
+
const a = argv[i];
|
|
4777
|
+
switch (a) {
|
|
4778
|
+
case "--mode": {
|
|
4779
|
+
const v = argv[++i];
|
|
4780
|
+
if (v !== "warn" && v !== "block") return null;
|
|
4781
|
+
flags.mode = v;
|
|
4782
|
+
break;
|
|
4783
|
+
}
|
|
4784
|
+
case "--stop-gate":
|
|
4785
|
+
flags.stopGate = true;
|
|
4786
|
+
break;
|
|
4787
|
+
case "--full":
|
|
4788
|
+
case "--yes":
|
|
4789
|
+
flags.full = true;
|
|
4790
|
+
break;
|
|
4791
|
+
case "--dry-run":
|
|
4792
|
+
flags.dryRun = true;
|
|
4793
|
+
break;
|
|
4794
|
+
default:
|
|
4795
|
+
return null;
|
|
4796
|
+
}
|
|
4797
|
+
}
|
|
4798
|
+
return flags;
|
|
4799
|
+
}
|
|
4800
|
+
async function runGuardInstall(argv, homeDir, out2 = process.stdout) {
|
|
4801
|
+
const flags = parseGuardInstallFlags(argv);
|
|
4802
|
+
if (flags === null) {
|
|
4803
|
+
out2.write(
|
|
4804
|
+
"usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]\n"
|
|
4805
|
+
);
|
|
4806
|
+
return 1;
|
|
4807
|
+
}
|
|
4808
|
+
const opts = {
|
|
4809
|
+
homeDir,
|
|
4810
|
+
isInteractive: process.stdin.isTTY === true,
|
|
4811
|
+
full: flags.full,
|
|
4812
|
+
skip: false,
|
|
4813
|
+
dryRun: flags.dryRun,
|
|
4814
|
+
out: out2
|
|
4815
|
+
};
|
|
4816
|
+
const results = [];
|
|
4817
|
+
for (const hook of GUARD_SUBCOMMAND_HOOKS) {
|
|
4818
|
+
results.push(await mergeSubcommandHook(opts, hook));
|
|
4819
|
+
}
|
|
4820
|
+
for (const r of results) {
|
|
4821
|
+
out2.write(` ${r.status.padEnd(12)} ${r.target}${r.detail ? ` \u2014 ${r.detail}` : ""}
|
|
4822
|
+
`);
|
|
4823
|
+
}
|
|
4824
|
+
const declined = results.some((r) => r.detail === "user declined");
|
|
4825
|
+
const failed3 = results.some((r) => r.status === "failed");
|
|
4826
|
+
if (flags.dryRun) {
|
|
4827
|
+
out2.write(
|
|
4828
|
+
`
|
|
4829
|
+
[dry-run] would set guard_mode=${flags.mode}` + (flags.stopGate ? " + guard_stop_gate=true" : "") + " in the bridge config.\n"
|
|
4830
|
+
);
|
|
4831
|
+
return 0;
|
|
4832
|
+
}
|
|
4833
|
+
await writeGuardConfig({
|
|
4834
|
+
guard_mode: flags.mode,
|
|
4835
|
+
...flags.stopGate ? { guard_stop_gate: true } : {}
|
|
4836
|
+
});
|
|
4837
|
+
out2.write(
|
|
4838
|
+
`
|
|
4839
|
+
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"
|
|
4840
|
+
);
|
|
4841
|
+
if (declined) {
|
|
4842
|
+
out2.write(
|
|
4843
|
+
"Note: at least one hook was declined \u2014 the guard runs with what was consented.\n"
|
|
4844
|
+
);
|
|
4845
|
+
}
|
|
4846
|
+
return failed3 ? 1 : 0;
|
|
4847
|
+
}
|
|
4848
|
+
var init_install = __esm({
|
|
4849
|
+
"src/guard/install.ts"() {
|
|
4850
|
+
"use strict";
|
|
4851
|
+
init_hook_wiring();
|
|
4852
|
+
init_hook_merge();
|
|
4853
|
+
init_config();
|
|
4854
|
+
}
|
|
4855
|
+
});
|
|
4856
|
+
|
|
4857
|
+
// src/guard/session-file.ts
|
|
4858
|
+
import { existsSync as existsSync11 } from "node:fs";
|
|
4859
|
+
import { mkdir as mkdir3, readFile as readFile3, readdir, rename as rename3, stat as stat2, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
|
|
4860
|
+
import { join as join17 } from "node:path";
|
|
4861
|
+
function sessionFile(sessionId) {
|
|
4862
|
+
return join17(GUARD_SESSIONS_DIR, sessionId.replace(/[^a-zA-Z0-9._-]/g, "_") + ".json");
|
|
4863
|
+
}
|
|
4864
|
+
async function loadGuardSession(sessionId) {
|
|
4865
|
+
try {
|
|
4866
|
+
const file = sessionFile(sessionId);
|
|
4867
|
+
if (!existsSync11(file)) return {};
|
|
4868
|
+
const parsed = JSON.parse(await readFile3(file, "utf8"));
|
|
4869
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
4870
|
+
return parsed;
|
|
4871
|
+
}
|
|
4872
|
+
return {};
|
|
4873
|
+
} catch {
|
|
4874
|
+
return {};
|
|
4875
|
+
}
|
|
4876
|
+
}
|
|
4877
|
+
async function saveGuardSession(sessionId, state) {
|
|
4878
|
+
await mkdir3(GUARD_SESSIONS_DIR, { recursive: true, mode: 448 });
|
|
4879
|
+
const file = sessionFile(sessionId);
|
|
4880
|
+
const tmp = `${file}.tmp`;
|
|
4881
|
+
await writeFile4(tmp, JSON.stringify({ ...state, updated_at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2), {
|
|
4882
|
+
mode: 384
|
|
4883
|
+
});
|
|
4884
|
+
await rename3(tmp, file);
|
|
4885
|
+
}
|
|
4886
|
+
async function sweepOldGuardSessions(maxAgeMs = 7 * 24 * 60 * 60 * 1e3, nowMs = Date.now()) {
|
|
4887
|
+
try {
|
|
4888
|
+
if (!existsSync11(GUARD_SESSIONS_DIR)) return;
|
|
4889
|
+
for (const name of await readdir(GUARD_SESSIONS_DIR)) {
|
|
4890
|
+
if (!name.endsWith(".json")) continue;
|
|
4891
|
+
const file = join17(GUARD_SESSIONS_DIR, name);
|
|
4892
|
+
try {
|
|
4893
|
+
const s = await stat2(file);
|
|
4894
|
+
if (nowMs - s.mtimeMs > maxAgeMs) await unlink2(file);
|
|
4895
|
+
} catch {
|
|
4896
|
+
}
|
|
4897
|
+
}
|
|
4898
|
+
} catch {
|
|
4899
|
+
}
|
|
4900
|
+
}
|
|
4901
|
+
var GUARD_DIR, GUARD_SESSIONS_DIR;
|
|
4902
|
+
var init_session_file = __esm({
|
|
4903
|
+
"src/guard/session-file.ts"() {
|
|
4904
|
+
"use strict";
|
|
4905
|
+
init_state();
|
|
4906
|
+
GUARD_DIR = join17(STATE_DIR, "guard");
|
|
4907
|
+
GUARD_SESSIONS_DIR = join17(GUARD_DIR, "sessions");
|
|
4908
|
+
}
|
|
4909
|
+
});
|
|
4910
|
+
|
|
4911
|
+
// src/guard/log.ts
|
|
4912
|
+
import { existsSync as existsSync12 } from "node:fs";
|
|
4913
|
+
import { appendFile, mkdir as mkdir4, open } from "node:fs/promises";
|
|
4914
|
+
import { join as join18 } from "node:path";
|
|
4915
|
+
async function appendGuardEvent(event) {
|
|
4916
|
+
try {
|
|
4917
|
+
await mkdir4(GUARD_DIR, { recursive: true, mode: 448 });
|
|
4918
|
+
const line = JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...event }) + "\n";
|
|
4919
|
+
await appendFile(GUARD_EVENTS_FILE, line, { mode: 384 });
|
|
4920
|
+
} catch {
|
|
4921
|
+
}
|
|
4922
|
+
}
|
|
4923
|
+
async function readGuardEventCounts(tailBytes = 256 * 1024) {
|
|
4924
|
+
const counts = {
|
|
4925
|
+
inject_ok: 0,
|
|
4926
|
+
inject_fail: 0,
|
|
4927
|
+
warn: 0,
|
|
4928
|
+
deny: 0,
|
|
4929
|
+
override: 0,
|
|
4930
|
+
stop_block: 0
|
|
4931
|
+
};
|
|
4932
|
+
try {
|
|
4933
|
+
if (!existsSync12(GUARD_EVENTS_FILE)) return counts;
|
|
4934
|
+
const fh = await open(GUARD_EVENTS_FILE, "r");
|
|
4935
|
+
try {
|
|
4936
|
+
const size = (await fh.stat()).size;
|
|
4937
|
+
const start = Math.max(0, size - tailBytes);
|
|
4938
|
+
const buf = Buffer.alloc(size - start);
|
|
4939
|
+
await fh.read(buf, 0, buf.length, start);
|
|
4940
|
+
const text = buf.toString("utf8");
|
|
4941
|
+
const lines2 = text.split("\n");
|
|
4942
|
+
for (const line of start > 0 ? lines2.slice(1) : lines2) {
|
|
4943
|
+
if (!line.trim()) continue;
|
|
4944
|
+
try {
|
|
4945
|
+
const parsed = JSON.parse(line);
|
|
4946
|
+
if (typeof parsed.event === "string" && parsed.event in counts) {
|
|
4947
|
+
counts[parsed.event] += 1;
|
|
4948
|
+
}
|
|
4949
|
+
} catch {
|
|
4950
|
+
}
|
|
4951
|
+
}
|
|
4952
|
+
} finally {
|
|
4953
|
+
await fh.close();
|
|
4954
|
+
}
|
|
4955
|
+
} catch {
|
|
4956
|
+
}
|
|
4957
|
+
return counts;
|
|
4958
|
+
}
|
|
4959
|
+
var GUARD_EVENTS_FILE;
|
|
4960
|
+
var init_log = __esm({
|
|
4961
|
+
"src/guard/log.ts"() {
|
|
4962
|
+
"use strict";
|
|
4963
|
+
init_session_file();
|
|
4964
|
+
GUARD_EVENTS_FILE = join18(GUARD_DIR, "events.jsonl");
|
|
4965
|
+
}
|
|
4966
|
+
});
|
|
4967
|
+
|
|
4968
|
+
// src/guard/cli.ts
|
|
4969
|
+
var cli_exports = {};
|
|
4970
|
+
__export(cli_exports, {
|
|
4971
|
+
runGuard: () => runGuard
|
|
4972
|
+
});
|
|
4973
|
+
import { existsSync as existsSync13, readFileSync as readFileSync9 } from "node:fs";
|
|
4974
|
+
import { homedir as homedir7 } from "node:os";
|
|
4975
|
+
import { join as join19 } from "node:path";
|
|
4976
|
+
async function runGuard(argv) {
|
|
4977
|
+
const verb = argv[0];
|
|
4978
|
+
const rest = argv.slice(1);
|
|
4979
|
+
switch (verb) {
|
|
4980
|
+
case "install":
|
|
4981
|
+
return runGuardInstall(rest, homedir7());
|
|
4982
|
+
case "status":
|
|
4983
|
+
return runGuardStatus();
|
|
4984
|
+
case "mode": {
|
|
4985
|
+
const v = rest[0];
|
|
4986
|
+
if (v !== "warn" && v !== "block") {
|
|
4987
|
+
process.stdout.write("usage: maind-mcp-bridge guard mode <warn|block>\n");
|
|
4988
|
+
return 1;
|
|
4989
|
+
}
|
|
4990
|
+
await writeGuardConfig({ guard_mode: v });
|
|
4991
|
+
process.stdout.write(
|
|
4992
|
+
`guard mode set to '${v}' \u2014 takes effect for new sessions.
|
|
4993
|
+
`
|
|
4994
|
+
);
|
|
4995
|
+
return 0;
|
|
4996
|
+
}
|
|
4997
|
+
case "off":
|
|
4998
|
+
await writeGuardConfig({ guard_mode: "off" });
|
|
4999
|
+
process.stdout.write(
|
|
5000
|
+
"guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.\n"
|
|
5001
|
+
);
|
|
5002
|
+
return 0;
|
|
5003
|
+
case "stop-gate": {
|
|
5004
|
+
const v = rest[0];
|
|
5005
|
+
if (v !== "on" && v !== "off") {
|
|
5006
|
+
process.stdout.write("usage: maind-mcp-bridge guard stop-gate <on|off>\n");
|
|
5007
|
+
return 1;
|
|
5008
|
+
}
|
|
5009
|
+
await writeGuardConfig({ guard_stop_gate: v === "on" });
|
|
5010
|
+
process.stdout.write(`strict stop-gate ${v === "on" ? "enabled" : "disabled"}.
|
|
5011
|
+
`);
|
|
5012
|
+
return 0;
|
|
5013
|
+
}
|
|
5014
|
+
case "skip":
|
|
5015
|
+
return runGuardSkip(rest);
|
|
5016
|
+
default:
|
|
5017
|
+
process.stdout.write(USAGE);
|
|
5018
|
+
return verb === void 0 || verb === "--help" || verb === "-h" ? 0 : 1;
|
|
5019
|
+
}
|
|
5020
|
+
}
|
|
5021
|
+
async function runGuardSkip(argv) {
|
|
5022
|
+
let sessionId = null;
|
|
5023
|
+
let reason = null;
|
|
5024
|
+
for (let i = 0; i < argv.length; i++) {
|
|
5025
|
+
if (argv[i] === "--session") sessionId = argv[++i] ?? null;
|
|
5026
|
+
else if (argv[i] === "--reason") reason = argv[++i] ?? null;
|
|
5027
|
+
}
|
|
5028
|
+
if (!sessionId || !reason || reason.trim().length === 0) {
|
|
5029
|
+
process.stdout.write(
|
|
5030
|
+
'usage: maind-mcp-bridge guard skip --session <id> --reason "<why consultation is unnecessary here>"\n'
|
|
5031
|
+
);
|
|
5032
|
+
return 1;
|
|
5033
|
+
}
|
|
5034
|
+
const trimmed = reason.trim().slice(0, 500);
|
|
5035
|
+
const session = await loadGuardSession(sessionId);
|
|
5036
|
+
await saveGuardSession(sessionId, { ...session, override_reason: trimmed });
|
|
5037
|
+
await appendGuardEvent({
|
|
5038
|
+
event: "override",
|
|
5039
|
+
session_id: sessionId,
|
|
5040
|
+
reason: trimmed,
|
|
5041
|
+
cwd: process.cwd()
|
|
5042
|
+
});
|
|
5043
|
+
process.stdout.write(
|
|
5044
|
+
`override recorded for session ${sessionId} \u2014 the gate opens on the next attempt.
|
|
5045
|
+
logged (auditable) in ${GUARD_EVENTS_FILE}
|
|
5046
|
+
`
|
|
5047
|
+
);
|
|
5048
|
+
return 0;
|
|
5049
|
+
}
|
|
5050
|
+
async function runGuardStatus() {
|
|
5051
|
+
const config = resolveGuardConfig();
|
|
5052
|
+
const settingsPath = join19(homedir7(), ".claude", "settings.json");
|
|
5053
|
+
let raw = null;
|
|
5054
|
+
try {
|
|
5055
|
+
if (existsSync13(settingsPath)) raw = readFileSync9(settingsPath, "utf8");
|
|
5056
|
+
} catch {
|
|
5057
|
+
}
|
|
5058
|
+
const wiring = inspectHookWiring(raw, {}, GUARD_SUBCOMMAND_HOOKS);
|
|
5059
|
+
const events = await readGuardEventCounts();
|
|
5060
|
+
process.stdout.write(
|
|
5061
|
+
JSON.stringify(
|
|
5062
|
+
{
|
|
5063
|
+
mode: config.mode,
|
|
5064
|
+
stop_gate: config.stopGate,
|
|
5065
|
+
mode_source: process.env.MAIND_GUARD ? "env:MAIND_GUARD" : "config.json",
|
|
5066
|
+
hook_wiring: wiring.map((f) => ({
|
|
5067
|
+
event: f.event,
|
|
5068
|
+
subcommand: f.subcommand,
|
|
5069
|
+
status: f.status,
|
|
5070
|
+
detail: f.detail
|
|
5071
|
+
})),
|
|
5072
|
+
events,
|
|
5073
|
+
events_file: GUARD_EVENTS_FILE
|
|
5074
|
+
},
|
|
5075
|
+
null,
|
|
5076
|
+
2
|
|
5077
|
+
) + "\n"
|
|
5078
|
+
);
|
|
5079
|
+
const missing = wiring.filter((f) => f.status !== "ok");
|
|
5080
|
+
if (config.mode === "off") {
|
|
5081
|
+
process.stderr.write(
|
|
5082
|
+
"\n[maind] guard is OFF \u2014 enable with `guard install` (first time) or `guard mode warn|block`.\n"
|
|
5083
|
+
);
|
|
5084
|
+
}
|
|
5085
|
+
if (missing.length > 0 && config.mode !== "off") {
|
|
5086
|
+
process.stderr.write("\n[maind] guard hook wiring is incomplete:\n");
|
|
5087
|
+
for (const f of missing) process.stderr.write(` \u2022 ${f.detail}
|
|
5088
|
+
`);
|
|
5089
|
+
if (missing.some((f) => f.remedy === "run-install")) {
|
|
5090
|
+
process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n");
|
|
5091
|
+
}
|
|
5092
|
+
}
|
|
5093
|
+
return 0;
|
|
5094
|
+
}
|
|
5095
|
+
var USAGE;
|
|
5096
|
+
var init_cli = __esm({
|
|
5097
|
+
"src/guard/cli.ts"() {
|
|
5098
|
+
"use strict";
|
|
5099
|
+
init_hook_wiring();
|
|
5100
|
+
init_config();
|
|
5101
|
+
init_install();
|
|
5102
|
+
init_log();
|
|
5103
|
+
init_session_file();
|
|
5104
|
+
USAGE = [
|
|
5105
|
+
"usage: maind-mcp-bridge guard <verb>",
|
|
5106
|
+
"",
|
|
5107
|
+
" install [--mode warn|block] [--stop-gate] [--full] [--dry-run]",
|
|
5108
|
+
" wire the guard hooks (consent per hook, append-only) + set the mode",
|
|
5109
|
+
" status mode, hook wiring, and local event counts",
|
|
5110
|
+
" mode <warn|block>",
|
|
5111
|
+
" flip enforcement hardness (config-only; settings.json untouched)",
|
|
5112
|
+
" off disable the guard (hooks stay wired, become no-ops)",
|
|
5113
|
+
" stop-gate <on|off>",
|
|
5114
|
+
" toggle the strict completion gate (review before finish)",
|
|
5115
|
+
' skip --session <id> --reason "<why>"',
|
|
5116
|
+
" record a logged override for one session (block-gate exit valve)",
|
|
5117
|
+
""
|
|
5118
|
+
].join("\n");
|
|
5119
|
+
}
|
|
5120
|
+
});
|
|
5121
|
+
|
|
5122
|
+
// src/guard/mcp-client.ts
|
|
5123
|
+
async function fetchSessionBriefing(opts) {
|
|
5124
|
+
const mcpUrl = opts.mcpUrl ?? process.env.MAIND_MCP_URL ?? DEFAULT_MCP_URL3;
|
|
5125
|
+
const controller = new AbortController();
|
|
5126
|
+
const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 3e3);
|
|
5127
|
+
try {
|
|
5128
|
+
const base = {
|
|
5129
|
+
"content-type": "application/json",
|
|
5130
|
+
accept: "application/json, text/event-stream",
|
|
5131
|
+
authorization: `Bearer ${opts.apiKey}`,
|
|
5132
|
+
// The guard acts on behalf of a Claude Code session — attribute it so.
|
|
5133
|
+
"x-maind-client-family": "claude-code",
|
|
5134
|
+
"x-maind-client-version": opts.bridgeVersion,
|
|
5135
|
+
"x-maind-bridge-version": opts.bridgeVersion
|
|
5136
|
+
};
|
|
5137
|
+
if (opts.deviceId) base["x-maind-device-id"] = opts.deviceId;
|
|
5138
|
+
if (opts.projectKey) base["x-maind-project-key"] = opts.projectKey;
|
|
5139
|
+
const init = await fetch(mcpUrl, {
|
|
5140
|
+
method: "POST",
|
|
5141
|
+
headers: base,
|
|
5142
|
+
signal: controller.signal,
|
|
5143
|
+
body: JSON.stringify({
|
|
5144
|
+
jsonrpc: "2.0",
|
|
5145
|
+
id: "guard-init",
|
|
5146
|
+
method: "initialize",
|
|
5147
|
+
params: {
|
|
5148
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
5149
|
+
capabilities: {},
|
|
5150
|
+
clientInfo: { name: "maind-mcp-bridge-guard", version: opts.bridgeVersion }
|
|
5151
|
+
}
|
|
5152
|
+
})
|
|
5153
|
+
});
|
|
5154
|
+
const sessionId = init.headers.get("mcp-session-id");
|
|
5155
|
+
await init.text().catch(() => "");
|
|
5156
|
+
if (!init.ok || !sessionId) return null;
|
|
5157
|
+
const withSession = { ...base, "mcp-session-id": sessionId };
|
|
5158
|
+
await fetch(mcpUrl, {
|
|
5159
|
+
method: "POST",
|
|
5160
|
+
headers: withSession,
|
|
5161
|
+
signal: controller.signal,
|
|
5162
|
+
body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
|
|
5163
|
+
}).then((r) => r.text().catch(() => "")).catch(() => "");
|
|
5164
|
+
const call = await fetch(mcpUrl, {
|
|
5165
|
+
method: "POST",
|
|
5166
|
+
headers: withSession,
|
|
5167
|
+
signal: controller.signal,
|
|
5168
|
+
body: JSON.stringify({
|
|
5169
|
+
jsonrpc: "2.0",
|
|
5170
|
+
id: "guard-briefing",
|
|
5171
|
+
method: "tools/call",
|
|
5172
|
+
params: {
|
|
5173
|
+
name: "get_session_briefing",
|
|
5174
|
+
arguments: { tools: ["claude-code"] }
|
|
5175
|
+
}
|
|
5176
|
+
})
|
|
5177
|
+
});
|
|
5178
|
+
if (!call.ok) return null;
|
|
5179
|
+
const contentType = call.headers.get("content-type") ?? "";
|
|
5180
|
+
const raw = contentType.startsWith("text/event-stream") ? await readSseMessage(call) : await call.text();
|
|
5181
|
+
if (raw.trim().length === 0) return null;
|
|
5182
|
+
const message = JSON.parse(raw);
|
|
5183
|
+
if (message.error || message.result?.isError) return null;
|
|
5184
|
+
const text = message.result?.content?.find(
|
|
5185
|
+
(c) => c.type === "text" && typeof c.text === "string"
|
|
5186
|
+
)?.text;
|
|
5187
|
+
return typeof text === "string" && text.trim().length > 0 ? text : null;
|
|
5188
|
+
} catch {
|
|
5189
|
+
return null;
|
|
5190
|
+
} finally {
|
|
5191
|
+
clearTimeout(timer);
|
|
5192
|
+
}
|
|
5193
|
+
}
|
|
5194
|
+
async function readSseMessage(response) {
|
|
5195
|
+
if (!response.body) return "";
|
|
5196
|
+
const reader = response.body.getReader();
|
|
5197
|
+
const decoder = new TextDecoder();
|
|
5198
|
+
let buffer = "";
|
|
5199
|
+
let dataLines = [];
|
|
5200
|
+
let lastPayload = "";
|
|
5201
|
+
const flush = () => {
|
|
5202
|
+
if (dataLines.length === 0) return;
|
|
5203
|
+
const payload = dataLines.join("\n").trim();
|
|
5204
|
+
dataLines = [];
|
|
5205
|
+
if (payload.length > 0) lastPayload = payload;
|
|
5206
|
+
};
|
|
5207
|
+
while (true) {
|
|
5208
|
+
const { value, done } = await reader.read();
|
|
5209
|
+
if (done) break;
|
|
5210
|
+
buffer += decoder.decode(value, { stream: true });
|
|
5211
|
+
let nl;
|
|
5212
|
+
while ((nl = buffer.indexOf("\n")) !== -1) {
|
|
5213
|
+
const rawLine = buffer.slice(0, nl);
|
|
5214
|
+
buffer = buffer.slice(nl + 1);
|
|
5215
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
5216
|
+
if (line === "") {
|
|
5217
|
+
flush();
|
|
5218
|
+
continue;
|
|
5219
|
+
}
|
|
5220
|
+
if (line.startsWith(":")) continue;
|
|
5221
|
+
if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^\s/, ""));
|
|
5222
|
+
}
|
|
5223
|
+
}
|
|
5224
|
+
flush();
|
|
5225
|
+
return lastPayload;
|
|
4270
5226
|
}
|
|
4271
|
-
var
|
|
4272
|
-
var
|
|
4273
|
-
"src/
|
|
5227
|
+
var DEFAULT_MCP_URL3, MCP_PROTOCOL_VERSION;
|
|
5228
|
+
var init_mcp_client = __esm({
|
|
5229
|
+
"src/guard/mcp-client.ts"() {
|
|
4274
5230
|
"use strict";
|
|
4275
|
-
|
|
5231
|
+
DEFAULT_MCP_URL3 = "https://mcp.maind.dev/mcp";
|
|
5232
|
+
MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
4276
5233
|
}
|
|
4277
5234
|
});
|
|
4278
5235
|
|
|
4279
|
-
// src/
|
|
4280
|
-
var
|
|
4281
|
-
__export(
|
|
4282
|
-
|
|
5236
|
+
// src/guard/inject.ts
|
|
5237
|
+
var inject_exports = {};
|
|
5238
|
+
__export(inject_exports, {
|
|
5239
|
+
BRIEFING_CACHE_FILE: () => BRIEFING_CACHE_FILE,
|
|
5240
|
+
formatInjection: () => formatInjection,
|
|
5241
|
+
resolveBriefingInjection: () => resolveBriefingInjection,
|
|
5242
|
+
runGuardInject: () => runGuardInject
|
|
4283
5243
|
});
|
|
4284
|
-
|
|
5244
|
+
import { existsSync as existsSync14 } from "node:fs";
|
|
5245
|
+
import { mkdir as mkdir5, readFile as readFile4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
|
|
5246
|
+
import { dirname as dirname6, join as join20 } from "node:path";
|
|
5247
|
+
async function resolveBriefingInjection(projectKey, apiKey, deps = {}) {
|
|
5248
|
+
const nowMs = deps.nowMs ?? Date.now();
|
|
5249
|
+
const cacheFile = deps.cacheFile ?? BRIEFING_CACHE_FILE;
|
|
5250
|
+
const fetcher = deps.fetcher ?? fetchSessionBriefing;
|
|
5251
|
+
const cache = await readCache(cacheFile);
|
|
5252
|
+
const fresh = cache !== null && nowMs - Date.parse(cache.fetched_at) < CACHE_TTL_MS && cache.project_key === projectKey;
|
|
5253
|
+
if (fresh) return { text: cache.text, via: "cache" };
|
|
5254
|
+
const fetched = await fetcher({
|
|
5255
|
+
apiKey,
|
|
5256
|
+
deviceId: safeDeviceId(),
|
|
5257
|
+
projectKey,
|
|
5258
|
+
bridgeVersion: BRIDGE_VERSION,
|
|
5259
|
+
timeoutMs: FETCH_BUDGET_MS
|
|
5260
|
+
});
|
|
5261
|
+
if (fetched !== null) {
|
|
5262
|
+
await writeCache(cacheFile, {
|
|
5263
|
+
fetched_at: new Date(nowMs).toISOString(),
|
|
5264
|
+
project_key: projectKey,
|
|
5265
|
+
text: fetched
|
|
5266
|
+
});
|
|
5267
|
+
return { text: fetched, via: "fetch" };
|
|
5268
|
+
}
|
|
5269
|
+
if (cache !== null) return { text: cache.text, via: "stale-cache" };
|
|
5270
|
+
return { text: null, via: "none" };
|
|
5271
|
+
}
|
|
5272
|
+
async function runGuardInject() {
|
|
4285
5273
|
try {
|
|
5274
|
+
const guard = resolveGuardConfig();
|
|
5275
|
+
if (guard.mode === "off") return 0;
|
|
5276
|
+
const input = await readHookInput();
|
|
5277
|
+
const sessionId = typeof input.session_id === "string" && input.session_id.trim().length > 0 ? input.session_id.trim() : null;
|
|
5278
|
+
if (sessionId === null) return 0;
|
|
5279
|
+
await sweepOldGuardSessions();
|
|
5280
|
+
const source = typeof input.source === "string" ? input.source : "startup";
|
|
5281
|
+
if (source === "resume" || source === "compact") {
|
|
5282
|
+
const state2 = await loadGuardSession(sessionId);
|
|
5283
|
+
await saveGuardSession(sessionId, { ...state2, carryover: true });
|
|
5284
|
+
return 0;
|
|
5285
|
+
}
|
|
5286
|
+
const apiKey = readApiKey();
|
|
5287
|
+
if (apiKey === null) return 0;
|
|
5288
|
+
const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
|
|
4286
5289
|
const projectKey = computeProjectKey();
|
|
4287
|
-
const
|
|
4288
|
-
|
|
4289
|
-
if (
|
|
4290
|
-
|
|
4291
|
-
|
|
4292
|
-
|
|
5290
|
+
const result = await resolveBriefingInjection(projectKey, apiKey);
|
|
5291
|
+
const state = await loadGuardSession(sessionId);
|
|
5292
|
+
if (result.text === null) {
|
|
5293
|
+
await saveGuardSession(sessionId, { ...state, inject_failed: true });
|
|
5294
|
+
await appendGuardEvent({
|
|
5295
|
+
event: "inject_fail",
|
|
5296
|
+
session_id: sessionId,
|
|
5297
|
+
cwd,
|
|
5298
|
+
project_key: projectKey ?? void 0
|
|
4293
5299
|
});
|
|
4294
|
-
|
|
4295
|
-
|
|
4296
|
-
|
|
4297
|
-
|
|
5300
|
+
process.stderr.write(
|
|
5301
|
+
"[maind] guard: briefing fetch failed and no cache \u2014 session starts unbriefed; the model should call get_session_briefing itself.\n"
|
|
5302
|
+
);
|
|
5303
|
+
return 0;
|
|
4298
5304
|
}
|
|
4299
|
-
|
|
5305
|
+
process.stdout.write(formatInjection(result.text, result.via));
|
|
5306
|
+
await saveGuardSession(sessionId, { ...state, injected: true });
|
|
5307
|
+
await appendGuardEvent({
|
|
5308
|
+
event: "inject_ok",
|
|
5309
|
+
session_id: sessionId,
|
|
5310
|
+
cwd,
|
|
5311
|
+
project_key: projectKey ?? void 0,
|
|
5312
|
+
detail: result.via
|
|
5313
|
+
});
|
|
5314
|
+
return 0;
|
|
4300
5315
|
} catch {
|
|
4301
|
-
return
|
|
5316
|
+
return 0;
|
|
4302
5317
|
}
|
|
4303
5318
|
}
|
|
4304
|
-
function
|
|
4305
|
-
const
|
|
4306
|
-
|
|
5319
|
+
function formatInjection(text, via) {
|
|
5320
|
+
const staleNote = via === "stale-cache" ? " \u2014 served from local cache, server unreachable" : "";
|
|
5321
|
+
let body = text;
|
|
5322
|
+
if (Buffer.byteLength(body, "utf8") > MAX_INJECT_BYTES) {
|
|
5323
|
+
body = body.slice(0, MAX_INJECT_BYTES) + "\n\u2026 [maind guard: briefing truncated at 10KB]";
|
|
5324
|
+
}
|
|
5325
|
+
return `[maind guard] Session briefing, injected deterministically (ADR-284)${staleNote} \u2014 the session-start get_session_briefing consultation is satisfied by this block:
|
|
5326
|
+
|
|
5327
|
+
` + body + "\n";
|
|
4307
5328
|
}
|
|
4308
|
-
async function
|
|
4309
|
-
|
|
4310
|
-
|
|
4311
|
-
|
|
4312
|
-
|
|
4313
|
-
|
|
4314
|
-
|
|
4315
|
-
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
5329
|
+
async function readCache(file) {
|
|
5330
|
+
try {
|
|
5331
|
+
if (!existsSync14(file)) return null;
|
|
5332
|
+
const parsed = JSON.parse(await readFile4(file, "utf8"));
|
|
5333
|
+
if (typeof parsed.fetched_at !== "string" || typeof parsed.text !== "string") return null;
|
|
5334
|
+
if (Number.isNaN(Date.parse(parsed.fetched_at))) return null;
|
|
5335
|
+
return {
|
|
5336
|
+
fetched_at: parsed.fetched_at,
|
|
5337
|
+
project_key: typeof parsed.project_key === "string" ? parsed.project_key : null,
|
|
5338
|
+
text: parsed.text
|
|
5339
|
+
};
|
|
5340
|
+
} catch {
|
|
5341
|
+
return null;
|
|
5342
|
+
}
|
|
4321
5343
|
}
|
|
4322
|
-
async function
|
|
4323
|
-
|
|
4324
|
-
|
|
4325
|
-
|
|
4326
|
-
|
|
4327
|
-
|
|
4328
|
-
|
|
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
|
-
}
|
|
5344
|
+
async function writeCache(file, cache) {
|
|
5345
|
+
try {
|
|
5346
|
+
await mkdir5(dirname6(file), { recursive: true, mode: 448 });
|
|
5347
|
+
const tmp = `${file}.tmp`;
|
|
5348
|
+
await writeFile5(tmp, JSON.stringify(cache, null, 2), { mode: 384 });
|
|
5349
|
+
await rename4(tmp, file);
|
|
5350
|
+
} catch {
|
|
4355
5351
|
}
|
|
4356
|
-
await runSessionEndMetrics(sessionId);
|
|
4357
|
-
return 0;
|
|
4358
5352
|
}
|
|
4359
|
-
|
|
4360
|
-
|
|
4361
|
-
|
|
5353
|
+
function safeDeviceId() {
|
|
5354
|
+
try {
|
|
5355
|
+
return ensureDeviceId();
|
|
5356
|
+
} catch {
|
|
5357
|
+
return null;
|
|
5358
|
+
}
|
|
5359
|
+
}
|
|
5360
|
+
var BRIEFING_CACHE_FILE, CACHE_TTL_MS, FETCH_BUDGET_MS, MAX_INJECT_BYTES;
|
|
5361
|
+
var init_inject = __esm({
|
|
5362
|
+
"src/guard/inject.ts"() {
|
|
4362
5363
|
"use strict";
|
|
4363
|
-
init_dist();
|
|
4364
|
-
init_bridge_config();
|
|
4365
5364
|
init_device_id();
|
|
4366
|
-
init_api();
|
|
4367
|
-
init_edit_guard();
|
|
4368
5365
|
init_hook_input();
|
|
4369
|
-
init_hooks2();
|
|
4370
|
-
init_presence();
|
|
4371
|
-
init_presence_snapshot();
|
|
4372
5366
|
init_project_key();
|
|
4373
5367
|
init_version();
|
|
4374
|
-
|
|
4375
|
-
|
|
5368
|
+
init_config();
|
|
5369
|
+
init_log();
|
|
5370
|
+
init_session_file();
|
|
5371
|
+
init_mcp_client();
|
|
5372
|
+
BRIEFING_CACHE_FILE = join20(GUARD_DIR, "briefing-cache.json");
|
|
5373
|
+
CACHE_TTL_MS = 12 * 60 * 60 * 1e3;
|
|
5374
|
+
FETCH_BUDGET_MS = 3e3;
|
|
5375
|
+
MAX_INJECT_BYTES = 10 * 1024;
|
|
5376
|
+
}
|
|
5377
|
+
});
|
|
5378
|
+
|
|
5379
|
+
// src/guard/gate.ts
|
|
5380
|
+
var gate_exports = {};
|
|
5381
|
+
__export(gate_exports, {
|
|
5382
|
+
decideGate: () => decideGate,
|
|
5383
|
+
runGuardGate: () => runGuardGate
|
|
5384
|
+
});
|
|
5385
|
+
function decideGate(input) {
|
|
5386
|
+
const { mode, session } = input;
|
|
5387
|
+
if (mode === "off") return { kind: "allow" };
|
|
5388
|
+
const consulted = session.injected === true || session.carryover === true || typeof session.override_reason === "string" || input.consulted;
|
|
5389
|
+
if (consulted) return { kind: "allow" };
|
|
5390
|
+
if (mode === "warn") {
|
|
5391
|
+
if (session.warned === true) return { kind: "allow" };
|
|
5392
|
+
return { kind: "warn", context: warnText(session) };
|
|
5393
|
+
}
|
|
5394
|
+
if ((session.deny_count ?? 0) >= DENY_CAP) {
|
|
5395
|
+
if (session.warned === true) return { kind: "allow" };
|
|
5396
|
+
return {
|
|
5397
|
+
kind: "warn",
|
|
5398
|
+
context: "[maind guard] Block-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. " + warnText(session)
|
|
5399
|
+
};
|
|
5400
|
+
}
|
|
5401
|
+
return { kind: "deny", reason: denyText(input.sessionId, session) };
|
|
5402
|
+
}
|
|
5403
|
+
function warnText(session) {
|
|
5404
|
+
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.";
|
|
5405
|
+
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.`;
|
|
5406
|
+
}
|
|
5407
|
+
function denyText(sessionId, session) {
|
|
5408
|
+
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";
|
|
5409
|
+
return `[maind guard | block] Edit denied \u2014 ${injectNote} (mandated by proc/maind-consultation-triggers). Two exits:
|
|
5410
|
+
1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
|
|
5411
|
+
2. Override (logged): run \`maind-mcp-bridge guard skip --session ${sessionId} --reason "<why consultation is unnecessary here>"\` and retry.
|
|
5412
|
+
After ${DENY_CAP} denies this gate downgrades itself to warn.`;
|
|
5413
|
+
}
|
|
5414
|
+
async function runGuardGate() {
|
|
5415
|
+
try {
|
|
5416
|
+
const guard = resolveGuardConfig();
|
|
5417
|
+
if (guard.mode === "off") return 0;
|
|
5418
|
+
const input = await readHookInput();
|
|
5419
|
+
const tool = (input.tool_name ?? "").toString();
|
|
5420
|
+
if (tool !== "Edit" && tool !== "Write") return 0;
|
|
5421
|
+
const sessionId = typeof input.session_id === "string" && input.session_id.trim().length > 0 ? input.session_id.trim() : null;
|
|
5422
|
+
if (sessionId === null) return 0;
|
|
5423
|
+
const session = await loadGuardSession(sessionId);
|
|
5424
|
+
const consulted = (await loadState()).guard_signals?.[sessionId]?.consulted_at !== void 0;
|
|
5425
|
+
const decision = decideGate({ mode: guard.mode, session, consulted, sessionId });
|
|
5426
|
+
const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
|
|
5427
|
+
const projectKey = computeProjectKey() ?? void 0;
|
|
5428
|
+
if (decision.kind === "deny") {
|
|
5429
|
+
process.stdout.write(denyPayload(decision.reason));
|
|
5430
|
+
await saveGuardSession(sessionId, {
|
|
5431
|
+
...session,
|
|
5432
|
+
deny_count: (session.deny_count ?? 0) + 1
|
|
5433
|
+
});
|
|
5434
|
+
await appendGuardEvent({
|
|
5435
|
+
event: "deny",
|
|
5436
|
+
session_id: sessionId,
|
|
5437
|
+
cwd,
|
|
5438
|
+
project_key: projectKey
|
|
5439
|
+
});
|
|
5440
|
+
return 0;
|
|
5441
|
+
}
|
|
5442
|
+
if (decision.kind === "warn") {
|
|
5443
|
+
process.stdout.write(advisoryPayload(decision.context));
|
|
5444
|
+
await saveGuardSession(sessionId, {
|
|
5445
|
+
...session,
|
|
5446
|
+
warned: true,
|
|
5447
|
+
edits_seen: (session.edits_seen ?? 0) + 1
|
|
5448
|
+
});
|
|
5449
|
+
await appendGuardEvent({
|
|
5450
|
+
event: "warn",
|
|
5451
|
+
session_id: sessionId,
|
|
5452
|
+
cwd,
|
|
5453
|
+
project_key: projectKey
|
|
5454
|
+
});
|
|
5455
|
+
return 0;
|
|
5456
|
+
}
|
|
5457
|
+
await saveGuardSession(sessionId, {
|
|
5458
|
+
...session,
|
|
5459
|
+
edits_seen: (session.edits_seen ?? 0) + 1
|
|
5460
|
+
});
|
|
5461
|
+
return 0;
|
|
5462
|
+
} catch {
|
|
5463
|
+
return 0;
|
|
5464
|
+
}
|
|
5465
|
+
}
|
|
5466
|
+
var DENY_CAP;
|
|
5467
|
+
var init_gate = __esm({
|
|
5468
|
+
"src/guard/gate.ts"() {
|
|
5469
|
+
"use strict";
|
|
5470
|
+
init_hook_input();
|
|
5471
|
+
init_payloads();
|
|
5472
|
+
init_state();
|
|
5473
|
+
init_project_key();
|
|
5474
|
+
init_config();
|
|
5475
|
+
init_log();
|
|
5476
|
+
init_session_file();
|
|
5477
|
+
DENY_CAP = 3;
|
|
5478
|
+
}
|
|
5479
|
+
});
|
|
5480
|
+
|
|
5481
|
+
// src/guard/stop.ts
|
|
5482
|
+
var stop_exports = {};
|
|
5483
|
+
__export(stop_exports, {
|
|
5484
|
+
decideStopGate: () => decideStopGate,
|
|
5485
|
+
runGuardStop: () => runGuardStop
|
|
5486
|
+
});
|
|
5487
|
+
function decideStopGate(input) {
|
|
5488
|
+
return {
|
|
5489
|
+
block: input.enabled && input.editsSeen > 0 && !input.reviewed && !input.stopHookActive && !input.alreadyBlocked
|
|
5490
|
+
};
|
|
5491
|
+
}
|
|
5492
|
+
async function runGuardStop() {
|
|
5493
|
+
try {
|
|
5494
|
+
const guard = resolveGuardConfig();
|
|
5495
|
+
if (guard.mode === "off" || !guard.stopGate) return 0;
|
|
5496
|
+
const input = await readHookInput();
|
|
5497
|
+
const sessionId = typeof input.session_id === "string" && input.session_id.trim().length > 0 ? input.session_id.trim() : null;
|
|
5498
|
+
if (sessionId === null) return 0;
|
|
5499
|
+
const session = await loadGuardSession(sessionId);
|
|
5500
|
+
const reviewed = (await loadState()).guard_signals?.[sessionId]?.reviewed_at !== void 0;
|
|
5501
|
+
const decision = decideStopGate({
|
|
5502
|
+
enabled: true,
|
|
5503
|
+
editsSeen: session.edits_seen ?? 0,
|
|
5504
|
+
reviewed,
|
|
5505
|
+
stopHookActive: input.stop_hook_active === true,
|
|
5506
|
+
alreadyBlocked: session.stop_blocked === true
|
|
5507
|
+
});
|
|
5508
|
+
if (!decision.block) return 0;
|
|
5509
|
+
process.stdout.write(JSON.stringify({ decision: "block", reason: STOP_REASON }));
|
|
5510
|
+
await saveGuardSession(sessionId, { ...session, stop_blocked: true });
|
|
5511
|
+
await appendGuardEvent({ event: "stop_block", session_id: sessionId });
|
|
5512
|
+
return 0;
|
|
5513
|
+
} catch {
|
|
5514
|
+
return 0;
|
|
5515
|
+
}
|
|
5516
|
+
}
|
|
5517
|
+
var STOP_REASON;
|
|
5518
|
+
var init_stop = __esm({
|
|
5519
|
+
"src/guard/stop.ts"() {
|
|
5520
|
+
"use strict";
|
|
5521
|
+
init_hook_input();
|
|
5522
|
+
init_state();
|
|
5523
|
+
init_config();
|
|
5524
|
+
init_log();
|
|
5525
|
+
init_session_file();
|
|
5526
|
+
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
5527
|
}
|
|
4377
5528
|
});
|
|
4378
5529
|
|
|
@@ -5519,109 +6670,46 @@ function getClientTargets(ctx) {
|
|
|
5519
6670
|
{
|
|
5520
6671
|
key: "windsurf",
|
|
5521
6672
|
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
|
-
}
|
|
6673
|
+
clientFamilyEnv: "windsurf",
|
|
6674
|
+
scope: "user",
|
|
6675
|
+
path: path3.join(ctx.homeDir, ".codeium", "windsurf", "mcp_config.json"),
|
|
6676
|
+
kind: "json"
|
|
6677
|
+
},
|
|
6678
|
+
{
|
|
6679
|
+
key: "codex-cli",
|
|
6680
|
+
label: "Codex CLI (~/.codex/config.toml)",
|
|
6681
|
+
clientFamilyEnv: "codex",
|
|
6682
|
+
scope: "user",
|
|
6683
|
+
path: path3.join(ctx.homeDir, ".codex", "config.toml"),
|
|
6684
|
+
kind: "toml"
|
|
5600
6685
|
}
|
|
5601
|
-
|
|
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));
|
|
6686
|
+
];
|
|
6687
|
+
return targets;
|
|
5611
6688
|
}
|
|
5612
|
-
function
|
|
5613
|
-
|
|
6689
|
+
function filterTargetsByFamily(targets, family) {
|
|
6690
|
+
if (family === null) return targets;
|
|
6691
|
+
return targets.filter((t) => t.clientFamilyEnv === family);
|
|
5614
6692
|
}
|
|
5615
|
-
function
|
|
5616
|
-
|
|
5617
|
-
|
|
5618
|
-
|
|
6693
|
+
function makeDefaultContext(args) {
|
|
6694
|
+
return {
|
|
6695
|
+
projectRoot: args.projectRoot,
|
|
6696
|
+
homeDir: args.homeDir,
|
|
6697
|
+
platform: args.platform,
|
|
6698
|
+
xdgConfigHome: nonEmpty(args.env.XDG_CONFIG_HOME),
|
|
6699
|
+
appData: nonEmpty(args.env.APPDATA)
|
|
6700
|
+
};
|
|
5619
6701
|
}
|
|
5620
|
-
function
|
|
5621
|
-
|
|
6702
|
+
function nonEmpty(v) {
|
|
6703
|
+
if (v === void 0) return null;
|
|
6704
|
+
const trimmed = v.trim();
|
|
6705
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
5622
6706
|
}
|
|
5623
6707
|
|
|
6708
|
+
// src/install/index.ts
|
|
6709
|
+
init_bridge_entry();
|
|
6710
|
+
|
|
5624
6711
|
// src/install/json-merge.ts
|
|
6712
|
+
init_atomic_write();
|
|
5625
6713
|
var MAIND_SERVER_KEY = "maind";
|
|
5626
6714
|
async function mergeJsonConfig(target, serverEntry, dryRun = false) {
|
|
5627
6715
|
if (target.kind !== "json") {
|
|
@@ -5752,6 +6840,7 @@ function failed(target, phase, err) {
|
|
|
5752
6840
|
}
|
|
5753
6841
|
|
|
5754
6842
|
// src/install/toml-merge.ts
|
|
6843
|
+
init_atomic_write();
|
|
5755
6844
|
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
|
|
5756
6845
|
async function mergeTomlConfig(target, serverEntry, dryRun = false) {
|
|
5757
6846
|
if (target.kind !== "toml") {
|
|
@@ -6578,6 +7667,7 @@ const tools = await mcp.getTools();
|
|
|
6578
7667
|
var SNIPPET_TEMPLATES = buildSnippetTemplates(DEFAULT_MCP_ENDPOINT);
|
|
6579
7668
|
|
|
6580
7669
|
// src/install/preamble.ts
|
|
7670
|
+
init_atomic_write();
|
|
6581
7671
|
var PREAMBLE_HEADER_PREFIX = "## maind MCP integration";
|
|
6582
7672
|
function buildPreambleTargets(ctx) {
|
|
6583
7673
|
return [
|
|
@@ -6670,211 +7760,12 @@ function ensureTrailingBlankLine(content) {
|
|
|
6670
7760
|
return content + "\n\n";
|
|
6671
7761
|
}
|
|
6672
7762
|
|
|
6673
|
-
// src/install/
|
|
6674
|
-
|
|
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
|
-
}
|
|
7763
|
+
// src/install/index.ts
|
|
7764
|
+
init_hook_merge();
|
|
6875
7765
|
|
|
6876
7766
|
// src/install/working-paths-consent.ts
|
|
6877
7767
|
init_bridge_config();
|
|
7768
|
+
init_atomic_write();
|
|
6878
7769
|
import * as readline3 from "node:readline";
|
|
6879
7770
|
var TARGET_KEY = "config:auto_working_paths";
|
|
6880
7771
|
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 +9490,18 @@ async function dispatchLocalTool(engine, name, args) {
|
|
|
8599
9490
|
dirs: Array.isArray(args.dirs) ? args.dirs.filter((d) => typeof d === "string") : void 0,
|
|
8600
9491
|
minFiles
|
|
8601
9492
|
});
|
|
8602
|
-
const
|
|
9493
|
+
const open2 = report.findings.filter((f) => f.status === "open");
|
|
8603
9494
|
const preexisting = report.findings.filter(
|
|
8604
9495
|
(f) => f.status === "info"
|
|
8605
9496
|
);
|
|
8606
9497
|
return {
|
|
8607
9498
|
ok: report.ok,
|
|
8608
|
-
open_count:
|
|
9499
|
+
open_count: open2.length,
|
|
8609
9500
|
preexisting_count: preexisting.length,
|
|
8610
9501
|
// Nur die blockierenden Findings vollständig; der Bestand als Zahl plus
|
|
8611
9502
|
// Nummern, damit ein Repo mit alten Doppelungen die Antwort nicht flutet
|
|
8612
9503
|
// und der Agent das Handlungsrelevante zuerst liest.
|
|
8613
|
-
findings:
|
|
9504
|
+
findings: open2,
|
|
8614
9505
|
preexisting: preexisting.map(
|
|
8615
9506
|
(f) => `${f.namespace.prefix}${f.number}`
|
|
8616
9507
|
),
|
|
@@ -8620,7 +9511,7 @@ async function dispatchLocalTool(engine, name, args) {
|
|
|
8620
9511
|
file_count: ns.fileCount
|
|
8621
9512
|
})),
|
|
8622
9513
|
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." : `${
|
|
9514
|
+
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
9515
|
};
|
|
8625
9516
|
}
|
|
8626
9517
|
case "codebase_search": {
|
|
@@ -9048,6 +9939,23 @@ async function main() {
|
|
|
9048
9939
|
const { runOnSessionEnd: runOnSessionEnd2 } = await Promise.resolve().then(() => (init_session_end(), session_end_exports));
|
|
9049
9940
|
process.exit(await runOnSessionEnd2());
|
|
9050
9941
|
}
|
|
9942
|
+
if (firstPositional === "guard") {
|
|
9943
|
+
const guardIndex = process.argv.indexOf("guard");
|
|
9944
|
+
const { runGuard: runGuard2 } = await Promise.resolve().then(() => (init_cli(), cli_exports));
|
|
9945
|
+
process.exit(await runGuard2(process.argv.slice(guardIndex + 1)));
|
|
9946
|
+
}
|
|
9947
|
+
if (firstPositional === "guard-inject") {
|
|
9948
|
+
const { runGuardInject: runGuardInject2 } = await Promise.resolve().then(() => (init_inject(), inject_exports));
|
|
9949
|
+
process.exit(await runGuardInject2());
|
|
9950
|
+
}
|
|
9951
|
+
if (firstPositional === "guard-gate") {
|
|
9952
|
+
const { runGuardGate: runGuardGate2 } = await Promise.resolve().then(() => (init_gate(), gate_exports));
|
|
9953
|
+
process.exit(await runGuardGate2());
|
|
9954
|
+
}
|
|
9955
|
+
if (firstPositional === "guard-stop") {
|
|
9956
|
+
const { runGuardStop: runGuardStop2 } = await Promise.resolve().then(() => (init_stop(), stop_exports));
|
|
9957
|
+
process.exit(await runGuardStop2());
|
|
9958
|
+
}
|
|
9051
9959
|
if (firstPositional !== void 0 && isHookSubcommand(firstPositional)) {
|
|
9052
9960
|
const hooks = await Promise.resolve().then(() => (init_hooks2(), hooks_exports));
|
|
9053
9961
|
const run = {
|
|
@@ -9179,6 +10087,13 @@ function printHelp() {
|
|
|
9179
10087
|
" flush post queued Tier-3 metrics now",
|
|
9180
10088
|
" status show pairing, queued metrics and active thresholds",
|
|
9181
10089
|
"",
|
|
10090
|
+
"Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:",
|
|
10091
|
+
" guard install wire the guard hook pack (consent per hook) + set mode",
|
|
10092
|
+
" guard status mode, guard-hook wiring, local enforcement-event counts",
|
|
10093
|
+
" guard mode <warn|block> | guard off | guard stop-gate <on|off>",
|
|
10094
|
+
' guard skip --session <id> --reason "\u2026" logged override (block-gate exit)',
|
|
10095
|
+
" (hook subcommands, wired by `guard install`: guard-inject, guard-gate, guard-stop)",
|
|
10096
|
+
"",
|
|
9182
10097
|
"Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent",
|
|
9183
10098
|
"Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.",
|
|
9184
10099
|
"",
|