@mrrlin-dev/mcp 0.4.174 → 0.4.176

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.
Files changed (2) hide show
  1. package/dist/bin.cjs +1670 -618
  2. package/package.json +1 -1
package/dist/bin.cjs CHANGED
@@ -5258,8 +5258,8 @@ var require_utils = __commonJS({
5258
5258
  }
5259
5259
  return ind;
5260
5260
  }
5261
- function removeDotSegments(path38) {
5262
- let input = path38;
5261
+ function removeDotSegments(path39) {
5262
+ let input = path39;
5263
5263
  const output3 = [];
5264
5264
  let nextSlash = -1;
5265
5265
  let len = 0;
@@ -5668,8 +5668,8 @@ var require_schemes = __commonJS({
5668
5668
  }
5669
5669
  if (wsComponent.resourceName) {
5670
5670
  const queryIndex = wsComponent.resourceName.indexOf("?");
5671
- const path38 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
5672
- wsComponent.path = path38 && path38 !== "/" ? path38 : void 0;
5671
+ const path39 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
5672
+ wsComponent.path = path39 && path39 !== "/" ? path39 : void 0;
5673
5673
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
5674
5674
  wsComponent.resourceName = void 0;
5675
5675
  }
@@ -9305,7 +9305,7 @@ var require_windows = __commonJS({
9305
9305
  module2.exports = isexe;
9306
9306
  isexe.sync = sync;
9307
9307
  var fs18 = require("fs");
9308
- function checkPathExt(path38, options) {
9308
+ function checkPathExt(path39, options) {
9309
9309
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
9310
9310
  if (!pathext) {
9311
9311
  return true;
@@ -9316,25 +9316,25 @@ var require_windows = __commonJS({
9316
9316
  }
9317
9317
  for (var i = 0; i < pathext.length; i++) {
9318
9318
  var p = pathext[i].toLowerCase();
9319
- if (p && path38.substr(-p.length).toLowerCase() === p) {
9319
+ if (p && path39.substr(-p.length).toLowerCase() === p) {
9320
9320
  return true;
9321
9321
  }
9322
9322
  }
9323
9323
  return false;
9324
9324
  }
9325
- function checkStat(stat3, path38, options) {
9325
+ function checkStat(stat3, path39, options) {
9326
9326
  if (!stat3.isSymbolicLink() && !stat3.isFile()) {
9327
9327
  return false;
9328
9328
  }
9329
- return checkPathExt(path38, options);
9329
+ return checkPathExt(path39, options);
9330
9330
  }
9331
- function isexe(path38, options, cb) {
9332
- fs18.stat(path38, function(er, stat3) {
9333
- cb(er, er ? false : checkStat(stat3, path38, options));
9331
+ function isexe(path39, options, cb) {
9332
+ fs18.stat(path39, function(er, stat3) {
9333
+ cb(er, er ? false : checkStat(stat3, path39, options));
9334
9334
  });
9335
9335
  }
9336
- function sync(path38, options) {
9337
- return checkStat(fs18.statSync(path38), path38, options);
9336
+ function sync(path39, options) {
9337
+ return checkStat(fs18.statSync(path39), path39, options);
9338
9338
  }
9339
9339
  }
9340
9340
  });
@@ -9345,13 +9345,13 @@ var require_mode = __commonJS({
9345
9345
  module2.exports = isexe;
9346
9346
  isexe.sync = sync;
9347
9347
  var fs18 = require("fs");
9348
- function isexe(path38, options, cb) {
9349
- fs18.stat(path38, function(er, stat3) {
9348
+ function isexe(path39, options, cb) {
9349
+ fs18.stat(path39, function(er, stat3) {
9350
9350
  cb(er, er ? false : checkStat(stat3, options));
9351
9351
  });
9352
9352
  }
9353
- function sync(path38, options) {
9354
- return checkStat(fs18.statSync(path38), options);
9353
+ function sync(path39, options) {
9354
+ return checkStat(fs18.statSync(path39), options);
9355
9355
  }
9356
9356
  function checkStat(stat3, options) {
9357
9357
  return stat3.isFile() && checkMode(stat3, options);
@@ -9384,7 +9384,7 @@ var require_isexe = __commonJS({
9384
9384
  }
9385
9385
  module2.exports = isexe;
9386
9386
  isexe.sync = sync;
9387
- function isexe(path38, options, cb) {
9387
+ function isexe(path39, options, cb) {
9388
9388
  if (typeof options === "function") {
9389
9389
  cb = options;
9390
9390
  options = {};
@@ -9394,7 +9394,7 @@ var require_isexe = __commonJS({
9394
9394
  throw new TypeError("callback not provided");
9395
9395
  }
9396
9396
  return new Promise(function(resolve3, reject) {
9397
- isexe(path38, options || {}, function(er, is) {
9397
+ isexe(path39, options || {}, function(er, is) {
9398
9398
  if (er) {
9399
9399
  reject(er);
9400
9400
  } else {
@@ -9403,7 +9403,7 @@ var require_isexe = __commonJS({
9403
9403
  });
9404
9404
  });
9405
9405
  }
9406
- core(path38, options || {}, function(er, is) {
9406
+ core(path39, options || {}, function(er, is) {
9407
9407
  if (er) {
9408
9408
  if (er.code === "EACCES" || options && options.ignoreErrors) {
9409
9409
  er = null;
@@ -9413,9 +9413,9 @@ var require_isexe = __commonJS({
9413
9413
  cb(er, is);
9414
9414
  });
9415
9415
  }
9416
- function sync(path38, options) {
9416
+ function sync(path39, options) {
9417
9417
  try {
9418
- return core.sync(path38, options || {});
9418
+ return core.sync(path39, options || {});
9419
9419
  } catch (er) {
9420
9420
  if (options && options.ignoreErrors || er.code === "EACCES") {
9421
9421
  return false;
@@ -9431,7 +9431,7 @@ var require_isexe = __commonJS({
9431
9431
  var require_which = __commonJS({
9432
9432
  "../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(exports2, module2) {
9433
9433
  var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
9434
- var path38 = require("path");
9434
+ var path39 = require("path");
9435
9435
  var COLON = isWindows ? ";" : ":";
9436
9436
  var isexe = require_isexe();
9437
9437
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -9469,7 +9469,7 @@ var require_which = __commonJS({
9469
9469
  return opt.all && found.length ? resolve3(found) : reject(getNotFoundError(cmd));
9470
9470
  const ppRaw = pathEnv[i];
9471
9471
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
9472
- const pCmd = path38.join(pathPart, cmd);
9472
+ const pCmd = path39.join(pathPart, cmd);
9473
9473
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
9474
9474
  resolve3(subStep(p, i, 0));
9475
9475
  });
@@ -9496,7 +9496,7 @@ var require_which = __commonJS({
9496
9496
  for (let i = 0; i < pathEnv.length; i++) {
9497
9497
  const ppRaw = pathEnv[i];
9498
9498
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
9499
- const pCmd = path38.join(pathPart, cmd);
9499
+ const pCmd = path39.join(pathPart, cmd);
9500
9500
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
9501
9501
  for (let j = 0; j < pathExt.length; j++) {
9502
9502
  const cur = p + pathExt[j];
@@ -9544,7 +9544,7 @@ var require_path_key = __commonJS({
9544
9544
  var require_resolveCommand = __commonJS({
9545
9545
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2, module2) {
9546
9546
  "use strict";
9547
- var path38 = require("path");
9547
+ var path39 = require("path");
9548
9548
  var which = require_which();
9549
9549
  var getPathKey = require_path_key();
9550
9550
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -9562,7 +9562,7 @@ var require_resolveCommand = __commonJS({
9562
9562
  try {
9563
9563
  resolved = which.sync(parsed.command, {
9564
9564
  path: env[getPathKey({ env })],
9565
- pathExt: withoutPathExt ? path38.delimiter : void 0
9565
+ pathExt: withoutPathExt ? path39.delimiter : void 0
9566
9566
  });
9567
9567
  } catch (e) {
9568
9568
  } finally {
@@ -9571,7 +9571,7 @@ var require_resolveCommand = __commonJS({
9571
9571
  }
9572
9572
  }
9573
9573
  if (resolved) {
9574
- resolved = path38.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
9574
+ resolved = path39.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
9575
9575
  }
9576
9576
  return resolved;
9577
9577
  }
@@ -9625,8 +9625,8 @@ var require_shebang_command = __commonJS({
9625
9625
  if (!match) {
9626
9626
  return null;
9627
9627
  }
9628
- const [path38, argument] = match[0].replace(/#! ?/, "").split(" ");
9629
- const binary = path38.split("/").pop();
9628
+ const [path39, argument] = match[0].replace(/#! ?/, "").split(" ");
9629
+ const binary = path39.split("/").pop();
9630
9630
  if (binary === "env") {
9631
9631
  return argument;
9632
9632
  }
@@ -9661,7 +9661,7 @@ var require_readShebang = __commonJS({
9661
9661
  var require_parse2 = __commonJS({
9662
9662
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports2, module2) {
9663
9663
  "use strict";
9664
- var path38 = require("path");
9664
+ var path39 = require("path");
9665
9665
  var resolveCommand = require_resolveCommand();
9666
9666
  var escape2 = require_escape();
9667
9667
  var readShebang = require_readShebang();
@@ -9686,7 +9686,7 @@ var require_parse2 = __commonJS({
9686
9686
  const needsShell = !isExecutableRegExp.test(commandFile);
9687
9687
  if (parsed.options.forceShell || needsShell) {
9688
9688
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
9689
- parsed.command = path38.normalize(parsed.command);
9689
+ parsed.command = path39.normalize(parsed.command);
9690
9690
  parsed.command = escape2.command(parsed.command);
9691
9691
  parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
9692
9692
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
@@ -9848,14 +9848,14 @@ var require_polyfills = __commonJS({
9848
9848
  fs18.fstatSync = statFixSync(fs18.fstatSync);
9849
9849
  fs18.lstatSync = statFixSync(fs18.lstatSync);
9850
9850
  if (fs18.chmod && !fs18.lchmod) {
9851
- fs18.lchmod = function(path38, mode, cb) {
9851
+ fs18.lchmod = function(path39, mode, cb) {
9852
9852
  if (cb) process.nextTick(cb);
9853
9853
  };
9854
9854
  fs18.lchmodSync = function() {
9855
9855
  };
9856
9856
  }
9857
9857
  if (fs18.chown && !fs18.lchown) {
9858
- fs18.lchown = function(path38, uid, gid, cb) {
9858
+ fs18.lchown = function(path39, uid, gid, cb) {
9859
9859
  if (cb) process.nextTick(cb);
9860
9860
  };
9861
9861
  fs18.lchownSync = function() {
@@ -9922,9 +9922,9 @@ var require_polyfills = __commonJS({
9922
9922
  };
9923
9923
  }(fs18.readSync);
9924
9924
  function patchLchmod(fs19) {
9925
- fs19.lchmod = function(path38, mode, callback) {
9925
+ fs19.lchmod = function(path39, mode, callback) {
9926
9926
  fs19.open(
9927
- path38,
9927
+ path39,
9928
9928
  constants2.O_WRONLY | constants2.O_SYMLINK,
9929
9929
  mode,
9930
9930
  function(err, fd) {
@@ -9940,8 +9940,8 @@ var require_polyfills = __commonJS({
9940
9940
  }
9941
9941
  );
9942
9942
  };
9943
- fs19.lchmodSync = function(path38, mode) {
9944
- var fd = fs19.openSync(path38, constants2.O_WRONLY | constants2.O_SYMLINK, mode);
9943
+ fs19.lchmodSync = function(path39, mode) {
9944
+ var fd = fs19.openSync(path39, constants2.O_WRONLY | constants2.O_SYMLINK, mode);
9945
9945
  var threw = true;
9946
9946
  var ret;
9947
9947
  try {
@@ -9962,8 +9962,8 @@ var require_polyfills = __commonJS({
9962
9962
  }
9963
9963
  function patchLutimes(fs19) {
9964
9964
  if (constants2.hasOwnProperty("O_SYMLINK") && fs19.futimes) {
9965
- fs19.lutimes = function(path38, at, mt, cb) {
9966
- fs19.open(path38, constants2.O_SYMLINK, function(er, fd) {
9965
+ fs19.lutimes = function(path39, at, mt, cb) {
9966
+ fs19.open(path39, constants2.O_SYMLINK, function(er, fd) {
9967
9967
  if (er) {
9968
9968
  if (cb) cb(er);
9969
9969
  return;
@@ -9975,8 +9975,8 @@ var require_polyfills = __commonJS({
9975
9975
  });
9976
9976
  });
9977
9977
  };
9978
- fs19.lutimesSync = function(path38, at, mt) {
9979
- var fd = fs19.openSync(path38, constants2.O_SYMLINK);
9978
+ fs19.lutimesSync = function(path39, at, mt) {
9979
+ var fd = fs19.openSync(path39, constants2.O_SYMLINK);
9980
9980
  var ret;
9981
9981
  var threw = true;
9982
9982
  try {
@@ -10094,11 +10094,11 @@ var require_legacy_streams = __commonJS({
10094
10094
  ReadStream,
10095
10095
  WriteStream
10096
10096
  };
10097
- function ReadStream(path38, options) {
10098
- if (!(this instanceof ReadStream)) return new ReadStream(path38, options);
10097
+ function ReadStream(path39, options) {
10098
+ if (!(this instanceof ReadStream)) return new ReadStream(path39, options);
10099
10099
  Stream.call(this);
10100
10100
  var self = this;
10101
- this.path = path38;
10101
+ this.path = path39;
10102
10102
  this.fd = null;
10103
10103
  this.readable = true;
10104
10104
  this.paused = false;
@@ -10143,10 +10143,10 @@ var require_legacy_streams = __commonJS({
10143
10143
  self._read();
10144
10144
  });
10145
10145
  }
10146
- function WriteStream(path38, options) {
10147
- if (!(this instanceof WriteStream)) return new WriteStream(path38, options);
10146
+ function WriteStream(path39, options) {
10147
+ if (!(this instanceof WriteStream)) return new WriteStream(path39, options);
10148
10148
  Stream.call(this);
10149
- this.path = path38;
10149
+ this.path = path39;
10150
10150
  this.fd = null;
10151
10151
  this.writable = true;
10152
10152
  this.flags = "w";
@@ -10257,14 +10257,14 @@ var require_graceful_fs = __commonJS({
10257
10257
  return close;
10258
10258
  }(fs18.close);
10259
10259
  fs18.closeSync = function(fs$closeSync) {
10260
- function closeSync2(fd) {
10260
+ function closeSync3(fd) {
10261
10261
  fs$closeSync.apply(fs18, arguments);
10262
10262
  resetQueue();
10263
10263
  }
10264
- Object.defineProperty(closeSync2, previousSymbol, {
10264
+ Object.defineProperty(closeSync3, previousSymbol, {
10265
10265
  value: fs$closeSync
10266
10266
  });
10267
- return closeSync2;
10267
+ return closeSync3;
10268
10268
  }(fs18.closeSync);
10269
10269
  if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
10270
10270
  process.on("exit", function() {
@@ -10289,14 +10289,14 @@ var require_graceful_fs = __commonJS({
10289
10289
  fs19.createWriteStream = createWriteStream;
10290
10290
  var fs$readFile = fs19.readFile;
10291
10291
  fs19.readFile = readFile10;
10292
- function readFile10(path38, options, cb) {
10292
+ function readFile10(path39, options, cb) {
10293
10293
  if (typeof options === "function")
10294
10294
  cb = options, options = null;
10295
- return go$readFile(path38, options, cb);
10296
- function go$readFile(path39, options2, cb2, startTime) {
10297
- return fs$readFile(path39, options2, function(err) {
10295
+ return go$readFile(path39, options, cb);
10296
+ function go$readFile(path40, options2, cb2, startTime) {
10297
+ return fs$readFile(path40, options2, function(err) {
10298
10298
  if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
10299
- enqueue([go$readFile, [path39, options2, cb2], err, startTime || Date.now(), Date.now()]);
10299
+ enqueue([go$readFile, [path40, options2, cb2], err, startTime || Date.now(), Date.now()]);
10300
10300
  else {
10301
10301
  if (typeof cb2 === "function")
10302
10302
  cb2.apply(this, arguments);
@@ -10306,14 +10306,14 @@ var require_graceful_fs = __commonJS({
10306
10306
  }
10307
10307
  var fs$writeFile = fs19.writeFile;
10308
10308
  fs19.writeFile = writeFile5;
10309
- function writeFile5(path38, data, options, cb) {
10309
+ function writeFile5(path39, data, options, cb) {
10310
10310
  if (typeof options === "function")
10311
10311
  cb = options, options = null;
10312
- return go$writeFile(path38, data, options, cb);
10313
- function go$writeFile(path39, data2, options2, cb2, startTime) {
10314
- return fs$writeFile(path39, data2, options2, function(err) {
10312
+ return go$writeFile(path39, data, options, cb);
10313
+ function go$writeFile(path40, data2, options2, cb2, startTime) {
10314
+ return fs$writeFile(path40, data2, options2, function(err) {
10315
10315
  if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
10316
- enqueue([go$writeFile, [path39, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
10316
+ enqueue([go$writeFile, [path40, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
10317
10317
  else {
10318
10318
  if (typeof cb2 === "function")
10319
10319
  cb2.apply(this, arguments);
@@ -10324,14 +10324,14 @@ var require_graceful_fs = __commonJS({
10324
10324
  var fs$appendFile = fs19.appendFile;
10325
10325
  if (fs$appendFile)
10326
10326
  fs19.appendFile = appendFile2;
10327
- function appendFile2(path38, data, options, cb) {
10327
+ function appendFile2(path39, data, options, cb) {
10328
10328
  if (typeof options === "function")
10329
10329
  cb = options, options = null;
10330
- return go$appendFile(path38, data, options, cb);
10331
- function go$appendFile(path39, data2, options2, cb2, startTime) {
10332
- return fs$appendFile(path39, data2, options2, function(err) {
10330
+ return go$appendFile(path39, data, options, cb);
10331
+ function go$appendFile(path40, data2, options2, cb2, startTime) {
10332
+ return fs$appendFile(path40, data2, options2, function(err) {
10333
10333
  if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
10334
- enqueue([go$appendFile, [path39, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
10334
+ enqueue([go$appendFile, [path40, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
10335
10335
  else {
10336
10336
  if (typeof cb2 === "function")
10337
10337
  cb2.apply(this, arguments);
@@ -10362,31 +10362,31 @@ var require_graceful_fs = __commonJS({
10362
10362
  var fs$readdir = fs19.readdir;
10363
10363
  fs19.readdir = readdir5;
10364
10364
  var noReaddirOptionVersions = /^v[0-5]\./;
10365
- function readdir5(path38, options, cb) {
10365
+ function readdir5(path39, options, cb) {
10366
10366
  if (typeof options === "function")
10367
10367
  cb = options, options = null;
10368
- var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path39, options2, cb2, startTime) {
10369
- return fs$readdir(path39, fs$readdirCallback(
10370
- path39,
10368
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path40, options2, cb2, startTime) {
10369
+ return fs$readdir(path40, fs$readdirCallback(
10370
+ path40,
10371
10371
  options2,
10372
10372
  cb2,
10373
10373
  startTime
10374
10374
  ));
10375
- } : function go$readdir2(path39, options2, cb2, startTime) {
10376
- return fs$readdir(path39, options2, fs$readdirCallback(
10377
- path39,
10375
+ } : function go$readdir2(path40, options2, cb2, startTime) {
10376
+ return fs$readdir(path40, options2, fs$readdirCallback(
10377
+ path40,
10378
10378
  options2,
10379
10379
  cb2,
10380
10380
  startTime
10381
10381
  ));
10382
10382
  };
10383
- return go$readdir(path38, options, cb);
10384
- function fs$readdirCallback(path39, options2, cb2, startTime) {
10383
+ return go$readdir(path39, options, cb);
10384
+ function fs$readdirCallback(path40, options2, cb2, startTime) {
10385
10385
  return function(err, files) {
10386
10386
  if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
10387
10387
  enqueue([
10388
10388
  go$readdir,
10389
- [path39, options2, cb2],
10389
+ [path40, options2, cb2],
10390
10390
  err,
10391
10391
  startTime || Date.now(),
10392
10392
  Date.now()
@@ -10457,7 +10457,7 @@ var require_graceful_fs = __commonJS({
10457
10457
  enumerable: true,
10458
10458
  configurable: true
10459
10459
  });
10460
- function ReadStream(path38, options) {
10460
+ function ReadStream(path39, options) {
10461
10461
  if (this instanceof ReadStream)
10462
10462
  return fs$ReadStream.apply(this, arguments), this;
10463
10463
  else
@@ -10477,7 +10477,7 @@ var require_graceful_fs = __commonJS({
10477
10477
  }
10478
10478
  });
10479
10479
  }
10480
- function WriteStream(path38, options) {
10480
+ function WriteStream(path39, options) {
10481
10481
  if (this instanceof WriteStream)
10482
10482
  return fs$WriteStream.apply(this, arguments), this;
10483
10483
  else
@@ -10495,22 +10495,22 @@ var require_graceful_fs = __commonJS({
10495
10495
  }
10496
10496
  });
10497
10497
  }
10498
- function createReadStream2(path38, options) {
10499
- return new fs19.ReadStream(path38, options);
10498
+ function createReadStream2(path39, options) {
10499
+ return new fs19.ReadStream(path39, options);
10500
10500
  }
10501
- function createWriteStream(path38, options) {
10502
- return new fs19.WriteStream(path38, options);
10501
+ function createWriteStream(path39, options) {
10502
+ return new fs19.WriteStream(path39, options);
10503
10503
  }
10504
10504
  var fs$open = fs19.open;
10505
10505
  fs19.open = open;
10506
- function open(path38, flags, mode, cb) {
10506
+ function open(path39, flags, mode, cb) {
10507
10507
  if (typeof mode === "function")
10508
10508
  cb = mode, mode = null;
10509
- return go$open(path38, flags, mode, cb);
10510
- function go$open(path39, flags2, mode2, cb2, startTime) {
10511
- return fs$open(path39, flags2, mode2, function(err, fd) {
10509
+ return go$open(path39, flags, mode, cb);
10510
+ function go$open(path40, flags2, mode2, cb2, startTime) {
10511
+ return fs$open(path40, flags2, mode2, function(err, fd) {
10512
10512
  if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
10513
- enqueue([go$open, [path39, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
10513
+ enqueue([go$open, [path40, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
10514
10514
  else {
10515
10515
  if (typeof cb2 === "function")
10516
10516
  cb2.apply(this, arguments);
@@ -11039,7 +11039,7 @@ var require_mtime_precision = __commonJS({
11039
11039
  var require_lockfile = __commonJS({
11040
11040
  "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js"(exports2, module2) {
11041
11041
  "use strict";
11042
- var path38 = require("path");
11042
+ var path39 = require("path");
11043
11043
  var fs18 = require_graceful_fs();
11044
11044
  var retry = require_retry2();
11045
11045
  var onExit = require_signal_exit();
@@ -11050,7 +11050,7 @@ var require_lockfile = __commonJS({
11050
11050
  }
11051
11051
  function resolveCanonicalPath(file2, options, callback) {
11052
11052
  if (!options.realpath) {
11053
- return callback(null, path38.resolve(file2));
11053
+ return callback(null, path39.resolve(file2));
11054
11054
  }
11055
11055
  options.fs.realpath(file2, callback);
11056
11056
  }
@@ -17043,9 +17043,9 @@ async function pathExists5(target) {
17043
17043
  }
17044
17044
  }
17045
17045
  async function writeAtomic(targetPath, content) {
17046
- const dir = import_node_path40.default.dirname(targetPath);
17046
+ const dir = import_node_path41.default.dirname(targetPath);
17047
17047
  await import_promises17.default.mkdir(dir, { recursive: true, mode: 448 });
17048
- const tempPath = import_node_path40.default.join(dir, `.tmp.${import_node_path40.default.basename(targetPath)}.${Date.now()}`);
17048
+ const tempPath = import_node_path41.default.join(dir, `.tmp.${import_node_path41.default.basename(targetPath)}.${Date.now()}`);
17049
17049
  await import_promises17.default.writeFile(tempPath, content, { mode: 384 });
17050
17050
  await import_promises17.default.rename(tempPath, targetPath);
17051
17051
  }
@@ -17085,9 +17085,9 @@ ${newBlock}
17085
17085
  function getDefaultNativePaths() {
17086
17086
  const homeDir = import_node_os19.default.homedir();
17087
17087
  return {
17088
- claude: import_node_path40.default.join(homeDir, ".claude.json"),
17089
- codex: import_node_path40.default.join(homeDir, ".codex", "config.toml"),
17090
- gemini: import_node_path40.default.join(homeDir, ".gemini", "antigravity", "mcp_config.json")
17088
+ claude: import_node_path41.default.join(homeDir, ".claude.json"),
17089
+ codex: import_node_path41.default.join(homeDir, ".codex", "config.toml"),
17090
+ gemini: import_node_path41.default.join(homeDir, ".gemini", "antigravity", "mcp_config.json")
17091
17091
  };
17092
17092
  }
17093
17093
  async function writeServerToClaudeJson(filePath, serverId, expected, options = {}) {
@@ -17285,13 +17285,13 @@ async function installPublicMcpServerToConfigs(serverId, expected, options = {})
17285
17285
  results
17286
17286
  };
17287
17287
  }
17288
- var import_promises17, import_node_os19, import_node_path40, toml4;
17288
+ var import_promises17, import_node_os19, import_node_path41, toml4;
17289
17289
  var init_install_public_mcp = __esm({
17290
17290
  "src/install-public-mcp.ts"() {
17291
17291
  "use strict";
17292
17292
  import_promises17 = __toESM(require("node:fs/promises"), 1);
17293
17293
  import_node_os19 = __toESM(require("node:os"), 1);
17294
- import_node_path40 = __toESM(require("node:path"), 1);
17294
+ import_node_path41 = __toESM(require("node:path"), 1);
17295
17295
  toml4 = __toESM(require_toml(), 1);
17296
17296
  }
17297
17297
  });
@@ -18837,10 +18837,10 @@ var require_segments = __commonJS({
18837
18837
  const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled());
18838
18838
  const nodes = buildNodes(segs);
18839
18839
  const graph = buildGraph(nodes, version2);
18840
- const path38 = dijkstra.find_path(graph.map, "start", "end");
18840
+ const path39 = dijkstra.find_path(graph.map, "start", "end");
18841
18841
  const optimizedSegs = [];
18842
- for (let i = 1; i < path38.length - 1; i++) {
18843
- optimizedSegs.push(graph.table[path38[i]].node);
18842
+ for (let i = 1; i < path39.length - 1; i++) {
18843
+ optimizedSegs.push(graph.table[path39[i]].node);
18844
18844
  }
18845
18845
  return exports2.fromArray(mergeSegments(optimizedSegs));
18846
18846
  };
@@ -21317,7 +21317,7 @@ var require_png2 = __commonJS({
21317
21317
  });
21318
21318
  png.pack();
21319
21319
  };
21320
- exports2.renderToFile = function renderToFile(path38, qrData, options, cb) {
21320
+ exports2.renderToFile = function renderToFile(path39, qrData, options, cb) {
21321
21321
  if (typeof cb === "undefined") {
21322
21322
  cb = options;
21323
21323
  options = void 0;
@@ -21328,7 +21328,7 @@ var require_png2 = __commonJS({
21328
21328
  called = true;
21329
21329
  cb.apply(null, args);
21330
21330
  };
21331
- const stream = fs18.createWriteStream(path38);
21331
+ const stream = fs18.createWriteStream(path39);
21332
21332
  stream.on("error", done);
21333
21333
  stream.on("close", done);
21334
21334
  exports2.renderToFileStream(stream, qrData, options);
@@ -21390,14 +21390,14 @@ var require_utf8 = __commonJS({
21390
21390
  }
21391
21391
  return output3;
21392
21392
  };
21393
- exports2.renderToFile = function renderToFile(path38, qrData, options, cb) {
21393
+ exports2.renderToFile = function renderToFile(path39, qrData, options, cb) {
21394
21394
  if (typeof cb === "undefined") {
21395
21395
  cb = options;
21396
21396
  options = void 0;
21397
21397
  }
21398
21398
  const fs18 = require("fs");
21399
21399
  const utf8 = exports2.render(qrData, options);
21400
- fs18.writeFile(path38, utf8, cb);
21400
+ fs18.writeFile(path39, utf8, cb);
21401
21401
  };
21402
21402
  }
21403
21403
  });
@@ -21518,7 +21518,7 @@ var require_svg_tag = __commonJS({
21518
21518
  return str;
21519
21519
  }
21520
21520
  function qrToPath(data, size, margin) {
21521
- let path38 = "";
21521
+ let path39 = "";
21522
21522
  let moveBy = 0;
21523
21523
  let newRow = false;
21524
21524
  let lineLength = 0;
@@ -21529,19 +21529,19 @@ var require_svg_tag = __commonJS({
21529
21529
  if (data[i]) {
21530
21530
  lineLength++;
21531
21531
  if (!(i > 0 && col > 0 && data[i - 1])) {
21532
- path38 += newRow ? svgCmd("M", col + margin, 0.5 + row + margin) : svgCmd("m", moveBy, 0);
21532
+ path39 += newRow ? svgCmd("M", col + margin, 0.5 + row + margin) : svgCmd("m", moveBy, 0);
21533
21533
  moveBy = 0;
21534
21534
  newRow = false;
21535
21535
  }
21536
21536
  if (!(col + 1 < size && data[i + 1])) {
21537
- path38 += svgCmd("h", lineLength);
21537
+ path39 += svgCmd("h", lineLength);
21538
21538
  lineLength = 0;
21539
21539
  }
21540
21540
  } else {
21541
21541
  moveBy++;
21542
21542
  }
21543
21543
  }
21544
- return path38;
21544
+ return path39;
21545
21545
  }
21546
21546
  exports2.render = function render(qrData, options, cb) {
21547
21547
  const opts = Utils.getOptions(options);
@@ -21549,10 +21549,10 @@ var require_svg_tag = __commonJS({
21549
21549
  const data = qrData.modules.data;
21550
21550
  const qrcodesize = size + opts.margin * 2;
21551
21551
  const bg = !opts.color.light.a ? "" : "<path " + getColorAttrib(opts.color.light, "fill") + ' d="M0 0h' + qrcodesize + "v" + qrcodesize + 'H0z"/>';
21552
- const path38 = "<path " + getColorAttrib(opts.color.dark, "stroke") + ' d="' + qrToPath(data, size, opts.margin) + '"/>';
21552
+ const path39 = "<path " + getColorAttrib(opts.color.dark, "stroke") + ' d="' + qrToPath(data, size, opts.margin) + '"/>';
21553
21553
  const viewBox = 'viewBox="0 0 ' + qrcodesize + " " + qrcodesize + '"';
21554
21554
  const width = !opts.width ? "" : 'width="' + opts.width + '" height="' + opts.width + '" ';
21555
- const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path38 + "</svg>\n";
21555
+ const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path39 + "</svg>\n";
21556
21556
  if (typeof cb === "function") {
21557
21557
  cb(null, svgTag);
21558
21558
  }
@@ -21566,7 +21566,7 @@ var require_svg = __commonJS({
21566
21566
  "../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/renderer/svg.js"(exports2) {
21567
21567
  var svgTagRenderer = require_svg_tag();
21568
21568
  exports2.render = svgTagRenderer.render;
21569
- exports2.renderToFile = function renderToFile(path38, qrData, options, cb) {
21569
+ exports2.renderToFile = function renderToFile(path39, qrData, options, cb) {
21570
21570
  if (typeof cb === "undefined") {
21571
21571
  cb = options;
21572
21572
  options = void 0;
@@ -21574,7 +21574,7 @@ var require_svg = __commonJS({
21574
21574
  const fs18 = require("fs");
21575
21575
  const svgTag = exports2.render(qrData, options);
21576
21576
  const xmlStr = '<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' + svgTag;
21577
- fs18.writeFile(path38, xmlStr, cb);
21577
+ fs18.writeFile(path39, xmlStr, cb);
21578
21578
  };
21579
21579
  }
21580
21580
  });
@@ -21732,8 +21732,8 @@ var require_server = __commonJS({
21732
21732
  cb
21733
21733
  };
21734
21734
  }
21735
- function getTypeFromFilename(path38) {
21736
- return path38.slice((path38.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
21735
+ function getTypeFromFilename(path39) {
21736
+ return path39.slice((path39.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
21737
21737
  }
21738
21738
  function getRendererFromType(type) {
21739
21739
  switch (type) {
@@ -21797,17 +21797,17 @@ var require_server = __commonJS({
21797
21797
  const renderer = getRendererFromType(params.opts.type);
21798
21798
  return render(renderer.renderToBuffer, text, params);
21799
21799
  };
21800
- exports2.toFile = function toFile(path38, text, opts, cb) {
21801
- if (typeof path38 !== "string" || !(typeof text === "string" || typeof text === "object")) {
21800
+ exports2.toFile = function toFile(path39, text, opts, cb) {
21801
+ if (typeof path39 !== "string" || !(typeof text === "string" || typeof text === "object")) {
21802
21802
  throw new Error("Invalid argument");
21803
21803
  }
21804
21804
  if (arguments.length < 3 && !canPromise()) {
21805
21805
  throw new Error("Too few arguments provided");
21806
21806
  }
21807
21807
  const params = checkParams(text, opts, cb);
21808
- const type = params.opts.type || getTypeFromFilename(path38);
21808
+ const type = params.opts.type || getTypeFromFilename(path39);
21809
21809
  const renderer = getRendererFromType(type);
21810
- const renderToFile = renderer.renderToFile.bind(null, path38);
21810
+ const renderToFile = renderer.renderToFile.bind(null, path39);
21811
21811
  return render(renderToFile, text, params);
21812
21812
  };
21813
21813
  exports2.toFileStream = function toFileStream(stream, text, opts) {
@@ -21835,11 +21835,11 @@ __export(bin_exports, {
21835
21835
  augmentProcessPathWithCommonDirs: () => augmentProcessPathWithCommonDirs
21836
21836
  });
21837
21837
  module.exports = __toCommonJS(bin_exports);
21838
- var import_node_path52 = __toESM(require("node:path"), 1);
21838
+ var import_node_path53 = __toESM(require("node:path"), 1);
21839
21839
  var import_node_child_process27 = require("node:child_process");
21840
- var import_node_fs35 = require("node:fs");
21840
+ var import_node_fs36 = require("node:fs");
21841
21841
  var import_node_os26 = require("node:os");
21842
- var import_node_path53 = __toESM(require("node:path"), 1);
21842
+ var import_node_path54 = __toESM(require("node:path"), 1);
21843
21843
 
21844
21844
  // src/install-codex.ts
21845
21845
  var import_promises = __toESM(require("node:fs/promises"), 1);
@@ -22967,12 +22967,12 @@ async function installClaude(options) {
22967
22967
  // src/install-agy.ts
22968
22968
  var import_promises11 = __toESM(require("node:fs/promises"), 1);
22969
22969
  var import_node_os14 = __toESM(require("node:os"), 1);
22970
- var import_node_path26 = __toESM(require("node:path"), 1);
22970
+ var import_node_path27 = __toESM(require("node:path"), 1);
22971
22971
 
22972
22972
  // src/tools.ts
22973
- var import_node_crypto18 = require("node:crypto");
22973
+ var import_node_crypto19 = require("node:crypto");
22974
22974
  var import_promises10 = require("node:fs/promises");
22975
- var import_node_path25 = __toESM(require("node:path"), 1);
22975
+ var import_node_path26 = __toESM(require("node:path"), 1);
22976
22976
  var import_node_os13 = __toESM(require("node:os"), 1);
22977
22977
 
22978
22978
  // ../../packages/schemas/dist/canonical-json.js
@@ -23753,10 +23753,10 @@ function mergeDefs(...defs) {
23753
23753
  function cloneDef(schema) {
23754
23754
  return mergeDefs(schema._zod.def);
23755
23755
  }
23756
- function getElementAtPath(obj, path38) {
23757
- if (!path38)
23756
+ function getElementAtPath(obj, path39) {
23757
+ if (!path39)
23758
23758
  return obj;
23759
- return path38.reduce((acc, key) => acc?.[key], obj);
23759
+ return path39.reduce((acc, key) => acc?.[key], obj);
23760
23760
  }
23761
23761
  function promiseAllObject(promisesObj) {
23762
23762
  const keys = Object.keys(promisesObj);
@@ -24165,11 +24165,11 @@ function explicitlyAborted(x, startIndex = 0) {
24165
24165
  }
24166
24166
  return false;
24167
24167
  }
24168
- function prefixIssues(path38, issues) {
24168
+ function prefixIssues(path39, issues) {
24169
24169
  return issues.map((iss) => {
24170
24170
  var _a3;
24171
24171
  (_a3 = iss).path ?? (_a3.path = []);
24172
- iss.path.unshift(path38);
24172
+ iss.path.unshift(path39);
24173
24173
  return iss;
24174
24174
  });
24175
24175
  }
@@ -24316,16 +24316,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
24316
24316
  }
24317
24317
  function formatError(error51, mapper = (issue2) => issue2.message) {
24318
24318
  const fieldErrors = { _errors: [] };
24319
- const processError = (error52, path38 = []) => {
24319
+ const processError = (error52, path39 = []) => {
24320
24320
  for (const issue2 of error52.issues) {
24321
24321
  if (issue2.code === "invalid_union" && issue2.errors.length) {
24322
- issue2.errors.map((issues) => processError({ issues }, [...path38, ...issue2.path]));
24322
+ issue2.errors.map((issues) => processError({ issues }, [...path39, ...issue2.path]));
24323
24323
  } else if (issue2.code === "invalid_key") {
24324
- processError({ issues: issue2.issues }, [...path38, ...issue2.path]);
24324
+ processError({ issues: issue2.issues }, [...path39, ...issue2.path]);
24325
24325
  } else if (issue2.code === "invalid_element") {
24326
- processError({ issues: issue2.issues }, [...path38, ...issue2.path]);
24326
+ processError({ issues: issue2.issues }, [...path39, ...issue2.path]);
24327
24327
  } else {
24328
- const fullpath = [...path38, ...issue2.path];
24328
+ const fullpath = [...path39, ...issue2.path];
24329
24329
  if (fullpath.length === 0) {
24330
24330
  fieldErrors._errors.push(mapper(issue2));
24331
24331
  } else {
@@ -24352,17 +24352,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
24352
24352
  }
24353
24353
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
24354
24354
  const result = { errors: [] };
24355
- const processError = (error52, path38 = []) => {
24355
+ const processError = (error52, path39 = []) => {
24356
24356
  var _a3, _b;
24357
24357
  for (const issue2 of error52.issues) {
24358
24358
  if (issue2.code === "invalid_union" && issue2.errors.length) {
24359
- issue2.errors.map((issues) => processError({ issues }, [...path38, ...issue2.path]));
24359
+ issue2.errors.map((issues) => processError({ issues }, [...path39, ...issue2.path]));
24360
24360
  } else if (issue2.code === "invalid_key") {
24361
- processError({ issues: issue2.issues }, [...path38, ...issue2.path]);
24361
+ processError({ issues: issue2.issues }, [...path39, ...issue2.path]);
24362
24362
  } else if (issue2.code === "invalid_element") {
24363
- processError({ issues: issue2.issues }, [...path38, ...issue2.path]);
24363
+ processError({ issues: issue2.issues }, [...path39, ...issue2.path]);
24364
24364
  } else {
24365
- const fullpath = [...path38, ...issue2.path];
24365
+ const fullpath = [...path39, ...issue2.path];
24366
24366
  if (fullpath.length === 0) {
24367
24367
  result.errors.push(mapper(issue2));
24368
24368
  continue;
@@ -24394,8 +24394,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
24394
24394
  }
24395
24395
  function toDotPath(_path) {
24396
24396
  const segs = [];
24397
- const path38 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
24398
- for (const seg of path38) {
24397
+ const path39 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
24398
+ for (const seg of path39) {
24399
24399
  if (typeof seg === "number")
24400
24400
  segs.push(`[${seg}]`);
24401
24401
  else if (typeof seg === "symbol")
@@ -37087,13 +37087,13 @@ function resolveRef(ref, ctx) {
37087
37087
  if (!ref.startsWith("#")) {
37088
37088
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
37089
37089
  }
37090
- const path38 = ref.slice(1).split("/").filter(Boolean);
37091
- if (path38.length === 0) {
37090
+ const path39 = ref.slice(1).split("/").filter(Boolean);
37091
+ if (path39.length === 0) {
37092
37092
  return ctx.rootSchema;
37093
37093
  }
37094
37094
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
37095
- if (path38[0] === defsKey) {
37096
- const key = path38[1];
37095
+ if (path39[0] === defsKey) {
37096
+ const key = path39[1];
37097
37097
  if (!key || !ctx.defs[key]) {
37098
37098
  throw new Error(`Reference not found: ${ref}`);
37099
37099
  }
@@ -37792,6 +37792,10 @@ var openApiOperationIds = {
37792
37792
  getCapabilityPermit: "getCapabilityPermit",
37793
37793
  getCapabilityInvocation: "getCapabilityInvocation",
37794
37794
  reconcilePendingCapabilityInvocations: "reconcilePendingCapabilityInvocations",
37795
+ issueLocalGitSettlement: "issueLocalGitSettlement",
37796
+ getLocalGitSettlement: "getLocalGitSettlement",
37797
+ acknowledgeLocalGitLanding: "acknowledgeLocalGitLanding",
37798
+ listPendingLocalGitLandings: "listPendingLocalGitLandings",
37795
37799
  mintIntegrationSetupTicket: "mintIntegrationSetupTicket",
37796
37800
  redeemIntegrationSetupTicket: "redeemIntegrationSetupTicket",
37797
37801
  registerBridgeInstallation: "registerBridgeInstallation",
@@ -37843,6 +37847,7 @@ var operatorSessionSchema = external_exports.object({
37843
37847
  // Default 'project' for backward-compat: tokens minted before this field existed parse
37844
37848
  // cleanly into the project branch of the middleware (which mirrors today's behavior).
37845
37849
  scope: external_exports.enum(["project", "operator"]).default("project"),
37850
+ agentCredentialId: external_exports.string().uuid().optional(),
37846
37851
  accountId: external_exports.string().uuid().optional(),
37847
37852
  identitySubject: external_exports.string().min(1).optional(),
37848
37853
  githubId: external_exports.union([external_exports.number().int(), external_exports.string().min(1)]).optional(),
@@ -38863,6 +38868,188 @@ var manualTaskClosureRequestSchema = external_exports.object({
38863
38868
  outcome: external_exports.enum(["completed", "negative_result", "wont_do"]),
38864
38869
  reason: external_exports.string().optional()
38865
38870
  });
38871
+ var gitOidSha1Schema = external_exports.string().regex(/^[0-9a-f]{40}$/, "Invalid SHA-1 Git OID (must be 40 lowercase hex characters)");
38872
+ var gitOidSha256Schema = external_exports.string().regex(/^[0-9a-f]{64}$/, "Invalid SHA-256 Git OID (must be 64 lowercase hex characters)");
38873
+ var gitOidSchema = external_exports.string().regex(/^[0-9a-f]{40}$|^[0-9a-f]{64}$/, "Invalid Git OID (must be 40 or 64 lowercase hex characters)");
38874
+ var gitRefSchema = external_exports.string().regex(/^refs\/[a-zA-Z0-9_./-]+$/, "Must be a fully-qualified git ref (refs/...)");
38875
+ var issueLocalGitSettlementRequestSchema = external_exports.object({
38876
+ leaseId: external_exports.string().min(1),
38877
+ evidence: external_exports.object({
38878
+ artifactId: external_exports.string().min(1)
38879
+ }).strict()
38880
+ }).strict();
38881
+ var localGitSettlementLandingStateSchema = external_exports.enum(["receipt_issued", "landing_applied"]);
38882
+ var localGitSettlementLandingReceiptIssuedSchema = external_exports.object({
38883
+ receiptId: external_exports.string().uuid(),
38884
+ state: external_exports.literal("receipt_issued"),
38885
+ appliedAt: external_exports.null(),
38886
+ evidenceSource: external_exports.literal("client_reported")
38887
+ }).passthrough();
38888
+ var localGitSettlementLandingAppliedSchema = external_exports.object({
38889
+ receiptId: external_exports.string().uuid(),
38890
+ state: external_exports.literal("landing_applied"),
38891
+ appliedAt: external_exports.string().min(1),
38892
+ evidenceSource: external_exports.literal("client_reported")
38893
+ }).passthrough();
38894
+ var localGitSettlementLandingSchema = external_exports.discriminatedUnion("state", [
38895
+ localGitSettlementLandingReceiptIssuedSchema,
38896
+ localGitSettlementLandingAppliedSchema
38897
+ ]);
38898
+ var gitSha1BindingSchema = external_exports.object({
38899
+ object_format: external_exports.literal("sha1"),
38900
+ source_base_oid: gitOidSha1Schema,
38901
+ base_oid: gitOidSha1Schema,
38902
+ head_oid: gitOidSha1Schema,
38903
+ target_ref: gitRefSchema,
38904
+ run_ref: gitRefSchema,
38905
+ checkout_digest: external_exports.string().min(1)
38906
+ }).passthrough();
38907
+ var gitSha256BindingSchema = external_exports.object({
38908
+ object_format: external_exports.literal("sha256"),
38909
+ source_base_oid: gitOidSha256Schema,
38910
+ base_oid: gitOidSha256Schema,
38911
+ head_oid: gitOidSha256Schema,
38912
+ target_ref: gitRefSchema,
38913
+ run_ref: gitRefSchema,
38914
+ checkout_digest: external_exports.string().min(1)
38915
+ }).passthrough();
38916
+ var gitBindingSchema = external_exports.discriminatedUnion("object_format", [
38917
+ gitSha1BindingSchema,
38918
+ gitSha256BindingSchema
38919
+ ]);
38920
+ var localGitSettlementPayloadV2Schema = external_exports.object({
38921
+ type: external_exports.literal("mrrlin.local_git_settlement"),
38922
+ version: external_exports.literal(2),
38923
+ candidate_id: external_exports.string().uuid(),
38924
+ project_slug: external_exports.string().min(1),
38925
+ task_id: external_exports.string().min(1),
38926
+ run_id: external_exports.string().min(1),
38927
+ closure_generation: external_exports.number().int().positive(),
38928
+ outcome: external_exports.literal("completed"),
38929
+ nonce: external_exports.string().min(1),
38930
+ signing_key_id: external_exports.string().min(1),
38931
+ server_attested: external_exports.object({
38932
+ owner_login: external_exports.string().min(1),
38933
+ owner_credential_id: external_exports.string().min(1),
38934
+ lease_id: external_exports.string().min(1),
38935
+ prepared_at: external_exports.string(),
38936
+ canonical_request_digest: external_exports.string(),
38937
+ artifact_set_digest: external_exports.string(),
38938
+ declared_outcome_digest: external_exports.string(),
38939
+ artifacts: external_exports.array(external_exports.object({
38940
+ artifact_id: external_exports.string(),
38941
+ storage_version: external_exports.string(),
38942
+ content_hash: external_exports.string(),
38943
+ kind: external_exports.literal("verification")
38944
+ }).passthrough())
38945
+ }).passthrough(),
38946
+ client_reported: external_exports.object({
38947
+ git: gitBindingSchema,
38948
+ local_build_receipt: external_exports.record(external_exports.string(), external_exports.unknown())
38949
+ }).passthrough()
38950
+ }).passthrough();
38951
+ var settlementReceiptV2Schema = external_exports.object({
38952
+ receiptId: external_exports.string().uuid(),
38953
+ candidateId: external_exports.string().uuid(),
38954
+ projectSlug: external_exports.string().min(1),
38955
+ taskId: external_exports.string().min(1),
38956
+ runId: external_exports.string().min(1),
38957
+ closureGeneration: external_exports.number().int().positive(),
38958
+ outcome: external_exports.literal("completed"),
38959
+ signingKeyId: external_exports.string().min(1),
38960
+ signingKeyStatus: signingKeyStatusSchema.optional(),
38961
+ signature: external_exports.string().min(1),
38962
+ canonicalPayload: localGitSettlementPayloadV2Schema,
38963
+ finalizedAt: external_exports.string(),
38964
+ isIdempotent: external_exports.boolean().optional()
38965
+ }).passthrough();
38966
+ var localGitSettlementResponseSchema = external_exports.object({
38967
+ data: external_exports.object({
38968
+ state: localGitSettlementLandingStateSchema,
38969
+ receipt: settlementReceiptV2Schema,
38970
+ signingKey: external_exports.object({
38971
+ keyId: external_exports.string().min(1),
38972
+ publicKey: external_exports.string().min(1),
38973
+ status: signingKeyStatusSchema
38974
+ }).passthrough(),
38975
+ landing: localGitSettlementLandingSchema,
38976
+ isIdempotent: external_exports.boolean()
38977
+ }).passthrough()
38978
+ }).passthrough();
38979
+ var acknowledgeLocalGitLandingRequestSchema = external_exports.object({
38980
+ receiptId: external_exports.string().uuid(),
38981
+ baseOid: gitOidSchema,
38982
+ headOid: gitOidSchema,
38983
+ targetRef: gitRefSchema,
38984
+ checkoutDigest: external_exports.string().min(1)
38985
+ }).strict();
38986
+ var localGitSettlementLookupSchema = external_exports.union([
38987
+ external_exports.object({
38988
+ data: external_exports.object({
38989
+ state: external_exports.enum(["prepared", "expired", "superseded"]),
38990
+ candidateId: external_exports.string().uuid(),
38991
+ expiresAt: external_exports.string()
38992
+ }).passthrough()
38993
+ }).passthrough(),
38994
+ localGitSettlementResponseSchema
38995
+ ]);
38996
+
38997
+ // ../../packages/schemas/dist/receipt-canonical.js
38998
+ function isWellFormedString(str) {
38999
+ if (typeof str.isWellFormed === "function") {
39000
+ return str.isWellFormed();
39001
+ }
39002
+ return !/(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(str);
39003
+ }
39004
+ function canonicalizeJson(value) {
39005
+ if (value === null || typeof value === "boolean") {
39006
+ return JSON.stringify(value);
39007
+ }
39008
+ if (typeof value === "string") {
39009
+ if (!isWellFormedString(value)) {
39010
+ throw new TypeError("canonicalizeJson: string contains lone surrogates");
39011
+ }
39012
+ return JSON.stringify(value);
39013
+ }
39014
+ if (typeof value === "number") {
39015
+ if (!Number.isFinite(value)) {
39016
+ throw new TypeError("canonicalizeJson: non-finite numbers are not permitted");
39017
+ }
39018
+ return JSON.stringify(value);
39019
+ }
39020
+ if (value === void 0) {
39021
+ throw new TypeError("canonicalizeJson: undefined is not permitted at root");
39022
+ }
39023
+ if (Array.isArray(value)) {
39024
+ const items = [];
39025
+ for (let i = 0; i < value.length; i++) {
39026
+ const item = value[i];
39027
+ if (item === void 0 || typeof item === "symbol" || typeof item === "function") {
39028
+ items.push("null");
39029
+ } else {
39030
+ items.push(canonicalizeJson(item));
39031
+ }
39032
+ }
39033
+ return "[" + items.join(",") + "]";
39034
+ }
39035
+ if (typeof value === "object") {
39036
+ const obj = value;
39037
+ const keys = Object.keys(obj).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
39038
+ const entries = [];
39039
+ for (const k of keys) {
39040
+ if (!isWellFormedString(k)) {
39041
+ throw new TypeError("canonicalizeJson: property name contains lone surrogates");
39042
+ }
39043
+ const v = obj[k];
39044
+ if (v === void 0 || typeof v === "symbol" || typeof v === "function") {
39045
+ continue;
39046
+ }
39047
+ entries.push(JSON.stringify(k) + ":" + canonicalizeJson(v));
39048
+ }
39049
+ return "{" + entries.join(",") + "}";
39050
+ }
39051
+ throw new TypeError(`canonicalizeJson: unsupported type ${typeof value}`);
39052
+ }
38866
39053
 
38867
39054
  // ../../packages/schemas/dist/report-auth.js
38868
39055
  var encoder2 = new TextEncoder();
@@ -40006,6 +40193,8 @@ var mrrlinTaskSchema = external_exports.object({
40006
40193
  tags: mrrlinTaskTagsSchema,
40007
40194
  title: external_exports.string().min(1),
40008
40195
  type: mrrlinTaskTypeSchema,
40196
+ closureGeneration: external_exports.number().int().nonnegative().optional(),
40197
+ terminalReceiptId: external_exports.string().nullable().optional(),
40009
40198
  // Maintained by a BEFORE UPDATE trigger (set_tasks_updated_at). Output-optional (not
40010
40199
  // defaulted-required) so hardcoded task fixtures/mocks need no churn; DB rows always carry it.
40011
40200
  // The scheduler's spec-draft re-arm signal compares this against the newest failed draft job.
@@ -41993,7 +42182,7 @@ function createMrrlinClient(config2) {
41993
42182
  }
41994
42183
  });
41995
42184
  }
41996
- async function executeFetch(path38, init) {
42185
+ async function executeFetch(path39, init) {
41997
42186
  const method = (init?.method ?? "GET").toUpperCase();
41998
42187
  const dynamicHeaders = typeof config2.headers === "function" ? await config2.headers() : config2.headers;
41999
42188
  const headers = new Headers(dynamicHeaders ?? {});
@@ -42004,7 +42193,7 @@ function createMrrlinClient(config2) {
42004
42193
  if (token && !headers.has("authorization")) {
42005
42194
  headers.set("authorization", `Bearer ${token}`);
42006
42195
  }
42007
- const url2 = `${baseUrl}${path38}`;
42196
+ const url2 = `${baseUrl}${path39}`;
42008
42197
  const isIdempotent = method === "GET" || method === "HEAD";
42009
42198
  const maxAttempts = isIdempotent ? 3 : 1;
42010
42199
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
@@ -42040,13 +42229,13 @@ function createMrrlinClient(config2) {
42040
42229
  throw err;
42041
42230
  }
42042
42231
  }
42043
- throw new Error(`Failed to execute ${method} ${path38}`);
42232
+ throw new Error(`Failed to execute ${method} ${path39}`);
42044
42233
  }
42045
- async function handleResponseError(response, method, path38) {
42234
+ async function handleResponseError(response, method, path39) {
42046
42235
  const body = await response.text();
42047
42236
  let code = `HTTP_${response.status}`;
42048
42237
  let violations = null;
42049
- let message = `Mrrlin API ${method} ${path38} failed: ${response.status}`;
42238
+ let message = `Mrrlin API ${method} ${path39} failed: ${response.status}`;
42050
42239
  try {
42051
42240
  const parsed = JSON.parse(body);
42052
42241
  const violationsParsed = apiViolationsErrorSchema.safeParse(parsed);
@@ -42066,26 +42255,26 @@ function createMrrlinClient(config2) {
42066
42255
  throw new MrrlinApiError({
42067
42256
  code,
42068
42257
  method,
42069
- path: path38,
42258
+ path: path39,
42070
42259
  responseBody: body,
42071
42260
  status: response.status,
42072
42261
  violations,
42073
42262
  message
42074
42263
  });
42075
42264
  }
42076
- async function request(path38, init) {
42265
+ async function request(path39, init) {
42077
42266
  const method = init?.method ?? "GET";
42078
- const response = await executeFetch(path38, init);
42267
+ const response = await executeFetch(path39, init);
42079
42268
  if (!response.ok) {
42080
- await handleResponseError(response, method, path38);
42269
+ await handleResponseError(response, method, path39);
42081
42270
  }
42082
42271
  return response.json();
42083
42272
  }
42084
- async function requestText(path38, init) {
42273
+ async function requestText(path39, init) {
42085
42274
  const method = init?.method ?? "GET";
42086
- const response = await executeFetch(path38, init);
42275
+ const response = await executeFetch(path39, init);
42087
42276
  if (!response.ok) {
42088
- await handleResponseError(response, method, path38);
42277
+ await handleResponseError(response, method, path39);
42089
42278
  }
42090
42279
  return response.text();
42091
42280
  }
@@ -42256,16 +42445,16 @@ function createMrrlinClient(config2) {
42256
42445
  // rejected against the first, MrrlinTask[]-only overload) -- the `any` here is contained to
42257
42446
  // this one implementation signature; MrrlinClient's declared overloads keep callers precise.
42258
42447
  async listTasks(projectSlug, filters = {}, options) {
42259
- const path38 = buildTaskListPath(projectSlug, filters, options?.view);
42260
- const body = await request(path38, options?.signal ? { signal: options.signal } : void 0);
42448
+ const path39 = buildTaskListPath(projectSlug, filters, options?.view);
42449
+ const body = await request(path39, options?.signal ? { signal: options.signal } : void 0);
42261
42450
  if (options?.view === "summary") {
42262
42451
  return taskSummaryListResponseSchema.parse(body).data;
42263
42452
  }
42264
42453
  return taskListResponseSchema.parse(body).data;
42265
42454
  },
42266
42455
  async listTaskSummaries(projectSlug, filters = {}, options) {
42267
- const path38 = buildTaskListPath(projectSlug, filters, "summary");
42268
- const body = await request(path38, options?.signal ? { signal: options.signal } : void 0);
42456
+ const path39 = buildTaskListPath(projectSlug, filters, "summary");
42457
+ const body = await request(path39, options?.signal ? { signal: options.signal } : void 0);
42269
42458
  return taskSummaryListResponseSchema.parse(body).data;
42270
42459
  },
42271
42460
  async listTaxonomy(projectSlug) {
@@ -42274,7 +42463,7 @@ function createMrrlinClient(config2) {
42274
42463
  },
42275
42464
  async listWikiPages(projectSlug, filters = {}, options) {
42276
42465
  const view = options?.view ?? filters.view;
42277
- const path38 = appendQuery(`${projectPath(projectSlug)}/wiki`, {
42466
+ const path39 = appendQuery(`${projectPath(projectSlug)}/wiki`, {
42278
42467
  folder: filters.folder,
42279
42468
  id: filters.id,
42280
42469
  limit: filters.limit === void 0 ? void 0 : String(filters.limit),
@@ -42282,20 +42471,20 @@ function createMrrlinClient(config2) {
42282
42471
  taskId: filters.taskId,
42283
42472
  view
42284
42473
  });
42285
- const body = await request(path38, options?.signal ? { signal: options.signal } : void 0);
42474
+ const body = await request(path39, options?.signal ? { signal: options.signal } : void 0);
42286
42475
  if (view === "summary") {
42287
42476
  return wikiPageSummaryListResponseSchema.parse(body).data;
42288
42477
  }
42289
42478
  return wikiPageListResponseSchema.parse(body).data;
42290
42479
  },
42291
42480
  async searchWikiPages(projectSlug, query) {
42292
- const path38 = appendQuery(`${projectPath(projectSlug)}/wiki/search`, {
42481
+ const path39 = appendQuery(`${projectPath(projectSlug)}/wiki/search`, {
42293
42482
  folder: query.folder,
42294
42483
  limit: query.limit === void 0 ? void 0 : String(query.limit),
42295
42484
  pathPrefix: query.pathPrefix,
42296
42485
  q: query.q
42297
42486
  });
42298
- const body = await request(path38);
42487
+ const body = await request(path39);
42299
42488
  return wikiPageSearchResponseSchema.parse(body).data;
42300
42489
  },
42301
42490
  async updatePlan(projectSlug, planId, patch) {
@@ -43240,6 +43429,34 @@ function createMrrlinClient(config2) {
43240
43429
  const body = await request("/.well-known/jwks.json");
43241
43430
  return jwksResponseSchema.parse(body);
43242
43431
  },
43432
+ async issueLocalGitSettlement(projectSlug, runId, input, options) {
43433
+ const body = await request(`${projectPath(projectSlug)}/execution-runs/${encodeURIComponent(runId)}/settlement`, {
43434
+ method: "POST",
43435
+ headers: {
43436
+ "content-type": "application/json",
43437
+ "idempotency-key": options.idempotencyKey
43438
+ },
43439
+ body: JSON.stringify(input)
43440
+ });
43441
+ return localGitSettlementResponseSchema.parse(body).data;
43442
+ },
43443
+ async getLocalGitSettlement(projectSlug, runId, idempotencyKey) {
43444
+ const body = await request(`${projectPath(projectSlug)}/execution-runs/${encodeURIComponent(runId)}/settlement?idempotencyKey=${encodeURIComponent(idempotencyKey)}`);
43445
+ return localGitSettlementLookupSchema.parse(body);
43446
+ },
43447
+ async acknowledgeLocalGitLanding(projectSlug, runId, input) {
43448
+ const body = await request(`${projectPath(projectSlug)}/execution-runs/${encodeURIComponent(runId)}/settlement/landing`, {
43449
+ method: "POST",
43450
+ headers: { "content-type": "application/json" },
43451
+ body: JSON.stringify(input)
43452
+ });
43453
+ return localGitSettlementLandingSchema.parse(body.data ?? body);
43454
+ },
43455
+ async listPendingLocalGitLandings(projectSlug, options) {
43456
+ const q = options?.limit ? `?limit=${encodeURIComponent(options.limit)}` : "";
43457
+ const body = await request(`${projectPath(projectSlug)}/settlement/pending-landings${q}`);
43458
+ return body.data ?? body;
43459
+ },
43243
43460
  async issueCapabilityPermit(projectSlug, input) {
43244
43461
  const body = await request(`${projectPath(projectSlug)}/capability-permits`, {
43245
43462
  method: "POST",
@@ -45860,14 +46077,21 @@ var QA_QUESTION_MIN_CHARS = 120;
45860
46077
  function cutHead(text, max) {
45861
46078
  return text.length > max ? `${text.slice(0, Math.max(0, max - 1))}\u2026` : text;
45862
46079
  }
45863
- function cutNoteBody(flat) {
46080
+ function flattenNote(text) {
46081
+ return text.replace(/[\p{Cc}\u2028\u2029]+/gu, " ").replace(/ {2,}/g, " ").trim();
46082
+ }
46083
+ function needsTaskNoteAnswer(body) {
46084
+ const flat = flattenNote(body);
46085
+ return flat.length > NOTE_BODY_MAX_CHARS && flat.startsWith("Q: ") && flat.indexOf(" A: ") !== flat.lastIndexOf(" A: ");
46086
+ }
46087
+ function cutNoteBody(flat, questionAnswer) {
45864
46088
  if (flat.length <= NOTE_BODY_MAX_CHARS)
45865
46089
  return flat;
45866
46090
  const split2 = flat.startsWith("Q: ") ? flat.lastIndexOf(" A: ") : -1;
45867
- if (split2 < 0)
46091
+ if (!questionAnswer && split2 < 0)
45868
46092
  return cutHead(flat, NOTE_BODY_MAX_CHARS);
45869
- const question = flat.slice(3, split2);
45870
- const answer = flat.slice(split2 + 4);
46093
+ const question = questionAnswer ? flattenNote(questionAnswer.question) : flat.slice(3, split2);
46094
+ const answer = questionAnswer ? flattenNote(questionAnswer.answer) : flat.slice(split2 + 4);
45871
46095
  const frame = "Q: A: ".length;
45872
46096
  const answerPart = cutHead(answer, NOTE_BODY_MAX_CHARS - frame - QA_QUESTION_MIN_CHARS);
45873
46097
  const questionPart = cutHead(question, NOTE_BODY_MAX_CHARS - frame - answerPart.length);
@@ -45878,10 +46102,7 @@ function renderTaskNotes(events, heading, maxChars = NOTES_SECTION_MAX_CHARS) {
45878
46102
  const notes = events.filter((e) => e.eventType === "note" && typeof e.body === "string" && e.body.trim() !== "");
45879
46103
  if (notes.length === 0)
45880
46104
  return "";
45881
- const lineOf = (note) => {
45882
- const flat = note.body.replace(/[\p{Cc}\u2028\u2029]+/gu, " ").replace(/ {2,}/g, " ").trim();
45883
- return `- ${note.createdAt}: ${cutNoteBody(flat)}`;
45884
- };
46105
+ const lineOf = (note) => `- ${note.createdAt}: ${cutNoteBody(flattenNote(note.body), note.questionAnswer)}`;
45885
46106
  const reserve = heading.length + 1 + `(+${notes.length} older notes omitted)`.length + 1;
45886
46107
  const keptNewestFirst = [];
45887
46108
  let used = reserve;
@@ -60316,8 +60537,8 @@ async function findSessionDays(stateDir, sessionId) {
60316
60537
  function isRecord5(v) {
60317
60538
  return v !== null && typeof v === "object";
60318
60539
  }
60319
- function resolvePath(root, path38) {
60320
- const parts = path38.split(".");
60540
+ function resolvePath(root, path39) {
60541
+ const parts = path39.split(".");
60321
60542
  let cur = root;
60322
60543
  for (let i = 0; i < parts.length - 1; i += 1) {
60323
60544
  const part = parts[i];
@@ -60385,9 +60606,9 @@ async function gate(artifact, prose, ctx) {
60385
60606
  return { ok: true, gated: true, artifact: withheldExcerptClone(artifact) };
60386
60607
  }
60387
60608
  const maskedClone = typeof structuredClone === "function" ? structuredClone(artifact) : JSON.parse(JSON.stringify(artifact));
60388
- for (const { path: path38, masked } of fields) {
60389
- const target = resolvePath(maskedClone, path38);
60390
- if (!target) throw new Error(`pii-gate: path "${path38}" failed to resolve on the clone after validating on the original`);
60609
+ for (const { path: path39, masked } of fields) {
60610
+ const target = resolvePath(maskedClone, path39);
60611
+ if (!target) throw new Error(`pii-gate: path "${path39}" failed to resolve on the clone after validating on the original`);
60391
60612
  target.parent[target.key] = masked;
60392
60613
  }
60393
60614
  return { ok: true, gated: false, artifact: maskedClone };
@@ -60597,9 +60818,9 @@ var CheckoutRegistry = class {
60597
60818
  get(slug) {
60598
60819
  return this.read()[slug] ?? null;
60599
60820
  }
60600
- confirm(slug, path38, now) {
60821
+ confirm(slug, path39, now) {
60601
60822
  const all = this.read();
60602
- all[slug] = { path: path38, confirmedAt: now };
60823
+ all[slug] = { path: path39, confirmedAt: now };
60603
60824
  (0, import_node_fs10.writeFileSync)(this.file, JSON.stringify(all, null, 2));
60604
60825
  }
60605
60826
  /**
@@ -61016,9 +61237,9 @@ function provisionNewProjectFolder(registry3, projectSlug, machineLabel, options
61016
61237
 
61017
61238
  // src/local-apply.ts
61018
61239
  var import_node_child_process16 = require("node:child_process");
61019
- var import_node_crypto16 = __toESM(require("node:crypto"), 1);
61020
- var import_node_fs16 = require("node:fs");
61021
- var import_node_path22 = __toESM(require("node:path"), 1);
61240
+ var import_node_crypto17 = __toESM(require("node:crypto"), 1);
61241
+ var import_node_fs17 = require("node:fs");
61242
+ var import_node_path23 = __toESM(require("node:path"), 1);
61022
61243
 
61023
61244
  // src/checkout-lock.ts
61024
61245
  var import_node_crypto13 = require("node:crypto");
@@ -61084,7 +61305,7 @@ function emptyHooksDir() {
61084
61305
  return noHooksDir;
61085
61306
  }
61086
61307
  function gitArgs(repo, args) {
61087
- return ["-C", repo, "-c", `core.hooksPath=${emptyHooksDir()}`, ...args];
61308
+ return ["-C", repo, "-c", `core.hooksPath=${emptyHooksDir()}`, "-c", "submodule.recurse=false", ...args];
61088
61309
  }
61089
61310
  var STEP_ENV_NAMES = /* @__PURE__ */ new Set([
61090
61311
  // user, shell, temp dirs, locale
@@ -61480,7 +61701,7 @@ function restoreRunBranch(input) {
61480
61701
  }
61481
61702
  abortIntegration({ worktreePath: input.worktreePath });
61482
61703
  git(input.worktreePath, ["checkout", "-q", "-f", `mrrlin/run-${input.runId}`]);
61483
- git(input.worktreePath, ["reset", "-q", "--hard"]);
61704
+ git(input.worktreePath, ["reset", "-q", "--no-recurse-submodules", "--hard"]);
61484
61705
  git(input.worktreePath, ["clean", "-q", "-f", "-d"]);
61485
61706
  return { restored: true, branchTip: input.preMergeHead };
61486
61707
  }
@@ -61561,9 +61782,76 @@ function verifyIntegrationResolved(input) {
61561
61782
  function applyLocalRun(input) {
61562
61783
  const repo = input.checkoutRealPath;
61563
61784
  const ref = `refs/heads/${input.defaultBranch}`;
61564
- const old = git(repo, ["rev-parse", ref]);
61565
- if (old === input.headSha || isAncestor(repo, input.headSha, old)) {
61566
- return { applied: false, reason: "already_applied", detail: `${input.defaultBranch} at ${old.slice(0, 12)} already contains ${input.headSha.slice(0, 12)}` };
61785
+ if (input.runBranchGuard) {
61786
+ const guardRes = gitTry(repo, ["rev-parse", "-q", "--verify", input.runBranchGuard.ref]);
61787
+ if (guardRes.status !== 0 || guardRes.stdout.trim() !== input.runBranchGuard.sha) {
61788
+ return {
61789
+ applied: false,
61790
+ reason: "run_branch_changed",
61791
+ detail: `run branch ${input.runBranchGuard.ref} moved or missing: expected ${input.runBranchGuard.sha.slice(0, 12)}, got ${guardRes.stdout.trim().slice(0, 12)}`
61792
+ };
61793
+ }
61794
+ }
61795
+ const oldRes = gitTry(repo, ["rev-parse", "-q", "--verify", ref]);
61796
+ if (oldRes.status !== 0) {
61797
+ return {
61798
+ applied: false,
61799
+ reason: "landing_partial",
61800
+ detail: `rev-parse ${ref} failed: ${oldRes.stderr || oldRes.stdout}`
61801
+ };
61802
+ }
61803
+ const old = oldRes.stdout.trim();
61804
+ const isTargetAtHead = old === input.headSha;
61805
+ const isTargetAncestorOfOld = !isTargetAtHead && isAncestor(repo, input.headSha, old);
61806
+ if (isTargetAtHead || isTargetAncestorOfOld) {
61807
+ const holders2 = worktreesWithBranch(repo, input.defaultBranch);
61808
+ const headTreeRes = gitTry(repo, ["rev-parse", `${input.headSha}^{tree}`]);
61809
+ if (headTreeRes.status !== 0) {
61810
+ return { applied: false, reason: "landing_partial", detail: `rev-parse head tree failed: ${headTreeRes.stderr || headTreeRes.stdout}` };
61811
+ }
61812
+ const headTree = headTreeRes.stdout.trim();
61813
+ const targetTreeRes = isTargetAncestorOfOld ? gitTry(repo, ["rev-parse", `${old}^{tree}`]) : null;
61814
+ if (targetTreeRes && targetTreeRes.status !== 0) {
61815
+ return { applied: false, reason: "landing_partial", detail: `rev-parse target tree failed: ${targetTreeRes.stderr || targetTreeRes.stdout}` };
61816
+ }
61817
+ const targetTree = targetTreeRes ? targetTreeRes.stdout.trim() : null;
61818
+ const holderStates = [];
61819
+ for (const h of holders2) {
61820
+ const updateIndexRes = gitTry(h, ["update-index", "-q", "--refresh"]);
61821
+ if (updateIndexRes.status !== 0 && updateIndexRes.status !== 1) {
61822
+ return { applied: false, reason: "landing_partial", detail: `update-index failed on ${h}: ${updateIndexRes.stderr || updateIndexRes.stdout}` };
61823
+ }
61824
+ const diffFilesRes = gitTry(h, ["diff-files", "--name-only"]);
61825
+ if (diffFilesRes.status !== 0) {
61826
+ return { applied: false, reason: "landing_partial", detail: `diff-files failed on ${h}: ${diffFilesRes.stderr || diffFilesRes.stdout}` };
61827
+ }
61828
+ const unstaged = diffFilesRes.stdout.trim();
61829
+ const hHeadRes = gitTry(h, ["rev-parse", "-q", "--verify", "HEAD"]);
61830
+ if (hHeadRes.status !== 0) {
61831
+ return { applied: false, reason: "landing_partial", detail: `rev-parse HEAD failed on ${h}: ${hHeadRes.stderr || hHeadRes.stdout}` };
61832
+ }
61833
+ const hHead = hHeadRes.stdout.trim();
61834
+ const hTreeRes = gitTry(h, ["write-tree"]);
61835
+ if (hTreeRes.status !== 0) {
61836
+ return { applied: false, reason: "landing_partial", detail: `write-tree failed on ${h}: ${hTreeRes.stderr || hTreeRes.stdout}` };
61837
+ }
61838
+ const hTree = hTreeRes.stdout.trim();
61839
+ const isSynced = isTargetAtHead ? hHead === input.headSha && hTree === headTree && unstaged.length === 0 : hHead === old && hTree === targetTree && unstaged.length === 0;
61840
+ holderStates.push({ holder: h, hHead, hTree, unstaged, isSynced });
61841
+ }
61842
+ const unsynced = holderStates.find((s) => !s.isSynced);
61843
+ if (!unsynced) {
61844
+ return {
61845
+ applied: false,
61846
+ reason: "already_applied",
61847
+ detail: `${input.defaultBranch} at ${old.slice(0, 12)} already contains ${input.headSha.slice(0, 12)}`
61848
+ };
61849
+ }
61850
+ return {
61851
+ applied: false,
61852
+ reason: "landing_partial",
61853
+ detail: `target branch ${input.defaultBranch} contains ${input.headSha.slice(0, 12)} at ${old.slice(0, 12)}, but holder ${unsynced.holder} is not cleanly synchronized (HEAD=${unsynced.hHead.slice(0, 8)}, unstaged=${unsynced.unstaged.length > 0}); refusing automatic repair to preserve operator changes`
61854
+ };
61567
61855
  }
61568
61856
  if (input.expectedOldSha && old !== input.expectedOldSha) {
61569
61857
  return {
@@ -61581,12 +61869,38 @@ function applyLocalRun(input) {
61581
61869
  }
61582
61870
  const holders = worktreesWithBranch(repo, input.defaultBranch);
61583
61871
  for (const holder of holders) {
61584
- gitTry(holder, ["update-index", "-q", "--refresh"]);
61585
- const dirty = git(holder, ["status", "--porcelain", "--untracked-files=no"]);
61872
+ const uRes = gitTry(holder, ["update-index", "-q", "--refresh"]);
61873
+ if (uRes.status !== 0 && uRes.status !== 1) {
61874
+ return { applied: false, reason: "landing_partial", detail: `update-index failed on ${holder}: ${uRes.stderr || uRes.stdout}` };
61875
+ }
61876
+ const statusRes = gitTry(holder, ["status", "--porcelain", "--untracked-files=no"]);
61877
+ if (statusRes.status !== 0) {
61878
+ return { applied: false, reason: "landing_partial", detail: `status failed on ${holder}: ${statusRes.stderr || statusRes.stdout}` };
61879
+ }
61880
+ const dirty = statusRes.stdout.trim();
61586
61881
  if (dirty.length > 0) {
61587
61882
  return { applied: false, reason: "uncommitted_changes", detail: dirty };
61588
61883
  }
61589
61884
  }
61885
+ const holdersInfo = [];
61886
+ for (const holder of holders) {
61887
+ const wtRes = gitTry(holder, ["write-tree"]);
61888
+ if (wtRes.status !== 0) {
61889
+ return { applied: false, reason: "landing_partial", detail: `write-tree failed on ${holder}: ${wtRes.stderr || wtRes.stdout}` };
61890
+ }
61891
+ holdersInfo.push({
61892
+ path: holder,
61893
+ beforeIndexTree: wtRes.stdout.trim(),
61894
+ synced: false
61895
+ });
61896
+ }
61897
+ input.onLandingPrepared?.({
61898
+ baseOid: old,
61899
+ headOid: input.headSha,
61900
+ targetRef: ref,
61901
+ runRef: input.runBranchGuard?.ref ?? "",
61902
+ holders: holdersInfo
61903
+ });
61590
61904
  input.beforeRefUpdate?.();
61591
61905
  input.beforeRefTransaction?.();
61592
61906
  const transaction = [
@@ -61619,6 +61933,7 @@ function applyLocalRun(input) {
61619
61933
  return { applied: false, reason: "default_branch_moved", detail };
61620
61934
  }
61621
61935
  input.afterRefUpdate?.();
61936
+ input.onRefUpdated?.();
61622
61937
  const updated = [];
61623
61938
  for (const holder of holders) {
61624
61939
  const moved = gitTry(holder, ["read-tree", "-m", "-u", old, input.headSha]);
@@ -61643,14 +61958,34 @@ function applyLocalRun(input) {
61643
61958
  if (/overwritten/.test(detail)) return { applied: false, reason: "would_overwrite_files", detail };
61644
61959
  return { applied: false, reason: "ff_failed", detail };
61645
61960
  }
61961
+ const nowRefRes = gitTry(repo, ["rev-parse", "--verify", "-q", ref]);
61962
+ if (nowRefRes.status !== 0) {
61963
+ return {
61964
+ applied: false,
61965
+ reason: "landing_partial",
61966
+ detail: `rev-parse ${ref} failed after landing: ${nowRefRes.stderr || nowRefRes.stdout}`
61967
+ };
61968
+ }
61969
+ const nowRef = nowRefRes.stdout.trim();
61970
+ const headTreeExpectedRes = gitTry(repo, ["rev-parse", `${input.headSha}^{tree}`]);
61971
+ if (headTreeExpectedRes.status !== 0) {
61972
+ return {
61973
+ applied: false,
61974
+ reason: "landing_partial",
61975
+ detail: `rev-parse ${input.headSha}^{tree} failed after landing: ${headTreeExpectedRes.stderr || headTreeExpectedRes.stdout}`
61976
+ };
61977
+ }
61978
+ const expectedHeadTree = headTreeExpectedRes.stdout.trim();
61979
+ const off = [];
61980
+ for (const holder of holders) {
61981
+ const headRes = gitTry(holder, ["rev-parse", "HEAD"]);
61982
+ const writeTreeRes = gitTry(holder, ["write-tree"]);
61983
+ if (headRes.status !== 0 || writeTreeRes.status !== 0 || headRes.stdout.trim() !== input.headSha || writeTreeRes.stdout.trim() !== expectedHeadTree) {
61984
+ off.push(holder);
61985
+ }
61986
+ }
61646
61987
  const known = new Set(holders.map((holder) => realpathOr(holder)));
61647
61988
  const appeared = worktreesWithBranch(repo, input.defaultBranch).filter((holder) => !known.has(realpathOr(holder)));
61648
- const nowRef = gitTry(repo, ["rev-parse", "--verify", "-q", ref]).stdout || "missing";
61649
- const off = holders.filter((holder) => {
61650
- const head = gitTry(holder, ["rev-parse", "HEAD"]).stdout;
61651
- const indexTree = gitTry(holder, ["write-tree"]).stdout;
61652
- return head !== input.headSha || indexTree !== gitTry(holder, ["rev-parse", `${input.headSha}^{tree}`]).stdout;
61653
- });
61654
61989
  if (nowRef !== input.headSha || off.length > 0 || appeared.length > 0) {
61655
61990
  return {
61656
61991
  applied: false,
@@ -61658,6 +61993,7 @@ function applyLocalRun(input) {
61658
61993
  detail: `${ref} is at ${nowRef.slice(0, 12)} (was ${old.slice(0, 12)}, landing ${input.headSha.slice(0, 12)}); worktrees whose HEAD or index is not the landed commit: ${off.length > 0 ? off.join(", ") : "none"}; worktrees that started holding ${input.defaultBranch} during the landing: ${appeared.length > 0 ? appeared.join(", ") : "none"}`
61659
61994
  };
61660
61995
  }
61996
+ input.onFilesSynced?.();
61661
61997
  return { applied: true, previousSha: old };
61662
61998
  }
61663
61999
  function realpathOr(target) {
@@ -61678,11 +62014,133 @@ function worktreesWithBranch(repo, branch) {
61678
62014
  return holders;
61679
62015
  }
61680
62016
 
62017
+ // src/delivery/settlement-journal.ts
62018
+ var import_node_fs15 = require("node:fs");
62019
+ var import_node_path21 = __toESM(require("node:path"), 1);
62020
+ var import_node_crypto15 = __toESM(require("node:crypto"), 1);
62021
+ function settlementJournalDir(stateDir, projectSlug, runId) {
62022
+ return import_node_path21.default.join(stateDir, "settlements", projectSlug, runId);
62023
+ }
62024
+ function settlementJournalPath(stateDir, projectSlug, runId, idempotencyKey) {
62025
+ return import_node_path21.default.join(settlementJournalDir(stateDir, projectSlug, runId), `${idempotencyKey}.json`);
62026
+ }
62027
+ function writeSettlementJournalSync(stateDir, journal) {
62028
+ const dir = settlementJournalDir(stateDir, journal.projectSlug, journal.runId);
62029
+ (0, import_node_fs15.mkdirSync)(dir, { recursive: true, mode: 448 });
62030
+ const finalPath = import_node_path21.default.join(dir, `${journal.idempotencyKey}.json`);
62031
+ const tempPath = import_node_path21.default.join(dir, `${journal.idempotencyKey}.tmp.${process.pid}.${Date.now()}.${import_node_crypto15.default.randomBytes(4).toString("hex")}`);
62032
+ const content = JSON.stringify(journal, null, 2);
62033
+ const fd = (0, import_node_fs15.openSync)(tempPath, "w", 384);
62034
+ try {
62035
+ (0, import_node_fs15.writeFileSync)(fd, content, "utf8");
62036
+ (0, import_node_fs15.fsyncSync)(fd);
62037
+ } finally {
62038
+ (0, import_node_fs15.closeSync)(fd);
62039
+ }
62040
+ (0, import_node_fs15.renameSync)(tempPath, finalPath);
62041
+ try {
62042
+ const dirFd = (0, import_node_fs15.openSync)(dir, "r");
62043
+ try {
62044
+ (0, import_node_fs15.fsyncSync)(dirFd);
62045
+ } finally {
62046
+ (0, import_node_fs15.closeSync)(dirFd);
62047
+ }
62048
+ } catch {
62049
+ }
62050
+ }
62051
+ function readSettlementJournalSync(stateDir, projectSlug, runId, idempotencyKey) {
62052
+ const filePath = settlementJournalPath(stateDir, projectSlug, runId, idempotencyKey);
62053
+ try {
62054
+ if (!(0, import_node_fs15.existsSync)(filePath)) return null;
62055
+ const raw = (0, import_node_fs15.readFileSync)(filePath, "utf8");
62056
+ const parsed = JSON.parse(raw);
62057
+ if (parsed.version !== 1 || parsed.projectSlug !== projectSlug || parsed.runId !== runId) {
62058
+ return null;
62059
+ }
62060
+ return parsed;
62061
+ } catch {
62062
+ return null;
62063
+ }
62064
+ }
62065
+ function findSettlementJournalsSync(stateDir, projectSlug, runId) {
62066
+ const dir = settlementJournalDir(stateDir, projectSlug, runId);
62067
+ try {
62068
+ if (!(0, import_node_fs15.existsSync)(dir)) return [];
62069
+ const entries = (0, import_node_fs15.readdirSync)(dir);
62070
+ const journals = [];
62071
+ for (const entry of entries) {
62072
+ if (!entry.endsWith(".json") || entry.includes(".tmp.")) continue;
62073
+ const key = entry.slice(0, -".json".length);
62074
+ const journal = readSettlementJournalSync(stateDir, projectSlug, runId, key);
62075
+ if (journal) journals.push(journal);
62076
+ }
62077
+ return journals;
62078
+ } catch {
62079
+ return [];
62080
+ }
62081
+ }
62082
+ function createSettlementJournal(params) {
62083
+ const stateDir = params.stateDir ?? resolveStateDir();
62084
+ const idempotencyKey = params.idempotencyKey ?? import_node_crypto15.default.randomUUID();
62085
+ const journal = {
62086
+ version: 1,
62087
+ projectSlug: params.projectSlug,
62088
+ taskId: params.taskId,
62089
+ runId: params.runId,
62090
+ idempotencyKey,
62091
+ artifactId: params.artifactId,
62092
+ leaseId: params.leaseId,
62093
+ phase: "request_pending",
62094
+ receipt: null,
62095
+ landing: null
62096
+ };
62097
+ writeSettlementJournalSync(stateDir, journal);
62098
+ return journal;
62099
+ }
62100
+ function updateSettlementJournalSync(stateDir, journal, updates) {
62101
+ const updated = {
62102
+ ...journal,
62103
+ ...updates,
62104
+ version: 1,
62105
+ projectSlug: journal.projectSlug,
62106
+ runId: journal.runId,
62107
+ idempotencyKey: journal.idempotencyKey
62108
+ };
62109
+ writeSettlementJournalSync(stateDir, updated);
62110
+ return updated;
62111
+ }
62112
+ function listPendingSettlementJournalsSync(stateDir, projectSlug) {
62113
+ const settlementsRoot = import_node_path21.default.join(stateDir, "settlements");
62114
+ if (!(0, import_node_fs15.existsSync)(settlementsRoot)) return [];
62115
+ const results = [];
62116
+ try {
62117
+ const projects = projectSlug ? [projectSlug] : (0, import_node_fs15.readdirSync)(settlementsRoot);
62118
+ for (const proj of projects) {
62119
+ const projDir = import_node_path21.default.join(settlementsRoot, proj);
62120
+ try {
62121
+ if (!(0, import_node_fs15.existsSync)(projDir)) continue;
62122
+ const runs = (0, import_node_fs15.readdirSync)(projDir);
62123
+ for (const r of runs) {
62124
+ const journals = findSettlementJournalsSync(stateDir, proj, r);
62125
+ for (const j of journals) {
62126
+ if (j.phase !== "complete") {
62127
+ results.push(j);
62128
+ }
62129
+ }
62130
+ }
62131
+ } catch {
62132
+ }
62133
+ }
62134
+ } catch {
62135
+ }
62136
+ return results;
62137
+ }
62138
+
61681
62139
  // src/worktree.ts
61682
62140
  var import_node_child_process14 = require("node:child_process");
61683
- var import_node_crypto15 = require("node:crypto");
61684
- var import_node_fs15 = require("node:fs");
61685
- var import_node_path21 = require("node:path");
62141
+ var import_node_crypto16 = require("node:crypto");
62142
+ var import_node_fs16 = require("node:fs");
62143
+ var import_node_path22 = require("node:path");
61686
62144
  var import_node_util3 = require("node:util");
61687
62145
  function worktreeBranch(runId) {
61688
62146
  return `mrrlin/run-${runId}`;
@@ -61690,26 +62148,26 @@ function worktreeBranch(runId) {
61690
62148
  var defaultGitExec = (args, env) => (0, import_node_child_process14.execFileSync)("git", args, { encoding: "utf8", timeout: 3e4, env });
61691
62149
  var execGitPush = (0, import_node_util3.promisify)(import_node_child_process14.execFile);
61692
62150
  function disabledGitHooksPath(locksDir, scope) {
61693
- const scopeKey = (0, import_node_crypto15.createHash)("sha256").update(scope).digest("hex").slice(0, 32);
61694
- return (0, import_node_path21.resolve)(locksDir, "..", "disabled-git-hooks", scopeKey);
62151
+ const scopeKey = (0, import_node_crypto16.createHash)("sha256").update(scope).digest("hex").slice(0, 32);
62152
+ return (0, import_node_path22.resolve)(locksDir, "..", "disabled-git-hooks", scopeKey);
61695
62153
  }
61696
62154
  function prepareDisabledGitHooksDir(locksDir, scope) {
61697
62155
  const hooksDir = disabledGitHooksPath(locksDir, scope);
61698
- const hooksRoot = (0, import_node_path21.resolve)(hooksDir, "..");
61699
- (0, import_node_fs15.mkdirSync)(hooksRoot, { recursive: true, mode: 448 });
61700
- (0, import_node_fs15.mkdirSync)(hooksDir, { recursive: true, mode: 320 });
61701
- if ((0, import_node_fs15.readdirSync)(hooksDir).length > 0) {
62156
+ const hooksRoot = (0, import_node_path22.resolve)(hooksDir, "..");
62157
+ (0, import_node_fs16.mkdirSync)(hooksRoot, { recursive: true, mode: 448 });
62158
+ (0, import_node_fs16.mkdirSync)(hooksDir, { recursive: true, mode: 320 });
62159
+ if ((0, import_node_fs16.readdirSync)(hooksDir).length > 0) {
61702
62160
  throw new Error(`disabled_git_hooks_dir_not_empty: ${hooksDir}`);
61703
62161
  }
61704
62162
  try {
61705
- (0, import_node_fs15.chmodSync)(hooksDir, 320);
62163
+ (0, import_node_fs16.chmodSync)(hooksDir, 320);
61706
62164
  } catch {
61707
62165
  }
61708
62166
  return hooksDir;
61709
62167
  }
61710
62168
  function removeDisabledGitHooksDir(locksDir, scope) {
61711
62169
  try {
61712
- (0, import_node_fs15.rmdirSync)(disabledGitHooksPath(locksDir, scope));
62170
+ (0, import_node_fs16.rmdirSync)(disabledGitHooksPath(locksDir, scope));
61713
62171
  } catch {
61714
62172
  }
61715
62173
  }
@@ -61732,14 +62190,14 @@ function git2(checkout, args, hooksDir, baseEnv = process.env) {
61732
62190
  });
61733
62191
  }
61734
62192
  async function createRunWorktree(opts) {
61735
- const worktreePath = (0, import_node_path21.join)(opts.worktreeRoot, opts.slug, opts.runId);
62193
+ const worktreePath = (0, import_node_path22.join)(opts.worktreeRoot, opts.slug, opts.runId);
61736
62194
  const hooksDir = prepareDisabledGitHooksDir(opts.locksDir, opts.runId);
61737
62195
  await withCheckoutLock(opts.locksDir, opts.slug, async () => {
61738
- (0, import_node_fs15.mkdirSync)(opts.worktreeRoot, { recursive: true });
62196
+ (0, import_node_fs16.mkdirSync)(opts.worktreeRoot, { recursive: true });
61739
62197
  const base = opts.local ? `refs/heads/${opts.defaultBranch}` : `origin/${opts.defaultBranch}`;
61740
62198
  try {
61741
62199
  if (!opts.local) git2(opts.checkout, ["fetch", "origin", opts.defaultBranch], hooksDir);
61742
- if (!(0, import_node_fs15.existsSync)(worktreePath)) {
62200
+ if (!(0, import_node_fs16.existsSync)(worktreePath)) {
61743
62201
  git2(opts.checkout, [
61744
62202
  "worktree",
61745
62203
  "add",
@@ -61760,16 +62218,16 @@ async function createRunWorktree(opts) {
61760
62218
  return worktreePath;
61761
62219
  }
61762
62220
  async function openRunWorktree(opts) {
61763
- const worktreePath = (0, import_node_path21.join)(opts.worktreeRoot, opts.slug, opts.runId);
62221
+ const worktreePath = (0, import_node_path22.join)(opts.worktreeRoot, opts.slug, opts.runId);
61764
62222
  const hooksDir = prepareDisabledGitHooksDir(opts.locksDir, opts.runId);
61765
62223
  const branch = worktreeBranch(opts.runId);
61766
62224
  const env = buildLocalStepEnv();
61767
62225
  await withCheckoutLock(opts.locksDir, opts.slug, async () => {
61768
- if ((0, import_node_fs15.existsSync)(worktreePath)) {
61769
- const real = (0, import_node_fs15.realpathSync)(worktreePath);
62226
+ if ((0, import_node_fs16.existsSync)(worktreePath)) {
62227
+ const real = (0, import_node_fs16.realpathSync)(worktreePath);
61770
62228
  const listed = git2(opts.checkout, ["worktree", "list", "--porcelain"], hooksDir, env).split(/\n\s*\n/).map((block) => block.split("\n")).find((lines2) => {
61771
62229
  const listedPath = lines2.find((line) => line.startsWith("worktree "))?.slice("worktree ".length);
61772
- return listedPath !== void 0 && (0, import_node_fs15.existsSync)(listedPath) && (0, import_node_fs15.realpathSync)(listedPath) === real;
62230
+ return listedPath !== void 0 && (0, import_node_fs16.existsSync)(listedPath) && (0, import_node_fs16.realpathSync)(listedPath) === real;
61773
62231
  });
61774
62232
  if (!listed) {
61775
62233
  throw new Error(`run_worktree_invalid: ${worktreePath} exists but is not a worktree of ${opts.checkout}`);
@@ -61784,21 +62242,21 @@ async function openRunWorktree(opts) {
61784
62242
  } catch {
61785
62243
  throw new Error(`run_branch_missing: ${opts.checkout} has no branch ${branch}`);
61786
62244
  }
61787
- (0, import_node_fs15.mkdirSync)(opts.worktreeRoot, { recursive: true });
62245
+ (0, import_node_fs16.mkdirSync)(opts.worktreeRoot, { recursive: true });
61788
62246
  git2(opts.checkout, ["worktree", "prune"], hooksDir, env);
61789
62247
  git2(opts.checkout, ["worktree", "add", worktreePath, branch], hooksDir, env);
61790
62248
  });
61791
62249
  return worktreePath;
61792
62250
  }
61793
62251
  async function removeRunWorktree(opts) {
61794
- const hooksDir = prepareDisabledGitHooksDir(opts.locksDir, (0, import_node_path21.basename)(opts.worktreePath));
62252
+ const hooksDir = prepareDisabledGitHooksDir(opts.locksDir, (0, import_node_path22.basename)(opts.worktreePath));
61795
62253
  await withCheckoutLock(opts.locksDir, opts.slug, async () => {
61796
62254
  try {
61797
62255
  git2(opts.checkout, ["worktree", "remove", "--force", opts.worktreePath], hooksDir);
61798
62256
  } catch {
61799
62257
  }
61800
62258
  git2(opts.checkout, ["worktree", "prune"], hooksDir);
61801
- removeDisabledGitHooksDir(opts.locksDir, (0, import_node_path21.basename)(opts.worktreePath));
62259
+ removeDisabledGitHooksDir(opts.locksDir, (0, import_node_path22.basename)(opts.worktreePath));
61802
62260
  });
61803
62261
  }
61804
62262
  async function pushRunBranch(opts, execGit = defaultGitExec) {
@@ -61920,11 +62378,11 @@ async function sweepOrphanWorktrees(opts) {
61920
62378
  const hooksDir = prepareDisabledGitHooksDir(opts.locksDir, `sweep:${opts.slug}`);
61921
62379
  const ownedPrefix = (() => {
61922
62380
  try {
61923
- return (import_node_fs15.realpathSync.native ?? import_node_fs15.realpathSync)(opts.worktreeRoot);
62381
+ return (import_node_fs16.realpathSync.native ?? import_node_fs16.realpathSync)(opts.worktreeRoot);
61924
62382
  } catch {
61925
62383
  return opts.worktreeRoot;
61926
62384
  }
61927
- })() + import_node_path21.sep + opts.slug + import_node_path21.sep;
62385
+ })() + import_node_path22.sep + opts.slug + import_node_path22.sep;
61928
62386
  try {
61929
62387
  await withCheckoutLock(opts.locksDir, opts.slug, async () => {
61930
62388
  const listing = git2(opts.checkout, ["worktree", "list", "--porcelain"], hooksDir);
@@ -61934,18 +62392,18 @@ async function sweepOrphanWorktrees(opts) {
61934
62392
  if (!wt) continue;
61935
62393
  const canonicalWt = (() => {
61936
62394
  try {
61937
- return (import_node_fs15.realpathSync.native ?? import_node_fs15.realpathSync)(wt);
62395
+ return (import_node_fs16.realpathSync.native ?? import_node_fs16.realpathSync)(wt);
61938
62396
  } catch {
61939
62397
  return wt;
61940
62398
  }
61941
62399
  })();
61942
- const normWt = (0, import_node_path21.normalize)(canonicalWt);
61943
- const normPrefix = (0, import_node_path21.normalize)(ownedPrefix);
62400
+ const normWt = (0, import_node_path22.normalize)(canonicalWt);
62401
+ const normPrefix = (0, import_node_path22.normalize)(ownedPrefix);
61944
62402
  const isMatch = process.platform === "win32" ? normWt.toLowerCase().startsWith(normPrefix.toLowerCase()) : normWt.startsWith(normPrefix);
61945
62403
  if (isMatch && opts.isReapable(wt)) {
61946
62404
  try {
61947
62405
  git2(opts.checkout, ["worktree", "remove", "--force", wt], hooksDir);
61948
- removeDisabledGitHooksDir(opts.locksDir, (0, import_node_path21.basename)(wt));
62406
+ removeDisabledGitHooksDir(opts.locksDir, (0, import_node_path22.basename)(wt));
61949
62407
  reaped.push(wt);
61950
62408
  } catch {
61951
62409
  }
@@ -62082,9 +62540,24 @@ function renderUnlandedWork(branches, base) {
62082
62540
  }
62083
62541
 
62084
62542
  // src/local-apply.ts
62543
+ function verifyReceiptSignature(payload, signatureBase64, publicKeyBase64) {
62544
+ try {
62545
+ const bytes3 = Buffer.from(canonicalizeJson(payload), "utf8");
62546
+ const sigBuffer = Buffer.from(signatureBase64, "base64");
62547
+ const isUrl = publicKeyBase64.includes("-") || publicKeyBase64.includes("_");
62548
+ let keyBuffer = Buffer.from(publicKeyBase64, isUrl ? "base64url" : "base64");
62549
+ if (keyBuffer.length === 32) {
62550
+ keyBuffer = Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), keyBuffer]);
62551
+ }
62552
+ const pubKey = import_node_crypto17.default.createPublicKey({ key: keyBuffer, format: "der", type: "spki" });
62553
+ return import_node_crypto17.default.verify(null, bytes3, pubKey, sigBuffer);
62554
+ } catch {
62555
+ return false;
62556
+ }
62557
+ }
62085
62558
  function readIntegratedTip(localEvidenceDir, runId) {
62086
62559
  try {
62087
- const evidence = JSON.parse((0, import_node_fs16.readFileSync)(import_node_path22.default.join(localEvidenceDir, `${runId}.json`), "utf8"));
62560
+ const evidence = JSON.parse((0, import_node_fs17.readFileSync)(import_node_path23.default.join(localEvidenceDir, `${runId}.json`), "utf8"));
62088
62561
  return typeof evidence.integration?.defaultTipSha === "string" ? evidence.integration.defaultTipSha : null;
62089
62562
  } catch {
62090
62563
  return null;
@@ -62107,12 +62580,12 @@ function gitRead(cwd, args) {
62107
62580
  }
62108
62581
  function isBridgeRunWorktree(worktreePath, checkout, worktreeRoot) {
62109
62582
  const real = (target) => {
62110
- const resolved = (import_node_fs16.realpathSync.native ?? import_node_fs16.realpathSync)(target);
62583
+ const resolved = (import_node_fs17.realpathSync.native ?? import_node_fs17.realpathSync)(target);
62111
62584
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
62112
62585
  };
62113
62586
  try {
62114
62587
  const own = real(worktreePath);
62115
- return own !== real(checkout) && own.startsWith(`${real(worktreeRoot)}${import_node_path22.default.sep}`);
62588
+ return own !== real(checkout) && own.startsWith(`${real(worktreeRoot)}${import_node_path23.default.sep}`);
62116
62589
  } catch {
62117
62590
  return false;
62118
62591
  }
@@ -62155,7 +62628,7 @@ async function fileLocalLandingNote(client, projectSlug, outcome, ctx) {
62155
62628
  );
62156
62629
  await client.createInboxItem(projectSlug, { id: note.id, kind: "info", taskId: ctx.taskId, body: note.body }).catch(logFailure("inbox_note"));
62157
62630
  await client.appendExecutionArtifact(projectSlug, ctx.runId, {
62158
- id: `EA-${import_node_crypto16.default.randomUUID()}`,
62631
+ id: `EA-${import_node_crypto17.default.randomUUID()}`,
62159
62632
  kind: "checkpoint",
62160
62633
  payload: {
62161
62634
  event: "local_apply",
@@ -62347,9 +62820,9 @@ async function applyLocalRunForTool(deps, input) {
62347
62820
  })
62348
62821
  );
62349
62822
  const record2 = (extra) => {
62350
- (0, import_node_fs16.mkdirSync)(deps.localEvidenceDir, { recursive: true, mode: 448 });
62351
- (0, import_node_fs16.writeFileSync)(
62352
- import_node_path22.default.join(deps.localEvidenceDir, `${runId}.apply.json`),
62823
+ (0, import_node_fs17.mkdirSync)(deps.localEvidenceDir, { recursive: true, mode: 448 });
62824
+ (0, import_node_fs17.writeFileSync)(
62825
+ import_node_path23.default.join(deps.localEvidenceDir, `${runId}.apply.json`),
62353
62826
  JSON.stringify({ checkout, defaultBranch, ...extra }, null, 2),
62354
62827
  { mode: 384 }
62355
62828
  );
@@ -62391,7 +62864,7 @@ async function applyLocalRunForTool(deps, input) {
62391
62864
  "Gemfile.lock",
62392
62865
  "poetry.lock"
62393
62866
  ]);
62394
- const isLockfile = (file2) => LOCKFILE_NAMES.has(import_node_path22.default.basename(file2));
62867
+ const isLockfile = (file2) => LOCKFILE_NAMES.has(import_node_path23.default.basename(file2));
62395
62868
  const nonLockfiles = changedByBuild.filter((f) => !isLockfile(f));
62396
62869
  const lockfilesChanged = changedByBuild.filter((f) => isLockfile(f));
62397
62870
  if (lockfilesChanged.length > 0) {
@@ -62433,11 +62906,174 @@ async function applyLocalRunForTool(deps, input) {
62433
62906
  deliveryLockKey(checkout),
62434
62907
  async () => {
62435
62908
  if (!runBranchStillSigned()) return branchChanged();
62909
+ const serverDeclaredV2 = Boolean(
62910
+ task.terminalReceiptId || task.closureGeneration !== null && task.closureGeneration !== void 0 && task.closureGeneration >= 1
62911
+ );
62912
+ const stateDir = resolveStateDir();
62913
+ const journals = findSettlementJournalsSync(stateDir, projectSlug, runId);
62914
+ const v2Journal = journals.find((j) => j.receipt !== null);
62915
+ const idempotencyKey = v2Journal?.idempotencyKey ?? journals[0]?.idempotencyKey;
62916
+ let serverSettlement = null;
62917
+ if (deps.client.getLocalGitSettlement && idempotencyKey) {
62918
+ try {
62919
+ serverSettlement = await deps.client.getLocalGitSettlement(projectSlug, runId, idempotencyKey);
62920
+ } catch (error51) {
62921
+ const lookupErr = error51;
62922
+ if (serverDeclaredV2 || v2Journal) {
62923
+ return {
62924
+ outcome: "build_failed",
62925
+ previousSha: null,
62926
+ headSha: delivered.headSha,
62927
+ detail: `Failed to fetch authoritative server settlement: ${lookupErr?.message ?? String(lookupErr)}`
62928
+ };
62929
+ }
62930
+ }
62931
+ }
62932
+ const v2Response = serverSettlement && "data" in serverSettlement && "receipt" in serverSettlement.data ? serverSettlement.data : null;
62933
+ const isV2 = Boolean(serverDeclaredV2 || v2Journal || v2Response);
62934
+ let verifiedReceipt = null;
62935
+ if (isV2) {
62936
+ let receipt = v2Response?.receipt ?? v2Journal?.receipt;
62937
+ if (!receipt && task.terminalReceiptId && deps.client.getSettlementReceipt) {
62938
+ try {
62939
+ receipt = await deps.client.getSettlementReceipt(projectSlug, task.terminalReceiptId);
62940
+ } catch (error51) {
62941
+ const fetchErr = error51;
62942
+ return {
62943
+ outcome: "build_failed",
62944
+ previousSha: null,
62945
+ headSha: delivered.headSha,
62946
+ detail: `Failed to fetch terminal settlement receipt ${task.terminalReceiptId}: ${fetchErr?.message ?? String(fetchErr)}`
62947
+ };
62948
+ }
62949
+ }
62950
+ if (!receipt) {
62951
+ return {
62952
+ outcome: "build_failed",
62953
+ previousSha: null,
62954
+ headSha: delivered.headSha,
62955
+ detail: "Missing authoritative V2 settlement receipt for verified landing"
62956
+ };
62957
+ }
62958
+ const targetKeyId = receipt.signingKeyId ?? receipt.signing_key_id;
62959
+ let publicKey = null;
62960
+ if (deps.client.getJwks) {
62961
+ let jwks;
62962
+ try {
62963
+ jwks = await deps.client.getJwks();
62964
+ } catch (error51) {
62965
+ const err = error51;
62966
+ return {
62967
+ outcome: "build_failed",
62968
+ previousSha: null,
62969
+ headSha: delivered.headSha,
62970
+ detail: `Failed to fetch authoritative JWKS public key registry: ${err?.message ?? String(err)}`
62971
+ };
62972
+ }
62973
+ const found = jwks?.keys?.find((k) => k.kid === targetKeyId);
62974
+ if (!found?.x) {
62975
+ return {
62976
+ outcome: "build_failed",
62977
+ previousSha: null,
62978
+ headSha: delivered.headSha,
62979
+ detail: `Signing key ${targetKeyId ?? "unknown"} is not published in JWKS (omitted, expired, or compromised)`
62980
+ };
62981
+ }
62982
+ publicKey = found.x;
62983
+ } else if (v2Response?.signingKey) {
62984
+ const respKey = v2Response.signingKey;
62985
+ if (respKey.keyId === targetKeyId) {
62986
+ if (respKey.status === "compromised") {
62987
+ return {
62988
+ outcome: "build_failed",
62989
+ previousSha: null,
62990
+ headSha: delivered.headSha,
62991
+ detail: `Signing key ${respKey.keyId} is compromised`
62992
+ };
62993
+ }
62994
+ if (respKey.status === "active" || respKey.status === "retired") {
62995
+ publicKey = respKey.publicKey;
62996
+ }
62997
+ }
62998
+ }
62999
+ if (!publicKey) {
63000
+ return {
63001
+ outcome: "build_failed",
63002
+ previousSha: null,
63003
+ headSha: delivered.headSha,
63004
+ detail: `Signing key ${targetKeyId ?? "unknown"} is not recognized, expired, or compromised (must be active or retired)`
63005
+ };
63006
+ }
63007
+ const canonicalPayload = receipt.canonicalPayload ?? receipt.payload;
63008
+ if (!canonicalPayload || !receipt.signature || !verifyReceiptSignature(canonicalPayload, receipt.signature, publicKey)) {
63009
+ return { outcome: "build_failed", previousSha: null, headSha: delivered.headSha, detail: "Invalid V2 receipt signature" };
63010
+ }
63011
+ const git3 = canonicalPayload?.client_reported?.git;
63012
+ if (!git3) {
63013
+ return { outcome: "build_failed", previousSha: null, headSha: delivered.headSha, detail: "Missing signed git binding in receipt" };
63014
+ }
63015
+ if (git3.head_oid !== delivered.headSha) {
63016
+ return { outcome: "build_failed", previousSha: null, headSha: delivered.headSha, detail: `Delivered head ${delivered.headSha} does not match receipt head_oid ${git3.head_oid}` };
63017
+ }
63018
+ if (git3.target_ref !== `refs/heads/${defaultBranch}`) {
63019
+ return { outcome: "build_failed", previousSha: null, headSha: delivered.headSha, detail: `Target ref refs/heads/${defaultBranch} does not match receipt target_ref ${git3.target_ref}` };
63020
+ }
63021
+ if (git3.base_oid !== expectedTip) {
63022
+ return { outcome: "default_branch_moved", previousSha: null, headSha: delivered.headSha, detail: `Expected tip ${expectedTip} does not match receipt base_oid ${git3.base_oid}` };
63023
+ }
63024
+ const expectedRunRef = `refs/heads/${worktreeBranch(runId)}`;
63025
+ if (git3.run_ref !== expectedRunRef) {
63026
+ return { outcome: "build_failed", previousSha: null, headSha: delivered.headSha, detail: `Run ref ${expectedRunRef} does not match receipt run_ref ${git3.run_ref}` };
63027
+ }
63028
+ const currentCheckoutDigest = import_node_crypto17.default.createHash("sha256").update(checkout).digest("hex");
63029
+ if (git3.checkout_digest && git3.checkout_digest !== currentCheckoutDigest) {
63030
+ return { outcome: "build_failed", previousSha: null, headSha: delivered.headSha, detail: `Checkout digest ${currentCheckoutDigest} does not match receipt checkout_digest ${git3.checkout_digest}` };
63031
+ }
63032
+ verifiedReceipt = receipt;
63033
+ }
62436
63034
  const first = await land(delivered.headSha, expectedTip);
62437
- if (first.applied) return { outcome: "applied", previousSha: first.previousSha, headSha: delivered.headSha, detail: "" };
63035
+ if (first.applied || isV2 && first.reason === "already_applied") {
63036
+ if (isV2) {
63037
+ const receiptToAck = verifiedReceipt ?? v2Response?.receipt ?? v2Journal?.receipt;
63038
+ const canonicalPayload = receiptToAck?.canonicalPayload ?? receiptToAck?.payload;
63039
+ const git3 = canonicalPayload?.client_reported?.git;
63040
+ if (git3 && receiptToAck && deps.client.acknowledgeLocalGitLanding) {
63041
+ try {
63042
+ await deps.client.acknowledgeLocalGitLanding(projectSlug, runId, {
63043
+ receiptId: receiptToAck.receiptId,
63044
+ headOid: git3.head_oid,
63045
+ baseOid: git3.base_oid,
63046
+ targetRef: git3.target_ref,
63047
+ checkoutDigest: git3.checkout_digest
63048
+ });
63049
+ if (v2Journal) {
63050
+ updateSettlementJournalSync(stateDir, v2Journal, { phase: "complete" });
63051
+ }
63052
+ } catch (ackError) {
63053
+ if (v2Journal) {
63054
+ updateSettlementJournalSync(stateDir, v2Journal, { phase: "ack_pending" });
63055
+ }
63056
+ process.stderr.write(
63057
+ `[mrrlin-mcp local-apply] failed to acknowledge local git landing for ${projectSlug}/${runId}: ${ackError instanceof Error ? ackError.message : String(ackError)}
63058
+ `
63059
+ );
63060
+ }
63061
+ } else if (v2Journal) {
63062
+ updateSettlementJournalSync(stateDir, v2Journal, { phase: "complete" });
63063
+ }
63064
+ }
63065
+ if (first.applied) {
63066
+ return { outcome: "applied", previousSha: first.previousSha, headSha: delivered.headSha, detail: "" };
63067
+ } else {
63068
+ return { outcome: "already_applied", previousSha: null, headSha: delivered.headSha, detail: first.detail };
63069
+ }
63070
+ }
62438
63071
  if (first.reason !== "default_branch_moved") {
62439
63072
  return { outcome: first.reason, previousSha: null, headSha: delivered.headSha, detail: first.detail };
62440
63073
  }
63074
+ if (isV2) {
63075
+ return { outcome: "default_branch_moved", previousSha: null, headSha: delivered.headSha, detail: first.detail };
63076
+ }
62441
63077
  const worktreePath = await openRunWorktree({
62442
63078
  checkout,
62443
63079
  worktreeRoot: deps.worktreeRoot,
@@ -62489,8 +63125,8 @@ async function applyLocalRunForTool(deps, input) {
62489
63125
  { name: DELIVERY_LOCK_NAME, maxWaitMs: DELIVERY_LOCK_MAX_WAIT_MS }
62490
63126
  );
62491
63127
  if (landing.outcome === "applied" || landing.outcome === "already_applied") {
62492
- const worktreePath = import_node_path22.default.join(deps.worktreeRoot, projectSlug, runId);
62493
- if ((0, import_node_fs16.existsSync)(worktreePath)) {
63128
+ const worktreePath = import_node_path23.default.join(deps.worktreeRoot, projectSlug, runId);
63129
+ if ((0, import_node_fs17.existsSync)(worktreePath)) {
62494
63130
  await removeRunWorktree({ checkout, worktreePath, locksDir: deps.locksDir, slug: projectSlug }).catch(() => {
62495
63131
  });
62496
63132
  }
@@ -62531,19 +63167,19 @@ async function applyLocalRunForTool(deps, input) {
62531
63167
  }
62532
63168
 
62533
63169
  // src/operator-token.ts
62534
- var import_node_fs17 = require("node:fs");
63170
+ var import_node_fs18 = require("node:fs");
62535
63171
  var import_node_os11 = __toESM(require("node:os"), 1);
62536
- var import_node_path23 = __toESM(require("node:path"), 1);
63172
+ var import_node_path24 = __toESM(require("node:path"), 1);
62537
63173
  function operatorDir() {
62538
- const base = process.env.CODEX_HOME ? import_node_path23.default.join(process.env.CODEX_HOME, "mrrlin") : import_node_path23.default.join(import_node_os11.default.homedir(), ".mrrlin");
63174
+ const base = process.env.CODEX_HOME ? import_node_path24.default.join(process.env.CODEX_HOME, "mrrlin") : import_node_path24.default.join(import_node_os11.default.homedir(), ".mrrlin");
62539
63175
  return base;
62540
63176
  }
62541
63177
  function operatorTokenPath() {
62542
- return import_node_path23.default.join(operatorDir(), "operator-token");
63178
+ return import_node_path24.default.join(operatorDir(), "operator-token");
62543
63179
  }
62544
63180
  function readOperatorToken() {
62545
63181
  try {
62546
- const token = (0, import_node_fs17.readFileSync)(operatorTokenPath(), "utf8").trim();
63182
+ const token = (0, import_node_fs18.readFileSync)(operatorTokenPath(), "utf8").trim();
62547
63183
  return token.length > 0 ? token : null;
62548
63184
  } catch {
62549
63185
  return null;
@@ -62551,24 +63187,24 @@ function readOperatorToken() {
62551
63187
  }
62552
63188
  function persistOperatorToken(token) {
62553
63189
  const dir = operatorDir();
62554
- (0, import_node_fs17.mkdirSync)(dir, { recursive: true, mode: 448 });
62555
- (0, import_node_fs17.writeFileSync)(operatorTokenPath(), `${token.trim()}
63190
+ (0, import_node_fs18.mkdirSync)(dir, { recursive: true, mode: 448 });
63191
+ (0, import_node_fs18.writeFileSync)(operatorTokenPath(), `${token.trim()}
62556
63192
  `, { encoding: "utf8", mode: 384 });
62557
63193
  }
62558
63194
  function agentCredentialPath() {
62559
- return import_node_path23.default.join(operatorDir(), "agent-credential");
63195
+ return import_node_path24.default.join(operatorDir(), "agent-credential");
62560
63196
  }
62561
63197
  function persistAgentSecret(secret) {
62562
63198
  const dir = operatorDir();
62563
- (0, import_node_fs17.mkdirSync)(dir, { recursive: true, mode: 448 });
62564
- (0, import_node_fs17.writeFileSync)(agentCredentialPath(), `${secret.trim()}
63199
+ (0, import_node_fs18.mkdirSync)(dir, { recursive: true, mode: 448 });
63200
+ (0, import_node_fs18.writeFileSync)(agentCredentialPath(), `${secret.trim()}
62565
63201
  `, { encoding: "utf8", mode: 384 });
62566
63202
  }
62567
63203
  function readAgentSecret() {
62568
63204
  const fromEnv = process.env.MRRLIN_AGENT_SECRET?.trim();
62569
63205
  if (fromEnv) return fromEnv;
62570
63206
  try {
62571
- const raw = (0, import_node_fs17.readFileSync)(agentCredentialPath(), "utf8").trim();
63207
+ const raw = (0, import_node_fs18.readFileSync)(agentCredentialPath(), "utf8").trim();
62572
63208
  return raw || void 0;
62573
63209
  } catch {
62574
63210
  return void 0;
@@ -62576,10 +63212,10 @@ function readAgentSecret() {
62576
63212
  }
62577
63213
 
62578
63214
  // src/worker-token.ts
62579
- var import_node_crypto17 = require("node:crypto");
62580
- var import_node_fs18 = require("node:fs");
63215
+ var import_node_crypto18 = require("node:crypto");
63216
+ var import_node_fs19 = require("node:fs");
62581
63217
  var import_node_os12 = __toESM(require("node:os"), 1);
62582
- var import_node_path24 = __toESM(require("node:path"), 1);
63218
+ var import_node_path25 = __toESM(require("node:path"), 1);
62583
63219
  var DEFAULT_WORKER_PORT = 8792;
62584
63220
  function workerPort() {
62585
63221
  const raw = process.env.MRRLIN_WORKER_PORT;
@@ -62588,15 +63224,15 @@ function workerPort() {
62588
63224
  return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_WORKER_PORT;
62589
63225
  }
62590
63226
  function workerDir() {
62591
- const base = process.env.CODEX_HOME ? import_node_path24.default.join(process.env.CODEX_HOME, "mrrlin") : import_node_path24.default.join(import_node_os12.default.homedir(), ".mrrlin");
62592
- return import_node_path24.default.join(base, "worker");
63227
+ const base = process.env.CODEX_HOME ? import_node_path25.default.join(process.env.CODEX_HOME, "mrrlin") : import_node_path25.default.join(import_node_os12.default.homedir(), ".mrrlin");
63228
+ return import_node_path25.default.join(base, "worker");
62593
63229
  }
62594
63230
  function workerTokenPath() {
62595
- return import_node_path24.default.join(workerDir(), "token");
63231
+ return import_node_path25.default.join(workerDir(), "token");
62596
63232
  }
62597
63233
  function readWorkerToken() {
62598
63234
  try {
62599
- const token = (0, import_node_fs18.readFileSync)(workerTokenPath(), "utf8").trim();
63235
+ const token = (0, import_node_fs19.readFileSync)(workerTokenPath(), "utf8").trim();
62600
63236
  return token.length > 0 ? token : null;
62601
63237
  } catch {
62602
63238
  return null;
@@ -62606,9 +63242,9 @@ function readOrCreateWorkerToken() {
62606
63242
  const existing = readWorkerToken();
62607
63243
  if (existing) return existing;
62608
63244
  const dir = workerDir();
62609
- (0, import_node_fs18.mkdirSync)(dir, { recursive: true, mode: 448 });
62610
- const token = (0, import_node_crypto17.randomBytes)(32).toString("hex");
62611
- (0, import_node_fs18.writeFileSync)(workerTokenPath(), `${token}
63245
+ (0, import_node_fs19.mkdirSync)(dir, { recursive: true, mode: 448 });
63246
+ const token = (0, import_node_crypto18.randomBytes)(32).toString("hex");
63247
+ (0, import_node_fs19.writeFileSync)(workerTokenPath(), `${token}
62612
63248
  `, { encoding: "utf8", mode: 384 });
62613
63249
  return token;
62614
63250
  }
@@ -64541,7 +65177,7 @@ function createMrrlinTools(options) {
64541
65177
  "Unable to record produced URL.",
64542
65178
  async (c, { projectSlug, runId, url: url2, label }) => {
64543
65179
  await checkTenantBoundary(projectSlug, "produced url");
64544
- const id = `EA-pu-${(0, import_node_crypto18.randomBytes)(4).toString("hex")}`;
65180
+ const id = `EA-pu-${(0, import_node_crypto19.randomBytes)(4).toString("hex")}`;
64545
65181
  const payload = label ? { url: url2, label } : { url: url2 };
64546
65182
  return await c.appendExecutionArtifact(projectSlug, runId, {
64547
65183
  id,
@@ -64628,7 +65264,7 @@ function createMrrlinTools(options) {
64628
65264
  "Unable to upload artifact file.",
64629
65265
  async (c, { projectSlug, path: filePath, class: artifactClass, taskId, runId, description }) => {
64630
65266
  await checkTenantBoundary(projectSlug, "artifact upload");
64631
- const extension2 = import_node_path25.default.extname(filePath).toLowerCase();
65267
+ const extension2 = import_node_path26.default.extname(filePath).toLowerCase();
64632
65268
  const contentType2 = ARTIFACT_EXTENSION_TYPES[extension2];
64633
65269
  if (!contentType2) {
64634
65270
  throw new McpToolCodedError(
@@ -64656,7 +65292,7 @@ function createMrrlinTools(options) {
64656
65292
  "Artifact exceeds 5MB; split or summarize instead."
64657
65293
  );
64658
65294
  }
64659
- const filename = import_node_path25.default.basename(filePath);
65295
+ const filename = import_node_path26.default.basename(filePath);
64660
65296
  return deliverBuiltIn(
64661
65297
  c,
64662
65298
  projectSlug,
@@ -64679,7 +65315,7 @@ function createMrrlinTools(options) {
64679
65315
  `Invalid filename '${filename}'; provide a bare filename with no path separators or '..'.`
64680
65316
  );
64681
65317
  }
64682
- const extension2 = import_node_path25.default.extname(filename).toLowerCase();
65318
+ const extension2 = import_node_path26.default.extname(filename).toLowerCase();
64683
65319
  const contentType2 = ARTIFACT_EXTENSION_TYPES[extension2];
64684
65320
  if (!contentType2) {
64685
65321
  throw new McpToolCodedError(
@@ -64822,9 +65458,9 @@ function createMrrlinTools(options) {
64822
65458
  {
64823
65459
  client: c,
64824
65460
  registry: new CheckoutRegistry(stateDir),
64825
- locksDir: import_node_path25.default.join(stateDir, "locks"),
64826
- worktreeRoot: import_node_path25.default.join(stateDir, "worktrees"),
64827
- localEvidenceDir: import_node_path25.default.join(stateDir, "local-evidence")
65461
+ locksDir: import_node_path26.default.join(stateDir, "locks"),
65462
+ worktreeRoot: import_node_path26.default.join(stateDir, "worktrees"),
65463
+ localEvidenceDir: import_node_path26.default.join(stateDir, "local-evidence")
64828
65464
  },
64829
65465
  { projectSlug, runId }
64830
65466
  );
@@ -64967,20 +65603,20 @@ function allAgyGrantStrings() {
64967
65603
  }
64968
65604
  function resolveAgyConfigPath(options) {
64969
65605
  if (options.agyConfigPath) return options.agyConfigPath;
64970
- return import_node_path26.default.join(options.homeDir ?? import_node_os14.default.homedir(), ".gemini", "config", "mcp_config.json");
65606
+ return import_node_path27.default.join(options.homeDir ?? import_node_os14.default.homedir(), ".gemini", "config", "mcp_config.json");
64971
65607
  }
64972
65608
  function resolveConfigJsonPath(options) {
64973
65609
  if (options.configJsonPath) return options.configJsonPath;
64974
- return import_node_path26.default.join(options.homeDir ?? import_node_os14.default.homedir(), ".gemini", "config", "config.json");
65610
+ return import_node_path27.default.join(options.homeDir ?? import_node_os14.default.homedir(), ".gemini", "config", "config.json");
64975
65611
  }
64976
65612
  async function detectInstallDistribution3(options) {
64977
65613
  if (options.distribution && options.distribution !== "auto") return options.distribution;
64978
- let current2 = import_node_path26.default.dirname(options.binPath);
65614
+ let current2 = import_node_path27.default.dirname(options.binPath);
64979
65615
  while (true) {
64980
- if (await pathExists4(import_node_path26.default.join(current2, "pnpm-workspace.yaml"))) {
65616
+ if (await pathExists4(import_node_path27.default.join(current2, "pnpm-workspace.yaml"))) {
64981
65617
  return "local";
64982
65618
  }
64983
- const parent = import_node_path26.default.dirname(current2);
65619
+ const parent = import_node_path27.default.dirname(current2);
64984
65620
  if (parent === current2) break;
64985
65621
  current2 = parent;
64986
65622
  }
@@ -65017,8 +65653,8 @@ async function installAgy(options) {
65017
65653
  const configJsonPath = resolveConfigJsonPath(options);
65018
65654
  const distribution = await detectInstallDistribution3(options);
65019
65655
  const entries = managedEntries2(options, distribution);
65020
- await import_promises11.default.mkdir(import_node_path26.default.dirname(configPath), { recursive: true });
65021
- await import_promises11.default.mkdir(import_node_path26.default.dirname(configJsonPath), { recursive: true });
65656
+ await import_promises11.default.mkdir(import_node_path27.default.dirname(configPath), { recursive: true });
65657
+ await import_promises11.default.mkdir(import_node_path27.default.dirname(configJsonPath), { recursive: true });
65022
65658
  let action = "noop";
65023
65659
  const preservedEnvBlocks = [];
65024
65660
  if (!await pathExists4(configPath)) {
@@ -65134,9 +65770,9 @@ async function installAgy(options) {
65134
65770
 
65135
65771
  // src/provider-readiness.ts
65136
65772
  var import_promises12 = require("node:fs/promises");
65137
- var import_node_fs19 = require("node:fs");
65773
+ var import_node_fs20 = require("node:fs");
65138
65774
  var import_node_os15 = __toESM(require("node:os"), 1);
65139
- var import_node_path27 = __toESM(require("node:path"), 1);
65775
+ var import_node_path28 = __toESM(require("node:path"), 1);
65140
65776
  var import_semver2 = __toESM(require_semver2(), 1);
65141
65777
  var toml3 = __toESM(require_toml(), 1);
65142
65778
 
@@ -65227,13 +65863,13 @@ function startCodexProbe(deps = {}) {
65227
65863
  // src/provider-readiness.ts
65228
65864
  function resolveCodexHome2(opts) {
65229
65865
  if (opts.codexHome) return opts.codexHome;
65230
- if (opts.homeDir) return import_node_path27.default.join(opts.homeDir, ".codex");
65866
+ if (opts.homeDir) return import_node_path28.default.join(opts.homeDir, ".codex");
65231
65867
  if (process.env.CODEX_HOME) return process.env.CODEX_HOME;
65232
- return import_node_path27.default.join(import_node_os15.default.homedir(), ".codex");
65868
+ return import_node_path28.default.join(import_node_os15.default.homedir(), ".codex");
65233
65869
  }
65234
65870
  function resolveClaudeConfigPath2(opts) {
65235
65871
  if (opts.claudeConfigPath) return opts.claudeConfigPath;
65236
- return import_node_path27.default.join(opts.homeDir ?? import_node_os15.default.homedir(), ".claude.json");
65872
+ return import_node_path28.default.join(opts.homeDir ?? import_node_os15.default.homedir(), ".claude.json");
65237
65873
  }
65238
65874
  async function verifyProviderReadiness(provider, run3, opts = {}) {
65239
65875
  if (provider === "agy") {
@@ -65294,9 +65930,9 @@ async function verifyProviderReadiness(provider, run3, opts = {}) {
65294
65930
  if (!checks.version) details.push(`version: ${version2 ?? "unparseable"} is below the required 2.1.232`);
65295
65931
  }
65296
65932
  if (provider === "codex") {
65297
- const authPath = import_node_path27.default.join(resolveCodexHome2(opts), "auth.json");
65933
+ const authPath = import_node_path28.default.join(resolveCodexHome2(opts), "auth.json");
65298
65934
  try {
65299
- await (0, import_promises12.access)(authPath, import_node_fs19.constants.F_OK);
65935
+ await (0, import_promises12.access)(authPath, import_node_fs20.constants.F_OK);
65300
65936
  checks.auth = true;
65301
65937
  } catch {
65302
65938
  details.push(`auth: ${authPath} not found`);
@@ -65311,7 +65947,7 @@ async function verifyProviderReadiness(provider, run3, opts = {}) {
65311
65947
  if (!checks.auth) details.push("auth: `claude auth status` failed");
65312
65948
  }
65313
65949
  if (provider === "codex") {
65314
- const configPath = import_node_path27.default.join(resolveCodexHome2(opts), "config.toml");
65950
+ const configPath = import_node_path28.default.join(resolveCodexHome2(opts), "config.toml");
65315
65951
  try {
65316
65952
  const raw = await (0, import_promises12.readFile)(configPath, "utf8");
65317
65953
  const parsed = toml3.parse(raw);
@@ -65592,21 +66228,21 @@ async function runBrowserServeProxy(opts) {
65592
66228
  }
65593
66229
 
65594
66230
  // src/director-bridge.ts
65595
- var import_node_fs32 = __toESM(require("node:fs"), 1);
66231
+ var import_node_fs33 = __toESM(require("node:fs"), 1);
65596
66232
 
65597
66233
  // src/executor-thread-instructions.ts
65598
- var import_node_crypto19 = require("node:crypto");
65599
- var import_node_fs20 = require("node:fs");
65600
- var import_node_path28 = require("node:path");
66234
+ var import_node_crypto20 = require("node:crypto");
66235
+ var import_node_fs21 = require("node:fs");
66236
+ var import_node_path29 = require("node:path");
65601
66237
  function instructionHash(instructions) {
65602
- return (0, import_node_crypto19.createHash)("sha256").update(instructions ?? "").digest("hex").slice(0, 16);
66238
+ return (0, import_node_crypto20.createHash)("sha256").update(instructions ?? "").digest("hex").slice(0, 16);
65603
66239
  }
65604
66240
  var MAX_ENTRIES = 1e4;
65605
- function createExecutorThreadInstructionStore(path38, warn = (message) => process.stderr.write(`${message}
66241
+ function createExecutorThreadInstructionStore(path39, warn = (message) => process.stderr.write(`${message}
65606
66242
  `)) {
65607
66243
  const load = () => {
65608
66244
  try {
65609
- const parsed = JSON.parse((0, import_node_fs20.readFileSync)(path38, "utf8"));
66245
+ const parsed = JSON.parse((0, import_node_fs21.readFileSync)(path39, "utf8"));
65610
66246
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
65611
66247
  const out = {};
65612
66248
  for (const [key, value] of Object.entries(parsed)) {
@@ -65636,15 +66272,15 @@ function createExecutorThreadInstructionStore(path38, warn = (message) => proces
65636
66272
  ordered.delete(threadId);
65637
66273
  ordered.set(threadId, hash3);
65638
66274
  const kept = [...ordered].slice(Math.max(0, ordered.size - MAX_ENTRIES));
65639
- (0, import_node_fs20.mkdirSync)((0, import_node_path28.dirname)(path38), { recursive: true });
65640
- const tmp = `${path38}.${process.pid}.tmp`;
65641
- (0, import_node_fs20.writeFileSync)(tmp, JSON.stringify(Object.fromEntries(kept)), { mode: 384 });
65642
- (0, import_node_fs20.renameSync)(tmp, path38);
66275
+ (0, import_node_fs21.mkdirSync)((0, import_node_path29.dirname)(path39), { recursive: true });
66276
+ const tmp = `${path39}.${process.pid}.tmp`;
66277
+ (0, import_node_fs21.writeFileSync)(tmp, JSON.stringify(Object.fromEntries(kept)), { mode: 384 });
66278
+ (0, import_node_fs21.renameSync)(tmp, path39);
65643
66279
  } catch (error51) {
65644
66280
  if (!warned) {
65645
66281
  warned = true;
65646
66282
  warn(
65647
- `[mrrlin-mcp director-bridge] executor_thread_instructions_write_failed ${path38}: ${error51 instanceof Error ? error51.message : String(error51)} (kept in memory for this session)`
66283
+ `[mrrlin-mcp director-bridge] executor_thread_instructions_write_failed ${path39}: ${error51 instanceof Error ? error51.message : String(error51)} (kept in memory for this session)`
65648
66284
  );
65649
66285
  }
65650
66286
  }
@@ -65655,9 +66291,9 @@ function createExecutorThreadInstructionStore(path38, warn = (message) => proces
65655
66291
  // src/director-bridge.ts
65656
66292
  var import_node_http4 = __toESM(require("node:http"), 1);
65657
66293
  var import_node_os23 = __toESM(require("node:os"), 1);
65658
- var import_node_path46 = __toESM(require("node:path"), 1);
66294
+ var import_node_path47 = __toESM(require("node:path"), 1);
65659
66295
  var import_node_child_process25 = require("node:child_process");
65660
- var import_node_crypto27 = __toESM(require("node:crypto"), 1);
66296
+ var import_node_crypto28 = __toESM(require("node:crypto"), 1);
65661
66297
 
65662
66298
  // src/turn-replay-buffer.ts
65663
66299
  var DEFAULT_MAX_EVENTS = 2e3;
@@ -66202,16 +66838,16 @@ function createTurnLock() {
66202
66838
 
66203
66839
  // src/self-update.ts
66204
66840
  var import_node_child_process20 = require("node:child_process");
66205
- var import_node_crypto20 = require("node:crypto");
66206
- var import_node_fs22 = require("node:fs");
66207
- var import_node_path30 = __toESM(require("node:path"), 1);
66841
+ var import_node_crypto21 = require("node:crypto");
66842
+ var import_node_fs23 = require("node:fs");
66843
+ var import_node_path31 = __toESM(require("node:path"), 1);
66208
66844
  var import_semver3 = __toESM(require_semver2(), 1);
66209
66845
 
66210
66846
  // src/codex-auth-preflight.ts
66211
66847
  var import_node_child_process19 = require("node:child_process");
66212
- var import_node_fs21 = require("node:fs");
66848
+ var import_node_fs22 = require("node:fs");
66213
66849
  var import_node_os17 = __toESM(require("node:os"), 1);
66214
- var import_node_path29 = __toESM(require("node:path"), 1);
66850
+ var import_node_path30 = __toESM(require("node:path"), 1);
66215
66851
  var DEFAULT_CODEX_AUTH_MIN_TTL_SECONDS = 15 * 60;
66216
66852
  var DEFAULT_CODEX_AUTH_SMOKE_TIMEOUT_MS = 2e4;
66217
66853
  var DEFAULT_CODEX_AUTH_SMOKE_MODEL = "gpt-5.4-mini";
@@ -66230,7 +66866,7 @@ function codexAuthSmokeTimeoutMs(env = process.env) {
66230
66866
  function resolveCodexAuthPath(opts = {}) {
66231
66867
  const env = opts.env ?? process.env;
66232
66868
  const codexHome = env.CODEX_HOME?.trim();
66233
- return import_node_path29.default.join(codexHome || import_node_path29.default.join(opts.homeDir ?? import_node_os17.default.homedir(), ".codex"), "auth.json");
66869
+ return import_node_path30.default.join(codexHome || import_node_path30.default.join(opts.homeDir ?? import_node_os17.default.homedir(), ".codex"), "auth.json");
66234
66870
  }
66235
66871
  function decodeJwtExpMs(token) {
66236
66872
  const parts = token.split(".");
@@ -66351,7 +66987,7 @@ function inspectCodexAuthForBridgeUpdate(opts = {}) {
66351
66987
  const nowMs = opts.nowMs ?? Date.now();
66352
66988
  const minTtlSeconds = opts.minTtlSeconds ?? codexAuthMinTtlSeconds(env);
66353
66989
  const authPath = resolveCodexAuthPath({ env, homeDir: opts.homeDir });
66354
- const readFile10 = opts.readFileSyncImpl ?? ((p, encoding) => (0, import_node_fs21.readFileSync)(p, encoding));
66990
+ const readFile10 = opts.readFileSyncImpl ?? ((p, encoding) => (0, import_node_fs22.readFileSync)(p, encoding));
66355
66991
  let raw;
66356
66992
  try {
66357
66993
  raw = readFile10(authPath, "utf8");
@@ -66465,7 +67101,7 @@ function inspectCodexAuthForBridgeUpdate(opts = {}) {
66465
67101
  var BIN_NAME = "mrrlin-mcp";
66466
67102
  var SELF_UPDATE_AUTH_PREFLIGHT_OFFER_PREFIX = "[bridge:update:auth-preflight]";
66467
67103
  function resolveBinPath(opts) {
66468
- if (opts.argv1 && import_node_path30.default.basename(opts.argv1).includes("mrrlin")) {
67104
+ if (opts.argv1 && import_node_path31.default.basename(opts.argv1).includes("mrrlin")) {
66469
67105
  return { path: opts.argv1, source: "argv" };
66470
67106
  }
66471
67107
  const whichSync = opts.whichSync ?? ((name) => {
@@ -66475,16 +67111,16 @@ function resolveBinPath(opts) {
66475
67111
  return null;
66476
67112
  }
66477
67113
  });
66478
- const existsSync7 = opts.existsSync ?? import_node_fs22.existsSync;
67114
+ const existsSync8 = opts.existsSync ?? import_node_fs23.existsSync;
66479
67115
  const resolved = whichSync(BIN_NAME);
66480
- if (resolved && existsSync7(resolved)) {
67116
+ if (resolved && existsSync8(resolved)) {
66481
67117
  return { path: resolved, source: "which" };
66482
67118
  }
66483
67119
  const envPath = (opts.env ?? process.env).PATH ?? "";
66484
- for (const dir of envPath.split(import_node_path30.default.delimiter)) {
67120
+ for (const dir of envPath.split(import_node_path31.default.delimiter)) {
66485
67121
  if (!dir) continue;
66486
- const candidate = import_node_path30.default.join(dir, BIN_NAME);
66487
- if (existsSync7(candidate)) {
67122
+ const candidate = import_node_path31.default.join(dir, BIN_NAME);
67123
+ if (existsSync8(candidate)) {
66488
67124
  return { path: candidate, source: "path-walk" };
66489
67125
  }
66490
67126
  }
@@ -66510,12 +67146,12 @@ function readIntervalEnv(name, fallback) {
66510
67146
  return Number.isFinite(n) && n > 0 ? n : fallback;
66511
67147
  }
66512
67148
  function sha2562(buf) {
66513
- return (0, import_node_crypto20.createHash)("sha256").update(buf).digest("hex");
67149
+ return (0, import_node_crypto21.createHash)("sha256").update(buf).digest("hex");
66514
67150
  }
66515
67151
  function startSelfUpdate(deps) {
66516
67152
  const log2 = deps.log ?? (() => {
66517
67153
  });
66518
- const readFile10 = deps.readFileSyncImpl ?? ((p) => (0, import_node_fs22.readFileSync)(p));
67154
+ const readFile10 = deps.readFileSyncImpl ?? ((p) => (0, import_node_fs23.readFileSync)(p));
66519
67155
  const setIntervalFn = deps.setIntervalImpl ?? setInterval;
66520
67156
  const clearIntervalFn = deps.clearIntervalImpl ?? clearInterval;
66521
67157
  const intervalMs = deps.intervalMs ?? readIntervalEnv("MRRLIN_DIRECTOR_BRIDGE_SELF_UPDATE_INTERVAL_MS", DEFAULT_INTERVAL_MS);
@@ -66806,7 +67442,7 @@ Do NOT derail the current task - if the operator has an in-flight question, answ
66806
67442
  }
66807
67443
 
66808
67444
  // src/_generated/version.ts
66809
- var PKG_VERSION = "0.4.174";
67445
+ var PKG_VERSION = "0.4.176";
66810
67446
 
66811
67447
  // src/bridge-allowed-origins.ts
66812
67448
  var DEFAULT_DIRECTOR_BRIDGE_ALLOWED_ORIGINS = [
@@ -66835,28 +67471,28 @@ function readDirectorBridgeAllowedOrigins(env = process.env) {
66835
67471
  }
66836
67472
 
66837
67473
  // src/receipt-signing.ts
66838
- var import_node_crypto21 = __toESM(require("node:crypto"), 1);
67474
+ var import_node_crypto22 = __toESM(require("node:crypto"), 1);
66839
67475
  var FIXTURE_SIGNING_KEY_ID = "ed25519:fixture:default";
66840
67476
  var FIXTURE_PRIVATE_KEY_BASE64 = "MC4CAQAwBQYDK2VwBCIEIFnZBWdVAlsGODDrzXF2wQxO4mBVB/AEos6tYJzg/C/+";
66841
- function canonicalizeJson(obj) {
67477
+ function canonicalizeJson2(obj) {
66842
67478
  if (obj === null || typeof obj !== "object") {
66843
67479
  return JSON.stringify(obj);
66844
67480
  }
66845
67481
  if (Array.isArray(obj)) {
66846
- return "[" + obj.map((item) => canonicalizeJson(item)).join(",") + "]";
67482
+ return "[" + obj.map((item) => canonicalizeJson2(item)).join(",") + "]";
66847
67483
  }
66848
67484
  const keys = Object.keys(obj).sort();
66849
67485
  const entries = keys.map((key) => {
66850
67486
  const val = obj[key];
66851
- return JSON.stringify(key) + ":" + canonicalizeJson(val);
67487
+ return JSON.stringify(key) + ":" + canonicalizeJson2(val);
66852
67488
  });
66853
67489
  return "{" + entries.join(",") + "}";
66854
67490
  }
66855
67491
  function canonicalBytes(obj) {
66856
- return Buffer.from(canonicalizeJson(obj), "utf8");
67492
+ return Buffer.from(canonicalizeJson2(obj), "utf8");
66857
67493
  }
66858
67494
  function sha256Hex(data) {
66859
- return import_node_crypto21.default.createHash("sha256").update(data).digest("hex");
67495
+ return import_node_crypto22.default.createHash("sha256").update(data).digest("hex");
66860
67496
  }
66861
67497
  var LocalEd25519SigningProvider = class {
66862
67498
  keyId;
@@ -66869,9 +67505,9 @@ var LocalEd25519SigningProvider = class {
66869
67505
  if (options.privateKey) {
66870
67506
  if (typeof options.privateKey === "string") {
66871
67507
  if (options.privateKey.includes("-----BEGIN")) {
66872
- this.privateKey = import_node_crypto21.default.createPrivateKey(options.privateKey);
67508
+ this.privateKey = import_node_crypto22.default.createPrivateKey(options.privateKey);
66873
67509
  } else {
66874
- this.privateKey = import_node_crypto21.default.createPrivateKey({
67510
+ this.privateKey = import_node_crypto22.default.createPrivateKey({
66875
67511
  key: Buffer.from(options.privateKey, "base64"),
66876
67512
  format: "der",
66877
67513
  type: "pkcs8"
@@ -66880,10 +67516,10 @@ var LocalEd25519SigningProvider = class {
66880
67516
  } else {
66881
67517
  this.privateKey = options.privateKey;
66882
67518
  }
66883
- const pub = import_node_crypto21.default.createPublicKey(this.privateKey);
67519
+ const pub = import_node_crypto22.default.createPublicKey(this.privateKey);
66884
67520
  this.publicKeyBase64 = pub.export({ type: "spki", format: "der" }).toString("base64");
66885
67521
  } else {
66886
- const pair = import_node_crypto21.default.generateKeyPairSync("ed25519");
67522
+ const pair = import_node_crypto22.default.generateKeyPairSync("ed25519");
66887
67523
  this.privateKey = pair.privateKey;
66888
67524
  this.publicKeyBase64 = pair.publicKey.export({ type: "spki", format: "der" }).toString("base64");
66889
67525
  }
@@ -66906,24 +67542,38 @@ var LocalEd25519SigningProvider = class {
66906
67542
  throw new Error(`KEY_COMPROMISED: signing key ${this.keyId} is compromised: ${this.compromiseReason}`);
66907
67543
  }
66908
67544
  const bytes3 = canonicalBytes(payload);
66909
- const signature = import_node_crypto21.default.sign(null, bytes3, this.privateKey).toString("base64");
67545
+ const signature = import_node_crypto22.default.sign(null, bytes3, this.privateKey).toString("base64");
66910
67546
  return {
66911
67547
  keyId: this.keyId,
66912
67548
  signature,
66913
- canonicalPayload: JSON.parse(canonicalizeJson(payload))
67549
+ canonicalPayload: JSON.parse(canonicalizeJson2(payload))
66914
67550
  };
66915
67551
  }
66916
67552
  verify(payload, signature, publicKeySpkiBase64) {
66917
67553
  try {
66918
67554
  const bytes3 = canonicalBytes(payload);
66919
67555
  const sigBuffer = Buffer.from(signature, "base64");
66920
- const pubKey = publicKeySpkiBase64 ? import_node_crypto21.default.createPublicKey({ key: Buffer.from(publicKeySpkiBase64, "base64"), format: "der", type: "spki" }) : import_node_crypto21.default.createPublicKey(this.privateKey);
66921
- return import_node_crypto21.default.verify(null, bytes3, pubKey, sigBuffer);
67556
+ const pubKey = publicKeySpkiBase64 ? import_node_crypto22.default.createPublicKey({ key: Buffer.from(publicKeySpkiBase64, "base64"), format: "der", type: "spki" }) : import_node_crypto22.default.createPublicKey(this.privateKey);
67557
+ return import_node_crypto22.default.verify(null, bytes3, pubKey, sigBuffer);
66922
67558
  } catch {
66923
67559
  return false;
66924
67560
  }
66925
67561
  }
66926
67562
  };
67563
+ function verifySettlementReceiptV2(receipt, publicKeyBase64) {
67564
+ try {
67565
+ const bytes3 = canonicalBytes(receipt.canonicalPayload);
67566
+ const sigBuffer = Buffer.from(receipt.signature, "base64");
67567
+ let keyBuffer = Buffer.from(publicKeyBase64, "base64");
67568
+ if (keyBuffer.length === 32) {
67569
+ keyBuffer = Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), keyBuffer]);
67570
+ }
67571
+ const pubKey = import_node_crypto22.default.createPublicKey({ key: keyBuffer, format: "der", type: "spki" });
67572
+ return import_node_crypto22.default.verify(null, bytes3, pubKey, sigBuffer);
67573
+ } catch {
67574
+ return false;
67575
+ }
67576
+ }
66927
67577
 
66928
67578
  // src/director-closure.ts
66929
67579
  var CLOSURE_SNAPSHOT_TIMEOUT_MS = 2e3;
@@ -67185,7 +67835,7 @@ async function orchestrateSettlementClosure(deps, params) {
67185
67835
  outcome: params.outcome,
67186
67836
  nonce: params.nonce
67187
67837
  };
67188
- const canonicalRequestDigest = sha256Hex(canonicalizeJson(canonicalRequest));
67838
+ const canonicalRequestDigest = sha256Hex(canonicalizeJson2(canonicalRequest));
67189
67839
  const candidate = await deps.prepareSettlementCandidate(params.projectSlug, {
67190
67840
  taskId: params.taskId,
67191
67841
  runId: params.runId,
@@ -67212,7 +67862,7 @@ async function orchestrateSettlementClosure(deps, params) {
67212
67862
  const signed = deps.signingProvider.sign(signingPayload);
67213
67863
  if (deps.resolveCurrentArtifacts) {
67214
67864
  const currentArtifacts = await deps.resolveCurrentArtifacts(params.projectSlug, params.runId);
67215
- if (canonicalizeJson(currentArtifacts) !== canonicalizeJson(params.artifacts)) {
67865
+ if (canonicalizeJson2(currentArtifacts) !== canonicalizeJson2(params.artifacts)) {
67216
67866
  throw new Error("ARTIFACT_SET_DRIFT: authorized artifacts have changed after candidate preparation");
67217
67867
  }
67218
67868
  }
@@ -67227,6 +67877,142 @@ async function orchestrateSettlementClosure(deps, params) {
67227
67877
  isIdempotent: finalized.isIdempotent
67228
67878
  };
67229
67879
  }
67880
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
67881
+ function isRetryableTransportError(error51) {
67882
+ if (error51 instanceof MrrlinApiError) {
67883
+ return RETRYABLE_STATUSES.has(error51.status);
67884
+ }
67885
+ return true;
67886
+ }
67887
+ async function orchestrateLocalGitSettlementClosure(deps, params) {
67888
+ const { journal } = deps;
67889
+ const sleep = deps.retrySleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms)));
67890
+ let receipt = journal.receipt;
67891
+ let signingKey = null;
67892
+ if (!receipt) {
67893
+ const delays = [500, 1e3, 2e3];
67894
+ let lastError = null;
67895
+ for (let attempt = 0; attempt <= delays.length; attempt++) {
67896
+ try {
67897
+ const issued = await deps.issueLocalGitSettlement(
67898
+ params.projectSlug,
67899
+ params.runId,
67900
+ { leaseId: params.leaseId, evidence: params.evidence },
67901
+ { idempotencyKey: journal.idempotencyKey }
67902
+ );
67903
+ receipt = issued.receipt;
67904
+ signingKey = issued.signingKey;
67905
+ break;
67906
+ } catch (err) {
67907
+ lastError = err;
67908
+ if (!isRetryableTransportError(err)) {
67909
+ throw err;
67910
+ }
67911
+ try {
67912
+ const lookup = await deps.getLocalGitSettlement(params.projectSlug, params.runId, journal.idempotencyKey);
67913
+ const data = lookup && "data" in lookup ? lookup.data : null;
67914
+ if (data && "receipt" in data && "signingKey" in data) {
67915
+ const settlement = data;
67916
+ receipt = settlement.receipt;
67917
+ signingKey = settlement.signingKey;
67918
+ break;
67919
+ }
67920
+ } catch {
67921
+ }
67922
+ const delay3 = delays[attempt];
67923
+ if (delay3 !== void 0) {
67924
+ await sleep(delay3);
67925
+ }
67926
+ }
67927
+ }
67928
+ if (!receipt || !signingKey) {
67929
+ throw lastError ?? new Error("LOCAL_GIT_SETTLEMENT_FAILED: failed to obtain server settlement receipt");
67930
+ }
67931
+ } else {
67932
+ const lookup = await deps.getLocalGitSettlement(params.projectSlug, params.runId, journal.idempotencyKey);
67933
+ const data = lookup && "data" in lookup ? lookup.data : null;
67934
+ if (!data || !("signingKey" in data)) {
67935
+ throw new Error(`SIGNING_KEY_LOOKUP_FAILED: cannot find signing key for receipt ${receipt.receiptId}`);
67936
+ }
67937
+ signingKey = data.signingKey;
67938
+ }
67939
+ if (!signingKey) {
67940
+ throw new Error("SIGNING_KEY_MISSING: signing key details are not available");
67941
+ }
67942
+ const targetKeyId = receipt.signingKeyId ?? receipt.signing_key_id;
67943
+ let resolvedPublicKey = null;
67944
+ if (deps.getJwks) {
67945
+ let jwks = null;
67946
+ let lastJwksError = null;
67947
+ const jwksDelays = [200, 500, 1e3];
67948
+ for (let attempt = 0; attempt <= jwksDelays.length; attempt++) {
67949
+ try {
67950
+ jwks = await deps.getJwks();
67951
+ break;
67952
+ } catch (err) {
67953
+ lastJwksError = err;
67954
+ const delay3 = jwksDelays[attempt];
67955
+ if (delay3 !== void 0) {
67956
+ await sleep(delay3);
67957
+ }
67958
+ }
67959
+ }
67960
+ if (!jwks) {
67961
+ throw new Error(`JWKS_FETCH_FAILED: failed to fetch authoritative JWKS public key registry: ${lastJwksError instanceof Error ? lastJwksError.message : String(lastJwksError)}`);
67962
+ }
67963
+ const found = jwks.keys?.find((k) => k.kid === targetKeyId);
67964
+ if (!found?.x) {
67965
+ throw new Error(`SIGNING_KEY_NOT_PUBLISHED: signing key ${targetKeyId ?? "unknown"} is not published in JWKS (omitted, expired, or compromised)`);
67966
+ }
67967
+ resolvedPublicKey = found.x;
67968
+ } else {
67969
+ if (signingKey.status === "compromised" || signingKey.status === "revoked") {
67970
+ throw new Error(`REVOKED_SIGNING_KEY: signing key ${signingKey.keyId} has been revoked or compromised`);
67971
+ }
67972
+ resolvedPublicKey = signingKey.publicKey;
67973
+ }
67974
+ const verify = deps.verifyReceipt ?? verifySettlementReceiptV2;
67975
+ const verified = verify(receipt, resolvedPublicKey);
67976
+ if (!verified) {
67977
+ throw new Error("RECEIPT_SIGNATURE_INVALID: server receipt failed cryptographic signature verification");
67978
+ }
67979
+ const payload = receipt.canonicalPayload ?? receipt.payload;
67980
+ if (!payload || !payload.client_reported || !payload.client_reported.git) {
67981
+ throw new Error("MALFORMED_RECEIPT: receipt missing canonicalPayload or client_reported.git");
67982
+ }
67983
+ const git3 = payload.client_reported.git;
67984
+ if (git3.head_oid !== params.expectedGit.headOid) {
67985
+ throw new Error(`BINDING_MISMATCH: head_oid mismatch (expected ${params.expectedGit.headOid}, got ${git3.head_oid})`);
67986
+ }
67987
+ if (git3.base_oid !== params.expectedGit.baseOid) {
67988
+ throw new Error(`BINDING_MISMATCH: base_oid mismatch (expected ${params.expectedGit.baseOid}, got ${git3.base_oid})`);
67989
+ }
67990
+ if (git3.target_ref !== params.expectedGit.targetRef) {
67991
+ throw new Error(`BINDING_MISMATCH: target_ref mismatch (expected ${params.expectedGit.targetRef}, got ${git3.target_ref})`);
67992
+ }
67993
+ if (git3.run_ref !== params.expectedGit.runRef) {
67994
+ throw new Error(`BINDING_MISMATCH: run_ref mismatch (expected ${params.expectedGit.runRef}, got ${git3.run_ref})`);
67995
+ }
67996
+ if (params.expectedGit.checkoutDigest && git3.checkout_digest !== params.expectedGit.checkoutDigest) {
67997
+ throw new Error(`BINDING_MISMATCH: checkout_digest mismatch (expected ${params.expectedGit.checkoutDigest}, got ${git3.checkout_digest})`);
67998
+ }
67999
+ journal.receipt = receipt;
68000
+ if (journal.phase === "request_pending") {
68001
+ journal.phase = "receipt_saved";
68002
+ }
68003
+ if (deps.stateDir) {
68004
+ updateSettlementJournalSync(deps.stateDir, journal, {
68005
+ phase: journal.phase,
68006
+ receipt
68007
+ });
68008
+ }
68009
+ const state = journal.phase === "files_synced" || journal.phase === "complete" ? "landing_applied" : "receipt_issued";
68010
+ return {
68011
+ receipt,
68012
+ git: git3,
68013
+ state
68014
+ };
68015
+ }
67230
68016
 
67231
68017
  // src/clarification-ledger.ts
67232
68018
  var LEDGER_MAX_ITEMS = 20;
@@ -67716,14 +68502,14 @@ function parseLedger(value) {
67716
68502
  }
67717
68503
 
67718
68504
  // src/api-base-url-migrate.ts
67719
- var import_node_fs23 = __toESM(require("node:fs"), 1);
68505
+ var import_node_fs24 = __toESM(require("node:fs"), 1);
67720
68506
  var import_node_os18 = __toESM(require("node:os"), 1);
67721
- var import_node_path32 = __toESM(require("node:path"), 1);
68507
+ var import_node_path33 = __toESM(require("node:path"), 1);
67722
68508
 
67723
68509
  // src/service-paths.ts
67724
- var import_node_path31 = __toESM(require("node:path"), 1);
68510
+ var import_node_path32 = __toESM(require("node:path"), 1);
67725
68511
  function isWorktreePath(p) {
67726
- const norm = import_node_path31.default.normalize(p).split(import_node_path31.default.sep).join("/");
68512
+ const norm = import_node_path32.default.normalize(p).split(import_node_path32.default.sep).join("/");
67727
68513
  return norm.includes("/.claude/worktrees/");
67728
68514
  }
67729
68515
  function resolveServiceCwd(opts) {
@@ -67798,17 +68584,17 @@ function defaultDeps(deps) {
67798
68584
  const home = deps.home ?? process.env.HOME ?? import_node_os18.default.homedir();
67799
68585
  return {
67800
68586
  home,
67801
- codexHome: deps.codexHome ?? process.env.CODEX_HOME?.trim() ?? import_node_path32.default.join(home, ".codex"),
67802
- readFile: deps.readFile ?? ((p) => import_node_fs23.default.readFileSync(p, "utf8")),
68587
+ codexHome: deps.codexHome ?? process.env.CODEX_HOME?.trim() ?? import_node_path33.default.join(home, ".codex"),
68588
+ readFile: deps.readFile ?? ((p) => import_node_fs24.default.readFileSync(p, "utf8")),
67803
68589
  // Temp-file + atomic rename so a concurrent `serve` and `director-bridge` startup can never
67804
68590
  // interleave partial writes into a config the next start has to parse. Note this normalizes the
67805
68591
  // file to 0o600 — deliberate, since both files can carry a credential-bearing URL.
67806
68592
  writeFile: deps.writeFile ?? ((p, c) => {
67807
68593
  const tmp = `${p}.tmp-${process.pid}`;
67808
- import_node_fs23.default.writeFileSync(tmp, c, { mode: 384 });
67809
- import_node_fs23.default.renameSync(tmp, p);
68594
+ import_node_fs24.default.writeFileSync(tmp, c, { mode: 384 });
68595
+ import_node_fs24.default.renameSync(tmp, p);
67810
68596
  }),
67811
- exists: deps.exists ?? ((p) => import_node_fs23.default.existsSync(p)),
68597
+ exists: deps.exists ?? ((p) => import_node_fs24.default.existsSync(p)),
67812
68598
  log: deps.log ?? ((m) => process.stderr.write(`${m}
67813
68599
  `))
67814
68600
  };
@@ -67847,7 +68633,7 @@ function backupOnce(file2, text, deps) {
67847
68633
  }
67848
68634
  function migrateEcosystemConfig(deps = {}) {
67849
68635
  const d = defaultDeps(deps);
67850
- const file2 = import_node_path32.default.join(d.home, ".mrrlin", "ecosystem.config.cjs");
68636
+ const file2 = import_node_path33.default.join(d.home, ".mrrlin", "ecosystem.config.cjs");
67851
68637
  if (!d.exists(file2)) return { file: file2, status: "absent" };
67852
68638
  const text = d.readFile(file2);
67853
68639
  if (!findRetiredHost(text) && !hasLiveLegacyStagingFlag(text, "js"))
@@ -67997,7 +68783,7 @@ ${envLines}
67997
68783
  }
67998
68784
  function migrateCodexConfig(deps = {}) {
67999
68785
  const d = defaultDeps(deps);
68000
- const file2 = import_node_path32.default.join(d.codexHome, "config.toml");
68786
+ const file2 = import_node_path33.default.join(d.codexHome, "config.toml");
68001
68787
  if (!d.exists(file2)) return { file: file2, status: "absent" };
68002
68788
  const text = d.readFile(file2);
68003
68789
  const host = findRetiredHost(text);
@@ -68083,7 +68869,7 @@ $1`
68083
68869
  }
68084
68870
  function migrateClaudeConfig(deps = {}) {
68085
68871
  const d = defaultDeps(deps);
68086
- const file2 = import_node_path32.default.join(d.home, ".claude.json");
68872
+ const file2 = import_node_path33.default.join(d.home, ".claude.json");
68087
68873
  if (!d.exists(file2)) return { file: file2, status: "absent" };
68088
68874
  const text = d.readFile(file2);
68089
68875
  let parsed;
@@ -68133,9 +68919,9 @@ function migrateRetiredApiBaseUrls(deps = {}) {
68133
68919
  const d = defaultDeps(deps);
68134
68920
  const results = [];
68135
68921
  const steps = [
68136
- { run: migrateEcosystemConfig, file: import_node_path32.default.join(d.home, ".mrrlin", "ecosystem.config.cjs") },
68137
- { run: migrateCodexConfig, file: import_node_path32.default.join(d.codexHome, "config.toml") },
68138
- { run: migrateClaudeConfig, file: import_node_path32.default.join(d.home, ".claude.json") }
68922
+ { run: migrateEcosystemConfig, file: import_node_path33.default.join(d.home, ".mrrlin", "ecosystem.config.cjs") },
68923
+ { run: migrateCodexConfig, file: import_node_path33.default.join(d.codexHome, "config.toml") },
68924
+ { run: migrateClaudeConfig, file: import_node_path33.default.join(d.home, ".claude.json") }
68139
68925
  ];
68140
68926
  for (const step of steps) {
68141
68927
  try {
@@ -68161,8 +68947,8 @@ function migrateRetiredApiBaseUrls(deps = {}) {
68161
68947
  }
68162
68948
 
68163
68949
  // src/bridge-health.ts
68164
- var import_node_fs24 = require("node:fs");
68165
- var import_node_path33 = __toESM(require("node:path"), 1);
68950
+ var import_node_fs25 = require("node:fs");
68951
+ var import_node_path34 = __toESM(require("node:path"), 1);
68166
68952
  var SENTINEL_FILE_NAME = "bridge-health-circuit-breaker.json";
68167
68953
  var CRASH_WINDOW_MS = 60 * 60 * 1e3;
68168
68954
  var MAX_CRASHES_PER_WINDOW = 3;
@@ -68174,9 +68960,9 @@ function isCrashSentinel(value) {
68174
68960
  return typeof candidate.crashCount === "number" && Number.isInteger(candidate.crashCount) && candidate.crashCount >= 0 && typeof candidate.windowStartedAt === "string";
68175
68961
  }
68176
68962
  async function readCrashSentinel(stateDir, now = Date.now) {
68177
- const sentinelPath = import_node_path33.default.join(stateDir, SENTINEL_FILE_NAME);
68963
+ const sentinelPath = import_node_path34.default.join(stateDir, SENTINEL_FILE_NAME);
68178
68964
  try {
68179
- const raw = await import_node_fs24.promises.readFile(sentinelPath, "utf8");
68965
+ const raw = await import_node_fs25.promises.readFile(sentinelPath, "utf8");
68180
68966
  const parsed = JSON.parse(raw);
68181
68967
  if (isCrashSentinel(parsed)) return parsed;
68182
68968
  } catch {
@@ -68184,11 +68970,11 @@ async function readCrashSentinel(stateDir, now = Date.now) {
68184
68970
  return { crashCount: 0, windowStartedAt: new Date(now()).toISOString() };
68185
68971
  }
68186
68972
  async function writeCrashSentinel(stateDir, sentinel) {
68187
- await import_node_fs24.promises.mkdir(stateDir, { recursive: true });
68188
- const sentinelPath = import_node_path33.default.join(stateDir, SENTINEL_FILE_NAME);
68973
+ await import_node_fs25.promises.mkdir(stateDir, { recursive: true });
68974
+ const sentinelPath = import_node_path34.default.join(stateDir, SENTINEL_FILE_NAME);
68189
68975
  const tmpPath = `${sentinelPath}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
68190
- await import_node_fs24.promises.writeFile(tmpPath, JSON.stringify(sentinel), "utf8");
68191
- await import_node_fs24.promises.rename(tmpPath, sentinelPath);
68976
+ await import_node_fs25.promises.writeFile(tmpPath, JSON.stringify(sentinel), "utf8");
68977
+ await import_node_fs25.promises.rename(tmpPath, sentinelPath);
68192
68978
  }
68193
68979
  function withTimeout(fn, ms = DEFAULT_OPERATION_TIMEOUT_MS) {
68194
68980
  const controller = new AbortController();
@@ -68515,14 +69301,14 @@ function startSchedulerTickLoop(deps) {
68515
69301
 
68516
69302
  // src/retention/pruner.ts
68517
69303
  var import_promises13 = require("node:fs/promises");
68518
- var import_node_path34 = __toESM(require("node:path"), 1);
69304
+ var import_node_path35 = __toESM(require("node:path"), 1);
68519
69305
  var LOG_DIR_MODE2 = 448;
68520
69306
  var LOG_FILE_MODE2 = 384;
68521
69307
  function protectedDayFloor(protectedSinceMs) {
68522
69308
  return new Date(protectedSinceMs).toISOString().slice(0, 10);
68523
69309
  }
68524
69310
  async function prune(stateDir, bounds) {
68525
- const logsDir = import_node_path34.default.join(stateDir, "logs");
69311
+ const logsDir = import_node_path35.default.join(stateDir, "logs");
68526
69312
  let entries;
68527
69313
  try {
68528
69314
  entries = await (0, import_promises13.readdir)(logsDir);
@@ -68538,7 +69324,7 @@ async function prune(stateDir, bounds) {
68538
69324
  for (const entry of entries) {
68539
69325
  const m = bridgeRe.exec(entry);
68540
69326
  if (!m?.[1]) continue;
68541
- const fullPath = import_node_path34.default.join(logsDir, entry);
69327
+ const fullPath = import_node_path35.default.join(logsDir, entry);
68542
69328
  const s = await (0, import_promises13.stat)(fullPath);
68543
69329
  files.push({ day: m[1], size: s.size, fullPath });
68544
69330
  }
@@ -68547,7 +69333,7 @@ async function prune(stateDir, bounds) {
68547
69333
  const reasonByDay = {};
68548
69334
  let bytesRemoved = 0;
68549
69335
  async function isDaySafeToDelete(day) {
68550
- const telemetryDir = import_node_path34.default.join(stateDir, "telemetry");
69336
+ const telemetryDir = import_node_path35.default.join(stateDir, "telemetry");
68551
69337
  let telemetryEntries;
68552
69338
  try {
68553
69339
  telemetryEntries = await (0, import_promises13.readdir)(telemetryDir);
@@ -68563,7 +69349,7 @@ async function prune(stateDir, bounds) {
68563
69349
  }
68564
69350
  if (projectSlugs.length === 0) return true;
68565
69351
  for (const slug of projectSlugs) {
68566
- const markerPath = import_node_path34.default.join(telemetryDir, `.processed-${slug}-${day}`);
69352
+ const markerPath = import_node_path35.default.join(telemetryDir, `.processed-${slug}-${day}`);
68567
69353
  try {
68568
69354
  await (0, import_promises13.stat)(markerPath);
68569
69355
  } catch (err) {
@@ -68613,7 +69399,7 @@ async function prune(stateDir, bounds) {
68613
69399
  const budgetOvershootBytes = Math.max(0, totalSize2 - budgetBytes);
68614
69400
  await emitPruneLog(stateDir, daysRemoved, reasonByDay, bytesRemoved, oldestDayRemaining);
68615
69401
  if (daysRemoved.length > 0) {
68616
- const sessionsPath = import_node_path34.default.join(logsDir, ".sessions.json");
69402
+ const sessionsPath = import_node_path35.default.join(logsDir, ".sessions.json");
68617
69403
  let sessionsObj = {};
68618
69404
  let fileExists = true;
68619
69405
  try {
@@ -68635,8 +69421,8 @@ async function prune(stateDir, bounds) {
68635
69421
  return { daysRemoved, reasonByDay, bytesRemoved, oldestDayRemaining, budgetOvershootBytes };
68636
69422
  }
68637
69423
  async function emitPruneLog(stateDir, daysRemoved, reasonByDay, bytesRemoved, oldestDayRemaining) {
68638
- const logsDir = import_node_path34.default.join(stateDir, "logs");
68639
- const logPath = import_node_path34.default.join(logsDir, ".pruned.jsonl");
69424
+ const logsDir = import_node_path35.default.join(stateDir, "logs");
69425
+ const logPath = import_node_path35.default.join(logsDir, ".pruned.jsonl");
68640
69426
  await (0, import_promises13.mkdir)(logsDir, { recursive: true, mode: LOG_DIR_MODE2 });
68641
69427
  const record2 = { ts: Date.now(), dir: "logs", daysRemoved, reasonByDay, bytesRemoved, oldestDayRemaining };
68642
69428
  await (0, import_promises13.appendFile)(logPath, `${JSON.stringify(record2)}
@@ -68644,9 +69430,9 @@ async function emitPruneLog(stateDir, daysRemoved, reasonByDay, bytesRemoved, ol
68644
69430
  }
68645
69431
 
68646
69432
  // src/telemetry/turn-aggregator.ts
68647
- var import_node_crypto22 = require("node:crypto");
69433
+ var import_node_crypto23 = require("node:crypto");
68648
69434
  var import_promises14 = require("node:fs/promises");
68649
- var import_node_path35 = require("node:path");
69435
+ var import_node_path36 = require("node:path");
68650
69436
  var BRIDGE_FILE_RE = /^bridge-(\d{4}-\d{2}-\d{2})\.jsonl$/;
68651
69437
  var PLUMBING_COUNTER_KEY = {
68652
69438
  socket_close: "socketCloses",
@@ -68675,7 +69461,7 @@ function inheritSlug(seeds, index) {
68675
69461
  return (preceding ?? following)?.slug;
68676
69462
  }
68677
69463
  async function foldClosedDays(stateDir, today) {
68678
- const logsDir = (0, import_node_path35.join)(stateDir, "logs");
69464
+ const logsDir = (0, import_node_path36.join)(stateDir, "logs");
68679
69465
  let entries;
68680
69466
  try {
68681
69467
  entries = await (0, import_promises14.readdir)(logsDir);
@@ -68687,7 +69473,7 @@ async function foldClosedDays(stateDir, today) {
68687
69473
  if (!m) continue;
68688
69474
  const day = m[1];
68689
69475
  if (day === today) continue;
68690
- const raw = await (0, import_promises14.readFile)((0, import_node_path35.join)(logsDir, entry), "utf8");
69476
+ const raw = await (0, import_promises14.readFile)((0, import_node_path36.join)(logsDir, entry), "utf8");
68691
69477
  const groups = /* @__PURE__ */ new Map();
68692
69478
  let groupCounter = 0;
68693
69479
  for (const line of raw.split("\n")) {
@@ -68798,11 +69584,11 @@ async function foldClosedDays(stateDir, today) {
68798
69584
  rowsByProject.set(slug, rows);
68799
69585
  }
68800
69586
  if (rowsByProject.size === 0) continue;
68801
- const telemetryDir = (0, import_node_path35.join)(stateDir, "telemetry");
69587
+ const telemetryDir = (0, import_node_path36.join)(stateDir, "telemetry");
68802
69588
  await (0, import_promises14.mkdir)(telemetryDir, { recursive: true });
68803
69589
  for (const [slug, rows] of rowsByProject) {
68804
- const finalPath = (0, import_node_path35.join)(telemetryDir, `rows-${slug}-${day}.jsonl`);
68805
- const tmpPath = `${finalPath}.tmp-${process.pid}-${(0, import_node_crypto22.randomBytes)(6).toString("hex")}`;
69590
+ const finalPath = (0, import_node_path36.join)(telemetryDir, `rows-${slug}-${day}.jsonl`);
69591
+ const tmpPath = `${finalPath}.tmp-${process.pid}-${(0, import_node_crypto23.randomBytes)(6).toString("hex")}`;
68806
69592
  try {
68807
69593
  await (0, import_promises14.writeFile)(tmpPath, rows.map((r) => JSON.stringify(r)).join("\n") + "\n", "utf8");
68808
69594
  await (0, import_promises14.rename)(tmpPath, finalPath);
@@ -68816,27 +69602,27 @@ async function foldClosedDays(stateDir, today) {
68816
69602
 
68817
69603
  // src/telemetry/daily-uploader.ts
68818
69604
  var import_promises15 = require("node:fs/promises");
68819
- var import_node_path37 = require("node:path");
69605
+ var import_node_path38 = require("node:path");
68820
69606
 
68821
69607
  // src/telemetry/installation-id.ts
68822
- var import_node_crypto23 = require("node:crypto");
68823
- var import_node_fs25 = require("node:fs");
68824
- var import_node_path36 = require("node:path");
69608
+ var import_node_crypto24 = require("node:crypto");
69609
+ var import_node_fs26 = require("node:fs");
69610
+ var import_node_path37 = require("node:path");
68825
69611
  var FILE_NAME = "installation-id";
68826
69612
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
68827
69613
  var cache = /* @__PURE__ */ new Map();
68828
69614
  function resolveInstallationId(stateDir) {
68829
69615
  const cached2 = cache.get(stateDir);
68830
69616
  if (cached2 !== void 0) return cached2;
68831
- const path38 = (0, import_node_path36.join)(stateDir, FILE_NAME);
69617
+ const path39 = (0, import_node_path37.join)(stateDir, FILE_NAME);
68832
69618
  let id;
68833
69619
  try {
68834
- id = (0, import_node_fs25.readFileSync)(path38, "utf8").trim();
69620
+ id = (0, import_node_fs26.readFileSync)(path39, "utf8").trim();
68835
69621
  if (!UUID.test(id)) throw new Error("unusable");
68836
69622
  } catch {
68837
- id = (0, import_node_crypto23.randomUUID)();
68838
- (0, import_node_fs25.mkdirSync)((0, import_node_path36.dirname)(path38), { recursive: true });
68839
- (0, import_node_fs25.writeFileSync)(path38, `${id}
69623
+ id = (0, import_node_crypto24.randomUUID)();
69624
+ (0, import_node_fs26.mkdirSync)((0, import_node_path37.dirname)(path39), { recursive: true });
69625
+ (0, import_node_fs26.writeFileSync)(path39, `${id}
68840
69626
  `, "utf8");
68841
69627
  }
68842
69628
  cache.set(stateDir, id);
@@ -68853,7 +69639,7 @@ function truncateCause(err) {
68853
69639
  return `${message.slice(0, MAX_CAUSE_CHARS - 3)}...`;
68854
69640
  }
68855
69641
  async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
68856
- const telemetryDir = (0, import_node_path37.join)(stateDir, "telemetry");
69642
+ const telemetryDir = (0, import_node_path38.join)(stateDir, "telemetry");
68857
69643
  let files;
68858
69644
  try {
68859
69645
  files = await (0, import_promises15.readdir)(telemetryDir);
@@ -68869,14 +69655,14 @@ async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
68869
69655
  const [, projectSlug, day] = match;
68870
69656
  const key = `${projectSlug}\0${day}`;
68871
69657
  const entry = discovered.get(key) ?? { projectSlug, day, rowsPath: null };
68872
- if (rowsMatch) entry.rowsPath = (0, import_node_path37.join)(telemetryDir, file2);
69658
+ if (rowsMatch) entry.rowsPath = (0, import_node_path38.join)(telemetryDir, file2);
68873
69659
  discovered.set(key, entry);
68874
69660
  }
68875
69661
  const today = telemetryDay();
68876
69662
  const pending = [];
68877
69663
  const deferred = [];
68878
69664
  for (const { projectSlug, day, rowsPath } of discovered.values()) {
68879
- const markerPath = (0, import_node_path37.join)(telemetryDir, `.processed-${projectSlug}-${day}`);
69665
+ const markerPath = (0, import_node_path38.join)(telemetryDir, `.processed-${projectSlug}-${day}`);
68880
69666
  if (rowsPath === null && day >= today) {
68881
69667
  try {
68882
69668
  await (0, import_promises15.access)(markerPath);
@@ -68896,7 +69682,7 @@ async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
68896
69682
  const fullUnprocessed = [...pending.map((p) => ({ projectSlug: p.projectSlug, day: p.day })), ...deferred];
68897
69683
  pending.sort((a, b) => a.day.localeCompare(b.day));
68898
69684
  for (const cur of pending) {
68899
- const failurePath = (0, import_node_path37.join)(telemetryDir, `.failed-${cur.projectSlug}-${cur.day}.json`);
69685
+ const failurePath = (0, import_node_path38.join)(telemetryDir, `.failed-${cur.projectSlug}-${cur.day}.json`);
68900
69686
  let failureState = null;
68901
69687
  try {
68902
69688
  const data = await (0, import_promises15.readFile)(failurePath, "utf8");
@@ -68930,7 +69716,7 @@ async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
68930
69716
  }
68931
69717
  const gateCalls = [];
68932
69718
  try {
68933
- const rawGate = await (0, import_promises15.readFile)((0, import_node_path37.join)(telemetryDir, gateFileName(cur.projectSlug, cur.day)), "utf8");
69719
+ const rawGate = await (0, import_promises15.readFile)((0, import_node_path38.join)(telemetryDir, gateFileName(cur.projectSlug, cur.day)), "utf8");
68934
69720
  for (const line of rawGate.split("\n")) {
68935
69721
  if (!line.trim()) continue;
68936
69722
  try {
@@ -69080,8 +69866,8 @@ function setSelectedProvider(value) {
69080
69866
 
69081
69867
  // src/execution-consumer.ts
69082
69868
  var import_node_child_process22 = require("node:child_process");
69083
- var import_node_crypto24 = __toESM(require("node:crypto"), 1);
69084
- var import_node_path38 = __toESM(require("node:path"), 1);
69869
+ var import_node_crypto25 = __toESM(require("node:crypto"), 1);
69870
+ var import_node_path39 = __toESM(require("node:path"), 1);
69085
69871
  var import_node_util5 = require("node:util");
69086
69872
 
69087
69873
  // src/notify-templates.ts
@@ -70872,11 +71658,11 @@ function isBridgeGeneratedArtifact(artifact) {
70872
71658
  return typeof payload === "object" && payload !== null && "event" in payload;
70873
71659
  }
70874
71660
  function newArtifactId() {
70875
- return `EA-${import_node_crypto24.default.randomUUID()}`;
71661
+ return `EA-${import_node_crypto25.default.randomUUID()}`;
70876
71662
  }
70877
71663
  var BLAST_RADIUS_FLOOR_PATTERNS = [/^supabase\/migrations\//, /^packages\/db\/src\/schema\.ts$/];
70878
- function isBlastRadiusFloorPath(path38) {
70879
- return BLAST_RADIUS_FLOOR_PATTERNS.some((re) => re.test(path38));
71664
+ function isBlastRadiusFloorPath(path39) {
71665
+ return BLAST_RADIUS_FLOOR_PATTERNS.some((re) => re.test(path39));
70880
71666
  }
70881
71667
  var execFileAsync3 = (0, import_node_util5.promisify)(import_node_child_process22.execFile);
70882
71668
  async function gitOutput(cwd, args) {
@@ -70990,7 +71776,26 @@ async function gatherContext(client, projectSlug, task, openRunId, rawProjectInp
70990
71776
  const omittedArtifactCount = allArtifacts.length - artifacts.length;
70991
71777
  const events = await client.listTaskEvents(projectSlug, task.id);
70992
71778
  const autonomyEvents = events.filter((event) => event.eventType === "autonomy_set").sort((a, b) => a.createdAt.localeCompare(b.createdAt));
70993
- const noteEvents = events.filter((event) => event.eventType === "note").sort((a, b) => a.createdAt.localeCompare(b.createdAt));
71779
+ let noteEvents = events.filter((event) => event.eventType === "note").sort((a, b) => a.createdAt.localeCompare(b.createdAt));
71780
+ const ambiguousNotes = new Set(noteEvents.flatMap(
71781
+ ({ body }) => body && needsTaskNoteAnswer(body) ? [body] : []
71782
+ ));
71783
+ if (ambiguousNotes.size > 0) {
71784
+ const items = await client.listInboxItems(projectSlug, { kind: "question", taskId: task.id }).catch(() => []);
71785
+ const byNoteBody = /* @__PURE__ */ new Map();
71786
+ for (const item of items) {
71787
+ if (item.kind !== "question" || item.taskId !== task.id || item.status !== "acknowledged" || !item.answer) continue;
71788
+ if (item.origin === "gate" || item.origin === "capability") continue;
71789
+ const body = `Q: ${item.body} A: ${item.answer}`;
71790
+ if (!ambiguousNotes.has(body)) continue;
71791
+ const previous = byNoteBody.get(body);
71792
+ byNoteBody.set(body, previous === null || previous && previous.answer !== item.answer ? null : { question: item.body, answer: item.answer });
71793
+ }
71794
+ noteEvents = noteEvents.map((event) => {
71795
+ const questionAnswer = event.body ? byNoteBody.get(event.body) : void 0;
71796
+ return questionAnswer ? { ...event, questionAnswer } : event;
71797
+ });
71798
+ }
70994
71799
  let specMarkdown = verifiedSpecMarkdown ?? null;
70995
71800
  if (verifiedSpecMarkdown === void 0 && task.specWikiPageId) {
70996
71801
  try {
@@ -71126,7 +71931,7 @@ async function readApprovedMixedCodeSpec(client, projectSlug, runId, runApproval
71126
71931
  if (!matches(task)) throw changed();
71127
71932
  const read = async () => {
71128
71933
  const page = await client.getWikiPage(projectSlug, runApproval.specPageId);
71129
- if (page.id !== runApproval.specPageId || page.folder !== "Specs" || page.taskId !== task.id || page.specReady !== true || import_node_crypto24.default.createHash("sha256").update(page.markdownBody, "utf8").digest("hex") !== runApproval.specContentHash) {
71934
+ if (page.id !== runApproval.specPageId || page.folder !== "Specs" || page.taskId !== task.id || page.specReady !== true || import_node_crypto25.default.createHash("sha256").update(page.markdownBody, "utf8").digest("hex") !== runApproval.specContentHash) {
71130
71935
  throw changed();
71131
71936
  }
71132
71937
  const current2 = await client.getTask(projectSlug, task.id);
@@ -71262,7 +72067,7 @@ async function driveRun(deps, projectSlug, runId) {
71262
72067
  if (!claimed) return;
71263
72068
  if (!claimed.leaseId) {
71264
72069
  await deps.client.createInboxItem(projectSlug, {
71265
- id: `II-${import_node_crypto24.default.randomUUID()}`,
72070
+ id: `II-${import_node_crypto25.default.randomUUID()}`,
71266
72071
  kind: "handoff",
71267
72072
  taskId: claimed.taskId,
71268
72073
  body: `Execution run ${runId} was claimed but returned no leaseId. This indicates DB/API corruption and requires operator attention.`
@@ -72438,7 +73243,7 @@ ${workInstruction}` : workInstruction;
72438
73243
  taskId: task.id,
72439
73244
  runId,
72440
73245
  outcome: "completed",
72441
- nonce: import_node_crypto24.default.randomUUID(),
73246
+ nonce: import_node_crypto25.default.randomUUID(),
72442
73247
  artifacts: []
72443
73248
  }
72444
73249
  );
@@ -72935,7 +73740,7 @@ async function driveNonCodeRun(deps, projectSlug, runId, leaseId, task, domain2,
72935
73740
  taskId: task.id,
72936
73741
  runId,
72937
73742
  outcome: parsedResult.outcome,
72938
- nonce: import_node_crypto24.default.randomUUID(),
73743
+ nonce: import_node_crypto25.default.randomUUID(),
72939
73744
  artifacts: [
72940
73745
  {
72941
73746
  artifactId: pageId,
@@ -73292,12 +74097,26 @@ async function deliverLocalRun(deps, input) {
73292
74097
  localBuild: outcome.evidence
73293
74098
  };
73294
74099
  const artifactId = `EA-LG-${runId}-${outcome.evidence.headSha.slice(0, 12)}`;
74100
+ const outcomeHeadSha = outcome.evidence.headSha;
74101
+ const gitSettlementBinding = {
74102
+ object_format: outcomeHeadSha.length === 64 ? "sha256" : "sha1",
74103
+ source_base_oid: input.baseSha,
74104
+ base_oid: input.integration?.defaultTipSha ?? input.baseSha,
74105
+ head_oid: outcomeHeadSha,
74106
+ target_ref: `refs/heads/${input.defaultBranch}`,
74107
+ run_ref: `refs/heads/${worktreeBranch(runId)}`,
74108
+ checkout_digest: outcome.evidence.checkoutDigest
74109
+ };
73295
74110
  let artifact;
73296
74111
  try {
73297
74112
  artifact = await deps.client.appendExecutionArtifact(projectSlug, runId, {
73298
74113
  id: artifactId,
73299
74114
  kind: "verification",
73300
- payload: { [LOCAL_BUILD_RECEIPT_PAYLOAD_KEY]: receipt, deliveryRef: outcome.deliveryRef }
74115
+ payload: {
74116
+ [LOCAL_BUILD_RECEIPT_PAYLOAD_KEY]: receipt,
74117
+ deliveryRef: outcome.deliveryRef,
74118
+ gitSettlement: gitSettlementBinding
74119
+ }
73301
74120
  });
73302
74121
  } catch (error51) {
73303
74122
  const existing = await deps.client.listExecutionArtifacts(projectSlug, runId).catch(() => []);
@@ -73306,74 +74125,127 @@ async function deliverLocalRun(deps, input) {
73306
74125
  await handOff(`local_delivery_failed: could not record the build receipt: ${error51 instanceof Error ? error51.message : String(error51)}`);
73307
74126
  return;
73308
74127
  }
74128
+ const foundPayload = found.payload;
74129
+ const foundBuildReceipt = foundPayload?.[LOCAL_BUILD_RECEIPT_PAYLOAD_KEY];
74130
+ const foundGitSettlement = foundPayload?.gitSettlement ?? foundPayload?.gitBinding ?? foundPayload?.git;
74131
+ if (foundPayload?.deliveryRef !== outcome.deliveryRef || foundBuildReceipt?.evidenceValue !== outcome.evidence.headSha || foundBuildReceipt?.localBuild?.headSha !== outcome.evidence.headSha || foundBuildReceipt?.localBuild?.baseSha !== outcome.evidence.baseSha || foundGitSettlement && (foundGitSettlement.head_oid !== outcome.evidence.headSha || foundGitSettlement.base_oid !== (input.integration?.defaultTipSha ?? input.baseSha))) {
74132
+ await handOff(`local_delivery_failed: artifact ${artifactId} already exists with different payload bindings`);
74133
+ return;
74134
+ }
73309
74135
  artifact = found;
73310
74136
  }
73311
- if (!deps.signingProvider) {
73312
- await handOff(`closure_signing_unavailable: run ${runId} delivered ${outcome.deliveryRef} with a green bridge-run build, but this bridge has no receipt signing key (MRRLIN_SIGNING_KEY_ID / MRRLIN_SIGNING_PRIVATE_KEY), so the task cannot be closed. Configure signing and restart the run.`);
73313
- return;
73314
- }
73315
- const stored = artifact?.payload ?? {};
73316
- const contentHash = String(stored.contentHash ?? stored.content_hash ?? stored.hash ?? "");
73317
74137
  if (!await runHasLease(deps, projectSlug, runId, leaseId)) {
73318
74138
  await restoreForLostLease();
73319
74139
  return;
73320
74140
  }
73321
- const finalizeUnanswered = { seen: false };
73322
- await input.guard?.check();
73323
- try {
73324
- await orchestrateSettlementClosure(
73325
- {
73326
- prepareSettlementCandidate: (slug, params) => deps.client.prepareSettlementCandidate(slug, params),
73327
- signingProvider: deps.signingProvider,
73328
- finalizeSettlementReceipt: (slug, params) => finalizeWithReplay(
73329
- deps,
73330
- { projectSlug, runId, taskId: task.id, unanswered: finalizeUnanswered },
73331
- async () => {
74141
+ const stateDir = deps.stateDir ?? resolveStateDir();
74142
+ const existingJournals = findSettlementJournalsSync(stateDir, projectSlug, runId);
74143
+ let journal = existingJournals.find((j) => j.artifactId === (artifact?.id ?? artifactId)) ?? null;
74144
+ if (!journal) {
74145
+ journal = createSettlementJournal({
74146
+ stateDir,
74147
+ projectSlug,
74148
+ taskId: task.id,
74149
+ runId,
74150
+ idempotencyKey: import_node_crypto25.default.randomUUID(),
74151
+ artifactId: artifact?.id ?? artifactId,
74152
+ leaseId
74153
+ });
74154
+ }
74155
+ let verifiedSettlement = null;
74156
+ if (!deps.signingProvider) {
74157
+ try {
74158
+ await input.guard?.check();
74159
+ verifiedSettlement = await orchestrateLocalGitSettlementClosure(
74160
+ {
74161
+ issueLocalGitSettlement: async (slug, rId, params, options) => {
73332
74162
  await input.guard?.check();
73333
- return deps.client.finalizeSettlementReceipt(slug, params);
73334
- }
73335
- )
73336
- },
73337
- {
73338
- projectSlug,
73339
- taskId: task.id,
73340
- runId,
73341
- outcome: "completed",
73342
- nonce: import_node_crypto24.default.randomUUID(),
73343
- artifacts: [{ artifactId: artifact?.id ?? artifactId, storageVersion: "1", contentHash, kind: "verification" }]
73344
- }
73345
- );
73346
- } catch (error51) {
73347
- if (error51 instanceof MixedCodeApprovalError) throw error51;
73348
- const message = error51 instanceof Error ? error51.message : String(error51);
73349
- const settlement = await readSettlementState(deps, projectSlug, task.id, runId, SETTLEMENT_READBACK_ATTEMPTS);
73350
- if (!settlement || settlement.taskStatus !== "closed_done" || !settlement.runDone) {
73351
- if (!settlement && finalizeUnanswered.seen) {
73352
- console.warn(JSON.stringify({
73353
- event: "settlement_outcome_unknown",
74163
+ return deps.client.issueLocalGitSettlement(slug, rId, params, options);
74164
+ },
74165
+ getLocalGitSettlement: (slug, rId, key) => deps.client.getLocalGitSettlement(slug, rId, key),
74166
+ getJwks: deps.client.getJwks ? () => deps.client.getJwks() : void 0,
74167
+ journal,
74168
+ stateDir,
74169
+ retrySleep: deps.settlementRetrySleep
74170
+ },
74171
+ {
73354
74172
  projectSlug,
73355
74173
  runId,
73356
- taskId: task.id,
73357
- headSha: outcome.evidence.headSha,
73358
- deliveryRef: outcome.deliveryRef,
73359
- error: message,
73360
- next: `Once the API answers: if ${task.id} is closed_done, ask the Director to apply run ${runId} (apply_local_run); otherwise the run is handed off or requeued as usual.`
73361
- }));
73362
- }
74174
+ leaseId,
74175
+ evidence: { artifactId: artifact?.id ?? artifactId },
74176
+ expectedGit: {
74177
+ headOid: outcome.evidence.headSha,
74178
+ baseOid: input.integration?.defaultTipSha ?? input.baseSha,
74179
+ targetRef: `refs/heads/${input.defaultBranch}`,
74180
+ runRef: `refs/heads/${worktreeBranch(runId)}`,
74181
+ checkoutDigest: outcome.evidence.checkoutDigest
74182
+ }
74183
+ }
74184
+ );
74185
+ } catch (error51) {
74186
+ if (error51 instanceof MixedCodeApprovalError) throw error51;
74187
+ const message = error51 instanceof Error ? error51.message : String(error51);
73363
74188
  await handOff(`local_delivery_settlement_failed: ${message}`);
73364
74189
  return;
73365
74190
  }
73366
- console.warn(JSON.stringify({
73367
- event: "settlement_outcome_recovered",
73368
- projectSlug,
73369
- runId,
73370
- taskId: task.id,
73371
- error: message
73372
- }));
74191
+ } else {
74192
+ const stored = artifact?.payload ?? {};
74193
+ const contentHash = String(stored.contentHash ?? stored.content_hash ?? stored.hash ?? "");
74194
+ const finalizeUnanswered = { seen: false };
74195
+ await input.guard?.check();
74196
+ try {
74197
+ await orchestrateSettlementClosure(
74198
+ {
74199
+ prepareSettlementCandidate: (slug, params) => deps.client.prepareSettlementCandidate(slug, params),
74200
+ signingProvider: deps.signingProvider,
74201
+ finalizeSettlementReceipt: (slug, params) => finalizeWithReplay(deps, { projectSlug, runId, taskId: task.id, unanswered: finalizeUnanswered }, async () => {
74202
+ await input.guard?.check();
74203
+ return deps.client.finalizeSettlementReceipt(slug, params);
74204
+ })
74205
+ },
74206
+ {
74207
+ projectSlug,
74208
+ taskId: task.id,
74209
+ runId,
74210
+ outcome: "completed",
74211
+ nonce: import_node_crypto25.default.randomUUID(),
74212
+ artifacts: [{ artifactId: artifact?.id ?? artifactId, storageVersion: "1", contentHash, kind: "verification" }]
74213
+ }
74214
+ );
74215
+ } catch (error51) {
74216
+ if (error51 instanceof MixedCodeApprovalError) throw error51;
74217
+ const message = error51 instanceof Error ? error51.message : String(error51);
74218
+ const settlement = await readSettlementState(deps, projectSlug, task.id, runId, SETTLEMENT_READBACK_ATTEMPTS);
74219
+ if (!settlement || settlement.taskStatus !== "closed_done" || !settlement.runDone) {
74220
+ if (!settlement && finalizeUnanswered.seen) {
74221
+ console.warn(JSON.stringify({
74222
+ event: "settlement_outcome_unknown",
74223
+ projectSlug,
74224
+ runId,
74225
+ taskId: task.id,
74226
+ headSha: outcome.evidence.headSha,
74227
+ deliveryRef: outcome.deliveryRef,
74228
+ error: message,
74229
+ next: `Once the API answers: if ${task.id} is closed_done, ask the Director to apply run ${runId} (apply_local_run); otherwise the run is handed off or requeued as usual.`
74230
+ }));
74231
+ }
74232
+ await handOff(`local_delivery_settlement_failed: ${message}`);
74233
+ return;
74234
+ }
74235
+ console.warn(JSON.stringify({
74236
+ event: "settlement_outcome_recovered",
74237
+ projectSlug,
74238
+ runId,
74239
+ taskId: task.id,
74240
+ error: message
74241
+ }));
74242
+ }
73373
74243
  }
73374
74244
  if (input.delivery) input.delivery.settled = true;
73375
74245
  const locksDir = deps.locksDir ?? "/tmp/mrrlin-locks";
73376
- const headSha = outcome.evidence.headSha;
74246
+ const headSha = verifiedSettlement ? verifiedSettlement.git.head_oid : outcome.evidence.headSha;
74247
+ const expectedOldSha = verifiedSettlement ? verifiedSettlement.git.base_oid : input.integration ? input.integration.defaultTipSha : void 0;
74248
+ const runBranchGuardRef = verifiedSettlement ? verifiedSettlement.git.run_ref : `refs/heads/${worktreeBranch(runId)}`;
73377
74249
  const logLanding = (event, extra) => console.warn(JSON.stringify({ event, projectSlug, runId, taskId: task.id, headSha, ...extra }));
73378
74250
  logLanding("landing_started", { defaultBranch: input.defaultBranch });
73379
74251
  let settledLease;
@@ -73411,16 +74283,73 @@ async function deliverLocalRun(deps, input) {
73411
74283
  defaultBranch: input.defaultBranch,
73412
74284
  headSha,
73413
74285
  hooksDir,
73414
- // The tip the run was integrated with: any other tip (even an ancestor after a user's reset)
73415
- // is default_branch_moved, never fast-forwarded over.
73416
- ...input.integration ? { expectedOldSha: input.integration.defaultTipSha } : {},
73417
- // Land only while the run branch still ends at the head that was just signed.
73418
- runBranchGuard: { ref: `refs/heads/${worktreeBranch(runId)}`, sha: headSha }
74286
+ expectedOldSha,
74287
+ runBranchGuard: { ref: runBranchGuardRef, sha: headSha },
74288
+ onLandingPrepared: (info) => {
74289
+ if (journal) {
74290
+ journal = updateSettlementJournalSync(stateDir, journal, {
74291
+ phase: "landing_prepared",
74292
+ landing: {
74293
+ baseOid: info.baseOid,
74294
+ headOid: info.headOid,
74295
+ targetRef: info.targetRef,
74296
+ runRef: info.runRef,
74297
+ checkoutDigest: verifiedSettlement?.git.checkout_digest ?? outcome.evidence.checkoutDigest,
74298
+ holders: info.holders
74299
+ }
74300
+ });
74301
+ }
74302
+ },
74303
+ onRefUpdated: () => {
74304
+ if (journal) {
74305
+ journal = updateSettlementJournalSync(stateDir, journal, {
74306
+ phase: "ref_updated"
74307
+ });
74308
+ }
74309
+ },
74310
+ onFilesSynced: () => {
74311
+ if (journal) {
74312
+ if (journal.landing) {
74313
+ journal.landing.holders.forEach((h) => {
74314
+ h.synced = true;
74315
+ });
74316
+ }
74317
+ journal = updateSettlementJournalSync(stateDir, journal, {
74318
+ phase: "files_synced",
74319
+ landing: journal.landing
74320
+ });
74321
+ }
74322
+ }
73419
74323
  })
73420
74324
  );
73421
74325
  } catch (error51) {
73422
74326
  landing = { applied: false, reason: "ff_failed", detail: error51 instanceof Error ? error51.message : String(error51) };
73423
74327
  }
74328
+ if ((landing.applied || landing.reason === "already_applied") && verifiedSettlement && typeof deps.client.acknowledgeLocalGitLanding === "function") {
74329
+ if (journal) {
74330
+ journal = updateSettlementJournalSync(stateDir, journal, { phase: "ack_pending" });
74331
+ }
74332
+ try {
74333
+ await deps.client.acknowledgeLocalGitLanding(projectSlug, runId, {
74334
+ receiptId: verifiedSettlement.receipt.receiptId,
74335
+ headOid: verifiedSettlement.git.head_oid,
74336
+ baseOid: verifiedSettlement.git.base_oid,
74337
+ targetRef: verifiedSettlement.git.target_ref,
74338
+ checkoutDigest: verifiedSettlement.git.checkout_digest
74339
+ });
74340
+ if (journal) {
74341
+ journal = updateSettlementJournalSync(stateDir, journal, { phase: "complete" });
74342
+ }
74343
+ } catch (ackError) {
74344
+ console.warn(JSON.stringify({
74345
+ event: "landing_ack_failed",
74346
+ projectSlug,
74347
+ runId,
74348
+ receiptId: verifiedSettlement.receipt.receiptId,
74349
+ error: ackError instanceof Error ? ackError.message : String(ackError)
74350
+ }));
74351
+ }
74352
+ }
73424
74353
  logLanding("landing_result", {
73425
74354
  outcome: landing.applied ? "applied" : landing.reason,
73426
74355
  ...landing.applied ? { previousSha: landing.previousSha } : { detail: landing.detail }
@@ -73666,7 +74595,7 @@ async function reconcileTaskAwaitingMerge(deps, projectSlug, task, runId, reason
73666
74595
  }
73667
74596
  try {
73668
74597
  await deps.client.createInboxItem(projectSlug, {
73669
- id: `II-${import_node_crypto24.default.randomUUID()}`,
74598
+ id: `II-${import_node_crypto25.default.randomUUID()}`,
73670
74599
  kind: "handoff",
73671
74600
  taskId: task.id,
73672
74601
  body: `Task ${task.id} (${task.title}) still needs operator follow-up: ${reason}. Mrrlin could not move the task back to Handoff needed automatically.`
@@ -73701,7 +74630,7 @@ async function notifyOperatorHandoff(deps, projectSlug, task, runId, reason) {
73701
74630
  }
73702
74631
  try {
73703
74632
  await deps.client.createInboxItem(projectSlug, {
73704
- id: `II-${import_node_crypto24.default.randomUUID()}`,
74633
+ id: `II-${import_node_crypto25.default.randomUUID()}`,
73705
74634
  kind: "handoff",
73706
74635
  taskId: task.id,
73707
74636
  body: `Execution run ${runId} for task ${task.id} (${task.title}) needs operator attention: ${reason}`
@@ -73858,8 +74787,8 @@ async function runBackstopSweep(deps, drive = (slug, id) => driveRun(deps, slug,
73858
74787
  function isRunRecoverableByThisBridge(run3, worktreeRoot) {
73859
74788
  if (!worktreeRoot) return true;
73860
74789
  if (!run3.worktreeId) return true;
73861
- const relative = import_node_path38.default.relative(import_node_path38.default.resolve(worktreeRoot), import_node_path38.default.resolve(run3.worktreeId));
73862
- return relative === "" || relative.length > 0 && !relative.startsWith("..") && !import_node_path38.default.isAbsolute(relative);
74790
+ const relative = import_node_path39.default.relative(import_node_path39.default.resolve(worktreeRoot), import_node_path39.default.resolve(run3.worktreeId));
74791
+ return relative === "" || relative.length > 0 && !relative.startsWith("..") && !import_node_path39.default.isAbsolute(relative);
73863
74792
  }
73864
74793
  async function deployGateHandoff(deps, projectSlug, task, runId, reason, leaseId, reasonCode) {
73865
74794
  const isRollbackReconciliation = reason.startsWith(`${ROLLBACK_INVOCATION_UNCONFIRMED}:`);
@@ -73886,7 +74815,7 @@ async function deployGateHandoff(deps, projectSlug, task, runId, reason, leaseId
73886
74815
  });
73887
74816
  if (isRollbackReconciliation) return;
73888
74817
  await deps.client.createInboxItem(projectSlug, {
73889
- id: `II-${import_node_crypto24.default.randomUUID()}`,
74818
+ id: `II-${import_node_crypto25.default.randomUUID()}`,
73890
74819
  kind: "handoff",
73891
74820
  taskId: task.id,
73892
74821
  body: `Deploy gate for run ${runId} (task ${task.id} \u2014 ${task.title}) needs operator attention: ${reason}`
@@ -73905,7 +74834,7 @@ function maxLeaseReclaims() {
73905
74834
  }
73906
74835
 
73907
74836
  // src/async-job-consumer.ts
73908
- var import_node_crypto25 = __toESM(require("node:crypto"), 1);
74837
+ var import_node_crypto26 = __toESM(require("node:crypto"), 1);
73909
74838
  var ASYNC_JOB_MAX_ATTEMPTS = 2;
73910
74839
  function ASYNC_UNOWNED_TTL_DAYS() {
73911
74840
  const raw = Number(process.env.MRRLIN_ASYNC_UNOWNED_TTL_DAYS);
@@ -74030,7 +74959,7 @@ async function driveAsyncJob(deps, projectSlug, jobId) {
74030
74959
  const delivery = descriptor2.onComplete(outcome, input);
74031
74960
  if (!delivery.suppressInbox) {
74032
74961
  await deps.client.createInboxItem(projectSlug, {
74033
- id: delivery.id ?? `II-${import_node_crypto25.default.randomUUID()}`,
74962
+ id: delivery.id ?? `II-${import_node_crypto26.default.randomUUID()}`,
74034
74963
  kind: delivery.kind,
74035
74964
  body: delivery.body,
74036
74965
  ...delivery.taskId ? { taskId: delivery.taskId } : {},
@@ -74048,13 +74977,13 @@ async function deriveRequestedHash(client, toolName2, input) {
74048
74977
  if (input.requestedHash) return input.requestedHash;
74049
74978
  if (toolName2 === "run_spec_consensus" && input.pageId) {
74050
74979
  const page = await client.getWikiPage(input.projectSlug, input.pageId);
74051
- return page.contentHash ?? import_node_crypto25.default.createHash("sha256").update(page.markdownBody).digest("hex");
74980
+ return page.contentHash ?? import_node_crypto26.default.createHash("sha256").update(page.markdownBody).digest("hex");
74052
74981
  }
74053
74982
  if (toolName2 === "draft_task_spec" && input.taskId) {
74054
74983
  const task = await client.getTask(input.projectSlug, input.taskId);
74055
- return task.updatedAt ?? import_node_crypto25.default.createHash("sha256").update(JSON.stringify(task)).digest("hex");
74984
+ return task.updatedAt ?? import_node_crypto26.default.createHash("sha256").update(JSON.stringify(task)).digest("hex");
74056
74985
  }
74057
- return import_node_crypto25.default.createHash("sha256").update(JSON.stringify(input)).digest("hex");
74986
+ return import_node_crypto26.default.createHash("sha256").update(JSON.stringify(input)).digest("hex");
74058
74987
  }
74059
74988
  async function runAsyncBackstopSweep(deps, drive = (slug, jobId) => driveAsyncJob(deps, slug, jobId)) {
74060
74989
  const projects = await deps.client.listProjects();
@@ -74080,19 +75009,19 @@ async function runAsyncBackstopSweep(deps, drive = (slug, jobId) => driveAsyncJo
74080
75009
  }
74081
75010
 
74082
75011
  // src/bridge-artifacts.ts
74083
- var import_node_fs26 = __toESM(require("node:fs"), 1);
75012
+ var import_node_fs27 = __toESM(require("node:fs"), 1);
74084
75013
  var import_promises16 = __toESM(require("node:fs/promises"), 1);
74085
- var import_node_path39 = __toESM(require("node:path"), 1);
75014
+ var import_node_path40 = __toESM(require("node:path"), 1);
74086
75015
  var DEFAULT_MAX_ARTIFACTS_BYTES = 500 * 1024 * 1024;
74087
75016
  var DEFAULT_MAX_ARTIFACT_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
74088
75017
  function resolveArtifactsDir(baseStateDir) {
74089
75018
  const stateDir = baseStateDir ?? resolveStateDir();
74090
- return import_node_path39.default.join(stateDir, "artifacts");
75019
+ return import_node_path40.default.join(stateDir, "artifacts");
74091
75020
  }
74092
75021
  function ensureDir(dir) {
74093
- import_node_fs26.default.mkdirSync(dir, { recursive: true, mode: 448 });
75022
+ import_node_fs27.default.mkdirSync(dir, { recursive: true, mode: 448 });
74094
75023
  try {
74095
- import_node_fs26.default.chmodSync(dir, 448);
75024
+ import_node_fs27.default.chmodSync(dir, 448);
74096
75025
  } catch {
74097
75026
  }
74098
75027
  }
@@ -74100,7 +75029,7 @@ function safeArtifactPath(artifactsDir, id) {
74100
75029
  if (!id || typeof id !== "string" || !/^[a-zA-Z0-9_-]+$/.test(id)) {
74101
75030
  throw new Error("Invalid artifact id");
74102
75031
  }
74103
- return import_node_path39.default.join(artifactsDir, `${id}.json`);
75032
+ return import_node_path40.default.join(artifactsDir, `${id}.json`);
74104
75033
  }
74105
75034
  async function writeLocalArtifact(id, payload, baseStateDir) {
74106
75035
  const artifactsDir = resolveArtifactsDir(baseStateDir);
@@ -74143,7 +75072,7 @@ async function cleanArtifacts(baseStateDir, options) {
74143
75072
  let deletedBytes = 0;
74144
75073
  for (const name of entries) {
74145
75074
  if (!name.endsWith(".json")) continue;
74146
- const filePath = import_node_path39.default.join(artifactsDir, name);
75075
+ const filePath = import_node_path40.default.join(artifactsDir, name);
74147
75076
  try {
74148
75077
  const stat3 = await import_promises16.default.stat(filePath);
74149
75078
  if (now - stat3.mtimeMs > maxAgeMs) {
@@ -75688,16 +76617,16 @@ async function handleIntegrationRpc(deps, msg) {
75688
76617
  }
75689
76618
 
75690
76619
  // src/thread-index.ts
75691
- var import_node_fs27 = require("node:fs");
75692
- var import_node_path41 = __toESM(require("node:path"), 1);
76620
+ var import_node_fs28 = require("node:fs");
76621
+ var import_node_path42 = __toESM(require("node:path"), 1);
75693
76622
  function threadIndexPath(stateDir) {
75694
- return import_node_path41.default.join(stateDir, "threads.json");
76623
+ return import_node_path42.default.join(stateDir, "threads.json");
75695
76624
  }
75696
76625
  function loadThreadIndex(stateDir, ttlMs, now) {
75697
76626
  const result = /* @__PURE__ */ new Map();
75698
76627
  let parsed;
75699
76628
  try {
75700
- parsed = JSON.parse((0, import_node_fs27.readFileSync)(threadIndexPath(stateDir), "utf8"));
76629
+ parsed = JSON.parse((0, import_node_fs28.readFileSync)(threadIndexPath(stateDir), "utf8"));
75701
76630
  } catch {
75702
76631
  return result;
75703
76632
  }
@@ -75723,8 +76652,8 @@ function loadThreadIndex(stateDir, ttlMs, now) {
75723
76652
  return result;
75724
76653
  }
75725
76654
  function saveThreadIndex(stateDir, entries) {
75726
- (0, import_node_fs27.mkdirSync)(stateDir, { recursive: true, mode: 448 });
75727
- (0, import_node_fs27.writeFileSync)(threadIndexPath(stateDir), `${JSON.stringify(Object.fromEntries(entries), null, 2)}
76655
+ (0, import_node_fs28.mkdirSync)(stateDir, { recursive: true, mode: 448 });
76656
+ (0, import_node_fs28.writeFileSync)(threadIndexPath(stateDir), `${JSON.stringify(Object.fromEntries(entries), null, 2)}
75728
76657
  `, {
75729
76658
  encoding: "utf8",
75730
76659
  mode: 384
@@ -75860,13 +76789,13 @@ function createToolBusyClock(opts) {
75860
76789
 
75861
76790
  // src/remote-phone-relay.ts
75862
76791
  var import_node_events3 = require("node:events");
75863
- var import_node_fs28 = require("node:fs");
76792
+ var import_node_fs29 = require("node:fs");
75864
76793
  var import_node_os20 = require("node:os");
75865
- var import_node_path42 = require("node:path");
76794
+ var import_node_path43 = require("node:path");
75866
76795
 
75867
76796
  // ../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/esm/cryptoNode.js
75868
76797
  var nc = __toESM(require("node:crypto"), 1);
75869
- var crypto12 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : void 0;
76798
+ var crypto13 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : void 0;
75870
76799
 
75871
76800
  // ../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/esm/utils.js
75872
76801
  function isBytes(a) {
@@ -75921,8 +76850,8 @@ function wrapConstructor(hashCons) {
75921
76850
  return hashC;
75922
76851
  }
75923
76852
  function randomBytes5(bytesLength = 32) {
75924
- if (crypto12 && typeof crypto12.getRandomValues === "function") {
75925
- return crypto12.getRandomValues(new Uint8Array(bytesLength));
76853
+ if (crypto13 && typeof crypto13.getRandomValues === "function") {
76854
+ return crypto13.getRandomValues(new Uint8Array(bytesLength));
75926
76855
  }
75927
76856
  throw new Error("crypto.getRandomValues must be defined");
75928
76857
  }
@@ -79433,9 +80362,9 @@ var DirectorRelay = class {
79433
80362
 
79434
80363
  // src/remote-phone-relay.ts
79435
80364
  function loadOrCreateAgentDeviceKey() {
79436
- const path38 = (0, import_node_path42.join)((0, import_node_os20.homedir)(), ".mrrlin", "agent-device-key");
80365
+ const path39 = (0, import_node_path43.join)((0, import_node_os20.homedir)(), ".mrrlin", "agent-device-key");
79437
80366
  try {
79438
- const raw = JSON.parse((0, import_node_fs28.readFileSync)(path38, "utf8"));
80367
+ const raw = JSON.parse((0, import_node_fs29.readFileSync)(path39, "utf8"));
79439
80368
  if (typeof raw.priv === "string" && typeof raw.pub === "string") {
79440
80369
  return { privateKey: fromBase64Url(raw.priv), publicKey: fromBase64Url(raw.pub) };
79441
80370
  }
@@ -79443,9 +80372,9 @@ function loadOrCreateAgentDeviceKey() {
79443
80372
  }
79444
80373
  const kp = generateIdentityKeyPair();
79445
80374
  try {
79446
- (0, import_node_fs28.mkdirSync)((0, import_node_path42.join)((0, import_node_os20.homedir)(), ".mrrlin"), { recursive: true });
79447
- (0, import_node_fs28.writeFileSync)(
79448
- path38,
80375
+ (0, import_node_fs29.mkdirSync)((0, import_node_path43.join)((0, import_node_os20.homedir)(), ".mrrlin"), { recursive: true });
80376
+ (0, import_node_fs29.writeFileSync)(
80377
+ path39,
79449
80378
  JSON.stringify({ priv: toBase64Url(kp.privateKey), pub: toBase64Url(kp.publicKey) }),
79450
80379
  { mode: 384 }
79451
80380
  );
@@ -79453,10 +80382,10 @@ function loadOrCreateAgentDeviceKey() {
79453
80382
  }
79454
80383
  return kp;
79455
80384
  }
79456
- var AGENT_PAIRING_PATH = (0, import_node_path42.join)((0, import_node_os20.homedir)(), ".mrrlin", "agent-pairing.json");
80385
+ var AGENT_PAIRING_PATH = (0, import_node_path43.join)((0, import_node_os20.homedir)(), ".mrrlin", "agent-pairing.json");
79457
80386
  function loadAgentPairing() {
79458
80387
  try {
79459
- const raw = JSON.parse((0, import_node_fs28.readFileSync)(AGENT_PAIRING_PATH, "utf8"));
80388
+ const raw = JSON.parse((0, import_node_fs29.readFileSync)(AGENT_PAIRING_PATH, "utf8"));
79460
80389
  if (typeof raw.channelId === "string" && typeof raw.agentControlSecret === "string" && typeof raw.relayAuth === "string" && typeof raw.peerIdentityKey === "string") {
79461
80390
  return {
79462
80391
  channelId: raw.channelId,
@@ -79471,8 +80400,8 @@ function loadAgentPairing() {
79471
80400
  }
79472
80401
  function saveAgentPairing(record2) {
79473
80402
  try {
79474
- (0, import_node_fs28.mkdirSync)((0, import_node_path42.join)((0, import_node_os20.homedir)(), ".mrrlin"), { recursive: true });
79475
- (0, import_node_fs28.writeFileSync)(AGENT_PAIRING_PATH, JSON.stringify(record2), { mode: 384 });
80403
+ (0, import_node_fs29.mkdirSync)((0, import_node_path43.join)((0, import_node_os20.homedir)(), ".mrrlin"), { recursive: true });
80404
+ (0, import_node_fs29.writeFileSync)(AGENT_PAIRING_PATH, JSON.stringify(record2), { mode: 384 });
79476
80405
  } catch {
79477
80406
  }
79478
80407
  }
@@ -79821,10 +80750,10 @@ var import_node_http3 = __toESM(require("node:http"), 1);
79821
80750
  var import_node_https3 = __toESM(require("node:https"), 1);
79822
80751
  var import_node_net3 = __toESM(require("node:net"), 1);
79823
80752
  var import_node_tls = __toESM(require("node:tls"), 1);
79824
- var import_node_fs29 = __toESM(require("node:fs"), 1);
80753
+ var import_node_fs30 = __toESM(require("node:fs"), 1);
79825
80754
  var import_node_os21 = __toESM(require("node:os"), 1);
79826
- var import_node_path43 = __toESM(require("node:path"), 1);
79827
- var import_node_crypto26 = __toESM(require("node:crypto"), 1);
80755
+ var import_node_path44 = __toESM(require("node:path"), 1);
80756
+ var import_node_crypto27 = __toESM(require("node:crypto"), 1);
79828
80757
  var import_node_zlib = __toESM(require("node:zlib"), 1);
79829
80758
 
79830
80759
  // src/verification-egress-policy.ts
@@ -80167,29 +81096,29 @@ function createBrokerSocketPath(runId, nonce, baseDirs = process.platform === "w
80167
81096
  for (const base of baseDirs) {
80168
81097
  let dir;
80169
81098
  try {
80170
- dir = import_node_fs29.default.mkdtempSync(import_node_path43.default.join(base, "mrrlin-b-"));
81099
+ dir = import_node_fs30.default.mkdtempSync(import_node_path44.default.join(base, "mrrlin-b-"));
80171
81100
  } catch {
80172
81101
  continue;
80173
81102
  }
80174
- const socketPath = import_node_path43.default.join(dir, fileName);
81103
+ const socketPath = import_node_path44.default.join(dir, fileName);
80175
81104
  if (process.platform === "win32" || Buffer.byteLength(socketPath) <= MAX_UNIX_SOCKET_PATH_BYTES) {
80176
- import_node_fs29.default.chmodSync(dir, 448);
81105
+ import_node_fs30.default.chmodSync(dir, 448);
80177
81106
  return { dir, socketPath };
80178
81107
  }
80179
- import_node_fs29.default.rmSync(dir, { recursive: true, force: true });
81108
+ import_node_fs30.default.rmSync(dir, { recursive: true, force: true });
80180
81109
  }
80181
81110
  throw new Error(`BROKER_SOCKET_ERROR: no temp directory gives a socket path within ${MAX_UNIX_SOCKET_PATH_BYTES} bytes`);
80182
81111
  }
80183
81112
  async function createVerificationBrokerSession(options) {
80184
- const nonce = import_node_crypto26.default.randomBytes(16).toString("hex");
81113
+ const nonce = import_node_crypto27.default.randomBytes(16).toString("hex");
80185
81114
  let createdDir = null;
80186
81115
  let socketPath = options.socketPath;
80187
81116
  if (!socketPath) {
80188
81117
  ({ dir: createdDir, socketPath } = createBrokerSocketPath(options.runId, nonce));
80189
81118
  }
80190
81119
  try {
80191
- if (import_node_fs29.default.existsSync(socketPath)) {
80192
- import_node_fs29.default.unlinkSync(socketPath);
81120
+ if (import_node_fs30.default.existsSync(socketPath)) {
81121
+ import_node_fs30.default.unlinkSync(socketPath);
80193
81122
  }
80194
81123
  } catch {
80195
81124
  }
@@ -80477,12 +81406,12 @@ async function createVerificationBrokerSession(options) {
80477
81406
  } catch (err) {
80478
81407
  server.close();
80479
81408
  try {
80480
- if (import_node_fs29.default.existsSync(socketPath)) import_node_fs29.default.unlinkSync(socketPath);
81409
+ if (import_node_fs30.default.existsSync(socketPath)) import_node_fs30.default.unlinkSync(socketPath);
80481
81410
  } catch (error51) {
80482
81411
  }
80483
81412
  if (createdDir) {
80484
81413
  try {
80485
- import_node_fs29.default.rmSync(createdDir, { recursive: true, force: true });
81414
+ import_node_fs30.default.rmSync(createdDir, { recursive: true, force: true });
80486
81415
  } catch (error51) {
80487
81416
  }
80488
81417
  }
@@ -80510,14 +81439,14 @@ async function createVerificationBrokerSession(options) {
80510
81439
  server.close(() => resolve3());
80511
81440
  });
80512
81441
  try {
80513
- if (import_node_fs29.default.existsSync(socketPath)) {
80514
- import_node_fs29.default.unlinkSync(socketPath);
81442
+ if (import_node_fs30.default.existsSync(socketPath)) {
81443
+ import_node_fs30.default.unlinkSync(socketPath);
80515
81444
  }
80516
81445
  } catch {
80517
81446
  }
80518
81447
  if (createdDir) {
80519
81448
  try {
80520
- import_node_fs29.default.rmSync(createdDir, { recursive: true, force: true });
81449
+ import_node_fs30.default.rmSync(createdDir, { recursive: true, force: true });
80521
81450
  } catch {
80522
81451
  }
80523
81452
  }
@@ -80986,9 +81915,9 @@ function createRunVerificationTurn(deps) {
80986
81915
  }
80987
81916
 
80988
81917
  // src/director-reseed.ts
80989
- var import_node_fs30 = require("node:fs");
81918
+ var import_node_fs31 = require("node:fs");
80990
81919
  var import_node_readline3 = require("node:readline");
80991
- var import_node_path44 = require("node:path");
81920
+ var import_node_path45 = require("node:path");
80992
81921
  function estimateTokens(s) {
80993
81922
  return Buffer.byteLength(s, "utf8");
80994
81923
  }
@@ -81137,9 +82066,9 @@ async function readSessionRows(logsDir, files, sessionIds) {
81137
82066
  const lines2 = [];
81138
82067
  let missingFiles = 0;
81139
82068
  for (const f of files) {
81140
- const filePath = (0, import_node_path44.join)(logsDir, f);
82069
+ const filePath = (0, import_node_path45.join)(logsDir, f);
81141
82070
  try {
81142
- const stream = (0, import_node_fs30.createReadStream)(filePath, { encoding: "utf8" });
82071
+ const stream = (0, import_node_fs31.createReadStream)(filePath, { encoding: "utf8" });
81143
82072
  const rl = (0, import_node_readline3.createInterface)({ input: stream, crlfDelay: Infinity });
81144
82073
  try {
81145
82074
  for await (const line of rl) {
@@ -81163,10 +82092,10 @@ async function readSessionRows(logsDir, files, sessionIds) {
81163
82092
  }
81164
82093
 
81165
82094
  // src/external-agents-prune.ts
81166
- var import_node_fs31 = require("node:fs");
82095
+ var import_node_fs32 = require("node:fs");
81167
82096
  var import_promises19 = __toESM(require("node:fs/promises"), 1);
81168
82097
  var import_node_os22 = __toESM(require("node:os"), 1);
81169
- var import_node_path45 = __toESM(require("node:path"), 1);
82098
+ var import_node_path46 = __toESM(require("node:path"), 1);
81170
82099
  var toml5 = __toESM(require_toml(), 1);
81171
82100
  var LEGACY_EXTERNAL_AGENTS_TOOL_NAMES = [
81172
82101
  "dispatch",
@@ -81219,8 +82148,8 @@ async function realPathOr(file2) {
81219
82148
  }
81220
82149
  }
81221
82150
  function resolveCodexConfigPath(options) {
81222
- const codexHome = options.codexHome ?? (options.homeDir ? import_node_path45.default.join(options.homeDir, ".codex") : process.env.CODEX_HOME ?? import_node_path45.default.join(import_node_os22.default.homedir(), ".codex"));
81223
- return import_node_path45.default.join(codexHome, "config.toml");
82151
+ const codexHome = options.codexHome ?? (options.homeDir ? import_node_path46.default.join(options.homeDir, ".codex") : process.env.CODEX_HOME ?? import_node_path46.default.join(import_node_os22.default.homedir(), ".codex"));
82152
+ return import_node_path46.default.join(codexHome, "config.toml");
81224
82153
  }
81225
82154
  async function pruneCodexExternalAgents(options) {
81226
82155
  const configPath = await realPathOr(resolveCodexConfigPath(options));
@@ -81254,13 +82183,13 @@ async function pruneJsonMcpEntry(client, file2, binPath) {
81254
82183
  return { ...absent, status: "pruned" };
81255
82184
  }
81256
82185
  async function pruneClaudeExternalAgents(options) {
81257
- const file2 = options.claudeConfigPath ?? import_node_path45.default.join(options.homeDir ?? import_node_os22.default.homedir(), ".claude.json");
82186
+ const file2 = options.claudeConfigPath ?? import_node_path46.default.join(options.homeDir ?? import_node_os22.default.homedir(), ".claude.json");
81258
82187
  return pruneJsonMcpEntry("claude", file2, options.binPath);
81259
82188
  }
81260
82189
  async function pruneAgyExternalAgents(options) {
81261
82190
  const home = options.homeDir ?? import_node_os22.default.homedir();
81262
- const mcpFile = options.agyConfigPath ?? import_node_path45.default.join(home, ".gemini", "config", "mcp_config.json");
81263
- const configJsonPath = options.configJsonPath ?? import_node_path45.default.join(home, ".gemini", "config", "config.json");
82191
+ const mcpFile = options.agyConfigPath ?? import_node_path46.default.join(home, ".gemini", "config", "mcp_config.json");
82192
+ const configJsonPath = options.configJsonPath ?? import_node_path46.default.join(home, ".gemini", "config", "config.json");
81264
82193
  const result = await pruneJsonMcpEntry("agy", mcpFile, options.binPath);
81265
82194
  if (result.status !== "pruned") return result;
81266
82195
  const raw = await readIfExists(configJsonPath);
@@ -81300,10 +82229,10 @@ function runningBinPaths(argv1, resolveOpts) {
81300
82229
  const out = /* @__PURE__ */ new Set();
81301
82230
  const add2 = (p) => {
81302
82231
  if (!p) return;
81303
- const resolved = import_node_path45.default.resolve(p);
82232
+ const resolved = import_node_path46.default.resolve(p);
81304
82233
  out.add(resolved);
81305
82234
  try {
81306
- out.add((0, import_node_fs31.realpathSync)(resolved));
82235
+ out.add((0, import_node_fs32.realpathSync)(resolved));
81307
82236
  } catch {
81308
82237
  }
81309
82238
  };
@@ -81382,7 +82311,7 @@ function addBridgeModel(target, model) {
81382
82311
  }
81383
82312
  function readTextIfExists(filePath) {
81384
82313
  try {
81385
- return import_node_fs32.default.readFileSync(filePath, "utf8");
82314
+ return import_node_fs33.default.readFileSync(filePath, "utf8");
81386
82315
  } catch {
81387
82316
  return null;
81388
82317
  }
@@ -81393,9 +82322,9 @@ function readKnownGptSlugsFromTomlFile(filePath) {
81393
82322
  return Array.from(raw.matchAll(/^\s*model\s*=\s*"([^"]+)"/gm)).map((match) => match[1]?.trim() ?? "").filter(isSelectableModelSlug);
81394
82323
  }
81395
82324
  function readCodexFallbackModels() {
81396
- const codexHome = process.env.CODEX_HOME?.trim() || import_node_path46.default.join(import_node_os23.default.homedir(), ".codex");
82325
+ const codexHome = process.env.CODEX_HOME?.trim() || import_node_path47.default.join(import_node_os23.default.homedir(), ".codex");
81397
82326
  const models = /* @__PURE__ */ new Map();
81398
- const cachePath = import_node_path46.default.join(codexHome, "models_cache.json");
82327
+ const cachePath = import_node_path47.default.join(codexHome, "models_cache.json");
81399
82328
  const cacheRaw = readTextIfExists(cachePath);
81400
82329
  if (cacheRaw) {
81401
82330
  try {
@@ -81445,7 +82374,7 @@ function readCodexFallbackModels() {
81445
82374
  );
81446
82375
  }
81447
82376
  }
81448
- for (const slug of readKnownGptSlugsFromTomlFile(import_node_path46.default.join(codexHome, "config.toml"))) {
82377
+ for (const slug of readKnownGptSlugsFromTomlFile(import_node_path47.default.join(codexHome, "config.toml"))) {
81449
82378
  addBridgeModel(
81450
82379
  models,
81451
82380
  mapBridgeModel({
@@ -81459,11 +82388,11 @@ function readCodexFallbackModels() {
81459
82388
  })
81460
82389
  );
81461
82390
  }
81462
- const automationsDir = import_node_path46.default.join(codexHome, "automations");
82391
+ const automationsDir = import_node_path47.default.join(codexHome, "automations");
81463
82392
  try {
81464
- for (const entry of import_node_fs32.default.readdirSync(automationsDir, { withFileTypes: true })) {
82393
+ for (const entry of import_node_fs33.default.readdirSync(automationsDir, { withFileTypes: true })) {
81465
82394
  if (!entry.isDirectory()) continue;
81466
- for (const slug of readKnownGptSlugsFromTomlFile(import_node_path46.default.join(automationsDir, entry.name, "automation.toml"))) {
82395
+ for (const slug of readKnownGptSlugsFromTomlFile(import_node_path47.default.join(automationsDir, entry.name, "automation.toml"))) {
81467
82396
  addBridgeModel(
81468
82397
  models,
81469
82398
  mapBridgeModel({
@@ -81483,16 +82412,16 @@ function readCodexFallbackModels() {
81483
82412
  return [...models.values()];
81484
82413
  }
81485
82414
  function selfUpdateInboxItemId(offeredVersion) {
81486
- if (!offeredVersion) return `II-MCPUPD-${(0, import_node_crypto27.randomUUID)()}`;
82415
+ if (!offeredVersion) return `II-MCPUPD-${(0, import_node_crypto28.randomUUID)()}`;
81487
82416
  if (/^[A-Za-z0-9._-]+$/.test(offeredVersion)) return `II-MCPUPD-${offeredVersion}`;
81488
- const hash3 = import_node_crypto27.default.createHash("sha256").update(offeredVersion).digest("hex").slice(0, 10);
82417
+ const hash3 = import_node_crypto28.default.createHash("sha256").update(offeredVersion).digest("hex").slice(0, 10);
81489
82418
  return `II-MCPUPD-${offeredVersion.replace(/[^A-Za-z0-9._-]/g, "-")}-${hash3}`;
81490
82419
  }
81491
82420
  function neutralCheckoutCwd(stateDir) {
81492
- const dir = import_node_path46.default.join(stateDir, "no-checkout");
82421
+ const dir = import_node_path47.default.join(stateDir, "no-checkout");
81493
82422
  try {
81494
- import_node_fs32.default.mkdirSync(dir, { recursive: true });
81495
- if (!import_node_fs32.default.existsSync(import_node_path46.default.join(dir, ".git"))) {
82423
+ import_node_fs33.default.mkdirSync(dir, { recursive: true });
82424
+ if (!import_node_fs33.default.existsSync(import_node_path47.default.join(dir, ".git"))) {
81496
82425
  try {
81497
82426
  (0, import_node_child_process25.spawnSync)("git", ["init", "-b", "main"], { cwd: dir, stdio: "ignore" });
81498
82427
  } catch {
@@ -82079,7 +83008,7 @@ async function runOrphanWorktreeSweep(client, opts) {
82079
83008
  const cutoff = Date.now() - worktreeRetentionMs();
82080
83009
  const isReapable = (worktreePath) => {
82081
83010
  try {
82082
- return import_node_fs32.default.statSync(worktreePath).mtimeMs < cutoff;
83011
+ return import_node_fs33.default.statSync(worktreePath).mtimeMs < cutoff;
82083
83012
  } catch {
82084
83013
  return false;
82085
83014
  }
@@ -82115,6 +83044,136 @@ async function runOrphanWorktreeSweep(client, opts) {
82115
83044
  );
82116
83045
  }
82117
83046
  }
83047
+ await recoverPendingSettlementJournals(client, opts);
83048
+ }
83049
+ async function recoverSingleLanding(client, checkoutPath, projectSlug, runId, receipt, locksDir, journal, stateDir) {
83050
+ if (!receipt || !client.getJwks) return false;
83051
+ const targetKeyId = receipt.signingKeyId ?? receipt.signing_key_id;
83052
+ const jwks = await client.getJwks().catch(() => null);
83053
+ const activeKey = jwks?.keys?.find((k) => k.kid === targetKeyId);
83054
+ if (!activeKey?.x) {
83055
+ return false;
83056
+ }
83057
+ const canonicalPayload = receipt.canonicalPayload ?? receipt.payload;
83058
+ if (!canonicalPayload || !receipt.signature) {
83059
+ return false;
83060
+ }
83061
+ if (!verifyReceiptSignature(canonicalPayload, receipt.signature, activeKey.x)) {
83062
+ return false;
83063
+ }
83064
+ const git3 = canonicalPayload?.client_reported?.git;
83065
+ if (!git3 || !git3.head_oid || !git3.base_oid || !git3.target_ref || !git3.checkout_digest) {
83066
+ return false;
83067
+ }
83068
+ const checkoutRealPath = import_node_fs33.default.realpathSync(checkoutPath);
83069
+ const currentCheckoutDigest = import_node_crypto28.default.createHash("sha256").update(checkoutRealPath).digest("hex");
83070
+ if (git3.checkout_digest !== currentCheckoutDigest) {
83071
+ return false;
83072
+ }
83073
+ const expectedRunRef = `refs/heads/mrrlin/run-${runId}`;
83074
+ if (git3.run_ref !== expectedRunRef) {
83075
+ return false;
83076
+ }
83077
+ const defaultBranch = resolveLocalDefaultBranch(checkoutRealPath);
83078
+ if (git3.target_ref !== `refs/heads/${defaultBranch}`) {
83079
+ return false;
83080
+ }
83081
+ let success2 = false;
83082
+ await withCheckoutLock(locksDir, deliveryLockKey(checkoutRealPath), async () => {
83083
+ const hooksDir = prepareDisabledGitHooksDir(locksDir, runId);
83084
+ const applyRes = applyLocalRun({
83085
+ checkoutRealPath,
83086
+ defaultBranch,
83087
+ headSha: git3.head_oid,
83088
+ expectedOldSha: git3.base_oid,
83089
+ hooksDir,
83090
+ runBranchGuard: { ref: expectedRunRef, sha: git3.head_oid },
83091
+ recoveryContext: journal ? {
83092
+ phase: journal.phase,
83093
+ holders: journal.landing?.holders
83094
+ } : void 0
83095
+ });
83096
+ if (applyRes.applied || applyRes.reason === "already_applied") {
83097
+ if (client.acknowledgeLocalGitLanding) {
83098
+ await client.acknowledgeLocalGitLanding(projectSlug, runId, {
83099
+ receiptId: receipt.receiptId,
83100
+ headOid: git3.head_oid,
83101
+ baseOid: git3.base_oid,
83102
+ targetRef: git3.target_ref,
83103
+ checkoutDigest: git3.checkout_digest
83104
+ });
83105
+ }
83106
+ if (journal && stateDir) {
83107
+ updateSettlementJournalSync(stateDir, journal, { phase: "complete" });
83108
+ }
83109
+ success2 = true;
83110
+ }
83111
+ });
83112
+ return success2;
83113
+ }
83114
+ async function recoverPendingSettlementJournals(client, opts) {
83115
+ const stateDir = resolveStateDir(process.env);
83116
+ const pendingJournals = listPendingSettlementJournalsSync(stateDir);
83117
+ const locksDir = import_node_path47.default.join(stateDir, "locks");
83118
+ for (const journal of pendingJournals) {
83119
+ const checkout = opts.checkoutRegistry.get(journal.projectSlug);
83120
+ if (!checkout) continue;
83121
+ if (!journal.receipt && client.getLocalGitSettlement && journal.idempotencyKey) {
83122
+ const lookup = await client.getLocalGitSettlement(journal.projectSlug, journal.runId, journal.idempotencyKey).catch(() => null);
83123
+ if (lookup && "data" in lookup && "receipt" in lookup.data) {
83124
+ journal.receipt = lookup.data.receipt;
83125
+ updateSettlementJournalSync(stateDir, journal, { receipt: journal.receipt, phase: "receipt_saved" });
83126
+ }
83127
+ }
83128
+ if (!journal.receipt) continue;
83129
+ try {
83130
+ await recoverSingleLanding(
83131
+ client,
83132
+ checkout.path,
83133
+ journal.projectSlug,
83134
+ journal.runId,
83135
+ journal.receipt,
83136
+ locksDir,
83137
+ journal,
83138
+ stateDir
83139
+ );
83140
+ } catch {
83141
+ }
83142
+ }
83143
+ try {
83144
+ const projects = await client.listProjects();
83145
+ for (const project of projects) {
83146
+ const checkout = opts.checkoutRegistry.get(project.slug);
83147
+ if (!checkout) continue;
83148
+ if (!client.listPendingLocalGitLandings) continue;
83149
+ const pendingResponse = await client.listPendingLocalGitLandings(project.slug).catch(() => null);
83150
+ if (!Array.isArray(pendingResponse)) continue;
83151
+ for (const landing of pendingResponse) {
83152
+ if (landing.state !== "receipt_issued") continue;
83153
+ const journals = findSettlementJournalsSync(stateDir, project.slug, landing.runId);
83154
+ const idempotencyKey = journals.find((j) => j.idempotencyKey)?.idempotencyKey;
83155
+ if (!idempotencyKey) continue;
83156
+ const lookup = await client.getLocalGitSettlement(project.slug, landing.runId, idempotencyKey).catch(() => null);
83157
+ if (!lookup || !("data" in lookup) || !("receipt" in lookup.data)) continue;
83158
+ const settlement = lookup.data;
83159
+ const journal = journals.find((j) => j.receipt?.receiptId === settlement.receipt.receiptId);
83160
+ try {
83161
+ await recoverSingleLanding(
83162
+ client,
83163
+ checkout.path,
83164
+ project.slug,
83165
+ landing.runId,
83166
+ settlement.receipt,
83167
+ locksDir,
83168
+ journal,
83169
+ stateDir
83170
+ );
83171
+ } catch {
83172
+ }
83173
+ }
83174
+ }
83175
+ } catch {
83176
+ }
82118
83177
  }
82119
83178
  function readStateDir() {
82120
83179
  return resolveStateDir(process.env);
@@ -82228,7 +83287,7 @@ function createBridgeRequestListener(opts) {
82228
83287
  res.end(JSON.stringify({ ok: false, error: "Origin not allowed." }));
82229
83288
  return;
82230
83289
  }
82231
- const nonce = import_node_crypto27.default.randomBytes(16).toString("base64url");
83290
+ const nonce = import_node_crypto28.default.randomBytes(16).toString("base64url");
82232
83291
  res.writeHead(200, { "content-type": "application/json" });
82233
83292
  const publicHost = host === "0.0.0.0" ? "127.0.0.1" : host;
82234
83293
  res.end(JSON.stringify({ ok: true, wsUrl: `ws://${publicHost}:${port}/ws`, token, nonce }));
@@ -82513,7 +83572,7 @@ function createBridgeMessageHandler(deps) {
82513
83572
  }
82514
83573
  }
82515
83574
  socket.on("message", async (data) => {
82516
- const spanId = import_node_crypto27.default.randomUUID();
83575
+ const spanId = import_node_crypto28.default.randomUUID();
82517
83576
  if (logCtx) {
82518
83577
  logCtx.span.id = spanId;
82519
83578
  logCtx.span.at = Date.now();
@@ -82710,7 +83769,7 @@ function createBridgeMessageHandler(deps) {
82710
83769
  return;
82711
83770
  }
82712
83771
  if (typeof msg.type === "string" && isIntegrationRpcType(msg.type)) {
82713
- const store = deps.connectionStore ?? new LocalConnectionStore(deps.stateDir ?? import_node_path46.default.join(import_node_os23.default.homedir(), ".mrrlin"));
83772
+ const store = deps.connectionStore ?? new LocalConnectionStore(deps.stateDir ?? import_node_path47.default.join(import_node_os23.default.homedir(), ".mrrlin"));
82714
83773
  const allowLocal = process.env.NODE_ENV !== "production" && (process.env.NODE_ENV === "test" || process.env.MRRLIN_ALLOW_LOCAL_ENDPOINTS === "1");
82715
83774
  const rawMsg = msg;
82716
83775
  const msgProjectSlug = typeof rawMsg.projectSlug === "string" ? rawMsg.projectSlug : typeof rawMsg.context?.projectSlug === "string" ? rawMsg.context.projectSlug : void 0;
@@ -82992,7 +84051,7 @@ function createBridgeMessageHandler(deps) {
82992
84051
  let desiredInstructionHash = null;
82993
84052
  try {
82994
84053
  const startParams = deps.buildStartParams(msg, desiredModel);
82995
- desiredInstructionHash = import_node_crypto27.default.createHash("sha256").update(startParams.baseInstructions ?? "").digest("hex");
84054
+ desiredInstructionHash = import_node_crypto28.default.createHash("sha256").update(startParams.baseInstructions ?? "").digest("hex");
82996
84055
  if (!thread) {
82997
84056
  const newThread = {
82998
84057
  threadId: "",
@@ -83073,7 +84132,7 @@ function createBridgeMessageHandler(deps) {
83073
84132
  thread.inFlight = true;
83074
84133
  pendingTurnSessions.delete(directorSessionId);
83075
84134
  thread.replay = createReplayBuffer({
83076
- turnId: (0, import_node_crypto27.randomUUID)(),
84135
+ turnId: (0, import_node_crypto28.randomUUID)(),
83077
84136
  spanId,
83078
84137
  ...deps.retentionMs !== void 0 ? { retentionMs: deps.retentionMs } : {},
83079
84138
  ...deps.ackLingerMs !== void 0 ? { ackLingerMs: deps.ackLingerMs } : {}
@@ -83708,23 +84767,10 @@ function createSelectedProviderRefresher(deps) {
83708
84767
  }
83709
84768
  });
83710
84769
  }
83711
- var envSigningProvider;
83712
84770
  function buildBridgeSigningProvider() {
83713
- const signingKeyId = process.env.MRRLIN_SIGNING_KEY_ID;
83714
- const signingPrivateKey = process.env.MRRLIN_SIGNING_PRIVATE_KEY;
83715
84771
  delete process.env.MRRLIN_SIGNING_PRIVATE_KEY;
83716
- if (signingKeyId && signingPrivateKey) {
83717
- envSigningProvider = new LocalEd25519SigningProvider({
83718
- keyId: signingKeyId,
83719
- privateKey: signingPrivateKey
83720
- });
83721
- return envSigningProvider;
83722
- }
83723
- if (signingKeyId && envSigningProvider?.getKeyId() === signingKeyId) {
83724
- return envSigningProvider;
83725
- }
83726
- const isTestOrSmoke = process.env.NODE_ENV === "test" || process.env.MRRLIN_TEST === "1" || process.env.MRRLIN_SMOKE_TEST === "1";
83727
- if (isTestOrSmoke) {
84772
+ const isExplicitTest = process.env.NODE_ENV === "test" || process.env.MRRLIN_TEST === "1" || process.env.MRRLIN_SMOKE_TEST === "1";
84773
+ if (isExplicitTest) {
83728
84774
  return new LocalEd25519SigningProvider({
83729
84775
  keyId: FIXTURE_SIGNING_KEY_ID,
83730
84776
  privateKey: FIXTURE_PRIVATE_KEY_BASE64
@@ -83915,10 +84961,10 @@ async function startDirectorBridge(startupDeps = {}) {
83915
84961
  codexCwd: config2.codexCwd,
83916
84962
  codexExecutable: config2.codexExecutable,
83917
84963
  checkoutRegistry,
83918
- worktreeRoot: import_node_path46.default.join(config2.stateDir, "worktrees"),
83919
- locksDir: import_node_path46.default.join(config2.stateDir, "locks"),
84964
+ worktreeRoot: import_node_path47.default.join(config2.stateDir, "worktrees"),
84965
+ locksDir: import_node_path47.default.join(config2.stateDir, "locks"),
83920
84966
  // local-git-delivery: bridge-local evidence (checkout realpath, build logs) that never leaves this machine.
83921
- localEvidenceDir: import_node_path46.default.join(config2.stateDir, "local-evidence"),
84967
+ localEvidenceDir: import_node_path47.default.join(config2.stateDir, "local-evidence"),
83922
84968
  // Wire the executor server for code-execution runs. Each run gets its own provider process
83923
84969
  // (app-server for codex, a resident CLI child for claude) at the run worktree, running
83924
84970
  // UNRESTRICTED from the real operator config (owner no-sandbox decision — auth + mrrlin MCP
@@ -83935,7 +84981,7 @@ async function startDirectorBridge(startupDeps = {}) {
83935
84981
  // The run's provider process carries exactly its own project (or none), so its Mrrlin MCP
83936
84982
  // server is bound to it and never to whatever the bridge's environment names.
83937
84983
  env: threadProcessEnv(process.env, directorThreadEnv(projectSlug)),
83938
- disabledGitHooksDir: prepareDisabledGitHooksDir(import_node_path46.default.join(config2.stateDir, "locks"), import_node_path46.default.basename(worktreePath)),
84984
+ disabledGitHooksDir: prepareDisabledGitHooksDir(import_node_path47.default.join(config2.stateDir, "locks"), import_node_path47.default.basename(worktreePath)),
83939
84985
  provider: providerId
83940
84986
  });
83941
84987
  return { handle: executor.handle, dispose: executor.dispose };
@@ -83953,7 +84999,7 @@ async function startDirectorBridge(startupDeps = {}) {
83953
84999
  provisionProjectFolder: (projectSlug) => provisionNewProjectFolder(checkoutRegistry, projectSlug, import_node_os23.default.hostname()),
83954
85000
  // Dogfood v2 F-36: an executor thread started under older instructions is not resumed.
83955
85001
  executorThreadInstructions: createExecutorThreadInstructionStore(
83956
- import_node_path46.default.join(config2.stateDir, "executor-thread-instructions.json")
85002
+ import_node_path47.default.join(config2.stateDir, "executor-thread-instructions.json")
83957
85003
  ),
83958
85004
  // ADR 0007 self-review: critique the committed diff on the executor's own agent handle before
83959
85005
  // push/PR. Reuses the collected-turn runner (startThread + collect assistant text).
@@ -83978,10 +85024,10 @@ async function startDirectorBridge(startupDeps = {}) {
83978
85024
  runVerificationTurn: createRunVerificationTurn({
83979
85025
  startSandbox: async (egressDomains, providerId, opts) => {
83980
85026
  opts?.wrapCommand?.(["node"]);
83981
- const scratchDir = import_node_fs32.default.mkdtempSync(import_node_path46.default.join(import_node_os23.default.tmpdir(), "mrrlin-verify-"));
85027
+ const scratchDir = import_node_fs33.default.mkdtempSync(import_node_path47.default.join(import_node_os23.default.tmpdir(), "mrrlin-verify-"));
83982
85028
  const executor = await startExecutorServer({
83983
85029
  worktree: scratchDir,
83984
- disabledGitHooksDir: prepareDisabledGitHooksDir(import_node_path46.default.join(config2.stateDir, "locks"), import_node_path46.default.basename(scratchDir)),
85030
+ disabledGitHooksDir: prepareDisabledGitHooksDir(import_node_path47.default.join(config2.stateDir, "locks"), import_node_path47.default.basename(scratchDir)),
83985
85031
  provider: providerId,
83986
85032
  wrapCommand: opts?.wrapCommand,
83987
85033
  brokerSocket: opts?.brokerSocket,
@@ -83994,7 +85040,7 @@ async function startDirectorBridge(startupDeps = {}) {
83994
85040
  dispose: () => {
83995
85041
  executor.dispose();
83996
85042
  try {
83997
- import_node_fs32.default.rmSync(scratchDir, { recursive: true, force: true });
85043
+ import_node_fs33.default.rmSync(scratchDir, { recursive: true, force: true });
83998
85044
  } catch {
83999
85045
  }
84000
85046
  },
@@ -84028,7 +85074,7 @@ async function startDirectorBridge(startupDeps = {}) {
84028
85074
  };
84029
85075
  const sessionSinks = createSessionSinkRegistry();
84030
85076
  const tombstones = /* @__PURE__ */ new Map();
84031
- const bridgeInstanceId = (0, import_node_crypto27.randomUUID)();
85077
+ const bridgeInstanceId = (0, import_node_crypto28.randomUUID)();
84032
85078
  const asyncConsumerDeps = {
84033
85079
  client,
84034
85080
  run: wrappedTurnLock.run,
@@ -84207,7 +85253,7 @@ async function startDirectorBridge(startupDeps = {}) {
84207
85253
  const files = dayFilesInWindow(/* @__PURE__ */ new Date(), reseedWindowMs);
84208
85254
  filesCount = files.length;
84209
85255
  const sessionIds = [args.directorSessionId, ...args.priorSessionIds];
84210
- const { lines: lines2, missingFiles } = await readSessionRows(import_node_path46.default.join(config2.stateDir, "logs"), files, sessionIds);
85256
+ const { lines: lines2, missingFiles } = await readSessionRows(import_node_path47.default.join(config2.stateDir, "logs"), files, sessionIds);
84211
85257
  missingFilesCount = missingFiles;
84212
85258
  const extracted = extractItems(lines2, sessionIds);
84213
85259
  items = extracted.items;
@@ -84356,7 +85402,7 @@ async function startDirectorBridge(startupDeps = {}) {
84356
85402
  const bridgeLogger = createBridgeLogger(config2.stateDir, process.env);
84357
85403
  let bridgeBinShaShort = "unknown00000";
84358
85404
  try {
84359
- bridgeBinShaShort = import_node_crypto27.default.createHash("sha256").update(import_node_fs32.default.readFileSync(process.argv[1] ?? "")).digest("hex").slice(0, 12);
85405
+ bridgeBinShaShort = import_node_crypto28.default.createHash("sha256").update(import_node_fs33.default.readFileSync(process.argv[1] ?? "")).digest("hex").slice(0, 12);
84360
85406
  } catch {
84361
85407
  }
84362
85408
  attachBridgeWss(server, {
@@ -84497,8 +85543,8 @@ async function startDirectorBridge(startupDeps = {}) {
84497
85543
  );
84498
85544
  void runOrphanWorktreeSweep(client, {
84499
85545
  checkoutRegistry,
84500
- worktreeRoot: import_node_path46.default.join(config2.stateDir, "worktrees"),
84501
- locksDir: import_node_path46.default.join(config2.stateDir, "locks")
85546
+ worktreeRoot: import_node_path47.default.join(config2.stateDir, "worktrees"),
85547
+ locksDir: import_node_path47.default.join(config2.stateDir, "locks")
84502
85548
  });
84503
85549
  {
84504
85550
  const { retainedBuffers, retainedBytes, tombstonesRemoved } = sweepReplayBuffers(threads, tombstones, {
@@ -84591,6 +85637,12 @@ async function startDirectorBridge(startupDeps = {}) {
84591
85637
  }, claimIntervalMs());
84592
85638
  claimTimer.unref?.();
84593
85639
  };
85640
+ void recoverPendingSettlementJournals(client, { checkoutRegistry }).catch((err) => {
85641
+ process.stderr.write(
85642
+ `[mrrlin-mcp director-bridge] startup settlement recovery failed: ${err instanceof Error ? err.message : String(err)}
85643
+ `
85644
+ );
85645
+ });
84594
85646
  if (shouldRunClaimLoop({ hasStaticToken, hasTokenProvider: Boolean(tokenProvider) })) {
84595
85647
  scheduleClaimLoop();
84596
85648
  } else {
@@ -84797,7 +85849,7 @@ function timingSafeTokenEqual(provided, expected) {
84797
85849
  const a = Buffer.from(provided);
84798
85850
  const b = Buffer.from(expected);
84799
85851
  if (a.length !== b.length) return false;
84800
- return import_node_crypto27.default.timingSafeEqual(a, b);
85852
+ return import_node_crypto28.default.timingSafeEqual(a, b);
84801
85853
  }
84802
85854
  function readDispatchBody(req) {
84803
85855
  return new Promise((resolve3, reject) => {
@@ -84819,15 +85871,15 @@ function readDispatchBody(req) {
84819
85871
  function readOrCreateBridgeToken(stateDir) {
84820
85872
  const explicit = (process.env.MRRLIN_DIRECTOR_BRIDGE_TOKEN ?? "").trim();
84821
85873
  if (explicit) return explicit;
84822
- const tokenPath = import_node_path46.default.join(stateDir, "token.txt");
85874
+ const tokenPath = import_node_path47.default.join(stateDir, "token.txt");
84823
85875
  try {
84824
- const existing = import_node_fs32.default.readFileSync(tokenPath, "utf8").trim();
85876
+ const existing = import_node_fs33.default.readFileSync(tokenPath, "utf8").trim();
84825
85877
  if (existing) return existing;
84826
85878
  } catch {
84827
85879
  }
84828
- import_node_fs32.default.mkdirSync(stateDir, { recursive: true, mode: 448 });
84829
- const token = import_node_crypto27.default.randomBytes(32).toString("base64url");
84830
- import_node_fs32.default.writeFileSync(tokenPath, `${token}
85880
+ import_node_fs33.default.mkdirSync(stateDir, { recursive: true, mode: 448 });
85881
+ const token = import_node_crypto28.default.randomBytes(32).toString("base64url");
85882
+ import_node_fs33.default.writeFileSync(tokenPath, `${token}
84831
85883
  `, { mode: 384 });
84832
85884
  return token;
84833
85885
  }
@@ -86275,8 +87327,8 @@ function runSetCredential(args) {
86275
87327
 
86276
87328
  // src/install-service.ts
86277
87329
  var import_node_os24 = __toESM(require("node:os"), 1);
86278
- var import_node_fs33 = require("node:fs");
86279
- var import_node_path47 = __toESM(require("node:path"), 1);
87330
+ var import_node_fs34 = require("node:fs");
87331
+ var import_node_path48 = __toESM(require("node:path"), 1);
86280
87332
  function parseEnvLine(line, env) {
86281
87333
  const trimmed = line.trim();
86282
87334
  if (!trimmed || trimmed === "}" || trimmed === "},") return;
@@ -86665,7 +87717,7 @@ function performConfigBackup(deps, ecoPath, existingText) {
86665
87717
  deps.log("Service config backup failed.");
86666
87718
  return;
86667
87719
  }
86668
- const dir = import_node_path47.default.dirname(ecoPath);
87720
+ const dir = import_node_path48.default.dirname(ecoPath);
86669
87721
  let files;
86670
87722
  try {
86671
87723
  files = deps.listDir(dir);
@@ -86677,7 +87729,7 @@ function performConfigBackup(deps, ecoPath, existingText) {
86677
87729
  deps.log("Service config backup failed.");
86678
87730
  return;
86679
87731
  }
86680
- const base = import_node_path47.default.basename(ecoPath);
87732
+ const base = import_node_path48.default.basename(ecoPath);
86681
87733
  const backupRegex = new RegExp(`^${escapeRegex2(base)}\\.bak-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}Z$`);
86682
87734
  const existingBackups = files.filter((f) => backupRegex.test(f));
86683
87735
  if (existingBackups.length >= 10) {
@@ -86712,7 +87764,7 @@ function performConfigBackup(deps, ecoPath, existingText) {
86712
87764
  var SYSTEM_PATH_DIRS = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];
86713
87765
  function defaultHomeOwnerUid(home) {
86714
87766
  try {
86715
- return (0, import_node_fs33.statSync)(home).uid;
87767
+ return (0, import_node_fs34.statSync)(home).uid;
86716
87768
  } catch {
86717
87769
  return null;
86718
87770
  }
@@ -86779,11 +87831,11 @@ function installService(deps) {
86779
87831
  const agyBin = deps.which("agy");
86780
87832
  const resolvedBins = [...bins, claudeBin, agyBin].filter((b) => b !== null);
86781
87833
  const isWin = import_node_os24.default.platform() === "win32";
86782
- const systemDirs = isWin ? (deps.env.PATH || "").split(import_node_path47.default.delimiter).filter(Boolean) : SYSTEM_PATH_DIRS;
87834
+ const systemDirs = isWin ? (deps.env.PATH || "").split(import_node_path48.default.delimiter).filter(Boolean) : SYSTEM_PATH_DIRS;
86783
87835
  const pathEnv = Array.from(
86784
- /* @__PURE__ */ new Set([...resolvedBins.map((b) => import_node_path47.default.dirname(b)), ...systemDirs])
86785
- ).join(import_node_path47.default.delimiter);
86786
- const ecoPath = import_node_path47.default.join(home, ".mrrlin", "ecosystem.config.cjs");
87836
+ /* @__PURE__ */ new Set([...resolvedBins.map((b) => import_node_path48.default.dirname(b)), ...systemDirs])
87837
+ ).join(import_node_path48.default.delimiter);
87838
+ const ecoPath = import_node_path48.default.join(home, ".mrrlin", "ecosystem.config.cjs");
86787
87839
  const existingText = deps.readFile ? deps.readFile(ecoPath) : null;
86788
87840
  const parseResult = parseExistingEcosystemConfig(existingText);
86789
87841
  if (parseResult.kind === "rejected") {
@@ -86862,13 +87914,13 @@ function uninstallService(deps) {
86862
87914
  // src/uninstall-codex.ts
86863
87915
  var import_promises20 = __toESM(require("node:fs/promises"), 1);
86864
87916
  var import_node_os25 = __toESM(require("node:os"), 1);
86865
- var import_node_path48 = __toESM(require("node:path"), 1);
87917
+ var import_node_path49 = __toESM(require("node:path"), 1);
86866
87918
  var toml6 = __toESM(require_toml(), 1);
86867
87919
  function resolveCodexHome3(options) {
86868
87920
  if (options.codexHome) return options.codexHome;
86869
- if (options.homeDir) return import_node_path48.default.join(options.homeDir, ".codex");
87921
+ if (options.homeDir) return import_node_path49.default.join(options.homeDir, ".codex");
86870
87922
  if (process.env.CODEX_HOME) return process.env.CODEX_HOME;
86871
- return import_node_path48.default.join(import_node_os25.default.homedir(), ".codex");
87923
+ return import_node_path49.default.join(import_node_os25.default.homedir(), ".codex");
86872
87924
  }
86873
87925
  async function pathExists6(target) {
86874
87926
  try {
@@ -86881,7 +87933,7 @@ async function pathExists6(target) {
86881
87933
  var MRRLIN_BLOCK_RE = /(^|\n)\[mcp_servers\.(?:mrrlin(?:-browser)?|external-agents)(?:\]|\.[^\]\n]*\])[\s\S]*?(?=\n\[|$)/g;
86882
87934
  async function uninstallCodex(options = {}) {
86883
87935
  const codexHome = resolveCodexHome3(options);
86884
- const configPath = import_node_path48.default.join(codexHome, "config.toml");
87936
+ const configPath = import_node_path49.default.join(codexHome, "config.toml");
86885
87937
  const removePrompts = async () => uninstallPrompts(codexHome, options.promptNames ?? []);
86886
87938
  if (!await pathExists6(configPath)) {
86887
87939
  return { action: "missing", configPath, prompts: await removePrompts() };
@@ -86909,10 +87961,10 @@ async function uninstallCodex(options = {}) {
86909
87961
  }
86910
87962
  async function uninstallPrompts(codexHome, names) {
86911
87963
  if (names.length === 0) return [];
86912
- const promptsDir = import_node_path48.default.join(codexHome, "prompts");
87964
+ const promptsDir = import_node_path49.default.join(codexHome, "prompts");
86913
87965
  const out = [];
86914
87966
  for (const name of names) {
86915
- const promptPath = import_node_path48.default.join(promptsDir, `${name}.md`);
87967
+ const promptPath = import_node_path49.default.join(promptsDir, `${name}.md`);
86916
87968
  try {
86917
87969
  await import_promises20.default.unlink(promptPath);
86918
87970
  out.push({ name, action: "removed", promptPath });
@@ -87092,32 +88144,32 @@ async function runConnect(argv, deps) {
87092
88144
  }
87093
88145
 
87094
88146
  // src/doctor.ts
87095
- var import_node_fs34 = require("node:fs");
87096
- var import_node_path49 = __toESM(require("node:path"), 1);
88147
+ var import_node_fs35 = require("node:fs");
88148
+ var import_node_path50 = __toESM(require("node:path"), 1);
87097
88149
  var import_semver4 = __toESM(require_semver2(), 1);
87098
88150
  var ISO_TS = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
87099
88151
  var defaultLogFs = {
87100
88152
  listDir: (dir) => {
87101
88153
  try {
87102
- return (0, import_node_fs34.readdirSync)(dir);
88154
+ return (0, import_node_fs35.readdirSync)(dir);
87103
88155
  } catch {
87104
88156
  return null;
87105
88157
  }
87106
88158
  },
87107
88159
  readFile: (p) => {
87108
88160
  try {
87109
- return (0, import_node_fs34.readFileSync)(p, "utf8");
88161
+ return (0, import_node_fs35.readFileSync)(p, "utf8");
87110
88162
  } catch {
87111
88163
  return null;
87112
88164
  }
87113
88165
  }
87114
88166
  };
87115
88167
  function readRecentErrorEntries(stateDir, n, fs18 = defaultLogFs) {
87116
- const logsDir = import_node_path49.default.join(stateDir, "logs");
88168
+ const logsDir = import_node_path50.default.join(stateDir, "logs");
87117
88169
  const names = (fs18.listDir(logsDir) ?? []).filter((name) => name.endsWith(".jsonl")).sort();
87118
88170
  const entries = [];
87119
88171
  for (const name of names) {
87120
- const raw = fs18.readFile(import_node_path49.default.join(logsDir, name));
88172
+ const raw = fs18.readFile(import_node_path50.default.join(logsDir, name));
87121
88173
  if (!raw) continue;
87122
88174
  for (const line of raw.split("\n")) {
87123
88175
  if (!line.trim()) continue;
@@ -87139,7 +88191,7 @@ function readRecentErrorEntries(stateDir, n, fs18 = defaultLogFs) {
87139
88191
  function configChecks(deps) {
87140
88192
  const fix = "mrrlin-mcp configure bridge";
87141
88193
  let claudeOk = false;
87142
- const claudeRaw = deps.readFile(import_node_path49.default.join(deps.homedir, ".claude.json"));
88194
+ const claudeRaw = deps.readFile(import_node_path50.default.join(deps.homedir, ".claude.json"));
87143
88195
  if (claudeRaw) {
87144
88196
  try {
87145
88197
  const parsed = JSON.parse(claudeRaw);
@@ -87148,7 +88200,7 @@ function configChecks(deps) {
87148
88200
  claudeOk = false;
87149
88201
  }
87150
88202
  }
87151
- const codexPath = import_node_path49.default.join(deps.codexHome ?? import_node_path49.default.join(deps.homedir, ".codex"), "config.toml");
88203
+ const codexPath = import_node_path50.default.join(deps.codexHome ?? import_node_path50.default.join(deps.homedir, ".codex"), "config.toml");
87152
88204
  const codexOk = /^\[mcp_servers\.mrrlin\]/m.test(deps.readFile(codexPath) ?? "");
87153
88205
  return [
87154
88206
  {
@@ -87314,17 +88366,17 @@ async function runDoctor(flags, deps) {
87314
88366
  }
87315
88367
 
87316
88368
  // src/launch-agent.ts
87317
- var import_node_path50 = __toESM(require("node:path"), 1);
88369
+ var import_node_path51 = __toESM(require("node:path"), 1);
87318
88370
  var BRIDGE_LAUNCH_AGENT_LABEL = "com.mrrlin.director-bridge";
87319
88371
  function escapeXml(value) {
87320
88372
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
87321
88373
  }
87322
88374
  function bridgeLaunchAgentPath(home) {
87323
- return import_node_path50.default.join(home, "Library", "LaunchAgents", `${BRIDGE_LAUNCH_AGENT_LABEL}.plist`);
88375
+ return import_node_path51.default.join(home, "Library", "LaunchAgents", `${BRIDGE_LAUNCH_AGENT_LABEL}.plist`);
87324
88376
  }
87325
88377
  function renderBridgeLaunchAgent(input) {
87326
88378
  const { home, pm2Path, nodeDir } = input;
87327
- const launchPath = `${nodeDir}:${import_node_path50.default.dirname(pm2Path)}:/usr/bin:/bin`;
88379
+ const launchPath = `${nodeDir}:${import_node_path51.default.dirname(pm2Path)}:/usr/bin:/bin`;
87328
88380
  const logDir = `${home}/.mrrlin/director-bridge`;
87329
88381
  return `<?xml version="1.0" encoding="UTF-8"?>
87330
88382
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -87365,7 +88417,7 @@ function installBridgeLaunchAgent(deps) {
87365
88417
  const plistPath = bridgeLaunchAgentPath(deps.home);
87366
88418
  const domain2 = `gui/${deps.uid}`;
87367
88419
  try {
87368
- deps.mkdirp(import_node_path50.default.dirname(plistPath));
88420
+ deps.mkdirp(import_node_path51.default.dirname(plistPath));
87369
88421
  deps.writeFile(
87370
88422
  plistPath,
87371
88423
  renderBridgeLaunchAgent({ home: deps.home, pm2Path: deps.pm2Path, nodeDir: deps.nodeDir }),
@@ -87395,7 +88447,7 @@ function removeBridgeLaunchAgent(deps) {
87395
88447
 
87396
88448
  // src/extract/command.ts
87397
88449
  var import_promises21 = require("node:fs/promises");
87398
- var import_node_path51 = require("node:path");
88450
+ var import_node_path52 = require("node:path");
87399
88451
  function parseArgs(args) {
87400
88452
  const map2 = /* @__PURE__ */ new Map();
87401
88453
  for (let i = 0; i < args.length; i++) {
@@ -87432,7 +88484,7 @@ Missing required flag(s): ${missing.join(
87432
88484
  const days = await findSessionDays(deps.stateDir, sessionId);
87433
88485
  const matchingLines = [];
87434
88486
  for (const day of days) {
87435
- const logPath = (0, import_node_path51.join)(deps.stateDir, "logs", `bridge-${day}.jsonl`);
88487
+ const logPath = (0, import_node_path52.join)(deps.stateDir, "logs", `bridge-${day}.jsonl`);
87436
88488
  let raw;
87437
88489
  try {
87438
88490
  raw = await (0, import_promises21.readFile)(logPath, "utf8");
@@ -87522,16 +88574,16 @@ function augmentProcessPathWithCommonDirs() {
87522
88574
  if (isWin) return;
87523
88575
  const home = process.env.HOME || (0, import_node_os26.homedir)();
87524
88576
  const candidates = [
87525
- import_node_path53.default.join(home, ".local", "bin"),
87526
- import_node_path53.default.join(home, ".cargo", "bin"),
88577
+ import_node_path54.default.join(home, ".local", "bin"),
88578
+ import_node_path54.default.join(home, ".cargo", "bin"),
87527
88579
  "/usr/local/bin",
87528
88580
  "/opt/homebrew/bin"
87529
88581
  ];
87530
- const existing = (process.env.PATH || "").split(import_node_path53.default.delimiter).filter(Boolean);
88582
+ const existing = (process.env.PATH || "").split(import_node_path54.default.delimiter).filter(Boolean);
87531
88583
  const existingSet = new Set(existing);
87532
- const toAdd = candidates.filter((d) => !existingSet.has(d) && (0, import_node_fs35.existsSync)(d));
88584
+ const toAdd = candidates.filter((d) => !existingSet.has(d) && (0, import_node_fs36.existsSync)(d));
87533
88585
  if (toAdd.length > 0) {
87534
- process.env.PATH = [...existing, ...toAdd].join(import_node_path53.default.delimiter);
88586
+ process.env.PATH = [...existing, ...toAdd].join(import_node_path54.default.delimiter);
87535
88587
  }
87536
88588
  }
87537
88589
  augmentProcessPathWithCommonDirs();
@@ -87551,15 +88603,15 @@ function bootHookStatus() {
87551
88603
  const uid = process.getuid?.();
87552
88604
  if (uid === void 0 || uid === 0) return { status: "unknown" };
87553
88605
  const home = process.env.HOME ?? (0, import_node_os26.homedir)();
87554
- const agents = import_node_path53.default.join(home, "Library", "LaunchAgents");
88606
+ const agents = import_node_path54.default.join(home, "Library", "LaunchAgents");
87555
88607
  const candidates = [
87556
- { label: "com.mrrlin.director-bridge", plist: import_node_path53.default.join(agents, "com.mrrlin.director-bridge.plist") },
87557
- { label: "com.PM2", plist: import_node_path53.default.join(agents, `pm2.${(0, import_node_os26.userInfo)().username}.plist`) }
88608
+ { label: "com.mrrlin.director-bridge", plist: import_node_path54.default.join(agents, "com.mrrlin.director-bridge.plist") },
88609
+ { label: "com.PM2", plist: import_node_path54.default.join(agents, `pm2.${(0, import_node_os26.userInfo)().username}.plist`) }
87558
88610
  ];
87559
88611
  for (const candidate of candidates) {
87560
88612
  const printed = (0, import_node_child_process27.spawnSync)("launchctl", ["print", `gui/${uid}/${candidate.label}`], { encoding: "utf8" });
87561
88613
  if (printed.status !== 0) continue;
87562
- if (!(0, import_node_fs35.existsSync)(candidate.plist)) continue;
88614
+ if (!(0, import_node_fs36.existsSync)(candidate.plist)) continue;
87563
88615
  const out = printed.stdout ?? "";
87564
88616
  const runs = /^\s*runs\s*=\s*(\d+)/m.exec(out);
87565
88617
  const exitCode = /^\s*last exit code\s*=\s*(-?\d+)/m.exec(out);
@@ -87575,16 +88627,16 @@ function realLaunchAgentDeps() {
87575
88627
  home: process.env.HOME ?? (0, import_node_os26.homedir)(),
87576
88628
  uid: process.getuid?.() ?? 0,
87577
88629
  pm2Path: whichBin("pm2") ?? "pm2",
87578
- nodeDir: import_node_path53.default.dirname(process.execPath),
88630
+ nodeDir: import_node_path54.default.dirname(process.execPath),
87579
88631
  mkdirp: (dir) => {
87580
- (0, import_node_fs35.mkdirSync)(dir, { recursive: true });
88632
+ (0, import_node_fs36.mkdirSync)(dir, { recursive: true });
87581
88633
  },
87582
88634
  writeFile: (p, c, mode) => {
87583
- (0, import_node_fs35.mkdirSync)(import_node_path53.default.join(process.env.HOME ?? (0, import_node_os26.homedir)(), ".mrrlin", "director-bridge"), { recursive: true, mode: 448 });
87584
- (0, import_node_fs35.writeFileSync)(p, c, { mode });
87585
- (0, import_node_fs35.chmodSync)(p, mode);
88635
+ (0, import_node_fs36.mkdirSync)(import_node_path54.default.join(process.env.HOME ?? (0, import_node_os26.homedir)(), ".mrrlin", "director-bridge"), { recursive: true, mode: 448 });
88636
+ (0, import_node_fs36.writeFileSync)(p, c, { mode });
88637
+ (0, import_node_fs36.chmodSync)(p, mode);
87586
88638
  },
87587
- removeFile: (p) => (0, import_node_fs35.rmSync)(p, { force: true }),
88639
+ removeFile: (p) => (0, import_node_fs36.rmSync)(p, { force: true }),
87588
88640
  launchctl: (args) => ({ status: (0, import_node_child_process27.spawnSync)("launchctl", args, { encoding: "utf8" }).status })
87589
88641
  };
87590
88642
  }
@@ -87695,7 +88747,7 @@ function realDoctorDeps() {
87695
88747
  verifyReadiness: (provider) => verifyProviderReadiness(provider, runnerFor(provider)),
87696
88748
  readFile: (p) => {
87697
88749
  try {
87698
- return (0, import_node_fs35.readFileSync)(p, "utf8");
88750
+ return (0, import_node_fs36.readFileSync)(p, "utf8");
87699
88751
  } catch {
87700
88752
  return null;
87701
88753
  }
@@ -87980,8 +89032,8 @@ async function main() {
87980
89032
  }
87981
89033
  }
87982
89034
  try {
87983
- const codexHome = process.env.CODEX_HOME ?? import_node_path53.default.join(process.env.HOME ?? (0, import_node_os26.homedir)(), ".codex");
87984
- (0, import_node_fs35.rmSync)(import_node_path53.default.join(codexHome, "prompts", "report-issue.md"), { force: true });
89035
+ const codexHome = process.env.CODEX_HOME ?? import_node_path54.default.join(process.env.HOME ?? (0, import_node_os26.homedir)(), ".codex");
89036
+ (0, import_node_fs36.rmSync)(import_node_path54.default.join(codexHome, "prompts", "report-issue.md"), { force: true });
87985
89037
  } catch {
87986
89038
  }
87987
89039
  const claudeResult = await installClaude({ binPath, force, serveEnv });
@@ -88059,13 +89111,13 @@ async function main() {
88059
89111
  env: process.env,
88060
89112
  cwd: process.cwd(),
88061
89113
  writeFile: (p, c) => {
88062
- (0, import_node_fs35.mkdirSync)(import_node_path53.default.dirname(p), { recursive: true, mode: 448 });
88063
- (0, import_node_fs35.writeFileSync)(p, c, { mode: 384 });
89114
+ (0, import_node_fs36.mkdirSync)(import_node_path54.default.dirname(p), { recursive: true, mode: 448 });
89115
+ (0, import_node_fs36.writeFileSync)(p, c, { mode: 384 });
88064
89116
  },
88065
- writeExclusiveFile: (p, c) => (0, import_node_fs35.writeFileSync)(p, c, { flag: "wx", mode: 384 }),
89117
+ writeExclusiveFile: (p, c) => (0, import_node_fs36.writeFileSync)(p, c, { flag: "wx", mode: 384 }),
88066
89118
  listDir: (p) => {
88067
89119
  try {
88068
- return (0, import_node_fs35.readdirSync)(p);
89120
+ return (0, import_node_fs36.readdirSync)(p);
88069
89121
  } catch {
88070
89122
  return null;
88071
89123
  }
@@ -88076,7 +89128,7 @@ async function main() {
88076
89128
  // value", never a failed install. See readExistingTelemetryDefaultProject.
88077
89129
  readFile: (p) => {
88078
89130
  try {
88079
- return (0, import_node_fs35.readFileSync)(p, "utf8");
89131
+ return (0, import_node_fs36.readFileSync)(p, "utf8");
88080
89132
  } catch {
88081
89133
  return null;
88082
89134
  }
@@ -88097,14 +89149,14 @@ async function main() {
88097
89149
  runPm2: (a) => ({ code: pm2Runner(a).code }),
88098
89150
  removeFile: (p) => {
88099
89151
  try {
88100
- (0, import_node_fs35.rmSync)(p, { force: true });
89152
+ (0, import_node_fs36.rmSync)(p, { force: true });
88101
89153
  } catch {
88102
89154
  }
88103
89155
  },
88104
89156
  purgeSecret: purge,
88105
89157
  secretPath: agentCredentialPath(),
88106
89158
  tokenPath: operatorTokenPath(),
88107
- ecoPath: import_node_path53.default.join(process.env.HOME ?? (0, import_node_os26.homedir)(), ".mrrlin", "ecosystem.config.cjs"),
89159
+ ecoPath: import_node_path54.default.join(process.env.HOME ?? (0, import_node_os26.homedir)(), ".mrrlin", "ecosystem.config.cjs"),
88108
89160
  log: (m) => process.stderr.write(`[mrrlin-mcp uninstall-service] ${m}
88109
89161
  `)
88110
89162
  });
@@ -88119,14 +89171,14 @@ async function main() {
88119
89171
  runPm2: (a) => ({ code: pm2Runner(a).code }),
88120
89172
  removeFile: (p) => {
88121
89173
  try {
88122
- (0, import_node_fs35.rmSync)(p, { force: true });
89174
+ (0, import_node_fs36.rmSync)(p, { force: true });
88123
89175
  } catch {
88124
89176
  }
88125
89177
  },
88126
89178
  purgeSecret: true,
88127
89179
  secretPath: agentCredentialPath(),
88128
89180
  tokenPath: operatorTokenPath(),
88129
- ecoPath: import_node_path53.default.join(home, ".mrrlin", "ecosystem.config.cjs"),
89181
+ ecoPath: import_node_path54.default.join(home, ".mrrlin", "ecosystem.config.cjs"),
88130
89182
  log: log2
88131
89183
  });
88132
89184
  let codexOk = true;
@@ -88146,7 +89198,7 @@ async function main() {
88146
89198
  log2(`codex config NOT modified: ${error51 instanceof Error ? error51.message : String(error51)}`);
88147
89199
  }
88148
89200
  try {
88149
- (0, import_node_fs35.rmSync)(import_node_path53.default.join(home, ".mrrlin"), { recursive: true, force: true });
89201
+ (0, import_node_fs36.rmSync)(import_node_path54.default.join(home, ".mrrlin"), { recursive: true, force: true });
88150
89202
  } catch {
88151
89203
  }
88152
89204
  log2("removed ~/.mrrlin");
@@ -88187,7 +89239,7 @@ ${HELP_TEXT}`);
88187
89239
  }
88188
89240
  }
88189
89241
  function resolveSelfBinPath() {
88190
- return import_node_path52.default.resolve(process.argv[1] ?? process.execPath);
89242
+ return import_node_path53.default.resolve(process.argv[1] ?? process.execPath);
88191
89243
  }
88192
89244
  main().catch((error51) => {
88193
89245
  process.stderr.write(`mrrlin-mcp fatal error: ${error51 instanceof Error ? error51.message : String(error51)}