pi-herdsman 0.31.0 → 0.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -37,7 +37,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
37
37
  // node_modules/graceful-fs/polyfills.js
38
38
  var require_polyfills = __commonJS({
39
39
  "node_modules/graceful-fs/polyfills.js"(exports, module) {
40
- var constants3 = __require("constants");
40
+ var constants4 = __require("constants");
41
41
  var origCwd = process.cwd;
42
42
  var cwd = null;
43
43
  var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
@@ -61,7 +61,7 @@ var require_polyfills = __commonJS({
61
61
  var chdir;
62
62
  module.exports = patch;
63
63
  function patch(fs2) {
64
- if (constants3.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
64
+ if (constants4.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
65
65
  patchLchmod(fs2);
66
66
  }
67
67
  if (!fs2.lutimes) {
@@ -163,7 +163,7 @@ var require_polyfills = __commonJS({
163
163
  fs3.lchmod = function(path, mode, callback) {
164
164
  fs3.open(
165
165
  path,
166
- constants3.O_WRONLY | constants3.O_SYMLINK,
166
+ constants4.O_WRONLY | constants4.O_SYMLINK,
167
167
  mode,
168
168
  function(err, fd) {
169
169
  if (err) {
@@ -179,7 +179,7 @@ var require_polyfills = __commonJS({
179
179
  );
180
180
  };
181
181
  fs3.lchmodSync = function(path, mode) {
182
- var fd = fs3.openSync(path, constants3.O_WRONLY | constants3.O_SYMLINK, mode);
182
+ var fd = fs3.openSync(path, constants4.O_WRONLY | constants4.O_SYMLINK, mode);
183
183
  var threw = true;
184
184
  var ret;
185
185
  try {
@@ -199,9 +199,9 @@ var require_polyfills = __commonJS({
199
199
  };
200
200
  }
201
201
  function patchLutimes(fs3) {
202
- if (constants3.hasOwnProperty("O_SYMLINK") && fs3.futimes) {
202
+ if (constants4.hasOwnProperty("O_SYMLINK") && fs3.futimes) {
203
203
  fs3.lutimes = function(path, at, mt, cb) {
204
- fs3.open(path, constants3.O_SYMLINK, function(er, fd) {
204
+ fs3.open(path, constants4.O_SYMLINK, function(er, fd) {
205
205
  if (er) {
206
206
  if (cb) cb(er);
207
207
  return;
@@ -214,7 +214,7 @@ var require_polyfills = __commonJS({
214
214
  });
215
215
  };
216
216
  fs3.lutimesSync = function(path, at, mt) {
217
- var fd = fs3.openSync(path, constants3.O_SYMLINK);
217
+ var fd = fs3.openSync(path, constants4.O_SYMLINK);
218
218
  var ret;
219
219
  var threw = true;
220
220
  try {
@@ -1627,7 +1627,7 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
1627
1627
  // package.json
1628
1628
  var package_default = {
1629
1629
  name: "pi-herdsman",
1630
- version: "0.31.0",
1630
+ version: "0.31.1",
1631
1631
  type: "module",
1632
1632
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
1633
1633
  license: "Apache-2.0",
@@ -3305,6 +3305,7 @@ ${text}`].join("\n\n");
3305
3305
  constants2.O_RDONLY | constants2.O_NONBLOCK
3306
3306
  );
3307
3307
  const current = fstatSync2(fd);
3308
+ const readVersion = fstatSync2(fd, { bigint: true });
3308
3309
  if (!current.isFile()) throw new Error("not a regular file");
3309
3310
  const verified = options2.verifiedEvidence?.find(
3310
3311
  (entry) => realpathSync(entry.path) === file2.canonicalPath
@@ -3316,6 +3317,12 @@ ${text}`].join("\n\n");
3316
3317
  `Required evidence identity check failed: ${file2.input}`,
3317
3318
  operation
3318
3319
  );
3320
+ if (options2.requireInline)
3321
+ fail(
3322
+ "invalid_request",
3323
+ `Attachment could not be fully embedded within the configured limits: ${file2.input}`,
3324
+ operation
3325
+ );
3319
3326
  continue;
3320
3327
  }
3321
3328
  const cannotInline = current.size > (options2.inlineLimitBytes ?? MAILBOX_PROTOCOL_LIMIT_BYTES) || (options2.fits !== void 0 || options2.serializedBytes === void 0) && !fits(
@@ -3325,7 +3332,15 @@ ${text}`].join("\n\n");
3325
3332
  ${text}`).join("\n\n"),
3326
3333
  resultBindings
3327
3334
  );
3328
- if (cannotInline && !verified) continue;
3335
+ if (cannotInline && !verified) {
3336
+ if (options2.requireInline)
3337
+ fail(
3338
+ "invalid_request",
3339
+ `Attachment could not be fully embedded within the configured limits: ${file2.input}`,
3340
+ operation
3341
+ );
3342
+ continue;
3343
+ }
3329
3344
  bytes = Buffer.allocUnsafe(current.size);
3330
3345
  let offset = 0;
3331
3346
  while (offset < current.size) {
@@ -3339,8 +3354,16 @@ ${text}`).join("\n\n"),
3339
3354
  if (!count) break;
3340
3355
  offset += count;
3341
3356
  }
3342
- if (offset !== current.size || fstatSync2(fd).size !== current.size)
3357
+ const afterRead = fstatSync2(fd, { bigint: true });
3358
+ if (offset !== current.size || afterRead.size !== readVersion.size || afterRead.dev !== readVersion.dev || afterRead.ino !== readVersion.ino || afterRead.mtimeNs !== readVersion.mtimeNs || afterRead.ctimeNs !== readVersion.ctimeNs) {
3359
+ if (options2.requireInline)
3360
+ fail(
3361
+ "invalid_request",
3362
+ `Attachment changed while being read: ${file2.input}`,
3363
+ operation
3364
+ );
3343
3365
  continue;
3366
+ }
3344
3367
  bytes = bytes.subarray(0, offset);
3345
3368
  if (verified && createHash5("sha256").update(bytes).digest("hex") !== verified.sha256)
3346
3369
  fail(
@@ -3348,11 +3371,25 @@ ${text}`).join("\n\n"),
3348
3371
  `Required evidence integrity check failed: ${file2.input}`,
3349
3372
  operation
3350
3373
  );
3351
- if (cannotInline) continue;
3374
+ if (cannotInline) {
3375
+ if (options2.requireInline)
3376
+ fail(
3377
+ "invalid_request",
3378
+ `Attachment could not be fully embedded within the configured limits: ${file2.input}`,
3379
+ operation
3380
+ );
3381
+ continue;
3382
+ }
3352
3383
  } catch (error2) {
3353
3384
  if (error2 instanceof OperationError) throw error2;
3354
3385
  if (resolvedResultPath && error2.code === "ENOENT")
3355
3386
  failUnknownResultRef(file2.input, operation);
3387
+ if (options2.requireInline)
3388
+ fail(
3389
+ "invalid_request",
3390
+ `Attachment could not be fully embedded: ${file2.input}`,
3391
+ operation
3392
+ );
3356
3393
  fail(
3357
3394
  "invalid_request",
3358
3395
  `Cannot read file ${file2.input}: ${error2 instanceof Error ? error2.message : String(error2)}`,
@@ -3361,15 +3398,37 @@ ${text}`).join("\n\n"),
3361
3398
  } finally {
3362
3399
  if (fd !== void 0) closeSync4(fd);
3363
3400
  }
3364
- if (bytes.includes(0)) continue;
3401
+ if (bytes.includes(0)) {
3402
+ if (options2.requireInline)
3403
+ fail(
3404
+ "invalid_request",
3405
+ `Attachment is not supported UTF-8 text: ${file2.input}`,
3406
+ operation
3407
+ );
3408
+ continue;
3409
+ }
3365
3410
  let content;
3366
3411
  try {
3367
3412
  content = new TextDecoder2("utf-8", { fatal: true }).decode(bytes);
3368
3413
  } catch {
3414
+ if (options2.requireInline)
3415
+ fail(
3416
+ "invalid_request",
3417
+ `Attachment is not supported UTF-8 text: ${file2.input}`,
3418
+ operation
3419
+ );
3369
3420
  continue;
3370
3421
  }
3371
3422
  sections[index] = renderMessageFile(file2, content);
3372
- if (!fits(rendered(), resultBindings)) sections[index] = prior;
3423
+ if (!fits(rendered(), resultBindings)) {
3424
+ sections[index] = prior;
3425
+ if (options2.requireInline)
3426
+ fail(
3427
+ "invalid_request",
3428
+ `Attachment could not be fully embedded within the configured limits: ${file2.input}`,
3429
+ operation
3430
+ );
3431
+ }
3373
3432
  }
3374
3433
  return {
3375
3434
  text: rendered(),
@@ -6147,6 +6206,7 @@ import { contentText as contentText2 } from "@earendil-works/pi-ai";
6147
6206
  import { realpathSync as realpathSync3, statSync as statSync5 } from "node:fs";
6148
6207
  import { unlinkSync as unlinkSync8 } from "node:fs";
6149
6208
  import { createHash as createHash9, randomUUID as randomUUID9 } from "node:crypto";
6209
+ import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
6150
6210
  import { homedir as homedir3 } from "node:os";
6151
6211
  import { join as join9, resolve as resolve4 } from "node:path";
6152
6212
  import { setTimeout as delay } from "node:timers/promises";
@@ -9017,15 +9077,18 @@ function updateConfig(key, value2) {
9017
9077
  }
9018
9078
 
9019
9079
  // extension/supervision.ts
9080
+ import { constants as constants3 } from "node:fs";
9020
9081
  import {
9021
9082
  chmodSync as chmodSync7,
9022
9083
  closeSync as closeSync8,
9023
9084
  fsyncSync as fsyncSync4,
9024
9085
  lstatSync as lstatSync4,
9086
+ fstatSync as fstatSync3,
9025
9087
  readdirSync as readdirSync5,
9026
9088
  mkdirSync as mkdirSync8,
9027
9089
  openSync as openSync8,
9028
9090
  readFileSync as readFileSync8,
9091
+ readSync as readSync3,
9029
9092
  statSync as statSync4,
9030
9093
  renameSync as renameSync7,
9031
9094
  unlinkSync as unlinkSync7,
@@ -9063,8 +9126,12 @@ function canMessagePeer(a, b) {
9063
9126
  var COORDINATION_MESSAGE_MAX_BYTES = 8 * 1024;
9064
9127
  var COORDINATION_INBOX_SCAN_LIMIT = 32;
9065
9128
  var CHIEF_DESCRIPTOR_MAX_BYTES = 2048;
9129
+ var COORDINATION_BODY_MAX_BYTES = 1024 * 1024;
9066
9130
  var UUID3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
9067
9131
  var MESSAGE_KINDS = new Set(COORDINATION_MESSAGE_KINDS);
9132
+ function validOverflowBodyRef(value2) {
9133
+ return !!value2 && typeof value2 === "object" && !Array.isArray(value2) && Object.keys(value2).length === 2 && Number.isInteger(value2.bytes) && value2.bytes > 0 && value2.bytes <= COORDINATION_BODY_MAX_BYTES && /^[a-f0-9]{64}$/.test(value2.sha256);
9134
+ }
9068
9135
  function validSession(value2) {
9069
9136
  return typeof value2 === "string" && value2.length > 0 && value2.length <= 512;
9070
9137
  }
@@ -9088,7 +9155,13 @@ function validMessage(value2) {
9088
9155
  "text",
9089
9156
  "createdAt"
9090
9157
  ];
9091
- const optional = ["branch", "resultBindings", "build", "peerSource"];
9158
+ const optional = [
9159
+ "branch",
9160
+ "resultBindings",
9161
+ "build",
9162
+ "peerSource",
9163
+ "bodyRef"
9164
+ ];
9092
9165
  if (Object.keys(record).some(
9093
9166
  (key) => !keys.includes(key) && !optional.includes(key)
9094
9167
  ) || Object.keys(record).length < keys.length || keys.some((key) => !Object.hasOwn(record, key)))
@@ -9104,7 +9177,7 @@ function validMessage(value2) {
9104
9177
  if (projectMessage ? !validNativeIdentity(record.branch) : record.branch !== void 0 && (record.kind !== "manager_message" || !validNativeIdentity(record.branch))) {
9105
9178
  return false;
9106
9179
  }
9107
- return record.version === 2 && (peerMessage ? !!validPeerSource : record.peerSource === void 0) && (record.build === void 0 || isRuntimeBuild(record.build)) && typeof record.id === "string" && UUID3.test(record.id) && typeof record.leaseId === "string" && UUID3.test(record.leaseId) && typeof record.kind === "string" && MESSAGE_KINDS.has(record.kind) && validSession(record.fromSessionId) && validSession(record.toSessionId) && validSession(record.leadSessionId) && typeof record.text === "string" && record.text.length > 0 && (record.resultBindings === void 0 || Array.isArray(record.resultBindings) && record.resultBindings.every(isResultBinding)) && Number.isInteger(record.createdAt) && record.createdAt >= 0;
9180
+ return record.version === 2 && (peerMessage ? !!validPeerSource : record.peerSource === void 0) && (record.build === void 0 || isRuntimeBuild(record.build)) && typeof record.id === "string" && UUID3.test(record.id) && typeof record.leaseId === "string" && UUID3.test(record.leaseId) && typeof record.kind === "string" && MESSAGE_KINDS.has(record.kind) && validSession(record.fromSessionId) && validSession(record.toSessionId) && validSession(record.leadSessionId) && typeof record.text === "string" && (record.bodyRef === void 0 ? record.text.length > 0 : record.text === "" && record.resultBindings === void 0 && validOverflowBodyRef(record.bodyRef)) && (record.resultBindings === void 0 || Array.isArray(record.resultBindings) && record.resultBindings.every(isResultBinding)) && Number.isInteger(record.createdAt) && record.createdAt >= 0;
9108
9181
  }
9109
9182
  function chiefMessageBytes(record) {
9110
9183
  return Buffer.byteLength(`${JSON.stringify(record)}
@@ -9115,6 +9188,19 @@ function assertMessage(value2) {
9115
9188
  if (chiefMessageBytes(value2) > COORDINATION_MESSAGE_MAX_BYTES)
9116
9189
  throw new Error("Chief message record is too large");
9117
9190
  }
9191
+ function compactChiefMessage(record, path) {
9192
+ if (chiefMessageBytes(record) <= COORDINATION_MESSAGE_MAX_BYTES)
9193
+ return record;
9194
+ const bodyRef = writeOverflowBody(`${path}.body`, {
9195
+ text: record.text,
9196
+ ...record.resultBindings ? { resultBindings: record.resultBindings } : {}
9197
+ });
9198
+ const stored = { ...record, text: "", bodyRef };
9199
+ delete stored.resultBindings;
9200
+ if (chiefMessageBytes(stored) > COORDINATION_MESSAGE_MAX_BYTES)
9201
+ throw new Error("Chief message routing metadata is too large");
9202
+ return stored;
9203
+ }
9118
9204
  function inboxFor(runtime, toSessionId) {
9119
9205
  if (!validSession(toSessionId))
9120
9206
  throw new Error("Invalid Chief message target");
@@ -9159,6 +9245,92 @@ function publishRecord(path, content) {
9159
9245
  }
9160
9246
  }
9161
9247
  }
9248
+ function writeOverflowBody(path, body) {
9249
+ const content = `${JSON.stringify(body)}
9250
+ `;
9251
+ const bytes = Buffer.byteLength(content, "utf8");
9252
+ if (bytes > COORDINATION_BODY_MAX_BYTES)
9253
+ throw new Error("Coordination message body is too large");
9254
+ const sha256 = createHash8("sha256").update(content).digest("hex");
9255
+ try {
9256
+ const stat = lstatSync4(path);
9257
+ if (!stat.isFile() || stat.size > COORDINATION_BODY_MAX_BYTES)
9258
+ throw new Error("Unsafe existing coordination message body");
9259
+ const fd = openSync8(
9260
+ path,
9261
+ constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0) | constants3.O_NONBLOCK
9262
+ );
9263
+ let existing;
9264
+ try {
9265
+ const current = fstatSync3(fd);
9266
+ if (!current.isFile() || current.size > COORDINATION_BODY_MAX_BYTES)
9267
+ throw new Error("Unsafe existing coordination message body");
9268
+ existing = Buffer.alloc(current.size);
9269
+ let offset = 0;
9270
+ while (offset < existing.length) {
9271
+ const count = readSync3(
9272
+ fd,
9273
+ existing,
9274
+ offset,
9275
+ existing.length - offset,
9276
+ offset
9277
+ );
9278
+ if (!count)
9279
+ throw new Error("Existing coordination message body is truncated");
9280
+ offset += count;
9281
+ }
9282
+ if (fstatSync3(fd).size !== current.size)
9283
+ throw new Error(
9284
+ "Existing coordination message body changed while reading"
9285
+ );
9286
+ } finally {
9287
+ closeSync8(fd);
9288
+ }
9289
+ if (existing.length !== bytes || createHash8("sha256").update(existing).digest("hex") !== sha256)
9290
+ throw new Error("Coordination message ID already has a different body");
9291
+ } catch (error2) {
9292
+ if (error2.code !== "ENOENT") throw error2;
9293
+ publishRecord(path, content);
9294
+ }
9295
+ return { bytes, sha256 };
9296
+ }
9297
+ function readOverflowBody(path, ref) {
9298
+ if (!ref || !Number.isInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > COORDINATION_BODY_MAX_BYTES || !/^[a-f0-9]{64}$/.test(ref.sha256))
9299
+ throw new Error("Invalid coordination message body reference");
9300
+ let fd;
9301
+ try {
9302
+ fd = openSync8(
9303
+ path,
9304
+ constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0) | constants3.O_NONBLOCK
9305
+ );
9306
+ const stat = fstatSync3(fd);
9307
+ if (!stat.isFile() || stat.size !== ref.bytes)
9308
+ throw new Error("Coordination message body size mismatch");
9309
+ const bytes = Buffer.alloc(ref.bytes);
9310
+ let offset = 0;
9311
+ while (offset < bytes.length) {
9312
+ const count = readSync3(fd, bytes, offset, bytes.length - offset, offset);
9313
+ if (!count) throw new Error("Coordination message body is truncated");
9314
+ offset += count;
9315
+ }
9316
+ if (createHash8("sha256").update(bytes).digest("hex") !== ref.sha256)
9317
+ throw new Error("Coordination message body integrity check failed");
9318
+ const parsed = JSON.parse(
9319
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes)
9320
+ );
9321
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.keys(parsed).some(
9322
+ (key) => !["text", "resultBindings"].includes(key)
9323
+ ) || typeof parsed.text !== "string" || !parsed.text.length || parsed.resultBindings !== void 0 && (!Array.isArray(parsed.resultBindings) || !parsed.resultBindings.every(isResultBinding)))
9324
+ throw new Error("Invalid coordination message body");
9325
+ return parsed;
9326
+ } catch (error2) {
9327
+ throw new Error("Unable to read coordination message body", {
9328
+ cause: error2
9329
+ });
9330
+ } finally {
9331
+ if (fd !== void 0) closeSync8(fd);
9332
+ }
9333
+ }
9162
9334
  function withChiefMessageLock(path, operation) {
9163
9335
  const lock = `${path}.lock`;
9164
9336
  const lease = acquireProcessLock(lock, { name: "Chief message lock" });
@@ -9268,7 +9440,8 @@ function removeChiefMessageQuarantineUnlocked(runtime, toSessionId, id) {
9268
9440
  function writeChiefMessage(record, runtime = supervisionRuntime(), clearQuarantine = true) {
9269
9441
  if (!record.build)
9270
9442
  throw new Error("Coordination message build identity is required");
9271
- assertMessage(record);
9443
+ if (!validMessage(record) || record.bodyRef !== void 0)
9444
+ throw new Error("Invalid Chief message record");
9272
9445
  return withChiefMessageLock(
9273
9446
  chiefMessagePath(runtime, record.toSessionId, record.id),
9274
9447
  () => writeChiefMessageUnlocked(record, runtime, clearQuarantine)
@@ -9295,8 +9468,9 @@ function writeChiefMessageUnlocked(record, runtime, clearQuarantine) {
9295
9468
  if (error2.code !== "ENOENT") throw error2;
9296
9469
  }
9297
9470
  }
9471
+ const stored = compactChiefMessage(record, path);
9298
9472
  const temporary = join8(directory, `.${record.id}.${randomUUID8()}.tmp`);
9299
- const content = `${JSON.stringify(record)}
9473
+ const content = `${JSON.stringify(stored)}
9300
9474
  `;
9301
9475
  let fd;
9302
9476
  try {
@@ -9366,7 +9540,7 @@ function assertChiefMessageNotQuarantined(runtime, toSessionId, id) {
9366
9540
  if (chiefMessageQuarantined(runtime, toSessionId, id))
9367
9541
  throw new Error("Chief message is quarantined");
9368
9542
  }
9369
- function readChiefMessage(path) {
9543
+ function readStoredChiefMessage(path) {
9370
9544
  let size;
9371
9545
  try {
9372
9546
  size = statSync4(path).size;
@@ -9385,6 +9559,17 @@ function readChiefMessage(path) {
9385
9559
  throw new Error("Invalid Chief message record", { cause: error2 });
9386
9560
  }
9387
9561
  }
9562
+ function readChiefMessage(path) {
9563
+ const parsed = readStoredChiefMessage(path);
9564
+ if (parsed.bodyRef) {
9565
+ const body = readOverflowBody(`${path}.body`, parsed.bodyRef);
9566
+ const logical = { ...parsed, ...body };
9567
+ delete logical.bodyRef;
9568
+ if (!validMessage(logical)) throw new Error("Invalid Chief message body");
9569
+ return logical;
9570
+ }
9571
+ return parsed;
9572
+ }
9388
9573
  function allChiefMessagePaths(runtime, toSessionId) {
9389
9574
  const directory = inboxFor(runtime, toSessionId);
9390
9575
  let entries;
@@ -9397,7 +9582,7 @@ function allChiefMessagePaths(runtime, toSessionId) {
9397
9582
  const paths = entries.filter((entry) => UUID3.test(entry.slice(0, -5)) && entry.endsWith(".json")).map((entry) => join8(directory, entry));
9398
9583
  return paths.flatMap((path) => {
9399
9584
  try {
9400
- const record = readChiefMessage(path);
9585
+ const record = readStoredChiefMessage(path);
9401
9586
  return [{ path, record }];
9402
9587
  } catch {
9403
9588
  return [{ path, record: void 0 }];
@@ -9428,7 +9613,10 @@ function removeChiefMessageUnlocked(runtime, toSessionId, id, expected) {
9428
9613
  const matchesExpected = () => {
9429
9614
  if (!expected) return true;
9430
9615
  try {
9431
- return JSON.stringify(readChiefMessage(path)) === JSON.stringify(expected);
9616
+ const stored = readStoredChiefMessage(path);
9617
+ if (expected.bodyRef)
9618
+ return isDeepStrictEqual(stored, expected);
9619
+ return isDeepStrictEqual(readChiefMessage(path), expected);
9432
9620
  } catch {
9433
9621
  return false;
9434
9622
  }
@@ -9460,6 +9648,11 @@ function removeChiefMessageUnlocked(runtime, toSessionId, id, expected) {
9460
9648
  if (error2.code !== "ENOENT")
9461
9649
  throw new Error("Unable to remove Chief message", { cause: error2 });
9462
9650
  }
9651
+ try {
9652
+ unlinkSync7(`${path}.body`);
9653
+ fsyncDirectory(directory);
9654
+ } catch {
9655
+ }
9463
9656
  try {
9464
9657
  removeChiefMessageQuarantineUnlocked(runtime, toSessionId, id);
9465
9658
  } catch (error2) {
@@ -9507,21 +9700,22 @@ function deliveredMessageContent(record) {
9507
9700
  const content = record.kind === "project_assignment" ? `Project assignment for branch ${record.branch}:
9508
9701
 
9509
9702
  ${record.text}` : `${prefix}${record.text}`;
9510
- return Buffer.from(content, "utf8").subarray(0, COORDINATION_MESSAGE_MAX_BYTES).toString("utf8");
9703
+ return content;
9511
9704
  }
9512
9705
  async function drainCoordinationInbox(options2) {
9513
9706
  let delivered = 0;
9514
- for (const path of listChiefMessagePaths(
9515
- options2.runtime,
9516
- options2.sessionId
9517
- )) {
9707
+ let examined = 0;
9708
+ for (const path of allChiefMessagePaths(options2.runtime, options2.sessionId)) {
9709
+ if (examined >= COORDINATION_INBOX_SCAN_LIMIT) break;
9518
9710
  if (options2.signal?.aborted) break;
9519
9711
  const id = basename6(path, ".json");
9520
9712
  if (UUID3.test(id) && chiefMessageQuarantined(options2.runtime, options2.sessionId, id))
9521
9713
  continue;
9714
+ let stored;
9522
9715
  let record;
9523
9716
  try {
9524
- record = readChiefMessage(path);
9717
+ stored = readStoredChiefMessage(path);
9718
+ record = stored;
9525
9719
  } catch {
9526
9720
  if (UUID3.test(id) && conclusivelyMalformedChiefMessage(path)) {
9527
9721
  for (const cleanupError of removeMalformedChiefMessage(
@@ -9536,6 +9730,7 @@ async function drainCoordinationInbox(options2) {
9536
9730
  }
9537
9731
  continue;
9538
9732
  }
9733
+ examined++;
9539
9734
  let token;
9540
9735
  const clearTransaction = async () => {
9541
9736
  if (token === void 0) return;
@@ -9611,6 +9806,21 @@ async function drainCoordinationInbox(options2) {
9611
9806
  record.id
9612
9807
  );
9613
9808
  if (!options2.isDelivered(record.id)) {
9809
+ if (stored.bodyRef) {
9810
+ try {
9811
+ const body = readOverflowBody(`${path}.body`, stored.bodyRef);
9812
+ record = { ...record, ...body };
9813
+ } catch {
9814
+ examined--;
9815
+ await options2.cleanupError?.(
9816
+ new Error(
9817
+ `Unable to read overflow body for Chief message ${id}`
9818
+ )
9819
+ );
9820
+ await clearTransaction();
9821
+ continue;
9822
+ }
9823
+ }
9614
9824
  await options2.sendMessage(
9615
9825
  {
9616
9826
  customType: `pi-herdsman-${record.kind}`,
@@ -10566,7 +10776,8 @@ function validProjectMessage(value2) {
10566
10776
  "text",
10567
10777
  "kind",
10568
10778
  "createdAt",
10569
- "resultBindings"
10779
+ "resultBindings",
10780
+ "bodyRef"
10570
10781
  ].includes(key)
10571
10782
  ) && Object.keys(r).length >= 7 && [
10572
10783
  "version",
@@ -10576,15 +10787,27 @@ function validProjectMessage(value2) {
10576
10787
  "fromSessionId",
10577
10788
  "text",
10578
10789
  "createdAt"
10579
- ].every((key) => Object.hasOwn(r, key)) && r.version === 2 && UUID3.test(String(r.id)) && validNativeIdentity(r.repoKey) && validNativeIdentity(r.branch) && validSession(r.fromSessionId) && typeof r.text === "string" && r.text.length > 0 && (r.kind === void 0 || r.kind === "execution_failure") && (r.resultBindings === void 0 || Array.isArray(r.resultBindings) && r.resultBindings.every(isResultBinding)) && Number.isInteger(r.createdAt) && r.createdAt >= 0 && Buffer.byteLength(`${JSON.stringify(r)}
10580
- `, "utf8") <= COORDINATION_MESSAGE_MAX_BYTES;
10790
+ ].every((key) => Object.hasOwn(r, key)) && r.version === 2 && UUID3.test(String(r.id)) && validNativeIdentity(r.repoKey) && validNativeIdentity(r.branch) && validSession(r.fromSessionId) && typeof r.text === "string" && (r.bodyRef === void 0 ? r.text.length > 0 : r.text === "" && r.resultBindings === void 0 && validOverflowBodyRef(r.bodyRef)) && (r.kind === void 0 || r.kind === "execution_failure") && (r.resultBindings === void 0 || Array.isArray(r.resultBindings) && r.resultBindings.every(isResultBinding)) && Number.isInteger(r.createdAt) && r.createdAt >= 0;
10581
10791
  }
10582
10792
  function projectMessageBytes(record) {
10583
10793
  return Buffer.byteLength(`${JSON.stringify(record)}
10584
10794
  `, "utf8");
10585
10795
  }
10586
10796
  function writeProjectMessage(record, runtime) {
10587
- if (!validProjectMessage(record)) throw new Error("Invalid project message");
10797
+ if (!validProjectMessage(record) || record.bodyRef !== void 0)
10798
+ throw new Error("Invalid project message");
10799
+ const path = join8(
10800
+ projectMessageDirectory(runtime, record.repoKey, record.branch),
10801
+ `${record.id}.json`
10802
+ );
10803
+ withChiefMessageLock(
10804
+ path,
10805
+ () => writeProjectMessageUnlocked(record, runtime)
10806
+ );
10807
+ }
10808
+ function writeProjectMessageUnlocked(record, runtime) {
10809
+ if (!validProjectMessage(record) || record.bodyRef !== void 0)
10810
+ throw new Error("Invalid project message");
10588
10811
  const directory = projectMessageDirectory(
10589
10812
  runtime,
10590
10813
  record.repoKey,
@@ -10596,28 +10819,37 @@ function writeProjectMessage(record, runtime) {
10596
10819
  chmodSync7(dirname6(directory), 448);
10597
10820
  chmodSync7(directory, 448);
10598
10821
  const path = join8(directory, `${record.id}.json`);
10822
+ let stored = record;
10823
+ if (projectMessageBytes(record) > COORDINATION_MESSAGE_MAX_BYTES) {
10824
+ const bodyRef = writeOverflowBody(`${path}.body`, {
10825
+ text: record.text,
10826
+ ...record.resultBindings ? { resultBindings: record.resultBindings } : {}
10827
+ });
10828
+ stored = { ...record, text: "", bodyRef };
10829
+ delete stored.resultBindings;
10830
+ if (projectMessageBytes(stored) > COORDINATION_MESSAGE_MAX_BYTES)
10831
+ throw new Error("Project message routing metadata is too large");
10832
+ }
10599
10833
  const temporary = join8(directory, `.${record.id}.${randomUUID8()}.tmp`);
10600
10834
  let fd;
10601
10835
  try {
10602
10836
  fd = openSync8(temporary, "wx", 384);
10603
- writeFileSync5(fd, `${JSON.stringify(record)}
10837
+ writeFileSync5(fd, `${JSON.stringify(stored)}
10604
10838
  `, "utf8");
10605
10839
  fsyncSync4(fd);
10606
10840
  closeSync8(fd);
10607
10841
  fd = void 0;
10608
10842
  let existing;
10609
10843
  try {
10610
- if (statSync4(path).size > COORDINATION_MESSAGE_MAX_BYTES)
10611
- throw new Error("large");
10612
- existing = JSON.parse(readFileSync8(path, "utf8"));
10844
+ existing = readProjectMessageFile(path);
10613
10845
  } catch (error2) {
10614
- if (error2.code !== "ENOENT")
10846
+ if (error2.cause?.code !== "ENOENT" && error2.code !== "ENOENT")
10615
10847
  throw new Error(`Unable to verify existing project message ${path}`, {
10616
10848
  cause: error2
10617
10849
  });
10618
10850
  }
10619
10851
  if (existing !== void 0) {
10620
- if (!validProjectMessage(existing) || JSON.stringify(existing) !== JSON.stringify(record))
10852
+ if (JSON.stringify(existing) !== JSON.stringify(record))
10621
10853
  throw new Error(
10622
10854
  "Project message identity conflicts with durable payload"
10623
10855
  );
@@ -10658,30 +10890,97 @@ function listProjectMessages(runtime, repoKey, branch) {
10658
10890
  return [value2];
10659
10891
  }).sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
10660
10892
  }
10893
+ function listProjectMessageHeaders(runtime, repoKey, branch) {
10894
+ const directory = projectMessageDirectory(runtime, repoKey, branch);
10895
+ let entries;
10896
+ try {
10897
+ entries = readdirSync5(directory);
10898
+ } catch (error2) {
10899
+ if (error2.code === "ENOENT") return [];
10900
+ throw error2;
10901
+ }
10902
+ return entries.filter((entry) => UUID3.test(entry.slice(0, -5)) && entry.endsWith(".json")).flatMap((entry) => {
10903
+ try {
10904
+ const value2 = readStoredProjectMessageFile(join8(directory, entry));
10905
+ if (value2.repoKey !== repoKey || value2.branch !== branch)
10906
+ throw new Error(
10907
+ `Project message identity does not match ${directory}`
10908
+ );
10909
+ return [value2];
10910
+ } catch (error2) {
10911
+ if (error2 instanceof Error && error2.cause?.code === "ENOENT")
10912
+ return [];
10913
+ throw error2;
10914
+ }
10915
+ }).sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
10916
+ }
10917
+ function readProjectMessage(runtime, repoKey, branch, id) {
10918
+ if (!UUID3.test(id)) throw new Error("Invalid project message ID");
10919
+ const record = readProjectMessageFile(
10920
+ join8(projectMessageDirectory(runtime, repoKey, branch), `${id}.json`)
10921
+ );
10922
+ if (record.repoKey !== repoKey || record.branch !== branch)
10923
+ throw new Error("Project message identity does not match its directory");
10924
+ return record;
10925
+ }
10661
10926
  function removeProjectMessage(runtime, repoKey, branch, id) {
10662
10927
  if (!UUID3.test(id)) throw new Error("Invalid project message ID");
10663
10928
  const directory = projectMessageDirectory(runtime, repoKey, branch);
10929
+ try {
10930
+ if (!statSync4(directory).isDirectory())
10931
+ throw new Error("Invalid project message directory");
10932
+ } catch (error2) {
10933
+ if (error2.code === "ENOENT") return;
10934
+ throw error2;
10935
+ }
10936
+ const path = join8(directory, `${id}.json`);
10937
+ withChiefMessageLock(path, () => removeProjectMessageUnlocked(directory, id));
10938
+ }
10939
+ function removeProjectMessageUnlocked(directory, id) {
10664
10940
  try {
10665
10941
  unlinkSync7(join8(directory, `${id}.json`));
10666
10942
  fsyncDirectory(directory);
10667
10943
  } catch (error2) {
10668
10944
  if (error2.code !== "ENOENT") throw error2;
10669
10945
  }
10946
+ try {
10947
+ unlinkSync7(join8(directory, `${id}.json.body`));
10948
+ fsyncDirectory(directory);
10949
+ } catch {
10950
+ }
10670
10951
  }
10671
10952
  function readProjectMessageFile(path) {
10953
+ try {
10954
+ const stored = readStoredProjectMessageFile(path);
10955
+ if (stored.bodyRef) {
10956
+ const compact = stored;
10957
+ const body = readOverflowBody(`${path}.body`, compact.bodyRef);
10958
+ const value2 = { ...compact, ...body };
10959
+ delete value2.bodyRef;
10960
+ if (!validProjectMessage(value2)) throw new Error("invalid body");
10961
+ return value2;
10962
+ }
10963
+ return stored;
10964
+ } catch (error2) {
10965
+ if (error2 instanceof Error && error2.message.startsWith("Unable to read project message "))
10966
+ throw error2;
10967
+ throw new Error(`Unable to read project message ${path}`, { cause: error2 });
10968
+ }
10969
+ }
10970
+ function readStoredProjectMessageFile(path) {
10672
10971
  try {
10673
10972
  if (statSync4(path).size > COORDINATION_MESSAGE_MAX_BYTES)
10674
10973
  throw new Error("large");
10675
- const value2 = JSON.parse(readFileSync8(path, "utf8"));
10676
- if (!validProjectMessage(value2) || basename6(path) !== `${value2.id}.json`)
10974
+ const stored = JSON.parse(readFileSync8(path, "utf8"));
10975
+ if (!validProjectMessage(stored) || basename6(path) !== `${stored.id}.json`)
10677
10976
  throw new Error("invalid");
10678
- return value2;
10977
+ return stored;
10679
10978
  } catch (error2) {
10680
10979
  throw new Error(`Unable to read project message ${path}`, { cause: error2 });
10681
10980
  }
10682
10981
  }
10683
10982
  function removeProjectMessagesForAssignment(runtime, assignment) {
10684
- for (const message of listProjectMessages(
10983
+ for (const message of listProjectMessageHeaders(
10685
10984
  runtime,
10686
10985
  assignment.repoKey,
10687
10986
  assignment.branch
@@ -10728,7 +11027,7 @@ function recoverStaleProjectMessages(runtime, repoKey) {
10728
11027
  const path = join8(messages, file2);
10729
11028
  let message;
10730
11029
  try {
10731
- message = readProjectMessageFile(path);
11030
+ message = readStoredProjectMessageFile(path);
10732
11031
  } catch (error2) {
10733
11032
  if (error2 instanceof Error && error2.cause?.code === "ENOENT")
10734
11033
  continue;
@@ -11534,6 +11833,37 @@ function requiredEvidenceEntriesForRequest(entries, requestId) {
11534
11833
  (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-agent-required-evidence" && entry.data?.requestId === requestId
11535
11834
  );
11536
11835
  }
11836
+ function consistentRequiredEvidenceUpdates(entries) {
11837
+ const records = entries.map((entry) => entry?.data);
11838
+ const itemsById = /* @__PURE__ */ new Map();
11839
+ for (let index = 1; index < records.length; index++) {
11840
+ const previous = records[index - 1];
11841
+ const current = records[index];
11842
+ if (!previous || !current || [
11843
+ "version",
11844
+ "sessionId",
11845
+ "requestId",
11846
+ "runId",
11847
+ "ownerSessionId",
11848
+ "workspaceId",
11849
+ "agentLabel",
11850
+ "paneId",
11851
+ "projectAssignmentId",
11852
+ "evidenceAssignmentId",
11853
+ "inheritedEvidence"
11854
+ ].some((field) => !isDeepStrictEqual2(previous[field], current[field])) || !Array.isArray(previous.localEvidence) || !Array.isArray(current.localEvidence))
11855
+ return false;
11856
+ }
11857
+ for (const record of records) {
11858
+ if (!Array.isArray(record?.localEvidence)) return false;
11859
+ for (const item of record.localEvidence) {
11860
+ const previous = itemsById.get(item.id);
11861
+ if (previous && !isDeepStrictEqual2(previous, item)) return false;
11862
+ itemsById.set(item.id, item);
11863
+ }
11864
+ }
11865
+ return true;
11866
+ }
11537
11867
  function currentManagedEvidence(ctx) {
11538
11868
  const state = readAgentState(process.env.PI_HERDSMAN_MAILBOX ?? "");
11539
11869
  if (!state?.projectAssignmentId || !state.activeRequestId) return void 0;
@@ -11820,6 +12150,25 @@ function agentResultDetails(entry) {
11820
12150
  const details = message.details && typeof message.details === "object" ? message.details : record.details;
11821
12151
  return details && typeof details === "object" && !Array.isArray(details) ? details : void 0;
11822
12152
  }
12153
+ function sameTerminalProvenance(left, right) {
12154
+ const fields = [
12155
+ "requestId",
12156
+ "runId",
12157
+ "ownerSessionId",
12158
+ "workspaceId",
12159
+ "agentLabel",
12160
+ "paneId",
12161
+ "piSessionId",
12162
+ "agentDefinition",
12163
+ "status"
12164
+ ];
12165
+ if (!fields.every((field) => left[field] === right[field])) return false;
12166
+ try {
12167
+ return typeof left.piSessionFile === "string" && typeof right.piSessionFile === "string" && canonicalSessionPath(left.piSessionFile) === canonicalSessionPath(right.piSessionFile);
12168
+ } catch {
12169
+ return false;
12170
+ }
12171
+ }
11823
12172
  var RESULT_REF_ENTRY = "pi-herdsman-result-ref";
11824
12173
  function canonicalResultRef(details, operation) {
11825
12174
  if (details.status !== "completed" || typeof details.requestId !== "string" || typeof details.resultRef !== "string")
@@ -12162,7 +12511,9 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
12162
12511
  "continue"
12163
12512
  );
12164
12513
  }
12165
- const allEvidenceEntries = manager.getEntries().filter(
12514
+ const allEntries = manager.getEntries();
12515
+ const evidenceBranch = typeof manager.getBranch === "function" ? manager.getBranch() : void 0;
12516
+ const allEvidenceEntries = allEntries.filter(
12166
12517
  (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-agent-required-evidence"
12167
12518
  );
12168
12519
  for (const entry of allEvidenceEntries) {
@@ -12193,12 +12544,51 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
12193
12544
  "continue"
12194
12545
  );
12195
12546
  const currentState = matchingStates[0];
12196
- if (hasProjectEvidenceHistory && !currentState)
12197
- fail(
12198
- "invalid_request",
12199
- "Cannot verify the current accepted assignment for saved evidence",
12200
- "continue"
12547
+ let historicalTerminal;
12548
+ if (hasProjectEvidenceHistory && !currentState) {
12549
+ if (!evidenceBranch)
12550
+ fail(
12551
+ "invalid_request",
12552
+ "Cannot verify the applicable accepted evidence branch",
12553
+ "continue"
12554
+ );
12555
+ const latestBranchEvidence = [...evidenceBranch].reverse().find(
12556
+ (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-agent-required-evidence"
12201
12557
  );
12558
+ const latestRequestId = latestBranchEvidence?.data?.requestId;
12559
+ const proofs = entries.map(agentResultDetails).filter(
12560
+ (details) => !!details && details.requestId === latestRequestId
12561
+ );
12562
+ if (!proofs.length || proofs.some((proof) => !sameTerminalProvenance(proof, proofs[0])))
12563
+ fail(
12564
+ "invalid_request",
12565
+ "Cannot verify the current accepted assignment for saved evidence",
12566
+ "continue"
12567
+ );
12568
+ historicalTerminal = proofs[0];
12569
+ if (!historicalTerminal || !validId(historicalTerminal.requestId) || !validId(historicalTerminal.runId) || historicalTerminal.ownerSessionId !== ownerId || historicalTerminal.piSessionId !== child.id || typeof historicalTerminal.piSessionFile !== "string" || canonicalSessionPath(historicalTerminal.piSessionFile) !== child.path || historicalTerminal.agentDefinition !== child.definition || historicalTerminal.agentLabel !== child.label || typeof historicalTerminal.workspaceId !== "string" || !historicalTerminal.workspaceId.trim() || typeof historicalTerminal.paneId !== "string" || !historicalTerminal.paneId.trim() || historicalTerminal.status !== "completed" && historicalTerminal.status !== "failed")
12570
+ fail(
12571
+ "invalid_request",
12572
+ "Cannot verify the terminal result for saved evidence",
12573
+ "continue"
12574
+ );
12575
+ try {
12576
+ statSync5(
12577
+ agentMailboxPath(
12578
+ historicalTerminal.workspaceId,
12579
+ historicalTerminal.agentLabel
12580
+ )
12581
+ );
12582
+ fail(
12583
+ "invalid_request",
12584
+ "Cannot verify mailbox cleanup because the historical mailbox still exists",
12585
+ "continue"
12586
+ );
12587
+ } catch (error2) {
12588
+ if (error2 instanceof OperationError || error2.code !== "ENOENT")
12589
+ throw error2;
12590
+ }
12591
+ }
12202
12592
  const exactIdState = selector.kind === "id" && currentState?.piSessionId === child.id && !!currentState.activeRequestId;
12203
12593
  if (currentState && (!identity || !exactIdState && (currentState.agentLabel !== child.label || currentState.agentDefinition !== child.definition) || currentState.piSessionId !== child.id || currentState.workspaceId.trim() === ""))
12204
12594
  fail(
@@ -12206,7 +12596,10 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
12206
12596
  "Saved assignment state does not match the exact owned session",
12207
12597
  "continue"
12208
12598
  );
12209
- const currentRequestId = currentState?.activeRequestId ?? currentState?.completedRequestId;
12599
+ const applicableEvidence = currentState || !hasProjectEvidenceHistory ? allEvidenceEntries : evidenceBranch.filter(
12600
+ (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-agent-required-evidence"
12601
+ );
12602
+ const currentRequestId = currentState ? currentState.activeRequestId ?? currentState.completedRequestId : historicalTerminal?.requestId;
12210
12603
  if (hasProjectEvidenceHistory && !currentRequestId)
12211
12604
  fail(
12212
12605
  "invalid_request",
@@ -12220,9 +12613,15 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
12220
12613
  "continue"
12221
12614
  );
12222
12615
  const evidenceEntries = currentRequestId ? requiredEvidenceEntriesForRequest(
12223
- allEvidenceEntries,
12616
+ applicableEvidence,
12224
12617
  currentRequestId
12225
12618
  ) : [];
12619
+ if (evidenceEntries.length > 1 && !consistentRequiredEvidenceUpdates(evidenceEntries))
12620
+ fail(
12621
+ "invalid_request",
12622
+ "Saved assignment has conflicting accepted evidence metadata",
12623
+ "continue"
12624
+ );
12226
12625
  if (hasProjectEvidenceHistory && !evidenceEntries.length)
12227
12626
  fail(
12228
12627
  "invalid_request",
@@ -12247,7 +12646,7 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
12247
12646
  "Saved assignment has malformed required-evidence metadata",
12248
12647
  "continue"
12249
12648
  );
12250
- if (!identity || identity.definition !== child.definition || identity.label !== record.agentLabel || record.requestId !== currentRequestId || record.agentLabel !== currentState?.agentLabel || record.projectAssignmentId !== currentState?.projectAssignmentId || record.runId !== currentState?.runId || record.ownerSessionId !== currentState?.ownerSessionId || record.workspaceId !== currentState?.workspaceId || record.paneId !== currentState?.paneId)
12649
+ if (!identity || identity.definition !== child.definition || identity.label !== record.agentLabel || record.requestId !== currentRequestId || record.agentLabel !== (currentState?.agentLabel ?? historicalTerminal?.agentLabel) || record.projectAssignmentId !== currentState?.projectAssignmentId && currentState !== void 0 || record.runId !== (currentState?.runId ?? historicalTerminal?.runId) || record.ownerSessionId !== (currentState?.ownerSessionId ?? historicalTerminal?.ownerSessionId) || record.workspaceId !== (currentState?.workspaceId ?? historicalTerminal?.workspaceId) || record.paneId !== (currentState?.paneId ?? historicalTerminal?.paneId))
12251
12650
  fail(
12252
12651
  "invalid_request",
12253
12652
  "Saved assignment evidence does not match the exact owned session",
@@ -12273,7 +12672,8 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
12273
12672
  ...record.projectAssignmentId ? { projectAssignmentId: record.projectAssignmentId } : {},
12274
12673
  ...record.evidenceAssignmentId ? { evidenceAssignmentId: record.evidenceAssignmentId } : {},
12275
12674
  inheritedEvidence: [...record.inheritedEvidence],
12276
- localEvidence: [...record.localEvidence]
12675
+ localEvidence: [...record.localEvidence],
12676
+ ...historicalTerminal ? { terminal: historicalTerminal } : {}
12277
12677
  };
12278
12678
  }
12279
12679
  return {
@@ -15171,6 +15571,12 @@ function createAgentController(pi, options2) {
15171
15571
  );
15172
15572
  const continuationEvidence = resumed?.evidence;
15173
15573
  let nestedEvidence = scope.kind === "managed-agent" ? currentManagedEvidence(ctx) : void 0;
15574
+ if (scope.kind === "managed-agent" && continuationEvidence?.projectAssignmentId && continuationEvidence.projectAssignmentId !== nestedEvidence?.projectAssignmentId)
15575
+ fail(
15576
+ "invalid_request",
15577
+ "Historical Agent belongs to a different project assignment",
15578
+ "continue"
15579
+ );
15174
15580
  const projectAssignmentId = nestedEvidence?.projectAssignmentId ?? continuationEvidence?.projectAssignmentId;
15175
15581
  let projectEvidence;
15176
15582
  projectEvidence = scope.kind === "root" ? await options2.projectEvidence?.(ctx) : nestedEvidence && projectAssignmentId ? await options2.managedProjectEvidence?.(
@@ -15320,7 +15726,30 @@ function createAgentController(pi, options2) {
15320
15726
  return true;
15321
15727
  }
15322
15728
  });
15323
- const assignmentFiles = [...requiredFiles, ...explicitFiles];
15729
+ const inheritedResultPaths = new Set(
15730
+ requiredFiles.flatMap((file2) => {
15731
+ if (typeof file2 === "string") return [];
15732
+ try {
15733
+ const path = resolveResultRef(file2.canonicalRef);
15734
+ return path ? [realpathSync3(path)] : [];
15735
+ } catch {
15736
+ return [];
15737
+ }
15738
+ })
15739
+ );
15740
+ const assignmentFiles = [
15741
+ ...explicitFiles.filter((file2) => {
15742
+ if (typeof file2 !== "string") return true;
15743
+ try {
15744
+ return !inheritedResultPaths.has(
15745
+ realpathSync3(resolve4(ctx.cwd, file2))
15746
+ );
15747
+ } catch {
15748
+ return true;
15749
+ }
15750
+ }),
15751
+ ...requiredFiles
15752
+ ];
15324
15753
  const prepareAssignmentInput = (assignmentLabel) => prepareMessageInput(
15325
15754
  p.task,
15326
15755
  assignmentFiles,
@@ -15767,20 +16196,41 @@ ${result.stderr ?? ""}`.trim(),
15767
16196
  );
15768
16197
  }
15769
16198
  if (continuationEvidence && resumed) {
15770
- const saved = SessionManager.open(resumed.path);
15771
- if (saved.getSessionId() !== resumed.id)
16199
+ const savedPath = canonicalSessionPath(resumed.path);
16200
+ const saved = SessionManager.open(savedPath);
16201
+ const identity = sessionAgentIdentity(
16202
+ saved.getEntries(),
16203
+ saved.getSessionId()
16204
+ );
16205
+ if (savedPath !== resumed.path || saved.getSessionId() !== resumed.id || identity?.definition !== resumed.definition || identity.label !== resumed.label)
15772
16206
  throw new Error(
15773
- "The exact saved assignment session changed during continuation; retry"
16207
+ "The exact saved assignment identity changed during continuation; retry"
15774
16208
  );
16209
+ const branch = saved.getBranch();
15775
16210
  const entries = requiredEvidenceEntriesForRequest(
15776
- saved.getEntries(),
16211
+ branch,
15777
16212
  continuationEvidence.requestId
15778
16213
  );
16214
+ const latestEvidence = [...branch].reverse().find(
16215
+ (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-agent-required-evidence"
16216
+ );
15779
16217
  const record = entries.at(-1)?.data;
15780
- if (!record || record.requestId !== continuationEvidence.requestId || record.projectAssignmentId !== continuationEvidence.projectAssignmentId || record.evidenceAssignmentId !== continuationEvidence.evidenceAssignmentId || JSON.stringify(record.inheritedEvidence) !== JSON.stringify(continuationEvidence.inheritedEvidence) || JSON.stringify(record.localEvidence) !== JSON.stringify(continuationEvidence.localEvidence))
16218
+ if (!consistentRequiredEvidenceUpdates(entries) || continuationEvidence.terminal && latestEvidence?.data?.requestId !== continuationEvidence.requestId || !record || record.requestId !== continuationEvidence.requestId || record.projectAssignmentId !== continuationEvidence.projectAssignmentId || record.evidenceAssignmentId !== continuationEvidence.evidenceAssignmentId || JSON.stringify(record.inheritedEvidence) !== JSON.stringify(continuationEvidence.inheritedEvidence) || JSON.stringify(record.localEvidence) !== JSON.stringify(continuationEvidence.localEvidence))
15781
16219
  throw new Error(
15782
16220
  "Saved assignment evidence changed during continuation; retry"
15783
16221
  );
16222
+ if (continuationEvidence.terminal && (() => {
16223
+ const expected = continuationEvidence.terminal;
16224
+ const records = ctx.sessionManager.getEntries().map(agentResultDetails).filter(
16225
+ (details) => !!details && (details.requestId === expected.requestId || details.runId === expected.runId)
16226
+ );
16227
+ return !records.length || records.some(
16228
+ (details) => !sameTerminalProvenance(details, expected)
16229
+ );
16230
+ })())
16231
+ throw new Error(
16232
+ "Saved assignment terminal proof changed during continuation; retry"
16233
+ );
15784
16234
  }
15785
16235
  if (!projectEvidence || !projectAssignment) {
15786
16236
  if (continuationEvidence?.projectAssignmentId || nestedEvidence?.projectAssignmentId)
@@ -17280,7 +17730,7 @@ function collectSessionUsage(ctx, ownedChildren, openOwnedSession, leadRoots = [
17280
17730
  // extension/managed-agent-runtime.ts
17281
17731
  import { randomUUID as randomUUID10 } from "node:crypto";
17282
17732
  import { Type as Type2 } from "typebox";
17283
- import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
17733
+ import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
17284
17734
  var DELEGATING_AGENT_ROLE_CHARTER = `## Delegating agent role
17285
17735
  ${DELEGATING_AGENT_SCOPE_DESCRIPTION}
17286
17736
  ${FILE_HANDOFF_GUIDANCE}`;
@@ -17314,7 +17764,7 @@ function persistAcceptedRequiredEvidence(pi, ctx, request, state) {
17314
17764
  const existing = ctx.sessionManager.getBranch().filter(
17315
17765
  (candidate) => candidate?.type === "custom" && candidate.customType === AGENT_REQUIRED_EVIDENCE_ENTRY && candidate.data?.requestId === request.requestId
17316
17766
  );
17317
- if (existing.some((candidate) => !isDeepStrictEqual2(candidate.data, entry)))
17767
+ if (existing.some((candidate) => !isDeepStrictEqual3(candidate.data, entry)))
17318
17768
  throw new Error(
17319
17769
  "Conflicting required-evidence metadata for accepted request"
17320
17770
  );
@@ -17397,7 +17847,7 @@ function sameSessionPath2(left, right) {
17397
17847
  function sameManagedAgentDurableState(left, right) {
17398
17848
  const { updatedAt: _leftUpdatedAt, ...leftDurable } = left;
17399
17849
  const { updatedAt: _rightUpdatedAt, ...rightDurable } = right;
17400
- return isDeepStrictEqual2(leftDurable, rightDurable);
17850
+ return isDeepStrictEqual3(leftDurable, rightDurable);
17401
17851
  }
17402
17852
  function validateManagedAgentIdentity(input) {
17403
17853
  const { state, mailbox, env } = input;
@@ -19536,6 +19986,7 @@ function createLeadToolState(getAllTools, ownedNames, leadCoordinationNames) {
19536
19986
  }
19537
19987
  };
19538
19988
  }
19989
+ var sameToolSelection = (left, right) => left.length === right.length && left.every((name, i) => name === right[i]);
19539
19990
  function sessionLeadExecutionState(entries) {
19540
19991
  const entry = [...entries].reverse().find(
19541
19992
  (candidate) => candidate?.type === "custom" && candidate.customType === "pi-herdsman-lead-execution"
@@ -20807,6 +21258,7 @@ function registerLeadRuntime(pi, options2) {
20807
21258
  let leadExecution;
20808
21259
  let leadExecutionPending = false;
20809
21260
  let supervisoryProfile;
21261
+ let inheritedProjection;
20810
21262
  const prepareSupervisoryProfile = (ctx, role2) => {
20811
21263
  const name = role2 === "manager" ? MANAGER_DEFINITION_NAME : CHIEF_DEFINITION_NAME;
20812
21264
  const definition = options2.commandHost.discoverRoleDefinition(
@@ -20958,6 +21410,24 @@ function registerLeadRuntime(pi, options2) {
20958
21410
  leadTools: [...tools]
20959
21411
  });
20960
21412
  };
21413
+ const captureInheritedTools = () => {
21414
+ const projection = inheritedProjection;
21415
+ if (!projection) return;
21416
+ const saved = leadToolState.getLeadTools() ?? [];
21417
+ const excluded = (name) => projection.excluded.some((pattern) => matchesToolPattern(pattern, name));
21418
+ const active = leadToolState.normalizeBaseTools(pi.getActiveTools()).filter((name) => !excluded(name));
21419
+ const next = leadToolState.normalizeBaseTools([
21420
+ ...active,
21421
+ ...saved.filter(excluded)
21422
+ ]);
21423
+ if (sameToolSelection(saved, next)) {
21424
+ inheritedProjection = void 0;
21425
+ return;
21426
+ }
21427
+ persistLeadExecution(projection.mode, next);
21428
+ leadToolState.setLeadTools(next);
21429
+ inheritedProjection = void 0;
21430
+ };
20961
21431
  let roleTransitions;
20962
21432
  let identityRuntime;
20963
21433
  const liveAgent = (...args) => identityRuntime.liveAgent(...args);
@@ -21256,6 +21726,7 @@ function registerLeadRuntime(pi, options2) {
21256
21726
  });
21257
21727
  };
21258
21728
  const persistRole = (role2) => {
21729
+ captureInheritedTools();
21259
21730
  const tools = leadToolState.getLeadTools();
21260
21731
  if (!tools) throw new Error("Lead tool baseline is unavailable");
21261
21732
  pi.appendEntry("pi-herdsman-role", { role: role2, leadTools: [...tools] });
@@ -21312,6 +21783,14 @@ function registerLeadRuntime(pi, options2) {
21312
21783
  advancePeerPresenceGeneration: () => coordinationRuntime.advancePresenceGeneration(),
21313
21784
  setCoordinationHealthy: (healthy) => coordinationRuntime.setCoordinationHealthy(healthy),
21314
21785
  normalizeBaseTools: leadToolState.normalizeBaseTools,
21786
+ captureInheritedTools,
21787
+ inheritedProjection: () => leadExecution?.valid && !leadExecution.managed && leadExecution.definition.frontmatter.tools === void 0 ? {
21788
+ mode: leadExecution.mode,
21789
+ excluded: configuredToolPolicy(leadExecution.definition, []).excluded
21790
+ } : void 0,
21791
+ setInheritedProjection: (projection) => {
21792
+ inheritedProjection = projection;
21793
+ },
21315
21794
  appendRegisteredTools: leadToolState.appendRegisteredTools,
21316
21795
  normalizeLeadTools: leadToolState.normalizeLeadTools,
21317
21796
  executionTools,
@@ -21753,7 +22232,7 @@ function registerLeadRuntime(pi, options2) {
21753
22232
  if (assignment) nameSessionIfUnset(pi, ctx, `Lead \xB7 ${assignment.branch}`);
21754
22233
  let saved;
21755
22234
  try {
21756
- saved = sessionLeadExecutionState(ctx.sessionManager.getEntries());
22235
+ saved = sessionLeadExecutionState(ctx.sessionManager.getBranch());
21757
22236
  } catch (error2) {
21758
22237
  if (signal.aborted) return;
21759
22238
  leadToolState.setLeadTools(currentBaseline());
@@ -21846,8 +22325,9 @@ function registerLeadRuntime(pi, options2) {
21846
22325
  if (leadExecution?.managed) await restoreLeadExecution(ctx);
21847
22326
  await ctx.waitForIdle();
21848
22327
  const definition = resolveExecutionDefinition(ctx, mode);
22328
+ captureInheritedTools();
21849
22329
  const saved = leadToolState.getLeadTools() ?? leadToolState.normalizeBaseTools(pi.getActiveTools());
21850
- const baseline = leadExecution?.mode === "flexible" && !leadExecution.managed && leadExecution.valid && leadExecution.definition.frontmatter.tools === void 0 && leadExecution.definition.frontmatter.excludeTools === void 0 && activeLeadRole(leadRuntime) === "lead" ? leadToolState.normalizeBaseTools(pi.getActiveTools()) : [...saved];
22330
+ const baseline = [...saved];
21851
22331
  const targetTools = leadToolState.projectLeadTools(baseline, definition);
21852
22332
  const previousExecution = leadExecution;
21853
22333
  const previousTools = pi.getActiveTools();
@@ -21857,12 +22337,21 @@ function registerLeadRuntime(pi, options2) {
21857
22337
  persistLeadExecution(mode, baseline);
21858
22338
  leadToolState.setLeadTools(baseline);
21859
22339
  leadExecution = { mode, definition, valid: true, managed: false };
22340
+ inheritedProjection = shouldActivate && definition.frontmatter.tools === void 0 && sameToolSelection(pi.getActiveTools(), targetTools) ? {
22341
+ mode,
22342
+ excluded: configuredToolPolicy(definition, []).excluded
22343
+ } : void 0;
21860
22344
  statusRuntime.requestRefresh();
21861
22345
  } catch (error2) {
21862
22346
  leadExecution = previousExecution;
21863
22347
  try {
21864
22348
  if (shouldActivate) pi.setActiveTools(previousTools);
22349
+ inheritedProjection = shouldActivate && previousExecution?.valid && !previousExecution.managed && previousExecution.definition.frontmatter.tools === void 0 && sameToolSelection(pi.getActiveTools(), previousTools) ? {
22350
+ mode: previousExecution.mode,
22351
+ excluded: configuredToolPolicy(previousExecution.definition, []).excluded
22352
+ } : void 0;
21865
22353
  } catch {
22354
+ inheritedProjection = void 0;
21866
22355
  leadExecution = { mode, valid: false, managed: false };
21867
22356
  try {
21868
22357
  pi.setActiveTools(leadToolState.normalizeLeadTools([]));
@@ -21909,6 +22398,7 @@ function registerLeadRuntime(pi, options2) {
21909
22398
  return true;
21910
22399
  };
21911
22400
  const reconcileBranchExecution = async (ctx) => {
22401
+ inheritedProjection = void 0;
21912
22402
  let saved;
21913
22403
  try {
21914
22404
  saved = sessionLeadExecutionState(ctx.sessionManager.getBranch());
@@ -22012,10 +22502,10 @@ function registerLeadRuntime(pi, options2) {
22012
22502
  "tool_call",
22013
22503
  (event, ctx) => agentEvents.toolCall(event, ctx)
22014
22504
  );
22015
- pi.on(
22016
- "session_start",
22017
- (_event, ctx) => sessionStart.sessionStart(ctx)
22018
- );
22505
+ pi.on("session_start", (_event, ctx) => {
22506
+ inheritedProjection = void 0;
22507
+ return sessionStart.sessionStart(ctx);
22508
+ });
22019
22509
  pi.on("session_info_changed", (event, ctx) => {
22020
22510
  if (!roleTransitions.chiefModeInactive()) return;
22021
22511
  if (!options2.hasPane()) return;
@@ -22030,14 +22520,14 @@ function registerLeadRuntime(pi, options2) {
22030
22520
  "session_compact",
22031
22521
  (_event, ctx) => options2.queueLeadPresentation(ctx)
22032
22522
  );
22033
- pi.on(
22034
- "session_tree",
22035
- (_event, ctx) => sessionTree.sessionTree(ctx)
22036
- );
22037
- pi.on(
22038
- "session_shutdown",
22039
- (_event, ctx) => shutdown.shutdown(ctx)
22040
- );
22523
+ pi.on("session_tree", (_event, ctx) => {
22524
+ inheritedProjection = void 0;
22525
+ return sessionTree.sessionTree(ctx);
22526
+ });
22527
+ pi.on("session_shutdown", (_event, ctx) => {
22528
+ inheritedProjection = void 0;
22529
+ return shutdown.shutdown(ctx);
22530
+ });
22041
22531
  return {
22042
22532
  roleTransitions,
22043
22533
  publishLeadRole,
@@ -24320,8 +24810,12 @@ function createLeadProjectRuntime(host) {
24320
24810
  operation.files,
24321
24811
  "delegate_project"
24322
24812
  );
24323
- const requiredEvidence = [
24324
- persistRequiredEvidenceSnapshot(id, "project-brief.md", operation.task),
24813
+ const projectBrief = persistRequiredEvidenceSnapshot(
24814
+ id,
24815
+ "project-brief.md",
24816
+ operation.task
24817
+ );
24818
+ const attachedEvidence = [
24325
24819
  ...persistRequiredTextFiles(
24326
24820
  id,
24327
24821
  suppliedFiles.filter(
@@ -24334,9 +24828,10 @@ function createLeadProjectRuntime(host) {
24334
24828
  (file2) => typeof file2 === "string" ? [] : [{ id: randomUUID11(), name: file2.ref, result: file2 }]
24335
24829
  )
24336
24830
  ];
24831
+ const requiredEvidence = [projectBrief, ...attachedEvidence];
24337
24832
  const prepared = prepareMessageInput2(
24338
24833
  operation.task,
24339
- requiredEvidence.flatMap(
24834
+ attachedEvidence.flatMap(
24340
24835
  (evidence) => "path" in evidence ? [evidence.path] : [evidence.result]
24341
24836
  ),
24342
24837
  ctx.cwd,
@@ -25365,12 +25860,14 @@ function createLeadCoordinationRuntime(host) {
25365
25860
  removeChiefMessage: removeChiefMessage2,
25366
25861
  quarantineChiefMessage: quarantineChiefMessage2,
25367
25862
  listProjectAssignments: listProjectAssignments2,
25368
- listProjectMessages: listProjectMessages2,
25863
+ listProjectMessageHeaders: listProjectMessageHeaders2,
25864
+ readProjectMessage: readProjectMessage2,
25369
25865
  removeProjectMessage: removeProjectMessage2,
25370
25866
  readProjectAssignment: readProjectAssignment2,
25371
25867
  importResultBindings: importResultBindings2
25372
25868
  } = host;
25373
25869
  const reportedProjectMessageCleanupErrors = /* @__PURE__ */ new Set();
25870
+ const reportedProjectMessageReadErrors = /* @__PURE__ */ new Set();
25374
25871
  const reportedRetirementErrors = /* @__PURE__ */ new Set();
25375
25872
  const retirementCursors = /* @__PURE__ */ new Map();
25376
25873
  const readLeadSessionIdsFromHost = (inventory, mailboxes, workspaceId2) => readLeadSessionIds(inventory, mailboxes, workspaceId2, host);
@@ -25378,10 +25875,8 @@ function createLeadCoordinationRuntime(host) {
25378
25875
  const limits = await host.messageLimits(ctx);
25379
25876
  return prepareMessageInput(text, files, ctx.cwd, operation, heading, {
25380
25877
  inlineLimitBytes: limits.inline.bytes,
25381
- mailboxLimitBytes: Math.min(
25382
- limits.mailbox.bytes,
25383
- host.coordinationMessageMaxBytes
25384
- ),
25878
+ mailboxLimitBytes: limits.mailbox.bytes,
25879
+ requireInline: true,
25385
25880
  serializedBytes: (candidate, resultBindings) => {
25386
25881
  const record = recordForInput(candidate, resultBindings);
25387
25882
  return typeof record === "number" ? record : host.chiefMessageBytes(record);
@@ -26214,6 +26709,7 @@ function createLeadCoordinationRuntime(host) {
26214
26709
  try {
26215
26710
  removeProjectMessage2(runtime, record.repoKey, record.branch, record.id);
26216
26711
  reportedProjectMessageCleanupErrors.delete(record.id);
26712
+ reportedProjectMessageReadErrors.delete(record.id);
26217
26713
  } catch (error2) {
26218
26714
  if (!reportedProjectMessageCleanupErrors.has(record.id)) {
26219
26715
  reportedProjectMessageCleanupErrors.add(record.id);
@@ -26222,11 +26718,18 @@ function createLeadCoordinationRuntime(host) {
26222
26718
  }
26223
26719
  };
26224
26720
  for (const assignment of listProjectAssignments2(runtime, manager.repoKey)) {
26225
- for (const record of listProjectMessages2(
26226
- runtime,
26227
- manager.repoKey,
26228
- assignment.branch
26229
- )) {
26721
+ let pending;
26722
+ try {
26723
+ pending = listProjectMessageHeaders2(
26724
+ runtime,
26725
+ manager.repoKey,
26726
+ assignment.branch
26727
+ );
26728
+ } catch (error2) {
26729
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
26730
+ return 0;
26731
+ }
26732
+ for (const record of pending) {
26230
26733
  if (record.fromSessionId !== assignment.id) continue;
26231
26734
  if (hasProjectMessageReceipt(record)) {
26232
26735
  consumeProjectMessage(record);
@@ -26240,26 +26743,47 @@ function createLeadCoordinationRuntime(host) {
26240
26743
  );
26241
26744
  if (!ctx.isIdle() || !current || !sameManagerDescriptor2(current, manager) || !stillAssigned || stillAssigned.id !== assignment.id)
26242
26745
  return 0;
26243
- importResultBindings2(pi, ctx, record.resultBindings, "project_message");
26244
- const backlog = record.createdAt < manager.createdAt;
26245
- const actionableFailure = backlog && record.kind === "execution_failure";
26746
+ let message;
26747
+ try {
26748
+ message = readProjectMessage2(
26749
+ runtime,
26750
+ record.repoKey,
26751
+ record.branch,
26752
+ record.id
26753
+ );
26754
+ reportedProjectMessageReadErrors.delete(record.id);
26755
+ } catch (error2) {
26756
+ if (!reportedProjectMessageReadErrors.has(record.id)) {
26757
+ reportedProjectMessageReadErrors.add(record.id);
26758
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
26759
+ }
26760
+ continue;
26761
+ }
26762
+ importResultBindings2(
26763
+ pi,
26764
+ ctx,
26765
+ message.resultBindings,
26766
+ "project_message"
26767
+ );
26768
+ const backlog = message.createdAt < manager.createdAt;
26769
+ const actionableFailure = backlog && message.kind === "execution_failure";
26246
26770
  pi.sendMessage(
26247
26771
  {
26248
26772
  customType: "pi-herdsman-project_message",
26249
- content: `Project ${record.branch} from lead ${record.fromSessionId}:
26773
+ content: `Project ${message.branch} from lead ${message.fromSessionId}:
26250
26774
 
26251
- ${record.text}`,
26775
+ ${message.text}`,
26252
26776
  display: true,
26253
26777
  details: {
26254
- id: record.id,
26255
- repoKey: record.repoKey,
26256
- branch: record.branch,
26257
- fromSessionId: record.fromSessionId
26778
+ id: message.id,
26779
+ repoKey: message.repoKey,
26780
+ branch: message.branch,
26781
+ fromSessionId: message.fromSessionId
26258
26782
  }
26259
26783
  },
26260
26784
  backlog && !actionableFailure ? { triggerTurn: false } : { deliverAs: "followUp", triggerTurn: true }
26261
26785
  );
26262
- if (hasProjectMessageReceipt(record)) consumeProjectMessage(record);
26786
+ if (hasProjectMessageReceipt(message)) consumeProjectMessage(message);
26263
26787
  return 1;
26264
26788
  }
26265
26789
  }
@@ -27382,11 +27906,17 @@ function createLeadRoleTransitions(state, host) {
27382
27906
  assignment.branch
27383
27907
  );
27384
27908
  if (!latest || latest.id !== sessionId) return void 0;
27385
- const existing = listProjectMessages(
27909
+ const existingHeader = listProjectMessageHeaders(
27386
27910
  runtime,
27387
27911
  assignment.repoKey,
27388
27912
  assignment.branch
27389
27913
  ).find((candidate) => candidate.id === id);
27914
+ const existing = existingHeader ? readProjectMessage(
27915
+ runtime,
27916
+ assignment.repoKey,
27917
+ assignment.branch,
27918
+ existingHeader.id
27919
+ ) : void 0;
27390
27920
  if (existing) {
27391
27921
  if (existing.fromSessionId !== sessionId || existing.text !== record.text || existing.kind !== record.kind || JSON.stringify(existing.resultBindings ?? []) !== JSON.stringify(record.resultBindings ?? []))
27392
27922
  throw new Error(
@@ -28092,6 +28622,8 @@ function createLeadRoleTransitions(state, host) {
28092
28622
  if (scope.primaryWorkspaceId !== workspaceId)
28093
28623
  throw new Error("/manager is available only in the primary workspace");
28094
28624
  const profile = host.prepareSupervisoryProfile(ctx, "manager");
28625
+ host.captureInheritedTools?.();
28626
+ const previousTools = host.getLeadTools() ?? host.normalizeLeadTools(host.pi.getActiveTools());
28095
28627
  let lease;
28096
28628
  try {
28097
28629
  lease = host.claimManagerLease({
@@ -28108,7 +28640,6 @@ function createLeadRoleTransitions(state, host) {
28108
28640
  throw new Error("This project already has an active Manager");
28109
28641
  throw error2;
28110
28642
  }
28111
- const previousTools = host.getLeadTools() ?? host.normalizeLeadTools(host.pi.getActiveTools());
28112
28643
  try {
28113
28644
  state.managerLease = lease;
28114
28645
  state.controllerRole = "manager";
@@ -28300,6 +28831,33 @@ function createLeadRoleTransitions(state, host) {
28300
28831
  };
28301
28832
  const reconcileRoleTools = () => {
28302
28833
  if (host.controllerScope?.kind !== "root") return;
28834
+ try {
28835
+ host.captureInheritedTools?.();
28836
+ } catch (error2) {
28837
+ if (state.leadContext)
28838
+ host.appendDurableError(
28839
+ host.pi,
28840
+ state.leadContext,
28841
+ "pi_herdsman_state_error",
28842
+ error2
28843
+ );
28844
+ const inheritingExecution = host.inheritedProjection?.();
28845
+ const canRetryCapture = !state.roleSuspended && state.chiefMode === "inactive" && activeLeadRole(state) === "lead" && inheritingExecution !== void 0;
28846
+ if (canRetryCapture) {
28847
+ const current2 = host.pi.getActiveTools();
28848
+ const permitted = host.normalizeLeadTools(
28849
+ current2.filter(
28850
+ (name) => !inheritingExecution.excluded.some(
28851
+ (pattern) => matchesToolPattern(pattern, name)
28852
+ )
28853
+ )
28854
+ );
28855
+ if (!sameToolSelection(current2, permitted))
28856
+ host.pi.setActiveTools(permitted);
28857
+ return;
28858
+ }
28859
+ host.setInheritedProjection?.(void 0);
28860
+ }
28303
28861
  if (state.controllerRole === "manager" && !state.roleSuspended) {
28304
28862
  let held = false;
28305
28863
  try {
@@ -28323,6 +28881,7 @@ function createLeadRoleTransitions(state, host) {
28323
28881
  }
28324
28882
  }
28325
28883
  if (state.roleSuspended || state.chiefMode === "suspended") {
28884
+ host.setInheritedProjection?.(void 0);
28326
28885
  const baseline = host.normalizeBaseTools(
28327
28886
  host.getLeadTools() ?? host.pi.getActiveTools()
28328
28887
  );
@@ -28331,6 +28890,7 @@ function createLeadRoleTransitions(state, host) {
28331
28890
  return;
28332
28891
  }
28333
28892
  if (activeLeadRole(state) === "chief") {
28893
+ host.setInheritedProjection?.(void 0);
28334
28894
  host.pi.setActiveTools(
28335
28895
  (state.leadContext && host.supervisoryTools(state.leadContext, "chief")) ?? [
28336
28896
  ...host.chiefTools
@@ -28338,12 +28898,22 @@ function createLeadRoleTransitions(state, host) {
28338
28898
  );
28339
28899
  return;
28340
28900
  }
28901
+ if (activeLeadRole(state) === "manager") {
28902
+ host.setInheritedProjection?.(void 0);
28903
+ const managerTools = (state.leadContext && host.supervisoryTools(state.leadContext, "manager")) ?? [
28904
+ ...host.managerTools
28905
+ ];
28906
+ if (!sameToolSelection(host.pi.getActiveTools(), managerTools))
28907
+ host.pi.setActiveTools(managerTools);
28908
+ return;
28909
+ }
28341
28910
  const current = host.pi.getActiveTools();
28342
28911
  const source = host.getLeadTools() ? [...host.getLeadTools()] : host.normalizeBaseTools(current);
28343
- host.pi.setActiveTools(
28344
- activeLeadRole(state) === "manager" ? (state.leadContext && host.supervisoryTools(state.leadContext, "manager")) ?? [
28345
- ...host.managerTools
28346
- ] : host.executionTools?.() ?? host.normalizeLeadTools(source)
28912
+ const next = host.executionTools?.() ?? host.normalizeLeadTools(source);
28913
+ if (!sameToolSelection(current, next)) host.pi.setActiveTools(next);
28914
+ const projection = host.inheritedProjection?.();
28915
+ host.setInheritedProjection?.(
28916
+ !state.roleSuspended && projection !== void 0 && sameToolSelection(host.pi.getActiveTools(), next) ? projection : void 0
28347
28917
  );
28348
28918
  };
28349
28919
  const resolveControllerRole = (ctx, requestedRole, optional = false) => {
@@ -29976,6 +30546,8 @@ ${summary}`,
29976
30546
  isPiAgent,
29977
30547
  writeChiefMessage,
29978
30548
  listProjectAssignments,
30549
+ listProjectMessageHeaders,
30550
+ readProjectMessage,
29979
30551
  listProjectMessages,
29980
30552
  removeProjectMessage,
29981
30553
  readProjectAssignment,