@maind-dev/mcp-bridge 0.36.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.36.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,15 +3136,28 @@ 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") {
3119
3151
  this.snapshot.endSession();
3120
3152
  } else if (payload !== null && payload !== void 0) {
3121
- this.snapshot.write(payload, {
3122
- sessionId: this.sessionId,
3123
- branch: this.lastBranch
3124
- });
3153
+ const meta = { sessionId: this.sessionId, branch: this.lastBranch };
3154
+ const p = typeof payload === "object" ? payload : null;
3155
+ if (p !== null && p.ok === true) {
3156
+ this.snapshot.write(payload, meta);
3157
+ } else if (this.snapshot.markFailed) {
3158
+ const code = p !== null && typeof p.error === "string" ? p.error : "announce_failed";
3159
+ this.snapshot.markFailed(code, meta);
3160
+ }
3125
3161
  }
3126
3162
  } catch {
3127
3163
  }
@@ -3189,6 +3225,30 @@ function createSnapshotStore(opts) {
3189
3225
  if (ownFile) unlinkSync(ownFile);
3190
3226
  } catch {
3191
3227
  }
3228
+ },
3229
+ markFailed(errorCode, meta) {
3230
+ try {
3231
+ const snapshot = {
3232
+ v: 1,
3233
+ written_at: new Date(now()).toISOString(),
3234
+ project_key: opts.projectKey,
3235
+ own_session_id: meta.sessionId,
3236
+ own_pid: pid,
3237
+ own_ppid: ppid,
3238
+ cwd,
3239
+ branch: meta.branch,
3240
+ peers: [],
3241
+ conflicts: [],
3242
+ announce_error: errorCode
3243
+ };
3244
+ mkdirSync4(dir, { recursive: true, mode: 448 });
3245
+ ownFile = join14(dir, `${meta.sessionId}.json`);
3246
+ const tmp = `${ownFile}.tmp-${pid}`;
3247
+ writeFileSync3(tmp, JSON.stringify(snapshot), { mode: 384 });
3248
+ renameSync2(tmp, ownFile);
3249
+ pruneStale(dir, now(), ownFile);
3250
+ } catch {
3251
+ }
3192
3252
  }
3193
3253
  };
3194
3254
  }
@@ -3249,7 +3309,8 @@ function parseSnapshot(raw) {
3249
3309
  cwd: o.cwd,
3250
3310
  branch: typeof o.branch === "string" ? o.branch : null,
3251
3311
  peers: Array.isArray(o.peers) ? o.peers : [],
3252
- conflicts: Array.isArray(o.conflicts) ? o.conflicts : []
3312
+ conflicts: Array.isArray(o.conflicts) ? o.conflicts : [],
3313
+ ...typeof o.announce_error === "string" ? { announce_error: o.announce_error } : {}
3253
3314
  };
3254
3315
  }
3255
3316
  var SNAPSHOT_TTL_MS;
@@ -3260,6 +3321,225 @@ var init_presence_snapshot = __esm({
3260
3321
  }
3261
3322
  });
3262
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
+
3263
3543
  // ../../packages/claude-code-telemetry/dist/types.js
3264
3544
  var init_types4 = __esm({
3265
3545
  "../../packages/claude-code-telemetry/dist/types.js"() {
@@ -3268,11 +3548,11 @@ var init_types4 = __esm({
3268
3548
  });
3269
3549
 
3270
3550
  // ../../packages/claude-code-telemetry/dist/transcript.js
3271
- import { createReadStream, existsSync as existsSync7 } from "node:fs";
3551
+ import { createReadStream, existsSync as existsSync8 } from "node:fs";
3272
3552
  import { stat } from "node:fs/promises";
3273
3553
  import { createInterface as createInterface5 } from "node:readline";
3274
3554
  async function summariseTranscript(path8) {
3275
- if (!path8 || !existsSync7(path8))
3555
+ if (!path8 || !existsSync8(path8))
3276
3556
  return null;
3277
3557
  let stats;
3278
3558
  try {
@@ -3357,7 +3637,7 @@ var init_effort = __esm({
3357
3637
  });
3358
3638
 
3359
3639
  // ../../packages/claude-code-telemetry/dist/session-analysis.js
3360
- import { createReadStream as createReadStream2, existsSync as existsSync8 } from "node:fs";
3640
+ import { createReadStream as createReadStream2, existsSync as existsSync9 } from "node:fs";
3361
3641
  import { createInterface as createInterface6 } from "node:readline";
3362
3642
  function num2(v) {
3363
3643
  return typeof v === "number" && Number.isFinite(v) ? v : 0;
@@ -3464,7 +3744,7 @@ function emptyAnalysis(sessionId) {
3464
3744
  }
3465
3745
  async function analyzeSession(path8) {
3466
3746
  const a = emptyAnalysis("");
3467
- if (!path8 || !existsSync8(path8))
3747
+ if (!path8 || !existsSync9(path8))
3468
3748
  return a;
3469
3749
  const reactions = [];
3470
3750
  const modelMix = /* @__PURE__ */ new Map();
@@ -3660,7 +3940,7 @@ var init_ingest = __esm({
3660
3940
  });
3661
3941
 
3662
3942
  // ../../packages/claude-code-telemetry/dist/session-span.js
3663
- import { createReadStream as createReadStream3, existsSync as existsSync9 } from "node:fs";
3943
+ import { createReadStream as createReadStream3, existsSync as existsSync10 } from "node:fs";
3664
3944
  import { createInterface as createInterface7 } from "node:readline";
3665
3945
  function asBlocks2(content) {
3666
3946
  if (typeof content === "string")
@@ -3712,7 +3992,7 @@ function classify2(parsed) {
3712
3992
  }
3713
3993
  async function analyzeSpan(path8) {
3714
3994
  const s = emptySpan("");
3715
- if (!path8 || !existsSync9(path8))
3995
+ if (!path8 || !existsSync10(path8))
3716
3996
  return s;
3717
3997
  let firstMs = null;
3718
3998
  let lastMs = 0;
@@ -3824,14 +4104,14 @@ var init_windows = __esm({
3824
4104
  });
3825
4105
 
3826
4106
  // ../../packages/claude-code-telemetry/dist/projects.js
3827
- import { homedir as homedir4 } from "node:os";
3828
- import { join as join15 } from "node:path";
4107
+ import { homedir as homedir5 } from "node:os";
4108
+ import { join as join16 } from "node:path";
3829
4109
  var HOME, DEFAULT_PROJECTS_DIR;
3830
4110
  var init_projects = __esm({
3831
4111
  "../../packages/claude-code-telemetry/dist/projects.js"() {
3832
4112
  "use strict";
3833
- HOME = homedir4();
3834
- DEFAULT_PROJECTS_DIR = join15(HOME, ".claude", "projects");
4113
+ HOME = homedir5();
4114
+ DEFAULT_PROJECTS_DIR = join16(HOME, ".claude", "projects");
3835
4115
  }
3836
4116
  });
3837
4117
 
@@ -3985,13 +4265,13 @@ function adviseOnPath(snap, relPath, opts) {
3985
4265
  ` + hits.map((h) => ` \u2022 ${h}`).join("\n") + `
3986
4266
  Verify live before large edits: check_path_conflicts({project_key: "${snap.project_key}", paths: ["${relPath}"]}) \u2014 then claim_paths for your own edit area.`;
3987
4267
  }
3988
- function sessionStartSummary(snap, ownSessionId, nowMs, maxAgeMs = SNAPSHOT_MAX_AGE_MS) {
4268
+ function sessionStartSummary(snap, ownSessionId, nowMs, maxAgeMs = SNAPSHOT_MAX_AGE_MS, ownAnnounceError = null) {
3989
4269
  if (!snap) return null;
3990
4270
  const ageMs = nowMs - Date.parse(snap.written_at);
3991
4271
  if (!Number.isFinite(ageMs) || ageMs < 0 || ageMs > maxAgeMs) return null;
3992
4272
  const ageSeconds = ageMs / 1e3;
3993
4273
  const peers = parsePeers(snap, ageSeconds);
3994
- const idLine = ownSessionId !== null ? `[maind] your coordination session: ${ownSessionId} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).` : null;
4274
+ const idLine = ownAnnounceError !== null ? `[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${ownAnnounceError}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.` : ownSessionId !== null ? `[maind] your coordination session: ${ownSessionId} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).` : null;
3995
4275
  if (peers.length === 0) return idLine;
3996
4276
  const claimCount = peers.reduce((n, p) => n + p.claims.length, 0);
3997
4277
  const signalPoor = peers.filter(
@@ -4079,14 +4359,14 @@ var init_payloads = __esm({
4079
4359
 
4080
4360
  // src/hooks/state.ts
4081
4361
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, rename as rename2 } from "node:fs/promises";
4082
- import { existsSync as existsSync10 } from "node:fs";
4083
- import { homedir as homedir5 } from "node:os";
4084
- 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";
4085
4365
  function emptyState() {
4086
4366
  return { config: null, sessions: {}, pending_metrics: [] };
4087
4367
  }
4088
4368
  async function loadState() {
4089
- if (!existsSync10(STATE_FILE)) return emptyState();
4369
+ if (!existsSync11(STATE_FILE)) return emptyState();
4090
4370
  try {
4091
4371
  const raw = await readFile2(STATE_FILE, "utf-8");
4092
4372
  const parsed = JSON.parse(raw);
@@ -4107,7 +4387,7 @@ async function loadState() {
4107
4387
  }
4108
4388
  }
4109
4389
  async function saveState(state) {
4110
- if (!existsSync10(STATE_DIR)) {
4390
+ if (!existsSync11(STATE_DIR)) {
4111
4391
  await mkdir2(STATE_DIR, { recursive: true, mode: 448 });
4112
4392
  }
4113
4393
  const tmp = `${STATE_FILE}.tmp`;
@@ -4121,8 +4401,8 @@ var STATE_DIR, STATE_FILE, DEFAULT_THRESHOLDS;
4121
4401
  var init_state = __esm({
4122
4402
  "src/hooks/state.ts"() {
4123
4403
  "use strict";
4124
- STATE_DIR = join16(homedir5(), ".maind");
4125
- STATE_FILE = join16(STATE_DIR, "state.json");
4404
+ STATE_DIR = join17(homedir6(), ".maind");
4405
+ STATE_FILE = join17(STATE_DIR, "state.json");
4126
4406
  DEFAULT_THRESHOLDS = {
4127
4407
  warn_at_pct: 60,
4128
4408
  handoff_at_pct: 85,
@@ -4147,11 +4427,11 @@ __export(hooks_exports, {
4147
4427
  runSessionEndMetrics: () => runSessionEndMetrics,
4148
4428
  runSyncConfig: () => runSyncConfig
4149
4429
  });
4150
- import { execFileSync as execFileSync7 } from "node:child_process";
4151
- 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";
4152
4432
  import { writeFile as writeFile3 } from "node:fs/promises";
4153
- import { homedir as homedir6 } from "node:os";
4154
- 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";
4155
4435
  function recordGuardSignals(state, sessionId, toolName, nowMs = Date.now()) {
4156
4436
  if (!toolName.includes("maind")) return;
4157
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");
@@ -4234,6 +4514,10 @@ async function runOnSessionStart() {
4234
4514
  if (sessionId === null) return 0;
4235
4515
  getOrCreateSession(state, sessionId);
4236
4516
  await saveState(state);
4517
+ try {
4518
+ writeIdentitySideChannel(input, sessionId);
4519
+ } catch {
4520
+ }
4237
4521
  try {
4238
4522
  const projectKey = computeProjectKey();
4239
4523
  if (projectKey !== null) {
@@ -4246,7 +4530,12 @@ async function runOnSessionStart() {
4246
4530
  const summary = sessionStartSummary(
4247
4531
  own?.snap ?? snaps[0] ?? null,
4248
4532
  own?.snap.own_session_id ?? null,
4249
- Date.now()
4533
+ Date.now(),
4534
+ void 0,
4535
+ // ADR-291 L4: nur der VERIFIZIERT eigene Snapshot darf eine
4536
+ // Fehl-Announce-Warnung auslösen — der announce_error eines Peers
4537
+ // sagt nichts über diese Session.
4538
+ own?.snap.announce_error ?? null
4250
4539
  );
4251
4540
  if (summary !== null) process.stdout.write(summary + "\n");
4252
4541
  }
@@ -4267,16 +4556,29 @@ async function runOnSessionStart() {
4267
4556
  }
4268
4557
  function readSettingsRaw() {
4269
4558
  try {
4270
- const p = join17(homedir6(), ".claude", "settings.json");
4271
- return existsSync11(p) ? readFileSync8(p, "utf8") : null;
4559
+ const p = join18(homedir7(), ".claude", "settings.json");
4560
+ return existsSync12(p) ? readFileSync9(p, "utf8") : null;
4272
4561
  } catch {
4273
4562
  return null;
4274
4563
  }
4275
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
+ }
4276
4578
  function grandparentPid() {
4277
4579
  try {
4278
4580
  if (process.platform === "win32") return null;
4279
- const out2 = execFileSync7("ps", ["-o", "ppid=", "-p", String(process.ppid)], {
4581
+ const out2 = execFileSync8("ps", ["-o", "ppid=", "-p", String(process.ppid)], {
4280
4582
  timeout: 1e3,
4281
4583
  encoding: "utf8"
4282
4584
  });
@@ -4293,6 +4595,13 @@ async function runOnToolUse() {
4293
4595
  const sessionId = sessionIdOf(input) ?? "unknown";
4294
4596
  const session = getOrCreateSession(state, sessionId);
4295
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
+ }
4296
4605
  const tool = (input.tool_name ?? "").toString();
4297
4606
  if (tool.includes("search_lessons") || tool.includes("get_session_briefing") || tool.includes("get_lesson")) {
4298
4607
  session.lessons_consulted += 1;
@@ -4314,15 +4623,15 @@ async function runOnToolUse() {
4314
4623
  }
4315
4624
  function realpathOfUnwritten(p) {
4316
4625
  let head = dirname6(p);
4317
- const tail = [basename2(p)];
4626
+ const tail = [basename3(p)];
4318
4627
  for (; ; ) {
4319
4628
  try {
4320
4629
  const real = realpathSync2(head);
4321
- return join17(real, ...tail.reverse());
4630
+ return join18(real, ...tail.reverse());
4322
4631
  } catch {
4323
4632
  const parent = dirname6(head);
4324
4633
  if (parent === head) return p;
4325
- tail.push(basename2(head));
4634
+ tail.push(basename3(head));
4326
4635
  head = parent;
4327
4636
  }
4328
4637
  }
@@ -4343,8 +4652,8 @@ async function runOnFileWrite() {
4343
4652
  const filePath = toolFilePathOf(input);
4344
4653
  if (!filePath) return 0;
4345
4654
  const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
4346
- const abs = isAbsolute4(filePath) ? filePath : join17(cwd, filePath);
4347
- if (existsSync11(abs)) return 0;
4655
+ const abs = isAbsolute4(filePath) ? filePath : join18(cwd, filePath);
4656
+ if (existsSync12(abs)) return 0;
4348
4657
  const repoRoot = resolveRepoRoot(cwd);
4349
4658
  const rel = relative3(repoRoot, realpathOfUnwritten(abs));
4350
4659
  if (rel.length === 0 || rel.startsWith("..") || isAbsolute4(rel)) return 0;
@@ -4364,7 +4673,7 @@ async function runOnFileEdit() {
4364
4673
  const filePath = toolFilePathOf(input);
4365
4674
  if (!filePath) return 0;
4366
4675
  const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
4367
- const abs = isAbsolute4(filePath) ? filePath : join17(cwd, filePath);
4676
+ const abs = isAbsolute4(filePath) ? filePath : join18(cwd, filePath);
4368
4677
  const projectKey = computeProjectKey();
4369
4678
  if (projectKey === null) return 0;
4370
4679
  const snaps = readSnapshots(projectKey);
@@ -4375,7 +4684,7 @@ async function runOnFileEdit() {
4375
4684
  });
4376
4685
  if (own === null) return 0;
4377
4686
  const repoRoot = resolveRepoRoot(cwd);
4378
- const real = existsSync11(abs) ? realpathSync2(abs) : realpathOfUnwritten(abs);
4687
+ const real = existsSync12(abs) ? realpathSync2(abs) : realpathOfUnwritten(abs);
4379
4688
  const rel = relative3(repoRoot, real).replace(/\\/g, "/");
4380
4689
  if (rel.length === 0 || rel.startsWith("..") || isAbsolute4(rel)) return 0;
4381
4690
  const advice = adviseOnPath(own.snap, rel, {
@@ -4392,7 +4701,7 @@ async function runOnFileEdit() {
4392
4701
  }
4393
4702
  function currentGitBranch(cwd) {
4394
4703
  try {
4395
- const out2 = execFileSync7("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
4704
+ const out2 = execFileSync8("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
4396
4705
  cwd,
4397
4706
  timeout: 1e3,
4398
4707
  encoding: "utf8"
@@ -4427,7 +4736,7 @@ async function maybeEmitAdvisory(state, session) {
4427
4736
  };
4428
4737
  try {
4429
4738
  await writeFile3(
4430
- join17(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
4739
+ join18(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
4431
4740
  JSON.stringify(payload, null, 2)
4432
4741
  );
4433
4742
  } catch (err) {
@@ -4547,10 +4856,10 @@ async function runHookStatus() {
4547
4856
  return 0;
4548
4857
  }
4549
4858
  function readHookWiring() {
4550
- const settingsPath = join17(homedir6(), ".claude", "settings.json");
4859
+ const settingsPath = join18(homedir7(), ".claude", "settings.json");
4551
4860
  let raw = null;
4552
4861
  try {
4553
- if (existsSync11(settingsPath)) raw = readFileSync8(settingsPath, "utf8");
4862
+ if (existsSync12(settingsPath)) raw = readFileSync9(settingsPath, "utf8");
4554
4863
  } catch {
4555
4864
  }
4556
4865
  return { settingsPath, findings: inspectHookWiring(raw) };
@@ -4624,7 +4933,7 @@ function sessionIdOf(input) {
4624
4933
  const id = typeof input.session_id === "string" ? input.session_id.trim() : "";
4625
4934
  return id.length > 0 ? id : null;
4626
4935
  }
4627
- 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;
4628
4937
  var init_hooks2 = __esm({
4629
4938
  "src/hooks/index.ts"() {
4630
4939
  "use strict";
@@ -4637,6 +4946,7 @@ var init_hooks2 = __esm({
4637
4946
  init_project_key();
4638
4947
  init_api();
4639
4948
  init_edit_guard();
4949
+ init_session_identity();
4640
4950
  init_hook_input();
4641
4951
  init_payloads();
4642
4952
  init_state();
@@ -4644,6 +4954,7 @@ var init_hooks2 = __esm({
4644
4954
  STOP_FLUSH_TIMEOUT_MS = 1500;
4645
4955
  MANUAL_FLUSH_TIMEOUT_MS = 1e4;
4646
4956
  STATE_GC_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
4957
+ IDENTITY_REFRESH_MS = 6e4;
4647
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.";
4648
4959
  }
4649
4960
  });
@@ -4691,8 +5002,21 @@ function connectionVerdict(sawMaindCall, nowMs) {
4691
5002
  }
4692
5003
  }
4693
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
+ }
4694
5018
  const raw = (process.env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
4695
- 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;
4696
5020
  }
4697
5021
  async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
4698
5022
  const post = fetch(INGEST_ENDPOINT, {
@@ -4709,6 +5033,13 @@ async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
4709
5033
  await Promise.race([post, timeout]);
4710
5034
  }
4711
5035
  async function runOnSessionEnd() {
5036
+ try {
5037
+ const agentPid = grandparentPid();
5038
+ if (agentPid !== null) {
5039
+ deleteAgentIdentityFile(identityDirPath(), agentPid);
5040
+ }
5041
+ } catch {
5042
+ }
4712
5043
  const apiKey = readApiKey();
4713
5044
  if (!apiKey) return 0;
4714
5045
  const input = await readHookInput();
@@ -4764,6 +5095,7 @@ var init_session_end = __esm({
4764
5095
  init_presence();
4765
5096
  init_presence_snapshot();
4766
5097
  init_project_key();
5098
+ init_session_identity();
4767
5099
  init_version();
4768
5100
  init_connection();
4769
5101
  INGEST_ENDPOINT = DEFAULT_INGEST_ENDPOINT;
@@ -4891,16 +5223,16 @@ var init_install = __esm({
4891
5223
  });
4892
5224
 
4893
5225
  // src/guard/session-file.ts
4894
- import { existsSync as existsSync12 } from "node:fs";
5226
+ import { existsSync as existsSync13 } from "node:fs";
4895
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";
4896
- import { join as join18 } from "node:path";
5228
+ import { join as join19 } from "node:path";
4897
5229
  function sessionFile(sessionId) {
4898
- 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");
4899
5231
  }
4900
5232
  async function loadGuardSession(sessionId) {
4901
5233
  try {
4902
5234
  const file = sessionFile(sessionId);
4903
- if (!existsSync12(file)) return {};
5235
+ if (!existsSync13(file)) return {};
4904
5236
  const parsed = JSON.parse(await readFile3(file, "utf8"));
4905
5237
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
4906
5238
  return parsed;
@@ -4921,10 +5253,10 @@ async function saveGuardSession(sessionId, state) {
4921
5253
  }
4922
5254
  async function sweepOldGuardSessions(maxAgeMs = 7 * 24 * 60 * 60 * 1e3, nowMs = Date.now()) {
4923
5255
  try {
4924
- if (!existsSync12(GUARD_SESSIONS_DIR)) return;
5256
+ if (!existsSync13(GUARD_SESSIONS_DIR)) return;
4925
5257
  for (const name of await readdir(GUARD_SESSIONS_DIR)) {
4926
5258
  if (!name.endsWith(".json")) continue;
4927
- const file = join18(GUARD_SESSIONS_DIR, name);
5259
+ const file = join19(GUARD_SESSIONS_DIR, name);
4928
5260
  try {
4929
5261
  const s = await stat2(file);
4930
5262
  if (nowMs - s.mtimeMs > maxAgeMs) await unlink2(file);
@@ -4939,15 +5271,15 @@ var init_session_file = __esm({
4939
5271
  "src/guard/session-file.ts"() {
4940
5272
  "use strict";
4941
5273
  init_state();
4942
- GUARD_DIR = join18(STATE_DIR, "guard");
4943
- GUARD_SESSIONS_DIR = join18(GUARD_DIR, "sessions");
5274
+ GUARD_DIR = join19(STATE_DIR, "guard");
5275
+ GUARD_SESSIONS_DIR = join19(GUARD_DIR, "sessions");
4944
5276
  }
4945
5277
  });
4946
5278
 
4947
5279
  // src/guard/log.ts
4948
- import { existsSync as existsSync13 } from "node:fs";
5280
+ import { existsSync as existsSync14 } from "node:fs";
4949
5281
  import { appendFile, mkdir as mkdir4, open } from "node:fs/promises";
4950
- import { join as join19 } from "node:path";
5282
+ import { join as join20 } from "node:path";
4951
5283
  async function appendGuardEvent(event) {
4952
5284
  try {
4953
5285
  await mkdir4(GUARD_DIR, { recursive: true, mode: 448 });
@@ -4969,7 +5301,7 @@ async function readGuardEventCounts(tailBytes = 256 * 1024) {
4969
5301
  cross_session_deny: 0
4970
5302
  };
4971
5303
  try {
4972
- if (!existsSync13(GUARD_EVENTS_FILE)) return counts;
5304
+ if (!existsSync14(GUARD_EVENTS_FILE)) return counts;
4973
5305
  const fh = await open(GUARD_EVENTS_FILE, "r");
4974
5306
  try {
4975
5307
  const size = (await fh.stat()).size;
@@ -5000,7 +5332,7 @@ var init_log = __esm({
5000
5332
  "src/guard/log.ts"() {
5001
5333
  "use strict";
5002
5334
  init_session_file();
5003
- GUARD_EVENTS_FILE = join19(GUARD_DIR, "events.jsonl");
5335
+ GUARD_EVENTS_FILE = join20(GUARD_DIR, "events.jsonl");
5004
5336
  }
5005
5337
  });
5006
5338
 
@@ -5009,15 +5341,15 @@ var cli_exports = {};
5009
5341
  __export(cli_exports, {
5010
5342
  runGuard: () => runGuard
5011
5343
  });
5012
- import { existsSync as existsSync14, readFileSync as readFileSync9 } from "node:fs";
5013
- import { homedir as homedir7 } from "node:os";
5014
- 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";
5015
5347
  async function runGuard(argv) {
5016
5348
  const verb = argv[0];
5017
5349
  const rest = argv.slice(1);
5018
5350
  switch (verb) {
5019
5351
  case "install":
5020
- return runGuardInstall(rest, homedir7());
5352
+ return runGuardInstall(rest, homedir8());
5021
5353
  case "status":
5022
5354
  return runGuardStatus();
5023
5355
  case "mode": {
@@ -5088,10 +5420,10 @@ logged (auditable) in ${GUARD_EVENTS_FILE}
5088
5420
  }
5089
5421
  async function runGuardStatus() {
5090
5422
  const config = resolveGuardConfig();
5091
- const settingsPath = join20(homedir7(), ".claude", "settings.json");
5423
+ const settingsPath = join21(homedir8(), ".claude", "settings.json");
5092
5424
  let raw = null;
5093
5425
  try {
5094
- if (existsSync14(settingsPath)) raw = readFileSync9(settingsPath, "utf8");
5426
+ if (existsSync15(settingsPath)) raw = readFileSync10(settingsPath, "utf8");
5095
5427
  } catch {
5096
5428
  }
5097
5429
  const wiring = inspectHookWiring(raw, {}, GUARD_SUBCOMMAND_HOOKS);
@@ -5283,9 +5615,9 @@ __export(inject_exports, {
5283
5615
  resolveBriefingInjection: () => resolveBriefingInjection,
5284
5616
  runGuardInject: () => runGuardInject
5285
5617
  });
5286
- import { existsSync as existsSync15 } from "node:fs";
5618
+ import { existsSync as existsSync16 } from "node:fs";
5287
5619
  import { mkdir as mkdir5, readFile as readFile4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
5288
- import { dirname as dirname7, join as join21 } from "node:path";
5620
+ import { dirname as dirname7, join as join22 } from "node:path";
5289
5621
  async function resolveBriefingInjection(projectKey, apiKey, deps = {}) {
5290
5622
  const nowMs = deps.nowMs ?? Date.now();
5291
5623
  const cacheFile = deps.cacheFile ?? BRIEFING_CACHE_FILE;
@@ -5370,7 +5702,7 @@ function formatInjection(text, via) {
5370
5702
  }
5371
5703
  async function readCache(file) {
5372
5704
  try {
5373
- if (!existsSync15(file)) return null;
5705
+ if (!existsSync16(file)) return null;
5374
5706
  const parsed = JSON.parse(await readFile4(file, "utf8"));
5375
5707
  if (typeof parsed.fetched_at !== "string" || typeof parsed.text !== "string") return null;
5376
5708
  if (Number.isNaN(Date.parse(parsed.fetched_at))) return null;
@@ -5411,7 +5743,7 @@ var init_inject = __esm({
5411
5743
  init_log();
5412
5744
  init_session_file();
5413
5745
  init_mcp_client();
5414
- BRIEFING_CACHE_FILE = join21(GUARD_DIR, "briefing-cache.json");
5746
+ BRIEFING_CACHE_FILE = join22(GUARD_DIR, "briefing-cache.json");
5415
5747
  CACHE_TTL_MS = 12 * 60 * 60 * 1e3;
5416
5748
  FETCH_BUDGET_MS = 3e3;
5417
5749
  MAX_INJECT_BYTES = 10 * 1024;
@@ -5640,8 +5972,8 @@ var init_frames = __esm({
5640
5972
 
5641
5973
  // src/gateway/attest.ts
5642
5974
  import { appendFile as appendFile2, mkdir as mkdir6, readFile as readFile5, rename as rename5, writeFile as writeFile6 } from "node:fs/promises";
5643
- import { homedir as homedir8 } from "node:os";
5644
- import { join as join22 } from "node:path";
5975
+ import { homedir as homedir9 } from "node:os";
5976
+ import { join as join23 } from "node:path";
5645
5977
  function aggregateWindow(events, mode, serverLabel, projectKey) {
5646
5978
  if (mode === "off" || events.length === 0) return null;
5647
5979
  const counts = {};
@@ -5675,7 +6007,7 @@ function aggregateWindow(events, mode, serverLabel, projectKey) {
5675
6007
  };
5676
6008
  }
5677
6009
  function attestSpoolPath() {
5678
- return join22(homedir8(), ".maind", "gateway", "attest-spool.jsonl");
6010
+ return join23(homedir9(), ".maind", "gateway", "attest-spool.jsonl");
5679
6011
  }
5680
6012
  async function postAttestation(payload) {
5681
6013
  const apiKey = readApiKey();
@@ -5698,7 +6030,7 @@ async function postAttestation(payload) {
5698
6030
  }
5699
6031
  async function spoolAttestation(payload) {
5700
6032
  try {
5701
- await mkdir6(join22(homedir8(), ".maind", "gateway"), { recursive: true });
6033
+ await mkdir6(join23(homedir9(), ".maind", "gateway"), { recursive: true });
5702
6034
  await appendFile2(attestSpoolPath(), JSON.stringify(payload) + "\n", { mode: 384 });
5703
6035
  await capSpool();
5704
6036
  } catch {
@@ -5863,11 +6195,11 @@ var init_policy = __esm({
5863
6195
  });
5864
6196
 
5865
6197
  // src/gateway/policy-cache.ts
5866
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync10, renameSync as renameSync3, writeFileSync as writeFileSync4 } from "node:fs";
5867
- import { homedir as homedir9 } from "node:os";
5868
- 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";
5869
6201
  function policyCachePath() {
5870
- return join23(homedir9(), ".maind", "gateway", "policy-cache.json");
6202
+ return join24(homedir10(), ".maind", "gateway", "policy-cache.json");
5871
6203
  }
5872
6204
  function writePolicyCache(identity, rules, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
5873
6205
  try {
@@ -5879,16 +6211,16 @@ function writePolicyCache(identity, rules, nowIso = (/* @__PURE__ */ new Date())
5879
6211
  rules
5880
6212
  };
5881
6213
  const target = policyCachePath();
5882
- mkdirSync5(dirname8(target), { recursive: true });
6214
+ mkdirSync6(dirname8(target), { recursive: true });
5883
6215
  const tmp = `${target}.${process.pid}.tmp`;
5884
- writeFileSync4(tmp, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 384 });
5885
- renameSync3(tmp, target);
6216
+ writeFileSync5(tmp, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 384 });
6217
+ renameSync4(tmp, target);
5886
6218
  } catch {
5887
6219
  }
5888
6220
  }
5889
6221
  function readPolicyCache(identity) {
5890
6222
  try {
5891
- const raw = readFileSync10(policyCachePath(), "utf8");
6223
+ const raw = readFileSync11(policyCachePath(), "utf8");
5892
6224
  const parsed = JSON.parse(raw);
5893
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)) {
5894
6226
  return null;
@@ -6035,9 +6367,9 @@ __export(install_exports, {
6035
6367
  runGatewayInstall: () => runGatewayInstall,
6036
6368
  runGatewayUninstall: () => runGatewayUninstall
6037
6369
  });
6038
- import { existsSync as existsSync16, readFileSync as readFileSync11 } from "node:fs";
6039
- import { homedir as homedir10 } from "node:os";
6040
- 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";
6041
6373
  import { createInterface as createInterface8 } from "node:readline";
6042
6374
  function parseFlags(argv) {
6043
6375
  const f = { yes: false, dryRun: false };
@@ -6050,8 +6382,8 @@ function parseFlags(argv) {
6050
6382
  }
6051
6383
  function targets() {
6052
6384
  return [
6053
- { label: "Claude Code (project .mcp.json)", path: join24(process.cwd(), ".mcp.json") },
6054
- { 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") }
6055
6387
  ];
6056
6388
  }
6057
6389
  async function confirm(question) {
@@ -6081,8 +6413,8 @@ function loadConfig(path8) {
6081
6413
  }
6082
6414
  function readFileSafeSync(path8) {
6083
6415
  try {
6084
- if (!existsSync16(path8)) return null;
6085
- return readFileSync11(path8, "utf8");
6416
+ if (!existsSync17(path8)) return null;
6417
+ return readFileSync12(path8, "utf8");
6086
6418
  } catch {
6087
6419
  return null;
6088
6420
  }
@@ -6311,16 +6643,16 @@ __export(run_exports, {
6311
6643
  });
6312
6644
  import { spawn as spawn2 } from "node:child_process";
6313
6645
  import { appendFile as appendFile3, mkdir as mkdir7 } from "node:fs/promises";
6314
- import { homedir as homedir11 } from "node:os";
6315
- 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";
6316
6648
  import { createInterface as createInterface9 } from "node:readline";
6317
6649
  function gatewayEventsFile() {
6318
- return join25(homedir11(), ".maind", "gateway", "events.jsonl");
6650
+ return join26(homedir12(), ".maind", "gateway", "events.jsonl");
6319
6651
  }
6320
6652
  async function logEvent(e) {
6321
6653
  try {
6322
6654
  const file = gatewayEventsFile();
6323
- await mkdir7(join25(homedir11(), ".maind", "gateway"), { recursive: true });
6655
+ await mkdir7(join26(homedir12(), ".maind", "gateway"), { recursive: true });
6324
6656
  await appendFile3(file, JSON.stringify(e) + "\n", { mode: 384 });
6325
6657
  } catch {
6326
6658
  }
@@ -6373,7 +6705,7 @@ async function runGateway(argv) {
6373
6705
  return 2;
6374
6706
  }
6375
6707
  const { denyTools, label, command, args } = parsed;
6376
- const serverLabel = label ?? basename3(command);
6708
+ const serverLabel = label ?? basename4(command);
6377
6709
  const mode = resolveGatewayMode();
6378
6710
  let policyRules = mode === "off" ? [] : readPolicyCache(policyIdentity())?.rules ?? [];
6379
6711
  if (mode !== "off") {
@@ -6507,10 +6839,10 @@ __export(cross_session_exports, {
6507
6839
  staleReason: () => staleReason
6508
6840
  });
6509
6841
  import { mkdir as mkdir8, readFile as readFile6, readdir as readdir2, stat as stat3, unlink as unlink3, writeFile as writeFile7 } from "node:fs/promises";
6510
- import { homedir as homedir12 } from "node:os";
6511
- import { join as join26 } from "node:path";
6842
+ import { homedir as homedir13 } from "node:os";
6843
+ import { join as join27 } from "node:path";
6512
6844
  function crossSessionDir() {
6513
- return join26(homedir12(), ".maind", "cross-session");
6845
+ return join27(homedir13(), ".maind", "cross-session");
6514
6846
  }
6515
6847
  function parseSessionDb(raw) {
6516
6848
  const empty = { files: {}, warned: {} };
@@ -6552,7 +6884,7 @@ function staleReason(path8, v) {
6552
6884
  async function dbPath(sessionId) {
6553
6885
  const dir = crossSessionDir();
6554
6886
  await mkdir8(dir, { recursive: true });
6555
- return join26(dir, `${sessionId}.json`);
6887
+ return join27(dir, `${sessionId}.json`);
6556
6888
  }
6557
6889
  async function loadDb(sessionId, now) {
6558
6890
  try {
@@ -6573,7 +6905,7 @@ async function sweepStaleSessionFiles(now) {
6573
6905
  const dir = crossSessionDir();
6574
6906
  for (const name of await readdir2(dir)) {
6575
6907
  if (!name.endsWith(".json")) continue;
6576
- const p = join26(dir, name);
6908
+ const p = join27(dir, name);
6577
6909
  const s = await stat3(p).catch(() => null);
6578
6910
  if (s && now - s.mtimeMs > TTL_MS) await unlink3(p).catch(() => {
6579
6911
  });
@@ -6658,7 +6990,7 @@ var init_cross_session = __esm({
6658
6990
  });
6659
6991
 
6660
6992
  // src/index.ts
6661
- import { randomUUID as randomUUID3 } from "node:crypto";
6993
+ import { randomUUID as randomUUID4 } from "node:crypto";
6662
6994
 
6663
6995
  // src/forward.ts
6664
6996
  import { createInterface } from "node:readline";
@@ -11118,6 +11450,7 @@ async function postSavingsMetric(input) {
11118
11450
  // src/index.ts
11119
11451
  init_presence();
11120
11452
  init_presence_snapshot();
11453
+ init_session_identity();
11121
11454
 
11122
11455
  // src/working-paths.ts
11123
11456
  import { execFile as execFile2 } from "node:child_process";
@@ -11278,7 +11611,7 @@ async function main() {
11278
11611
  const savingsEnabled = process.env.MAIND_DISABLE_CODEBASE_TOOLS !== "1" && process.env.MAIND_DISABLE_SAVINGS_METRICS !== "1";
11279
11612
  const aggregator = savingsEnabled ? new SavingsAggregator() : null;
11280
11613
  const localRouter = process.env.MAIND_DISABLE_CODEBASE_TOOLS === "1" ? null : new LocalToolRouter(void 0, aggregator);
11281
- const savingsSessionId = `bridge-${randomUUID3()}`;
11614
+ const savingsSessionId = `bridge-${randomUUID4()}`;
11282
11615
  const flushSavings = async () => {
11283
11616
  if (!aggregator) return;
11284
11617
  const delta = aggregator.takePending();
@@ -11298,6 +11631,11 @@ async function main() {
11298
11631
  let currentForwarder = null;
11299
11632
  const presence = new PresenceAnnouncer({
11300
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 }),
11301
11639
  postToolCall: (name, args) => {
11302
11640
  if (currentForwarder === null) {
11303
11641
  return Promise.reject(new Error("presence: no active forwarder"));