@maind-dev/mcp-bridge 0.23.0 → 0.25.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 +823 -145
- package/build/meta.json +1 -1
- package/package.json +16 -15
package/build/index.js
CHANGED
|
@@ -202,7 +202,57 @@ 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.25.0";
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// src/project-key.ts
|
|
210
|
+
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
211
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
212
|
+
function sha256Hex(input) {
|
|
213
|
+
return createHash2("sha256").update(input).digest("hex");
|
|
214
|
+
}
|
|
215
|
+
function normalizeRemoteUrl(raw) {
|
|
216
|
+
let s = raw.trim();
|
|
217
|
+
if (!s) return null;
|
|
218
|
+
const scheme = /^[a-z][a-z0-9+.-]*:\/\//i.exec(s);
|
|
219
|
+
if (scheme) {
|
|
220
|
+
s = s.slice(scheme[0].length);
|
|
221
|
+
s = s.replace(/^[^@/]+@/, "");
|
|
222
|
+
s = s.replace(/^([^/:]+):\d+(?=\/)/, "$1");
|
|
223
|
+
} else {
|
|
224
|
+
s = s.replace(/^[^@/]+@/, "");
|
|
225
|
+
const i = s.indexOf(":");
|
|
226
|
+
if (i >= 0) s = `${s.slice(0, i)}/${s.slice(i + 1)}`;
|
|
227
|
+
}
|
|
228
|
+
s = s.replace(/\.git$/i, "").replace(/\/+$/, "").toLowerCase();
|
|
229
|
+
return s.length > 0 ? s : null;
|
|
230
|
+
}
|
|
231
|
+
function projectKeyFromRemote(raw) {
|
|
232
|
+
const norm = normalizeRemoteUrl(raw);
|
|
233
|
+
return norm ? sha256Hex(norm) : null;
|
|
234
|
+
}
|
|
235
|
+
function computeProjectKey() {
|
|
236
|
+
const override = process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();
|
|
237
|
+
if (override && PROJECT_KEY_RE.test(override)) return override;
|
|
238
|
+
let remote;
|
|
239
|
+
try {
|
|
240
|
+
remote = execFileSync2("git", ["config", "--get", "remote.origin.url"], {
|
|
241
|
+
encoding: "utf8",
|
|
242
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
243
|
+
timeout: 5e3
|
|
244
|
+
}).trim();
|
|
245
|
+
} catch {
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
if (!remote) return null;
|
|
249
|
+
return projectKeyFromRemote(remote);
|
|
250
|
+
}
|
|
251
|
+
var PROJECT_KEY_RE;
|
|
252
|
+
var init_project_key = __esm({
|
|
253
|
+
"src/project-key.ts"() {
|
|
254
|
+
"use strict";
|
|
255
|
+
PROJECT_KEY_RE = /^[a-f0-9]{64}$/;
|
|
206
256
|
}
|
|
207
257
|
});
|
|
208
258
|
|
|
@@ -422,6 +472,14 @@ var init_hook_wiring = __esm({
|
|
|
422
472
|
matcher: "Write",
|
|
423
473
|
consentDescription: "It runs 'maind-mcp-bridge on-file-write' before the Write tool creates a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents, never any other tool's arguments \u2014 to check whether a numbered filename (ADR-262-\u2026, 0001-\u2026, RFC-12-\u2026) would claim a number a sibling branch or worktree already holds, and blocks that one Write while naming the next free number (ADR-263). Runs entirely on this machine (git + fs); nothing is uploaded. This is a SEPARATE hook from on-tool-use precisely because it reads an argument, which that one promises not to."
|
|
424
474
|
},
|
|
475
|
+
{
|
|
476
|
+
event: "PreToolUse",
|
|
477
|
+
subcommand: "on-file-edit",
|
|
478
|
+
label: "PreToolUse edit-guard hook",
|
|
479
|
+
timeout: 5,
|
|
480
|
+
matcher: "Edit|Write",
|
|
481
|
+
consentDescription: "It runs 'maind-mcp-bridge on-file-edit' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares it LOCALLY against the cached peer view from this machine's own presence announces (~/.maind/presence/): when another of your sessions holds a claim or works on the same directory, it INFORMS the agent with who/where/how-fresh. The path never leaves the machine; the hook never blocks a tool call (advisory only, ADR-277). This is a SEPARATE hook from on-file-write because that one's consent covers Write alone and may deny; this one covers Edit+Write and never does."
|
|
482
|
+
},
|
|
425
483
|
{
|
|
426
484
|
event: "Stop",
|
|
427
485
|
subcommand: "on-session-end",
|
|
@@ -1067,7 +1125,7 @@ var init_history = __esm({
|
|
|
1067
1125
|
|
|
1068
1126
|
// ../../packages/code-index/build/repo-health/divergence.js
|
|
1069
1127
|
import { execFileSync as execFileSync4 } from "node:child_process";
|
|
1070
|
-
import { existsSync as
|
|
1128
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
|
|
1071
1129
|
import { posix as posix3 } from "node:path";
|
|
1072
1130
|
function computeDivergence(facts) {
|
|
1073
1131
|
const out2 = [];
|
|
@@ -1222,12 +1280,12 @@ function detectInProgressOp(repoRoot) {
|
|
|
1222
1280
|
if (!gitDir)
|
|
1223
1281
|
return null;
|
|
1224
1282
|
const base = posix3.isAbsolute(gitDir) ? gitDir : posix3.join(repoRoot, gitDir);
|
|
1225
|
-
if (
|
|
1283
|
+
if (existsSync4(posix3.join(base, "rebase-merge")) || existsSync4(posix3.join(base, "rebase-apply"))) {
|
|
1226
1284
|
return "rebase";
|
|
1227
1285
|
}
|
|
1228
|
-
if (
|
|
1286
|
+
if (existsSync4(posix3.join(base, "MERGE_HEAD")))
|
|
1229
1287
|
return "merge";
|
|
1230
|
-
if (
|
|
1288
|
+
if (existsSync4(posix3.join(base, "CHERRY_PICK_HEAD")))
|
|
1231
1289
|
return "cherry-pick";
|
|
1232
1290
|
return null;
|
|
1233
1291
|
}
|
|
@@ -1255,10 +1313,10 @@ function parseWorktrees(raw) {
|
|
|
1255
1313
|
}
|
|
1256
1314
|
function readWorktreeRequirements(repoRoot) {
|
|
1257
1315
|
const p = posix3.join(repoRoot, WORKTREE_REQUIREMENTS_RELPATH);
|
|
1258
|
-
if (!
|
|
1316
|
+
if (!existsSync4(p))
|
|
1259
1317
|
return [];
|
|
1260
1318
|
try {
|
|
1261
|
-
return
|
|
1319
|
+
return readFileSync4(p, "utf8").split("\n").map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("#"));
|
|
1262
1320
|
} catch {
|
|
1263
1321
|
return [];
|
|
1264
1322
|
}
|
|
@@ -1325,7 +1383,7 @@ async function gatherRepoHealthFacts(repoRoot, opts = {}) {
|
|
|
1325
1383
|
...readWorktreeRequirements(toplevel),
|
|
1326
1384
|
...opts.probePaths ?? []
|
|
1327
1385
|
];
|
|
1328
|
-
const missing = probes.filter((rel) =>
|
|
1386
|
+
const missing = probes.filter((rel) => existsSync4(posix3.join(mainWorktree, rel)) && !existsSync4(posix3.join(toplevel, rel)));
|
|
1329
1387
|
worktreeParity = {
|
|
1330
1388
|
mainWorktreePath: mainWorktree,
|
|
1331
1389
|
currentWorktreePath: toplevel,
|
|
@@ -1424,7 +1482,7 @@ var init_divergence = __esm({
|
|
|
1424
1482
|
});
|
|
1425
1483
|
|
|
1426
1484
|
// ../../packages/code-index/build/repo-health/number-collisions.js
|
|
1427
|
-
import { existsSync as
|
|
1485
|
+
import { existsSync as existsSync5, readdirSync as readdirSync2 } from "node:fs";
|
|
1428
1486
|
import { posix as posix4 } from "node:path";
|
|
1429
1487
|
function isCounterNamespace(numbers, opts = {}) {
|
|
1430
1488
|
const minFiles = opts.minFiles ?? DEFAULT_MIN_FILES;
|
|
@@ -1628,7 +1686,7 @@ async function gatherNumberCollisionFacts(repoRoot, opts = {}) {
|
|
|
1628
1686
|
};
|
|
1629
1687
|
for (const dir of dirs) {
|
|
1630
1688
|
const abs = posix4.join(repoRoot, dir);
|
|
1631
|
-
if (!
|
|
1689
|
+
if (!existsSync5(abs))
|
|
1632
1690
|
continue;
|
|
1633
1691
|
try {
|
|
1634
1692
|
for (const file of readdirSync2(abs))
|
|
@@ -1655,11 +1713,11 @@ async function gatherNumberCollisionFacts(repoRoot, opts = {}) {
|
|
|
1655
1713
|
if (!line.startsWith("worktree "))
|
|
1656
1714
|
continue;
|
|
1657
1715
|
const root = line.slice("worktree ".length).trim();
|
|
1658
|
-
if (!root || root === selfRoot || !
|
|
1716
|
+
if (!root || root === selfRoot || !existsSync5(root))
|
|
1659
1717
|
continue;
|
|
1660
1718
|
for (const dir of dirs) {
|
|
1661
1719
|
const abs = posix4.join(root, dir);
|
|
1662
|
-
if (!
|
|
1720
|
+
if (!existsSync5(abs))
|
|
1663
1721
|
continue;
|
|
1664
1722
|
try {
|
|
1665
1723
|
for (const file of readdirSync2(abs)) {
|
|
@@ -1932,7 +1990,7 @@ var init_identifiers = __esm({
|
|
|
1932
1990
|
});
|
|
1933
1991
|
|
|
1934
1992
|
// ../../packages/code-index/build/query/engine.js
|
|
1935
|
-
import { readFileSync as
|
|
1993
|
+
import { readFileSync as readFileSync5 } from "node:fs";
|
|
1936
1994
|
import { posix as posix5 } from "node:path";
|
|
1937
1995
|
function toHit(n) {
|
|
1938
1996
|
return {
|
|
@@ -2214,7 +2272,7 @@ var init_engine = __esm({
|
|
|
2214
2272
|
return null;
|
|
2215
2273
|
let source = "";
|
|
2216
2274
|
try {
|
|
2217
|
-
const full =
|
|
2275
|
+
const full = readFileSync5(posix5.join(this.repoRoot, n.filePath), "utf8");
|
|
2218
2276
|
source = full.slice(n.startByte, n.endByte);
|
|
2219
2277
|
} catch {
|
|
2220
2278
|
return null;
|
|
@@ -2354,7 +2412,7 @@ var init_engine = __esm({
|
|
|
2354
2412
|
}
|
|
2355
2413
|
readRepoFile(relPath) {
|
|
2356
2414
|
try {
|
|
2357
|
-
return
|
|
2415
|
+
return readFileSync5(posix5.join(this.repoRoot, relPath), "utf8");
|
|
2358
2416
|
} catch {
|
|
2359
2417
|
return null;
|
|
2360
2418
|
}
|
|
@@ -2393,6 +2451,135 @@ var init_build = __esm({
|
|
|
2393
2451
|
}
|
|
2394
2452
|
});
|
|
2395
2453
|
|
|
2454
|
+
// src/presence-snapshot.ts
|
|
2455
|
+
import {
|
|
2456
|
+
mkdirSync as mkdirSync4,
|
|
2457
|
+
readdirSync as readdirSync3,
|
|
2458
|
+
readFileSync as readFileSync7,
|
|
2459
|
+
renameSync as renameSync2,
|
|
2460
|
+
statSync as statSync2,
|
|
2461
|
+
unlinkSync,
|
|
2462
|
+
writeFileSync as writeFileSync3
|
|
2463
|
+
} from "node:fs";
|
|
2464
|
+
import { homedir as homedir3 } from "node:os";
|
|
2465
|
+
import { join as join12 } from "node:path";
|
|
2466
|
+
function presenceSnapshotBaseDir() {
|
|
2467
|
+
return join12(homedir3(), ".maind", "presence");
|
|
2468
|
+
}
|
|
2469
|
+
function projectDir(baseDir, projectKey) {
|
|
2470
|
+
return join12(baseDir, projectKey);
|
|
2471
|
+
}
|
|
2472
|
+
function createSnapshotStore(opts) {
|
|
2473
|
+
const baseDir = opts.baseDir ?? presenceSnapshotBaseDir();
|
|
2474
|
+
const dir = projectDir(baseDir, opts.projectKey);
|
|
2475
|
+
const pid = opts.pid ?? process.pid;
|
|
2476
|
+
const ppid = opts.ppid ?? process.ppid;
|
|
2477
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
2478
|
+
const now = opts.now ?? Date.now;
|
|
2479
|
+
let ownFile = null;
|
|
2480
|
+
return {
|
|
2481
|
+
write(payload, meta) {
|
|
2482
|
+
try {
|
|
2483
|
+
if (typeof payload !== "object" || payload === null) return;
|
|
2484
|
+
const p = payload;
|
|
2485
|
+
if (p.ok !== true) return;
|
|
2486
|
+
const snapshot = {
|
|
2487
|
+
v: 1,
|
|
2488
|
+
written_at: new Date(now()).toISOString(),
|
|
2489
|
+
project_key: opts.projectKey,
|
|
2490
|
+
own_session_id: meta.sessionId,
|
|
2491
|
+
own_pid: pid,
|
|
2492
|
+
own_ppid: ppid,
|
|
2493
|
+
cwd,
|
|
2494
|
+
branch: meta.branch,
|
|
2495
|
+
peers: Array.isArray(p.peers) ? p.peers : [],
|
|
2496
|
+
conflicts: Array.isArray(p.conflicts) ? p.conflicts : []
|
|
2497
|
+
};
|
|
2498
|
+
mkdirSync4(dir, { recursive: true, mode: 448 });
|
|
2499
|
+
ownFile = join12(dir, `${meta.sessionId}.json`);
|
|
2500
|
+
const tmp = `${ownFile}.tmp-${pid}`;
|
|
2501
|
+
writeFileSync3(tmp, JSON.stringify(snapshot), { mode: 384 });
|
|
2502
|
+
renameSync2(tmp, ownFile);
|
|
2503
|
+
pruneStale(dir, now(), ownFile);
|
|
2504
|
+
} catch {
|
|
2505
|
+
}
|
|
2506
|
+
},
|
|
2507
|
+
endSession() {
|
|
2508
|
+
try {
|
|
2509
|
+
if (ownFile) unlinkSync(ownFile);
|
|
2510
|
+
} catch {
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
};
|
|
2514
|
+
}
|
|
2515
|
+
function pruneStale(dir, nowMs, keep) {
|
|
2516
|
+
try {
|
|
2517
|
+
for (const name of readdirSync3(dir)) {
|
|
2518
|
+
if (!name.endsWith(".json")) continue;
|
|
2519
|
+
const file = join12(dir, name);
|
|
2520
|
+
if (file === keep) continue;
|
|
2521
|
+
try {
|
|
2522
|
+
const age = nowMs - statSync2(file).mtimeMs;
|
|
2523
|
+
if (age > SNAPSHOT_TTL_MS) unlinkSync(file);
|
|
2524
|
+
} catch {
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
} catch {
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
function readSnapshots(projectKey, baseDir = presenceSnapshotBaseDir()) {
|
|
2531
|
+
try {
|
|
2532
|
+
const dir = projectDir(baseDir, projectKey);
|
|
2533
|
+
const out2 = [];
|
|
2534
|
+
for (const name of readdirSync3(dir)) {
|
|
2535
|
+
if (!name.endsWith(".json")) continue;
|
|
2536
|
+
try {
|
|
2537
|
+
const raw = JSON.parse(
|
|
2538
|
+
readFileSync7(join12(dir, name), "utf8")
|
|
2539
|
+
);
|
|
2540
|
+
const snap = parseSnapshot(raw);
|
|
2541
|
+
if (snap) out2.push(snap);
|
|
2542
|
+
} catch {
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
out2.sort((a, b) => b.written_at.localeCompare(a.written_at));
|
|
2546
|
+
return out2;
|
|
2547
|
+
} catch {
|
|
2548
|
+
return [];
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
function parseSnapshot(raw) {
|
|
2552
|
+
if (typeof raw !== "object" || raw === null) return null;
|
|
2553
|
+
const o = raw;
|
|
2554
|
+
if (o.v !== 1) return null;
|
|
2555
|
+
if (typeof o.written_at !== "string") return null;
|
|
2556
|
+
if (typeof o.project_key !== "string") return null;
|
|
2557
|
+
if (typeof o.own_session_id !== "string") return null;
|
|
2558
|
+
if (typeof o.own_pid !== "number" || typeof o.own_ppid !== "number") {
|
|
2559
|
+
return null;
|
|
2560
|
+
}
|
|
2561
|
+
if (typeof o.cwd !== "string") return null;
|
|
2562
|
+
return {
|
|
2563
|
+
v: 1,
|
|
2564
|
+
written_at: o.written_at,
|
|
2565
|
+
project_key: o.project_key,
|
|
2566
|
+
own_session_id: o.own_session_id,
|
|
2567
|
+
own_pid: o.own_pid,
|
|
2568
|
+
own_ppid: o.own_ppid,
|
|
2569
|
+
cwd: o.cwd,
|
|
2570
|
+
branch: typeof o.branch === "string" ? o.branch : null,
|
|
2571
|
+
peers: Array.isArray(o.peers) ? o.peers : [],
|
|
2572
|
+
conflicts: Array.isArray(o.conflicts) ? o.conflicts : []
|
|
2573
|
+
};
|
|
2574
|
+
}
|
|
2575
|
+
var SNAPSHOT_TTL_MS;
|
|
2576
|
+
var init_presence_snapshot = __esm({
|
|
2577
|
+
"src/presence-snapshot.ts"() {
|
|
2578
|
+
"use strict";
|
|
2579
|
+
SNAPSHOT_TTL_MS = 120 * 6e4;
|
|
2580
|
+
}
|
|
2581
|
+
});
|
|
2582
|
+
|
|
2396
2583
|
// ../../packages/claude-code-telemetry/dist/types.js
|
|
2397
2584
|
var init_types4 = __esm({
|
|
2398
2585
|
"../../packages/claude-code-telemetry/dist/types.js"() {
|
|
@@ -2403,7 +2590,7 @@ var init_types4 = __esm({
|
|
|
2403
2590
|
// ../../packages/claude-code-telemetry/dist/transcript.js
|
|
2404
2591
|
import { createReadStream, existsSync as existsSync6 } from "node:fs";
|
|
2405
2592
|
import { stat } from "node:fs/promises";
|
|
2406
|
-
import { createInterface as
|
|
2593
|
+
import { createInterface as createInterface5 } from "node:readline";
|
|
2407
2594
|
async function summariseTranscript(path8) {
|
|
2408
2595
|
if (!path8 || !existsSync6(path8))
|
|
2409
2596
|
return null;
|
|
@@ -2418,7 +2605,7 @@ async function summariseTranscript(path8) {
|
|
|
2418
2605
|
let lines2 = 0;
|
|
2419
2606
|
return await new Promise((resolve2) => {
|
|
2420
2607
|
const stream = createReadStream(path8, { encoding: "utf-8" });
|
|
2421
|
-
const rl =
|
|
2608
|
+
const rl = createInterface5({ input: stream });
|
|
2422
2609
|
rl.on("line", (line) => {
|
|
2423
2610
|
const trimmed = line.trim();
|
|
2424
2611
|
if (!trimmed)
|
|
@@ -2491,7 +2678,7 @@ var init_effort = __esm({
|
|
|
2491
2678
|
|
|
2492
2679
|
// ../../packages/claude-code-telemetry/dist/session-analysis.js
|
|
2493
2680
|
import { createReadStream as createReadStream2, existsSync as existsSync7 } from "node:fs";
|
|
2494
|
-
import { createInterface as
|
|
2681
|
+
import { createInterface as createInterface6 } from "node:readline";
|
|
2495
2682
|
function num2(v) {
|
|
2496
2683
|
return typeof v === "number" && Number.isFinite(v) ? v : 0;
|
|
2497
2684
|
}
|
|
@@ -2604,7 +2791,7 @@ async function analyzeSession(path8) {
|
|
|
2604
2791
|
let prevUserText = null;
|
|
2605
2792
|
await new Promise((resolve2) => {
|
|
2606
2793
|
const stream = createReadStream2(path8, { encoding: "utf-8" });
|
|
2607
|
-
const rl =
|
|
2794
|
+
const rl = createInterface6({ input: stream });
|
|
2608
2795
|
const processLine = (line) => {
|
|
2609
2796
|
const trimmed = line.trim();
|
|
2610
2797
|
if (!trimmed)
|
|
@@ -2775,7 +2962,7 @@ var init_ingest = __esm({
|
|
|
2775
2962
|
|
|
2776
2963
|
// ../../packages/claude-code-telemetry/dist/session-span.js
|
|
2777
2964
|
import { createReadStream as createReadStream3, existsSync as existsSync8 } from "node:fs";
|
|
2778
|
-
import { createInterface as
|
|
2965
|
+
import { createInterface as createInterface7 } from "node:readline";
|
|
2779
2966
|
function asBlocks2(content) {
|
|
2780
2967
|
if (typeof content === "string")
|
|
2781
2968
|
return [{ type: "text", text: content }];
|
|
@@ -2836,7 +3023,7 @@ async function analyzeSpan(path8) {
|
|
|
2836
3023
|
const pauses = [];
|
|
2837
3024
|
await new Promise((resolve2) => {
|
|
2838
3025
|
const stream = createReadStream3(path8, { encoding: "utf-8" });
|
|
2839
|
-
const rl =
|
|
3026
|
+
const rl = createInterface7({ input: stream });
|
|
2840
3027
|
const processLine = (line) => {
|
|
2841
3028
|
const trimmed = line.trim();
|
|
2842
3029
|
if (!trimmed)
|
|
@@ -2938,14 +3125,14 @@ var init_windows = __esm({
|
|
|
2938
3125
|
});
|
|
2939
3126
|
|
|
2940
3127
|
// ../../packages/claude-code-telemetry/dist/projects.js
|
|
2941
|
-
import { homedir as
|
|
2942
|
-
import { join as
|
|
3128
|
+
import { homedir as homedir4 } from "node:os";
|
|
3129
|
+
import { join as join13 } from "node:path";
|
|
2943
3130
|
var HOME, DEFAULT_PROJECTS_DIR;
|
|
2944
3131
|
var init_projects = __esm({
|
|
2945
3132
|
"../../packages/claude-code-telemetry/dist/projects.js"() {
|
|
2946
3133
|
"use strict";
|
|
2947
|
-
HOME =
|
|
2948
|
-
DEFAULT_PROJECTS_DIR =
|
|
3134
|
+
HOME = homedir4();
|
|
3135
|
+
DEFAULT_PROJECTS_DIR = join13(HOME, ".claude", "projects");
|
|
2949
3136
|
}
|
|
2950
3137
|
});
|
|
2951
3138
|
|
|
@@ -3056,11 +3243,119 @@ var init_hook_input = __esm({
|
|
|
3056
3243
|
}
|
|
3057
3244
|
});
|
|
3058
3245
|
|
|
3246
|
+
// src/hooks/edit-guard.ts
|
|
3247
|
+
function prefixConflict(a, b) {
|
|
3248
|
+
if (a === b) return true;
|
|
3249
|
+
if (a === "" || b === "") return true;
|
|
3250
|
+
return a.startsWith(b + "/") || b.startsWith(a + "/");
|
|
3251
|
+
}
|
|
3252
|
+
function parsePeers(snap, ageSeconds) {
|
|
3253
|
+
const out2 = [];
|
|
3254
|
+
for (const raw of snap.peers) {
|
|
3255
|
+
if (typeof raw !== "object" || raw === null) continue;
|
|
3256
|
+
const p = raw;
|
|
3257
|
+
const claimsRaw = Array.isArray(p.active_claims) ? p.active_claims : [];
|
|
3258
|
+
const claims = [];
|
|
3259
|
+
for (const c of claimsRaw) {
|
|
3260
|
+
if (typeof c !== "object" || c === null) continue;
|
|
3261
|
+
const cc = c;
|
|
3262
|
+
if (typeof cc.path_prefix !== "string") continue;
|
|
3263
|
+
const exp = typeof cc.expires_in_seconds === "number" ? cc.expires_in_seconds : 0;
|
|
3264
|
+
const remaining = exp - ageSeconds;
|
|
3265
|
+
if (remaining <= 0) continue;
|
|
3266
|
+
claims.push({
|
|
3267
|
+
path_prefix: cc.path_prefix,
|
|
3268
|
+
note: typeof cc.note === "string" ? cc.note : null,
|
|
3269
|
+
remaining_seconds: Math.round(remaining)
|
|
3270
|
+
});
|
|
3271
|
+
}
|
|
3272
|
+
out2.push({
|
|
3273
|
+
session_id_short: typeof p.session_id_short === "string" ? p.session_id_short : "?",
|
|
3274
|
+
is_own_user: p.is_own_user === true,
|
|
3275
|
+
branch: typeof p.branch === "string" ? p.branch : null,
|
|
3276
|
+
focus: typeof p.focus === "string" ? p.focus : null,
|
|
3277
|
+
machine_label: typeof p.machine_label === "string" ? p.machine_label : null,
|
|
3278
|
+
last_seen_seconds: typeof p.last_seen_seconds === "number" ? p.last_seen_seconds : 0,
|
|
3279
|
+
claims,
|
|
3280
|
+
working_paths: Array.isArray(p.working_paths) ? p.working_paths.filter((w) => typeof w === "string") : []
|
|
3281
|
+
});
|
|
3282
|
+
}
|
|
3283
|
+
return out2;
|
|
3284
|
+
}
|
|
3285
|
+
function selectOwnSnapshot(snaps, opts) {
|
|
3286
|
+
if (opts.grandparentPid !== null) {
|
|
3287
|
+
const byPpid = snaps.find((s) => s.own_ppid === opts.grandparentPid);
|
|
3288
|
+
if (byPpid) return { snap: byPpid, via: "ppid" };
|
|
3289
|
+
}
|
|
3290
|
+
const byCwd = snaps.find((s) => s.cwd === opts.cwd);
|
|
3291
|
+
if (byCwd) return { snap: byCwd, via: "cwd" };
|
|
3292
|
+
return null;
|
|
3293
|
+
}
|
|
3294
|
+
function ageDisplay(seconds) {
|
|
3295
|
+
if (seconds < 90) return `${Math.max(1, Math.round(seconds))}s`;
|
|
3296
|
+
return `${Math.round(seconds / 60)}m`;
|
|
3297
|
+
}
|
|
3298
|
+
function adviseOnPath(snap, relPath, opts) {
|
|
3299
|
+
const maxAge = opts.maxAgeMs ?? SNAPSHOT_MAX_AGE_MS;
|
|
3300
|
+
const ageMs = opts.nowMs - Date.parse(snap.written_at);
|
|
3301
|
+
if (!Number.isFinite(ageMs) || ageMs < 0 || ageMs > maxAge) return null;
|
|
3302
|
+
const ageSeconds = ageMs / 1e3;
|
|
3303
|
+
const peers = parsePeers(snap, ageSeconds);
|
|
3304
|
+
const hits = [];
|
|
3305
|
+
for (const peer of peers) {
|
|
3306
|
+
if (opts.via === "cwd") {
|
|
3307
|
+
if (opts.currentBranch === null || peer.branch === null) continue;
|
|
3308
|
+
if (peer.branch === opts.currentBranch) continue;
|
|
3309
|
+
}
|
|
3310
|
+
for (const claim of peer.claims) {
|
|
3311
|
+
if (!prefixConflict(relPath, claim.path_prefix)) continue;
|
|
3312
|
+
hits.push(
|
|
3313
|
+
`'${claim.path_prefix}' is CLAIMED by peer session ${peer.session_id_short}${peer.branch ? ` (branch ${peer.branch}` : " ("}${peer.machine_label ? `, ${peer.machine_label}` : ""}${peer.focus ? `, focus: "${peer.focus}"` : ""}, last seen ${ageDisplay(peer.last_seen_seconds + ageSeconds)} ago)${claim.note ? ` \u2014 note: "${claim.note}"` : ""}, claim expires in ${ageDisplay(claim.remaining_seconds)}`
|
|
3314
|
+
);
|
|
3315
|
+
}
|
|
3316
|
+
if (opts.via === "ppid" && peer.is_own_user) {
|
|
3317
|
+
for (const wp of peer.working_paths) {
|
|
3318
|
+
if (!prefixConflict(relPath, wp)) continue;
|
|
3319
|
+
hits.push(
|
|
3320
|
+
`'${wp}' has recent changes by your own peer session ${peer.session_id_short}${peer.branch ? ` (branch ${peer.branch})` : ""}, last seen ${ageDisplay(peer.last_seen_seconds + ageSeconds)} ago`
|
|
3321
|
+
);
|
|
3322
|
+
break;
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
if (hits.length === 0) return null;
|
|
3327
|
+
return `[maind coordination] Editing '${relPath}' overlaps parallel work (view as of ${ageDisplay(ageSeconds)} ago, advisory \u2014 never a lock):
|
|
3328
|
+
` + hits.map((h) => ` \u2022 ${h}`).join("\n") + `
|
|
3329
|
+
Verify live before large edits: check_path_conflicts({project_key: "${snap.project_key}", paths: ["${relPath}"]}) \u2014 then claim_paths for your own edit area.`;
|
|
3330
|
+
}
|
|
3331
|
+
function sessionStartSummary(snap, nowMs, maxAgeMs = SNAPSHOT_MAX_AGE_MS) {
|
|
3332
|
+
if (!snap) return null;
|
|
3333
|
+
const ageMs = nowMs - Date.parse(snap.written_at);
|
|
3334
|
+
if (!Number.isFinite(ageMs) || ageMs < 0 || ageMs > maxAgeMs) return null;
|
|
3335
|
+
const ageSeconds = ageMs / 1e3;
|
|
3336
|
+
const peers = parsePeers(snap, ageSeconds);
|
|
3337
|
+
if (peers.length === 0) return null;
|
|
3338
|
+
const claimCount = peers.reduce((n, p) => n + p.claims.length, 0);
|
|
3339
|
+
const signalPoor = peers.filter(
|
|
3340
|
+
(p) => p.focus === null && p.working_paths.length === 0 && p.claims.length === 0
|
|
3341
|
+
).length;
|
|
3342
|
+
const claimsText = claimCount > 0 ? `${claimCount} active claim${claimCount === 1 ? "" : "s"}` : "no active claims";
|
|
3343
|
+
const poorText = signalPoor > 0 ? `, ${signalPoor} presence-only` : "";
|
|
3344
|
+
return `[maind] ${peers.length} peer session${peers.length === 1 ? "" : "s"} on this repo (${claimsText}${poorText}) as of ${ageDisplay(ageSeconds)} ago \u2014 before large edits: check_path_conflicts({project_key: "${snap.project_key}", paths: [...]}).`;
|
|
3345
|
+
}
|
|
3346
|
+
var SNAPSHOT_MAX_AGE_MS;
|
|
3347
|
+
var init_edit_guard = __esm({
|
|
3348
|
+
"src/hooks/edit-guard.ts"() {
|
|
3349
|
+
"use strict";
|
|
3350
|
+
SNAPSHOT_MAX_AGE_MS = 10 * 6e4;
|
|
3351
|
+
}
|
|
3352
|
+
});
|
|
3353
|
+
|
|
3059
3354
|
// src/hooks/state.ts
|
|
3060
3355
|
import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, rename as rename2 } from "node:fs/promises";
|
|
3061
3356
|
import { existsSync as existsSync9 } from "node:fs";
|
|
3062
|
-
import { homedir as
|
|
3063
|
-
import { join as
|
|
3357
|
+
import { homedir as homedir5 } from "node:os";
|
|
3358
|
+
import { join as join14 } from "node:path";
|
|
3064
3359
|
function emptyState() {
|
|
3065
3360
|
return { config: null, sessions: {}, pending_metrics: [] };
|
|
3066
3361
|
}
|
|
@@ -3099,8 +3394,8 @@ var STATE_DIR, STATE_FILE, DEFAULT_THRESHOLDS;
|
|
|
3099
3394
|
var init_state = __esm({
|
|
3100
3395
|
"src/hooks/state.ts"() {
|
|
3101
3396
|
"use strict";
|
|
3102
|
-
STATE_DIR =
|
|
3103
|
-
STATE_FILE =
|
|
3397
|
+
STATE_DIR = join14(homedir5(), ".maind");
|
|
3398
|
+
STATE_FILE = join14(STATE_DIR, "state.json");
|
|
3104
3399
|
DEFAULT_THRESHOLDS = {
|
|
3105
3400
|
warn_at_pct: 60,
|
|
3106
3401
|
handoff_at_pct: 85,
|
|
@@ -3115,16 +3410,18 @@ __export(hooks_exports, {
|
|
|
3115
3410
|
effectiveConfig: () => effectiveConfig,
|
|
3116
3411
|
runFlush: () => runFlush,
|
|
3117
3412
|
runHookStatus: () => runHookStatus,
|
|
3413
|
+
runOnFileEdit: () => runOnFileEdit,
|
|
3118
3414
|
runOnFileWrite: () => runOnFileWrite,
|
|
3119
3415
|
runOnSessionStart: () => runOnSessionStart,
|
|
3120
3416
|
runOnToolUse: () => runOnToolUse,
|
|
3121
3417
|
runSessionEndMetrics: () => runSessionEndMetrics,
|
|
3122
3418
|
runSyncConfig: () => runSyncConfig
|
|
3123
3419
|
});
|
|
3124
|
-
import {
|
|
3420
|
+
import { execFileSync as execFileSync6 } from "node:child_process";
|
|
3421
|
+
import { existsSync as existsSync10, readFileSync as readFileSync8, realpathSync } from "node:fs";
|
|
3125
3422
|
import { writeFile as writeFile3 } from "node:fs/promises";
|
|
3126
|
-
import { homedir as
|
|
3127
|
-
import { basename, dirname as dirname5, isAbsolute as isAbsolute2, join as
|
|
3423
|
+
import { homedir as homedir6 } from "node:os";
|
|
3424
|
+
import { basename, dirname as dirname5, isAbsolute as isAbsolute2, join as join15, relative } from "node:path";
|
|
3128
3425
|
function effectiveConfig(state) {
|
|
3129
3426
|
if (state.config) return state.config;
|
|
3130
3427
|
const key = readApiKey();
|
|
@@ -3152,8 +3449,54 @@ async function runOnSessionStart() {
|
|
|
3152
3449
|
if (sessionId === null) return 0;
|
|
3153
3450
|
getOrCreateSession(state, sessionId);
|
|
3154
3451
|
await saveState(state);
|
|
3452
|
+
try {
|
|
3453
|
+
const projectKey = computeProjectKey();
|
|
3454
|
+
if (projectKey !== null) {
|
|
3455
|
+
const snaps = readSnapshots(projectKey);
|
|
3456
|
+
const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
|
|
3457
|
+
const own = selectOwnSnapshot(snaps, {
|
|
3458
|
+
grandparentPid: grandparentPid(),
|
|
3459
|
+
cwd
|
|
3460
|
+
});
|
|
3461
|
+
const summary = sessionStartSummary(own?.snap ?? snaps[0] ?? null, Date.now());
|
|
3462
|
+
if (summary !== null) process.stdout.write(summary + "\n");
|
|
3463
|
+
}
|
|
3464
|
+
} catch {
|
|
3465
|
+
}
|
|
3466
|
+
try {
|
|
3467
|
+
const wiring = inspectHookWiring(readSettingsRaw());
|
|
3468
|
+
if (hasWiringDrift(wiring) && needsInstallRun(wiring)) {
|
|
3469
|
+
const missing = wiring.filter((f) => f.remedy === "run-install").map((f) => f.subcommand).join(", ");
|
|
3470
|
+
process.stderr.write(
|
|
3471
|
+
`[maind] New bridge capability not yet wired (${missing}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
|
|
3472
|
+
`
|
|
3473
|
+
);
|
|
3474
|
+
}
|
|
3475
|
+
} catch {
|
|
3476
|
+
}
|
|
3155
3477
|
return 0;
|
|
3156
3478
|
}
|
|
3479
|
+
function readSettingsRaw() {
|
|
3480
|
+
try {
|
|
3481
|
+
const p = join15(homedir6(), ".claude", "settings.json");
|
|
3482
|
+
return existsSync10(p) ? readFileSync8(p, "utf8") : null;
|
|
3483
|
+
} catch {
|
|
3484
|
+
return null;
|
|
3485
|
+
}
|
|
3486
|
+
}
|
|
3487
|
+
function grandparentPid() {
|
|
3488
|
+
try {
|
|
3489
|
+
if (process.platform === "win32") return null;
|
|
3490
|
+
const out2 = execFileSync6("ps", ["-o", "ppid=", "-p", String(process.ppid)], {
|
|
3491
|
+
timeout: 1e3,
|
|
3492
|
+
encoding: "utf8"
|
|
3493
|
+
});
|
|
3494
|
+
const pid = Number.parseInt(out2.trim(), 10);
|
|
3495
|
+
return Number.isFinite(pid) && pid > 0 ? pid : null;
|
|
3496
|
+
} catch {
|
|
3497
|
+
return null;
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3157
3500
|
async function runOnToolUse() {
|
|
3158
3501
|
const state = await loadState();
|
|
3159
3502
|
if (effectiveConfig(state) === null) return 0;
|
|
@@ -3185,7 +3528,7 @@ function realpathOfUnwritten(p) {
|
|
|
3185
3528
|
for (; ; ) {
|
|
3186
3529
|
try {
|
|
3187
3530
|
const real = realpathSync(head);
|
|
3188
|
-
return
|
|
3531
|
+
return join15(real, ...tail.reverse());
|
|
3189
3532
|
} catch {
|
|
3190
3533
|
const parent = dirname5(head);
|
|
3191
3534
|
if (parent === head) return p;
|
|
@@ -3219,7 +3562,7 @@ async function runOnFileWrite() {
|
|
|
3219
3562
|
const filePath = toolFilePathOf(input);
|
|
3220
3563
|
if (!filePath) return 0;
|
|
3221
3564
|
const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
|
|
3222
|
-
const abs = isAbsolute2(filePath) ? filePath :
|
|
3565
|
+
const abs = isAbsolute2(filePath) ? filePath : join15(cwd, filePath);
|
|
3223
3566
|
if (existsSync10(abs)) return 0;
|
|
3224
3567
|
const repoRoot = resolveRepoRoot(cwd);
|
|
3225
3568
|
const rel = relative(repoRoot, realpathOfUnwritten(abs));
|
|
@@ -3232,6 +3575,61 @@ async function runOnFileWrite() {
|
|
|
3232
3575
|
return 0;
|
|
3233
3576
|
}
|
|
3234
3577
|
}
|
|
3578
|
+
function advisoryPayload(context) {
|
|
3579
|
+
return JSON.stringify({
|
|
3580
|
+
hookSpecificOutput: {
|
|
3581
|
+
hookEventName: "PreToolUse",
|
|
3582
|
+
additionalContext: context
|
|
3583
|
+
}
|
|
3584
|
+
});
|
|
3585
|
+
}
|
|
3586
|
+
async function runOnFileEdit() {
|
|
3587
|
+
try {
|
|
3588
|
+
const input = await readHookInput();
|
|
3589
|
+
const tool = (input.tool_name ?? "").toString();
|
|
3590
|
+
if (tool !== "Edit" && tool !== "Write") return 0;
|
|
3591
|
+
const filePath = toolFilePathOf(input);
|
|
3592
|
+
if (!filePath) return 0;
|
|
3593
|
+
const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
|
|
3594
|
+
const abs = isAbsolute2(filePath) ? filePath : join15(cwd, filePath);
|
|
3595
|
+
const projectKey = computeProjectKey();
|
|
3596
|
+
if (projectKey === null) return 0;
|
|
3597
|
+
const snaps = readSnapshots(projectKey);
|
|
3598
|
+
if (snaps.length === 0) return 0;
|
|
3599
|
+
const own = selectOwnSnapshot(snaps, {
|
|
3600
|
+
grandparentPid: grandparentPid(),
|
|
3601
|
+
cwd
|
|
3602
|
+
});
|
|
3603
|
+
if (own === null) return 0;
|
|
3604
|
+
const repoRoot = resolveRepoRoot(cwd);
|
|
3605
|
+
const real = existsSync10(abs) ? realpathSync(abs) : realpathOfUnwritten(abs);
|
|
3606
|
+
const rel = relative(repoRoot, real).replace(/\\/g, "/");
|
|
3607
|
+
if (rel.length === 0 || rel.startsWith("..") || isAbsolute2(rel)) return 0;
|
|
3608
|
+
const advice = adviseOnPath(own.snap, rel, {
|
|
3609
|
+
via: own.via,
|
|
3610
|
+
currentBranch: own.via === "cwd" ? currentGitBranch(cwd) : null,
|
|
3611
|
+
nowMs: Date.now()
|
|
3612
|
+
});
|
|
3613
|
+
if (advice === null) return 0;
|
|
3614
|
+
process.stdout.write(advisoryPayload(advice));
|
|
3615
|
+
return 0;
|
|
3616
|
+
} catch {
|
|
3617
|
+
return 0;
|
|
3618
|
+
}
|
|
3619
|
+
}
|
|
3620
|
+
function currentGitBranch(cwd) {
|
|
3621
|
+
try {
|
|
3622
|
+
const out2 = execFileSync6("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
|
|
3623
|
+
cwd,
|
|
3624
|
+
timeout: 1e3,
|
|
3625
|
+
encoding: "utf8"
|
|
3626
|
+
});
|
|
3627
|
+
const branch = out2.trim();
|
|
3628
|
+
return branch.length > 0 && branch !== "HEAD" ? branch : null;
|
|
3629
|
+
} catch {
|
|
3630
|
+
return null;
|
|
3631
|
+
}
|
|
3632
|
+
}
|
|
3235
3633
|
async function maybeEmitAdvisory(state, session) {
|
|
3236
3634
|
const t = resolveThresholds(state);
|
|
3237
3635
|
const tokens = session.token_count ?? 0;
|
|
@@ -3256,7 +3654,7 @@ async function maybeEmitAdvisory(state, session) {
|
|
|
3256
3654
|
};
|
|
3257
3655
|
try {
|
|
3258
3656
|
await writeFile3(
|
|
3259
|
-
|
|
3657
|
+
join15(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
|
|
3260
3658
|
JSON.stringify(payload, null, 2)
|
|
3261
3659
|
);
|
|
3262
3660
|
} catch (err) {
|
|
@@ -3395,10 +3793,10 @@ async function runHookStatus() {
|
|
|
3395
3793
|
return 0;
|
|
3396
3794
|
}
|
|
3397
3795
|
function readHookWiring() {
|
|
3398
|
-
const settingsPath =
|
|
3796
|
+
const settingsPath = join15(homedir6(), ".claude", "settings.json");
|
|
3399
3797
|
let raw = null;
|
|
3400
3798
|
try {
|
|
3401
|
-
if (existsSync10(settingsPath)) raw =
|
|
3799
|
+
if (existsSync10(settingsPath)) raw = readFileSync8(settingsPath, "utf8");
|
|
3402
3800
|
} catch {
|
|
3403
3801
|
}
|
|
3404
3802
|
return { settingsPath, findings: inspectHookWiring(raw) };
|
|
@@ -3481,7 +3879,10 @@ var init_hooks = __esm({
|
|
|
3481
3879
|
init_conventions_cache();
|
|
3482
3880
|
init_device_id();
|
|
3483
3881
|
init_hook_wiring();
|
|
3882
|
+
init_presence_snapshot();
|
|
3883
|
+
init_project_key();
|
|
3484
3884
|
init_api();
|
|
3885
|
+
init_edit_guard();
|
|
3485
3886
|
init_hook_input();
|
|
3486
3887
|
init_state();
|
|
3487
3888
|
DEFAULT_THRESHOLDS_ENDPOINT = process.env.MAIND_THRESHOLDS_ENDPOINT ?? "https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds";
|
|
@@ -3843,14 +4244,16 @@ var Forwarder = class {
|
|
|
3843
4244
|
emitJsonRpcError(id, -32001, `bridge auth error: ${body.slice(0, 200)}`);
|
|
3844
4245
|
}
|
|
3845
4246
|
/**
|
|
3846
|
-
* Auto-presence transport (ADR-242): post a self-generated
|
|
3847
|
-
* the forwarder's EXISTING MCP session. The response is
|
|
3848
|
-
*
|
|
3849
|
-
*
|
|
3850
|
-
*
|
|
3851
|
-
*
|
|
4247
|
+
* Auto-presence transport (ADR-242, revised ADR-277): post a self-generated
|
|
4248
|
+
* `tools/call` on the forwarder's EXISTING MCP session. The response is
|
|
4249
|
+
* PARSED and returned to the announcer (peers/conflicts feed the local
|
|
4250
|
+
* snapshot) — and still NEVER written to stdout: the local client must not
|
|
4251
|
+
* see frames it didn't send. String-namespaced ids keep the frame disjoint
|
|
4252
|
+
* from the client's numeric JSON-RPC ids. Riding the shared session keeps
|
|
4253
|
+
* the server's session accounting honest AND carries the detected
|
|
3852
4254
|
* client-family headers, so the announce row shows the real client.
|
|
3853
|
-
* Throws on
|
|
4255
|
+
* Throws on transport failure — the announcer turns that into backoff;
|
|
4256
|
+
* an unparseable body resolves to null (fail-open), never throws.
|
|
3854
4257
|
*/
|
|
3855
4258
|
async postPresenceToolCall(name, args) {
|
|
3856
4259
|
if (this.sessionId === null) {
|
|
@@ -3868,10 +4271,11 @@ var Forwarder = class {
|
|
|
3868
4271
|
headers: this.buildHeaders(true),
|
|
3869
4272
|
body: frame
|
|
3870
4273
|
});
|
|
3871
|
-
await response.text().catch(() => "");
|
|
4274
|
+
const body = await response.text().catch(() => "");
|
|
3872
4275
|
if (!response.ok) {
|
|
3873
4276
|
throw new Error(`presence: upstream HTTP ${response.status}`);
|
|
3874
4277
|
}
|
|
4278
|
+
return parsePresenceToolResult(body);
|
|
3875
4279
|
}
|
|
3876
4280
|
/**
|
|
3877
4281
|
* Build the outbound header set. `includeSession` attaches the current
|
|
@@ -4135,6 +4539,24 @@ function extractHint(lowerBody) {
|
|
|
4135
4539
|
if (lowerBody.includes("device_required")) return "device_required";
|
|
4136
4540
|
return "auth_failed";
|
|
4137
4541
|
}
|
|
4542
|
+
function parsePresenceToolResult(body) {
|
|
4543
|
+
try {
|
|
4544
|
+
const trimmed = body.trim();
|
|
4545
|
+
if (trimmed.length === 0) return null;
|
|
4546
|
+
let envelopeRaw = trimmed;
|
|
4547
|
+
if (!trimmed.startsWith("{")) {
|
|
4548
|
+
const dataLines = trimmed.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("data:"));
|
|
4549
|
+
if (dataLines.length === 0) return null;
|
|
4550
|
+
envelopeRaw = dataLines[dataLines.length - 1].slice(5).trim();
|
|
4551
|
+
}
|
|
4552
|
+
const envelope = JSON.parse(envelopeRaw);
|
|
4553
|
+
const text = envelope.result?.content?.[0]?.text;
|
|
4554
|
+
if (typeof text !== "string") return null;
|
|
4555
|
+
return JSON.parse(text);
|
|
4556
|
+
} catch {
|
|
4557
|
+
return null;
|
|
4558
|
+
}
|
|
4559
|
+
}
|
|
4138
4560
|
|
|
4139
4561
|
// src/index.ts
|
|
4140
4562
|
init_device_id();
|
|
@@ -4270,50 +4692,7 @@ async function openExternalBrowser(url) {
|
|
|
4270
4692
|
|
|
4271
4693
|
// src/index.ts
|
|
4272
4694
|
init_version();
|
|
4273
|
-
|
|
4274
|
-
// src/project-key.ts
|
|
4275
|
-
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
4276
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
4277
|
-
function sha256Hex(input) {
|
|
4278
|
-
return createHash2("sha256").update(input).digest("hex");
|
|
4279
|
-
}
|
|
4280
|
-
function normalizeRemoteUrl(raw) {
|
|
4281
|
-
let s = raw.trim();
|
|
4282
|
-
if (!s) return null;
|
|
4283
|
-
const scheme = /^[a-z][a-z0-9+.-]*:\/\//i.exec(s);
|
|
4284
|
-
if (scheme) {
|
|
4285
|
-
s = s.slice(scheme[0].length);
|
|
4286
|
-
s = s.replace(/^[^@/]+@/, "");
|
|
4287
|
-
s = s.replace(/^([^/:]+):\d+(?=\/)/, "$1");
|
|
4288
|
-
} else {
|
|
4289
|
-
s = s.replace(/^[^@/]+@/, "");
|
|
4290
|
-
const i = s.indexOf(":");
|
|
4291
|
-
if (i >= 0) s = `${s.slice(0, i)}/${s.slice(i + 1)}`;
|
|
4292
|
-
}
|
|
4293
|
-
s = s.replace(/\.git$/i, "").replace(/\/+$/, "").toLowerCase();
|
|
4294
|
-
return s.length > 0 ? s : null;
|
|
4295
|
-
}
|
|
4296
|
-
function projectKeyFromRemote(raw) {
|
|
4297
|
-
const norm = normalizeRemoteUrl(raw);
|
|
4298
|
-
return norm ? sha256Hex(norm) : null;
|
|
4299
|
-
}
|
|
4300
|
-
var PROJECT_KEY_RE = /^[a-f0-9]{64}$/;
|
|
4301
|
-
function computeProjectKey() {
|
|
4302
|
-
const override = process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();
|
|
4303
|
-
if (override && PROJECT_KEY_RE.test(override)) return override;
|
|
4304
|
-
let remote;
|
|
4305
|
-
try {
|
|
4306
|
-
remote = execFileSync2("git", ["config", "--get", "remote.origin.url"], {
|
|
4307
|
-
encoding: "utf8",
|
|
4308
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
4309
|
-
timeout: 5e3
|
|
4310
|
-
}).trim();
|
|
4311
|
-
} catch {
|
|
4312
|
-
return null;
|
|
4313
|
-
}
|
|
4314
|
-
if (!remote) return null;
|
|
4315
|
-
return projectKeyFromRemote(remote);
|
|
4316
|
-
}
|
|
4695
|
+
init_project_key();
|
|
4317
4696
|
|
|
4318
4697
|
// src/install/index.ts
|
|
4319
4698
|
init_version();
|
|
@@ -4334,6 +4713,7 @@ function parseInstallFlags(argv) {
|
|
|
4334
4713
|
client: null,
|
|
4335
4714
|
skipCodex: false,
|
|
4336
4715
|
dryRun: false,
|
|
4716
|
+
autoWorkingPaths: false,
|
|
4337
4717
|
help: false
|
|
4338
4718
|
};
|
|
4339
4719
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -4364,6 +4744,9 @@ function parseInstallFlags(argv) {
|
|
|
4364
4744
|
case "--dry-run":
|
|
4365
4745
|
flags.dryRun = true;
|
|
4366
4746
|
break;
|
|
4747
|
+
case "--auto-working-paths":
|
|
4748
|
+
flags.autoWorkingPaths = true;
|
|
4749
|
+
break;
|
|
4367
4750
|
case "--project-root": {
|
|
4368
4751
|
const next = argv[i + 1];
|
|
4369
4752
|
if (next === void 0 || next.startsWith("--")) {
|
|
@@ -6037,6 +6420,9 @@ async function mergeToolUseHook(opts) {
|
|
|
6037
6420
|
async function mergeFileWriteHook(opts) {
|
|
6038
6421
|
return mergeSubcommandHook(opts, managed("on-file-write"));
|
|
6039
6422
|
}
|
|
6423
|
+
async function mergeFileEditHook(opts) {
|
|
6424
|
+
return mergeSubcommandHook(opts, managed("on-file-edit"));
|
|
6425
|
+
}
|
|
6040
6426
|
function findExistingHookCommand(settings, event, pattern) {
|
|
6041
6427
|
const groups = settings.hooks?.[event];
|
|
6042
6428
|
if (!Array.isArray(groups)) return null;
|
|
@@ -6073,6 +6459,130 @@ function errMessage(err) {
|
|
|
6073
6459
|
return err instanceof Error ? err.message : String(err);
|
|
6074
6460
|
}
|
|
6075
6461
|
|
|
6462
|
+
// src/install/working-paths-consent.ts
|
|
6463
|
+
import * as readline3 from "node:readline";
|
|
6464
|
+
|
|
6465
|
+
// src/bridge-config.ts
|
|
6466
|
+
init_device_id();
|
|
6467
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
|
|
6468
|
+
import { join as join8 } from "node:path";
|
|
6469
|
+
function bridgeConfigPath() {
|
|
6470
|
+
return join8(configDir(), "config.json");
|
|
6471
|
+
}
|
|
6472
|
+
function readBridgeConfig() {
|
|
6473
|
+
try {
|
|
6474
|
+
const file = bridgeConfigPath();
|
|
6475
|
+
if (!existsSync3(file)) return null;
|
|
6476
|
+
const raw = JSON.parse(readFileSync3(file, "utf8"));
|
|
6477
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
6478
|
+
return null;
|
|
6479
|
+
}
|
|
6480
|
+
const o = raw;
|
|
6481
|
+
const config = {};
|
|
6482
|
+
if (typeof o.auto_announce === "boolean") {
|
|
6483
|
+
config.auto_announce = o.auto_announce;
|
|
6484
|
+
}
|
|
6485
|
+
if (typeof o.machine_label === "string") {
|
|
6486
|
+
config.machine_label = o.machine_label;
|
|
6487
|
+
}
|
|
6488
|
+
if (typeof o.auto_working_paths === "boolean") {
|
|
6489
|
+
config.auto_working_paths = o.auto_working_paths;
|
|
6490
|
+
}
|
|
6491
|
+
return config;
|
|
6492
|
+
} catch {
|
|
6493
|
+
return null;
|
|
6494
|
+
}
|
|
6495
|
+
}
|
|
6496
|
+
|
|
6497
|
+
// src/install/working-paths-consent.ts
|
|
6498
|
+
var TARGET_KEY = "config:auto_working_paths";
|
|
6499
|
+
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]: ';
|
|
6500
|
+
async function applyWorkingPathsConsent(opts) {
|
|
6501
|
+
const configPath = opts.configPath ?? bridgeConfigPath();
|
|
6502
|
+
let existing = {};
|
|
6503
|
+
try {
|
|
6504
|
+
const raw = await readFileSafe(configPath);
|
|
6505
|
+
if (raw !== null && raw.trim().length > 0) {
|
|
6506
|
+
const parsed = JSON.parse(raw);
|
|
6507
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
6508
|
+
existing = parsed;
|
|
6509
|
+
}
|
|
6510
|
+
}
|
|
6511
|
+
} catch {
|
|
6512
|
+
}
|
|
6513
|
+
if (typeof existing.auto_working_paths === "boolean") {
|
|
6514
|
+
return {
|
|
6515
|
+
target: TARGET_KEY,
|
|
6516
|
+
action: "skip",
|
|
6517
|
+
status: "skipped",
|
|
6518
|
+
detail: `already decided (${existing.auto_working_paths ? "enabled" : "disabled"}) in ${configPath}`
|
|
6519
|
+
};
|
|
6520
|
+
}
|
|
6521
|
+
let consent;
|
|
6522
|
+
if (opts.explicitFlag) {
|
|
6523
|
+
consent = true;
|
|
6524
|
+
} else if (!opts.isInteractive) {
|
|
6525
|
+
return {
|
|
6526
|
+
target: TARGET_KEY,
|
|
6527
|
+
action: "skip",
|
|
6528
|
+
status: "skipped",
|
|
6529
|
+
detail: "consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"
|
|
6530
|
+
};
|
|
6531
|
+
} else if (opts.dryRun) {
|
|
6532
|
+
return {
|
|
6533
|
+
target: TARGET_KEY,
|
|
6534
|
+
action: "merge",
|
|
6535
|
+
status: "would-merge",
|
|
6536
|
+
detail: `${configPath} (would prompt for consent in real run)`
|
|
6537
|
+
};
|
|
6538
|
+
} else {
|
|
6539
|
+
const promptFn = opts.promptFn ?? promptYesNoDefaultNo;
|
|
6540
|
+
consent = await promptFn(opts.out, WORKING_PATHS_CONSENT_PROMPT);
|
|
6541
|
+
}
|
|
6542
|
+
if (!consent) {
|
|
6543
|
+
return {
|
|
6544
|
+
target: TARGET_KEY,
|
|
6545
|
+
action: "skip",
|
|
6546
|
+
status: "skipped",
|
|
6547
|
+
detail: "user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"
|
|
6548
|
+
};
|
|
6549
|
+
}
|
|
6550
|
+
const next = { ...existing, auto_working_paths: true };
|
|
6551
|
+
const nextRaw = JSON.stringify(next, null, 2) + "\n";
|
|
6552
|
+
if (opts.dryRun) {
|
|
6553
|
+
return { target: TARGET_KEY, action: "merge", status: "would-merge", detail: configPath };
|
|
6554
|
+
}
|
|
6555
|
+
try {
|
|
6556
|
+
await atomicWriteFile(configPath, nextRaw, 384);
|
|
6557
|
+
} catch (err) {
|
|
6558
|
+
return {
|
|
6559
|
+
target: TARGET_KEY,
|
|
6560
|
+
action: "merge",
|
|
6561
|
+
status: "failed",
|
|
6562
|
+
detail: `write: ${err instanceof Error ? err.message : String(err)}`
|
|
6563
|
+
};
|
|
6564
|
+
}
|
|
6565
|
+
return {
|
|
6566
|
+
target: TARGET_KEY,
|
|
6567
|
+
action: "merge",
|
|
6568
|
+
status: "merged",
|
|
6569
|
+
detail: `${configPath} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`
|
|
6570
|
+
};
|
|
6571
|
+
}
|
|
6572
|
+
async function promptYesNoDefaultNo(out2, prompt) {
|
|
6573
|
+
out2.write(prompt);
|
|
6574
|
+
const rl = readline3.createInterface({
|
|
6575
|
+
input: process.stdin,
|
|
6576
|
+
output: out2,
|
|
6577
|
+
terminal: true
|
|
6578
|
+
});
|
|
6579
|
+
const answer = await new Promise((resolve2) => {
|
|
6580
|
+
rl.question("", (input) => resolve2(input.trim().toLowerCase()));
|
|
6581
|
+
});
|
|
6582
|
+
rl.close();
|
|
6583
|
+
return answer === "y" || answer === "yes";
|
|
6584
|
+
}
|
|
6585
|
+
|
|
6076
6586
|
// src/install/browser-pair.ts
|
|
6077
6587
|
init_device_id();
|
|
6078
6588
|
|
|
@@ -6343,7 +6853,7 @@ import { posix as posix6 } from "node:path";
|
|
|
6343
6853
|
// ../../packages/code-index/build/parse/tree-sitter/parser.js
|
|
6344
6854
|
init_keys();
|
|
6345
6855
|
init_types();
|
|
6346
|
-
import { join as
|
|
6856
|
+
import { join as join10 } from "node:path";
|
|
6347
6857
|
import Parser from "web-tree-sitter";
|
|
6348
6858
|
|
|
6349
6859
|
// ../../packages/code-index/build/parse/lang/python.js
|
|
@@ -6644,7 +7154,7 @@ function stripQuotes(s) {
|
|
|
6644
7154
|
|
|
6645
7155
|
// ../../packages/code-index/build/parse/tree-sitter/grammars.js
|
|
6646
7156
|
import { createRequire } from "node:module";
|
|
6647
|
-
import { join as
|
|
7157
|
+
import { join as join9 } from "node:path";
|
|
6648
7158
|
var GRAMMAR_FILE = {
|
|
6649
7159
|
typescript: "tree-sitter-typescript.wasm",
|
|
6650
7160
|
tsx: "tree-sitter-tsx.wasm",
|
|
@@ -6654,7 +7164,7 @@ var GRAMMAR_FILE = {
|
|
|
6654
7164
|
var CORE_WASM_FILE = "tree-sitter.wasm";
|
|
6655
7165
|
function grammarPath(language, assetDir) {
|
|
6656
7166
|
if (assetDir)
|
|
6657
|
-
return
|
|
7167
|
+
return join9(assetDir, GRAMMAR_FILE[language]);
|
|
6658
7168
|
return createRequire(import.meta.url).resolve(`tree-sitter-wasms/out/${GRAMMAR_FILE[language]}`);
|
|
6659
7169
|
}
|
|
6660
7170
|
|
|
@@ -6671,7 +7181,7 @@ var TreeSitterParser = class {
|
|
|
6671
7181
|
async init() {
|
|
6672
7182
|
if (this.initialized)
|
|
6673
7183
|
return;
|
|
6674
|
-
await Parser.init(this.assetDir ? { locateFile: (file) =>
|
|
7184
|
+
await Parser.init(this.assetDir ? { locateFile: (file) => join10(this.assetDir, file || CORE_WASM_FILE) } : void 0);
|
|
6675
7185
|
this.parser = new Parser();
|
|
6676
7186
|
this.initialized = true;
|
|
6677
7187
|
}
|
|
@@ -6728,14 +7238,111 @@ var TreeSitterParser = class {
|
|
|
6728
7238
|
// ../../packages/code-index/build/node.js
|
|
6729
7239
|
init_engine();
|
|
6730
7240
|
|
|
7241
|
+
// ../../packages/code-index/build/store/sqlite-driver.js
|
|
7242
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
7243
|
+
var requireHost = createRequire2(import.meta.url);
|
|
7244
|
+
function loadBuiltin() {
|
|
7245
|
+
return requireHost("node:sqlite");
|
|
7246
|
+
}
|
|
7247
|
+
var builtinProbeCache = null;
|
|
7248
|
+
function probeBuiltinSqlite() {
|
|
7249
|
+
if (builtinProbeCache)
|
|
7250
|
+
return builtinProbeCache;
|
|
7251
|
+
try {
|
|
7252
|
+
const { DatabaseSync } = loadBuiltin();
|
|
7253
|
+
const db = new DatabaseSync(":memory:");
|
|
7254
|
+
try {
|
|
7255
|
+
db.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)");
|
|
7256
|
+
db.exec("INSERT INTO probe_fts (t) VALUES ('probe')");
|
|
7257
|
+
db.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get();
|
|
7258
|
+
builtinProbeCache = { ok: true };
|
|
7259
|
+
} finally {
|
|
7260
|
+
db.close();
|
|
7261
|
+
}
|
|
7262
|
+
} catch (err) {
|
|
7263
|
+
builtinProbeCache = {
|
|
7264
|
+
ok: false,
|
|
7265
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
7266
|
+
};
|
|
7267
|
+
}
|
|
7268
|
+
return builtinProbeCache;
|
|
7269
|
+
}
|
|
7270
|
+
function openBuiltin(dbPath) {
|
|
7271
|
+
const { DatabaseSync } = loadBuiltin();
|
|
7272
|
+
const raw = new DatabaseSync(dbPath);
|
|
7273
|
+
return {
|
|
7274
|
+
prepare: (sql) => raw.prepare(sql),
|
|
7275
|
+
exec: (sql) => raw.exec(sql),
|
|
7276
|
+
close: () => raw.close(),
|
|
7277
|
+
// node:sqlite hat keinen .transaction()-Helper — manuelle Klammer.
|
|
7278
|
+
transaction: (fn) => () => {
|
|
7279
|
+
raw.exec("BEGIN");
|
|
7280
|
+
try {
|
|
7281
|
+
fn();
|
|
7282
|
+
raw.exec("COMMIT");
|
|
7283
|
+
} catch (err) {
|
|
7284
|
+
try {
|
|
7285
|
+
raw.exec("ROLLBACK");
|
|
7286
|
+
} catch {
|
|
7287
|
+
}
|
|
7288
|
+
throw err;
|
|
7289
|
+
}
|
|
7290
|
+
}
|
|
7291
|
+
};
|
|
7292
|
+
}
|
|
7293
|
+
function openBetter(dbPath) {
|
|
7294
|
+
const Database = requireHost("better-sqlite3");
|
|
7295
|
+
const raw = new Database(dbPath);
|
|
7296
|
+
return {
|
|
7297
|
+
prepare: (sql) => raw.prepare(sql),
|
|
7298
|
+
exec: (sql) => {
|
|
7299
|
+
raw.exec(sql);
|
|
7300
|
+
},
|
|
7301
|
+
close: () => {
|
|
7302
|
+
raw.close();
|
|
7303
|
+
},
|
|
7304
|
+
transaction: (fn) => raw.transaction(fn)
|
|
7305
|
+
};
|
|
7306
|
+
}
|
|
7307
|
+
function backendOverride() {
|
|
7308
|
+
const v = (process.env.MAIND_SQLITE_BACKEND ?? "").trim().toLowerCase();
|
|
7309
|
+
if (v === "builtin" || v === "better")
|
|
7310
|
+
return v;
|
|
7311
|
+
return null;
|
|
7312
|
+
}
|
|
7313
|
+
function openSqliteDatabase(dbPath) {
|
|
7314
|
+
const override = backendOverride();
|
|
7315
|
+
const openAs = (backend) => {
|
|
7316
|
+
const db = backend === "node:sqlite" ? openBuiltin(dbPath) : openBetter(dbPath);
|
|
7317
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
7318
|
+
db.exec("PRAGMA foreign_keys = ON");
|
|
7319
|
+
return { db, backend };
|
|
7320
|
+
};
|
|
7321
|
+
if (override === "builtin") {
|
|
7322
|
+
const probe2 = probeBuiltinSqlite();
|
|
7323
|
+
if (!probe2.ok) {
|
|
7324
|
+
throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${probe2.reason}`);
|
|
7325
|
+
}
|
|
7326
|
+
return openAs("node:sqlite");
|
|
7327
|
+
}
|
|
7328
|
+
if (override === "better") {
|
|
7329
|
+
return openAs("better-sqlite3");
|
|
7330
|
+
}
|
|
7331
|
+
const probe = probeBuiltinSqlite();
|
|
7332
|
+
if (probe.ok) {
|
|
7333
|
+
return openAs("node:sqlite");
|
|
7334
|
+
}
|
|
7335
|
+
try {
|
|
7336
|
+
return openAs("better-sqlite3");
|
|
7337
|
+
} catch (err) {
|
|
7338
|
+
const betterReason = err instanceof Error ? err.message : String(err);
|
|
7339
|
+
throw new Error(`no usable SQLite backend: node:sqlite unavailable (${probe.reason}); better-sqlite3 unavailable (${betterReason})`);
|
|
7340
|
+
}
|
|
7341
|
+
}
|
|
7342
|
+
|
|
6731
7343
|
// ../../packages/code-index/build/store/node-sqlite.js
|
|
6732
7344
|
init_schema();
|
|
6733
7345
|
init_identifiers();
|
|
6734
|
-
import { createRequire as createRequire2 } from "node:module";
|
|
6735
|
-
var requireNative = createRequire2(import.meta.url);
|
|
6736
|
-
function loadDatabase() {
|
|
6737
|
-
return requireNative("better-sqlite3");
|
|
6738
|
-
}
|
|
6739
7346
|
function toNodeRow(r) {
|
|
6740
7347
|
return {
|
|
6741
7348
|
nodeKey: r.node_key,
|
|
@@ -6755,11 +7362,12 @@ function toNodeRow(r) {
|
|
|
6755
7362
|
var CHUNK = 400;
|
|
6756
7363
|
var NodeSqliteStore = class {
|
|
6757
7364
|
db;
|
|
7365
|
+
/** Welches Backend diesen Store trägt — für Diagnose/Status-Ausgaben. */
|
|
7366
|
+
backend;
|
|
6758
7367
|
constructor(dbPath) {
|
|
6759
|
-
const
|
|
6760
|
-
this.db =
|
|
6761
|
-
this.
|
|
6762
|
-
this.db.pragma("foreign_keys = ON");
|
|
7368
|
+
const opened = openSqliteDatabase(dbPath);
|
|
7369
|
+
this.db = opened.db;
|
|
7370
|
+
this.backend = opened.backend;
|
|
6763
7371
|
}
|
|
6764
7372
|
async init() {
|
|
6765
7373
|
this.db.exec(SCHEMA_SQL);
|
|
@@ -6890,7 +7498,7 @@ var NodeSqliteStore = class {
|
|
|
6890
7498
|
}
|
|
6891
7499
|
async pruneOrphanEmbeddings() {
|
|
6892
7500
|
const info = this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();
|
|
6893
|
-
return info.changes;
|
|
7501
|
+
return Number(info.changes);
|
|
6894
7502
|
}
|
|
6895
7503
|
async countEmbeddings() {
|
|
6896
7504
|
return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c;
|
|
@@ -7027,19 +7635,27 @@ function createNodeCodeIndex(opts) {
|
|
|
7027
7635
|
|
|
7028
7636
|
// src/local-tools/engine.ts
|
|
7029
7637
|
function probeNativeStore() {
|
|
7638
|
+
const builtin = probeBuiltinSqlite();
|
|
7639
|
+
if (builtin.ok) return { ok: true, backend: "node:sqlite" };
|
|
7030
7640
|
try {
|
|
7031
7641
|
createRequire3(import.meta.url)("better-sqlite3");
|
|
7032
|
-
return { ok: true };
|
|
7642
|
+
return { ok: true, backend: "better-sqlite3" };
|
|
7033
7643
|
} catch (err) {
|
|
7034
|
-
|
|
7644
|
+
const better = err instanceof Error ? err.message : String(err);
|
|
7645
|
+
return {
|
|
7646
|
+
ok: false,
|
|
7647
|
+
reason: `node:sqlite: ${builtin.reason}; better-sqlite3: ${better}`
|
|
7648
|
+
};
|
|
7035
7649
|
}
|
|
7036
7650
|
}
|
|
7037
7651
|
function isNativeStoreUnavailable(err) {
|
|
7038
7652
|
const code = err?.code ?? "";
|
|
7039
7653
|
const msg = err instanceof Error ? err.message : String(err);
|
|
7040
|
-
return /better.sqlite3|better_sqlite3|bindings file
|
|
7654
|
+
return /better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(
|
|
7655
|
+
`${code} ${msg}`
|
|
7656
|
+
) || code === "ERR_DLOPEN_FAILED" || /NODE_MODULE_VERSION/.test(msg);
|
|
7041
7657
|
}
|
|
7042
|
-
var NATIVE_STORE_UNAVAILABLE_HINT = "codebase_* tools are unavailable on this machine:
|
|
7658
|
+
var NATIVE_STORE_UNAVAILABLE_HINT = "codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";
|
|
7043
7659
|
function resolveRepoRoot2(cwd = process.cwd()) {
|
|
7044
7660
|
try {
|
|
7045
7661
|
const top = execFileSync5("git", ["rev-parse", "--show-toplevel"], {
|
|
@@ -7195,7 +7811,16 @@ Skipping remaining steps.
|
|
|
7195
7811
|
report.add(await mergeSessionStartMetricsHook(hookOpts));
|
|
7196
7812
|
report.add(await mergeToolUseHook(hookOpts));
|
|
7197
7813
|
report.add(await mergeFileWriteHook(hookOpts));
|
|
7814
|
+
report.add(await mergeFileEditHook(hookOpts));
|
|
7198
7815
|
report.add(await mergeStopHook(hookOpts));
|
|
7816
|
+
report.add(
|
|
7817
|
+
await applyWorkingPathsConsent({
|
|
7818
|
+
isInteractive,
|
|
7819
|
+
explicitFlag: flags.autoWorkingPaths,
|
|
7820
|
+
dryRun: flags.dryRun,
|
|
7821
|
+
out: process.stdout
|
|
7822
|
+
})
|
|
7823
|
+
);
|
|
7199
7824
|
const nativeProbe = probeNativeStore();
|
|
7200
7825
|
if (!nativeProbe.ok) {
|
|
7201
7826
|
report.add({
|
|
@@ -7249,8 +7874,8 @@ Finished in ${wallClockSec}s. Restart your MCP client so it picks up the new ser
|
|
|
7249
7874
|
}
|
|
7250
7875
|
|
|
7251
7876
|
// src/local-tools/savings.ts
|
|
7252
|
-
import { readFileSync as
|
|
7253
|
-
import { join as
|
|
7877
|
+
import { readFileSync as readFileSync6 } from "node:fs";
|
|
7878
|
+
import { join as join11 } from "node:path";
|
|
7254
7879
|
|
|
7255
7880
|
// src/local-tools/token-estimate.ts
|
|
7256
7881
|
var CHARS_PER_TOKEN = 4;
|
|
@@ -7282,7 +7907,7 @@ var SavingsAggregator = class {
|
|
|
7282
7907
|
};
|
|
7283
7908
|
function readFileCapped(absPath) {
|
|
7284
7909
|
try {
|
|
7285
|
-
const content =
|
|
7910
|
+
const content = readFileSync6(absPath, "utf8");
|
|
7286
7911
|
return content.length > MAX_FILE_BYTES ? content.slice(0, MAX_FILE_BYTES) : content;
|
|
7287
7912
|
} catch {
|
|
7288
7913
|
return "";
|
|
@@ -7305,14 +7930,14 @@ function measureLocalToolSaved(name, result, serialized, repoRoot) {
|
|
|
7305
7930
|
if (files.length === 0) return 0;
|
|
7306
7931
|
let wholeTokens = 0;
|
|
7307
7932
|
for (const fp of files) {
|
|
7308
|
-
wholeTokens += estimateTokens(readFileCapped(
|
|
7933
|
+
wholeTokens += estimateTokens(readFileCapped(join11(repoRoot, fp)));
|
|
7309
7934
|
}
|
|
7310
7935
|
return Math.max(0, wholeTokens - resultTokens);
|
|
7311
7936
|
}
|
|
7312
7937
|
if (name === "codebase_snippet") {
|
|
7313
7938
|
const fp = result?.filePath;
|
|
7314
7939
|
if (typeof fp !== "string" || fp.length === 0) return 0;
|
|
7315
|
-
const wholeTokens = estimateTokens(readFileCapped(
|
|
7940
|
+
const wholeTokens = estimateTokens(readFileCapped(join11(repoRoot, fp)));
|
|
7316
7941
|
return Math.max(0, wholeTokens - resultTokens);
|
|
7317
7942
|
}
|
|
7318
7943
|
return 0;
|
|
@@ -7946,37 +8571,6 @@ async function postSavingsMetric(input) {
|
|
|
7946
8571
|
// src/presence.ts
|
|
7947
8572
|
import { execFile } from "node:child_process";
|
|
7948
8573
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
7949
|
-
|
|
7950
|
-
// src/bridge-config.ts
|
|
7951
|
-
init_device_id();
|
|
7952
|
-
import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
|
|
7953
|
-
import { join as join11 } from "node:path";
|
|
7954
|
-
function bridgeConfigPath() {
|
|
7955
|
-
return join11(configDir(), "config.json");
|
|
7956
|
-
}
|
|
7957
|
-
function readBridgeConfig() {
|
|
7958
|
-
try {
|
|
7959
|
-
const file = bridgeConfigPath();
|
|
7960
|
-
if (!existsSync5(file)) return null;
|
|
7961
|
-
const raw = JSON.parse(readFileSync6(file, "utf8"));
|
|
7962
|
-
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
7963
|
-
return null;
|
|
7964
|
-
}
|
|
7965
|
-
const o = raw;
|
|
7966
|
-
const config = {};
|
|
7967
|
-
if (typeof o.auto_announce === "boolean") {
|
|
7968
|
-
config.auto_announce = o.auto_announce;
|
|
7969
|
-
}
|
|
7970
|
-
if (typeof o.machine_label === "string") {
|
|
7971
|
-
config.machine_label = o.machine_label;
|
|
7972
|
-
}
|
|
7973
|
-
return config;
|
|
7974
|
-
} catch {
|
|
7975
|
-
return null;
|
|
7976
|
-
}
|
|
7977
|
-
}
|
|
7978
|
-
|
|
7979
|
-
// src/presence.ts
|
|
7980
8574
|
var REFRESH_THROTTLE_MS = 45e3;
|
|
7981
8575
|
var TTL_MINUTES = 120;
|
|
7982
8576
|
var BACKOFF_BASE_MS = 3e4;
|
|
@@ -7992,6 +8586,12 @@ function autoAnnounceDisabled(env, config) {
|
|
|
7992
8586
|
if (raw === "off" || raw === "0" || raw === "false") return true;
|
|
7993
8587
|
return config?.auto_announce === false;
|
|
7994
8588
|
}
|
|
8589
|
+
function autoWorkingPathsEnabled(env, config) {
|
|
8590
|
+
const raw = (env.MAIND_AUTO_WORKING_PATHS ?? "").trim().toLowerCase();
|
|
8591
|
+
if (raw === "on" || raw === "1" || raw === "true") return true;
|
|
8592
|
+
if (raw === "off" || raw === "0" || raw === "false") return false;
|
|
8593
|
+
return config?.auto_working_paths === true;
|
|
8594
|
+
}
|
|
7995
8595
|
var PresenceAnnouncer = class {
|
|
7996
8596
|
projectKey;
|
|
7997
8597
|
postToolCall;
|
|
@@ -8000,6 +8600,11 @@ var PresenceAnnouncer = class {
|
|
|
8000
8600
|
log;
|
|
8001
8601
|
machineLabel;
|
|
8002
8602
|
enabled;
|
|
8603
|
+
// ADR-277: consented enrichment + snapshot sink (both optional, fail-open).
|
|
8604
|
+
workingPathsEnabled;
|
|
8605
|
+
deriveWorkingPaths;
|
|
8606
|
+
snapshot;
|
|
8607
|
+
lastBranch = null;
|
|
8003
8608
|
sessionId;
|
|
8004
8609
|
lastAnnounceAt = 0;
|
|
8005
8610
|
inFlight = false;
|
|
@@ -8016,6 +8621,9 @@ var PresenceAnnouncer = class {
|
|
|
8016
8621
|
this.log = deps.log ?? ((msg) => process.stderr.write(msg + "\n"));
|
|
8017
8622
|
this.machineLabel = normalizeMachineLabel(config?.machine_label);
|
|
8018
8623
|
this.enabled = this.projectKey !== null && !autoAnnounceDisabled(env, config);
|
|
8624
|
+
this.workingPathsEnabled = autoWorkingPathsEnabled(env, config);
|
|
8625
|
+
this.deriveWorkingPaths = deps.deriveWorkingPaths ?? null;
|
|
8626
|
+
this.snapshot = deps.snapshot ?? null;
|
|
8019
8627
|
this.sessionId = resolveClientSessionId(env);
|
|
8020
8628
|
}
|
|
8021
8629
|
get isEnabled() {
|
|
@@ -8097,14 +8705,38 @@ var PresenceAnnouncer = class {
|
|
|
8097
8705
|
// skeleton row is indistinguishable from a sloppy agent session, which
|
|
8098
8706
|
// is how 16 of 23 rows came to say nothing AND not say why. Display hint
|
|
8099
8707
|
// only; the server keeps 'agent' once an agent has enriched the row.
|
|
8708
|
+
// ADR-277: the server ALSO keys its consent enforcement on this
|
|
8709
|
+
// self-declaration — infra-supplied working_paths are consent-gated,
|
|
8710
|
+
// deliberate agent declarations are not.
|
|
8100
8711
|
announce_source: "bridge"
|
|
8101
8712
|
};
|
|
8102
8713
|
if (status === "active") {
|
|
8103
8714
|
const branch = await this.gitBranch();
|
|
8104
8715
|
if (branch) args.branch = branch;
|
|
8716
|
+
this.lastBranch = branch;
|
|
8105
8717
|
if (this.machineLabel) args.machine_label = this.machineLabel;
|
|
8718
|
+
if (this.workingPathsEnabled && this.deriveWorkingPaths) {
|
|
8719
|
+
try {
|
|
8720
|
+
const wp = await this.deriveWorkingPaths();
|
|
8721
|
+
if (wp && wp.length > 0) args.working_paths = wp;
|
|
8722
|
+
} catch {
|
|
8723
|
+
}
|
|
8724
|
+
}
|
|
8725
|
+
}
|
|
8726
|
+
const payload = await this.postToolCall("announce_session", args);
|
|
8727
|
+
if (this.snapshot) {
|
|
8728
|
+
try {
|
|
8729
|
+
if (status === "ended") {
|
|
8730
|
+
this.snapshot.endSession();
|
|
8731
|
+
} else if (payload !== null && payload !== void 0) {
|
|
8732
|
+
this.snapshot.write(payload, {
|
|
8733
|
+
sessionId: this.sessionId,
|
|
8734
|
+
branch: this.lastBranch
|
|
8735
|
+
});
|
|
8736
|
+
}
|
|
8737
|
+
} catch {
|
|
8738
|
+
}
|
|
8106
8739
|
}
|
|
8107
|
-
await this.postToolCall("announce_session", args);
|
|
8108
8740
|
}
|
|
8109
8741
|
};
|
|
8110
8742
|
async function defaultGitBranch() {
|
|
@@ -8127,12 +8759,54 @@ function normalizeMachineLabel(raw) {
|
|
|
8127
8759
|
return v.length > 0 ? v : null;
|
|
8128
8760
|
}
|
|
8129
8761
|
|
|
8762
|
+
// src/index.ts
|
|
8763
|
+
init_presence_snapshot();
|
|
8764
|
+
|
|
8765
|
+
// src/working-paths.ts
|
|
8766
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
8767
|
+
var WORKING_PATHS_CAP = 8;
|
|
8768
|
+
var RAW_FILE_CAP = 32;
|
|
8769
|
+
function parsePorcelain(porcelain) {
|
|
8770
|
+
return porcelain.split("\n").filter((l) => l.trim().length > 0).map(
|
|
8771
|
+
(l) => (l.slice(3).split(" -> ").pop() ?? "").trim().replace(/^"|"$/g, "")
|
|
8772
|
+
).filter((p) => p.length > 0).slice(0, RAW_FILE_CAP);
|
|
8773
|
+
}
|
|
8774
|
+
function condenseToDirs(files, cap = WORKING_PATHS_CAP) {
|
|
8775
|
+
const out2 = [];
|
|
8776
|
+
for (const file of files) {
|
|
8777
|
+
const rel = file.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
|
|
8778
|
+
if (rel.length === 0) continue;
|
|
8779
|
+
const dir = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : rel;
|
|
8780
|
+
if (dir.length === 0 || out2.includes(dir)) continue;
|
|
8781
|
+
out2.push(dir);
|
|
8782
|
+
if (out2.length >= cap) break;
|
|
8783
|
+
}
|
|
8784
|
+
return out2;
|
|
8785
|
+
}
|
|
8786
|
+
async function deriveWorkingPaths(runGitStatus = defaultGitStatus) {
|
|
8787
|
+
const porcelain = await runGitStatus();
|
|
8788
|
+
if (porcelain === null) return null;
|
|
8789
|
+
const dirs = condenseToDirs(parsePorcelain(porcelain));
|
|
8790
|
+
return dirs.length > 0 ? dirs : null;
|
|
8791
|
+
}
|
|
8792
|
+
async function defaultGitStatus() {
|
|
8793
|
+
return await new Promise((resolve2) => {
|
|
8794
|
+
execFile2(
|
|
8795
|
+
"git",
|
|
8796
|
+
["status", "--porcelain"],
|
|
8797
|
+
{ timeout: 2e3, encoding: "utf8", maxBuffer: 1024 * 1024 },
|
|
8798
|
+
(err, stdout) => resolve2(err ? null : stdout)
|
|
8799
|
+
);
|
|
8800
|
+
});
|
|
8801
|
+
}
|
|
8802
|
+
|
|
8130
8803
|
// src/index.ts
|
|
8131
8804
|
var MAX_REAUTH_ATTEMPTS = 1;
|
|
8132
8805
|
var HOOK_SUBCOMMANDS = [
|
|
8133
8806
|
"on-session-start",
|
|
8134
8807
|
"on-tool-use",
|
|
8135
8808
|
"on-file-write",
|
|
8809
|
+
"on-file-edit",
|
|
8136
8810
|
"sync-config",
|
|
8137
8811
|
"flush",
|
|
8138
8812
|
"status"
|
|
@@ -8189,6 +8863,7 @@ async function main() {
|
|
|
8189
8863
|
"on-session-start": hooks.runOnSessionStart,
|
|
8190
8864
|
"on-tool-use": hooks.runOnToolUse,
|
|
8191
8865
|
"on-file-write": hooks.runOnFileWrite,
|
|
8866
|
+
"on-file-edit": hooks.runOnFileEdit,
|
|
8192
8867
|
"sync-config": hooks.runSyncConfig,
|
|
8193
8868
|
flush: hooks.runFlush,
|
|
8194
8869
|
status: hooks.runHookStatus
|
|
@@ -8241,7 +8916,9 @@ async function main() {
|
|
|
8241
8916
|
return Promise.reject(new Error("presence: no active forwarder"));
|
|
8242
8917
|
}
|
|
8243
8918
|
return currentForwarder.postPresenceToolCall(name, args);
|
|
8244
|
-
}
|
|
8919
|
+
},
|
|
8920
|
+
deriveWorkingPaths: () => deriveWorkingPaths(),
|
|
8921
|
+
snapshot: projectKey !== null ? createSnapshotStore({ projectKey }) : void 0
|
|
8245
8922
|
});
|
|
8246
8923
|
if (presence.isEnabled) {
|
|
8247
8924
|
const endAndExit = (code) => {
|
|
@@ -8305,6 +8982,7 @@ function printHelp() {
|
|
|
8305
8982
|
" on-session-start open a tracked session (Tier-3 flat metrics)",
|
|
8306
8983
|
" on-tool-use bump counters + evaluate the ADR-039 context advisory",
|
|
8307
8984
|
" on-file-write block a Write that claims a taken number (ADR-263)",
|
|
8985
|
+
" on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)",
|
|
8308
8986
|
" on-session-end session analytics + close/flush the tracked session",
|
|
8309
8987
|
" sync-config pull your context thresholds from the server (ADR-039)",
|
|
8310
8988
|
" flush post queued Tier-3 metrics now",
|