@maind-dev/mcp-bridge 0.24.0 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -84,7 +84,7 @@ ${original}`
84
84
  return JSON.stringify({ jsonrpc: "2.0", id, result });
85
85
  }
86
86
  function fallbackMarker(cachedAt, now) {
87
- 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.`;
87
+ 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.`;
88
88
  }
89
89
  function relativeAge(cachedAt, now) {
90
90
  const then = Date.parse(cachedAt);
@@ -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.24.0";
205
+ BRIDGE_VERSION = "0.25.1";
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",
@@ -1065,9 +1123,104 @@ var init_history = __esm({
1065
1123
  }
1066
1124
  });
1067
1125
 
1068
- // ../../packages/code-index/build/repo-health/divergence.js
1126
+ // ../../packages/code-index/build/repo-health/hooks.js
1069
1127
  import { execFileSync as execFileSync4 } from "node:child_process";
1070
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
1128
+ import { readdirSync as readdirSync2, statSync as statSync2 } from "node:fs";
1129
+ import { isAbsolute as isAbsolute2, join as join11, relative, resolve as resolve2 } from "node:path";
1130
+ function isRealHook(name) {
1131
+ return !name.endsWith(".sample") && !name.startsWith(".");
1132
+ }
1133
+ function gitConfig(root, key) {
1134
+ try {
1135
+ const out2 = execFileSync4("git", ["-C", root, "config", "--get", key], {
1136
+ encoding: "utf-8",
1137
+ timeout: 5e3,
1138
+ stdio: ["ignore", "pipe", "ignore"]
1139
+ }).trim();
1140
+ return out2.length > 0 ? out2 : null;
1141
+ } catch {
1142
+ return null;
1143
+ }
1144
+ }
1145
+ function hasExecutableHook(dir) {
1146
+ let entries;
1147
+ try {
1148
+ entries = readdirSync2(dir);
1149
+ } catch {
1150
+ return null;
1151
+ }
1152
+ for (const name of entries.filter(isRealHook)) {
1153
+ try {
1154
+ const st = statSync2(join11(dir, name));
1155
+ if (st.isFile() && (st.mode & 73) !== 0)
1156
+ return true;
1157
+ } catch {
1158
+ }
1159
+ }
1160
+ return false;
1161
+ }
1162
+ function isDir(p) {
1163
+ try {
1164
+ return statSync2(p).isDirectory();
1165
+ } catch {
1166
+ return false;
1167
+ }
1168
+ }
1169
+ function displayPath(root, absolute) {
1170
+ const rel = relative(root, absolute);
1171
+ return !rel || rel.startsWith("..") ? absolute : rel;
1172
+ }
1173
+ function resolveHookState(root) {
1174
+ const hookDirs = VERSIONED_HOOK_DIRS.filter((d) => isDir(join11(root, d)));
1175
+ const hooksPath = gitConfig(root, "core.hooksPath");
1176
+ const effectiveAbs = hooksPath ? isAbsolute2(hooksPath) ? hooksPath : resolve2(root, hooksPath) : join11(root, ".git", "hooks");
1177
+ const effectiveDir = displayPath(root, effectiveAbs);
1178
+ const found = hasExecutableHook(effectiveAbs);
1179
+ if (found === true) {
1180
+ return {
1181
+ verdict: "wired",
1182
+ reason: hooksPath ? "wired" : "default_path",
1183
+ hookDirs,
1184
+ hooksPath,
1185
+ effectiveDir
1186
+ };
1187
+ }
1188
+ const reason = hooksPath ? found === null ? "path_missing" : "path_empty" : hookDirs.length > 0 ? "path_unset" : "no_hooks";
1189
+ return {
1190
+ verdict: hookDirs.length > 0 ? "present_unwired" : "absent",
1191
+ reason,
1192
+ hookDirs,
1193
+ hooksPath,
1194
+ effectiveDir
1195
+ };
1196
+ }
1197
+ function describeHookState(state) {
1198
+ switch (state.reason) {
1199
+ case "wired":
1200
+ return `Git-Gates aktiv (core.hooksPath \u2192 ${state.effectiveDir}).`;
1201
+ case "default_path":
1202
+ return "Git-Gates aktiv (.git/hooks, nicht versioniert).";
1203
+ case "path_unset":
1204
+ return `${state.hookDirs.join(", ")} liegt im Repo, aber core.hooksPath ist ungesetzt \u2014 kein Gate feuert.`;
1205
+ case "path_missing":
1206
+ return `core.hooksPath zeigt auf ${state.effectiveDir}, das es nicht gibt \u2014 git f\xFChrt keinen Hook aus.`;
1207
+ case "path_empty":
1208
+ return `core.hooksPath zeigt auf ${state.effectiveDir}, dort liegt kein ausf\xFChrbarer Hook.`;
1209
+ case "no_hooks":
1210
+ return "Keine Git-Hooks im Repo.";
1211
+ }
1212
+ }
1213
+ var VERSIONED_HOOK_DIRS;
1214
+ var init_hooks = __esm({
1215
+ "../../packages/code-index/build/repo-health/hooks.js"() {
1216
+ "use strict";
1217
+ VERSIONED_HOOK_DIRS = [".githooks", ".husky"];
1218
+ }
1219
+ });
1220
+
1221
+ // ../../packages/code-index/build/repo-health/divergence.js
1222
+ import { execFileSync as execFileSync5 } from "node:child_process";
1223
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
1071
1224
  import { posix as posix3 } from "node:path";
1072
1225
  function computeDivergence(facts) {
1073
1226
  const out2 = [];
@@ -1192,8 +1345,23 @@ function computeDivergence(facts) {
1192
1345
  hint: "Check the CI provider's billing/spending status before debugging code."
1193
1346
  });
1194
1347
  }
1348
+ const hookFinding = computeHookFinding(facts.hooks);
1349
+ if (hookFinding)
1350
+ out2.push(hookFinding);
1195
1351
  return sortFindings(out2);
1196
1352
  }
1353
+ function computeHookFinding(hooks) {
1354
+ if (!hooks || hooks.verdict !== "present_unwired")
1355
+ return null;
1356
+ return {
1357
+ id: "setup.hooks-unwired",
1358
+ status: "warn",
1359
+ scope: "setup",
1360
+ title: "Git-Hooks liegen im Repo, feuern aber nicht",
1361
+ detail: describeHookState(hooks),
1362
+ hint: hooks.reason === "path_missing" ? `core.hooksPath zeigt ins Leere. Korrigieren: git config core.hooksPath ${hooks.hookDirs[0] ?? ".githooks"}` : `git config core.hooksPath ${hooks.hookDirs[0] ?? ".githooks"} \u2014 git klont das Verzeichnis mit, den Pfad nie.`
1363
+ };
1364
+ }
1197
1365
  function sortFindings(f) {
1198
1366
  return [...f].sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status] || a.id.localeCompare(b.id));
1199
1367
  }
@@ -1222,12 +1390,12 @@ function detectInProgressOp(repoRoot) {
1222
1390
  if (!gitDir)
1223
1391
  return null;
1224
1392
  const base = posix3.isAbsolute(gitDir) ? gitDir : posix3.join(repoRoot, gitDir);
1225
- if (existsSync3(posix3.join(base, "rebase-merge")) || existsSync3(posix3.join(base, "rebase-apply"))) {
1393
+ if (existsSync4(posix3.join(base, "rebase-merge")) || existsSync4(posix3.join(base, "rebase-apply"))) {
1226
1394
  return "rebase";
1227
1395
  }
1228
- if (existsSync3(posix3.join(base, "MERGE_HEAD")))
1396
+ if (existsSync4(posix3.join(base, "MERGE_HEAD")))
1229
1397
  return "merge";
1230
- if (existsSync3(posix3.join(base, "CHERRY_PICK_HEAD")))
1398
+ if (existsSync4(posix3.join(base, "CHERRY_PICK_HEAD")))
1231
1399
  return "cherry-pick";
1232
1400
  return null;
1233
1401
  }
@@ -1255,10 +1423,10 @@ function parseWorktrees(raw) {
1255
1423
  }
1256
1424
  function readWorktreeRequirements(repoRoot) {
1257
1425
  const p = posix3.join(repoRoot, WORKTREE_REQUIREMENTS_RELPATH);
1258
- if (!existsSync3(p))
1426
+ if (!existsSync4(p))
1259
1427
  return [];
1260
1428
  try {
1261
- return readFileSync3(p, "utf8").split("\n").map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("#"));
1429
+ return readFileSync4(p, "utf8").split("\n").map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("#"));
1262
1430
  } catch {
1263
1431
  return [];
1264
1432
  }
@@ -1282,7 +1450,8 @@ async function gatherRepoHealthFacts(repoRoot, opts = {}) {
1282
1450
  otherWorktrees: 0,
1283
1451
  worktreeParity: null,
1284
1452
  release: null,
1285
- unmergedMigrations: []
1453
+ unmergedMigrations: [],
1454
+ hooks: null
1286
1455
  };
1287
1456
  }
1288
1457
  const branchRaw = trimOrNull(runGit(repoRoot, ["rev-parse", "--abbrev-ref", "HEAD"]));
@@ -1325,7 +1494,7 @@ async function gatherRepoHealthFacts(repoRoot, opts = {}) {
1325
1494
  ...readWorktreeRequirements(toplevel),
1326
1495
  ...opts.probePaths ?? []
1327
1496
  ];
1328
- const missing = probes.filter((rel) => existsSync3(posix3.join(mainWorktree, rel)) && !existsSync3(posix3.join(toplevel, rel)));
1497
+ const missing = probes.filter((rel) => existsSync4(posix3.join(mainWorktree, rel)) && !existsSync4(posix3.join(toplevel, rel)));
1329
1498
  worktreeParity = {
1330
1499
  mainWorktreePath: mainWorktree,
1331
1500
  currentWorktreePath: toplevel,
@@ -1361,7 +1530,8 @@ async function gatherRepoHealthFacts(repoRoot, opts = {}) {
1361
1530
  otherWorktrees,
1362
1531
  worktreeParity,
1363
1532
  release: release2,
1364
- unmergedMigrations
1533
+ unmergedMigrations,
1534
+ hooks: resolveHookState(repoRoot)
1365
1535
  };
1366
1536
  }
1367
1537
  function samePath(a, b) {
@@ -1392,7 +1562,7 @@ function gatherReleaseFact(repoRoot, branch) {
1392
1562
  }
1393
1563
  function runGh(repoRoot, args) {
1394
1564
  try {
1395
- return execFileSync4("gh", args, {
1565
+ return execFileSync5("gh", args, {
1396
1566
  cwd: repoRoot,
1397
1567
  encoding: "utf8",
1398
1568
  stdio: ["ignore", "pipe", "ignore"],
@@ -1412,6 +1582,7 @@ var DEFAULT_WORKTREE_PROBE_PATHS, WORKTREE_REQUIREMENTS_RELPATH, STATUS_ORDER;
1412
1582
  var init_divergence = __esm({
1413
1583
  "../../packages/code-index/build/repo-health/divergence.js"() {
1414
1584
  "use strict";
1585
+ init_hooks();
1415
1586
  init_discover();
1416
1587
  DEFAULT_WORKTREE_PROBE_PATHS = [
1417
1588
  "supabase/config.toml",
@@ -1424,7 +1595,7 @@ var init_divergence = __esm({
1424
1595
  });
1425
1596
 
1426
1597
  // ../../packages/code-index/build/repo-health/number-collisions.js
1427
- import { existsSync as existsSync4, readdirSync as readdirSync2 } from "node:fs";
1598
+ import { existsSync as existsSync5, readdirSync as readdirSync3 } from "node:fs";
1428
1599
  import { posix as posix4 } from "node:path";
1429
1600
  function isCounterNamespace(numbers, opts = {}) {
1430
1601
  const minFiles = opts.minFiles ?? DEFAULT_MIN_FILES;
@@ -1628,10 +1799,10 @@ async function gatherNumberCollisionFacts(repoRoot, opts = {}) {
1628
1799
  };
1629
1800
  for (const dir of dirs) {
1630
1801
  const abs = posix4.join(repoRoot, dir);
1631
- if (!existsSync4(abs))
1802
+ if (!existsSync5(abs))
1632
1803
  continue;
1633
1804
  try {
1634
- for (const file of readdirSync2(abs))
1805
+ for (const file of readdirSync3(abs))
1635
1806
  record(`${dir}/${file}`, "self", "this worktree");
1636
1807
  } catch {
1637
1808
  skipped.push(`could not read ${dir}`);
@@ -1655,14 +1826,14 @@ async function gatherNumberCollisionFacts(repoRoot, opts = {}) {
1655
1826
  if (!line.startsWith("worktree "))
1656
1827
  continue;
1657
1828
  const root = line.slice("worktree ".length).trim();
1658
- if (!root || root === selfRoot || !existsSync4(root))
1829
+ if (!root || root === selfRoot || !existsSync5(root))
1659
1830
  continue;
1660
1831
  for (const dir of dirs) {
1661
1832
  const abs = posix4.join(root, dir);
1662
- if (!existsSync4(abs))
1833
+ if (!existsSync5(abs))
1663
1834
  continue;
1664
1835
  try {
1665
- for (const file of readdirSync2(abs)) {
1836
+ for (const file of readdirSync3(abs)) {
1666
1837
  record(`${dir}/${file}`, "worktree", `Worktree ${root}`);
1667
1838
  }
1668
1839
  } catch {
@@ -1932,7 +2103,7 @@ var init_identifiers = __esm({
1932
2103
  });
1933
2104
 
1934
2105
  // ../../packages/code-index/build/query/engine.js
1935
- import { readFileSync as readFileSync4 } from "node:fs";
2106
+ import { readFileSync as readFileSync5 } from "node:fs";
1936
2107
  import { posix as posix5 } from "node:path";
1937
2108
  function toHit(n) {
1938
2109
  return {
@@ -2214,7 +2385,7 @@ var init_engine = __esm({
2214
2385
  return null;
2215
2386
  let source = "";
2216
2387
  try {
2217
- const full = readFileSync4(posix5.join(this.repoRoot, n.filePath), "utf8");
2388
+ const full = readFileSync5(posix5.join(this.repoRoot, n.filePath), "utf8");
2218
2389
  source = full.slice(n.startByte, n.endByte);
2219
2390
  } catch {
2220
2391
  return null;
@@ -2354,7 +2525,7 @@ var init_engine = __esm({
2354
2525
  }
2355
2526
  readRepoFile(relPath) {
2356
2527
  try {
2357
- return readFileSync4(posix5.join(this.repoRoot, relPath), "utf8");
2528
+ return readFileSync5(posix5.join(this.repoRoot, relPath), "utf8");
2358
2529
  } catch {
2359
2530
  return null;
2360
2531
  }
@@ -2385,6 +2556,7 @@ var init_build = __esm({
2385
2556
  init_history();
2386
2557
  init_risk_rules();
2387
2558
  init_divergence();
2559
+ init_hooks();
2388
2560
  init_number_collisions();
2389
2561
  init_types();
2390
2562
  init_types2();
@@ -2393,6 +2565,135 @@ var init_build = __esm({
2393
2565
  }
2394
2566
  });
2395
2567
 
2568
+ // src/presence-snapshot.ts
2569
+ import {
2570
+ mkdirSync as mkdirSync4,
2571
+ readdirSync as readdirSync4,
2572
+ readFileSync as readFileSync7,
2573
+ renameSync as renameSync2,
2574
+ statSync as statSync3,
2575
+ unlinkSync,
2576
+ writeFileSync as writeFileSync3
2577
+ } from "node:fs";
2578
+ import { homedir as homedir3 } from "node:os";
2579
+ import { join as join13 } from "node:path";
2580
+ function presenceSnapshotBaseDir() {
2581
+ return join13(homedir3(), ".maind", "presence");
2582
+ }
2583
+ function projectDir(baseDir, projectKey) {
2584
+ return join13(baseDir, projectKey);
2585
+ }
2586
+ function createSnapshotStore(opts) {
2587
+ const baseDir = opts.baseDir ?? presenceSnapshotBaseDir();
2588
+ const dir = projectDir(baseDir, opts.projectKey);
2589
+ const pid = opts.pid ?? process.pid;
2590
+ const ppid = opts.ppid ?? process.ppid;
2591
+ const cwd = opts.cwd ?? process.cwd();
2592
+ const now = opts.now ?? Date.now;
2593
+ let ownFile = null;
2594
+ return {
2595
+ write(payload, meta) {
2596
+ try {
2597
+ if (typeof payload !== "object" || payload === null) return;
2598
+ const p = payload;
2599
+ if (p.ok !== true) return;
2600
+ const snapshot = {
2601
+ v: 1,
2602
+ written_at: new Date(now()).toISOString(),
2603
+ project_key: opts.projectKey,
2604
+ own_session_id: meta.sessionId,
2605
+ own_pid: pid,
2606
+ own_ppid: ppid,
2607
+ cwd,
2608
+ branch: meta.branch,
2609
+ peers: Array.isArray(p.peers) ? p.peers : [],
2610
+ conflicts: Array.isArray(p.conflicts) ? p.conflicts : []
2611
+ };
2612
+ mkdirSync4(dir, { recursive: true, mode: 448 });
2613
+ ownFile = join13(dir, `${meta.sessionId}.json`);
2614
+ const tmp = `${ownFile}.tmp-${pid}`;
2615
+ writeFileSync3(tmp, JSON.stringify(snapshot), { mode: 384 });
2616
+ renameSync2(tmp, ownFile);
2617
+ pruneStale(dir, now(), ownFile);
2618
+ } catch {
2619
+ }
2620
+ },
2621
+ endSession() {
2622
+ try {
2623
+ if (ownFile) unlinkSync(ownFile);
2624
+ } catch {
2625
+ }
2626
+ }
2627
+ };
2628
+ }
2629
+ function pruneStale(dir, nowMs, keep) {
2630
+ try {
2631
+ for (const name of readdirSync4(dir)) {
2632
+ if (!name.endsWith(".json")) continue;
2633
+ const file = join13(dir, name);
2634
+ if (file === keep) continue;
2635
+ try {
2636
+ const age = nowMs - statSync3(file).mtimeMs;
2637
+ if (age > SNAPSHOT_TTL_MS) unlinkSync(file);
2638
+ } catch {
2639
+ }
2640
+ }
2641
+ } catch {
2642
+ }
2643
+ }
2644
+ function readSnapshots(projectKey, baseDir = presenceSnapshotBaseDir()) {
2645
+ try {
2646
+ const dir = projectDir(baseDir, projectKey);
2647
+ const out2 = [];
2648
+ for (const name of readdirSync4(dir)) {
2649
+ if (!name.endsWith(".json")) continue;
2650
+ try {
2651
+ const raw = JSON.parse(
2652
+ readFileSync7(join13(dir, name), "utf8")
2653
+ );
2654
+ const snap = parseSnapshot(raw);
2655
+ if (snap) out2.push(snap);
2656
+ } catch {
2657
+ }
2658
+ }
2659
+ out2.sort((a, b) => b.written_at.localeCompare(a.written_at));
2660
+ return out2;
2661
+ } catch {
2662
+ return [];
2663
+ }
2664
+ }
2665
+ function parseSnapshot(raw) {
2666
+ if (typeof raw !== "object" || raw === null) return null;
2667
+ const o = raw;
2668
+ if (o.v !== 1) return null;
2669
+ if (typeof o.written_at !== "string") return null;
2670
+ if (typeof o.project_key !== "string") return null;
2671
+ if (typeof o.own_session_id !== "string") return null;
2672
+ if (typeof o.own_pid !== "number" || typeof o.own_ppid !== "number") {
2673
+ return null;
2674
+ }
2675
+ if (typeof o.cwd !== "string") return null;
2676
+ return {
2677
+ v: 1,
2678
+ written_at: o.written_at,
2679
+ project_key: o.project_key,
2680
+ own_session_id: o.own_session_id,
2681
+ own_pid: o.own_pid,
2682
+ own_ppid: o.own_ppid,
2683
+ cwd: o.cwd,
2684
+ branch: typeof o.branch === "string" ? o.branch : null,
2685
+ peers: Array.isArray(o.peers) ? o.peers : [],
2686
+ conflicts: Array.isArray(o.conflicts) ? o.conflicts : []
2687
+ };
2688
+ }
2689
+ var SNAPSHOT_TTL_MS;
2690
+ var init_presence_snapshot = __esm({
2691
+ "src/presence-snapshot.ts"() {
2692
+ "use strict";
2693
+ SNAPSHOT_TTL_MS = 120 * 6e4;
2694
+ }
2695
+ });
2696
+
2396
2697
  // ../../packages/claude-code-telemetry/dist/types.js
2397
2698
  var init_types4 = __esm({
2398
2699
  "../../packages/claude-code-telemetry/dist/types.js"() {
@@ -2403,7 +2704,7 @@ var init_types4 = __esm({
2403
2704
  // ../../packages/claude-code-telemetry/dist/transcript.js
2404
2705
  import { createReadStream, existsSync as existsSync6 } from "node:fs";
2405
2706
  import { stat } from "node:fs/promises";
2406
- import { createInterface as createInterface4 } from "node:readline";
2707
+ import { createInterface as createInterface5 } from "node:readline";
2407
2708
  async function summariseTranscript(path8) {
2408
2709
  if (!path8 || !existsSync6(path8))
2409
2710
  return null;
@@ -2416,9 +2717,9 @@ async function summariseTranscript(path8) {
2416
2717
  let input = 0;
2417
2718
  let output = 0;
2418
2719
  let lines2 = 0;
2419
- return await new Promise((resolve2) => {
2720
+ return await new Promise((resolve3) => {
2420
2721
  const stream = createReadStream(path8, { encoding: "utf-8" });
2421
- const rl = createInterface4({ input: stream });
2722
+ const rl = createInterface5({ input: stream });
2422
2723
  rl.on("line", (line) => {
2423
2724
  const trimmed = line.trim();
2424
2725
  if (!trimmed)
@@ -2437,7 +2738,7 @@ async function summariseTranscript(path8) {
2437
2738
  }
2438
2739
  });
2439
2740
  rl.on("close", () => {
2440
- resolve2({
2741
+ resolve3({
2441
2742
  input_tokens: input,
2442
2743
  output_tokens: output,
2443
2744
  total_tokens: input + output,
@@ -2445,8 +2746,8 @@ async function summariseTranscript(path8) {
2445
2746
  last_modified_ms: stats.mtimeMs
2446
2747
  });
2447
2748
  });
2448
- rl.on("error", () => resolve2(null));
2449
- stream.on("error", () => resolve2(null));
2749
+ rl.on("error", () => resolve3(null));
2750
+ stream.on("error", () => resolve3(null));
2450
2751
  });
2451
2752
  }
2452
2753
  var init_transcript = __esm({
@@ -2491,7 +2792,7 @@ var init_effort = __esm({
2491
2792
 
2492
2793
  // ../../packages/claude-code-telemetry/dist/session-analysis.js
2493
2794
  import { createReadStream as createReadStream2, existsSync as existsSync7 } from "node:fs";
2494
- import { createInterface as createInterface5 } from "node:readline";
2795
+ import { createInterface as createInterface6 } from "node:readline";
2495
2796
  function num2(v) {
2496
2797
  return typeof v === "number" && Number.isFinite(v) ? v : 0;
2497
2798
  }
@@ -2602,9 +2903,9 @@ async function analyzeSession(path8) {
2602
2903
  let effort = null;
2603
2904
  let priorAssistantWorked = false;
2604
2905
  let prevUserText = null;
2605
- await new Promise((resolve2) => {
2906
+ await new Promise((resolve3) => {
2606
2907
  const stream = createReadStream2(path8, { encoding: "utf-8" });
2607
- const rl = createInterface5({ input: stream });
2908
+ const rl = createInterface6({ input: stream });
2608
2909
  const processLine = (line) => {
2609
2910
  const trimmed = line.trim();
2610
2911
  if (!trimmed)
@@ -2700,9 +3001,9 @@ async function analyzeSession(path8) {
2700
3001
  } catch {
2701
3002
  }
2702
3003
  });
2703
- rl.on("close", () => resolve2());
2704
- rl.on("error", () => resolve2());
2705
- stream.on("error", () => resolve2());
3004
+ rl.on("close", () => resolve3());
3005
+ rl.on("error", () => resolve3());
3006
+ stream.on("error", () => resolve3());
2706
3007
  });
2707
3008
  a.effort_at_end = effort;
2708
3009
  a.model_mix = [...modelMix.values()].sort((x, y) => x.first_ts - y.first_ts || x.model.localeCompare(y.model));
@@ -2775,7 +3076,7 @@ var init_ingest = __esm({
2775
3076
 
2776
3077
  // ../../packages/claude-code-telemetry/dist/session-span.js
2777
3078
  import { createReadStream as createReadStream3, existsSync as existsSync8 } from "node:fs";
2778
- import { createInterface as createInterface6 } from "node:readline";
3079
+ import { createInterface as createInterface7 } from "node:readline";
2779
3080
  function asBlocks2(content) {
2780
3081
  if (typeof content === "string")
2781
3082
  return [{ type: "text", text: content }];
@@ -2834,9 +3135,9 @@ async function analyzeSpan(path8) {
2834
3135
  let prevMs = null;
2835
3136
  let prevHolder = "human";
2836
3137
  const pauses = [];
2837
- await new Promise((resolve2) => {
3138
+ await new Promise((resolve3) => {
2838
3139
  const stream = createReadStream3(path8, { encoding: "utf-8" });
2839
- const rl = createInterface6({ input: stream });
3140
+ const rl = createInterface7({ input: stream });
2840
3141
  const processLine = (line) => {
2841
3142
  const trimmed = line.trim();
2842
3143
  if (!trimmed)
@@ -2892,9 +3193,9 @@ async function analyzeSpan(path8) {
2892
3193
  } catch {
2893
3194
  }
2894
3195
  });
2895
- rl.on("close", () => resolve2());
2896
- rl.on("error", () => resolve2());
2897
- stream.on("error", () => resolve2());
3196
+ rl.on("close", () => resolve3());
3197
+ rl.on("error", () => resolve3());
3198
+ stream.on("error", () => resolve3());
2898
3199
  });
2899
3200
  if (firstMs === null)
2900
3201
  return s;
@@ -2938,14 +3239,14 @@ var init_windows = __esm({
2938
3239
  });
2939
3240
 
2940
3241
  // ../../packages/claude-code-telemetry/dist/projects.js
2941
- import { homedir as homedir3 } from "node:os";
2942
- import { join as join12 } from "node:path";
3242
+ import { homedir as homedir4 } from "node:os";
3243
+ import { join as join14 } from "node:path";
2943
3244
  var HOME, DEFAULT_PROJECTS_DIR;
2944
3245
  var init_projects = __esm({
2945
3246
  "../../packages/claude-code-telemetry/dist/projects.js"() {
2946
3247
  "use strict";
2947
- HOME = homedir3();
2948
- DEFAULT_PROJECTS_DIR = join12(HOME, ".claude", "projects");
3248
+ HOME = homedir4();
3249
+ DEFAULT_PROJECTS_DIR = join14(HOME, ".claude", "projects");
2949
3250
  }
2950
3251
  });
2951
3252
 
@@ -3018,13 +3319,13 @@ var init_api = __esm({
3018
3319
  async function readHookInput() {
3019
3320
  if (process.stdin.isTTY) return {};
3020
3321
  const chunks = [];
3021
- return await new Promise((resolve2) => {
3322
+ return await new Promise((resolve3) => {
3022
3323
  let settled = false;
3023
3324
  const settle = (value) => {
3024
3325
  if (settled) return;
3025
3326
  settled = true;
3026
3327
  clearTimeout(timer);
3027
- resolve2(value);
3328
+ resolve3(value);
3028
3329
  };
3029
3330
  const timer = setTimeout(() => settle({}), STDIN_TIMEOUT_MS);
3030
3331
  process.stdin.on("data", (c) => chunks.push(c));
@@ -3056,11 +3357,119 @@ var init_hook_input = __esm({
3056
3357
  }
3057
3358
  });
3058
3359
 
3360
+ // src/hooks/edit-guard.ts
3361
+ function prefixConflict(a, b) {
3362
+ if (a === b) return true;
3363
+ if (a === "" || b === "") return true;
3364
+ return a.startsWith(b + "/") || b.startsWith(a + "/");
3365
+ }
3366
+ function parsePeers(snap, ageSeconds) {
3367
+ const out2 = [];
3368
+ for (const raw of snap.peers) {
3369
+ if (typeof raw !== "object" || raw === null) continue;
3370
+ const p = raw;
3371
+ const claimsRaw = Array.isArray(p.active_claims) ? p.active_claims : [];
3372
+ const claims = [];
3373
+ for (const c of claimsRaw) {
3374
+ if (typeof c !== "object" || c === null) continue;
3375
+ const cc = c;
3376
+ if (typeof cc.path_prefix !== "string") continue;
3377
+ const exp = typeof cc.expires_in_seconds === "number" ? cc.expires_in_seconds : 0;
3378
+ const remaining = exp - ageSeconds;
3379
+ if (remaining <= 0) continue;
3380
+ claims.push({
3381
+ path_prefix: cc.path_prefix,
3382
+ note: typeof cc.note === "string" ? cc.note : null,
3383
+ remaining_seconds: Math.round(remaining)
3384
+ });
3385
+ }
3386
+ out2.push({
3387
+ session_id_short: typeof p.session_id_short === "string" ? p.session_id_short : "?",
3388
+ is_own_user: p.is_own_user === true,
3389
+ branch: typeof p.branch === "string" ? p.branch : null,
3390
+ focus: typeof p.focus === "string" ? p.focus : null,
3391
+ machine_label: typeof p.machine_label === "string" ? p.machine_label : null,
3392
+ last_seen_seconds: typeof p.last_seen_seconds === "number" ? p.last_seen_seconds : 0,
3393
+ claims,
3394
+ working_paths: Array.isArray(p.working_paths) ? p.working_paths.filter((w) => typeof w === "string") : []
3395
+ });
3396
+ }
3397
+ return out2;
3398
+ }
3399
+ function selectOwnSnapshot(snaps, opts) {
3400
+ if (opts.grandparentPid !== null) {
3401
+ const byPpid = snaps.find((s) => s.own_ppid === opts.grandparentPid);
3402
+ if (byPpid) return { snap: byPpid, via: "ppid" };
3403
+ }
3404
+ const byCwd = snaps.find((s) => s.cwd === opts.cwd);
3405
+ if (byCwd) return { snap: byCwd, via: "cwd" };
3406
+ return null;
3407
+ }
3408
+ function ageDisplay(seconds) {
3409
+ if (seconds < 90) return `${Math.max(1, Math.round(seconds))}s`;
3410
+ return `${Math.round(seconds / 60)}m`;
3411
+ }
3412
+ function adviseOnPath(snap, relPath, opts) {
3413
+ const maxAge = opts.maxAgeMs ?? SNAPSHOT_MAX_AGE_MS;
3414
+ const ageMs = opts.nowMs - Date.parse(snap.written_at);
3415
+ if (!Number.isFinite(ageMs) || ageMs < 0 || ageMs > maxAge) return null;
3416
+ const ageSeconds = ageMs / 1e3;
3417
+ const peers = parsePeers(snap, ageSeconds);
3418
+ const hits = [];
3419
+ for (const peer of peers) {
3420
+ if (opts.via === "cwd") {
3421
+ if (opts.currentBranch === null || peer.branch === null) continue;
3422
+ if (peer.branch === opts.currentBranch) continue;
3423
+ }
3424
+ for (const claim of peer.claims) {
3425
+ if (!prefixConflict(relPath, claim.path_prefix)) continue;
3426
+ hits.push(
3427
+ `'${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)}`
3428
+ );
3429
+ }
3430
+ if (opts.via === "ppid" && peer.is_own_user) {
3431
+ for (const wp of peer.working_paths) {
3432
+ if (!prefixConflict(relPath, wp)) continue;
3433
+ hits.push(
3434
+ `'${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`
3435
+ );
3436
+ break;
3437
+ }
3438
+ }
3439
+ }
3440
+ if (hits.length === 0) return null;
3441
+ return `[maind coordination] Editing '${relPath}' overlaps parallel work (view as of ${ageDisplay(ageSeconds)} ago, advisory \u2014 never a lock):
3442
+ ` + hits.map((h) => ` \u2022 ${h}`).join("\n") + `
3443
+ Verify live before large edits: check_path_conflicts({project_key: "${snap.project_key}", paths: ["${relPath}"]}) \u2014 then claim_paths for your own edit area.`;
3444
+ }
3445
+ function sessionStartSummary(snap, nowMs, maxAgeMs = SNAPSHOT_MAX_AGE_MS) {
3446
+ if (!snap) return null;
3447
+ const ageMs = nowMs - Date.parse(snap.written_at);
3448
+ if (!Number.isFinite(ageMs) || ageMs < 0 || ageMs > maxAgeMs) return null;
3449
+ const ageSeconds = ageMs / 1e3;
3450
+ const peers = parsePeers(snap, ageSeconds);
3451
+ if (peers.length === 0) return null;
3452
+ const claimCount = peers.reduce((n, p) => n + p.claims.length, 0);
3453
+ const signalPoor = peers.filter(
3454
+ (p) => p.focus === null && p.working_paths.length === 0 && p.claims.length === 0
3455
+ ).length;
3456
+ const claimsText = claimCount > 0 ? `${claimCount} active claim${claimCount === 1 ? "" : "s"}` : "no active claims";
3457
+ const poorText = signalPoor > 0 ? `, ${signalPoor} presence-only` : "";
3458
+ 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: [...]}).`;
3459
+ }
3460
+ var SNAPSHOT_MAX_AGE_MS;
3461
+ var init_edit_guard = __esm({
3462
+ "src/hooks/edit-guard.ts"() {
3463
+ "use strict";
3464
+ SNAPSHOT_MAX_AGE_MS = 10 * 6e4;
3465
+ }
3466
+ });
3467
+
3059
3468
  // src/hooks/state.ts
3060
3469
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, rename as rename2 } from "node:fs/promises";
3061
3470
  import { existsSync as existsSync9 } from "node:fs";
3062
- import { homedir as homedir4 } from "node:os";
3063
- import { join as join13 } from "node:path";
3471
+ import { homedir as homedir5 } from "node:os";
3472
+ import { join as join15 } from "node:path";
3064
3473
  function emptyState() {
3065
3474
  return { config: null, sessions: {}, pending_metrics: [] };
3066
3475
  }
@@ -3099,8 +3508,8 @@ var STATE_DIR, STATE_FILE, DEFAULT_THRESHOLDS;
3099
3508
  var init_state = __esm({
3100
3509
  "src/hooks/state.ts"() {
3101
3510
  "use strict";
3102
- STATE_DIR = join13(homedir4(), ".maind");
3103
- STATE_FILE = join13(STATE_DIR, "state.json");
3511
+ STATE_DIR = join15(homedir5(), ".maind");
3512
+ STATE_FILE = join15(STATE_DIR, "state.json");
3104
3513
  DEFAULT_THRESHOLDS = {
3105
3514
  warn_at_pct: 60,
3106
3515
  handoff_at_pct: 85,
@@ -3115,16 +3524,18 @@ __export(hooks_exports, {
3115
3524
  effectiveConfig: () => effectiveConfig,
3116
3525
  runFlush: () => runFlush,
3117
3526
  runHookStatus: () => runHookStatus,
3527
+ runOnFileEdit: () => runOnFileEdit,
3118
3528
  runOnFileWrite: () => runOnFileWrite,
3119
3529
  runOnSessionStart: () => runOnSessionStart,
3120
3530
  runOnToolUse: () => runOnToolUse,
3121
3531
  runSessionEndMetrics: () => runSessionEndMetrics,
3122
3532
  runSyncConfig: () => runSyncConfig
3123
3533
  });
3124
- import { existsSync as existsSync10, readFileSync as readFileSync7, realpathSync } from "node:fs";
3534
+ import { execFileSync as execFileSync7 } from "node:child_process";
3535
+ import { existsSync as existsSync10, readFileSync as readFileSync8, realpathSync } from "node:fs";
3125
3536
  import { writeFile as writeFile3 } from "node:fs/promises";
3126
- import { homedir as homedir5 } from "node:os";
3127
- import { basename, dirname as dirname5, isAbsolute as isAbsolute2, join as join14, relative } from "node:path";
3537
+ import { homedir as homedir6 } from "node:os";
3538
+ import { basename, dirname as dirname5, isAbsolute as isAbsolute3, join as join16, relative as relative2 } from "node:path";
3128
3539
  function effectiveConfig(state) {
3129
3540
  if (state.config) return state.config;
3130
3541
  const key = readApiKey();
@@ -3152,8 +3563,54 @@ async function runOnSessionStart() {
3152
3563
  if (sessionId === null) return 0;
3153
3564
  getOrCreateSession(state, sessionId);
3154
3565
  await saveState(state);
3566
+ try {
3567
+ const projectKey = computeProjectKey();
3568
+ if (projectKey !== null) {
3569
+ const snaps = readSnapshots(projectKey);
3570
+ const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
3571
+ const own = selectOwnSnapshot(snaps, {
3572
+ grandparentPid: grandparentPid(),
3573
+ cwd
3574
+ });
3575
+ const summary = sessionStartSummary(own?.snap ?? snaps[0] ?? null, Date.now());
3576
+ if (summary !== null) process.stdout.write(summary + "\n");
3577
+ }
3578
+ } catch {
3579
+ }
3580
+ try {
3581
+ const wiring = inspectHookWiring(readSettingsRaw());
3582
+ if (hasWiringDrift(wiring) && needsInstallRun(wiring)) {
3583
+ const missing = wiring.filter((f) => f.remedy === "run-install").map((f) => f.subcommand).join(", ");
3584
+ process.stderr.write(
3585
+ `[maind] New bridge capability not yet wired (${missing}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
3586
+ `
3587
+ );
3588
+ }
3589
+ } catch {
3590
+ }
3155
3591
  return 0;
3156
3592
  }
3593
+ function readSettingsRaw() {
3594
+ try {
3595
+ const p = join16(homedir6(), ".claude", "settings.json");
3596
+ return existsSync10(p) ? readFileSync8(p, "utf8") : null;
3597
+ } catch {
3598
+ return null;
3599
+ }
3600
+ }
3601
+ function grandparentPid() {
3602
+ try {
3603
+ if (process.platform === "win32") return null;
3604
+ const out2 = execFileSync7("ps", ["-o", "ppid=", "-p", String(process.ppid)], {
3605
+ timeout: 1e3,
3606
+ encoding: "utf8"
3607
+ });
3608
+ const pid = Number.parseInt(out2.trim(), 10);
3609
+ return Number.isFinite(pid) && pid > 0 ? pid : null;
3610
+ } catch {
3611
+ return null;
3612
+ }
3613
+ }
3157
3614
  async function runOnToolUse() {
3158
3615
  const state = await loadState();
3159
3616
  if (effectiveConfig(state) === null) return 0;
@@ -3185,7 +3642,7 @@ function realpathOfUnwritten(p) {
3185
3642
  for (; ; ) {
3186
3643
  try {
3187
3644
  const real = realpathSync(head);
3188
- return join14(real, ...tail.reverse());
3645
+ return join16(real, ...tail.reverse());
3189
3646
  } catch {
3190
3647
  const parent = dirname5(head);
3191
3648
  if (parent === head) return p;
@@ -3219,11 +3676,11 @@ async function runOnFileWrite() {
3219
3676
  const filePath = toolFilePathOf(input);
3220
3677
  if (!filePath) return 0;
3221
3678
  const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
3222
- const abs = isAbsolute2(filePath) ? filePath : join14(cwd, filePath);
3679
+ const abs = isAbsolute3(filePath) ? filePath : join16(cwd, filePath);
3223
3680
  if (existsSync10(abs)) return 0;
3224
3681
  const repoRoot = resolveRepoRoot(cwd);
3225
- const rel = relative(repoRoot, realpathOfUnwritten(abs));
3226
- if (rel.length === 0 || rel.startsWith("..") || isAbsolute2(rel)) return 0;
3682
+ const rel = relative2(repoRoot, realpathOfUnwritten(abs));
3683
+ if (rel.length === 0 || rel.startsWith("..") || isAbsolute3(rel)) return 0;
3227
3684
  const verdict = await checkNumberForPath(repoRoot, rel);
3228
3685
  if (!verdict.taken || verdict.namespace === null) return 0;
3229
3686
  process.stdout.write(denyPayload(denyReason(verdict, verdict.namespace)));
@@ -3232,6 +3689,61 @@ async function runOnFileWrite() {
3232
3689
  return 0;
3233
3690
  }
3234
3691
  }
3692
+ function advisoryPayload(context) {
3693
+ return JSON.stringify({
3694
+ hookSpecificOutput: {
3695
+ hookEventName: "PreToolUse",
3696
+ additionalContext: context
3697
+ }
3698
+ });
3699
+ }
3700
+ async function runOnFileEdit() {
3701
+ try {
3702
+ const input = await readHookInput();
3703
+ const tool = (input.tool_name ?? "").toString();
3704
+ if (tool !== "Edit" && tool !== "Write") return 0;
3705
+ const filePath = toolFilePathOf(input);
3706
+ if (!filePath) return 0;
3707
+ const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
3708
+ const abs = isAbsolute3(filePath) ? filePath : join16(cwd, filePath);
3709
+ const projectKey = computeProjectKey();
3710
+ if (projectKey === null) return 0;
3711
+ const snaps = readSnapshots(projectKey);
3712
+ if (snaps.length === 0) return 0;
3713
+ const own = selectOwnSnapshot(snaps, {
3714
+ grandparentPid: grandparentPid(),
3715
+ cwd
3716
+ });
3717
+ if (own === null) return 0;
3718
+ const repoRoot = resolveRepoRoot(cwd);
3719
+ const real = existsSync10(abs) ? realpathSync(abs) : realpathOfUnwritten(abs);
3720
+ const rel = relative2(repoRoot, real).replace(/\\/g, "/");
3721
+ if (rel.length === 0 || rel.startsWith("..") || isAbsolute3(rel)) return 0;
3722
+ const advice = adviseOnPath(own.snap, rel, {
3723
+ via: own.via,
3724
+ currentBranch: own.via === "cwd" ? currentGitBranch(cwd) : null,
3725
+ nowMs: Date.now()
3726
+ });
3727
+ if (advice === null) return 0;
3728
+ process.stdout.write(advisoryPayload(advice));
3729
+ return 0;
3730
+ } catch {
3731
+ return 0;
3732
+ }
3733
+ }
3734
+ function currentGitBranch(cwd) {
3735
+ try {
3736
+ const out2 = execFileSync7("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
3737
+ cwd,
3738
+ timeout: 1e3,
3739
+ encoding: "utf8"
3740
+ });
3741
+ const branch = out2.trim();
3742
+ return branch.length > 0 && branch !== "HEAD" ? branch : null;
3743
+ } catch {
3744
+ return null;
3745
+ }
3746
+ }
3235
3747
  async function maybeEmitAdvisory(state, session) {
3236
3748
  const t = resolveThresholds(state);
3237
3749
  const tokens = session.token_count ?? 0;
@@ -3256,7 +3768,7 @@ async function maybeEmitAdvisory(state, session) {
3256
3768
  };
3257
3769
  try {
3258
3770
  await writeFile3(
3259
- join14(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
3771
+ join16(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
3260
3772
  JSON.stringify(payload, null, 2)
3261
3773
  );
3262
3774
  } catch (err) {
@@ -3335,7 +3847,7 @@ async function flushPending(config, timeoutMs) {
3335
3847
  const batch = state.pending_metrics.slice(0, 100);
3336
3848
  const post = postMetrics(config.endpoint, config.api_key, batch);
3337
3849
  const timeout = new Promise(
3338
- (resolve2) => setTimeout(() => resolve2({ ok: false, inserted: 0, error: "timeout" }), timeoutMs)
3850
+ (resolve3) => setTimeout(() => resolve3({ ok: false, inserted: 0, error: "timeout" }), timeoutMs)
3339
3851
  );
3340
3852
  const result = await Promise.race([post, timeout]);
3341
3853
  if (result.ok) {
@@ -3395,10 +3907,10 @@ async function runHookStatus() {
3395
3907
  return 0;
3396
3908
  }
3397
3909
  function readHookWiring() {
3398
- const settingsPath = join14(homedir5(), ".claude", "settings.json");
3910
+ const settingsPath = join16(homedir6(), ".claude", "settings.json");
3399
3911
  let raw = null;
3400
3912
  try {
3401
- if (existsSync10(settingsPath)) raw = readFileSync7(settingsPath, "utf8");
3913
+ if (existsSync10(settingsPath)) raw = readFileSync8(settingsPath, "utf8");
3402
3914
  } catch {
3403
3915
  }
3404
3916
  return { settingsPath, findings: inspectHookWiring(raw) };
@@ -3473,7 +3985,7 @@ function sessionIdOf(input) {
3473
3985
  return id.length > 0 ? id : null;
3474
3986
  }
3475
3987
  var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS, WIRING_REMEDY;
3476
- var init_hooks = __esm({
3988
+ var init_hooks2 = __esm({
3477
3989
  "src/hooks/index.ts"() {
3478
3990
  "use strict";
3479
3991
  init_dist();
@@ -3481,7 +3993,10 @@ var init_hooks = __esm({
3481
3993
  init_conventions_cache();
3482
3994
  init_device_id();
3483
3995
  init_hook_wiring();
3996
+ init_presence_snapshot();
3997
+ init_project_key();
3484
3998
  init_api();
3999
+ init_edit_guard();
3485
4000
  init_hook_input();
3486
4001
  init_state();
3487
4002
  DEFAULT_THRESHOLDS_ENDPOINT = process.env.MAIND_THRESHOLDS_ENDPOINT ?? "https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds";
@@ -3511,7 +4026,7 @@ async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
3511
4026
  },
3512
4027
  body: JSON.stringify(body)
3513
4028
  }).then(() => void 0).catch(() => void 0);
3514
- const timeout = new Promise((resolve2) => setTimeout(resolve2, timeoutMs));
4029
+ const timeout = new Promise((resolve3) => setTimeout(resolve3, timeoutMs));
3515
4030
  await Promise.race([post, timeout]);
3516
4031
  }
3517
4032
  async function runOnSessionEnd() {
@@ -3555,7 +4070,7 @@ var init_session_end = __esm({
3555
4070
  init_device_id();
3556
4071
  init_api();
3557
4072
  init_hook_input();
3558
- init_hooks();
4073
+ init_hooks2();
3559
4074
  init_version();
3560
4075
  INGEST_ENDPOINT = DEFAULT_INGEST_ENDPOINT;
3561
4076
  }
@@ -3843,14 +4358,16 @@ var Forwarder = class {
3843
4358
  emitJsonRpcError(id, -32001, `bridge auth error: ${body.slice(0, 200)}`);
3844
4359
  }
3845
4360
  /**
3846
- * Auto-presence transport (ADR-242): post a self-generated `tools/call` on
3847
- * the forwarder's EXISTING MCP session. The response is drained and NEVER
3848
- * written to stdout — the local client must not see frames it didn't send.
3849
- * String-namespaced ids keep the frame disjoint from the client's numeric
3850
- * JSON-RPC ids. Riding the shared session (instead of opening a second one)
3851
- * keeps the server's session accounting honest AND carries the detected
4361
+ * Auto-presence transport (ADR-242, revised ADR-277): post a self-generated
4362
+ * `tools/call` on the forwarder's EXISTING MCP session. The response is
4363
+ * PARSED and returned to the announcer (peers/conflicts feed the local
4364
+ * snapshot) — and still NEVER written to stdout: the local client must not
4365
+ * see frames it didn't send. String-namespaced ids keep the frame disjoint
4366
+ * from the client's numeric JSON-RPC ids. Riding the shared session keeps
4367
+ * the server's session accounting honest AND carries the detected
3852
4368
  * client-family headers, so the announce row shows the real client.
3853
- * Throws on any failure — the announcer turns that into backoff, fail-open.
4369
+ * Throws on transport failure — the announcer turns that into backoff;
4370
+ * an unparseable body resolves to null (fail-open), never throws.
3854
4371
  */
3855
4372
  async postPresenceToolCall(name, args) {
3856
4373
  if (this.sessionId === null) {
@@ -3868,10 +4385,11 @@ var Forwarder = class {
3868
4385
  headers: this.buildHeaders(true),
3869
4386
  body: frame
3870
4387
  });
3871
- await response.text().catch(() => "");
4388
+ const body = await response.text().catch(() => "");
3872
4389
  if (!response.ok) {
3873
4390
  throw new Error(`presence: upstream HTTP ${response.status}`);
3874
4391
  }
4392
+ return parsePresenceToolResult(body);
3875
4393
  }
3876
4394
  /**
3877
4395
  * Build the outbound header set. `includeSession` attaches the current
@@ -4135,6 +4653,24 @@ function extractHint(lowerBody) {
4135
4653
  if (lowerBody.includes("device_required")) return "device_required";
4136
4654
  return "auth_failed";
4137
4655
  }
4656
+ function parsePresenceToolResult(body) {
4657
+ try {
4658
+ const trimmed = body.trim();
4659
+ if (trimmed.length === 0) return null;
4660
+ let envelopeRaw = trimmed;
4661
+ if (!trimmed.startsWith("{")) {
4662
+ const dataLines = trimmed.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("data:"));
4663
+ if (dataLines.length === 0) return null;
4664
+ envelopeRaw = dataLines[dataLines.length - 1].slice(5).trim();
4665
+ }
4666
+ const envelope = JSON.parse(envelopeRaw);
4667
+ const text = envelope.result?.content?.[0]?.text;
4668
+ if (typeof text !== "string") return null;
4669
+ return JSON.parse(text);
4670
+ } catch {
4671
+ return null;
4672
+ }
4673
+ }
4138
4674
 
4139
4675
  // src/index.ts
4140
4676
  init_device_id();
@@ -4211,7 +4747,7 @@ async function pollOnce(url, deviceCode) {
4211
4747
  return await res.json();
4212
4748
  }
4213
4749
  function sleep(ms) {
4214
- return new Promise((resolve2) => setTimeout(resolve2, ms));
4750
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
4215
4751
  }
4216
4752
  function printAuthInstructions(start, out2) {
4217
4753
  const lines2 = [
@@ -4253,7 +4789,7 @@ async function openExternalBrowser(url) {
4253
4789
  args = [url];
4254
4790
  break;
4255
4791
  }
4256
- return new Promise((resolve2, reject) => {
4792
+ return new Promise((resolve3, reject) => {
4257
4793
  try {
4258
4794
  const child = spawn(cmd, args, {
4259
4795
  stdio: "ignore",
@@ -4261,7 +4797,7 @@ async function openExternalBrowser(url) {
4261
4797
  });
4262
4798
  child.on("error", reject);
4263
4799
  child.unref();
4264
- resolve2();
4800
+ resolve3();
4265
4801
  } catch (err) {
4266
4802
  reject(err);
4267
4803
  }
@@ -4270,50 +4806,7 @@ async function openExternalBrowser(url) {
4270
4806
 
4271
4807
  // src/index.ts
4272
4808
  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
- }
4809
+ init_project_key();
4317
4810
 
4318
4811
  // src/install/index.ts
4319
4812
  init_version();
@@ -4334,6 +4827,7 @@ function parseInstallFlags(argv) {
4334
4827
  client: null,
4335
4828
  skipCodex: false,
4336
4829
  dryRun: false,
4830
+ autoWorkingPaths: false,
4337
4831
  help: false
4338
4832
  };
4339
4833
  for (let i = 0; i < argv.length; i++) {
@@ -4364,6 +4858,9 @@ function parseInstallFlags(argv) {
4364
4858
  case "--dry-run":
4365
4859
  flags.dryRun = true;
4366
4860
  break;
4861
+ case "--auto-working-paths":
4862
+ flags.autoWorkingPaths = true;
4863
+ break;
4367
4864
  case "--project-root": {
4368
4865
  const next = argv[i + 1];
4369
4866
  if (next === void 0 || next.startsWith("--")) {
@@ -4425,11 +4922,11 @@ var InstallFlagError = class extends Error {
4425
4922
  function printInstallHelp() {
4426
4923
  const help = [
4427
4924
  "",
4428
- "@maind-dev/mcp-bridge install \u2014 one-shot setup for the maind MCP server.",
4925
+ "@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.",
4429
4926
  "",
4430
- "Detects your project root, pairs this device with maind, merges the",
4927
+ "Detects your project root, pairs this device with MAIND, merges the",
4431
4928
  "MCP-server entry into every supported AI-client config it finds, and",
4432
- "(optionally) writes the maind preamble block into CLAUDE.md / AGENTS.md /",
4929
+ "(optionally) writes the MAIND preamble block into CLAUDE.md / AGENTS.md /",
4433
4930
  "Cursor / Windsurf / Copilot files. Idempotent \u2014 re-running is safe.",
4434
4931
  "",
4435
4932
  "Usage:",
@@ -4629,8 +5126,8 @@ Which one should receive the MCP config and preamble files? [1-${candidates.leng
4629
5126
  output: process.stdout,
4630
5127
  terminal: true
4631
5128
  });
4632
- const answer = await new Promise((resolve2) => {
4633
- rl.question("", (input) => resolve2(input.trim()));
5129
+ const answer = await new Promise((resolve3) => {
5130
+ rl.question("", (input) => resolve3(input.trim()));
4634
5131
  });
4635
5132
  rl.close();
4636
5133
  if (answer === "") return candidates[0];
@@ -6037,6 +6534,9 @@ async function mergeToolUseHook(opts) {
6037
6534
  async function mergeFileWriteHook(opts) {
6038
6535
  return mergeSubcommandHook(opts, managed("on-file-write"));
6039
6536
  }
6537
+ async function mergeFileEditHook(opts) {
6538
+ return mergeSubcommandHook(opts, managed("on-file-edit"));
6539
+ }
6040
6540
  function findExistingHookCommand(settings, event, pattern) {
6041
6541
  const groups = settings.hooks?.[event];
6042
6542
  if (!Array.isArray(groups)) return null;
@@ -6059,8 +6559,8 @@ async function promptYesNo(out2, prompt) {
6059
6559
  output: out2,
6060
6560
  terminal: true
6061
6561
  });
6062
- const answer = await new Promise((resolve2) => {
6063
- rl.question("", (input) => resolve2(input.trim().toLowerCase()));
6562
+ const answer = await new Promise((resolve3) => {
6563
+ rl.question("", (input) => resolve3(input.trim().toLowerCase()));
6064
6564
  });
6065
6565
  rl.close();
6066
6566
  if (answer === "" || answer === "y" || answer === "yes") return true;
@@ -6073,6 +6573,130 @@ function errMessage(err) {
6073
6573
  return err instanceof Error ? err.message : String(err);
6074
6574
  }
6075
6575
 
6576
+ // src/install/working-paths-consent.ts
6577
+ import * as readline3 from "node:readline";
6578
+
6579
+ // src/bridge-config.ts
6580
+ init_device_id();
6581
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
6582
+ import { join as join8 } from "node:path";
6583
+ function bridgeConfigPath() {
6584
+ return join8(configDir(), "config.json");
6585
+ }
6586
+ function readBridgeConfig() {
6587
+ try {
6588
+ const file = bridgeConfigPath();
6589
+ if (!existsSync3(file)) return null;
6590
+ const raw = JSON.parse(readFileSync3(file, "utf8"));
6591
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
6592
+ return null;
6593
+ }
6594
+ const o = raw;
6595
+ const config = {};
6596
+ if (typeof o.auto_announce === "boolean") {
6597
+ config.auto_announce = o.auto_announce;
6598
+ }
6599
+ if (typeof o.machine_label === "string") {
6600
+ config.machine_label = o.machine_label;
6601
+ }
6602
+ if (typeof o.auto_working_paths === "boolean") {
6603
+ config.auto_working_paths = o.auto_working_paths;
6604
+ }
6605
+ return config;
6606
+ } catch {
6607
+ return null;
6608
+ }
6609
+ }
6610
+
6611
+ // src/install/working-paths-consent.ts
6612
+ var TARGET_KEY = "config:auto_working_paths";
6613
+ 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]: ';
6614
+ async function applyWorkingPathsConsent(opts) {
6615
+ const configPath = opts.configPath ?? bridgeConfigPath();
6616
+ let existing = {};
6617
+ try {
6618
+ const raw = await readFileSafe(configPath);
6619
+ if (raw !== null && raw.trim().length > 0) {
6620
+ const parsed = JSON.parse(raw);
6621
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6622
+ existing = parsed;
6623
+ }
6624
+ }
6625
+ } catch {
6626
+ }
6627
+ if (typeof existing.auto_working_paths === "boolean") {
6628
+ return {
6629
+ target: TARGET_KEY,
6630
+ action: "skip",
6631
+ status: "skipped",
6632
+ detail: `already decided (${existing.auto_working_paths ? "enabled" : "disabled"}) in ${configPath}`
6633
+ };
6634
+ }
6635
+ let consent;
6636
+ if (opts.explicitFlag) {
6637
+ consent = true;
6638
+ } else if (!opts.isInteractive) {
6639
+ return {
6640
+ target: TARGET_KEY,
6641
+ action: "skip",
6642
+ status: "skipped",
6643
+ detail: "consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"
6644
+ };
6645
+ } else if (opts.dryRun) {
6646
+ return {
6647
+ target: TARGET_KEY,
6648
+ action: "merge",
6649
+ status: "would-merge",
6650
+ detail: `${configPath} (would prompt for consent in real run)`
6651
+ };
6652
+ } else {
6653
+ const promptFn = opts.promptFn ?? promptYesNoDefaultNo;
6654
+ consent = await promptFn(opts.out, WORKING_PATHS_CONSENT_PROMPT);
6655
+ }
6656
+ if (!consent) {
6657
+ return {
6658
+ target: TARGET_KEY,
6659
+ action: "skip",
6660
+ status: "skipped",
6661
+ detail: "user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"
6662
+ };
6663
+ }
6664
+ const next = { ...existing, auto_working_paths: true };
6665
+ const nextRaw = JSON.stringify(next, null, 2) + "\n";
6666
+ if (opts.dryRun) {
6667
+ return { target: TARGET_KEY, action: "merge", status: "would-merge", detail: configPath };
6668
+ }
6669
+ try {
6670
+ await atomicWriteFile(configPath, nextRaw, 384);
6671
+ } catch (err) {
6672
+ return {
6673
+ target: TARGET_KEY,
6674
+ action: "merge",
6675
+ status: "failed",
6676
+ detail: `write: ${err instanceof Error ? err.message : String(err)}`
6677
+ };
6678
+ }
6679
+ return {
6680
+ target: TARGET_KEY,
6681
+ action: "merge",
6682
+ status: "merged",
6683
+ detail: `${configPath} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`
6684
+ };
6685
+ }
6686
+ async function promptYesNoDefaultNo(out2, prompt) {
6687
+ out2.write(prompt);
6688
+ const rl = readline3.createInterface({
6689
+ input: process.stdin,
6690
+ output: out2,
6691
+ terminal: true
6692
+ });
6693
+ const answer = await new Promise((resolve3) => {
6694
+ rl.question("", (input) => resolve3(input.trim().toLowerCase()));
6695
+ });
6696
+ rl.close();
6697
+ return answer === "y" || answer === "yes";
6698
+ }
6699
+
6076
6700
  // src/install/browser-pair.ts
6077
6701
  init_device_id();
6078
6702
 
@@ -6260,7 +6884,7 @@ function validateTokenShape(token) {
6260
6884
  }
6261
6885
  if (!/^mnd_[A-Za-z0-9_]+$/.test(trimmed)) {
6262
6886
  throw new Error(
6263
- "--token does not match maind api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?"
6887
+ "--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?"
6264
6888
  );
6265
6889
  }
6266
6890
  return trimmed;
@@ -6333,7 +6957,7 @@ function parseNodeMajor(version) {
6333
6957
  }
6334
6958
 
6335
6959
  // src/local-tools/engine.ts
6336
- import { execFileSync as execFileSync5 } from "node:child_process";
6960
+ import { execFileSync as execFileSync6 } from "node:child_process";
6337
6961
  import { createRequire as createRequire3 } from "node:module";
6338
6962
 
6339
6963
  // ../../packages/code-index/build/node.js
@@ -6343,7 +6967,7 @@ import { posix as posix6 } from "node:path";
6343
6967
  // ../../packages/code-index/build/parse/tree-sitter/parser.js
6344
6968
  init_keys();
6345
6969
  init_types();
6346
- import { join as join9 } from "node:path";
6970
+ import { join as join10 } from "node:path";
6347
6971
  import Parser from "web-tree-sitter";
6348
6972
 
6349
6973
  // ../../packages/code-index/build/parse/lang/python.js
@@ -6644,7 +7268,7 @@ function stripQuotes(s) {
6644
7268
 
6645
7269
  // ../../packages/code-index/build/parse/tree-sitter/grammars.js
6646
7270
  import { createRequire } from "node:module";
6647
- import { join as join8 } from "node:path";
7271
+ import { join as join9 } from "node:path";
6648
7272
  var GRAMMAR_FILE = {
6649
7273
  typescript: "tree-sitter-typescript.wasm",
6650
7274
  tsx: "tree-sitter-tsx.wasm",
@@ -6654,7 +7278,7 @@ var GRAMMAR_FILE = {
6654
7278
  var CORE_WASM_FILE = "tree-sitter.wasm";
6655
7279
  function grammarPath(language, assetDir) {
6656
7280
  if (assetDir)
6657
- return join8(assetDir, GRAMMAR_FILE[language]);
7281
+ return join9(assetDir, GRAMMAR_FILE[language]);
6658
7282
  return createRequire(import.meta.url).resolve(`tree-sitter-wasms/out/${GRAMMAR_FILE[language]}`);
6659
7283
  }
6660
7284
 
@@ -6671,7 +7295,7 @@ var TreeSitterParser = class {
6671
7295
  async init() {
6672
7296
  if (this.initialized)
6673
7297
  return;
6674
- await Parser.init(this.assetDir ? { locateFile: (file) => join9(this.assetDir, file || CORE_WASM_FILE) } : void 0);
7298
+ await Parser.init(this.assetDir ? { locateFile: (file) => join10(this.assetDir, file || CORE_WASM_FILE) } : void 0);
6675
7299
  this.parser = new Parser();
6676
7300
  this.initialized = true;
6677
7301
  }
@@ -7148,7 +7772,7 @@ function isNativeStoreUnavailable(err) {
7148
7772
  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.";
7149
7773
  function resolveRepoRoot2(cwd = process.cwd()) {
7150
7774
  try {
7151
- const top = execFileSync5("git", ["rev-parse", "--show-toplevel"], {
7775
+ const top = execFileSync6("git", ["rev-parse", "--show-toplevel"], {
7152
7776
  cwd,
7153
7777
  encoding: "utf8",
7154
7778
  stdio: ["ignore", "pipe", "ignore"],
@@ -7301,7 +7925,16 @@ Skipping remaining steps.
7301
7925
  report.add(await mergeSessionStartMetricsHook(hookOpts));
7302
7926
  report.add(await mergeToolUseHook(hookOpts));
7303
7927
  report.add(await mergeFileWriteHook(hookOpts));
7928
+ report.add(await mergeFileEditHook(hookOpts));
7304
7929
  report.add(await mergeStopHook(hookOpts));
7930
+ report.add(
7931
+ await applyWorkingPathsConsent({
7932
+ isInteractive,
7933
+ explicitFlag: flags.autoWorkingPaths,
7934
+ dryRun: flags.dryRun,
7935
+ out: process.stdout
7936
+ })
7937
+ );
7305
7938
  const nativeProbe = probeNativeStore();
7306
7939
  if (!nativeProbe.ok) {
7307
7940
  report.add({
@@ -7355,8 +7988,8 @@ Finished in ${wallClockSec}s. Restart your MCP client so it picks up the new ser
7355
7988
  }
7356
7989
 
7357
7990
  // src/local-tools/savings.ts
7358
- import { readFileSync as readFileSync5 } from "node:fs";
7359
- import { join as join10 } from "node:path";
7991
+ import { readFileSync as readFileSync6 } from "node:fs";
7992
+ import { join as join12 } from "node:path";
7360
7993
 
7361
7994
  // src/local-tools/token-estimate.ts
7362
7995
  var CHARS_PER_TOKEN = 4;
@@ -7388,7 +8021,7 @@ var SavingsAggregator = class {
7388
8021
  };
7389
8022
  function readFileCapped(absPath) {
7390
8023
  try {
7391
- const content = readFileSync5(absPath, "utf8");
8024
+ const content = readFileSync6(absPath, "utf8");
7392
8025
  return content.length > MAX_FILE_BYTES ? content.slice(0, MAX_FILE_BYTES) : content;
7393
8026
  } catch {
7394
8027
  return "";
@@ -7411,14 +8044,14 @@ function measureLocalToolSaved(name, result, serialized, repoRoot) {
7411
8044
  if (files.length === 0) return 0;
7412
8045
  let wholeTokens = 0;
7413
8046
  for (const fp of files) {
7414
- wholeTokens += estimateTokens(readFileCapped(join10(repoRoot, fp)));
8047
+ wholeTokens += estimateTokens(readFileCapped(join12(repoRoot, fp)));
7415
8048
  }
7416
8049
  return Math.max(0, wholeTokens - resultTokens);
7417
8050
  }
7418
8051
  if (name === "codebase_snippet") {
7419
8052
  const fp = result?.filePath;
7420
8053
  if (typeof fp !== "string" || fp.length === 0) return 0;
7421
- const wholeTokens = estimateTokens(readFileCapped(join10(repoRoot, fp)));
8054
+ const wholeTokens = estimateTokens(readFileCapped(join12(repoRoot, fp)));
7422
8055
  return Math.max(0, wholeTokens - resultTokens);
7423
8056
  }
7424
8057
  return 0;
@@ -8052,37 +8685,6 @@ async function postSavingsMetric(input) {
8052
8685
  // src/presence.ts
8053
8686
  import { execFile } from "node:child_process";
8054
8687
  import { randomUUID as randomUUID2 } from "node:crypto";
8055
-
8056
- // src/bridge-config.ts
8057
- init_device_id();
8058
- import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
8059
- import { join as join11 } from "node:path";
8060
- function bridgeConfigPath() {
8061
- return join11(configDir(), "config.json");
8062
- }
8063
- function readBridgeConfig() {
8064
- try {
8065
- const file = bridgeConfigPath();
8066
- if (!existsSync5(file)) return null;
8067
- const raw = JSON.parse(readFileSync6(file, "utf8"));
8068
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
8069
- return null;
8070
- }
8071
- const o = raw;
8072
- const config = {};
8073
- if (typeof o.auto_announce === "boolean") {
8074
- config.auto_announce = o.auto_announce;
8075
- }
8076
- if (typeof o.machine_label === "string") {
8077
- config.machine_label = o.machine_label;
8078
- }
8079
- return config;
8080
- } catch {
8081
- return null;
8082
- }
8083
- }
8084
-
8085
- // src/presence.ts
8086
8688
  var REFRESH_THROTTLE_MS = 45e3;
8087
8689
  var TTL_MINUTES = 120;
8088
8690
  var BACKOFF_BASE_MS = 3e4;
@@ -8098,6 +8700,12 @@ function autoAnnounceDisabled(env, config) {
8098
8700
  if (raw === "off" || raw === "0" || raw === "false") return true;
8099
8701
  return config?.auto_announce === false;
8100
8702
  }
8703
+ function autoWorkingPathsEnabled(env, config) {
8704
+ const raw = (env.MAIND_AUTO_WORKING_PATHS ?? "").trim().toLowerCase();
8705
+ if (raw === "on" || raw === "1" || raw === "true") return true;
8706
+ if (raw === "off" || raw === "0" || raw === "false") return false;
8707
+ return config?.auto_working_paths === true;
8708
+ }
8101
8709
  var PresenceAnnouncer = class {
8102
8710
  projectKey;
8103
8711
  postToolCall;
@@ -8106,6 +8714,11 @@ var PresenceAnnouncer = class {
8106
8714
  log;
8107
8715
  machineLabel;
8108
8716
  enabled;
8717
+ // ADR-277: consented enrichment + snapshot sink (both optional, fail-open).
8718
+ workingPathsEnabled;
8719
+ deriveWorkingPaths;
8720
+ snapshot;
8721
+ lastBranch = null;
8109
8722
  sessionId;
8110
8723
  lastAnnounceAt = 0;
8111
8724
  inFlight = false;
@@ -8122,6 +8735,9 @@ var PresenceAnnouncer = class {
8122
8735
  this.log = deps.log ?? ((msg) => process.stderr.write(msg + "\n"));
8123
8736
  this.machineLabel = normalizeMachineLabel(config?.machine_label);
8124
8737
  this.enabled = this.projectKey !== null && !autoAnnounceDisabled(env, config);
8738
+ this.workingPathsEnabled = autoWorkingPathsEnabled(env, config);
8739
+ this.deriveWorkingPaths = deps.deriveWorkingPaths ?? null;
8740
+ this.snapshot = deps.snapshot ?? null;
8125
8741
  this.sessionId = resolveClientSessionId(env);
8126
8742
  }
8127
8743
  get isEnabled() {
@@ -8157,7 +8773,7 @@ var PresenceAnnouncer = class {
8157
8773
  this.ended = true;
8158
8774
  if (this.lastAnnounceAt === 0) return;
8159
8775
  const timeout = new Promise(
8160
- (resolve2) => setTimeout(resolve2, END_TIMEOUT_MS).unref()
8776
+ (resolve3) => setTimeout(resolve3, END_TIMEOUT_MS).unref()
8161
8777
  );
8162
8778
  await Promise.race([this.send("ended"), timeout]);
8163
8779
  }
@@ -8203,26 +8819,50 @@ var PresenceAnnouncer = class {
8203
8819
  // skeleton row is indistinguishable from a sloppy agent session, which
8204
8820
  // is how 16 of 23 rows came to say nothing AND not say why. Display hint
8205
8821
  // only; the server keeps 'agent' once an agent has enriched the row.
8822
+ // ADR-277: the server ALSO keys its consent enforcement on this
8823
+ // self-declaration — infra-supplied working_paths are consent-gated,
8824
+ // deliberate agent declarations are not.
8206
8825
  announce_source: "bridge"
8207
8826
  };
8208
8827
  if (status === "active") {
8209
8828
  const branch = await this.gitBranch();
8210
8829
  if (branch) args.branch = branch;
8830
+ this.lastBranch = branch;
8211
8831
  if (this.machineLabel) args.machine_label = this.machineLabel;
8832
+ if (this.workingPathsEnabled && this.deriveWorkingPaths) {
8833
+ try {
8834
+ const wp = await this.deriveWorkingPaths();
8835
+ if (wp && wp.length > 0) args.working_paths = wp;
8836
+ } catch {
8837
+ }
8838
+ }
8839
+ }
8840
+ const payload = await this.postToolCall("announce_session", args);
8841
+ if (this.snapshot) {
8842
+ try {
8843
+ if (status === "ended") {
8844
+ this.snapshot.endSession();
8845
+ } else if (payload !== null && payload !== void 0) {
8846
+ this.snapshot.write(payload, {
8847
+ sessionId: this.sessionId,
8848
+ branch: this.lastBranch
8849
+ });
8850
+ }
8851
+ } catch {
8852
+ }
8212
8853
  }
8213
- await this.postToolCall("announce_session", args);
8214
8854
  }
8215
8855
  };
8216
8856
  async function defaultGitBranch() {
8217
- return await new Promise((resolve2) => {
8857
+ return await new Promise((resolve3) => {
8218
8858
  execFile(
8219
8859
  "git",
8220
8860
  ["rev-parse", "--abbrev-ref", "HEAD"],
8221
8861
  { timeout: 2e3, encoding: "utf8" },
8222
8862
  (err, stdout) => {
8223
- if (err) return resolve2(null);
8863
+ if (err) return resolve3(null);
8224
8864
  const branch = stdout.trim();
8225
- resolve2(branch.length > 0 && branch !== "HEAD" ? branch : null);
8865
+ resolve3(branch.length > 0 && branch !== "HEAD" ? branch : null);
8226
8866
  }
8227
8867
  );
8228
8868
  });
@@ -8233,12 +8873,54 @@ function normalizeMachineLabel(raw) {
8233
8873
  return v.length > 0 ? v : null;
8234
8874
  }
8235
8875
 
8876
+ // src/index.ts
8877
+ init_presence_snapshot();
8878
+
8879
+ // src/working-paths.ts
8880
+ import { execFile as execFile2 } from "node:child_process";
8881
+ var WORKING_PATHS_CAP = 8;
8882
+ var RAW_FILE_CAP = 32;
8883
+ function parsePorcelain(porcelain) {
8884
+ return porcelain.split("\n").filter((l) => l.trim().length > 0).map(
8885
+ (l) => (l.slice(3).split(" -> ").pop() ?? "").trim().replace(/^"|"$/g, "")
8886
+ ).filter((p) => p.length > 0).slice(0, RAW_FILE_CAP);
8887
+ }
8888
+ function condenseToDirs(files, cap = WORKING_PATHS_CAP) {
8889
+ const out2 = [];
8890
+ for (const file of files) {
8891
+ const rel = file.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
8892
+ if (rel.length === 0) continue;
8893
+ const dir = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : rel;
8894
+ if (dir.length === 0 || out2.includes(dir)) continue;
8895
+ out2.push(dir);
8896
+ if (out2.length >= cap) break;
8897
+ }
8898
+ return out2;
8899
+ }
8900
+ async function deriveWorkingPaths(runGitStatus = defaultGitStatus) {
8901
+ const porcelain = await runGitStatus();
8902
+ if (porcelain === null) return null;
8903
+ const dirs = condenseToDirs(parsePorcelain(porcelain));
8904
+ return dirs.length > 0 ? dirs : null;
8905
+ }
8906
+ async function defaultGitStatus() {
8907
+ return await new Promise((resolve3) => {
8908
+ execFile2(
8909
+ "git",
8910
+ ["status", "--porcelain"],
8911
+ { timeout: 2e3, encoding: "utf8", maxBuffer: 1024 * 1024 },
8912
+ (err, stdout) => resolve3(err ? null : stdout)
8913
+ );
8914
+ });
8915
+ }
8916
+
8236
8917
  // src/index.ts
8237
8918
  var MAX_REAUTH_ATTEMPTS = 1;
8238
8919
  var HOOK_SUBCOMMANDS = [
8239
8920
  "on-session-start",
8240
8921
  "on-tool-use",
8241
8922
  "on-file-write",
8923
+ "on-file-edit",
8242
8924
  "sync-config",
8243
8925
  "flush",
8244
8926
  "status"
@@ -8290,11 +8972,12 @@ async function main() {
8290
8972
  process.exit(await runOnSessionEnd2());
8291
8973
  }
8292
8974
  if (firstPositional !== void 0 && isHookSubcommand(firstPositional)) {
8293
- const hooks = await Promise.resolve().then(() => (init_hooks(), hooks_exports));
8975
+ const hooks = await Promise.resolve().then(() => (init_hooks2(), hooks_exports));
8294
8976
  const run = {
8295
8977
  "on-session-start": hooks.runOnSessionStart,
8296
8978
  "on-tool-use": hooks.runOnToolUse,
8297
8979
  "on-file-write": hooks.runOnFileWrite,
8980
+ "on-file-edit": hooks.runOnFileEdit,
8298
8981
  "sync-config": hooks.runSyncConfig,
8299
8982
  flush: hooks.runFlush,
8300
8983
  status: hooks.runHookStatus
@@ -8347,7 +9030,9 @@ async function main() {
8347
9030
  return Promise.reject(new Error("presence: no active forwarder"));
8348
9031
  }
8349
9032
  return currentForwarder.postPresenceToolCall(name, args);
8350
- }
9033
+ },
9034
+ deriveWorkingPaths: () => deriveWorkingPaths(),
9035
+ snapshot: projectKey !== null ? createSnapshotStore({ projectKey }) : void 0
8351
9036
  });
8352
9037
  if (presence.isEnabled) {
8353
9038
  const endAndExit = (code) => {
@@ -8411,6 +9096,7 @@ function printHelp() {
8411
9096
  " on-session-start open a tracked session (Tier-3 flat metrics)",
8412
9097
  " on-tool-use bump counters + evaluate the ADR-039 context advisory",
8413
9098
  " on-file-write block a Write that claims a taken number (ADR-263)",
9099
+ " on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)",
8414
9100
  " on-session-end session analytics + close/flush the tracked session",
8415
9101
  " sync-config pull your context thresholds from the server (ADR-039)",
8416
9102
  " flush post queued Tier-3 metrics now",