@maind-dev/mcp-bridge 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.js +854 -60
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -10,37 +10,37 @@ var __export = (target, all) => {
|
|
|
10
10
|
};
|
|
11
11
|
|
|
12
12
|
// src/device-id.ts
|
|
13
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
|
|
13
|
+
import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2, chmodSync } from "node:fs";
|
|
14
14
|
import { homedir, hostname, platform, release } from "node:os";
|
|
15
15
|
import { randomUUID } from "node:crypto";
|
|
16
|
-
import { join } from "node:path";
|
|
16
|
+
import { join as join2 } from "node:path";
|
|
17
17
|
function configDir() {
|
|
18
18
|
const home = homedir();
|
|
19
19
|
const env = process.env;
|
|
20
20
|
if (platform() === "darwin") {
|
|
21
|
-
return
|
|
21
|
+
return join2(home, "Library", "Application Support", "maind");
|
|
22
22
|
}
|
|
23
23
|
if (platform() === "win32") {
|
|
24
|
-
const appdata = env.APPDATA && env.APPDATA.length > 0 ? env.APPDATA :
|
|
25
|
-
return
|
|
24
|
+
const appdata = env.APPDATA && env.APPDATA.length > 0 ? env.APPDATA : join2(home, "AppData", "Roaming");
|
|
25
|
+
return join2(appdata, "maind");
|
|
26
26
|
}
|
|
27
|
-
const xdg = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.length > 0 ? env.XDG_CONFIG_HOME :
|
|
28
|
-
return
|
|
27
|
+
const xdg = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.length > 0 ? env.XDG_CONFIG_HOME : join2(home, ".config");
|
|
28
|
+
return join2(xdg, "maind");
|
|
29
29
|
}
|
|
30
30
|
function ensureDir(path6) {
|
|
31
31
|
if (existsSync(path6)) return;
|
|
32
|
-
|
|
32
|
+
mkdirSync2(path6, { recursive: true, mode: 448 });
|
|
33
33
|
}
|
|
34
34
|
function ensureDeviceId() {
|
|
35
35
|
const dir = configDir();
|
|
36
36
|
ensureDir(dir);
|
|
37
|
-
const file =
|
|
37
|
+
const file = join2(dir, DEVICE_ID_FILE);
|
|
38
38
|
if (existsSync(file)) {
|
|
39
|
-
const stored =
|
|
39
|
+
const stored = readFileSync2(file, "utf8").trim();
|
|
40
40
|
if (isUuid(stored)) return stored;
|
|
41
41
|
}
|
|
42
42
|
const id = randomUUID();
|
|
43
|
-
|
|
43
|
+
writeFileSync2(file, id + "\n", { encoding: "utf8", mode: 384 });
|
|
44
44
|
try {
|
|
45
45
|
chmodSync(file, 384);
|
|
46
46
|
} catch {
|
|
@@ -51,13 +51,13 @@ function isUuid(s) {
|
|
|
51
51
|
return UUID_RE.test(s);
|
|
52
52
|
}
|
|
53
53
|
function apiKeyPath() {
|
|
54
|
-
return
|
|
54
|
+
return join2(configDir(), API_KEY_FILE);
|
|
55
55
|
}
|
|
56
56
|
function writeApiKey(key) {
|
|
57
57
|
const dir = configDir();
|
|
58
58
|
ensureDir(dir);
|
|
59
59
|
const file = apiKeyPath();
|
|
60
|
-
|
|
60
|
+
writeFileSync2(file, key + "\n", { encoding: "utf8", mode: 384 });
|
|
61
61
|
try {
|
|
62
62
|
chmodSync(file, 384);
|
|
63
63
|
} catch {
|
|
@@ -66,13 +66,13 @@ function writeApiKey(key) {
|
|
|
66
66
|
function readApiKey() {
|
|
67
67
|
const file = apiKeyPath();
|
|
68
68
|
if (!existsSync(file)) return null;
|
|
69
|
-
const raw =
|
|
69
|
+
const raw = readFileSync2(file, "utf8").trim();
|
|
70
70
|
return raw.length > 0 ? raw : null;
|
|
71
71
|
}
|
|
72
72
|
function clearApiKey() {
|
|
73
73
|
const file = apiKeyPath();
|
|
74
74
|
if (!existsSync(file)) return;
|
|
75
|
-
|
|
75
|
+
writeFileSync2(file, "", { encoding: "utf8", mode: 384 });
|
|
76
76
|
}
|
|
77
77
|
function clientMeta(version) {
|
|
78
78
|
return {
|
|
@@ -97,7 +97,7 @@ var BRIDGE_VERSION;
|
|
|
97
97
|
var init_version = __esm({
|
|
98
98
|
"src/version.ts"() {
|
|
99
99
|
"use strict";
|
|
100
|
-
BRIDGE_VERSION = "0.
|
|
100
|
+
BRIDGE_VERSION = "0.14.0";
|
|
101
101
|
}
|
|
102
102
|
});
|
|
103
103
|
|
|
@@ -150,7 +150,7 @@ var init_effort = __esm({
|
|
|
150
150
|
});
|
|
151
151
|
|
|
152
152
|
// ../../packages/claude-code-telemetry/dist/session-analysis.js
|
|
153
|
-
import { createReadStream, existsSync as
|
|
153
|
+
import { createReadStream, existsSync as existsSync4 } from "node:fs";
|
|
154
154
|
import { createInterface as createInterface4 } from "node:readline";
|
|
155
155
|
function num2(v) {
|
|
156
156
|
return typeof v === "number" && Number.isFinite(v) ? v : 0;
|
|
@@ -228,7 +228,7 @@ function emptyAnalysis(sessionId) {
|
|
|
228
228
|
}
|
|
229
229
|
async function analyzeSession(path6) {
|
|
230
230
|
const a = emptyAnalysis("");
|
|
231
|
-
if (!path6 || !
|
|
231
|
+
if (!path6 || !existsSync4(path6))
|
|
232
232
|
return a;
|
|
233
233
|
const reactions = [];
|
|
234
234
|
let effort = null;
|
|
@@ -400,13 +400,13 @@ var init_windows = __esm({
|
|
|
400
400
|
|
|
401
401
|
// ../../packages/claude-code-telemetry/dist/projects.js
|
|
402
402
|
import { homedir as homedir3 } from "node:os";
|
|
403
|
-
import { join as
|
|
403
|
+
import { join as join12 } from "node:path";
|
|
404
404
|
var HOME, DEFAULT_PROJECTS_DIR;
|
|
405
405
|
var init_projects = __esm({
|
|
406
406
|
"../../packages/claude-code-telemetry/dist/projects.js"() {
|
|
407
407
|
"use strict";
|
|
408
408
|
HOME = homedir3();
|
|
409
|
-
DEFAULT_PROJECTS_DIR =
|
|
409
|
+
DEFAULT_PROJECTS_DIR = join12(HOME, ".claude", "projects");
|
|
410
410
|
}
|
|
411
411
|
});
|
|
412
412
|
|
|
@@ -508,7 +508,7 @@ var init_session_end = __esm({
|
|
|
508
508
|
});
|
|
509
509
|
|
|
510
510
|
// src/index.ts
|
|
511
|
-
import { randomUUID as
|
|
511
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
512
512
|
|
|
513
513
|
// src/forward.ts
|
|
514
514
|
import { createInterface } from "node:readline";
|
|
@@ -577,6 +577,98 @@ function isRecord(v) {
|
|
|
577
577
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
578
578
|
}
|
|
579
579
|
|
|
580
|
+
// src/conventions-cache.ts
|
|
581
|
+
import { execFileSync } from "node:child_process";
|
|
582
|
+
import { createHash } from "node:crypto";
|
|
583
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
584
|
+
import { dirname, join } from "node:path";
|
|
585
|
+
var CACHE_VERSION = 1;
|
|
586
|
+
var CACHE_RELPATH = join(".maind", "conventions-cache.json");
|
|
587
|
+
function resolveRepoRoot(cwd = process.cwd()) {
|
|
588
|
+
try {
|
|
589
|
+
const top = execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
590
|
+
cwd,
|
|
591
|
+
encoding: "utf8",
|
|
592
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
593
|
+
timeout: 5e3
|
|
594
|
+
}).trim();
|
|
595
|
+
return top.length > 0 ? top : cwd;
|
|
596
|
+
} catch {
|
|
597
|
+
return cwd;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
function keyFingerprint(apiKey) {
|
|
601
|
+
return createHash("sha256").update(apiKey).digest("hex").slice(0, 16);
|
|
602
|
+
}
|
|
603
|
+
function cachePath(root) {
|
|
604
|
+
return join(root, CACHE_RELPATH);
|
|
605
|
+
}
|
|
606
|
+
function hasInstructions(result) {
|
|
607
|
+
return !!result && typeof result.instructions === "string" && result.instructions.trim().length > 0;
|
|
608
|
+
}
|
|
609
|
+
function writeConventionsCache(root, identity, result, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
610
|
+
try {
|
|
611
|
+
if (!hasInstructions(result)) return;
|
|
612
|
+
const payload = {
|
|
613
|
+
version: CACHE_VERSION,
|
|
614
|
+
cached_at: nowIso,
|
|
615
|
+
mcp_url: identity.mcpUrl,
|
|
616
|
+
key_fp: identity.keyFp,
|
|
617
|
+
result
|
|
618
|
+
};
|
|
619
|
+
const target = cachePath(root);
|
|
620
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
621
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
622
|
+
writeFileSync(tmp, JSON.stringify(payload, null, 2), "utf8");
|
|
623
|
+
renameSync(tmp, target);
|
|
624
|
+
} catch {
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
function readConventionsCache(root, identity) {
|
|
628
|
+
try {
|
|
629
|
+
const raw = readFileSync(cachePath(root), "utf8");
|
|
630
|
+
const parsed = JSON.parse(raw);
|
|
631
|
+
if (parsed.version !== CACHE_VERSION || parsed.mcp_url !== identity.mcpUrl || parsed.key_fp !== identity.keyFp || typeof parsed.cached_at !== "string" || !hasInstructions(parsed.result)) {
|
|
632
|
+
return null;
|
|
633
|
+
}
|
|
634
|
+
return {
|
|
635
|
+
version: CACHE_VERSION,
|
|
636
|
+
cached_at: parsed.cached_at,
|
|
637
|
+
mcp_url: parsed.mcp_url,
|
|
638
|
+
key_fp: parsed.key_fp,
|
|
639
|
+
result: parsed.result
|
|
640
|
+
};
|
|
641
|
+
} catch {
|
|
642
|
+
return null;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
function buildCachedInitializeResponse(id, cache, now = /* @__PURE__ */ new Date()) {
|
|
646
|
+
const marker = fallbackMarker(cache.cached_at, now);
|
|
647
|
+
const original = cache.result.instructions ?? "";
|
|
648
|
+
const result = {
|
|
649
|
+
...cache.result,
|
|
650
|
+
instructions: `${marker}
|
|
651
|
+
|
|
652
|
+
${original}`
|
|
653
|
+
};
|
|
654
|
+
return JSON.stringify({ jsonrpc: "2.0", id, result });
|
|
655
|
+
}
|
|
656
|
+
function fallbackMarker(cachedAt, now) {
|
|
657
|
+
return `NOTE (maind cache fallback): the maind MCP server was unreachable, so these project conventions were served from a local snapshot taken ${relativeAge(cachedAt, now)}. They may be stale, and maind tools are unavailable until the server is reachable again.`;
|
|
658
|
+
}
|
|
659
|
+
function relativeAge(cachedAt, now) {
|
|
660
|
+
const then = Date.parse(cachedAt);
|
|
661
|
+
if (Number.isNaN(then)) return "at an unknown time";
|
|
662
|
+
const ms = now.getTime() - then;
|
|
663
|
+
const mins = Math.floor(ms / 6e4);
|
|
664
|
+
if (mins < 1) return "just now";
|
|
665
|
+
if (mins < 60) return `${mins} minute${mins === 1 ? "" : "s"} ago`;
|
|
666
|
+
const hours = Math.floor(mins / 60);
|
|
667
|
+
if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
|
|
668
|
+
const days = Math.floor(hours / 24);
|
|
669
|
+
return `${days} day${days === 1 ? "" : "s"} ago`;
|
|
670
|
+
}
|
|
671
|
+
|
|
580
672
|
// src/forward.ts
|
|
581
673
|
var DEFAULT_MCP_URL = "https://mcp.maind.dev/mcp";
|
|
582
674
|
var BridgeReauthNeeded = class extends Error {
|
|
@@ -609,6 +701,11 @@ var Forwarder = class {
|
|
|
609
701
|
projectKey;
|
|
610
702
|
/** Local codebase-index tool router, or null when the feature is disabled. */
|
|
611
703
|
localRouter;
|
|
704
|
+
/** Auto-presence announcer (ADR-242), or null when disabled. */
|
|
705
|
+
presence;
|
|
706
|
+
/** Monotonic counter for presence-frame JSON-RPC ids (string-namespaced so
|
|
707
|
+
* they can never collide with the local client's numeric ids). */
|
|
708
|
+
presenceFrameId = 0;
|
|
612
709
|
/** Set by the first response that carries an Mcp-Session-Id header. */
|
|
613
710
|
sessionId = null;
|
|
614
711
|
/**
|
|
@@ -620,8 +717,20 @@ var Forwarder = class {
|
|
|
620
717
|
initFrame = null;
|
|
621
718
|
/** Set true once an unrecoverable auth condition is detected. */
|
|
622
719
|
terminated = false;
|
|
720
|
+
/**
|
|
721
|
+
* sha256 fingerprint of the api-key. Binds the conventions cache to this
|
|
722
|
+
* identity so a snapshot taken under a different key is never served (A5).
|
|
723
|
+
*/
|
|
724
|
+
keyFp;
|
|
725
|
+
/**
|
|
726
|
+
* Memoized repo root for `<root>/.maind/conventions-cache.json`. Resolved
|
|
727
|
+
* lazily on the first cache read/write (i.e. on initialize) so a plain
|
|
728
|
+
* session that never reaches that path pays no git subprocess at startup.
|
|
729
|
+
*/
|
|
730
|
+
repoRoot = null;
|
|
623
731
|
constructor(cfg) {
|
|
624
732
|
this.apiKey = cfg.apiKey;
|
|
733
|
+
this.keyFp = keyFingerprint(cfg.apiKey);
|
|
625
734
|
this.deviceId = cfg.deviceId;
|
|
626
735
|
this.bridgeVersion = cfg.bridgeVersion;
|
|
627
736
|
const rawFamily = cfg.clientFamily ?? process.env.MAIND_CLIENT_FAMILY ?? null;
|
|
@@ -633,6 +742,7 @@ var Forwarder = class {
|
|
|
633
742
|
const rawKey = (cfg.projectKey ?? null)?.trim().toLowerCase() ?? null;
|
|
634
743
|
this.projectKey = rawKey && /^[a-f0-9]{64}$/.test(rawKey) ? rawKey : null;
|
|
635
744
|
this.localRouter = cfg.localRouter ?? null;
|
|
745
|
+
this.presence = cfg.presence ?? null;
|
|
636
746
|
this.mcpUrl = cfg.mcpUrl ?? process.env.MAIND_MCP_URL ?? DEFAULT_MCP_URL;
|
|
637
747
|
}
|
|
638
748
|
/**
|
|
@@ -667,6 +777,9 @@ var Forwarder = class {
|
|
|
667
777
|
this.initFrame = frame;
|
|
668
778
|
}
|
|
669
779
|
const parsed = parseRpc(frame);
|
|
780
|
+
if (parsed?.method === "tools/call") {
|
|
781
|
+
this.presence?.onActivity();
|
|
782
|
+
}
|
|
670
783
|
if (this.localRouter && this.localRouter.handlesToolCall(parsed?.method, parsed?.params)) {
|
|
671
784
|
const out = await this.localRouter.handleToolCall(parsed?.id ?? null, parsed?.params);
|
|
672
785
|
process.stdout.write(out + "\n");
|
|
@@ -683,6 +796,7 @@ var Forwarder = class {
|
|
|
683
796
|
});
|
|
684
797
|
} catch (err) {
|
|
685
798
|
const id = tryExtractId(frame);
|
|
799
|
+
if (this.serveInitializeFromCache(frame, id)) return;
|
|
686
800
|
emitJsonRpcError(id, -32603, `bridge network error: ${stringifyErr(err)}`);
|
|
687
801
|
return;
|
|
688
802
|
}
|
|
@@ -711,6 +825,7 @@ var Forwarder = class {
|
|
|
711
825
|
if (!response.ok) {
|
|
712
826
|
const id = tryExtractId(frame);
|
|
713
827
|
const body = await response.text().catch(() => "");
|
|
828
|
+
if (this.serveInitializeFromCache(frame, id)) return;
|
|
714
829
|
emitJsonRpcError(
|
|
715
830
|
id,
|
|
716
831
|
-32603,
|
|
@@ -727,6 +842,15 @@ var Forwarder = class {
|
|
|
727
842
|
}
|
|
728
843
|
return;
|
|
729
844
|
}
|
|
845
|
+
if (isInitializeRequest(frame)) {
|
|
846
|
+
const body = contentType.startsWith("text/event-stream") ? await collectSseText(response) : await response.text();
|
|
847
|
+
this.cacheInitializeResult(body);
|
|
848
|
+
this.presence?.onSessionReady();
|
|
849
|
+
if (body.trim().length > 0) {
|
|
850
|
+
process.stdout.write(body + "\n");
|
|
851
|
+
}
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
730
854
|
if (contentType.startsWith("text/event-stream")) {
|
|
731
855
|
await pipeSseToStdout(response);
|
|
732
856
|
} else if (response.status === 202) {
|
|
@@ -755,6 +879,37 @@ var Forwarder = class {
|
|
|
755
879
|
const id = tryExtractId(frame);
|
|
756
880
|
emitJsonRpcError(id, -32001, `bridge auth error: ${body.slice(0, 200)}`);
|
|
757
881
|
}
|
|
882
|
+
/**
|
|
883
|
+
* Auto-presence transport (ADR-242): post a self-generated `tools/call` on
|
|
884
|
+
* the forwarder's EXISTING MCP session. The response is drained and NEVER
|
|
885
|
+
* written to stdout — the local client must not see frames it didn't send.
|
|
886
|
+
* String-namespaced ids keep the frame disjoint from the client's numeric
|
|
887
|
+
* JSON-RPC ids. Riding the shared session (instead of opening a second one)
|
|
888
|
+
* keeps the server's session accounting honest AND carries the detected
|
|
889
|
+
* client-family headers, so the announce row shows the real client.
|
|
890
|
+
* Throws on any failure — the announcer turns that into backoff, fail-open.
|
|
891
|
+
*/
|
|
892
|
+
async postPresenceToolCall(name, args) {
|
|
893
|
+
if (this.sessionId === null) {
|
|
894
|
+
throw new Error("presence: no MCP session established yet");
|
|
895
|
+
}
|
|
896
|
+
this.presenceFrameId += 1;
|
|
897
|
+
const frame = JSON.stringify({
|
|
898
|
+
jsonrpc: "2.0",
|
|
899
|
+
id: `maind-presence-${this.presenceFrameId}`,
|
|
900
|
+
method: "tools/call",
|
|
901
|
+
params: { name, arguments: args }
|
|
902
|
+
});
|
|
903
|
+
const response = await fetch(this.mcpUrl, {
|
|
904
|
+
method: "POST",
|
|
905
|
+
headers: this.buildHeaders(true),
|
|
906
|
+
body: frame
|
|
907
|
+
});
|
|
908
|
+
await response.text().catch(() => "");
|
|
909
|
+
if (!response.ok) {
|
|
910
|
+
throw new Error(`presence: upstream HTTP ${response.status}`);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
758
913
|
/**
|
|
759
914
|
* Build the outbound header set. `includeSession` attaches the current
|
|
760
915
|
* Mcp-Session-Id (when set) — pass false for the recovery initialize, which
|
|
@@ -823,6 +978,53 @@ var Forwarder = class {
|
|
|
823
978
|
}
|
|
824
979
|
return true;
|
|
825
980
|
}
|
|
981
|
+
/**
|
|
982
|
+
* Repo root for the conventions cache, memoized. The first call resolves it
|
|
983
|
+
* via `git rev-parse` (once per session, on initialize) — plain sessions that
|
|
984
|
+
* never hit the cache path pay nothing at startup.
|
|
985
|
+
*/
|
|
986
|
+
getRepoRoot() {
|
|
987
|
+
if (this.repoRoot === null) this.repoRoot = resolveRepoRoot();
|
|
988
|
+
return this.repoRoot;
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* Snapshot a successful initialize response's conventions block to the local
|
|
992
|
+
* cache. Fully isolated and best-effort — any parse/IO failure is swallowed
|
|
993
|
+
* so caching never disturbs a live session (mirrors augmentToolsList).
|
|
994
|
+
*/
|
|
995
|
+
cacheInitializeResult(body) {
|
|
996
|
+
try {
|
|
997
|
+
const msg = JSON.parse(body);
|
|
998
|
+
if (msg && msg.result) {
|
|
999
|
+
writeConventionsCache(
|
|
1000
|
+
this.getRepoRoot(),
|
|
1001
|
+
{ mcpUrl: this.mcpUrl, keyFp: this.keyFp },
|
|
1002
|
+
msg.result
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
} catch {
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* On an initialize that couldn't reach the server, serve the last-good
|
|
1010
|
+
* conventions block from the local cache instead of a hard error, so the
|
|
1011
|
+
* enforcement surface survives an outage (A5). Returns true iff it emitted a
|
|
1012
|
+
* cached response. Non-initialize frames and a missing/mismatched cache
|
|
1013
|
+
* return false — the caller then emits its normal JSON-RPC error.
|
|
1014
|
+
*/
|
|
1015
|
+
serveInitializeFromCache(frame, id) {
|
|
1016
|
+
if (!isInitializeRequest(frame)) return false;
|
|
1017
|
+
const cache = readConventionsCache(this.getRepoRoot(), {
|
|
1018
|
+
mcpUrl: this.mcpUrl,
|
|
1019
|
+
keyFp: this.keyFp
|
|
1020
|
+
});
|
|
1021
|
+
if (cache === null) return false;
|
|
1022
|
+
process.stdout.write(buildCachedInitializeResponse(id, cache) + "\n");
|
|
1023
|
+
console.error(
|
|
1024
|
+
`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${cachePath(this.getRepoRoot())} (snapshot ${cache.cached_at})`
|
|
1025
|
+
);
|
|
1026
|
+
return true;
|
|
1027
|
+
}
|
|
826
1028
|
};
|
|
827
1029
|
function normalizeClientFamily(raw) {
|
|
828
1030
|
if (raw === null) return null;
|
|
@@ -1107,10 +1309,10 @@ async function openExternalBrowser(url) {
|
|
|
1107
1309
|
init_version();
|
|
1108
1310
|
|
|
1109
1311
|
// src/project-key.ts
|
|
1110
|
-
import { execFileSync } from "node:child_process";
|
|
1111
|
-
import { createHash } from "node:crypto";
|
|
1312
|
+
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
1313
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1112
1314
|
function sha256Hex(input) {
|
|
1113
|
-
return
|
|
1315
|
+
return createHash2("sha256").update(input).digest("hex");
|
|
1114
1316
|
}
|
|
1115
1317
|
function normalizeRemoteUrl(raw) {
|
|
1116
1318
|
let s = raw.trim();
|
|
@@ -1138,7 +1340,7 @@ function computeProjectKey() {
|
|
|
1138
1340
|
if (override && PROJECT_KEY_RE.test(override)) return override;
|
|
1139
1341
|
let remote;
|
|
1140
1342
|
try {
|
|
1141
|
-
remote =
|
|
1343
|
+
remote = execFileSync2("git", ["config", "--get", "remote.origin.url"], {
|
|
1142
1344
|
encoding: "utf8",
|
|
1143
1345
|
stdio: ["ignore", "pipe", "ignore"],
|
|
1144
1346
|
timeout: 5e3
|
|
@@ -3163,14 +3365,14 @@ Finished in ${wallClockSec}s. Restart your MCP client so it picks up the new ser
|
|
|
3163
3365
|
}
|
|
3164
3366
|
|
|
3165
3367
|
// src/local-tools/engine.ts
|
|
3166
|
-
import { execFileSync as
|
|
3368
|
+
import { execFileSync as execFileSync5 } from "node:child_process";
|
|
3167
3369
|
|
|
3168
3370
|
// ../../packages/code-index/build/node.js
|
|
3169
|
-
import { mkdirSync as
|
|
3170
|
-
import { posix as
|
|
3371
|
+
import { mkdirSync as mkdirSync3 } from "node:fs";
|
|
3372
|
+
import { posix as posix5 } from "node:path";
|
|
3171
3373
|
|
|
3172
3374
|
// ../../packages/code-index/build/parse/tree-sitter/parser.js
|
|
3173
|
-
import { join as
|
|
3375
|
+
import { join as join9 } from "node:path";
|
|
3174
3376
|
import Parser from "web-tree-sitter";
|
|
3175
3377
|
|
|
3176
3378
|
// ../../packages/code-index/build/parse/keys.js
|
|
@@ -3492,7 +3694,7 @@ function stripQuotes(s) {
|
|
|
3492
3694
|
|
|
3493
3695
|
// ../../packages/code-index/build/parse/tree-sitter/grammars.js
|
|
3494
3696
|
import { createRequire } from "node:module";
|
|
3495
|
-
import { join as
|
|
3697
|
+
import { join as join8 } from "node:path";
|
|
3496
3698
|
var GRAMMAR_FILE = {
|
|
3497
3699
|
typescript: "tree-sitter-typescript.wasm",
|
|
3498
3700
|
tsx: "tree-sitter-tsx.wasm",
|
|
@@ -3502,7 +3704,7 @@ var GRAMMAR_FILE = {
|
|
|
3502
3704
|
var CORE_WASM_FILE = "tree-sitter.wasm";
|
|
3503
3705
|
function grammarPath(language, assetDir) {
|
|
3504
3706
|
if (assetDir)
|
|
3505
|
-
return
|
|
3707
|
+
return join8(assetDir, GRAMMAR_FILE[language]);
|
|
3506
3708
|
return createRequire(import.meta.url).resolve(`tree-sitter-wasms/out/${GRAMMAR_FILE[language]}`);
|
|
3507
3709
|
}
|
|
3508
3710
|
|
|
@@ -3519,7 +3721,7 @@ var TreeSitterParser = class {
|
|
|
3519
3721
|
async init() {
|
|
3520
3722
|
if (this.initialized)
|
|
3521
3723
|
return;
|
|
3522
|
-
await Parser.init(this.assetDir ? { locateFile: (file) =>
|
|
3724
|
+
await Parser.init(this.assetDir ? { locateFile: (file) => join9(this.assetDir, file || CORE_WASM_FILE) } : void 0);
|
|
3523
3725
|
this.parser = new Parser();
|
|
3524
3726
|
this.initialized = true;
|
|
3525
3727
|
}
|
|
@@ -3574,8 +3776,8 @@ var TreeSitterParser = class {
|
|
|
3574
3776
|
};
|
|
3575
3777
|
|
|
3576
3778
|
// ../../packages/code-index/build/query/engine.js
|
|
3577
|
-
import { readFileSync as
|
|
3578
|
-
import { posix as
|
|
3779
|
+
import { readFileSync as readFileSync4 } from "node:fs";
|
|
3780
|
+
import { posix as posix4 } from "node:path";
|
|
3579
3781
|
|
|
3580
3782
|
// ../../packages/code-index/build/embed/recipe.js
|
|
3581
3783
|
var MAX_CHARS = 1e3;
|
|
@@ -3696,8 +3898,8 @@ function resolveImportTarget(fromFile, specifier, files) {
|
|
|
3696
3898
|
}
|
|
3697
3899
|
|
|
3698
3900
|
// ../../packages/code-index/build/incremental/discover.js
|
|
3699
|
-
import { execFileSync as
|
|
3700
|
-
import { createHash as
|
|
3901
|
+
import { execFileSync as execFileSync3 } from "node:child_process";
|
|
3902
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
3701
3903
|
import { readdirSync, statSync } from "node:fs";
|
|
3702
3904
|
import { posix as posix2, sep } from "node:path";
|
|
3703
3905
|
var IGNORE_DIRS = /* @__PURE__ */ new Set([
|
|
@@ -3717,7 +3919,7 @@ var IGNORE_DIRS = /* @__PURE__ */ new Set([
|
|
|
3717
3919
|
var GIT_CONFIG_PIN = ["-c", "diff.renames=true", "-c", "core.quotePath=false"];
|
|
3718
3920
|
function runGit(repoRoot, args) {
|
|
3719
3921
|
try {
|
|
3720
|
-
return
|
|
3922
|
+
return execFileSync3("git", [...GIT_CONFIG_PIN, ...args], {
|
|
3721
3923
|
cwd: repoRoot,
|
|
3722
3924
|
encoding: "utf8",
|
|
3723
3925
|
stdio: ["ignore", "pipe", "ignore"],
|
|
@@ -3855,7 +4057,7 @@ function statFile(repoRoot, relPath) {
|
|
|
3855
4057
|
}
|
|
3856
4058
|
}
|
|
3857
4059
|
function hashContent(content) {
|
|
3858
|
-
return
|
|
4060
|
+
return createHash3("sha256").update(content).digest("hex");
|
|
3859
4061
|
}
|
|
3860
4062
|
function headCommit(repoRoot) {
|
|
3861
4063
|
return git(repoRoot, ["rev-parse", "HEAD"])?.trim() ?? null;
|
|
@@ -4124,6 +4326,357 @@ function readFileHistory(repoRoot, paths, opts = {}) {
|
|
|
4124
4326
|
};
|
|
4125
4327
|
}
|
|
4126
4328
|
|
|
4329
|
+
// ../../packages/code-index/build/repo-health/divergence.js
|
|
4330
|
+
import { execFileSync as execFileSync4 } from "node:child_process";
|
|
4331
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
|
|
4332
|
+
import { posix as posix3 } from "node:path";
|
|
4333
|
+
var DEFAULT_WORKTREE_PROBE_PATHS = [
|
|
4334
|
+
"supabase/config.toml",
|
|
4335
|
+
"supabase/.temp",
|
|
4336
|
+
".env"
|
|
4337
|
+
];
|
|
4338
|
+
var WORKTREE_REQUIREMENTS_RELPATH = ".maind/worktree-requirements";
|
|
4339
|
+
function computeDivergence(facts) {
|
|
4340
|
+
const out = [];
|
|
4341
|
+
if (!facts.isRepo)
|
|
4342
|
+
return out;
|
|
4343
|
+
const onFeatureBranch = facts.branch != null && facts.defaultBranch != null && facts.branch !== facts.defaultBranch && !facts.detachedHead;
|
|
4344
|
+
if (facts.detachedHead) {
|
|
4345
|
+
out.push({
|
|
4346
|
+
id: "worktree.detached-head",
|
|
4347
|
+
status: "warn",
|
|
4348
|
+
scope: "worktree",
|
|
4349
|
+
title: "Detached HEAD",
|
|
4350
|
+
detail: "HEAD points at a commit, not a branch \u2014 commits here are easily lost.",
|
|
4351
|
+
hint: "git switch -c <branch> to keep this work, or checkout an existing branch."
|
|
4352
|
+
});
|
|
4353
|
+
}
|
|
4354
|
+
if (onFeatureBranch) {
|
|
4355
|
+
if (facts.upstream == null) {
|
|
4356
|
+
out.push({
|
|
4357
|
+
id: "branch.no-upstream",
|
|
4358
|
+
status: "open",
|
|
4359
|
+
scope: "branch",
|
|
4360
|
+
title: "No upstream set",
|
|
4361
|
+
detail: `'${facts.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,
|
|
4362
|
+
hint: `git push -u origin ${facts.branch}`
|
|
4363
|
+
});
|
|
4364
|
+
} else {
|
|
4365
|
+
const upstreamBranch = facts.upstream.split("/").slice(1).join("/");
|
|
4366
|
+
if (upstreamBranch && upstreamBranch !== facts.branch) {
|
|
4367
|
+
out.push({
|
|
4368
|
+
id: "branch.upstream-mismatch",
|
|
4369
|
+
status: "open",
|
|
4370
|
+
scope: "branch",
|
|
4371
|
+
title: "Upstream points at a different branch",
|
|
4372
|
+
detail: `'${facts.branch}' tracks '${facts.upstream}' \u2014 pushes land on the wrong remote branch silently.`,
|
|
4373
|
+
hint: `git branch --set-upstream-to=origin/${facts.branch} (then push -u)`
|
|
4374
|
+
});
|
|
4375
|
+
}
|
|
4376
|
+
if (facts.remoteTrackingExists === false) {
|
|
4377
|
+
out.push({
|
|
4378
|
+
id: "branch.unpushed-missing-remote",
|
|
4379
|
+
status: "open",
|
|
4380
|
+
scope: "branch",
|
|
4381
|
+
title: "Branch not on remote",
|
|
4382
|
+
detail: `'${facts.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,
|
|
4383
|
+
hint: `git push -u origin ${facts.branch}`
|
|
4384
|
+
});
|
|
4385
|
+
}
|
|
4386
|
+
}
|
|
4387
|
+
}
|
|
4388
|
+
const behind = facts.behind ?? 0;
|
|
4389
|
+
const ahead = facts.ahead ?? 0;
|
|
4390
|
+
if (behind > 0) {
|
|
4391
|
+
out.push({
|
|
4392
|
+
id: "branch.behind",
|
|
4393
|
+
status: "info",
|
|
4394
|
+
scope: "branch",
|
|
4395
|
+
title: "Behind base",
|
|
4396
|
+
detail: `${behind} commit(s) behind origin/${facts.defaultBranch}${ahead > 0 ? ` (and ${ahead} ahead)` : ""} \u2014 rebase/merge base before merging to avoid a stale PR.`,
|
|
4397
|
+
hint: `git fetch && git rebase origin/${facts.defaultBranch}`
|
|
4398
|
+
});
|
|
4399
|
+
}
|
|
4400
|
+
if (facts.upstream != null && facts.headMatchesUpstream === false) {
|
|
4401
|
+
out.push({
|
|
4402
|
+
id: "branch.unpushed-commits",
|
|
4403
|
+
status: "warn",
|
|
4404
|
+
scope: "branch",
|
|
4405
|
+
title: "Unpushed commits",
|
|
4406
|
+
detail: `Local HEAD is ahead of ${facts.upstream} \u2014 commits exist only on this machine.`,
|
|
4407
|
+
hint: "git push"
|
|
4408
|
+
});
|
|
4409
|
+
}
|
|
4410
|
+
if (facts.unmergedMigrations.length > 0) {
|
|
4411
|
+
const n = facts.unmergedMigrations.length;
|
|
4412
|
+
out.push({
|
|
4413
|
+
id: "branch.unmerged-migrations",
|
|
4414
|
+
status: "info",
|
|
4415
|
+
scope: "branch",
|
|
4416
|
+
title: "Migrations not yet on the base branch",
|
|
4417
|
+
detail: `${n} migration file(s) added on '${facts.branch}' are not on origin/${facts.defaultBranch} yet \u2014 a cloud DB push run from ${facts.defaultBranch} will NOT include them until this branch is merged.`,
|
|
4418
|
+
hint: `Merge to ${facts.defaultBranch} first (promote), then run 'supabase db push --linked' from ${facts.defaultBranch}.`
|
|
4419
|
+
});
|
|
4420
|
+
}
|
|
4421
|
+
if (facts.isSharedMainTree && facts.otherWorktrees > 0 && facts.uncommitted > 0 && !onFeatureBranch) {
|
|
4422
|
+
out.push({
|
|
4423
|
+
id: "worktree.direct-on-shared-base",
|
|
4424
|
+
status: "warn",
|
|
4425
|
+
scope: "worktree",
|
|
4426
|
+
title: "Uncommitted work on the shared base tree",
|
|
4427
|
+
detail: `You are editing the shared '${facts.defaultBranch}' checkout while ${facts.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,
|
|
4428
|
+
hint: "Move the work into a feature worktree (scripts/feature.sh start <name>)."
|
|
4429
|
+
});
|
|
4430
|
+
}
|
|
4431
|
+
if (facts.inProgressOp) {
|
|
4432
|
+
out.push({
|
|
4433
|
+
id: "worktree.in-progress-op",
|
|
4434
|
+
status: "warn",
|
|
4435
|
+
scope: "worktree",
|
|
4436
|
+
title: `${facts.inProgressOp} in progress`,
|
|
4437
|
+
detail: `A ${facts.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,
|
|
4438
|
+
hint: `git ${facts.inProgressOp} --continue | --abort`
|
|
4439
|
+
});
|
|
4440
|
+
}
|
|
4441
|
+
if (facts.worktreeParity && facts.worktreeParity.missing.length > 0) {
|
|
4442
|
+
const miss = facts.worktreeParity.missing;
|
|
4443
|
+
out.push({
|
|
4444
|
+
id: "worktree.parity-missing",
|
|
4445
|
+
status: "open",
|
|
4446
|
+
scope: "worktree",
|
|
4447
|
+
title: "Tooling files missing vs main checkout",
|
|
4448
|
+
detail: `${miss.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,
|
|
4449
|
+
hint: `Copy the missing file(s) from ${facts.worktreeParity.mainWorktreePath}, or declare them in ${WORKTREE_REQUIREMENTS_RELPATH}.`
|
|
4450
|
+
});
|
|
4451
|
+
}
|
|
4452
|
+
if (facts.release?.allRed) {
|
|
4453
|
+
out.push({
|
|
4454
|
+
id: "release.all-checks-red",
|
|
4455
|
+
status: "warn",
|
|
4456
|
+
scope: "release",
|
|
4457
|
+
title: "All checks failing \u2014 suspect account/billing/quota",
|
|
4458
|
+
detail: `All ${facts.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,
|
|
4459
|
+
hint: "Check the CI provider's billing/spending status before debugging code."
|
|
4460
|
+
});
|
|
4461
|
+
}
|
|
4462
|
+
return sortFindings(out);
|
|
4463
|
+
}
|
|
4464
|
+
var STATUS_ORDER = { open: 0, warn: 1, info: 2, passed: 3 };
|
|
4465
|
+
function sortFindings(f) {
|
|
4466
|
+
return [...f].sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status] || a.id.localeCompare(b.id));
|
|
4467
|
+
}
|
|
4468
|
+
function isHealthy(findings) {
|
|
4469
|
+
return !findings.some((x) => x.status === "open" || x.status === "warn");
|
|
4470
|
+
}
|
|
4471
|
+
function trimOrNull(s) {
|
|
4472
|
+
const t = s?.trim();
|
|
4473
|
+
return t ? t : null;
|
|
4474
|
+
}
|
|
4475
|
+
function resolveDefaultBranch(repoRoot) {
|
|
4476
|
+
const sym = trimOrNull(runGit(repoRoot, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]));
|
|
4477
|
+
if (sym) {
|
|
4478
|
+
const m = /refs\/remotes\/origin\/(.+)$/.exec(sym);
|
|
4479
|
+
if (m)
|
|
4480
|
+
return m[1];
|
|
4481
|
+
}
|
|
4482
|
+
for (const cand of ["main", "master"]) {
|
|
4483
|
+
if (runGit(repoRoot, ["rev-parse", "--verify", "--quiet", `origin/${cand}`]) !== null)
|
|
4484
|
+
return cand;
|
|
4485
|
+
}
|
|
4486
|
+
return null;
|
|
4487
|
+
}
|
|
4488
|
+
function detectInProgressOp(repoRoot) {
|
|
4489
|
+
const gitDir = trimOrNull(runGit(repoRoot, ["rev-parse", "--git-dir"]));
|
|
4490
|
+
if (!gitDir)
|
|
4491
|
+
return null;
|
|
4492
|
+
const base = posix3.isAbsolute(gitDir) ? gitDir : posix3.join(repoRoot, gitDir);
|
|
4493
|
+
if (existsSync2(posix3.join(base, "rebase-merge")) || existsSync2(posix3.join(base, "rebase-apply"))) {
|
|
4494
|
+
return "rebase";
|
|
4495
|
+
}
|
|
4496
|
+
if (existsSync2(posix3.join(base, "MERGE_HEAD")))
|
|
4497
|
+
return "merge";
|
|
4498
|
+
if (existsSync2(posix3.join(base, "CHERRY_PICK_HEAD")))
|
|
4499
|
+
return "cherry-pick";
|
|
4500
|
+
return null;
|
|
4501
|
+
}
|
|
4502
|
+
function parseWorktrees(raw) {
|
|
4503
|
+
const out = [];
|
|
4504
|
+
let cur = null;
|
|
4505
|
+
const flush = () => {
|
|
4506
|
+
if (cur?.path)
|
|
4507
|
+
out.push({ path: cur.path, branch: cur.branch, detached: cur.detached ?? false });
|
|
4508
|
+
};
|
|
4509
|
+
for (const line of raw.split("\n")) {
|
|
4510
|
+
if (line.startsWith("worktree ")) {
|
|
4511
|
+
flush();
|
|
4512
|
+
cur = { path: line.slice("worktree ".length).trim(), detached: false };
|
|
4513
|
+
} else if (!cur) {
|
|
4514
|
+
continue;
|
|
4515
|
+
} else if (line.startsWith("branch ")) {
|
|
4516
|
+
cur.branch = line.slice("branch ".length).trim().replace(/^refs\/heads\//, "");
|
|
4517
|
+
} else if (line.trim() === "detached") {
|
|
4518
|
+
cur.detached = true;
|
|
4519
|
+
}
|
|
4520
|
+
}
|
|
4521
|
+
flush();
|
|
4522
|
+
return out;
|
|
4523
|
+
}
|
|
4524
|
+
function readWorktreeRequirements(repoRoot) {
|
|
4525
|
+
const p = posix3.join(repoRoot, WORKTREE_REQUIREMENTS_RELPATH);
|
|
4526
|
+
if (!existsSync2(p))
|
|
4527
|
+
return [];
|
|
4528
|
+
try {
|
|
4529
|
+
return readFileSync3(p, "utf8").split("\n").map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("#"));
|
|
4530
|
+
} catch {
|
|
4531
|
+
return [];
|
|
4532
|
+
}
|
|
4533
|
+
}
|
|
4534
|
+
async function gatherRepoHealthFacts(repoRoot, opts = {}) {
|
|
4535
|
+
const inside = trimOrNull(runGit(repoRoot, ["rev-parse", "--is-inside-work-tree"]));
|
|
4536
|
+
if (inside !== "true") {
|
|
4537
|
+
return {
|
|
4538
|
+
isRepo: false,
|
|
4539
|
+
branch: null,
|
|
4540
|
+
defaultBranch: null,
|
|
4541
|
+
upstream: null,
|
|
4542
|
+
headMatchesUpstream: null,
|
|
4543
|
+
remoteTrackingExists: null,
|
|
4544
|
+
ahead: null,
|
|
4545
|
+
behind: null,
|
|
4546
|
+
uncommitted: 0,
|
|
4547
|
+
detachedHead: false,
|
|
4548
|
+
inProgressOp: null,
|
|
4549
|
+
isSharedMainTree: false,
|
|
4550
|
+
otherWorktrees: 0,
|
|
4551
|
+
worktreeParity: null,
|
|
4552
|
+
release: null,
|
|
4553
|
+
unmergedMigrations: []
|
|
4554
|
+
};
|
|
4555
|
+
}
|
|
4556
|
+
const branchRaw = trimOrNull(runGit(repoRoot, ["rev-parse", "--abbrev-ref", "HEAD"]));
|
|
4557
|
+
const detachedHead = branchRaw === "HEAD";
|
|
4558
|
+
const branch = detachedHead ? null : branchRaw;
|
|
4559
|
+
const defaultBranch = resolveDefaultBranch(repoRoot);
|
|
4560
|
+
const upstream = trimOrNull(runGit(repoRoot, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]));
|
|
4561
|
+
let headMatchesUpstream = null;
|
|
4562
|
+
let remoteTrackingExists = null;
|
|
4563
|
+
if (upstream) {
|
|
4564
|
+
const head = trimOrNull(runGit(repoRoot, ["rev-parse", "HEAD"]));
|
|
4565
|
+
const up = trimOrNull(runGit(repoRoot, ["rev-parse", "@{u}"]));
|
|
4566
|
+
headMatchesUpstream = head != null && up != null ? head === up : null;
|
|
4567
|
+
remoteTrackingExists = runGit(repoRoot, ["rev-parse", "--verify", "--quiet", `refs/remotes/${upstream}`]) !== null;
|
|
4568
|
+
}
|
|
4569
|
+
let ahead = null;
|
|
4570
|
+
let behind = null;
|
|
4571
|
+
if (defaultBranch) {
|
|
4572
|
+
const counts = trimOrNull(runGit(repoRoot, ["rev-list", "--left-right", "--count", `origin/${defaultBranch}...HEAD`]));
|
|
4573
|
+
if (counts) {
|
|
4574
|
+
const [b, a] = counts.split(/\s+/).map((n) => Number.parseInt(n, 10));
|
|
4575
|
+
if (Number.isFinite(b))
|
|
4576
|
+
behind = b;
|
|
4577
|
+
if (Number.isFinite(a))
|
|
4578
|
+
ahead = a;
|
|
4579
|
+
}
|
|
4580
|
+
}
|
|
4581
|
+
const porcelain = runGit(repoRoot, ["status", "--porcelain"]) ?? "";
|
|
4582
|
+
const uncommitted = porcelain.split("\n").filter((l) => l.trim().length > 0).length;
|
|
4583
|
+
const inProgressOp = detectInProgressOp(repoRoot);
|
|
4584
|
+
const toplevel = trimOrNull(runGit(repoRoot, ["rev-parse", "--show-toplevel"])) ?? repoRoot;
|
|
4585
|
+
const worktrees = parseWorktrees(runGit(repoRoot, ["worktree", "list", "--porcelain"]) ?? "");
|
|
4586
|
+
const mainWorktree = worktrees[0]?.path ?? null;
|
|
4587
|
+
const isSharedMainTree = mainWorktree != null && samePath(mainWorktree, toplevel);
|
|
4588
|
+
const otherWorktrees = Math.max(0, worktrees.length - 1);
|
|
4589
|
+
let worktreeParity = null;
|
|
4590
|
+
if (mainWorktree && !samePath(mainWorktree, toplevel)) {
|
|
4591
|
+
const probes = [
|
|
4592
|
+
...DEFAULT_WORKTREE_PROBE_PATHS,
|
|
4593
|
+
...readWorktreeRequirements(toplevel),
|
|
4594
|
+
...opts.probePaths ?? []
|
|
4595
|
+
];
|
|
4596
|
+
const missing = probes.filter((rel) => existsSync2(posix3.join(mainWorktree, rel)) && !existsSync2(posix3.join(toplevel, rel)));
|
|
4597
|
+
worktreeParity = {
|
|
4598
|
+
mainWorktreePath: mainWorktree,
|
|
4599
|
+
currentWorktreePath: toplevel,
|
|
4600
|
+
missing: [...new Set(missing)]
|
|
4601
|
+
};
|
|
4602
|
+
}
|
|
4603
|
+
const release2 = opts.includeRelease === false ? null : gatherReleaseFact(repoRoot, branch);
|
|
4604
|
+
let unmergedMigrations = [];
|
|
4605
|
+
if (defaultBranch) {
|
|
4606
|
+
const raw = runGit(repoRoot, [
|
|
4607
|
+
"diff",
|
|
4608
|
+
"--name-only",
|
|
4609
|
+
"--diff-filter=A",
|
|
4610
|
+
`origin/${defaultBranch}...HEAD`,
|
|
4611
|
+
"--",
|
|
4612
|
+
"*supabase/migrations/*.sql"
|
|
4613
|
+
]);
|
|
4614
|
+
unmergedMigrations = (raw ?? "").split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
|
|
4615
|
+
}
|
|
4616
|
+
return {
|
|
4617
|
+
isRepo: true,
|
|
4618
|
+
branch,
|
|
4619
|
+
defaultBranch,
|
|
4620
|
+
upstream,
|
|
4621
|
+
headMatchesUpstream,
|
|
4622
|
+
remoteTrackingExists,
|
|
4623
|
+
ahead,
|
|
4624
|
+
behind,
|
|
4625
|
+
uncommitted,
|
|
4626
|
+
detachedHead,
|
|
4627
|
+
inProgressOp,
|
|
4628
|
+
isSharedMainTree,
|
|
4629
|
+
otherWorktrees,
|
|
4630
|
+
worktreeParity,
|
|
4631
|
+
release: release2,
|
|
4632
|
+
unmergedMigrations
|
|
4633
|
+
};
|
|
4634
|
+
}
|
|
4635
|
+
function samePath(a, b) {
|
|
4636
|
+
const norm = (p) => p.replace(/\/+$/, "");
|
|
4637
|
+
return norm(a) === norm(b);
|
|
4638
|
+
}
|
|
4639
|
+
function gatherReleaseFact(repoRoot, branch) {
|
|
4640
|
+
if (!branch)
|
|
4641
|
+
return null;
|
|
4642
|
+
const raw = runGh(repoRoot, ["pr", "checks", branch, "--json", "bucket"]);
|
|
4643
|
+
if (raw == null)
|
|
4644
|
+
return null;
|
|
4645
|
+
let rows;
|
|
4646
|
+
try {
|
|
4647
|
+
rows = JSON.parse(raw);
|
|
4648
|
+
} catch {
|
|
4649
|
+
return null;
|
|
4650
|
+
}
|
|
4651
|
+
if (rows.length === 0)
|
|
4652
|
+
return { prNumber: null, totalChecks: 0, failedChecks: 0, allRed: false };
|
|
4653
|
+
const failed3 = rows.filter((r) => r.bucket === "fail").length;
|
|
4654
|
+
return {
|
|
4655
|
+
prNumber: null,
|
|
4656
|
+
totalChecks: rows.length,
|
|
4657
|
+
failedChecks: failed3,
|
|
4658
|
+
allRed: failed3 === rows.length && rows.length > 0
|
|
4659
|
+
};
|
|
4660
|
+
}
|
|
4661
|
+
function runGh(repoRoot, args) {
|
|
4662
|
+
try {
|
|
4663
|
+
return execFileSync4("gh", args, {
|
|
4664
|
+
cwd: repoRoot,
|
|
4665
|
+
encoding: "utf8",
|
|
4666
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
4667
|
+
timeout: 1e4,
|
|
4668
|
+
maxBuffer: 8 * 1024 * 1024
|
|
4669
|
+
});
|
|
4670
|
+
} catch {
|
|
4671
|
+
return null;
|
|
4672
|
+
}
|
|
4673
|
+
}
|
|
4674
|
+
async function checkDivergence(repoRoot, opts = {}) {
|
|
4675
|
+
const facts = await gatherRepoHealthFacts(repoRoot, opts);
|
|
4676
|
+
const findings = computeDivergence(facts);
|
|
4677
|
+
return { ok: isHealthy(findings), findings, facts };
|
|
4678
|
+
}
|
|
4679
|
+
|
|
4127
4680
|
// ../../packages/code-index/build/review/risk-rules.js
|
|
4128
4681
|
var RISK_RULES = [
|
|
4129
4682
|
{
|
|
@@ -4510,7 +5063,7 @@ var CodeIndexEngine = class {
|
|
|
4510
5063
|
return null;
|
|
4511
5064
|
let source = "";
|
|
4512
5065
|
try {
|
|
4513
|
-
const full =
|
|
5066
|
+
const full = readFileSync4(posix4.join(this.repoRoot, n.filePath), "utf8");
|
|
4514
5067
|
source = full.slice(n.startByte, n.endByte);
|
|
4515
5068
|
} catch {
|
|
4516
5069
|
return null;
|
|
@@ -4568,7 +5121,7 @@ var CodeIndexEngine = class {
|
|
|
4568
5121
|
async fileHistory(opts = {}) {
|
|
4569
5122
|
let paths = opts.paths ?? [];
|
|
4570
5123
|
if (paths.length === 0) {
|
|
4571
|
-
const changed = enumerateChangedPaths(this.repoRoot, {});
|
|
5124
|
+
const changed = enumerateChangedPaths(this.repoRoot, { since: opts.since });
|
|
4572
5125
|
if (changed === null) {
|
|
4573
5126
|
throw new Error("fileHistory requires a git repository (history is git-based)");
|
|
4574
5127
|
}
|
|
@@ -4578,6 +5131,9 @@ var CodeIndexEngine = class {
|
|
|
4578
5131
|
}
|
|
4579
5132
|
return readFileHistory(this.repoRoot, paths, opts);
|
|
4580
5133
|
}
|
|
5134
|
+
async checkDivergence(opts = {}) {
|
|
5135
|
+
return checkDivergence(this.repoRoot, opts);
|
|
5136
|
+
}
|
|
4581
5137
|
async reviewChanges(opts = {}) {
|
|
4582
5138
|
await this.store.init();
|
|
4583
5139
|
const rawPaths = enumerateChangedPaths(this.repoRoot, opts);
|
|
@@ -4641,7 +5197,7 @@ var CodeIndexEngine = class {
|
|
|
4641
5197
|
}
|
|
4642
5198
|
readRepoFile(relPath) {
|
|
4643
5199
|
try {
|
|
4644
|
-
return
|
|
5200
|
+
return readFileSync4(posix4.join(this.repoRoot, relPath), "utf8");
|
|
4645
5201
|
} catch {
|
|
4646
5202
|
return null;
|
|
4647
5203
|
}
|
|
@@ -4975,8 +5531,8 @@ var NodeSqliteStore = class {
|
|
|
4975
5531
|
// ../../packages/code-index/build/node.js
|
|
4976
5532
|
var DEFAULT_DB_RELPATH = ".maind/code-index.sqlite";
|
|
4977
5533
|
function createNodeCodeIndex(opts) {
|
|
4978
|
-
const dbPath = opts.dbPath ??
|
|
4979
|
-
|
|
5534
|
+
const dbPath = opts.dbPath ?? posix5.join(opts.repoRoot, DEFAULT_DB_RELPATH);
|
|
5535
|
+
mkdirSync3(posix5.dirname(dbPath), { recursive: true });
|
|
4980
5536
|
const store = new NodeSqliteStore(dbPath);
|
|
4981
5537
|
const parser = new TreeSitterParser();
|
|
4982
5538
|
return new CodeIndexEngine({
|
|
@@ -4988,9 +5544,9 @@ function createNodeCodeIndex(opts) {
|
|
|
4988
5544
|
}
|
|
4989
5545
|
|
|
4990
5546
|
// src/local-tools/engine.ts
|
|
4991
|
-
function
|
|
5547
|
+
function resolveRepoRoot2(cwd = process.cwd()) {
|
|
4992
5548
|
try {
|
|
4993
|
-
const top =
|
|
5549
|
+
const top = execFileSync5("git", ["rev-parse", "--show-toplevel"], {
|
|
4994
5550
|
cwd,
|
|
4995
5551
|
encoding: "utf8",
|
|
4996
5552
|
stdio: ["ignore", "pipe", "ignore"],
|
|
@@ -5002,12 +5558,12 @@ function resolveRepoRoot(cwd = process.cwd()) {
|
|
|
5002
5558
|
}
|
|
5003
5559
|
}
|
|
5004
5560
|
function defaultEngineFactory() {
|
|
5005
|
-
return createNodeCodeIndex({ repoRoot:
|
|
5561
|
+
return createNodeCodeIndex({ repoRoot: resolveRepoRoot2() });
|
|
5006
5562
|
}
|
|
5007
5563
|
|
|
5008
5564
|
// src/local-tools/savings.ts
|
|
5009
|
-
import { readFileSync as
|
|
5010
|
-
import { join as
|
|
5565
|
+
import { readFileSync as readFileSync5 } from "node:fs";
|
|
5566
|
+
import { join as join10 } from "node:path";
|
|
5011
5567
|
|
|
5012
5568
|
// src/local-tools/token-estimate.ts
|
|
5013
5569
|
var CHARS_PER_TOKEN = 4;
|
|
@@ -5039,7 +5595,7 @@ var SavingsAggregator = class {
|
|
|
5039
5595
|
};
|
|
5040
5596
|
function readFileCapped(absPath) {
|
|
5041
5597
|
try {
|
|
5042
|
-
const content =
|
|
5598
|
+
const content = readFileSync5(absPath, "utf8");
|
|
5043
5599
|
return content.length > MAX_FILE_BYTES ? content.slice(0, MAX_FILE_BYTES) : content;
|
|
5044
5600
|
} catch {
|
|
5045
5601
|
return "";
|
|
@@ -5062,14 +5618,14 @@ function measureLocalToolSaved(name, result, serialized, repoRoot) {
|
|
|
5062
5618
|
if (files.length === 0) return 0;
|
|
5063
5619
|
let wholeTokens = 0;
|
|
5064
5620
|
for (const fp of files) {
|
|
5065
|
-
wholeTokens += estimateTokens(readFileCapped(
|
|
5621
|
+
wholeTokens += estimateTokens(readFileCapped(join10(repoRoot, fp)));
|
|
5066
5622
|
}
|
|
5067
5623
|
return Math.max(0, wholeTokens - resultTokens);
|
|
5068
5624
|
}
|
|
5069
5625
|
if (name === "codebase_snippet") {
|
|
5070
5626
|
const fp = result?.filePath;
|
|
5071
5627
|
if (typeof fp !== "string" || fp.length === 0) return 0;
|
|
5072
|
-
const wholeTokens = estimateTokens(readFileCapped(
|
|
5628
|
+
const wholeTokens = estimateTokens(readFileCapped(join10(repoRoot, fp)));
|
|
5073
5629
|
return Math.max(0, wholeTokens - resultTokens);
|
|
5074
5630
|
}
|
|
5075
5631
|
return 0;
|
|
@@ -5079,14 +5635,14 @@ function measureLocalToolSaved(name, result, serialized, repoRoot) {
|
|
|
5079
5635
|
}
|
|
5080
5636
|
|
|
5081
5637
|
// src/local-tools/tools.ts
|
|
5082
|
-
import { createHash as
|
|
5638
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
5083
5639
|
|
|
5084
5640
|
// ../../packages/code-index/build/index.js
|
|
5085
5641
|
var CODE_INDEX_VERSION = "0.1.0";
|
|
5086
5642
|
|
|
5087
5643
|
// src/local-tools/tools.ts
|
|
5088
5644
|
function nodeKeyHash(nodeKey) {
|
|
5089
|
-
return
|
|
5645
|
+
return createHash4("sha256").update(nodeKey, "utf8").digest("hex");
|
|
5090
5646
|
}
|
|
5091
5647
|
var NODE_KINDS = [
|
|
5092
5648
|
"module",
|
|
@@ -5227,14 +5783,32 @@ var LOCAL_TOOLS = [
|
|
|
5227
5783
|
}
|
|
5228
5784
|
}
|
|
5229
5785
|
}
|
|
5786
|
+
},
|
|
5787
|
+
{
|
|
5788
|
+
name: "check_divergence",
|
|
5789
|
+
description: "Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, tooling files missing vs the main checkout so tools silently target the wrong project), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it.",
|
|
5790
|
+
inputSchema: {
|
|
5791
|
+
type: "object",
|
|
5792
|
+
properties: {
|
|
5793
|
+
include_release: {
|
|
5794
|
+
type: "boolean",
|
|
5795
|
+
description: "Query gh for the all-checks-red signal (default true). Set false for a fully offline check."
|
|
5796
|
+
},
|
|
5797
|
+
probe_paths: {
|
|
5798
|
+
type: "array",
|
|
5799
|
+
items: { type: "string" },
|
|
5800
|
+
description: "Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."
|
|
5801
|
+
}
|
|
5802
|
+
}
|
|
5803
|
+
}
|
|
5230
5804
|
}
|
|
5231
5805
|
];
|
|
5232
5806
|
var LOCAL_TOOL_NAMES = new Set(LOCAL_TOOLS.map((t) => t.name));
|
|
5233
5807
|
function str(v) {
|
|
5234
5808
|
return typeof v === "string" && v.length > 0 ? v : void 0;
|
|
5235
5809
|
}
|
|
5236
|
-
var
|
|
5237
|
-
function
|
|
5810
|
+
var HOT_FILE_RECENT_COMMITS2 = 10;
|
|
5811
|
+
function aggregateHistoryContext2(res, now = Date.now()) {
|
|
5238
5812
|
if (res.history.length === 0) return void 0;
|
|
5239
5813
|
const authorEmails = /* @__PURE__ */ new Set();
|
|
5240
5814
|
let hotFiles = 0;
|
|
@@ -5242,7 +5816,7 @@ function aggregateHistoryContext(res, now = Date.now()) {
|
|
|
5242
5816
|
let newestMs = 0;
|
|
5243
5817
|
for (const entry of res.history) {
|
|
5244
5818
|
const inWindow = entry.ownership?.commitsInWindow ?? entry.lastCommits.length;
|
|
5245
|
-
if (inWindow >=
|
|
5819
|
+
if (inWindow >= HOT_FILE_RECENT_COMMITS2) hotFiles++;
|
|
5246
5820
|
if (inWindow > maxRecent) maxRecent = inWindow;
|
|
5247
5821
|
for (const a of entry.ownership?.topAuthors ?? []) {
|
|
5248
5822
|
authorEmails.add(a.email.toLowerCase() || a.name);
|
|
@@ -5271,6 +5845,22 @@ async function dispatchLocalTool(engine, name, args) {
|
|
|
5271
5845
|
return engine.indexRepository({ full: args.full === true });
|
|
5272
5846
|
case "codebase_status":
|
|
5273
5847
|
return engine.status();
|
|
5848
|
+
case "check_divergence": {
|
|
5849
|
+
const report = await engine.checkDivergence({
|
|
5850
|
+
includeRelease: args.include_release !== false,
|
|
5851
|
+
probePaths: Array.isArray(args.probe_paths) ? args.probe_paths.filter((p) => typeof p === "string") : void 0
|
|
5852
|
+
});
|
|
5853
|
+
const openCount = report.findings.filter((f) => f.status === "open").length;
|
|
5854
|
+
const warnCount = report.findings.filter((f) => f.status === "warn").length;
|
|
5855
|
+
return {
|
|
5856
|
+
ok: report.ok,
|
|
5857
|
+
open_count: openCount,
|
|
5858
|
+
warn_count: warnCount,
|
|
5859
|
+
findings: report.findings,
|
|
5860
|
+
facts: report.facts,
|
|
5861
|
+
hint: report.ok ? "No silent divergence detected \u2014 safe to proceed." : `${openCount} blocking (open) + ${warnCount} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`
|
|
5862
|
+
};
|
|
5863
|
+
}
|
|
5274
5864
|
case "codebase_search": {
|
|
5275
5865
|
const query = str(args.query);
|
|
5276
5866
|
if (!query) throw new Error("codebase_search requires a 'query' string");
|
|
@@ -5339,7 +5929,7 @@ async function dispatchLocalTool(engine, name, args) {
|
|
|
5339
5929
|
let history;
|
|
5340
5930
|
if (args.include_history !== false) {
|
|
5341
5931
|
try {
|
|
5342
|
-
history =
|
|
5932
|
+
history = aggregateHistoryContext2(
|
|
5343
5933
|
await engine.fileHistory({ since: str(args.since), limit: 1 })
|
|
5344
5934
|
);
|
|
5345
5935
|
} catch {
|
|
@@ -5456,7 +6046,7 @@ var LocalToolRouter = class {
|
|
|
5456
6046
|
* @param resolveRoot repo-root resolver for the whole-file counterfactual
|
|
5457
6047
|
* (injectable in tests; defaults to the git top-level of cwd).
|
|
5458
6048
|
*/
|
|
5459
|
-
constructor(makeEngine = defaultEngineFactory, aggregator = null, resolveRoot =
|
|
6049
|
+
constructor(makeEngine = defaultEngineFactory, aggregator = null, resolveRoot = resolveRepoRoot2) {
|
|
5460
6050
|
this.makeEngine = makeEngine;
|
|
5461
6051
|
this.aggregator = aggregator;
|
|
5462
6052
|
this.resolveRoot = resolveRoot;
|
|
@@ -5596,6 +6186,182 @@ async function postSavingsMetric(input) {
|
|
|
5596
6186
|
}
|
|
5597
6187
|
}
|
|
5598
6188
|
|
|
6189
|
+
// src/presence.ts
|
|
6190
|
+
import { execFile } from "node:child_process";
|
|
6191
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
6192
|
+
|
|
6193
|
+
// src/bridge-config.ts
|
|
6194
|
+
init_device_id();
|
|
6195
|
+
import { existsSync as existsSync3, readFileSync as readFileSync6 } from "node:fs";
|
|
6196
|
+
import { join as join11 } from "node:path";
|
|
6197
|
+
function bridgeConfigPath() {
|
|
6198
|
+
return join11(configDir(), "config.json");
|
|
6199
|
+
}
|
|
6200
|
+
function readBridgeConfig() {
|
|
6201
|
+
try {
|
|
6202
|
+
const file = bridgeConfigPath();
|
|
6203
|
+
if (!existsSync3(file)) return null;
|
|
6204
|
+
const raw = JSON.parse(readFileSync6(file, "utf8"));
|
|
6205
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
6206
|
+
return null;
|
|
6207
|
+
}
|
|
6208
|
+
const o = raw;
|
|
6209
|
+
const config = {};
|
|
6210
|
+
if (typeof o.auto_announce === "boolean") {
|
|
6211
|
+
config.auto_announce = o.auto_announce;
|
|
6212
|
+
}
|
|
6213
|
+
if (typeof o.machine_label === "string") {
|
|
6214
|
+
config.machine_label = o.machine_label;
|
|
6215
|
+
}
|
|
6216
|
+
return config;
|
|
6217
|
+
} catch {
|
|
6218
|
+
return null;
|
|
6219
|
+
}
|
|
6220
|
+
}
|
|
6221
|
+
|
|
6222
|
+
// src/presence.ts
|
|
6223
|
+
var REFRESH_THROTTLE_MS = 45e3;
|
|
6224
|
+
var TTL_MINUTES = 120;
|
|
6225
|
+
var BACKOFF_BASE_MS = 3e4;
|
|
6226
|
+
var BACKOFF_CAP_MS = 15 * 6e4;
|
|
6227
|
+
var END_TIMEOUT_MS = 1500;
|
|
6228
|
+
var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6229
|
+
function resolveClientSessionId(env) {
|
|
6230
|
+
const fromEnv = (env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
|
|
6231
|
+
return UUID_RE2.test(fromEnv) ? fromEnv : randomUUID2();
|
|
6232
|
+
}
|
|
6233
|
+
function autoAnnounceDisabled(env, config) {
|
|
6234
|
+
const raw = (env.MAIND_AUTO_ANNOUNCE ?? "").trim().toLowerCase();
|
|
6235
|
+
if (raw === "off" || raw === "0" || raw === "false") return true;
|
|
6236
|
+
return config?.auto_announce === false;
|
|
6237
|
+
}
|
|
6238
|
+
var PresenceAnnouncer = class {
|
|
6239
|
+
projectKey;
|
|
6240
|
+
postToolCall;
|
|
6241
|
+
now;
|
|
6242
|
+
gitBranch;
|
|
6243
|
+
log;
|
|
6244
|
+
machineLabel;
|
|
6245
|
+
enabled;
|
|
6246
|
+
sessionId;
|
|
6247
|
+
lastAnnounceAt = 0;
|
|
6248
|
+
inFlight = false;
|
|
6249
|
+
consecutiveFailures = 0;
|
|
6250
|
+
nextAttemptAt = 0;
|
|
6251
|
+
ended = false;
|
|
6252
|
+
constructor(deps) {
|
|
6253
|
+
const env = deps.env ?? process.env;
|
|
6254
|
+
const config = (deps.readConfig ?? readBridgeConfig)();
|
|
6255
|
+
this.projectKey = deps.projectKey;
|
|
6256
|
+
this.postToolCall = deps.postToolCall;
|
|
6257
|
+
this.now = deps.now ?? Date.now;
|
|
6258
|
+
this.gitBranch = deps.gitBranch ?? defaultGitBranch;
|
|
6259
|
+
this.log = deps.log ?? ((msg) => process.stderr.write(msg + "\n"));
|
|
6260
|
+
this.machineLabel = normalizeMachineLabel(config?.machine_label);
|
|
6261
|
+
this.enabled = this.projectKey !== null && !autoAnnounceDisabled(env, config);
|
|
6262
|
+
this.sessionId = resolveClientSessionId(env);
|
|
6263
|
+
}
|
|
6264
|
+
get isEnabled() {
|
|
6265
|
+
return this.enabled;
|
|
6266
|
+
}
|
|
6267
|
+
/**
|
|
6268
|
+
* Called once the forwarder's MCP session is established (initialize
|
|
6269
|
+
* response captured). Fires the first announce — the session becomes visible
|
|
6270
|
+
* on /planning without any agent involvement (C1).
|
|
6271
|
+
*/
|
|
6272
|
+
onSessionReady() {
|
|
6273
|
+
if (!this.enabled || this.ended) return;
|
|
6274
|
+
if (this.lastAnnounceAt > 0) return;
|
|
6275
|
+
void this.announce("active");
|
|
6276
|
+
}
|
|
6277
|
+
/**
|
|
6278
|
+
* Called on every real tool-call passing through the bridge. Throttled
|
|
6279
|
+
* re-announce keeps the session fresh WHILE it is actually working; an idle
|
|
6280
|
+
* session stops refreshing and goes stale on the renderer — honest freshness.
|
|
6281
|
+
*/
|
|
6282
|
+
onActivity() {
|
|
6283
|
+
if (!this.enabled || this.ended) return;
|
|
6284
|
+
if (this.lastAnnounceAt === 0) return;
|
|
6285
|
+
if (this.now() - this.lastAnnounceAt < REFRESH_THROTTLE_MS) return;
|
|
6286
|
+
void this.announce("active");
|
|
6287
|
+
}
|
|
6288
|
+
/**
|
|
6289
|
+
* Best-effort `status:'ended'` on shutdown, bounded by END_TIMEOUT_MS so it
|
|
6290
|
+
* can never hold the process open. The server TTL is the fallback.
|
|
6291
|
+
*/
|
|
6292
|
+
async end() {
|
|
6293
|
+
if (!this.enabled || this.ended) return;
|
|
6294
|
+
this.ended = true;
|
|
6295
|
+
if (this.lastAnnounceAt === 0) return;
|
|
6296
|
+
const timeout = new Promise(
|
|
6297
|
+
(resolve2) => setTimeout(resolve2, END_TIMEOUT_MS).unref()
|
|
6298
|
+
);
|
|
6299
|
+
await Promise.race([this.send("ended"), timeout]);
|
|
6300
|
+
}
|
|
6301
|
+
async announce(status) {
|
|
6302
|
+
if (this.inFlight) return;
|
|
6303
|
+
if (this.now() < this.nextAttemptAt) return;
|
|
6304
|
+
this.inFlight = true;
|
|
6305
|
+
try {
|
|
6306
|
+
await this.send(status);
|
|
6307
|
+
if (this.consecutiveFailures > 0) {
|
|
6308
|
+
this.log("[maind-mcp-bridge] presence announce recovered.");
|
|
6309
|
+
}
|
|
6310
|
+
this.consecutiveFailures = 0;
|
|
6311
|
+
this.nextAttemptAt = 0;
|
|
6312
|
+
this.lastAnnounceAt = this.now();
|
|
6313
|
+
} catch (err) {
|
|
6314
|
+
this.consecutiveFailures += 1;
|
|
6315
|
+
const backoff = Math.min(
|
|
6316
|
+
BACKOFF_BASE_MS * 2 ** (this.consecutiveFailures - 1),
|
|
6317
|
+
BACKOFF_CAP_MS
|
|
6318
|
+
);
|
|
6319
|
+
this.nextAttemptAt = this.now() + backoff;
|
|
6320
|
+
if (this.consecutiveFailures === 1) {
|
|
6321
|
+
this.log(
|
|
6322
|
+
`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${err instanceof Error ? err.message : String(err)}`
|
|
6323
|
+
);
|
|
6324
|
+
}
|
|
6325
|
+
} finally {
|
|
6326
|
+
this.inFlight = false;
|
|
6327
|
+
}
|
|
6328
|
+
}
|
|
6329
|
+
async send(status) {
|
|
6330
|
+
if (this.projectKey === null) return;
|
|
6331
|
+
const args = {
|
|
6332
|
+
project_key: this.projectKey,
|
|
6333
|
+
session_id: this.sessionId,
|
|
6334
|
+
status,
|
|
6335
|
+
ttl_minutes: TTL_MINUTES
|
|
6336
|
+
};
|
|
6337
|
+
if (status === "active") {
|
|
6338
|
+
const branch = await this.gitBranch();
|
|
6339
|
+
if (branch) args.branch = branch;
|
|
6340
|
+
if (this.machineLabel) args.machine_label = this.machineLabel;
|
|
6341
|
+
}
|
|
6342
|
+
await this.postToolCall("announce_session", args);
|
|
6343
|
+
}
|
|
6344
|
+
};
|
|
6345
|
+
async function defaultGitBranch() {
|
|
6346
|
+
return await new Promise((resolve2) => {
|
|
6347
|
+
execFile(
|
|
6348
|
+
"git",
|
|
6349
|
+
["rev-parse", "--abbrev-ref", "HEAD"],
|
|
6350
|
+
{ timeout: 2e3, encoding: "utf8" },
|
|
6351
|
+
(err, stdout) => {
|
|
6352
|
+
if (err) return resolve2(null);
|
|
6353
|
+
const branch = stdout.trim();
|
|
6354
|
+
resolve2(branch.length > 0 && branch !== "HEAD" ? branch : null);
|
|
6355
|
+
}
|
|
6356
|
+
);
|
|
6357
|
+
});
|
|
6358
|
+
}
|
|
6359
|
+
function normalizeMachineLabel(raw) {
|
|
6360
|
+
if (typeof raw !== "string") return null;
|
|
6361
|
+
const v = raw.trim().slice(0, 100);
|
|
6362
|
+
return v.length > 0 ? v : null;
|
|
6363
|
+
}
|
|
6364
|
+
|
|
5599
6365
|
// src/index.ts
|
|
5600
6366
|
var MAX_REAUTH_ATTEMPTS = 1;
|
|
5601
6367
|
var SAVINGS_FLUSH_INTERVAL_MS = 6e4;
|
|
@@ -5662,7 +6428,7 @@ async function main() {
|
|
|
5662
6428
|
const savingsEnabled = process.env.MAIND_DISABLE_CODEBASE_TOOLS !== "1" && process.env.MAIND_DISABLE_SAVINGS_METRICS !== "1";
|
|
5663
6429
|
const aggregator = savingsEnabled ? new SavingsAggregator() : null;
|
|
5664
6430
|
const localRouter = process.env.MAIND_DISABLE_CODEBASE_TOOLS === "1" ? null : new LocalToolRouter(void 0, aggregator);
|
|
5665
|
-
const savingsSessionId = `bridge-${
|
|
6431
|
+
const savingsSessionId = `bridge-${randomUUID3()}`;
|
|
5666
6432
|
const flushSavings = async () => {
|
|
5667
6433
|
if (!aggregator) return;
|
|
5668
6434
|
const delta = aggregator.takePending();
|
|
@@ -5679,6 +6445,23 @@ async function main() {
|
|
|
5679
6445
|
void flushSavings();
|
|
5680
6446
|
}, SAVINGS_FLUSH_INTERVAL_MS) : null;
|
|
5681
6447
|
flushTimer?.unref();
|
|
6448
|
+
let currentForwarder = null;
|
|
6449
|
+
const presence = new PresenceAnnouncer({
|
|
6450
|
+
projectKey,
|
|
6451
|
+
postToolCall: (name, args) => {
|
|
6452
|
+
if (currentForwarder === null) {
|
|
6453
|
+
return Promise.reject(new Error("presence: no active forwarder"));
|
|
6454
|
+
}
|
|
6455
|
+
return currentForwarder.postPresenceToolCall(name, args);
|
|
6456
|
+
}
|
|
6457
|
+
});
|
|
6458
|
+
if (presence.isEnabled) {
|
|
6459
|
+
const endAndExit = (code) => {
|
|
6460
|
+
void presence.end().finally(() => process.exit(code));
|
|
6461
|
+
};
|
|
6462
|
+
process.on("SIGTERM", () => endAndExit(143));
|
|
6463
|
+
process.on("SIGINT", () => endAndExit(130));
|
|
6464
|
+
}
|
|
5682
6465
|
let attempts = 0;
|
|
5683
6466
|
try {
|
|
5684
6467
|
while (true) {
|
|
@@ -5687,8 +6470,10 @@ async function main() {
|
|
|
5687
6470
|
deviceId,
|
|
5688
6471
|
bridgeVersion: BRIDGE_VERSION,
|
|
5689
6472
|
projectKey,
|
|
5690
|
-
localRouter
|
|
6473
|
+
localRouter,
|
|
6474
|
+
presence
|
|
5691
6475
|
});
|
|
6476
|
+
currentForwarder = forwarder;
|
|
5692
6477
|
try {
|
|
5693
6478
|
await forwarder.run();
|
|
5694
6479
|
return;
|
|
@@ -5707,6 +6492,7 @@ async function main() {
|
|
|
5707
6492
|
}
|
|
5708
6493
|
} finally {
|
|
5709
6494
|
if (flushTimer) clearInterval(flushTimer);
|
|
6495
|
+
await presence.end();
|
|
5710
6496
|
await flushSavings();
|
|
5711
6497
|
}
|
|
5712
6498
|
}
|
|
@@ -5730,8 +6516,16 @@ function printHelp() {
|
|
|
5730
6516
|
" MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)",
|
|
5731
6517
|
" MAIND_CLIENT_VERSION Optional client version marker (max 64 chars)",
|
|
5732
6518
|
" MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth",
|
|
6519
|
+
" MAIND_AUTO_ANNOUNCE Set to 'off' to disable automatic presence announces (ADR-242)",
|
|
6520
|
+
" MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe",
|
|
5733
6521
|
" XDG_CONFIG_HOME Override config-dir parent on Linux/BSD",
|
|
5734
6522
|
"",
|
|
6523
|
+
"Auto-presence (ADR-242): the bridge announces this session on the repo's",
|
|
6524
|
+
"shared working tree (project_key hash + branch only \u2014 no hostname, no paths),",
|
|
6525
|
+
"refreshes while tools are actually called, and ends the row on exit.",
|
|
6526
|
+
"Persistent opt-out / explicit machine_label via config.json in the maind",
|
|
6527
|
+
'config dir: { "auto_announce": false, "machine_label": "my-box" }',
|
|
6528
|
+
"",
|
|
5735
6529
|
"Place this in your .mcp.json (or equivalent):",
|
|
5736
6530
|
"",
|
|
5737
6531
|
" {",
|