pi-herdsman 0.29.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.29.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",
@@ -567,9 +567,8 @@ function claimProcessLock(path, options2 = {}) {
567
567
  }
568
568
  function releaseProcessLock(claimDir, ownerPath, claim, name) {
569
569
  let owner;
570
- let metadata;
571
570
  try {
572
- ({ owner, metadata } = lockOwnerEntry(claimDir));
571
+ ({ owner } = lockOwnerEntry(claimDir));
573
572
  } catch (error2) {
574
573
  if (error2.code === "ENOENT") return;
575
574
  try {
@@ -601,10 +600,27 @@ function releaseProcessLock(claimDir, ownerPath, claim, name) {
601
600
  throw new Error(
602
601
  `${name[0].toUpperCase()}${name.slice(1)} ownership changed`
603
602
  );
604
- unlinkMetadata(claimDir, metadata);
605
- 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));
606
622
  try {
607
- fs.rmdirSync(claimDir);
623
+ fs.rmdirSync(retired);
608
624
  } catch (error2) {
609
625
  const code = error2.code;
610
626
  if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error2;
@@ -6537,7 +6553,7 @@ function renderCompletionMessage(message, options2, theme) {
6537
6553
  const metadata = [
6538
6554
  ...d?.agentDefinition ? [`definition: ${d.agentDefinition}`] : [],
6539
6555
  ...d?.piSessionId ? [`session: ${d.piSessionId}`] : [],
6540
- ...d?.sessionRetired ? ["continuation: fresh agent required"] : [],
6556
+ ...d?.sessionRetired === true ? ["continuation: fresh agent required"] : d?.sessionRetired === null ? ["continuation: policy unverified"] : [],
6541
6557
  ...d?.requestId ? [`request: ${d.requestId}`] : [],
6542
6558
  ...elapsed ? [`elapsed: ${elapsed}`] : [],
6543
6559
  ...d?.contextUsage?.percent != null ? [`context: ${Math.round(d.contextUsage.percent)}%`] : [],
@@ -6562,7 +6578,7 @@ function renderCompletionMessage(message, options2, theme) {
6562
6578
  }
6563
6579
  } else {
6564
6580
  const notices = [
6565
- ...d?.sessionRetired ? ["session retired"] : [],
6581
+ ...d?.sessionRetired === true ? ["session retired"] : d?.sessionRetired === null ? ["retirement policy unverified"] : [],
6566
6582
  ...d?.truncated === true ? ["output truncated"] : [],
6567
6583
  ...d?.resultPersistenceError ? ["result not saved"] : []
6568
6584
  ];
@@ -6966,6 +6982,43 @@ function readRawConfig() {
6966
6982
  function readConfig() {
6967
6983
  return { ...DEFAULT_CONFIG, ...readRawConfig() };
6968
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
+ }
6969
7022
  function writeConfigAtomically(path, content) {
6970
7023
  const directory = dirname5(path);
6971
7024
  const temporaryPath = join7(
@@ -7034,7 +7087,6 @@ import {
7034
7087
  fsyncSync as fsyncSync4,
7035
7088
  lstatSync as lstatSync2,
7036
7089
  readdirSync as readdirSync5,
7037
- rmSync,
7038
7090
  mkdirSync as mkdirSync7,
7039
7091
  openSync as openSync8,
7040
7092
  readFileSync as readFileSync8,
@@ -8243,10 +8295,13 @@ function readProjectAssignment(runtime, repoKey, branch) {
8243
8295
  const path = projectAssignmentPath(runtime, repoKey, branch);
8244
8296
  return readProjectAssignmentFile(path, repoKey, branch);
8245
8297
  }
8246
- function readProjectAssignmentFile(path, repoKey, branch) {
8298
+ function readProjectAssignmentFile(path, repoKey, branch, pending = false) {
8247
8299
  let value2;
8248
8300
  try {
8249
- 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)
8250
8305
  throw new Error("file is too large");
8251
8306
  value2 = JSON.parse(readFileSync8(path, "utf8"));
8252
8307
  } catch (error2) {
@@ -8258,7 +8313,7 @@ function readProjectAssignmentFile(path, repoKey, branch) {
8258
8313
  throw projectAssignmentReadError(path, "invalid assignment schema");
8259
8314
  if (projectAssignmentBytes(value2) > PROJECT_ASSIGNMENT_MAX_BYTES)
8260
8315
  throw projectAssignmentReadError(path, "assignment payload is too large");
8261
- 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`)
8262
8317
  throw projectAssignmentReadError(path, "assignment identity mismatch");
8263
8318
  return value2;
8264
8319
  }
@@ -8296,11 +8351,158 @@ function findProjectAssignmentBySession2(runtime, repoKey, sessionId) {
8296
8351
  (assignment) => assignment.id === sessionId
8297
8352
  );
8298
8353
  }
8299
- function removeProjectAssignment(runtime, repoKey, branch) {
8300
- withProjectAssignmentLock(
8301
- () => 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`
8302
8423
  );
8303
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
+ }
8304
8506
  function removeProjectAssignmentUnlocked(runtime, repoKey, branch) {
8305
8507
  const path = projectAssignmentPath(runtime, repoKey, branch);
8306
8508
  try {
@@ -8504,20 +8706,18 @@ function listProjectMessages(runtime, repoKey, branch) {
8504
8706
  if (error2.code === "ENOENT") return [];
8505
8707
  throw error2;
8506
8708
  }
8507
- return entries.filter((entry) => UUID3.test(entry.slice(0, -5)) && entry.endsWith(".json")).map((entry) => {
8508
- const path = join8(directory, entry);
8709
+ return entries.filter((entry) => UUID3.test(entry.slice(0, -5)) && entry.endsWith(".json")).flatMap((entry) => {
8710
+ let value2;
8509
8711
  try {
8510
- if (statSync4(path).size > COORDINATION_MESSAGE_MAX_BYTES)
8511
- throw new Error("large");
8512
- const value2 = JSON.parse(readFileSync8(path, "utf8"));
8513
- if (!validProjectMessage(value2) || value2.repoKey !== repoKey || value2.branch !== branch || entry !== `${value2.id}.json`)
8514
- throw new Error("invalid");
8515
- return value2;
8712
+ value2 = readProjectMessageFile(join8(directory, entry));
8516
8713
  } catch (error2) {
8517
- throw new Error(`Unable to read project message ${path}`, {
8518
- cause: error2
8519
- });
8714
+ if (error2 instanceof Error && error2.cause?.code === "ENOENT")
8715
+ return [];
8716
+ throw error2;
8520
8717
  }
8718
+ if (value2.repoKey !== repoKey || value2.branch !== branch)
8719
+ throw new Error(`Project message identity does not match ${directory}`);
8720
+ return [value2];
8521
8721
  }).sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
8522
8722
  }
8523
8723
  function removeProjectMessage(runtime, repoKey, branch, id) {
@@ -8530,12 +8730,80 @@ function removeProjectMessage(runtime, repoKey, branch, id) {
8530
8730
  if (error2.code !== "ENOENT") throw error2;
8531
8731
  }
8532
8732
  }
8533
- function removeProjectMessages(runtime, repoKey, branch) {
8534
- rmSync(projectMessageDirectory(runtime, repoKey, branch), {
8535
- recursive: true,
8536
- 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
+ }
8537
8806
  });
8538
- fsyncDirectory(dirname6(projectAssignmentPath(runtime, repoKey, branch)));
8539
8807
  }
8540
8808
  function verifyManagerCoordinationAuthority(descriptor, coordinator, build, requireCompatibleBuild2) {
8541
8809
  if (!coordinator || coordinator.role !== "manager" || coordinator.piSessionId !== descriptor.piSessionId)
@@ -9920,12 +10188,16 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
9920
10188
  `Saved assignment session has no non-empty cwd in its session header: ${child.path}`,
9921
10189
  "continue"
9922
10190
  );
9923
- if (options2.contextRetirement && options2.isContextRetired?.(manager))
9924
- fail(
9925
- "invalid_request",
9926
- `Managed agent session ${child.id} is retired after context pressure. Delegate a fresh agent and pass the previous result/handoff and relevant files.`,
9927
- "continue"
9928
- );
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
+ }
9929
10201
  return {
9930
10202
  path: child.path,
9931
10203
  id: child.id,
@@ -12488,8 +12760,8 @@ function createAgentController(pi, options2) {
12488
12760
  "pi_herdsman_result_error",
12489
12761
  completion.persistenceError
12490
12762
  );
12491
- const sessionRetired = options2.sessionRetired(runtime);
12492
- 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;
12493
12765
  const status = resultStatus(runtime, result.requestId, entries);
12494
12766
  const header = [
12495
12767
  "Agent result",
@@ -12517,7 +12789,7 @@ function createAgentController(pi, options2) {
12517
12789
  ...runtime.piSessionFile !== void 0 ? { piSessionFile: runtime.piSessionFile } : {},
12518
12790
  agentDefinition: runtime.agentDefinition,
12519
12791
  status: result.status,
12520
- sessionRetired,
12792
+ sessionRetired: sessionRetired ?? null,
12521
12793
  ...elapsedMs !== void 0 ? { elapsedMs } : {},
12522
12794
  contextUsage: result.contextUsage,
12523
12795
  truncated: completion.truncated,
@@ -12636,8 +12908,8 @@ function createAgentController(pi, options2) {
12636
12908
  p.action
12637
12909
  );
12638
12910
  const resumed = p.action === "continue" ? resolveAssignmentSession(ctx, p.session, {
12639
- contextRetirement: readConfig().contextRetirement,
12640
- isContextRetired: options2.isContextRetired
12911
+ isContextRetired: options2.isContextRetired,
12912
+ contextRetirementForSession: (context, manager) => sameCwd(context.cwd, manager.getCwd()) ? readEffectiveConfig(context).contextRetirement : void 0
12641
12913
  }) : void 0;
12642
12914
  await herdrVersion(pi, ctx, signal);
12643
12915
  const agentDefinition = resumed ? resumed.definition : p.definition;
@@ -16301,8 +16573,9 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
16301
16573
  }
16302
16574
  });
16303
16575
  registerManagedAgentContextHandlers(pi, {
16304
- contextRetirementEnabled: () => readConfig().contextRetirement,
16305
- 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)
16306
16579
  });
16307
16580
  }
16308
16581
  function createManagedAgentRequestState(pi, options2) {
@@ -16479,12 +16752,28 @@ function registerManagedAgentContextHandlers(pi, options2) {
16479
16752
  let pendingGuidance;
16480
16753
  let queuedGuidanceSessionId;
16481
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
+ };
16482
16771
  pi.on(
16483
16772
  "session_before_compact",
16484
16773
  (event, ctx) => {
16485
- if (!options2.contextRetirementEnabled()) return;
16486
- if (!options2.hasActiveAssignment()) return;
16487
16774
  if (event.reason === "manual") return;
16775
+ if (!retirementEnabled(ctx)) return;
16776
+ if (!options2.hasActiveAssignment()) return;
16488
16777
  const sessionId = ctx.sessionManager.getSessionId();
16489
16778
  const entries = ctx.sessionManager.getEntries();
16490
16779
  const retired = sessionContextRetired(entries, sessionId);
@@ -16542,7 +16831,7 @@ function registerManagedAgentContextHandlers(pi, options2) {
16542
16831
  if (!pending) return;
16543
16832
  pendingGuidance = void 0;
16544
16833
  const sessionId = ctx.sessionManager.getSessionId();
16545
- if (!options2.contextRetirementEnabled() || !options2.hasActiveAssignment() || sessionId !== pending.sessionId)
16834
+ if (!retirementEnabled(ctx) || !options2.hasActiveAssignment() || sessionId !== pending.sessionId)
16546
16835
  return;
16547
16836
  bridgedGuidanceSessionId = sessionId;
16548
16837
  const alreadyVisible = event.messages.some(
@@ -16564,7 +16853,7 @@ function registerManagedAgentContextHandlers(pi, options2) {
16564
16853
  };
16565
16854
  });
16566
16855
  pi.on("tool_call", (event, ctx) => {
16567
- 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")
16568
16857
  return;
16569
16858
  if (!sessionContextRetired(
16570
16859
  ctx.sessionManager.getEntries(),
@@ -16962,7 +17251,14 @@ function createLeadSessionStartRuntime(host) {
16962
17251
  }
16963
17252
  skipLeadExecutionProfileResolution = persistedRole === "chief";
16964
17253
  host.roleTransitions.reconcileRoleTools();
16965
- 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
+ }
16966
17262
  let leadStateRestored = false;
16967
17263
  let leadStateValid = !optionalManager;
16968
17264
  if (optionalManager && host.roleTransitions.canRestoreChiefState()) {
@@ -17134,6 +17430,7 @@ function createLeadAgentEventRuntime(host) {
17134
17430
  delete sections.agent_definitions;
17135
17431
  const message = await host.prepareSupervisionMessage(ctx);
17136
17432
  if (message) host.sendMessage(message);
17433
+ await host.drainRetirementNotices(ctx, true);
17137
17434
  return;
17138
17435
  }
17139
17436
  const supervisorStateMessage2 = host.isActiveLead() ? await host.prepareLeadSupervisorStateMessage(ctx) : void 0;
@@ -17702,6 +17999,15 @@ Active work or pending results may be discarded.`
17702
17999
  let selectedSetting = "auto-activate-manager";
17703
18000
  while (true) {
17704
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
+ }
17705
18011
  const selected = await host.selectMenu(
17706
18012
  ctx,
17707
18013
  "Settings",
@@ -17715,13 +18021,13 @@ Active work or pending results may be discarded.`
17715
18021
  {
17716
18022
  value: "auto-activate-manager",
17717
18023
  label: "Manager auto-start",
17718
- description: config.autoActivateManager ? "on" : "off",
18024
+ description: `Global ${config.autoActivateManager ? "on" : "off"} \xB7 Effective ${effective.autoActivateManager ? "on" : "off"}${"autoActivateManager" in overrides ? " \xB7 Project" : ""}`,
17719
18025
  help: "Attempt Manager mode automatically on eligible future session starts. Changing this does not alter the current role."
17720
18026
  },
17721
18027
  {
17722
18028
  value: "context-retirement",
17723
18029
  label: "Context retirement",
17724
- description: config.contextRetirement ? "on" : "off",
18030
+ description: `Global ${config.contextRetirement ? "on" : "off"} \xB7 Effective ${effective.contextRetirement ? "on" : "off"}${"contextRetirement" in overrides ? " \xB7 Project" : ""}`,
17725
18031
  help: "Retire managed-Agent sessions at automatic context pressure instead of allowing normal threshold compaction."
17726
18032
  },
17727
18033
  {
@@ -17752,7 +18058,7 @@ Active work or pending results may be discarded.`
17752
18058
  const enabled = !host.readConfig()[key];
17753
18059
  host.updateConfig(key, enabled);
17754
18060
  ctx.ui.notify(
17755
- `${key === "contextRetirement" ? "Context retirement" : "Manager auto-start"}: ${enabled ? "on" : "off"}`
18061
+ `Global ${key === "contextRetirement" ? "context retirement" : "Manager auto-start"}: ${enabled ? "on" : "off"}`
17756
18062
  );
17757
18063
  }
17758
18064
  }
@@ -18127,6 +18433,7 @@ function registerLeadRuntime(pi, options2) {
18127
18433
  const remoteChiefAgent = (...args) => identityRuntime.remoteChiefAgent(...args);
18128
18434
  const liveLead = (...args) => identityRuntime.liveLead(...args);
18129
18435
  const coordinationServices = {
18436
+ withProjectAssignmentLock: (repoKey, branch, operation) => roleTransitions.withProjectAssignmentLock(repoKey, branch, operation),
18130
18437
  ...options2.coordinationHost,
18131
18438
  workspaceId: () => options2.roleTransitionHost.workspaceId(),
18132
18439
  currentManager: (...args) => roleTransitions.currentManager(...args),
@@ -18174,9 +18481,10 @@ function registerLeadRuntime(pi, options2) {
18174
18481
  options2.projectHost.writeProjectAssignment(...args);
18175
18482
  supervisionUiRuntime.requestRefresh();
18176
18483
  };
18177
- const removeProjectAssignment2 = (...args) => {
18178
- options2.roleTransitionHost.removeProjectAssignment(...args);
18484
+ const retireProjectAssignment2 = (...args) => {
18485
+ const retired = options2.roleTransitionHost.retireProjectAssignment(...args);
18179
18486
  supervisionUiRuntime.requestRefresh();
18487
+ return retired;
18180
18488
  };
18181
18489
  const clearSupervisionUI = (removeWidget = true) => {
18182
18490
  supervisionUiRuntime.stopPeriodic();
@@ -18462,7 +18770,12 @@ function registerLeadRuntime(pi, options2) {
18462
18770
  currentSupervisoryProfile,
18463
18771
  supervisoryTools,
18464
18772
  fallbackSupervisoryProfile,
18465
- removeProjectAssignment: removeProjectAssignment2,
18773
+ retireProjectAssignment: retireProjectAssignment2,
18774
+ releaseProjectAssignment: (...args) => {
18775
+ const released = roleHost.releaseProjectAssignment(...args);
18776
+ supervisionUiRuntime.requestRefresh();
18777
+ return released;
18778
+ },
18466
18779
  controllerScope: { kind: "root" },
18467
18780
  activationGuard,
18468
18781
  advancePeerPresenceGeneration: () => coordinationRuntime.advancePresenceGeneration(),
@@ -18542,7 +18855,9 @@ function registerLeadRuntime(pi, options2) {
18542
18855
  projectAssignmentForScope: (...args) => roleTransitions.projectAssignmentForScope(...args),
18543
18856
  resolveEffectiveSupervisor: (...args) => roleTransitions.resolveEffectiveSupervisor(...args),
18544
18857
  currentPeerPresenceValid: (ctx) => coordinationRuntime.currentPeerPresenceValid(ctx),
18545
- drainProjectMessages: (ctx) => coordinationRuntime.drainProjectMessages(ctx)
18858
+ drainProjectMessages: (ctx) => coordinationRuntime.drainRetirementNotices(ctx).then(
18859
+ async (count) => count + await coordinationRuntime.drainProjectMessages(ctx)
18860
+ )
18546
18861
  };
18547
18862
  inboxRuntime = createLeadInboxRuntime(inboxServices);
18548
18863
  let herdRunRuntime;
@@ -21170,6 +21485,8 @@ function createLeadProjectRuntime(host) {
21170
21485
  lead_stopped: leadStopped,
21171
21486
  checkout_removed: checkoutRemoved,
21172
21487
  assignment_retired: assignmentRetired,
21488
+ repo_key: candidate.manager.repoKey,
21489
+ assignment_id: candidate.assignment.id,
21173
21490
  forced: false,
21174
21491
  checkout_state: checkoutRemoved ? "removed" : checkoutState,
21175
21492
  ..."error" in removed ? { removal_error: removed.error } : {},
@@ -22205,6 +22522,8 @@ function createLeadCoordinationRuntime(host) {
22205
22522
  importResultBindings: importResultBindings2
22206
22523
  } = host;
22207
22524
  const reportedProjectMessageCleanupErrors = /* @__PURE__ */ new Set();
22525
+ const reportedRetirementErrors = /* @__PURE__ */ new Set();
22526
+ const retirementCursors = /* @__PURE__ */ new Map();
22208
22527
  const readLeadSessionIdsFromHost = (inventory, mailboxes, workspaceId2) => readLeadSessionIds(inventory, mailboxes, workspaceId2, host);
22209
22528
  const prepareCoordinationInput = async (ctx, text, files, operation, heading, recordForInput) => {
22210
22529
  const limits = await host.messageLimits(ctx);
@@ -22938,6 +23257,100 @@ function createLeadCoordinationRuntime(host) {
22938
23257
  }
22939
23258
  };
22940
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
+ };
22941
23354
  const drainProjectMessages = async (ctx) => {
22942
23355
  if (activeRole() !== "manager" || leadRuntime.roleSuspended || !ctx.isIdle())
22943
23356
  return 0;
@@ -23024,6 +23437,7 @@ ${record.text}`,
23024
23437
  queuePeerRecord,
23025
23438
  queueChiefRecord,
23026
23439
  enterCoordinationPublication,
23440
+ drainRetirementNotices,
23027
23441
  drainProjectMessages,
23028
23442
  readLeadSessionIds: readLeadSessionIdsFromHost,
23029
23443
  supervisorMessage: executeSupervisorMessage,
@@ -24256,21 +24670,15 @@ function createLeadRoleTransitions(state, host) {
24256
24670
  if (supervisor.kind === "manager") return supervisor.manager;
24257
24671
  return supervisor.kind === "chief" ? supervisor.chief : void 0;
24258
24672
  };
24259
- const removeProjectAssignmentState = (assignment, _ctx) => {
24673
+ const removeProjectAssignmentState = (assignment, ctx, takeover2 = false) => {
24260
24674
  const runtime = host.supervisionRuntime();
24261
- const current = host.readProjectAssignment(
24262
- runtime,
24263
- assignment.repoKey,
24264
- assignment.branch
24265
- );
24266
- 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)))
24267
24676
  return false;
24268
- host.removeProjectMessages(runtime, assignment.repoKey, assignment.branch);
24269
- host.removeProjectAssignment(
24270
- runtime,
24271
- assignment.repoKey,
24272
- assignment.branch
24273
- );
24677
+ try {
24678
+ host.removeProjectMessagesForAssignment(runtime, assignment);
24679
+ } catch (error2) {
24680
+ host.appendDurableError(host.pi, ctx, "pi_herdsman_state_error", error2);
24681
+ }
24274
24682
  return true;
24275
24683
  };
24276
24684
  const gitWorktreeInventory = async (ctx, repoKey, primaryWorkspaceId, sourceCheckoutPath) => {
@@ -24411,8 +24819,22 @@ function createLeadRoleTransitions(state, host) {
24411
24819
  }
24412
24820
  };
24413
24821
  const reconcileCurrentManagerAssignments = async (ctx) => {
24414
- 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
+ });
24415
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
+ }
24416
24838
  const topology = await host.runHerdr(
24417
24839
  host.pi,
24418
24840
  ctx,
@@ -24453,7 +24875,7 @@ function createLeadRoleTransitions(state, host) {
24453
24875
  async () => {
24454
24876
  const currentScope = await currentWorktreeScope(ctx);
24455
24877
  const current = currentScope && currentScope.repoKey === assignment.repoKey ? projectAssignmentForScope(currentScope, sessionId) : void 0;
24456
- if (!current || current.branch !== assignment.branch || !removeProjectAssignmentState(assignment, ctx))
24878
+ if (!current || current.branch !== assignment.branch || !removeProjectAssignmentState(assignment, ctx, true))
24457
24879
  throw new Error("Project assignment changed during takeover");
24458
24880
  }
24459
24881
  )
@@ -25639,15 +26061,16 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
25639
26061
  { triggerTurn: true }
25640
26062
  );
25641
26063
  },
25642
- sessionRetired: (runtime) => readConfig().contextRetirement && runtime.piSessionFile !== void 0 && (() => {
26064
+ sessionRetired: (ctx, runtime) => {
26065
+ if (!runtime.piSessionFile) return false;
25643
26066
  try {
25644
- return retiredManagedSession(
25645
- SessionManager2.open(runtime.piSessionFile)
25646
- );
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;
25647
26070
  } catch {
25648
- return false;
26071
+ return void 0;
25649
26072
  }
25650
- })(),
26073
+ },
25651
26074
  appendError: (ctx, kind, error2) => appendDurableError(pi, ctx, kind, error2),
25652
26075
  onChanged: () => leadStatusRuntime.requestRefresh(),
25653
26076
  reportWatcherError: (ctx, error2) => {
@@ -25891,8 +26314,10 @@ ${globalInstructions}
25891
26314
  prepareCoordinationInput: (...args) => leadRuntimes.coordinationRuntime.prepareCoordinationInput(...args),
25892
26315
  projectMessageBytes,
25893
26316
  writeProjectMessage,
25894
- removeProjectAssignment,
25895
- removeProjectMessages,
26317
+ releaseProjectAssignment,
26318
+ retireProjectAssignment,
26319
+ removeProjectMessagesForAssignment,
26320
+ recoverStaleProjectMessages,
25896
26321
  delay: delay2,
25897
26322
  appendDurableError,
25898
26323
  markLeadCoordinationUnhealthy,
@@ -25981,6 +26406,10 @@ ${globalInstructions}
25981
26406
  };
25982
26407
  prepareSupervisionMessage = (ctx) => leadRuntimes.supervisionUiRuntime.prepareMessage(ctx);
25983
26408
  const leadAgentEventOptions = {
26409
+ drainRetirementNotices: (ctx, preflight) => leadRuntimes.coordinationRuntime.drainRetirementNotices(
26410
+ ctx,
26411
+ preflight
26412
+ ),
25984
26413
  isCurrentChief,
25985
26414
  chiefTools: CHIEF_TOOLS,
25986
26415
  setActiveTools: (tools) => pi.setActiveTools(tools),
@@ -26211,6 +26640,8 @@ ${summary}`,
26211
26640
  selectMenu,
26212
26641
  selectModelMenu,
26213
26642
  readConfig,
26643
+ readEffectiveConfig,
26644
+ readProjectOverrides,
26214
26645
  contextAgentDefinitions,
26215
26646
  discoverRoleDefinition,
26216
26647
  setLeadExecutionMode: (ctx, mode) => leadRuntimes.setLeadExecutionMode(ctx, mode),
@@ -26530,7 +26961,7 @@ ${summary}`,
26530
26961
  appendRoleError: (ctx, error2) => appendDurableError(pi, ctx, "pi_herdsman_role_error", error2)
26531
26962
  };
26532
26963
  const sessionStartOptions = {
26533
- autoActivateManager: () => readConfig().autoActivateManager,
26964
+ autoActivateManager: (ctx) => readEffectiveConfig(ctx).autoActivateManager,
26534
26965
  clearDefinitionRoster: () => {
26535
26966
  startupDefinitionRoster = void 0;
26536
26967
  },