@maind-dev/mcp-bridge 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -202,7 +202,7 @@ var BRIDGE_VERSION;
202
202
  var init_version = __esm({
203
203
  "src/version.ts"() {
204
204
  "use strict";
205
- BRIDGE_VERSION = "0.37.0";
205
+ BRIDGE_VERSION = "0.38.0";
206
206
  }
207
207
  });
208
208
 
@@ -2970,6 +2970,18 @@ function normalizeMachineLabel(raw) {
2970
2970
  const v = raw.trim().slice(0, 100);
2971
2971
  return v.length > 0 ? v : null;
2972
2972
  }
2973
+ function staticIdentity(env, id) {
2974
+ let current = id;
2975
+ const fromEnv = (env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
2976
+ const source = UUID_RE2.test(fromEnv) && fromEnv === id ? "env" : "random";
2977
+ return {
2978
+ current: () => ({ id: current, source, aliases: [] }),
2979
+ tryUpgrade: () => false,
2980
+ adopt: (canon) => {
2981
+ if (UUID_RE2.test(canon)) current = canon.trim().toLowerCase();
2982
+ }
2983
+ };
2984
+ }
2973
2985
  var REFRESH_THROTTLE_MS, TTL_MINUTES, BACKOFF_BASE_MS, BACKOFF_CAP_MS, END_TIMEOUT_MS, UUID_RE2, PresenceAnnouncer;
2974
2986
  var init_presence = __esm({
2975
2987
  "src/presence.ts"() {
@@ -2993,8 +3005,8 @@ var init_presence = __esm({
2993
3005
  workingPathsEnabled;
2994
3006
  deriveWorkingPaths;
2995
3007
  snapshot;
3008
+ identity;
2996
3009
  lastBranch = null;
2997
- sessionId;
2998
3010
  lastAnnounceAt = 0;
2999
3011
  inFlight = false;
3000
3012
  consecutiveFailures = 0;
@@ -3013,7 +3025,11 @@ var init_presence = __esm({
3013
3025
  this.workingPathsEnabled = autoWorkingPathsEnabled(env, config);
3014
3026
  this.deriveWorkingPaths = deps.deriveWorkingPaths ?? null;
3015
3027
  this.snapshot = deps.snapshot ?? null;
3016
- this.sessionId = resolveClientSessionId(env);
3028
+ this.identity = deps.identity ?? staticIdentity(env, resolveClientSessionId(env));
3029
+ }
3030
+ /** Aktuelle (kanonische) Session-ID — kann per Upgrade/Adoption wechseln. */
3031
+ get sessionId() {
3032
+ return this.identity.current().id;
3017
3033
  }
3018
3034
  get isEnabled() {
3019
3035
  return this.enabled;
@@ -3082,9 +3098,14 @@ var init_presence = __esm({
3082
3098
  }
3083
3099
  async send(status) {
3084
3100
  if (this.projectKey === null) return;
3101
+ try {
3102
+ if (status === "active") this.identity.tryUpgrade();
3103
+ } catch {
3104
+ }
3105
+ const ident = this.identity.current();
3085
3106
  const args = {
3086
3107
  project_key: this.projectKey,
3087
- session_id: this.sessionId,
3108
+ session_id: ident.id,
3088
3109
  status,
3089
3110
  ttl_minutes: TTL_MINUTES,
3090
3111
  // Self-declaration (migration 20260801120000). The server CANNOT derive
@@ -3100,6 +3121,8 @@ var init_presence = __esm({
3100
3121
  announce_source: "bridge"
3101
3122
  };
3102
3123
  if (status === "active") {
3124
+ args.identity_source = ident.source;
3125
+ if (ident.aliases.length > 0) args.also_known_as = ident.aliases;
3103
3126
  const branch = await this.gitBranch();
3104
3127
  if (branch) args.branch = branch;
3105
3128
  this.lastBranch = branch;
@@ -3113,6 +3136,15 @@ var init_presence = __esm({
3113
3136
  }
3114
3137
  }
3115
3138
  const payload = await this.postToolCall("announce_session", args);
3139
+ if (status === "active" && payload !== null && typeof payload === "object") {
3140
+ const p = payload;
3141
+ if (p.ok === true && typeof p.session_id === "string") {
3142
+ try {
3143
+ this.identity.adopt(p.session_id);
3144
+ } catch {
3145
+ }
3146
+ }
3147
+ }
3116
3148
  if (this.snapshot) {
3117
3149
  try {
3118
3150
  if (status === "ended") {
@@ -3289,6 +3321,225 @@ var init_presence_snapshot = __esm({
3289
3321
  }
3290
3322
  });
3291
3323
 
3324
+ // src/session-identity.ts
3325
+ import { execFileSync as execFileSync7 } from "node:child_process";
3326
+ import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
3327
+ import {
3328
+ existsSync as existsSync7,
3329
+ mkdirSync as mkdirSync5,
3330
+ readdirSync as readdirSync5,
3331
+ readFileSync as readFileSync8,
3332
+ renameSync as renameSync3,
3333
+ statSync as statSync4,
3334
+ unlinkSync as unlinkSync2,
3335
+ writeFileSync as writeFileSync4
3336
+ } from "node:fs";
3337
+ import { homedir as homedir4 } from "node:os";
3338
+ import { basename as basename2, join as join15 } from "node:path";
3339
+ function identityDirPath(baseDir) {
3340
+ return join15(baseDir ?? join15(homedir4(), ".maind", "presence"), "identity");
3341
+ }
3342
+ function transcriptStemOf(transcriptPath, sessionId) {
3343
+ if (transcriptPath) {
3344
+ const stem = basename2(transcriptPath).replace(/\.jsonl$/i, "");
3345
+ if (UUID_RE3.test(stem)) return stem.toLowerCase();
3346
+ }
3347
+ if (sessionId && UUID_RE3.test(sessionId)) return sessionId.toLowerCase();
3348
+ return null;
3349
+ }
3350
+ function writeAgentIdentityFile(opts) {
3351
+ const now = opts.nowMs ?? Date.now();
3352
+ mkdirSync5(opts.dir, { recursive: true, mode: 448 });
3353
+ const file = join15(opts.dir, `${opts.agentPid}.json`);
3354
+ const tmp = `${file}.tmp-${process.pid}`;
3355
+ const payload = {
3356
+ v: 1,
3357
+ session_id: opts.sessionId,
3358
+ transcript_stem: opts.transcriptStem,
3359
+ cwd: opts.cwd,
3360
+ agent_pid: opts.agentPid,
3361
+ written_at: new Date(now).toISOString()
3362
+ };
3363
+ writeFileSync4(tmp, JSON.stringify(payload, null, 2) + "\n", { mode: 384 });
3364
+ renameSync3(tmp, file);
3365
+ pruneIdentityDir(opts.dir, now);
3366
+ }
3367
+ function identityFileStale(dir, agentPid, maxAgeMs, nowMs = Date.now()) {
3368
+ try {
3369
+ const st = statSync4(join15(dir, `${agentPid}.json`));
3370
+ return nowMs - st.mtimeMs > maxAgeMs;
3371
+ } catch {
3372
+ return true;
3373
+ }
3374
+ }
3375
+ function deleteAgentIdentityFile(dir, agentPid) {
3376
+ try {
3377
+ unlinkSync2(join15(dir, `${agentPid}.json`));
3378
+ } catch {
3379
+ }
3380
+ }
3381
+ function pruneIdentityDir(dir, nowMs) {
3382
+ try {
3383
+ for (const f of readdirSync5(dir)) {
3384
+ if (!f.endsWith(".json")) continue;
3385
+ try {
3386
+ const st = statSync4(join15(dir, f));
3387
+ if (nowMs - st.mtimeMs > IDENTITY_TTL_MS) unlinkSync2(join15(dir, f));
3388
+ } catch {
3389
+ }
3390
+ }
3391
+ } catch {
3392
+ }
3393
+ }
3394
+ function readAgentIdentityFile(opts) {
3395
+ const file = join15(opts.dir, `${opts.agentPid}.json`);
3396
+ try {
3397
+ if (!existsSync7(file)) return null;
3398
+ const st = statSync4(file);
3399
+ if (st.mtimeMs < opts.bridgeStartMs - IDENTITY_MAX_AGE_SLACK_MS) {
3400
+ return null;
3401
+ }
3402
+ const parsed = JSON.parse(readFileSync8(file, "utf8"));
3403
+ if (typeof parsed !== "object" || parsed === null) return null;
3404
+ const o = parsed;
3405
+ if (o.v !== 1) return null;
3406
+ if (typeof o.transcript_stem !== "string" || !UUID_RE3.test(o.transcript_stem)) {
3407
+ return null;
3408
+ }
3409
+ if (typeof o.session_id !== "string" || typeof o.cwd !== "string") return null;
3410
+ if (o.agent_pid !== opts.agentPid) return null;
3411
+ if (normDir(o.cwd) !== normDir(opts.cwd)) return null;
3412
+ return o;
3413
+ } catch {
3414
+ return null;
3415
+ }
3416
+ }
3417
+ function normDir(p) {
3418
+ return p.replace(/\/+$/, "");
3419
+ }
3420
+ function uuidV5(name, namespace) {
3421
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
3422
+ const hash = createHash5("sha1").update(ns).update(name, "utf8").digest();
3423
+ const b = Buffer.from(hash.subarray(0, 16));
3424
+ b[6] = b[6] & 15 | 80;
3425
+ b[8] = b[8] & 63 | 128;
3426
+ const h = b.toString("hex");
3427
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
3428
+ }
3429
+ function processStartTime(pid) {
3430
+ if (process.platform === "win32") return null;
3431
+ try {
3432
+ const out2 = execFileSync7("ps", ["-o", "lstart=", "-p", String(pid)], {
3433
+ timeout: 1e3,
3434
+ encoding: "utf8"
3435
+ }).trim().replace(/\s+/g, " ");
3436
+ return out2.length > 0 ? out2 : null;
3437
+ } catch {
3438
+ return null;
3439
+ }
3440
+ }
3441
+ function defaultDeviceId() {
3442
+ try {
3443
+ return ensureDeviceId();
3444
+ } catch {
3445
+ return null;
3446
+ }
3447
+ }
3448
+ var UUID_RE3, MAX_ALIASES, IDENTITY_TTL_MS, IDENTITY_MAX_AGE_SLACK_MS, MAIND_SESSION_NAMESPACE, SessionIdentityManager;
3449
+ var init_session_identity = __esm({
3450
+ "src/session-identity.ts"() {
3451
+ "use strict";
3452
+ init_device_id();
3453
+ UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3454
+ MAX_ALIASES = 8;
3455
+ IDENTITY_TTL_MS = 48 * 60 * 6e4;
3456
+ IDENTITY_MAX_AGE_SLACK_MS = 6e4;
3457
+ MAIND_SESSION_NAMESPACE = "9f3c72da-2f10-4b8f-9c31-ad291c0de291";
3458
+ SessionIdentityManager = class {
3459
+ env;
3460
+ agentPid;
3461
+ cwd;
3462
+ dir;
3463
+ bridgeStartMs;
3464
+ nowMs;
3465
+ envId;
3466
+ id;
3467
+ source;
3468
+ aliases = [];
3469
+ constructor(deps) {
3470
+ this.env = deps.env ?? process.env;
3471
+ this.agentPid = deps.agentPid ?? process.ppid;
3472
+ this.cwd = deps.cwd ?? process.cwd();
3473
+ this.dir = deps.identityDir ?? identityDirPath();
3474
+ this.bridgeStartMs = deps.bridgeStartMs ?? Date.now();
3475
+ this.nowMs = deps.nowMs ?? Date.now;
3476
+ const rawEnv = (this.env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
3477
+ this.envId = UUID_RE3.test(rawEnv) ? rawEnv : null;
3478
+ const stem = this.readStem();
3479
+ if (stem !== null) {
3480
+ this.id = stem;
3481
+ this.source = "client_native";
3482
+ if (this.envId && this.envId !== stem) this.aliases = [this.envId];
3483
+ return;
3484
+ }
3485
+ if (this.envId !== null) {
3486
+ this.id = this.envId;
3487
+ this.source = "env";
3488
+ return;
3489
+ }
3490
+ const device = (deps.deviceId ?? defaultDeviceId)();
3491
+ const start = (deps.ppidStart ?? processStartTime)(this.agentPid);
3492
+ if (device !== null && start !== null && deps.projectKey !== null) {
3493
+ this.id = uuidV5(
3494
+ `${device}|${this.agentPid}|${start}|${deps.projectKey}`,
3495
+ MAIND_SESSION_NAMESPACE
3496
+ );
3497
+ this.source = "derived";
3498
+ return;
3499
+ }
3500
+ this.id = randomUUID3();
3501
+ this.source = "random";
3502
+ }
3503
+ current() {
3504
+ return { id: this.id, source: this.source, aliases: [...this.aliases] };
3505
+ }
3506
+ tryUpgrade() {
3507
+ if (this.source === "client_native") return false;
3508
+ const stem = this.readStem();
3509
+ if (stem === null || stem === this.id) return false;
3510
+ const prev = this.id;
3511
+ this.id = stem;
3512
+ this.source = "client_native";
3513
+ this.pushAlias(prev);
3514
+ if (this.envId !== null) this.pushAlias(this.envId);
3515
+ return true;
3516
+ }
3517
+ adopt(canonicalId) {
3518
+ const canon = canonicalId.trim().toLowerCase();
3519
+ if (!UUID_RE3.test(canon) || canon === this.id) return;
3520
+ const prev = this.id;
3521
+ this.id = canon;
3522
+ this.pushAlias(prev);
3523
+ }
3524
+ pushAlias(id) {
3525
+ if (id === this.id || this.aliases.includes(id)) return;
3526
+ this.aliases.push(id);
3527
+ if (this.aliases.length > MAX_ALIASES) this.aliases.shift();
3528
+ }
3529
+ readStem() {
3530
+ const f = readAgentIdentityFile({
3531
+ dir: this.dir,
3532
+ agentPid: this.agentPid,
3533
+ cwd: this.cwd,
3534
+ bridgeStartMs: this.bridgeStartMs,
3535
+ nowMs: this.nowMs()
3536
+ });
3537
+ return f === null ? null : f.transcript_stem.toLowerCase();
3538
+ }
3539
+ };
3540
+ }
3541
+ });
3542
+
3292
3543
  // ../../packages/claude-code-telemetry/dist/types.js
3293
3544
  var init_types4 = __esm({
3294
3545
  "../../packages/claude-code-telemetry/dist/types.js"() {
@@ -3297,11 +3548,11 @@ var init_types4 = __esm({
3297
3548
  });
3298
3549
 
3299
3550
  // ../../packages/claude-code-telemetry/dist/transcript.js
3300
- import { createReadStream, existsSync as existsSync7 } from "node:fs";
3551
+ import { createReadStream, existsSync as existsSync8 } from "node:fs";
3301
3552
  import { stat } from "node:fs/promises";
3302
3553
  import { createInterface as createInterface5 } from "node:readline";
3303
3554
  async function summariseTranscript(path8) {
3304
- if (!path8 || !existsSync7(path8))
3555
+ if (!path8 || !existsSync8(path8))
3305
3556
  return null;
3306
3557
  let stats;
3307
3558
  try {
@@ -3386,7 +3637,7 @@ var init_effort = __esm({
3386
3637
  });
3387
3638
 
3388
3639
  // ../../packages/claude-code-telemetry/dist/session-analysis.js
3389
- import { createReadStream as createReadStream2, existsSync as existsSync8 } from "node:fs";
3640
+ import { createReadStream as createReadStream2, existsSync as existsSync9 } from "node:fs";
3390
3641
  import { createInterface as createInterface6 } from "node:readline";
3391
3642
  function num2(v) {
3392
3643
  return typeof v === "number" && Number.isFinite(v) ? v : 0;
@@ -3493,7 +3744,7 @@ function emptyAnalysis(sessionId) {
3493
3744
  }
3494
3745
  async function analyzeSession(path8) {
3495
3746
  const a = emptyAnalysis("");
3496
- if (!path8 || !existsSync8(path8))
3747
+ if (!path8 || !existsSync9(path8))
3497
3748
  return a;
3498
3749
  const reactions = [];
3499
3750
  const modelMix = /* @__PURE__ */ new Map();
@@ -3689,7 +3940,7 @@ var init_ingest = __esm({
3689
3940
  });
3690
3941
 
3691
3942
  // ../../packages/claude-code-telemetry/dist/session-span.js
3692
- import { createReadStream as createReadStream3, existsSync as existsSync9 } from "node:fs";
3943
+ import { createReadStream as createReadStream3, existsSync as existsSync10 } from "node:fs";
3693
3944
  import { createInterface as createInterface7 } from "node:readline";
3694
3945
  function asBlocks2(content) {
3695
3946
  if (typeof content === "string")
@@ -3741,7 +3992,7 @@ function classify2(parsed) {
3741
3992
  }
3742
3993
  async function analyzeSpan(path8) {
3743
3994
  const s = emptySpan("");
3744
- if (!path8 || !existsSync9(path8))
3995
+ if (!path8 || !existsSync10(path8))
3745
3996
  return s;
3746
3997
  let firstMs = null;
3747
3998
  let lastMs = 0;
@@ -3853,14 +4104,14 @@ var init_windows = __esm({
3853
4104
  });
3854
4105
 
3855
4106
  // ../../packages/claude-code-telemetry/dist/projects.js
3856
- import { homedir as homedir4 } from "node:os";
3857
- import { join as join15 } from "node:path";
4107
+ import { homedir as homedir5 } from "node:os";
4108
+ import { join as join16 } from "node:path";
3858
4109
  var HOME, DEFAULT_PROJECTS_DIR;
3859
4110
  var init_projects = __esm({
3860
4111
  "../../packages/claude-code-telemetry/dist/projects.js"() {
3861
4112
  "use strict";
3862
- HOME = homedir4();
3863
- DEFAULT_PROJECTS_DIR = join15(HOME, ".claude", "projects");
4113
+ HOME = homedir5();
4114
+ DEFAULT_PROJECTS_DIR = join16(HOME, ".claude", "projects");
3864
4115
  }
3865
4116
  });
3866
4117
 
@@ -4108,14 +4359,14 @@ var init_payloads = __esm({
4108
4359
 
4109
4360
  // src/hooks/state.ts
4110
4361
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, rename as rename2 } from "node:fs/promises";
4111
- import { existsSync as existsSync10 } from "node:fs";
4112
- import { homedir as homedir5 } from "node:os";
4113
- import { join as join16 } from "node:path";
4362
+ import { existsSync as existsSync11 } from "node:fs";
4363
+ import { homedir as homedir6 } from "node:os";
4364
+ import { join as join17 } from "node:path";
4114
4365
  function emptyState() {
4115
4366
  return { config: null, sessions: {}, pending_metrics: [] };
4116
4367
  }
4117
4368
  async function loadState() {
4118
- if (!existsSync10(STATE_FILE)) return emptyState();
4369
+ if (!existsSync11(STATE_FILE)) return emptyState();
4119
4370
  try {
4120
4371
  const raw = await readFile2(STATE_FILE, "utf-8");
4121
4372
  const parsed = JSON.parse(raw);
@@ -4136,7 +4387,7 @@ async function loadState() {
4136
4387
  }
4137
4388
  }
4138
4389
  async function saveState(state) {
4139
- if (!existsSync10(STATE_DIR)) {
4390
+ if (!existsSync11(STATE_DIR)) {
4140
4391
  await mkdir2(STATE_DIR, { recursive: true, mode: 448 });
4141
4392
  }
4142
4393
  const tmp = `${STATE_FILE}.tmp`;
@@ -4150,8 +4401,8 @@ var STATE_DIR, STATE_FILE, DEFAULT_THRESHOLDS;
4150
4401
  var init_state = __esm({
4151
4402
  "src/hooks/state.ts"() {
4152
4403
  "use strict";
4153
- STATE_DIR = join16(homedir5(), ".maind");
4154
- STATE_FILE = join16(STATE_DIR, "state.json");
4404
+ STATE_DIR = join17(homedir6(), ".maind");
4405
+ STATE_FILE = join17(STATE_DIR, "state.json");
4155
4406
  DEFAULT_THRESHOLDS = {
4156
4407
  warn_at_pct: 60,
4157
4408
  handoff_at_pct: 85,
@@ -4176,11 +4427,11 @@ __export(hooks_exports, {
4176
4427
  runSessionEndMetrics: () => runSessionEndMetrics,
4177
4428
  runSyncConfig: () => runSyncConfig
4178
4429
  });
4179
- import { execFileSync as execFileSync7 } from "node:child_process";
4180
- import { existsSync as existsSync11, readFileSync as readFileSync8, realpathSync as realpathSync2 } from "node:fs";
4430
+ import { execFileSync as execFileSync8 } from "node:child_process";
4431
+ import { existsSync as existsSync12, readFileSync as readFileSync9, realpathSync as realpathSync2 } from "node:fs";
4181
4432
  import { writeFile as writeFile3 } from "node:fs/promises";
4182
- import { homedir as homedir6 } from "node:os";
4183
- import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute4, join as join17, relative as relative3 } from "node:path";
4433
+ import { homedir as homedir7 } from "node:os";
4434
+ import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute4, join as join18, relative as relative3 } from "node:path";
4184
4435
  function recordGuardSignals(state, sessionId, toolName, nowMs = Date.now()) {
4185
4436
  if (!toolName.includes("maind")) return;
4186
4437
  const consulted = toolName.includes("search_lessons") || toolName.includes("get_session_briefing") || toolName.includes("get_lesson") || toolName.includes("get_conventions") || toolName.includes("activate_skill") || toolName.includes("suggest_skills") || toolName.includes("codebase_change_briefing");
@@ -4263,6 +4514,10 @@ async function runOnSessionStart() {
4263
4514
  if (sessionId === null) return 0;
4264
4515
  getOrCreateSession(state, sessionId);
4265
4516
  await saveState(state);
4517
+ try {
4518
+ writeIdentitySideChannel(input, sessionId);
4519
+ } catch {
4520
+ }
4266
4521
  try {
4267
4522
  const projectKey = computeProjectKey();
4268
4523
  if (projectKey !== null) {
@@ -4301,16 +4556,29 @@ async function runOnSessionStart() {
4301
4556
  }
4302
4557
  function readSettingsRaw() {
4303
4558
  try {
4304
- const p = join17(homedir6(), ".claude", "settings.json");
4305
- return existsSync11(p) ? readFileSync8(p, "utf8") : null;
4559
+ const p = join18(homedir7(), ".claude", "settings.json");
4560
+ return existsSync12(p) ? readFileSync9(p, "utf8") : null;
4306
4561
  } catch {
4307
4562
  return null;
4308
4563
  }
4309
4564
  }
4565
+ function writeIdentitySideChannel(input, sessionId, knownAgentPid) {
4566
+ const agentPid = knownAgentPid ?? grandparentPid();
4567
+ if (agentPid === null || agentPid === void 0) return;
4568
+ const stem = transcriptStemOf(transcriptPathOf(input) || null, sessionId);
4569
+ if (stem === null) return;
4570
+ writeAgentIdentityFile({
4571
+ dir: identityDirPath(),
4572
+ agentPid,
4573
+ sessionId,
4574
+ transcriptStem: stem,
4575
+ cwd: typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd()
4576
+ });
4577
+ }
4310
4578
  function grandparentPid() {
4311
4579
  try {
4312
4580
  if (process.platform === "win32") return null;
4313
- const out2 = execFileSync7("ps", ["-o", "ppid=", "-p", String(process.ppid)], {
4581
+ const out2 = execFileSync8("ps", ["-o", "ppid=", "-p", String(process.ppid)], {
4314
4582
  timeout: 1e3,
4315
4583
  encoding: "utf8"
4316
4584
  });
@@ -4327,6 +4595,13 @@ async function runOnToolUse() {
4327
4595
  const sessionId = sessionIdOf(input) ?? "unknown";
4328
4596
  const session = getOrCreateSession(state, sessionId);
4329
4597
  session.tool_call_count += 1;
4598
+ try {
4599
+ const agentPid = grandparentPid();
4600
+ if (sessionId !== "unknown" && agentPid !== null && identityFileStale(identityDirPath(), agentPid, IDENTITY_REFRESH_MS)) {
4601
+ writeIdentitySideChannel(input, sessionId, agentPid);
4602
+ }
4603
+ } catch {
4604
+ }
4330
4605
  const tool = (input.tool_name ?? "").toString();
4331
4606
  if (tool.includes("search_lessons") || tool.includes("get_session_briefing") || tool.includes("get_lesson")) {
4332
4607
  session.lessons_consulted += 1;
@@ -4348,15 +4623,15 @@ async function runOnToolUse() {
4348
4623
  }
4349
4624
  function realpathOfUnwritten(p) {
4350
4625
  let head = dirname6(p);
4351
- const tail = [basename2(p)];
4626
+ const tail = [basename3(p)];
4352
4627
  for (; ; ) {
4353
4628
  try {
4354
4629
  const real = realpathSync2(head);
4355
- return join17(real, ...tail.reverse());
4630
+ return join18(real, ...tail.reverse());
4356
4631
  } catch {
4357
4632
  const parent = dirname6(head);
4358
4633
  if (parent === head) return p;
4359
- tail.push(basename2(head));
4634
+ tail.push(basename3(head));
4360
4635
  head = parent;
4361
4636
  }
4362
4637
  }
@@ -4377,8 +4652,8 @@ async function runOnFileWrite() {
4377
4652
  const filePath = toolFilePathOf(input);
4378
4653
  if (!filePath) return 0;
4379
4654
  const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
4380
- const abs = isAbsolute4(filePath) ? filePath : join17(cwd, filePath);
4381
- if (existsSync11(abs)) return 0;
4655
+ const abs = isAbsolute4(filePath) ? filePath : join18(cwd, filePath);
4656
+ if (existsSync12(abs)) return 0;
4382
4657
  const repoRoot = resolveRepoRoot(cwd);
4383
4658
  const rel = relative3(repoRoot, realpathOfUnwritten(abs));
4384
4659
  if (rel.length === 0 || rel.startsWith("..") || isAbsolute4(rel)) return 0;
@@ -4398,7 +4673,7 @@ async function runOnFileEdit() {
4398
4673
  const filePath = toolFilePathOf(input);
4399
4674
  if (!filePath) return 0;
4400
4675
  const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
4401
- const abs = isAbsolute4(filePath) ? filePath : join17(cwd, filePath);
4676
+ const abs = isAbsolute4(filePath) ? filePath : join18(cwd, filePath);
4402
4677
  const projectKey = computeProjectKey();
4403
4678
  if (projectKey === null) return 0;
4404
4679
  const snaps = readSnapshots(projectKey);
@@ -4409,7 +4684,7 @@ async function runOnFileEdit() {
4409
4684
  });
4410
4685
  if (own === null) return 0;
4411
4686
  const repoRoot = resolveRepoRoot(cwd);
4412
- const real = existsSync11(abs) ? realpathSync2(abs) : realpathOfUnwritten(abs);
4687
+ const real = existsSync12(abs) ? realpathSync2(abs) : realpathOfUnwritten(abs);
4413
4688
  const rel = relative3(repoRoot, real).replace(/\\/g, "/");
4414
4689
  if (rel.length === 0 || rel.startsWith("..") || isAbsolute4(rel)) return 0;
4415
4690
  const advice = adviseOnPath(own.snap, rel, {
@@ -4426,7 +4701,7 @@ async function runOnFileEdit() {
4426
4701
  }
4427
4702
  function currentGitBranch(cwd) {
4428
4703
  try {
4429
- const out2 = execFileSync7("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
4704
+ const out2 = execFileSync8("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
4430
4705
  cwd,
4431
4706
  timeout: 1e3,
4432
4707
  encoding: "utf8"
@@ -4461,7 +4736,7 @@ async function maybeEmitAdvisory(state, session) {
4461
4736
  };
4462
4737
  try {
4463
4738
  await writeFile3(
4464
- join17(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
4739
+ join18(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
4465
4740
  JSON.stringify(payload, null, 2)
4466
4741
  );
4467
4742
  } catch (err) {
@@ -4581,10 +4856,10 @@ async function runHookStatus() {
4581
4856
  return 0;
4582
4857
  }
4583
4858
  function readHookWiring() {
4584
- const settingsPath = join17(homedir6(), ".claude", "settings.json");
4859
+ const settingsPath = join18(homedir7(), ".claude", "settings.json");
4585
4860
  let raw = null;
4586
4861
  try {
4587
- if (existsSync11(settingsPath)) raw = readFileSync8(settingsPath, "utf8");
4862
+ if (existsSync12(settingsPath)) raw = readFileSync9(settingsPath, "utf8");
4588
4863
  } catch {
4589
4864
  }
4590
4865
  return { settingsPath, findings: inspectHookWiring(raw) };
@@ -4658,7 +4933,7 @@ function sessionIdOf(input) {
4658
4933
  const id = typeof input.session_id === "string" ? input.session_id.trim() : "";
4659
4934
  return id.length > 0 ? id : null;
4660
4935
  }
4661
- var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS, STATE_GC_TTL_MS, WIRING_REMEDY;
4936
+ var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS, STATE_GC_TTL_MS, IDENTITY_REFRESH_MS, WIRING_REMEDY;
4662
4937
  var init_hooks2 = __esm({
4663
4938
  "src/hooks/index.ts"() {
4664
4939
  "use strict";
@@ -4671,6 +4946,7 @@ var init_hooks2 = __esm({
4671
4946
  init_project_key();
4672
4947
  init_api();
4673
4948
  init_edit_guard();
4949
+ init_session_identity();
4674
4950
  init_hook_input();
4675
4951
  init_payloads();
4676
4952
  init_state();
@@ -4678,6 +4954,7 @@ var init_hooks2 = __esm({
4678
4954
  STOP_FLUSH_TIMEOUT_MS = 1500;
4679
4955
  MANUAL_FLUSH_TIMEOUT_MS = 1e4;
4680
4956
  STATE_GC_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
4957
+ IDENTITY_REFRESH_MS = 6e4;
4681
4958
  WIRING_REMEDY = "Re-run `maind-mcp-bridge install` to add the missing hooks \u2014 it is append-only and idempotent: it adds only what is absent, asks consent per hook, and never rewrites an entry you already have.";
4682
4959
  }
4683
4960
  });
@@ -4725,8 +5002,21 @@ function connectionVerdict(sawMaindCall, nowMs) {
4725
5002
  }
4726
5003
  }
4727
5004
  function presenceSessionId() {
5005
+ const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5006
+ try {
5007
+ const pk = computeProjectKey();
5008
+ if (pk !== null) {
5009
+ const own = selectOwnSnapshot(readSnapshots(pk), {
5010
+ grandparentPid: grandparentPid(),
5011
+ cwd: process.cwd()
5012
+ });
5013
+ const id = own?.snap.own_session_id ?? null;
5014
+ if (id !== null && uuidRe.test(id)) return id.toLowerCase();
5015
+ }
5016
+ } catch {
5017
+ }
4728
5018
  const raw = (process.env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
4729
- return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(raw) ? raw : null;
5019
+ return uuidRe.test(raw) ? raw : null;
4730
5020
  }
4731
5021
  async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
4732
5022
  const post = fetch(INGEST_ENDPOINT, {
@@ -4743,6 +5033,13 @@ async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
4743
5033
  await Promise.race([post, timeout]);
4744
5034
  }
4745
5035
  async function runOnSessionEnd() {
5036
+ try {
5037
+ const agentPid = grandparentPid();
5038
+ if (agentPid !== null) {
5039
+ deleteAgentIdentityFile(identityDirPath(), agentPid);
5040
+ }
5041
+ } catch {
5042
+ }
4746
5043
  const apiKey = readApiKey();
4747
5044
  if (!apiKey) return 0;
4748
5045
  const input = await readHookInput();
@@ -4798,6 +5095,7 @@ var init_session_end = __esm({
4798
5095
  init_presence();
4799
5096
  init_presence_snapshot();
4800
5097
  init_project_key();
5098
+ init_session_identity();
4801
5099
  init_version();
4802
5100
  init_connection();
4803
5101
  INGEST_ENDPOINT = DEFAULT_INGEST_ENDPOINT;
@@ -4925,16 +5223,16 @@ var init_install = __esm({
4925
5223
  });
4926
5224
 
4927
5225
  // src/guard/session-file.ts
4928
- import { existsSync as existsSync12 } from "node:fs";
5226
+ import { existsSync as existsSync13 } from "node:fs";
4929
5227
  import { mkdir as mkdir3, readFile as readFile3, readdir, rename as rename3, stat as stat2, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
4930
- import { join as join18 } from "node:path";
5228
+ import { join as join19 } from "node:path";
4931
5229
  function sessionFile(sessionId) {
4932
- return join18(GUARD_SESSIONS_DIR, sessionId.replace(/[^a-zA-Z0-9._-]/g, "_") + ".json");
5230
+ return join19(GUARD_SESSIONS_DIR, sessionId.replace(/[^a-zA-Z0-9._-]/g, "_") + ".json");
4933
5231
  }
4934
5232
  async function loadGuardSession(sessionId) {
4935
5233
  try {
4936
5234
  const file = sessionFile(sessionId);
4937
- if (!existsSync12(file)) return {};
5235
+ if (!existsSync13(file)) return {};
4938
5236
  const parsed = JSON.parse(await readFile3(file, "utf8"));
4939
5237
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
4940
5238
  return parsed;
@@ -4955,10 +5253,10 @@ async function saveGuardSession(sessionId, state) {
4955
5253
  }
4956
5254
  async function sweepOldGuardSessions(maxAgeMs = 7 * 24 * 60 * 60 * 1e3, nowMs = Date.now()) {
4957
5255
  try {
4958
- if (!existsSync12(GUARD_SESSIONS_DIR)) return;
5256
+ if (!existsSync13(GUARD_SESSIONS_DIR)) return;
4959
5257
  for (const name of await readdir(GUARD_SESSIONS_DIR)) {
4960
5258
  if (!name.endsWith(".json")) continue;
4961
- const file = join18(GUARD_SESSIONS_DIR, name);
5259
+ const file = join19(GUARD_SESSIONS_DIR, name);
4962
5260
  try {
4963
5261
  const s = await stat2(file);
4964
5262
  if (nowMs - s.mtimeMs > maxAgeMs) await unlink2(file);
@@ -4973,15 +5271,15 @@ var init_session_file = __esm({
4973
5271
  "src/guard/session-file.ts"() {
4974
5272
  "use strict";
4975
5273
  init_state();
4976
- GUARD_DIR = join18(STATE_DIR, "guard");
4977
- GUARD_SESSIONS_DIR = join18(GUARD_DIR, "sessions");
5274
+ GUARD_DIR = join19(STATE_DIR, "guard");
5275
+ GUARD_SESSIONS_DIR = join19(GUARD_DIR, "sessions");
4978
5276
  }
4979
5277
  });
4980
5278
 
4981
5279
  // src/guard/log.ts
4982
- import { existsSync as existsSync13 } from "node:fs";
5280
+ import { existsSync as existsSync14 } from "node:fs";
4983
5281
  import { appendFile, mkdir as mkdir4, open } from "node:fs/promises";
4984
- import { join as join19 } from "node:path";
5282
+ import { join as join20 } from "node:path";
4985
5283
  async function appendGuardEvent(event) {
4986
5284
  try {
4987
5285
  await mkdir4(GUARD_DIR, { recursive: true, mode: 448 });
@@ -5003,7 +5301,7 @@ async function readGuardEventCounts(tailBytes = 256 * 1024) {
5003
5301
  cross_session_deny: 0
5004
5302
  };
5005
5303
  try {
5006
- if (!existsSync13(GUARD_EVENTS_FILE)) return counts;
5304
+ if (!existsSync14(GUARD_EVENTS_FILE)) return counts;
5007
5305
  const fh = await open(GUARD_EVENTS_FILE, "r");
5008
5306
  try {
5009
5307
  const size = (await fh.stat()).size;
@@ -5034,7 +5332,7 @@ var init_log = __esm({
5034
5332
  "src/guard/log.ts"() {
5035
5333
  "use strict";
5036
5334
  init_session_file();
5037
- GUARD_EVENTS_FILE = join19(GUARD_DIR, "events.jsonl");
5335
+ GUARD_EVENTS_FILE = join20(GUARD_DIR, "events.jsonl");
5038
5336
  }
5039
5337
  });
5040
5338
 
@@ -5043,15 +5341,15 @@ var cli_exports = {};
5043
5341
  __export(cli_exports, {
5044
5342
  runGuard: () => runGuard
5045
5343
  });
5046
- import { existsSync as existsSync14, readFileSync as readFileSync9 } from "node:fs";
5047
- import { homedir as homedir7 } from "node:os";
5048
- import { join as join20 } from "node:path";
5344
+ import { existsSync as existsSync15, readFileSync as readFileSync10 } from "node:fs";
5345
+ import { homedir as homedir8 } from "node:os";
5346
+ import { join as join21 } from "node:path";
5049
5347
  async function runGuard(argv) {
5050
5348
  const verb = argv[0];
5051
5349
  const rest = argv.slice(1);
5052
5350
  switch (verb) {
5053
5351
  case "install":
5054
- return runGuardInstall(rest, homedir7());
5352
+ return runGuardInstall(rest, homedir8());
5055
5353
  case "status":
5056
5354
  return runGuardStatus();
5057
5355
  case "mode": {
@@ -5122,10 +5420,10 @@ logged (auditable) in ${GUARD_EVENTS_FILE}
5122
5420
  }
5123
5421
  async function runGuardStatus() {
5124
5422
  const config = resolveGuardConfig();
5125
- const settingsPath = join20(homedir7(), ".claude", "settings.json");
5423
+ const settingsPath = join21(homedir8(), ".claude", "settings.json");
5126
5424
  let raw = null;
5127
5425
  try {
5128
- if (existsSync14(settingsPath)) raw = readFileSync9(settingsPath, "utf8");
5426
+ if (existsSync15(settingsPath)) raw = readFileSync10(settingsPath, "utf8");
5129
5427
  } catch {
5130
5428
  }
5131
5429
  const wiring = inspectHookWiring(raw, {}, GUARD_SUBCOMMAND_HOOKS);
@@ -5317,9 +5615,9 @@ __export(inject_exports, {
5317
5615
  resolveBriefingInjection: () => resolveBriefingInjection,
5318
5616
  runGuardInject: () => runGuardInject
5319
5617
  });
5320
- import { existsSync as existsSync15 } from "node:fs";
5618
+ import { existsSync as existsSync16 } from "node:fs";
5321
5619
  import { mkdir as mkdir5, readFile as readFile4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
5322
- import { dirname as dirname7, join as join21 } from "node:path";
5620
+ import { dirname as dirname7, join as join22 } from "node:path";
5323
5621
  async function resolveBriefingInjection(projectKey, apiKey, deps = {}) {
5324
5622
  const nowMs = deps.nowMs ?? Date.now();
5325
5623
  const cacheFile = deps.cacheFile ?? BRIEFING_CACHE_FILE;
@@ -5404,7 +5702,7 @@ function formatInjection(text, via) {
5404
5702
  }
5405
5703
  async function readCache(file) {
5406
5704
  try {
5407
- if (!existsSync15(file)) return null;
5705
+ if (!existsSync16(file)) return null;
5408
5706
  const parsed = JSON.parse(await readFile4(file, "utf8"));
5409
5707
  if (typeof parsed.fetched_at !== "string" || typeof parsed.text !== "string") return null;
5410
5708
  if (Number.isNaN(Date.parse(parsed.fetched_at))) return null;
@@ -5445,7 +5743,7 @@ var init_inject = __esm({
5445
5743
  init_log();
5446
5744
  init_session_file();
5447
5745
  init_mcp_client();
5448
- BRIEFING_CACHE_FILE = join21(GUARD_DIR, "briefing-cache.json");
5746
+ BRIEFING_CACHE_FILE = join22(GUARD_DIR, "briefing-cache.json");
5449
5747
  CACHE_TTL_MS = 12 * 60 * 60 * 1e3;
5450
5748
  FETCH_BUDGET_MS = 3e3;
5451
5749
  MAX_INJECT_BYTES = 10 * 1024;
@@ -5674,8 +5972,8 @@ var init_frames = __esm({
5674
5972
 
5675
5973
  // src/gateway/attest.ts
5676
5974
  import { appendFile as appendFile2, mkdir as mkdir6, readFile as readFile5, rename as rename5, writeFile as writeFile6 } from "node:fs/promises";
5677
- import { homedir as homedir8 } from "node:os";
5678
- import { join as join22 } from "node:path";
5975
+ import { homedir as homedir9 } from "node:os";
5976
+ import { join as join23 } from "node:path";
5679
5977
  function aggregateWindow(events, mode, serverLabel, projectKey) {
5680
5978
  if (mode === "off" || events.length === 0) return null;
5681
5979
  const counts = {};
@@ -5709,7 +6007,7 @@ function aggregateWindow(events, mode, serverLabel, projectKey) {
5709
6007
  };
5710
6008
  }
5711
6009
  function attestSpoolPath() {
5712
- return join22(homedir8(), ".maind", "gateway", "attest-spool.jsonl");
6010
+ return join23(homedir9(), ".maind", "gateway", "attest-spool.jsonl");
5713
6011
  }
5714
6012
  async function postAttestation(payload) {
5715
6013
  const apiKey = readApiKey();
@@ -5732,7 +6030,7 @@ async function postAttestation(payload) {
5732
6030
  }
5733
6031
  async function spoolAttestation(payload) {
5734
6032
  try {
5735
- await mkdir6(join22(homedir8(), ".maind", "gateway"), { recursive: true });
6033
+ await mkdir6(join23(homedir9(), ".maind", "gateway"), { recursive: true });
5736
6034
  await appendFile2(attestSpoolPath(), JSON.stringify(payload) + "\n", { mode: 384 });
5737
6035
  await capSpool();
5738
6036
  } catch {
@@ -5897,11 +6195,11 @@ var init_policy = __esm({
5897
6195
  });
5898
6196
 
5899
6197
  // src/gateway/policy-cache.ts
5900
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync10, renameSync as renameSync3, writeFileSync as writeFileSync4 } from "node:fs";
5901
- import { homedir as homedir9 } from "node:os";
5902
- import { dirname as dirname8, join as join23 } from "node:path";
6198
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync11, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "node:fs";
6199
+ import { homedir as homedir10 } from "node:os";
6200
+ import { dirname as dirname8, join as join24 } from "node:path";
5903
6201
  function policyCachePath() {
5904
- return join23(homedir9(), ".maind", "gateway", "policy-cache.json");
6202
+ return join24(homedir10(), ".maind", "gateway", "policy-cache.json");
5905
6203
  }
5906
6204
  function writePolicyCache(identity, rules, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
5907
6205
  try {
@@ -5913,16 +6211,16 @@ function writePolicyCache(identity, rules, nowIso = (/* @__PURE__ */ new Date())
5913
6211
  rules
5914
6212
  };
5915
6213
  const target = policyCachePath();
5916
- mkdirSync5(dirname8(target), { recursive: true });
6214
+ mkdirSync6(dirname8(target), { recursive: true });
5917
6215
  const tmp = `${target}.${process.pid}.tmp`;
5918
- writeFileSync4(tmp, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 384 });
5919
- renameSync3(tmp, target);
6216
+ writeFileSync5(tmp, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 384 });
6217
+ renameSync4(tmp, target);
5920
6218
  } catch {
5921
6219
  }
5922
6220
  }
5923
6221
  function readPolicyCache(identity) {
5924
6222
  try {
5925
- const raw = readFileSync10(policyCachePath(), "utf8");
6223
+ const raw = readFileSync11(policyCachePath(), "utf8");
5926
6224
  const parsed = JSON.parse(raw);
5927
6225
  if (parsed.version !== CACHE_VERSION2 || parsed.mcp_url !== identity.mcpUrl || parsed.key_fp !== identity.keyFp || typeof parsed.cached_at !== "string" || !Array.isArray(parsed.rules)) {
5928
6226
  return null;
@@ -6069,9 +6367,9 @@ __export(install_exports, {
6069
6367
  runGatewayInstall: () => runGatewayInstall,
6070
6368
  runGatewayUninstall: () => runGatewayUninstall
6071
6369
  });
6072
- import { existsSync as existsSync16, readFileSync as readFileSync11 } from "node:fs";
6073
- import { homedir as homedir10 } from "node:os";
6074
- import { join as join24 } from "node:path";
6370
+ import { existsSync as existsSync17, readFileSync as readFileSync12 } from "node:fs";
6371
+ import { homedir as homedir11 } from "node:os";
6372
+ import { join as join25 } from "node:path";
6075
6373
  import { createInterface as createInterface8 } from "node:readline";
6076
6374
  function parseFlags(argv) {
6077
6375
  const f = { yes: false, dryRun: false };
@@ -6084,8 +6382,8 @@ function parseFlags(argv) {
6084
6382
  }
6085
6383
  function targets() {
6086
6384
  return [
6087
- { label: "Claude Code (project .mcp.json)", path: join24(process.cwd(), ".mcp.json") },
6088
- { label: "Claude Code (user ~/.claude.json)", path: join24(homedir10(), ".claude.json") }
6385
+ { label: "Claude Code (project .mcp.json)", path: join25(process.cwd(), ".mcp.json") },
6386
+ { label: "Claude Code (user ~/.claude.json)", path: join25(homedir11(), ".claude.json") }
6089
6387
  ];
6090
6388
  }
6091
6389
  async function confirm(question) {
@@ -6115,8 +6413,8 @@ function loadConfig(path8) {
6115
6413
  }
6116
6414
  function readFileSafeSync(path8) {
6117
6415
  try {
6118
- if (!existsSync16(path8)) return null;
6119
- return readFileSync11(path8, "utf8");
6416
+ if (!existsSync17(path8)) return null;
6417
+ return readFileSync12(path8, "utf8");
6120
6418
  } catch {
6121
6419
  return null;
6122
6420
  }
@@ -6345,16 +6643,16 @@ __export(run_exports, {
6345
6643
  });
6346
6644
  import { spawn as spawn2 } from "node:child_process";
6347
6645
  import { appendFile as appendFile3, mkdir as mkdir7 } from "node:fs/promises";
6348
- import { homedir as homedir11 } from "node:os";
6349
- import { basename as basename3, join as join25 } from "node:path";
6646
+ import { homedir as homedir12 } from "node:os";
6647
+ import { basename as basename4, join as join26 } from "node:path";
6350
6648
  import { createInterface as createInterface9 } from "node:readline";
6351
6649
  function gatewayEventsFile() {
6352
- return join25(homedir11(), ".maind", "gateway", "events.jsonl");
6650
+ return join26(homedir12(), ".maind", "gateway", "events.jsonl");
6353
6651
  }
6354
6652
  async function logEvent(e) {
6355
6653
  try {
6356
6654
  const file = gatewayEventsFile();
6357
- await mkdir7(join25(homedir11(), ".maind", "gateway"), { recursive: true });
6655
+ await mkdir7(join26(homedir12(), ".maind", "gateway"), { recursive: true });
6358
6656
  await appendFile3(file, JSON.stringify(e) + "\n", { mode: 384 });
6359
6657
  } catch {
6360
6658
  }
@@ -6407,7 +6705,7 @@ async function runGateway(argv) {
6407
6705
  return 2;
6408
6706
  }
6409
6707
  const { denyTools, label, command, args } = parsed;
6410
- const serverLabel = label ?? basename3(command);
6708
+ const serverLabel = label ?? basename4(command);
6411
6709
  const mode = resolveGatewayMode();
6412
6710
  let policyRules = mode === "off" ? [] : readPolicyCache(policyIdentity())?.rules ?? [];
6413
6711
  if (mode !== "off") {
@@ -6541,10 +6839,10 @@ __export(cross_session_exports, {
6541
6839
  staleReason: () => staleReason
6542
6840
  });
6543
6841
  import { mkdir as mkdir8, readFile as readFile6, readdir as readdir2, stat as stat3, unlink as unlink3, writeFile as writeFile7 } from "node:fs/promises";
6544
- import { homedir as homedir12 } from "node:os";
6545
- import { join as join26 } from "node:path";
6842
+ import { homedir as homedir13 } from "node:os";
6843
+ import { join as join27 } from "node:path";
6546
6844
  function crossSessionDir() {
6547
- return join26(homedir12(), ".maind", "cross-session");
6845
+ return join27(homedir13(), ".maind", "cross-session");
6548
6846
  }
6549
6847
  function parseSessionDb(raw) {
6550
6848
  const empty = { files: {}, warned: {} };
@@ -6586,7 +6884,7 @@ function staleReason(path8, v) {
6586
6884
  async function dbPath(sessionId) {
6587
6885
  const dir = crossSessionDir();
6588
6886
  await mkdir8(dir, { recursive: true });
6589
- return join26(dir, `${sessionId}.json`);
6887
+ return join27(dir, `${sessionId}.json`);
6590
6888
  }
6591
6889
  async function loadDb(sessionId, now) {
6592
6890
  try {
@@ -6607,7 +6905,7 @@ async function sweepStaleSessionFiles(now) {
6607
6905
  const dir = crossSessionDir();
6608
6906
  for (const name of await readdir2(dir)) {
6609
6907
  if (!name.endsWith(".json")) continue;
6610
- const p = join26(dir, name);
6908
+ const p = join27(dir, name);
6611
6909
  const s = await stat3(p).catch(() => null);
6612
6910
  if (s && now - s.mtimeMs > TTL_MS) await unlink3(p).catch(() => {
6613
6911
  });
@@ -6692,7 +6990,7 @@ var init_cross_session = __esm({
6692
6990
  });
6693
6991
 
6694
6992
  // src/index.ts
6695
- import { randomUUID as randomUUID3 } from "node:crypto";
6993
+ import { randomUUID as randomUUID4 } from "node:crypto";
6696
6994
 
6697
6995
  // src/forward.ts
6698
6996
  import { createInterface } from "node:readline";
@@ -11152,6 +11450,7 @@ async function postSavingsMetric(input) {
11152
11450
  // src/index.ts
11153
11451
  init_presence();
11154
11452
  init_presence_snapshot();
11453
+ init_session_identity();
11155
11454
 
11156
11455
  // src/working-paths.ts
11157
11456
  import { execFile as execFile2 } from "node:child_process";
@@ -11312,7 +11611,7 @@ async function main() {
11312
11611
  const savingsEnabled = process.env.MAIND_DISABLE_CODEBASE_TOOLS !== "1" && process.env.MAIND_DISABLE_SAVINGS_METRICS !== "1";
11313
11612
  const aggregator = savingsEnabled ? new SavingsAggregator() : null;
11314
11613
  const localRouter = process.env.MAIND_DISABLE_CODEBASE_TOOLS === "1" ? null : new LocalToolRouter(void 0, aggregator);
11315
- const savingsSessionId = `bridge-${randomUUID3()}`;
11614
+ const savingsSessionId = `bridge-${randomUUID4()}`;
11316
11615
  const flushSavings = async () => {
11317
11616
  if (!aggregator) return;
11318
11617
  const delta = aggregator.takePending();
@@ -11332,6 +11631,11 @@ async function main() {
11332
11631
  let currentForwarder = null;
11333
11632
  const presence = new PresenceAnnouncer({
11334
11633
  projectKey,
11634
+ // ADR-291 L1: abgeleitete Identität statt Würfeln — Kette Stem (Hook-
11635
+ // Seitenkanal) → MAIND_SESSION_ID → UUIDv5(device|ppid|Startzeit|repo)
11636
+ // → random. Der Announcer prüft den Seitenkanal vor jedem Announce und
11637
+ // meldet frühere Namen als also_known_as (L3a-Merge-Beweis).
11638
+ identity: new SessionIdentityManager({ projectKey }),
11335
11639
  postToolCall: (name, args) => {
11336
11640
  if (currentForwarder === null) {
11337
11641
  return Promise.reject(new Error("presence: no active forwarder"));