pi-herdsman 0.28.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
15
15
  // package.json
16
16
  var package_default = {
17
17
  name: "pi-herdsman",
18
- version: "0.28.0",
18
+ version: "0.30.0",
19
19
  type: "module",
20
20
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
21
21
  license: "Apache-2.0",
@@ -199,6 +199,15 @@ import { join } from "node:path";
199
199
  var RESULT_PREFIX = "result:";
200
200
  var RESULT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
201
201
  var SEMANTIC_RESULT_REF = /^result:([a-z][a-z0-9_-]{0,31})#([1-9][0-9]*)$/;
202
+ var INCIDENTAL_METADATA = /* @__PURE__ */ new Set([
203
+ ".ds_store",
204
+ "desktop.ini",
205
+ "thumbs.db",
206
+ ".directory"
207
+ ]);
208
+ function isIncidentalMetadata(entry) {
209
+ return entry.isFile() && INCIDENTAL_METADATA.has(entry.name.toLowerCase());
210
+ }
202
211
  function parseSemanticResultRef(input) {
203
212
  const match = SEMANTIC_RESULT_REF.exec(input);
204
213
  if (!match) return void 0;
@@ -372,6 +381,25 @@ function readProcessLockClaim(path, owner) {
372
381
  throw new Error("invalid process lock claim");
373
382
  return claim;
374
383
  }
384
+ function ownerMissing(path) {
385
+ try {
386
+ fs.lstatSync(path);
387
+ return false;
388
+ } catch (error2) {
389
+ if (error2.code === "ENOENT") return true;
390
+ throw error2;
391
+ }
392
+ }
393
+ function lockOwnerEntry(path) {
394
+ const entries = fs.readdirSync(path, { withFileTypes: true });
395
+ const owners = entries.filter((entry) => !isIncidentalMetadata(entry));
396
+ if (owners.length !== 1 || !owners[0].isFile())
397
+ throw new Error("Invalid process lock owner");
398
+ return {
399
+ owner: owners[0].name,
400
+ metadata: entries.filter(isIncidentalMetadata).map((entry) => entry.name)
401
+ };
402
+ }
375
403
  function processExists(pid) {
376
404
  try {
377
405
  process.kill(pid, 0);
@@ -415,14 +443,12 @@ function readLiveProcessLock(path, name = "process lock") {
415
443
  }
416
444
  function readProcessLockStatus(path, name = "process lock") {
417
445
  const verifyMessage = `Unable to verify ${name}`;
418
- let entries;
446
+ let owner;
419
447
  try {
420
- entries = fs.readdirSync(path);
448
+ ({ owner } = lockOwnerEntry(path));
421
449
  } catch (error2) {
422
450
  throw new Error(verifyMessage, { cause: error2 });
423
451
  }
424
- if (entries.length !== 1) throw new Error(verifyMessage);
425
- const owner = entries[0];
426
452
  try {
427
453
  const claim = readProcessLockClaim(path, owner);
428
454
  return { claim, live: processExists(claim.pid) };
@@ -444,9 +470,10 @@ function acquireProcessLock(path, options2 = {}) {
444
470
  const payload = JSON.stringify(claim);
445
471
  const ownerPath = join2(claimDir, owner);
446
472
  try {
447
- if (fs.readdirSync(claimDir).length === 0) throw new Error(verifyMessage);
473
+ lockOwnerEntry(claimDir);
448
474
  } catch (error2) {
449
- if (error2.code !== "ENOENT") throw error2;
475
+ if (error2.code !== "ENOENT")
476
+ throw new Error(verifyMessage, { cause: error2 });
450
477
  }
451
478
  try {
452
479
  publishClaim(parent, claimDir, owner, payload);
@@ -454,17 +481,12 @@ function acquireProcessLock(path, options2 = {}) {
454
481
  const code = error2.code;
455
482
  if (code !== "EEXIST" && code !== "ENOTEMPTY" && code !== "EPERM")
456
483
  throw error2;
457
- let entries;
484
+ let observedOwner;
458
485
  try {
459
- entries = fs.readdirSync(claimDir);
486
+ ({ owner: observedOwner } = lockOwnerEntry(claimDir));
460
487
  } catch {
461
488
  throw new Error(verifyMessage);
462
489
  }
463
- if (entries.length === 0) {
464
- throw new Error(verifyMessage);
465
- }
466
- if (entries.length !== 1) throw new Error(verifyMessage);
467
- const observedOwner = entries[0];
468
490
  let staleClaim;
469
491
  try {
470
492
  staleClaim = readProcessLockClaim(claimDir, observedOwner);
@@ -483,8 +505,8 @@ function acquireProcessLock(path, options2 = {}) {
483
505
  `.${basename(claimDir)}.${randomUUID()}.stale`
484
506
  );
485
507
  try {
486
- const currentEntries = fs.readdirSync(claimDir);
487
- if (currentEntries.length !== 1 || currentEntries[0] !== observedOwner)
508
+ const { owner: currentOwner } = lockOwnerEntry(claimDir);
509
+ if (currentOwner !== observedOwner)
488
510
  throw new ProcessLockOccupiedError(occupiedMessage);
489
511
  const currentClaim = readProcessLockClaim(claimDir, observedOwner);
490
512
  if (currentClaim.pid !== staleClaim.pid || currentClaim.id !== staleClaim.id)
@@ -501,13 +523,14 @@ function acquireProcessLock(path, options2 = {}) {
501
523
  throw new ProcessLockOccupiedError(occupiedMessage);
502
524
  throw new Error(recoverMessage, { cause: removeError });
503
525
  }
504
- let quarantinedEntries;
526
+ let quarantinedOwner;
527
+ let metadata;
505
528
  try {
506
- quarantinedEntries = fs.readdirSync(quarantine);
529
+ ({ owner: quarantinedOwner, metadata } = lockOwnerEntry(quarantine));
507
530
  } catch (error3) {
508
531
  throw new Error(recoverMessage, { cause: error3 });
509
532
  }
510
- if (quarantinedEntries.length !== 1 || quarantinedEntries[0] !== observedOwner)
533
+ if (quarantinedOwner !== observedOwner)
511
534
  throw new ProcessLockOccupiedError(occupiedMessage);
512
535
  try {
513
536
  const quarantinedClaim = readProcessLockClaim(quarantine, observedOwner);
@@ -519,6 +542,7 @@ function acquireProcessLock(path, options2 = {}) {
519
542
  }
520
543
  options2.afterStaleOwnerRemoved?.();
521
544
  try {
545
+ unlinkMetadata(quarantine, metadata);
522
546
  fs.unlinkSync(join2(quarantine, observedOwner));
523
547
  fs.rmdirSync(quarantine);
524
548
  } catch (cleanupError) {
@@ -542,25 +566,75 @@ function claimProcessLock(path, options2 = {}) {
542
566
  return acquireProcessLock(path, options2).release;
543
567
  }
544
568
  function releaseProcessLock(claimDir, ownerPath, claim, name) {
569
+ let owner;
570
+ try {
571
+ ({ owner } = lockOwnerEntry(claimDir));
572
+ } catch (error2) {
573
+ if (error2.code === "ENOENT") return;
574
+ try {
575
+ if (ownerMissing(ownerPath)) return;
576
+ } catch (missing) {
577
+ throw new Error(`Unable to verify ${name} ownership`, { cause: missing });
578
+ }
579
+ throw new Error(`Unable to verify ${name} ownership`, { cause: error2 });
580
+ }
581
+ if (owner !== basename(ownerPath)) {
582
+ try {
583
+ if (ownerMissing(ownerPath)) return;
584
+ } catch (error2) {
585
+ throw new Error(`Unable to verify ${name} ownership`, { cause: error2 });
586
+ }
587
+ throw new Error(
588
+ `${name[0].toUpperCase()}${name.slice(1)} ownership changed`
589
+ );
590
+ }
545
591
  let current;
546
592
  try {
547
593
  current = readProcessLockClaim(claimDir, basename(ownerPath));
548
594
  } catch (error2) {
549
- if (error2.code === "ENOENT") return;
595
+ if (error2.code === "ENOENT" && ownerMissing(ownerPath))
596
+ return;
550
597
  throw new Error(`Unable to verify ${name} ownership`, { cause: error2 });
551
598
  }
552
599
  if (current.pid !== claim.pid || current.id !== claim.id)
553
600
  throw new Error(
554
601
  `${name[0].toUpperCase()}${name.slice(1)} ownership changed`
555
602
  );
556
- fs.unlinkSync(ownerPath);
603
+ const retired = join2(
604
+ dirname(claimDir),
605
+ `.${basename(claimDir)}.${randomUUID()}.released`
606
+ );
607
+ fs.renameSync(claimDir, retired);
608
+ let retiredOwner;
609
+ let metadata;
610
+ try {
611
+ ({ owner: retiredOwner, metadata } = lockOwnerEntry(retired));
612
+ if (retiredOwner !== basename(ownerPath))
613
+ throw new Error("Process lock owner changed");
614
+ const relocated = readProcessLockClaim(retired, retiredOwner);
615
+ if (relocated.pid !== claim.pid || relocated.id !== claim.id)
616
+ throw new Error("Process lock generation changed");
617
+ } catch (error2) {
618
+ throw new Error(`Unable to verify ${name} ownership`, { cause: error2 });
619
+ }
620
+ unlinkMetadata(retired, metadata);
621
+ fs.unlinkSync(join2(retired, retiredOwner));
557
622
  try {
558
- fs.rmdirSync(claimDir);
623
+ fs.rmdirSync(retired);
559
624
  } catch (error2) {
560
625
  const code = error2.code;
561
626
  if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error2;
562
627
  }
563
628
  }
629
+ function unlinkMetadata(path, entries) {
630
+ for (const entry of entries) {
631
+ try {
632
+ fs.unlinkSync(join2(path, entry));
633
+ } catch (error2) {
634
+ if (error2.code !== "ENOENT") throw error2;
635
+ }
636
+ }
637
+ }
564
638
 
565
639
  // extension/mailbox.ts
566
640
  var MANAGED_AGENT_BOOTSTRAP_LIMIT_BYTES = 64 * 1024;
@@ -6479,7 +6553,7 @@ function renderCompletionMessage(message, options2, theme) {
6479
6553
  const metadata = [
6480
6554
  ...d?.agentDefinition ? [`definition: ${d.agentDefinition}`] : [],
6481
6555
  ...d?.piSessionId ? [`session: ${d.piSessionId}`] : [],
6482
- ...d?.sessionRetired ? ["continuation: fresh agent required"] : [],
6556
+ ...d?.sessionRetired === true ? ["continuation: fresh agent required"] : d?.sessionRetired === null ? ["continuation: policy unverified"] : [],
6483
6557
  ...d?.requestId ? [`request: ${d.requestId}`] : [],
6484
6558
  ...elapsed ? [`elapsed: ${elapsed}`] : [],
6485
6559
  ...d?.contextUsage?.percent != null ? [`context: ${Math.round(d.contextUsage.percent)}%`] : [],
@@ -6504,7 +6578,7 @@ function renderCompletionMessage(message, options2, theme) {
6504
6578
  }
6505
6579
  } else {
6506
6580
  const notices = [
6507
- ...d?.sessionRetired ? ["session retired"] : [],
6581
+ ...d?.sessionRetired === true ? ["session retired"] : d?.sessionRetired === null ? ["retirement policy unverified"] : [],
6508
6582
  ...d?.truncated === true ? ["output truncated"] : [],
6509
6583
  ...d?.resultPersistenceError ? ["result not saved"] : []
6510
6584
  ];
@@ -6908,6 +6982,43 @@ function readRawConfig() {
6908
6982
  function readConfig() {
6909
6983
  return { ...DEFAULT_CONFIG, ...readRawConfig() };
6910
6984
  }
6985
+ function readProjectOverrides(ctx) {
6986
+ if (!ctx.isProjectTrusted()) return {};
6987
+ const path = join7(ctx.cwd, ".pi", "settings.json");
6988
+ let content;
6989
+ try {
6990
+ content = readFileSync7(path, "utf8");
6991
+ } catch (error2) {
6992
+ if (error2.code === "ENOENT") return {};
6993
+ throw error2;
6994
+ }
6995
+ let settings;
6996
+ try {
6997
+ settings = JSON.parse(content.replace(/^\uFEFF/, ""));
6998
+ } catch (error2) {
6999
+ throw new Error(
7000
+ `Invalid project settings ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
7001
+ );
7002
+ }
7003
+ if (!settings || typeof settings !== "object" || Array.isArray(settings))
7004
+ throw new Error(`Invalid project settings ${path}: expected an object`);
7005
+ const raw = settings.piHerdsman;
7006
+ if (raw === void 0) return {};
7007
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
7008
+ throw new Error(`Invalid ${path}: piHerdsman must be an object`);
7009
+ const overrides = {};
7010
+ for (const [key, value2] of Object.entries(raw)) {
7011
+ if (key !== "autoActivateManager" && key !== "contextRetirement")
7012
+ throw new Error(`Invalid ${path}: unsupported piHerdsman field ${key}`);
7013
+ if (typeof value2 !== "boolean")
7014
+ throw new Error(`Invalid ${path}: piHerdsman.${key} must be boolean`);
7015
+ overrides[key] = value2;
7016
+ }
7017
+ return overrides;
7018
+ }
7019
+ function readEffectiveConfig(ctx) {
7020
+ return { ...readConfig(), ...readProjectOverrides(ctx) };
7021
+ }
6911
7022
  function writeConfigAtomically(path, content) {
6912
7023
  const directory = dirname5(path);
6913
7024
  const temporaryPath = join7(
@@ -6974,9 +7085,8 @@ import {
6974
7085
  chmodSync as chmodSync7,
6975
7086
  closeSync as closeSync8,
6976
7087
  fsyncSync as fsyncSync4,
6977
- lstatSync,
7088
+ lstatSync as lstatSync2,
6978
7089
  readdirSync as readdirSync5,
6979
- rmSync,
6980
7090
  mkdirSync as mkdirSync7,
6981
7091
  openSync as openSync8,
6982
7092
  readFileSync as readFileSync8,
@@ -8185,10 +8295,13 @@ function readProjectAssignment(runtime, repoKey, branch) {
8185
8295
  const path = projectAssignmentPath(runtime, repoKey, branch);
8186
8296
  return readProjectAssignmentFile(path, repoKey, branch);
8187
8297
  }
8188
- function readProjectAssignmentFile(path, repoKey, branch) {
8298
+ function readProjectAssignmentFile(path, repoKey, branch, pending = false) {
8189
8299
  let value2;
8190
8300
  try {
8191
- if (statSync4(path).size > PROJECT_ASSIGNMENT_FILE_MAX_BYTES)
8301
+ const file2 = lstatSync2(path);
8302
+ if (!file2.isFile() || file2.isSymbolicLink())
8303
+ throw new Error("invalid file");
8304
+ if (file2.size > PROJECT_ASSIGNMENT_FILE_MAX_BYTES)
8192
8305
  throw new Error("file is too large");
8193
8306
  value2 = JSON.parse(readFileSync8(path, "utf8"));
8194
8307
  } catch (error2) {
@@ -8200,7 +8313,7 @@ function readProjectAssignmentFile(path, repoKey, branch) {
8200
8313
  throw projectAssignmentReadError(path, "invalid assignment schema");
8201
8314
  if (projectAssignmentBytes(value2) > PROJECT_ASSIGNMENT_MAX_BYTES)
8202
8315
  throw projectAssignmentReadError(path, "assignment payload is too large");
8203
- if (repoKey !== void 0 && value2.repoKey !== repoKey || basename5(dirname6(path)) !== createHash6("sha256").update(value2.repoKey).digest("hex") || branch !== void 0 && value2.branch !== branch || basename5(path) !== `${createHash6("sha256").update(value2.branch).digest("hex")}.json`)
8316
+ if (repoKey !== void 0 && value2.repoKey !== repoKey || basename5(dirname6(path)) !== createHash6("sha256").update(value2.repoKey).digest("hex") || branch !== void 0 && value2.branch !== branch || basename5(path) !== `${createHash6("sha256").update(value2.branch).digest("hex")}${pending ? `.${value2.id}` : ""}.json`)
8204
8317
  throw projectAssignmentReadError(path, "assignment identity mismatch");
8205
8318
  return value2;
8206
8319
  }
@@ -8238,11 +8351,158 @@ function findProjectAssignmentBySession2(runtime, repoKey, sessionId) {
8238
8351
  (assignment) => assignment.id === sessionId
8239
8352
  );
8240
8353
  }
8241
- function removeProjectAssignment(runtime, repoKey, branch) {
8242
- withProjectAssignmentLock(
8243
- () => removeProjectAssignmentUnlocked(runtime, repoKey, branch)
8354
+ function releaseProjectAssignment(runtime, expected) {
8355
+ return withProjectAssignmentLock(() => {
8356
+ const current = readProjectAssignment(
8357
+ runtime,
8358
+ expected.repoKey,
8359
+ expected.branch
8360
+ );
8361
+ if (!current || current.id !== expected.id) return false;
8362
+ removeProjectAssignmentUnlocked(runtime, expected.repoKey, expected.branch);
8363
+ return true;
8364
+ });
8365
+ }
8366
+ function retireProjectAssignment(runtime, expected) {
8367
+ return withProjectAssignmentLock(() => {
8368
+ for (const directory of [
8369
+ herdsmanDataRoot(),
8370
+ dirname6(dirname6(runtime.root)),
8371
+ dirname6(runtime.root),
8372
+ runtime.root,
8373
+ runtime.assignments,
8374
+ dirname6(
8375
+ projectAssignmentPath(runtime, expected.repoKey, expected.branch)
8376
+ )
8377
+ ])
8378
+ assignmentDirectory(directory);
8379
+ const current = readProjectAssignment(
8380
+ runtime,
8381
+ expected.repoKey,
8382
+ expected.branch
8383
+ );
8384
+ if (!current || current.id !== expected.id) return false;
8385
+ const source = projectAssignmentPath(
8386
+ runtime,
8387
+ current.repoKey,
8388
+ current.branch
8389
+ );
8390
+ const destination = pendingRetirementPath(runtime, current);
8391
+ const root2 = join8(runtime.root, "retirements");
8392
+ for (const directory of [root2, dirname6(destination)]) {
8393
+ try {
8394
+ mkdirSync7(directory, { mode: 448 });
8395
+ } catch (error2) {
8396
+ if (error2.code !== "EEXIST") throw error2;
8397
+ }
8398
+ assignmentDirectory(directory);
8399
+ }
8400
+ if (lstatSync2(destination, { throwIfNoEntry: false }))
8401
+ throw new Error("Pending retirement already exists");
8402
+ renameSync6(source, destination);
8403
+ fsyncDirectory(dirname6(source));
8404
+ fsyncDirectory(dirname6(destination));
8405
+ fsyncDirectory(root2);
8406
+ fsyncDirectory(runtime.root);
8407
+ return true;
8408
+ });
8409
+ }
8410
+ function pendingRetirementPath(runtime, expected) {
8411
+ if (!validProjectAssignment(expected))
8412
+ throw new Error("Invalid project assignment");
8413
+ const active = projectAssignmentPath(
8414
+ runtime,
8415
+ expected.repoKey,
8416
+ expected.branch
8417
+ );
8418
+ return join8(
8419
+ runtime.root,
8420
+ "retirements",
8421
+ basename5(dirname6(active)),
8422
+ `${basename5(active, ".json")}.${expected.id}.json`
8244
8423
  );
8245
8424
  }
8425
+ function listPendingRetirements(runtime, repoKey, options2 = {}) {
8426
+ const repository = basename5(
8427
+ dirname6(projectAssignmentPath(runtime, repoKey, "lookup"))
8428
+ );
8429
+ const root2 = join8(runtime.root, "retirements");
8430
+ const directory = join8(root2, repository);
8431
+ let entries;
8432
+ try {
8433
+ for (const parent of [
8434
+ herdsmanDataRoot(),
8435
+ dirname6(dirname6(runtime.root)),
8436
+ dirname6(runtime.root),
8437
+ runtime.root,
8438
+ root2,
8439
+ directory
8440
+ ])
8441
+ assignmentDirectory(parent);
8442
+ entries = readdirSync5(directory);
8443
+ } catch (error2) {
8444
+ if (error2.code === "ENOENT") return [];
8445
+ throw error2;
8446
+ }
8447
+ entries.sort();
8448
+ const start = options2.after ? Math.max(
8449
+ 0,
8450
+ entries.findIndex((entry) => entry > options2.after)
8451
+ ) : 0;
8452
+ const ordered = [...entries.slice(start), ...entries.slice(0, start)];
8453
+ const records = [];
8454
+ const recordLimit = Math.min(
8455
+ options2.recordLimit ?? COORDINATION_INBOX_SCAN_LIMIT,
8456
+ COORDINATION_INBOX_SCAN_LIMIT
8457
+ );
8458
+ for (const entry of ordered.slice(0, COORDINATION_INBOX_SCAN_LIMIT)) {
8459
+ options2.onScanned?.(entry);
8460
+ const path = join8(directory, entry);
8461
+ try {
8462
+ const record = readProjectAssignmentFile(path, repoKey, void 0, true);
8463
+ if (!record)
8464
+ throw projectAssignmentReadError(
8465
+ path,
8466
+ "file disappeared while listing"
8467
+ );
8468
+ records.push(record);
8469
+ if (records.length >= recordLimit) break;
8470
+ } catch (error2) {
8471
+ const failure = error2 instanceof Error ? error2 : new Error(String(error2));
8472
+ if (!options2.onReadError) throw failure;
8473
+ options2.onReadError(failure);
8474
+ }
8475
+ }
8476
+ return records.sort(
8477
+ (a, b) => a.branch.localeCompare(b.branch) || a.id.localeCompare(b.id)
8478
+ );
8479
+ }
8480
+ function removePendingRetirement(runtime, expected) {
8481
+ withProjectAssignmentLock(() => {
8482
+ const path = pendingRetirementPath(runtime, expected);
8483
+ const root2 = join8(runtime.root, "retirements");
8484
+ for (const directory of [
8485
+ herdsmanDataRoot(),
8486
+ dirname6(dirname6(runtime.root)),
8487
+ dirname6(runtime.root),
8488
+ runtime.root,
8489
+ root2,
8490
+ dirname6(path)
8491
+ ])
8492
+ assignmentDirectory(directory);
8493
+ const record = readProjectAssignmentFile(
8494
+ path,
8495
+ expected.repoKey,
8496
+ expected.branch,
8497
+ true
8498
+ );
8499
+ if (!record) return;
8500
+ if (record.id !== expected.id)
8501
+ throw new Error("Pending retirement identity mismatch");
8502
+ unlinkSync6(path);
8503
+ fsyncDirectory(dirname6(path));
8504
+ });
8505
+ }
8246
8506
  function removeProjectAssignmentUnlocked(runtime, repoKey, branch) {
8247
8507
  const path = projectAssignmentPath(runtime, repoKey, branch);
8248
8508
  try {
@@ -8253,7 +8513,7 @@ function removeProjectAssignmentUnlocked(runtime, repoKey, branch) {
8253
8513
  }
8254
8514
  }
8255
8515
  function assignmentDirectory(path) {
8256
- const stat = lstatSync(path);
8516
+ const stat = lstatSync2(path);
8257
8517
  if (!stat.isDirectory() || stat.isSymbolicLink())
8258
8518
  throw new Error(`Invalid project assignment authority directory ${path}`);
8259
8519
  }
@@ -8273,6 +8533,7 @@ function scanGlobalProjectAssignments() {
8273
8533
  }
8274
8534
  const bySession = /* @__PURE__ */ new Map();
8275
8535
  for (const socket of sockets) {
8536
+ if (isIncidentalMetadata(socket)) continue;
8276
8537
  if (!/^[a-f0-9]{64}$/.test(socket.name))
8277
8538
  throw new Error(
8278
8539
  `Unexpected project assignment socket entry ${socket.name}`
@@ -8294,6 +8555,7 @@ function scanGlobalProjectAssignments() {
8294
8555
  }
8295
8556
  assignmentDirectory(assignmentsRoot);
8296
8557
  for (const repository of repositories) {
8558
+ if (isIncidentalMetadata(repository)) continue;
8297
8559
  if (!/^[a-f0-9]{64}$/.test(repository.name))
8298
8560
  throw new Error(
8299
8561
  `Unexpected project assignment repository entry ${repository.name}`
@@ -8305,6 +8567,12 @@ function scanGlobalProjectAssignments() {
8305
8567
  const directory = join8(assignmentsRoot, repository.name);
8306
8568
  assignmentDirectory(directory);
8307
8569
  for (const entry of readdirSync5(directory, { withFileTypes: true })) {
8570
+ if (isIncidentalMetadata(entry)) continue;
8571
+ if (/^[a-f0-9]{64}\.messages$/.test(entry.name)) {
8572
+ if (!entry.isDirectory() || entry.isSymbolicLink())
8573
+ throw new Error(`Invalid project message directory ${entry.name}`);
8574
+ continue;
8575
+ }
8308
8576
  if (/^\..+\.[a-f0-9-]{36}\.tmp$/.test(entry.name)) {
8309
8577
  if (!entry.isFile() || entry.isSymbolicLink())
8310
8578
  throw new Error(
@@ -8438,20 +8706,18 @@ function listProjectMessages(runtime, repoKey, branch) {
8438
8706
  if (error2.code === "ENOENT") return [];
8439
8707
  throw error2;
8440
8708
  }
8441
- return entries.filter((entry) => UUID3.test(entry.slice(0, -5)) && entry.endsWith(".json")).map((entry) => {
8442
- const path = join8(directory, entry);
8709
+ return entries.filter((entry) => UUID3.test(entry.slice(0, -5)) && entry.endsWith(".json")).flatMap((entry) => {
8710
+ let value2;
8443
8711
  try {
8444
- if (statSync4(path).size > COORDINATION_MESSAGE_MAX_BYTES)
8445
- throw new Error("large");
8446
- const value2 = JSON.parse(readFileSync8(path, "utf8"));
8447
- if (!validProjectMessage(value2) || value2.repoKey !== repoKey || value2.branch !== branch || entry !== `${value2.id}.json`)
8448
- throw new Error("invalid");
8449
- return value2;
8712
+ value2 = readProjectMessageFile(join8(directory, entry));
8450
8713
  } catch (error2) {
8451
- throw new Error(`Unable to read project message ${path}`, {
8452
- cause: error2
8453
- });
8714
+ if (error2 instanceof Error && error2.cause?.code === "ENOENT")
8715
+ return [];
8716
+ throw error2;
8454
8717
  }
8718
+ if (value2.repoKey !== repoKey || value2.branch !== branch)
8719
+ throw new Error(`Project message identity does not match ${directory}`);
8720
+ return [value2];
8455
8721
  }).sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
8456
8722
  }
8457
8723
  function removeProjectMessage(runtime, repoKey, branch, id) {
@@ -8464,12 +8730,80 @@ function removeProjectMessage(runtime, repoKey, branch, id) {
8464
8730
  if (error2.code !== "ENOENT") throw error2;
8465
8731
  }
8466
8732
  }
8467
- function removeProjectMessages(runtime, repoKey, branch) {
8468
- rmSync(projectMessageDirectory(runtime, repoKey, branch), {
8469
- recursive: true,
8470
- force: true
8733
+ function readProjectMessageFile(path) {
8734
+ try {
8735
+ if (statSync4(path).size > COORDINATION_MESSAGE_MAX_BYTES)
8736
+ throw new Error("large");
8737
+ const value2 = JSON.parse(readFileSync8(path, "utf8"));
8738
+ if (!validProjectMessage(value2) || basename5(path) !== `${value2.id}.json`)
8739
+ throw new Error("invalid");
8740
+ return value2;
8741
+ } catch (error2) {
8742
+ throw new Error(`Unable to read project message ${path}`, { cause: error2 });
8743
+ }
8744
+ }
8745
+ function removeProjectMessagesForAssignment(runtime, assignment) {
8746
+ for (const message of listProjectMessages(
8747
+ runtime,
8748
+ assignment.repoKey,
8749
+ assignment.branch
8750
+ )) {
8751
+ if (message.fromSessionId === assignment.id)
8752
+ removeProjectMessage(
8753
+ runtime,
8754
+ assignment.repoKey,
8755
+ assignment.branch,
8756
+ message.id
8757
+ );
8758
+ }
8759
+ }
8760
+ function recoverStaleProjectMessages(runtime, repoKey) {
8761
+ withProjectAssignmentLock(() => {
8762
+ const directory = dirname6(
8763
+ projectAssignmentPath(runtime, repoKey, "lookup")
8764
+ );
8765
+ let entries;
8766
+ try {
8767
+ const dataRoot = herdsmanDataRoot();
8768
+ for (const path of [
8769
+ dataRoot,
8770
+ join8(dataRoot, "runtime"),
8771
+ join8(dataRoot, "runtime", "supervision-v2"),
8772
+ runtime.root,
8773
+ runtime.assignments,
8774
+ directory
8775
+ ])
8776
+ assignmentDirectory(path);
8777
+ entries = readdirSync5(directory);
8778
+ } catch (error2) {
8779
+ if (error2.code === "ENOENT") return;
8780
+ throw error2;
8781
+ }
8782
+ for (const entry of entries.filter(
8783
+ (entry2) => /^[a-f0-9]{64}\.messages$/.test(entry2)
8784
+ )) {
8785
+ const messages = join8(directory, entry);
8786
+ assignmentDirectory(messages);
8787
+ for (const file2 of readdirSync5(messages).filter(
8788
+ (file3) => UUID3.test(file3.slice(0, -5)) && file3.endsWith(".json")
8789
+ )) {
8790
+ const path = join8(messages, file2);
8791
+ let message;
8792
+ try {
8793
+ message = readProjectMessageFile(path);
8794
+ } catch (error2) {
8795
+ if (error2 instanceof Error && error2.cause?.code === "ENOENT")
8796
+ continue;
8797
+ throw error2;
8798
+ }
8799
+ if (message.repoKey !== repoKey || projectMessageDirectory(runtime, message.repoKey, message.branch) !== messages)
8800
+ throw new Error(`Project message identity does not match ${path}`);
8801
+ const current = readProjectAssignment(runtime, repoKey, message.branch);
8802
+ if (!current || current.id !== message.fromSessionId)
8803
+ removeProjectMessage(runtime, repoKey, message.branch, message.id);
8804
+ }
8805
+ }
8471
8806
  });
8472
- fsyncDirectory(dirname6(projectAssignmentPath(runtime, repoKey, branch)));
8473
8807
  }
8474
8808
  function verifyManagerCoordinationAuthority(descriptor, coordinator, build, requireCompatibleBuild2) {
8475
8809
  if (!coordinator || coordinator.role !== "manager" || coordinator.piSessionId !== descriptor.piSessionId)
@@ -8585,13 +8919,9 @@ function projectWorkSnapshot(options2) {
8585
8919
  issue = "project runtime identity is ambiguous";
8586
8920
  } else {
8587
8921
  const workspaceId = worktrees[0]?.open_workspace_id ?? void 0;
8588
- const occupants = workspaceId ? options2.leads.filter((lead) => lead.workspaceId === workspaceId) : [];
8589
8922
  if (exact.length === 1 && (!workspaceId || exact[0].workspaceId !== workspaceId)) {
8590
8923
  status = "conflict";
8591
8924
  issue = "assigned Lead is running outside its branch worktree";
8592
- } else if (occupants.some((lead) => lead.lead !== assignment.id)) {
8593
- status = "conflict";
8594
- issue = "another Lead is active in this worktree";
8595
8925
  } else if (exact.length === 1) {
8596
8926
  status = "active";
8597
8927
  runtimeState = exact[0].runtimeState;
@@ -9858,12 +10188,16 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
9858
10188
  `Saved assignment session has no non-empty cwd in its session header: ${child.path}`,
9859
10189
  "continue"
9860
10190
  );
9861
- if (options2.contextRetirement && options2.isContextRetired?.(manager))
9862
- fail(
9863
- "invalid_request",
9864
- `Managed agent session ${child.id} is retired after context pressure. Delegate a fresh agent and pass the previous result/handoff and relevant files.`,
9865
- "continue"
9866
- );
10191
+ const retired = options2.isContextRetired?.(manager) ?? false;
10192
+ if (retired) {
10193
+ const enabled = options2.contextRetirementForSession?.(ctx, manager);
10194
+ if (enabled !== false)
10195
+ fail(
10196
+ "invalid_request",
10197
+ enabled === true ? `Managed agent session ${child.id} is retired after context pressure. Delegate a fresh agent and pass the previous result/handoff and relevant files.` : `Cannot verify the retirement policy for saved agent session ${child.id}. Continue from the original trusted project context or create a fresh Agent.`,
10198
+ "continue"
10199
+ );
10200
+ }
9867
10201
  return {
9868
10202
  path: child.path,
9869
10203
  id: child.id,
@@ -12426,8 +12760,8 @@ function createAgentController(pi, options2) {
12426
12760
  "pi_herdsman_result_error",
12427
12761
  completion.persistenceError
12428
12762
  );
12429
- const sessionRetired = options2.sessionRetired(runtime);
12430
- const retirement = sessionRetired ? "Session retired after context pressure. Do not continue this session. For follow-up, delegate a fresh agent and pass this result/handoff plus the relevant files." : void 0;
12763
+ const sessionRetired = options2.sessionRetired(context, runtime);
12764
+ const retirement = sessionRetired === true ? "Session retired after context pressure. Do not continue this session. For follow-up, delegate a fresh agent and pass this result/handoff plus the relevant files." : sessionRetired === void 0 ? "The saved session's retirement policy could not be verified. Continue only from its original trusted project context or create a fresh Agent." : void 0;
12431
12765
  const status = resultStatus(runtime, result.requestId, entries);
12432
12766
  const header = [
12433
12767
  "Agent result",
@@ -12455,7 +12789,7 @@ function createAgentController(pi, options2) {
12455
12789
  ...runtime.piSessionFile !== void 0 ? { piSessionFile: runtime.piSessionFile } : {},
12456
12790
  agentDefinition: runtime.agentDefinition,
12457
12791
  status: result.status,
12458
- sessionRetired,
12792
+ sessionRetired: sessionRetired ?? null,
12459
12793
  ...elapsedMs !== void 0 ? { elapsedMs } : {},
12460
12794
  contextUsage: result.contextUsage,
12461
12795
  truncated: completion.truncated,
@@ -12574,8 +12908,8 @@ function createAgentController(pi, options2) {
12574
12908
  p.action
12575
12909
  );
12576
12910
  const resumed = p.action === "continue" ? resolveAssignmentSession(ctx, p.session, {
12577
- contextRetirement: readConfig().contextRetirement,
12578
- isContextRetired: options2.isContextRetired
12911
+ isContextRetired: options2.isContextRetired,
12912
+ contextRetirementForSession: (context, manager) => sameCwd(context.cwd, manager.getCwd()) ? readEffectiveConfig(context).contextRetirement : void 0
12579
12913
  }) : void 0;
12580
12914
  await herdrVersion(pi, ctx, signal);
12581
12915
  const agentDefinition = resumed ? resumed.definition : p.definition;
@@ -13336,11 +13670,11 @@ ${result.stderr ?? ""}`.trim(),
13336
13670
  description: "Allowed Agent definition."
13337
13671
  } : Type.String({
13338
13672
  description: "Agent definition for a fresh Agent.",
13339
- pattern: "\\S"
13673
+ minLength: 1
13340
13674
  }),
13341
13675
  task: Type.String({
13342
13676
  description: "Non-empty assignment.",
13343
- pattern: "\\S"
13677
+ minLength: 1
13344
13678
  }),
13345
13679
  label: Type.Optional(
13346
13680
  Type.String({
@@ -13356,11 +13690,11 @@ ${result.stderr ?? ""}`.trim(),
13356
13690
  {
13357
13691
  session: Type.String({
13358
13692
  description: "Exact saved managed-Agent Pi session path or full UUID.",
13359
- pattern: "\\S"
13693
+ minLength: 1
13360
13694
  }),
13361
13695
  task: Type.String({
13362
13696
  description: "Non-empty assignment.",
13363
- pattern: "\\S"
13697
+ minLength: 1
13364
13698
  }),
13365
13699
  files: FILES_SCHEMA
13366
13700
  },
@@ -13369,7 +13703,7 @@ ${result.stderr ?? ""}`.trim(),
13369
13703
  const agentMessageParameters = Type.Object(
13370
13704
  {
13371
13705
  agent: Type.String({ pattern: AGENT_LABEL_PATTERN.source }),
13372
- message: Type.String({ pattern: "\\S" }),
13706
+ message: Type.String({ minLength: 1 }),
13373
13707
  files: FILES_SCHEMA
13374
13708
  },
13375
13709
  { additionalProperties: false }
@@ -16239,8 +16573,9 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
16239
16573
  }
16240
16574
  });
16241
16575
  registerManagedAgentContextHandlers(pi, {
16242
- contextRetirementEnabled: () => readConfig().contextRetirement,
16243
- hasActiveAssignment: () => !!execution.assignment?.activeRequestId
16576
+ contextRetirementEnabled: (ctx) => readEffectiveConfig(ctx).contextRetirement,
16577
+ hasActiveAssignment: () => !!execution.assignment?.activeRequestId,
16578
+ reportConfigError: (ctx, error2) => options2.appendError(ctx, "pi_herdsman_config_error", error2)
16244
16579
  });
16245
16580
  }
16246
16581
  function createManagedAgentRequestState(pi, options2) {
@@ -16417,12 +16752,28 @@ function registerManagedAgentContextHandlers(pi, options2) {
16417
16752
  let pendingGuidance;
16418
16753
  let queuedGuidanceSessionId;
16419
16754
  let bridgedGuidanceSessionId;
16755
+ let reportedConfigError = false;
16756
+ const retirementEnabled = (ctx) => {
16757
+ try {
16758
+ return options2.contextRetirementEnabled(ctx);
16759
+ } catch (error2) {
16760
+ if (!reportedConfigError) {
16761
+ reportedConfigError = true;
16762
+ options2.reportConfigError(ctx, error2);
16763
+ ctx.ui.notify(
16764
+ "Herdsman configuration error; context retirement remains enabled for safety.",
16765
+ "error"
16766
+ );
16767
+ }
16768
+ return true;
16769
+ }
16770
+ };
16420
16771
  pi.on(
16421
16772
  "session_before_compact",
16422
16773
  (event, ctx) => {
16423
- if (!options2.contextRetirementEnabled()) return;
16424
- if (!options2.hasActiveAssignment()) return;
16425
16774
  if (event.reason === "manual") return;
16775
+ if (!retirementEnabled(ctx)) return;
16776
+ if (!options2.hasActiveAssignment()) return;
16426
16777
  const sessionId = ctx.sessionManager.getSessionId();
16427
16778
  const entries = ctx.sessionManager.getEntries();
16428
16779
  const retired = sessionContextRetired(entries, sessionId);
@@ -16480,7 +16831,7 @@ function registerManagedAgentContextHandlers(pi, options2) {
16480
16831
  if (!pending) return;
16481
16832
  pendingGuidance = void 0;
16482
16833
  const sessionId = ctx.sessionManager.getSessionId();
16483
- if (!options2.contextRetirementEnabled() || !options2.hasActiveAssignment() || sessionId !== pending.sessionId)
16834
+ if (!retirementEnabled(ctx) || !options2.hasActiveAssignment() || sessionId !== pending.sessionId)
16484
16835
  return;
16485
16836
  bridgedGuidanceSessionId = sessionId;
16486
16837
  const alreadyVisible = event.messages.some(
@@ -16502,7 +16853,7 @@ function registerManagedAgentContextHandlers(pi, options2) {
16502
16853
  };
16503
16854
  });
16504
16855
  pi.on("tool_call", (event, ctx) => {
16505
- if (!options2.contextRetirementEnabled() || !options2.hasActiveAssignment() || event.toolName !== "delegate_agent" && event.toolName !== "continue_agent")
16856
+ if (!retirementEnabled(ctx) || !options2.hasActiveAssignment() || event.toolName !== "delegate_agent" && event.toolName !== "continue_agent")
16506
16857
  return;
16507
16858
  if (!sessionContextRetired(
16508
16859
  ctx.sessionManager.getEntries(),
@@ -16900,7 +17251,14 @@ function createLeadSessionStartRuntime(host) {
16900
17251
  }
16901
17252
  skipLeadExecutionProfileResolution = persistedRole === "chief";
16902
17253
  host.roleTransitions.reconcileRoleTools();
16903
- const optionalManager = !hasPersistedRole && !malformedRole && host.autoActivateManager();
17254
+ let optionalManager = false;
17255
+ if (!hasPersistedRole && !malformedRole) {
17256
+ try {
17257
+ optionalManager = host.autoActivateManager(ctx);
17258
+ } catch (error2) {
17259
+ host.appendRoleError(ctx, error2);
17260
+ }
17261
+ }
16904
17262
  let leadStateRestored = false;
16905
17263
  let leadStateValid = !optionalManager;
16906
17264
  if (optionalManager && host.roleTransitions.canRestoreChiefState()) {
@@ -17072,6 +17430,7 @@ function createLeadAgentEventRuntime(host) {
17072
17430
  delete sections.agent_definitions;
17073
17431
  const message = await host.prepareSupervisionMessage(ctx);
17074
17432
  if (message) host.sendMessage(message);
17433
+ await host.drainRetirementNotices(ctx, true);
17075
17434
  return;
17076
17435
  }
17077
17436
  const supervisorStateMessage2 = host.isActiveLead() ? await host.prepareLeadSupervisorStateMessage(ctx) : void 0;
@@ -17640,6 +17999,15 @@ Active work or pending results may be discarded.`
17640
17999
  let selectedSetting = "auto-activate-manager";
17641
18000
  while (true) {
17642
18001
  const config = host.readConfig();
18002
+ let effective;
18003
+ let overrides;
18004
+ try {
18005
+ effective = host.readEffectiveConfig(ctx);
18006
+ overrides = host.readProjectOverrides(ctx);
18007
+ } catch (error2) {
18008
+ ctx.ui.notify(String(error2).replace(/^Error: /, ""), "error");
18009
+ return;
18010
+ }
17643
18011
  const selected = await host.selectMenu(
17644
18012
  ctx,
17645
18013
  "Settings",
@@ -17653,13 +18021,13 @@ Active work or pending results may be discarded.`
17653
18021
  {
17654
18022
  value: "auto-activate-manager",
17655
18023
  label: "Manager auto-start",
17656
- description: config.autoActivateManager ? "on" : "off",
18024
+ description: `Global ${config.autoActivateManager ? "on" : "off"} \xB7 Effective ${effective.autoActivateManager ? "on" : "off"}${"autoActivateManager" in overrides ? " \xB7 Project" : ""}`,
17657
18025
  help: "Attempt Manager mode automatically on eligible future session starts. Changing this does not alter the current role."
17658
18026
  },
17659
18027
  {
17660
18028
  value: "context-retirement",
17661
18029
  label: "Context retirement",
17662
- description: config.contextRetirement ? "on" : "off",
18030
+ description: `Global ${config.contextRetirement ? "on" : "off"} \xB7 Effective ${effective.contextRetirement ? "on" : "off"}${"contextRetirement" in overrides ? " \xB7 Project" : ""}`,
17663
18031
  help: "Retire managed-Agent sessions at automatic context pressure instead of allowing normal threshold compaction."
17664
18032
  },
17665
18033
  {
@@ -17690,7 +18058,7 @@ Active work or pending results may be discarded.`
17690
18058
  const enabled = !host.readConfig()[key];
17691
18059
  host.updateConfig(key, enabled);
17692
18060
  ctx.ui.notify(
17693
- `${key === "contextRetirement" ? "Context retirement" : "Manager auto-start"}: ${enabled ? "on" : "off"}`
18061
+ `Global ${key === "contextRetirement" ? "context retirement" : "Manager auto-start"}: ${enabled ? "on" : "off"}`
17694
18062
  );
17695
18063
  }
17696
18064
  }
@@ -18065,6 +18433,7 @@ function registerLeadRuntime(pi, options2) {
18065
18433
  const remoteChiefAgent = (...args) => identityRuntime.remoteChiefAgent(...args);
18066
18434
  const liveLead = (...args) => identityRuntime.liveLead(...args);
18067
18435
  const coordinationServices = {
18436
+ withProjectAssignmentLock: (repoKey, branch, operation) => roleTransitions.withProjectAssignmentLock(repoKey, branch, operation),
18068
18437
  ...options2.coordinationHost,
18069
18438
  workspaceId: () => options2.roleTransitionHost.workspaceId(),
18070
18439
  currentManager: (...args) => roleTransitions.currentManager(...args),
@@ -18112,9 +18481,10 @@ function registerLeadRuntime(pi, options2) {
18112
18481
  options2.projectHost.writeProjectAssignment(...args);
18113
18482
  supervisionUiRuntime.requestRefresh();
18114
18483
  };
18115
- const removeProjectAssignment2 = (...args) => {
18116
- options2.roleTransitionHost.removeProjectAssignment(...args);
18484
+ const retireProjectAssignment2 = (...args) => {
18485
+ const retired = options2.roleTransitionHost.retireProjectAssignment(...args);
18117
18486
  supervisionUiRuntime.requestRefresh();
18487
+ return retired;
18118
18488
  };
18119
18489
  const clearSupervisionUI = (removeWidget = true) => {
18120
18490
  supervisionUiRuntime.stopPeriodic();
@@ -18400,7 +18770,12 @@ function registerLeadRuntime(pi, options2) {
18400
18770
  currentSupervisoryProfile,
18401
18771
  supervisoryTools,
18402
18772
  fallbackSupervisoryProfile,
18403
- removeProjectAssignment: removeProjectAssignment2,
18773
+ retireProjectAssignment: retireProjectAssignment2,
18774
+ releaseProjectAssignment: (...args) => {
18775
+ const released = roleHost.releaseProjectAssignment(...args);
18776
+ supervisionUiRuntime.requestRefresh();
18777
+ return released;
18778
+ },
18404
18779
  controllerScope: { kind: "root" },
18405
18780
  activationGuard,
18406
18781
  advancePeerPresenceGeneration: () => coordinationRuntime.advancePresenceGeneration(),
@@ -18480,7 +18855,9 @@ function registerLeadRuntime(pi, options2) {
18480
18855
  projectAssignmentForScope: (...args) => roleTransitions.projectAssignmentForScope(...args),
18481
18856
  resolveEffectiveSupervisor: (...args) => roleTransitions.resolveEffectiveSupervisor(...args),
18482
18857
  currentPeerPresenceValid: (ctx) => coordinationRuntime.currentPeerPresenceValid(ctx),
18483
- drainProjectMessages: (ctx) => coordinationRuntime.drainProjectMessages(ctx)
18858
+ drainProjectMessages: (ctx) => coordinationRuntime.drainRetirementNotices(ctx).then(
18859
+ async (count) => count + await coordinationRuntime.drainProjectMessages(ctx)
18860
+ )
18484
18861
  };
18485
18862
  inboxRuntime = createLeadInboxRuntime(inboxServices);
18486
18863
  let herdRunRuntime;
@@ -19337,8 +19714,7 @@ function createLeadSupervisionRuntime(host) {
19337
19714
  throw new Error("Multiple project assignments match a Lead session");
19338
19715
  return snapshot2.leads.filter((lead) => scope.workspaceIds.includes(lead.workspaceId)).map((lead) => ({
19339
19716
  ...lead,
19340
- relationship: sessions.has(lead.lead) ? "assigned" : "supervised",
19341
- availableActions: sessions.has(lead.lead) ? lead.availableActions : ["message"]
19717
+ relationship: sessions.has(lead.lead) ? "assigned" : "supervised"
19342
19718
  }));
19343
19719
  }
19344
19720
  if (host.activeRole() !== "chief")
@@ -19695,6 +20071,7 @@ function createLeadSupervisionRuntime(host) {
19695
20071
  const supervisionGeneration = generation(ctx);
19696
20072
  const sessionId = ctx.sessionManager.getSessionId();
19697
20073
  let mode = "overview";
20074
+ let peekRequest = 0;
19698
20075
  let peekLead;
19699
20076
  let peekEvidence;
19700
20077
  let list;
@@ -19886,6 +20263,7 @@ function createLeadSupervisionRuntime(host) {
19886
20263
  return finish();
19887
20264
  if (mode === "peek") {
19888
20265
  if (host.tui.matchesKey(data, host.tui.Key.escape) || host.tui.matchesKey(data, host.tui.Key.space)) {
20266
+ peekRequest++;
19889
20267
  mode = "overview";
19890
20268
  showOverview();
19891
20269
  tui.requestRender();
@@ -19901,6 +20279,7 @@ function createLeadSupervisionRuntime(host) {
19901
20279
  const leadId = selected?.startsWith("lead:") ? selected.slice("lead:".length) : selected;
19902
20280
  const lead = host.presentationReports(snapshot).find((item) => item.lead === leadId);
19903
20281
  if (!lead) return;
20282
+ const request = ++peekRequest;
19904
20283
  peekLead = lead;
19905
20284
  peekEvidence = {
19906
20285
  agents: (lead.agents ?? []).map(
@@ -19910,8 +20289,6 @@ function createLeadSupervisionRuntime(host) {
19910
20289
  mode = "peek";
19911
20290
  showPeek();
19912
20291
  tui.requestRender();
19913
- if (host.activeRole() === "manager" && lead.relationship === "supervised")
19914
- return;
19915
20292
  void host.inspectHerdrAgent(
19916
20293
  host.pi,
19917
20294
  ctx,
@@ -19921,12 +20298,20 @@ function createLeadSupervisionRuntime(host) {
19921
20298
  piSessionId: lead.lead
19922
20299
  },
19923
20300
  ctx.signal,
19924
- (agent) => host.isPiAgent(agent) && agent?.pane_id === lead.paneId && agent?.tab_id === lead.tabId && host.herdrSessionId(agent) === lead.lead && host.readLeadCoordinationState(
19925
- host.supervisionRuntime(),
19926
- lead.lead
19927
- )?.piSessionId === lead.lead && lead.availableActions.includes("inspect")
20301
+ async (agent) => {
20302
+ if (!isCurrentOverview() || !host.isPiAgent(agent) || agent?.pane_id !== lead.paneId || agent?.tab_id !== lead.tabId || host.herdrSessionId(agent) !== lead.lead || host.readLeadCoordinationState(
20303
+ host.supervisionRuntime(),
20304
+ lead.lead
20305
+ )?.piSessionId !== lead.lead || !lead.availableActions.includes("inspect"))
20306
+ return false;
20307
+ const current = (await directReports(ctx)).find(
20308
+ (candidate) => candidate.lead === lead.lead && candidate.instanceId === lead.instanceId && candidate.workspaceId === lead.workspaceId && candidate.paneId === lead.paneId && candidate.tabId === lead.tabId && candidate.availableActions.includes("inspect")
20309
+ );
20310
+ return isCurrentOverview() && !!current;
20311
+ }
19928
20312
  ).then((inspection) => {
19929
- if (!isCurrentOverview()) return;
20313
+ if (!isCurrentOverview() || mode !== "peek" || request !== peekRequest)
20314
+ return;
19930
20315
  peekEvidence = {
19931
20316
  recentOutput: inspection.recentOutput,
19932
20317
  process: inspection.process,
@@ -21100,6 +21485,8 @@ function createLeadProjectRuntime(host) {
21100
21485
  lead_stopped: leadStopped,
21101
21486
  checkout_removed: checkoutRemoved,
21102
21487
  assignment_retired: assignmentRetired,
21488
+ repo_key: candidate.manager.repoKey,
21489
+ assignment_id: candidate.assignment.id,
21103
21490
  forced: false,
21104
21491
  checkout_state: checkoutRemoved ? "removed" : checkoutState,
21105
21492
  ..."error" in removed ? { removal_error: removed.error } : {},
@@ -21194,6 +21581,10 @@ function createLeadProjectRuntime(host) {
21194
21581
  id: randomUUID10(),
21195
21582
  branch: params.branch ?? `herdsman/work-${randomUUID10().slice(0, 8)}`
21196
21583
  } : params;
21584
+ if (!operation.branch.trim())
21585
+ throw new Error("Project branch must not be empty");
21586
+ if (operation.action === "delegate" && operation.base !== void 0 && !operation.base.trim())
21587
+ throw new Error("Base ref must not be empty");
21197
21588
  return withProjectWorkLock(
21198
21589
  `${repoKey}\0${operation.branch}`,
21199
21590
  () => activateProjectLeadLocked(operation, ctx, signal)
@@ -22131,6 +22522,8 @@ function createLeadCoordinationRuntime(host) {
22131
22522
  importResultBindings: importResultBindings2
22132
22523
  } = host;
22133
22524
  const reportedProjectMessageCleanupErrors = /* @__PURE__ */ new Set();
22525
+ const reportedRetirementErrors = /* @__PURE__ */ new Set();
22526
+ const retirementCursors = /* @__PURE__ */ new Map();
22134
22527
  const readLeadSessionIdsFromHost = (inventory, mailboxes, workspaceId2) => readLeadSessionIds(inventory, mailboxes, workspaceId2, host);
22135
22528
  const prepareCoordinationInput = async (ctx, text, files, operation, heading, recordForInput) => {
22136
22529
  const limits = await host.messageLimits(ctx);
@@ -22864,6 +23257,100 @@ function createLeadCoordinationRuntime(host) {
22864
23257
  }
22865
23258
  };
22866
23259
  };
23260
+ const processRetirementNotices = async (ctx, preflight) => {
23261
+ const eligible = () => activeRole() === "manager" && !leadRuntime.roleSuspended && (preflight || ctx.isIdle());
23262
+ if (!eligible()) return 0;
23263
+ const manager = await currentManager(ctx);
23264
+ const verified = (current) => eligible() && !!current && !!manager && !!leadRuntime.managerLease && sameManagerDescriptor2(current, manager) && sameManagerDescriptor2(current, leadRuntime.managerLease.descriptor) && ctx.sessionManager.getSessionId() === current.piSessionId;
23265
+ if (!verified(manager)) return 0;
23266
+ const runtime = supervisionRuntime3();
23267
+ let errorKey = manager.repoKey;
23268
+ try {
23269
+ let processed = 0;
23270
+ for (const retired of listPendingRetirements(runtime, manager.repoKey, {
23271
+ after: retirementCursors.get(manager.repoKey),
23272
+ recordLimit: preflight ? COORDINATION_INBOX_SCAN_LIMIT : 1,
23273
+ onScanned: (entry) => retirementCursors.set(manager.repoKey, entry),
23274
+ onReadError: (error2) => {
23275
+ const key = `${manager.repoKey}:${error2.message}`;
23276
+ if (reportedRetirementErrors.has(key)) return;
23277
+ reportedRetirementErrors.add(key);
23278
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
23279
+ }
23280
+ })) {
23281
+ errorKey = retired.id;
23282
+ try {
23283
+ processed += await host.withProjectAssignmentLock(
23284
+ retired.repoKey,
23285
+ retired.branch,
23286
+ async () => {
23287
+ if (!verified(await currentManager(ctx))) return 0;
23288
+ if (readProjectAssignment2(runtime, retired.repoKey, retired.branch)?.id === retired.id)
23289
+ throw new Error(
23290
+ "Pending retirement still grants assignment authority"
23291
+ );
23292
+ removeProjectMessagesForAssignment(runtime, retired);
23293
+ const received = () => ctx.sessionManager.getEntries().some((entry) => {
23294
+ if (entry?.type === "custom_message" && entry.customType === "pi-herdsman-project_retired")
23295
+ return entry.details?.repoKey === retired.repoKey && entry.details?.branch === retired.branch && entry.details?.assignmentId === retired.id;
23296
+ const message = entry?.message;
23297
+ const details = message?.details;
23298
+ return entry?.type === "message" && message?.role === "toolResult" && !message.isError && (message.toolName === "staff" || message.toolName === "remove_worktree") && details?.ok === true && details?.action === "remove" && details?.checkout_removed === true && details?.assignment_retired === true && details?.repo_key === retired.repoKey && details?.assignment_id === retired.id;
23299
+ });
23300
+ if (!received()) {
23301
+ pi.sendMessage(
23302
+ {
23303
+ customType: "pi-herdsman-project_retired",
23304
+ content: [
23305
+ "[Pi Herdsman lifecycle notice]",
23306
+ `The worktree for project branch ${JSON.stringify(retired.branch)} was verified removed.`,
23307
+ `The assignment for Lead session ${retired.id} was retired.`,
23308
+ "Manager authority for that assignment has ended.",
23309
+ "This does not establish task completion, acceptance, merge, or discard.",
23310
+ "Retiring this assignment does not itself delete the Git branch or Pi session history."
23311
+ ].join("\n"),
23312
+ display: false,
23313
+ details: {
23314
+ repoKey: retired.repoKey,
23315
+ branch: retired.branch,
23316
+ assignmentId: retired.id
23317
+ }
23318
+ },
23319
+ { triggerTurn: false }
23320
+ );
23321
+ }
23322
+ if (received()) removePendingRetirement(runtime, retired);
23323
+ reportedRetirementErrors.delete(errorKey);
23324
+ return 1;
23325
+ }
23326
+ );
23327
+ } catch (error2) {
23328
+ if (!reportedRetirementErrors.has(retired.id)) {
23329
+ reportedRetirementErrors.add(retired.id);
23330
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
23331
+ }
23332
+ }
23333
+ }
23334
+ return processed;
23335
+ } catch (error2) {
23336
+ if (!reportedRetirementErrors.has(errorKey)) {
23337
+ reportedRetirementErrors.add(errorKey);
23338
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
23339
+ }
23340
+ return 0;
23341
+ }
23342
+ };
23343
+ let retirementDrain = Promise.resolve();
23344
+ const drainRetirementNotices = (ctx, preflight = false) => {
23345
+ const pass = retirementDrain.then(
23346
+ () => processRetirementNotices(ctx, preflight)
23347
+ );
23348
+ retirementDrain = pass.then(
23349
+ () => void 0,
23350
+ () => void 0
23351
+ );
23352
+ return pass;
23353
+ };
22867
23354
  const drainProjectMessages = async (ctx) => {
22868
23355
  if (activeRole() !== "manager" || leadRuntime.roleSuspended || !ctx.isIdle())
22869
23356
  return 0;
@@ -22950,6 +23437,7 @@ ${record.text}`,
22950
23437
  queuePeerRecord,
22951
23438
  queueChiefRecord,
22952
23439
  enterCoordinationPublication,
23440
+ drainRetirementNotices,
22953
23441
  drainProjectMessages,
22954
23442
  readLeadSessionIds: readLeadSessionIdsFromHost,
22955
23443
  supervisorMessage: executeSupervisorMessage,
@@ -23277,15 +23765,6 @@ function createLeadInboxRuntime(host) {
23277
23765
  return void 0;
23278
23766
  }
23279
23767
  if (!authorized) return "followUp";
23280
- const workspaceId = host.workspaceId();
23281
- if (!workspaceId) return void 0;
23282
- const relation = await host.resolveEffectiveSupervisor(
23283
- ctx,
23284
- ctx.sessionManager.getSessionId(),
23285
- workspaceId
23286
- );
23287
- const assigned = relation.kind === "assigned";
23288
- if (!assigned) return ctx.isIdle() ? "followUp" : void 0;
23289
23768
  return "steer";
23290
23769
  }
23291
23770
  const supervisorDownlink = role2 === "lead" && record.kind === "chief_message" || role2 === "manager" && record.kind === "chief_message";
@@ -24191,21 +24670,15 @@ function createLeadRoleTransitions(state, host) {
24191
24670
  if (supervisor.kind === "manager") return supervisor.manager;
24192
24671
  return supervisor.kind === "chief" ? supervisor.chief : void 0;
24193
24672
  };
24194
- const removeProjectAssignmentState = (assignment, _ctx) => {
24673
+ const removeProjectAssignmentState = (assignment, ctx, takeover2 = false) => {
24195
24674
  const runtime = host.supervisionRuntime();
24196
- const current = host.readProjectAssignment(
24197
- runtime,
24198
- assignment.repoKey,
24199
- assignment.branch
24200
- );
24201
- if (!current || current.repoKey !== assignment.repoKey || current.branch !== assignment.branch || current.id !== assignment.id)
24675
+ if (!(takeover2 ? host.releaseProjectAssignment(runtime, assignment) : host.retireProjectAssignment(runtime, assignment)))
24202
24676
  return false;
24203
- host.removeProjectMessages(runtime, assignment.repoKey, assignment.branch);
24204
- host.removeProjectAssignment(
24205
- runtime,
24206
- assignment.repoKey,
24207
- assignment.branch
24208
- );
24677
+ try {
24678
+ host.removeProjectMessagesForAssignment(runtime, assignment);
24679
+ } catch (error2) {
24680
+ host.appendDurableError(host.pi, ctx, "pi_herdsman_state_error", error2);
24681
+ }
24209
24682
  return true;
24210
24683
  };
24211
24684
  const gitWorktreeInventory = async (ctx, repoKey, primaryWorkspaceId, sourceCheckoutPath) => {
@@ -24346,8 +24819,22 @@ function createLeadRoleTransitions(state, host) {
24346
24819
  }
24347
24820
  };
24348
24821
  const reconcileCurrentManagerAssignments = async (ctx) => {
24349
- const manager = await currentManager(ctx);
24822
+ const lease = state.managerLease?.descriptor;
24823
+ if (activeLeadRole(state) !== "manager" || state.roleSuspended || !lease || lease.piSessionId !== ctx.sessionManager.getSessionId() || lease.workspaceId !== host.workspaceId())
24824
+ return;
24825
+ const manager = await currentManager(ctx, {
24826
+ repoKey: lease.repoKey,
24827
+ primaryWorkspaceId: lease.workspaceId
24828
+ });
24350
24829
  if (!manager) return;
24830
+ try {
24831
+ host.recoverStaleProjectMessages(
24832
+ host.supervisionRuntime(),
24833
+ manager.repoKey
24834
+ );
24835
+ } catch (error2) {
24836
+ host.appendDurableError(host.pi, ctx, "pi_herdsman_state_error", error2);
24837
+ }
24351
24838
  const topology = await host.runHerdr(
24352
24839
  host.pi,
24353
24840
  ctx,
@@ -24388,7 +24875,7 @@ function createLeadRoleTransitions(state, host) {
24388
24875
  async () => {
24389
24876
  const currentScope = await currentWorktreeScope(ctx);
24390
24877
  const current = currentScope && currentScope.repoKey === assignment.repoKey ? projectAssignmentForScope(currentScope, sessionId) : void 0;
24391
- if (!current || current.branch !== assignment.branch || !removeProjectAssignmentState(assignment, ctx))
24878
+ if (!current || current.branch !== assignment.branch || !removeProjectAssignmentState(assignment, ctx, true))
24392
24879
  throw new Error("Project assignment changed during takeover");
24393
24880
  }
24394
24881
  )
@@ -25213,7 +25700,7 @@ ${LEAD_SUPERVISOR_PEER_GUIDANCE}
25213
25700
  For assigned project work, automatic result handoffs contain summary text but no file attachments. When the Manager needs an actual artifact for review, decision-making, or onward delegation, explicitly transfer the relevant evidence through message_supervisor.files.
25214
25701
  ${FILE_HANDOFF_GUIDANCE}`;
25215
25702
  var MANAGER_ROLE_CONTRACT = `## Manager role
25216
- You are the verified Manager for this Pi session. Supervise only project Leads established by exact current project assignments; configuration changes operating guidance and ordinary tool availability, never authority. Project execution belongs to assigned Leads and their Agent trees. Coordination messages and reports are nonterminal and do not establish completion. Use remove_worktree only for an explicitly requested checkout-removal action; never infer removal from completion, review, or inactivity. The user must confirm interactively.`;
25703
+ You are the verified Manager for this Pi session. Supervise eligible Leads in your verified project worktree group. Manage project execution only through exact current project assignments; supervision alone grants no Agent ownership or project lifecycle authority. Configuration changes operating guidance and ordinary tool availability, never authority. Project execution belongs to assigned Leads and their Agent trees. Coordination messages and reports are nonterminal and do not establish completion. Use remove_worktree only for an explicitly requested checkout-removal action; never infer removal from completion, review, or inactivity. The user must confirm interactively.`;
25217
25704
  var SUPERVISION_CONTEXT_TYPE = "pi-herdsman-supervision-context";
25218
25705
  var SUPERVISOR_STATE_TYPE = "pi-herdsman-supervisor-state";
25219
25706
  var STALE_AFTER_MS = 10 * 6e4;
@@ -25574,15 +26061,16 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
25574
26061
  { triggerTurn: true }
25575
26062
  );
25576
26063
  },
25577
- sessionRetired: (runtime) => readConfig().contextRetirement && runtime.piSessionFile !== void 0 && (() => {
26064
+ sessionRetired: (ctx, runtime) => {
26065
+ if (!runtime.piSessionFile) return false;
25578
26066
  try {
25579
- return retiredManagedSession(
25580
- SessionManager2.open(runtime.piSessionFile)
25581
- );
26067
+ const session = SessionManager2.open(runtime.piSessionFile);
26068
+ if (!retiredManagedSession(session)) return false;
26069
+ return sameCwd(ctx.cwd, session.getCwd()) ? readEffectiveConfig(ctx).contextRetirement : void 0;
25582
26070
  } catch {
25583
- return false;
26071
+ return void 0;
25584
26072
  }
25585
- })(),
26073
+ },
25586
26074
  appendError: (ctx, kind, error2) => appendDurableError(pi, ctx, kind, error2),
25587
26075
  onChanged: () => leadStatusRuntime.requestRefresh(),
25588
26076
  reportWatcherError: (ctx, error2) => {
@@ -25618,7 +26106,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
25618
26106
  pattern: PI_SESSION_ID_PATTERN,
25619
26107
  description: "Exact full Pi session ID from the fresh supervision snapshot or list_staff."
25620
26108
  }),
25621
- message: Type3.String({ pattern: "\\S" }),
26109
+ message: Type3.String({ minLength: 1 }),
25622
26110
  files: FILES_SCHEMA
25623
26111
  },
25624
26112
  { additionalProperties: false }
@@ -25629,7 +26117,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
25629
26117
  pattern: PI_SESSION_ID_PATTERN,
25630
26118
  description: "Exact full Pi session ID returned by list_peers; never use a display label."
25631
26119
  }),
25632
- message: Type3.String({ pattern: "\\S" }),
26120
+ message: Type3.String({ minLength: 1 }),
25633
26121
  files: FILES_SCHEMA
25634
26122
  },
25635
26123
  { additionalProperties: false }
@@ -25641,18 +26129,18 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
25641
26129
  const staffDelegateParameters = Type3.Object(
25642
26130
  {
25643
26131
  task: Type3.String({
25644
- pattern: "\\S",
26132
+ minLength: 1,
25645
26133
  description: "Non-empty task for new project work."
25646
26134
  }),
25647
26135
  branch: Type3.Optional(
25648
26136
  Type3.String({
25649
- pattern: "\\S",
26137
+ minLength: 1,
25650
26138
  description: "Optional Git branch for the new project work; Herdsman generates one when omitted."
25651
26139
  })
25652
26140
  ),
25653
26141
  base: Type3.Optional(
25654
26142
  Type3.String({
25655
- pattern: "\\S",
26143
+ minLength: 1,
25656
26144
  description: "Base ref used only when Herdsman creates a new worktree."
25657
26145
  })
25658
26146
  ),
@@ -25663,7 +26151,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
25663
26151
  const staffBranchParameters = Type3.Object(
25664
26152
  {
25665
26153
  branch: Type3.String({
25666
- pattern: "\\S",
26154
+ minLength: 1,
25667
26155
  description: "Exact project branch."
25668
26156
  })
25669
26157
  },
@@ -25826,8 +26314,10 @@ ${globalInstructions}
25826
26314
  prepareCoordinationInput: (...args) => leadRuntimes.coordinationRuntime.prepareCoordinationInput(...args),
25827
26315
  projectMessageBytes,
25828
26316
  writeProjectMessage,
25829
- removeProjectAssignment,
25830
- removeProjectMessages,
26317
+ releaseProjectAssignment,
26318
+ retireProjectAssignment,
26319
+ removeProjectMessagesForAssignment,
26320
+ recoverStaleProjectMessages,
25831
26321
  delay: delay2,
25832
26322
  appendDurableError,
25833
26323
  markLeadCoordinationUnhealthy,
@@ -25916,6 +26406,10 @@ ${globalInstructions}
25916
26406
  };
25917
26407
  prepareSupervisionMessage = (ctx) => leadRuntimes.supervisionUiRuntime.prepareMessage(ctx);
25918
26408
  const leadAgentEventOptions = {
26409
+ drainRetirementNotices: (ctx, preflight) => leadRuntimes.coordinationRuntime.drainRetirementNotices(
26410
+ ctx,
26411
+ preflight
26412
+ ),
25919
26413
  isCurrentChief,
25920
26414
  chiefTools: CHIEF_TOOLS,
25921
26415
  setActiveTools: (tools) => pi.setActiveTools(tools),
@@ -26146,6 +26640,8 @@ ${summary}`,
26146
26640
  selectMenu,
26147
26641
  selectModelMenu,
26148
26642
  readConfig,
26643
+ readEffectiveConfig,
26644
+ readProjectOverrides,
26149
26645
  contextAgentDefinitions,
26150
26646
  discoverRoleDefinition,
26151
26647
  setLeadExecutionMode: (ctx, mode) => leadRuntimes.setLeadExecutionMode(ctx, mode),
@@ -26465,7 +26961,7 @@ ${summary}`,
26465
26961
  appendRoleError: (ctx, error2) => appendDurableError(pi, ctx, "pi_herdsman_role_error", error2)
26466
26962
  };
26467
26963
  const sessionStartOptions = {
26468
- autoActivateManager: () => readConfig().autoActivateManager,
26964
+ autoActivateManager: (ctx) => readEffectiveConfig(ctx).autoActivateManager,
26469
26965
  clearDefinitionRoster: () => {
26470
26966
  startupDefinitionRoster = void 0;
26471
26967
  },