pi-herdsman 0.33.0 → 0.34.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
@@ -718,8 +718,26 @@ function acquireProcessLock(path, options2 = {}) {
718
718
  let staleOwner;
719
719
  try {
720
720
  staleOwner = readProcessLockOwner(claimDir, observedOwner);
721
- } catch {
722
- throw new Error(verifyMessage);
721
+ } catch (error3) {
722
+ if (error3.code === "ENOENT") {
723
+ let currentOwner;
724
+ try {
725
+ ({ owner: currentOwner } = lockOwnerEntry(claimDir));
726
+ } catch (checkError) {
727
+ if (checkError.code === "ENOENT")
728
+ throw new ProcessLockOccupiedError(occupiedMessage);
729
+ throw new Error(verifyMessage, { cause: checkError });
730
+ }
731
+ if (currentOwner !== observedOwner) {
732
+ try {
733
+ readProcessLockOwner(claimDir, currentOwner);
734
+ } catch (checkError) {
735
+ throw new Error(verifyMessage, { cause: checkError });
736
+ }
737
+ throw new ProcessLockOccupiedError(occupiedMessage);
738
+ }
739
+ }
740
+ throw new Error(verifyMessage, { cause: error3 });
723
741
  }
724
742
  try {
725
743
  if (processOwnerExists(staleOwner))
@@ -3173,9 +3191,13 @@ async function listAllHerdrAgents(pi, ctx, signal) {
3173
3191
  async function herdrSessionSnapshot(pi, ctx, signal) {
3174
3192
  const result = await runHerdr(pi, ctx, ["api", "snapshot"], { signal });
3175
3193
  const snapshot = result?.snapshot;
3176
- if (!Array.isArray(snapshot?.panes) || !Array.isArray(snapshot?.agents))
3194
+ if (!Array.isArray(snapshot?.panes) || !Array.isArray(snapshot?.agents) || !Array.isArray(snapshot?.workspaces))
3177
3195
  error("session snapshot", "Herdr session inventory is unavailable");
3178
- return { panes: snapshot.panes, agents: snapshot.agents };
3196
+ return {
3197
+ panes: snapshot.panes,
3198
+ agents: snapshot.agents,
3199
+ workspaces: snapshot.workspaces
3200
+ };
3179
3201
  }
3180
3202
  function watchHerdrLifecycle(socketPath2, signal, onChange) {
3181
3203
  let socket;
@@ -4853,7 +4875,7 @@ function projectWorkspaceProvenance(workspaceId, workspace2, worktreeInfo, fallb
4853
4875
  );
4854
4876
  const repoName = typeof worktree.repo_name === "string" ? worktree.repo_name : typeof worktreeInfo?.source?.repo_name === "string" ? worktreeInfo.source.repo_name : void 0;
4855
4877
  const branch = typeof currentWorktree?.branch === "string" ? currentWorktree.branch : void 0;
4856
- const workspaceCwd = typeof worktreeInfo?.source?.source_checkout_path === "string" ? worktreeInfo.source.source_checkout_path : fallbackCwd;
4878
+ const workspaceCwd = typeof currentWorktree?.path === "string" ? currentWorktree.path : typeof worktree?.checkout_path === "string" ? worktree.checkout_path : fallbackCwd;
4857
4879
  return {
4858
4880
  ...workspaceLabel ? { workspaceLabel } : {},
4859
4881
  ...workspaceCwd ? { workspaceCwd } : {},
@@ -6090,6 +6112,10 @@ function formatToolModelResult(action, v) {
6090
6112
  action = value(action) || "agent";
6091
6113
  const definition = value(v.definition);
6092
6114
  const cleanup = value(v.cleanup_error) ? ["", `Cleanup warning: ${value(v.cleanup_error)}`] : v.cleanup_errors && typeof v.cleanup_errors === "object" ? ["", "Cleanup warnings:", JSON.stringify(v.cleanup_errors, null, 2)] : [];
6115
+ const descendantWarning = value(v.descendant_continuation_warning) ? [
6116
+ "",
6117
+ `Descendant continuation warning: ${value(v.descendant_continuation_warning)}`
6118
+ ] : [];
6093
6119
  if (v.ok === false) {
6094
6120
  const e = v.error ?? {};
6095
6121
  const details = e.details && typeof e.details === "object" ? e.details : void 0;
@@ -6267,7 +6293,8 @@ function formatToolModelResult(action, v) {
6267
6293
  }
6268
6294
  return lines;
6269
6295
  })() : [],
6270
- ...cleanup
6296
+ ...cleanup,
6297
+ ...descendantWarning
6271
6298
  ].join("\n");
6272
6299
  }
6273
6300
  function humanText(theme, color, text) {
@@ -6571,7 +6598,7 @@ function agentHierarchy(details) {
6571
6598
  }
6572
6599
  function expandedResultLines(tool, action, details, args, theme, activeRole) {
6573
6600
  const display = value(details.display_name) || value(details.agent) || value(details.label) || value(details.session) || value(args.agent) || value(args.label) || "agent";
6574
- const heading = action === "list" ? tool === "staff" ? "staff" : tool === "peer" ? "peer" : "agents" : tool === "peer" && action === "message" ? peerMessageStatus(details) : action === "inspect" ? `inspect ${display}` : tool === "staff" && action === "remove" ? "remove worktree" : action === "delegate" || action === "continue" ? `${display} started` : tool === "supervisor" ? "sent to supervisor" : action === "steer" ? "steering queued" : action === "interrupt" ? "interrupt accepted" : tool === "agent" && action === "reply" ? `reply sent to ${display}` : action === "close" ? `${display} closed` : `${action} ${display}`;
6601
+ const heading = tool === "staff" && action === "merge" && details.ok === true ? "merge project" : tool === "staff" && action === "resume" && details.already_running === true ? "project already running" : action === "list" ? tool === "staff" ? "staff" : tool === "peer" ? "peer" : "agents" : tool === "peer" && action === "message" ? peerMessageStatus(details) : action === "inspect" ? `inspect ${display}` : tool === "staff" && action === "remove" ? "remove worktree" : action === "delegate" || action === "continue" ? `${display} started` : tool === "supervisor" ? "sent to supervisor" : action === "steer" ? "steering queued" : action === "interrupt" ? "interrupt accepted" : tool === "agent" && action === "reply" ? `reply sent to ${display}` : action === "close" ? `${display} closed` : `${action} ${display}`;
6575
6602
  const lines = [heading];
6576
6603
  const fields = [
6577
6604
  ["definition", details.definition ?? details.agent_definition],
@@ -6614,6 +6641,16 @@ function expandedResultLines(tool, action, details, args, theme, activeRole) {
6614
6641
  `assignment: ${details.assignment_retired === true ? "retired" : details.assignment_retired === false ? "not retired" : "unconfirmed"}`
6615
6642
  );
6616
6643
  }
6644
+ if (tool === "staff" && action === "merge") {
6645
+ for (const [label, key] of [
6646
+ ["status", "status"],
6647
+ ["integrated", "integrated"],
6648
+ ["checkout removed", "checkout_removed"],
6649
+ ["assignment retired", "assignment_retired"]
6650
+ ])
6651
+ if (details[key] !== void 0)
6652
+ lines.push(`${label}: ${String(details[key])}`);
6653
+ }
6617
6654
  if (action === "list" && tool === "agent")
6618
6655
  lines.push(
6619
6656
  "",
@@ -6629,6 +6666,10 @@ function expandedResultLines(tool, action, details, args, theme, activeRole) {
6629
6666
  })
6630
6667
  ] : []
6631
6668
  );
6669
+ if (action === "close" && value(details.descendant_continuation_warning))
6670
+ lines.push(
6671
+ `descendant continuation warning: ${value(details.descendant_continuation_warning)}`
6672
+ );
6632
6673
  if (action === "list" && (tool === "staff" || tool === "peer")) {
6633
6674
  if (tool === "peer") {
6634
6675
  const peers = Array.isArray(details.peers) ? details.peers : [];
@@ -6793,6 +6834,29 @@ ${resultContent(result)}` : `Confirmation required \xB7 ${value(details.branch)
6793
6834
  );
6794
6835
  if (failed) {
6795
6836
  const raw = resultContent(result);
6837
+ if (!expanded && tool === "staff" && action === "merge" && details.status === "cleanup_pending")
6838
+ return new WidthSafeText(
6839
+ statusLine(
6840
+ theme,
6841
+ "warning",
6842
+ "!",
6843
+ details.integrated === true ? `integrated ${value(details.branch) || value(args.branch) || "branch"} \xB7 cleanup pending` : `merge incomplete \xB7 ${value(details.branch) || value(args.branch) || "branch"}`
6844
+ ),
6845
+ 0,
6846
+ 0
6847
+ );
6848
+ if (expanded && tool === "staff" && action === "merge")
6849
+ return new WidthSafeText(
6850
+ statusLine(
6851
+ theme,
6852
+ "error",
6853
+ "\u2717",
6854
+ raw.length > 4e3 ? `${raw.slice(0, 3999)}\u2026` : raw || "Operation failed"
6855
+ ) + `
6856
+ ${expandedResultLines(tool, action, details, args, theme, context?.activeRole).slice(1).join("\n")}`,
6857
+ 0,
6858
+ 0
6859
+ );
6796
6860
  const fallback = expanded ? raw.length > 4e3 ? `${raw.slice(0, 3999)}\u2026` : raw || "Operation failed" : collapseDisplayText(raw, 240) || "Operation failed";
6797
6861
  return new WidthSafeText(statusLine(theme, "error", "\u2717", fallback), 0, 0);
6798
6862
  }
@@ -6801,6 +6865,27 @@ ${resultContent(result)}` : `Confirmation required \xB7 ${value(details.branch)
6801
6865
  ...context,
6802
6866
  expanded: false
6803
6867
  });
6868
+ if (tool === "staff" && action === "merge") {
6869
+ const branch = value(details.branch) || value(args.branch) || "branch";
6870
+ const complete = details.status === "complete" && details.integrated === true && details.checkout_removed === true && details.assignment_retired === true;
6871
+ const outcome = complete ? `integrated ${branch} \xB7 checkout removed \xB7 assignment retired` : `merge incomplete \xB7 ${branch}`;
6872
+ if (!expanded)
6873
+ return new WidthSafeText(
6874
+ statusLine(
6875
+ theme,
6876
+ complete ? "success" : "warning",
6877
+ complete ? "\u2713" : "!",
6878
+ outcome
6879
+ ),
6880
+ 0,
6881
+ 0
6882
+ );
6883
+ }
6884
+ if (!expanded && tool === "staff" && ["delegate", "resume", "stop"].includes(action)) {
6885
+ const branch = value(details.branch) || value(args.branch) || "project";
6886
+ const outcome = action === "delegate" ? `project started \xB7 ${branch}` : action === "resume" ? details.already_running === true ? `project already running \xB7 ${branch}` : `project resumed \xB7 ${branch}` : `Lead stopped \xB7 ${branch} preserved`;
6887
+ return new WidthSafeText(statusLine(theme, "success", "\u2713", outcome), 0, 0);
6888
+ }
6804
6889
  if (expanded)
6805
6890
  return new WidthSafeText(
6806
6891
  expandedResultLines(
@@ -6852,7 +6937,8 @@ ${resultContent(result)}` : `Confirmation required \xB7 ${value(details.branch)
6852
6937
  const message = action === "delegate" || action === "continue" ? `${label} started` : action === "steer" ? "steering queued" : action === "reply" ? "reply sent" : action === "close" ? `${label} closed` : `${action} ${label}`;
6853
6938
  return new WidthSafeText(
6854
6939
  statusLine(theme, "success", "\u2713", message) + (details.cleanup_error || details.cleanup_errors && typeof details.cleanup_errors === "object" ? `
6855
- ${humanText(theme, "warning", ` ! cleanup warning \xB7 Ctrl+O`)}` : ""),
6940
+ ${humanText(theme, "warning", ` ! cleanup warning \xB7 Ctrl+O`)}` : "") + (action === "close" && value(details.descendant_continuation_warning) ? `
6941
+ ${humanText(theme, "warning", ` ! descendant continuation warning \xB7 Ctrl+O`)}` : ""),
6856
6942
  0,
6857
6943
  0
6858
6944
  );
@@ -9135,6 +9221,13 @@ function parseRawConfig(content) {
9135
9221
  throw new Error("Invalid Pi Herdsman config field autoActivateManager");
9136
9222
  result.autoActivateManager = record.autoActivateManager;
9137
9223
  }
9224
+ if ("managerGitBootstrapWithoutConfirmation" in record) {
9225
+ if (typeof record.managerGitBootstrapWithoutConfirmation !== "boolean")
9226
+ throw new Error(
9227
+ "Invalid Pi Herdsman config field managerGitBootstrapWithoutConfirmation"
9228
+ );
9229
+ result.managerGitBootstrapWithoutConfirmation = record.managerGitBootstrapWithoutConfirmation;
9230
+ }
9138
9231
  if ("managerMergeEnabled" in record) {
9139
9232
  if (typeof record.managerMergeEnabled !== "boolean")
9140
9233
  throw new Error("Invalid Pi Herdsman config field managerMergeEnabled");
@@ -9415,6 +9508,10 @@ function updateConfig(key, value2) {
9415
9508
  throw new Error("Invalid Pi Herdsman config field contextRetirement");
9416
9509
  if (key === "autoActivateManager" && typeof value2 !== "boolean")
9417
9510
  throw new Error("Invalid Pi Herdsman config field autoActivateManager");
9511
+ if (key === "managerGitBootstrapWithoutConfirmation" && typeof value2 !== "boolean")
9512
+ throw new Error(
9513
+ "Invalid Pi Herdsman config field managerGitBootstrapWithoutConfirmation"
9514
+ );
9418
9515
  if (key === "managerMergeEnabled" && typeof value2 !== "boolean")
9419
9516
  throw new Error("Invalid Pi Herdsman config field managerMergeEnabled");
9420
9517
  if (key === "managerMergeOverrides" && !validManagerMergeOverrides(value2))
@@ -9425,7 +9522,7 @@ function updateConfig(key, value2) {
9425
9522
  throw new Error(
9426
9523
  "Invalid Pi Herdsman config field worktreeRemovalPreapprovedRepos"
9427
9524
  );
9428
- if (key !== "spawnPlacement" && key !== "defaultLeadExecution" && key !== "contextRetirement" && key !== "autoActivateManager" && key !== "managerMergeEnabled" && key !== "managerMergeOverrides" && key !== "worktreeRemovalPreapprovedRepos" && !validByteLimit(value2))
9525
+ if (key !== "spawnPlacement" && key !== "defaultLeadExecution" && key !== "contextRetirement" && key !== "autoActivateManager" && key !== "managerGitBootstrapWithoutConfirmation" && key !== "managerMergeEnabled" && key !== "managerMergeOverrides" && key !== "worktreeRemovalPreapprovedRepos" && !validByteLimit(value2))
9429
9526
  throw new Error(`Invalid Pi Herdsman config field ${key}`);
9430
9527
  current[key] = value2;
9431
9528
  } else delete current[key];
@@ -9458,6 +9555,7 @@ var init_config = __esm({
9458
9555
  defaultLeadExecution: "flexible",
9459
9556
  contextRetirement: true,
9460
9557
  autoActivateManager: false,
9558
+ managerGitBootstrapWithoutConfirmation: false,
9461
9559
  inlineAttachmentLimitBytes: DEFAULT_BYTE_LIMIT,
9462
9560
  mailboxPayloadLimitBytes: DEFAULT_BYTE_LIMIT,
9463
9561
  worktreeRemovalPreapprovedRepos: [],
@@ -9469,6 +9567,7 @@ var init_config = __esm({
9469
9567
  "defaultLeadExecution",
9470
9568
  "contextRetirement",
9471
9569
  "autoActivateManager",
9570
+ "managerGitBootstrapWithoutConfirmation",
9472
9571
  "inlineAttachmentLimitBytes",
9473
9572
  "mailboxPayloadLimitBytes",
9474
9573
  "worktreeRemovalPreapprovedRepos",
@@ -9497,7 +9596,7 @@ import {
9497
9596
  writeFileSync as writeFileSync5
9498
9597
  } from "node:fs";
9499
9598
  import { createHash as createHash8, randomUUID as randomUUID9 } from "node:crypto";
9500
- import { basename as basename7, dirname as dirname7, join as join8 } from "node:path";
9599
+ import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute3, join as join8, normalize } from "node:path";
9501
9600
  import { isDeepStrictEqual } from "node:util";
9502
9601
  function readSessionKind(entries, sessionId) {
9503
9602
  let identity;
@@ -10421,6 +10520,48 @@ function withProjectAssignmentLock(operation) {
10421
10520
  lease.release();
10422
10521
  }
10423
10522
  }
10523
+ async function withProjectAssignmentAuthorityWait(operation, signal, onOccupied) {
10524
+ const deadline = Date.now() + 2e3;
10525
+ while (true) {
10526
+ signal?.throwIfAborted();
10527
+ let lease;
10528
+ try {
10529
+ lease = acquireProcessLock(projectAuthorityLock, {
10530
+ name: "project assignment authority"
10531
+ });
10532
+ } catch (error2) {
10533
+ if (!(error2 instanceof ProcessLockOccupiedError)) throw error2;
10534
+ onOccupied?.();
10535
+ const remaining = deadline - Date.now();
10536
+ if (remaining <= 0) throw error2;
10537
+ await new Promise((resolve8, reject) => {
10538
+ const timer = setTimeout(done, Math.min(25, remaining));
10539
+ function done() {
10540
+ signal?.removeEventListener("abort", aborted);
10541
+ resolve8();
10542
+ }
10543
+ function aborted() {
10544
+ clearTimeout(timer);
10545
+ signal?.removeEventListener("abort", aborted);
10546
+ reject(signal?.reason ?? new Error("Operation aborted"));
10547
+ }
10548
+ signal?.addEventListener("abort", aborted, { once: true });
10549
+ if (signal?.aborted) aborted();
10550
+ });
10551
+ continue;
10552
+ }
10553
+ try {
10554
+ const result = operation();
10555
+ if (result && typeof result.then === "function")
10556
+ throw new Error(
10557
+ "Project assignment authority operation must be synchronous"
10558
+ );
10559
+ return result;
10560
+ } finally {
10561
+ lease.release();
10562
+ }
10563
+ }
10564
+ }
10424
10565
  function peerRuntime(_socket) {
10425
10566
  const root2 = join8(herdsmanDataRoot(), "runtime", "peers-v2");
10426
10567
  return {
@@ -10839,7 +10980,7 @@ function claimManagerLease(identity, runtime = supervisionRuntime()) {
10839
10980
  };
10840
10981
  }
10841
10982
  function projectAssignmentBytes(assignment) {
10842
- const { piSessionFile: _, ...payload } = assignment;
10983
+ const { checkoutPath: _, piSessionFile: __, ...payload } = assignment;
10843
10984
  return Buffer.byteLength(`${JSON.stringify(payload)}
10844
10985
  `, "utf8");
10845
10986
  }
@@ -10857,6 +10998,7 @@ function validProjectAssignment(value2) {
10857
10998
  const r = value2;
10858
10999
  const required = ["version", "id", "repoKey", "branch", "text"];
10859
11000
  const optional = [
11001
+ "checkoutPath",
10860
11002
  "piSessionFile",
10861
11003
  "resultBindings",
10862
11004
  "requiredEvidence",
@@ -10864,7 +11006,7 @@ function validProjectAssignment(value2) {
10864
11006
  ];
10865
11007
  return required.every((key) => Object.hasOwn(r, key)) && Object.keys(r).every(
10866
11008
  (key) => required.includes(key) || optional.includes(key)
10867
- ) && Object.keys(r).length >= required.length && r.version === 2 && UUID3.test(String(r.id)) && validNativeIdentity(r.repoKey) && validNativeIdentity(r.branch) && typeof r.text === "string" && r.text.length > 0 && (r.piSessionFile === void 0 || typeof r.piSessionFile === "string" && r.piSessionFile.length > 0) && (r.resultBindings === void 0 || Array.isArray(r.resultBindings) && r.resultBindings.every(isResultBinding)) && (r.requiredEvidence === void 0 || Array.isArray(r.requiredEvidence) && r.requiredEvidence.every(isRequiredEvidence) && r.requiredEvidence.every(
11009
+ ) && Object.keys(r).length >= required.length && r.version === 2 && UUID3.test(String(r.id)) && validNativeIdentity(r.repoKey) && validNativeIdentity(r.branch) && typeof r.text === "string" && r.text.length > 0 && (r.checkoutPath === void 0 || typeof r.checkoutPath === "string" && isAbsolute3(r.checkoutPath) && normalize(r.checkoutPath) === r.checkoutPath && !/[\u0000-\u001f]/.test(r.checkoutPath)) && (r.piSessionFile === void 0 || typeof r.piSessionFile === "string" && r.piSessionFile.length > 0) && (r.resultBindings === void 0 || Array.isArray(r.resultBindings) && r.resultBindings.every(isResultBinding)) && (r.requiredEvidence === void 0 || Array.isArray(r.requiredEvidence) && r.requiredEvidence.every(isRequiredEvidence) && r.requiredEvidence.every(
10868
11010
  (evidence) => "result" in evidence || evidence.sourceAssignmentId === r.id
10869
11011
  ) && new Set(r.requiredEvidence.map((evidence) => evidence.id)).size === r.requiredEvidence.length) && (r.currentEvidenceIds === void 0 || Array.isArray(r.currentEvidenceIds) && new Set(r.currentEvidenceIds).size === r.currentEvidenceIds.length && r.currentEvidenceIds.every(
10870
11012
  (id) => typeof id === "string" && r.requiredEvidence?.some(
@@ -10877,6 +11019,25 @@ function writeProjectAssignment(runtime, assignment) {
10877
11019
  () => writeProjectAssignmentUnlocked(runtime, assignment)
10878
11020
  );
10879
11021
  }
11022
+ function writeProjectAssignmentAfter(runtime, expected, assignment, signal, verifyAuthority, onOccupied) {
11023
+ return withProjectAssignmentAuthorityWait(
11024
+ () => {
11025
+ verifyAuthority?.();
11026
+ const current = readProjectAssignment(
11027
+ runtime,
11028
+ expected.repoKey,
11029
+ expected.branch
11030
+ );
11031
+ if (!current || !isDeepStrictEqual(current, expected))
11032
+ throw new Error(
11033
+ "Project assignment changed before required evidence was updated"
11034
+ );
11035
+ writeProjectAssignmentUnlocked(runtime, assignment);
11036
+ },
11037
+ signal,
11038
+ onOccupied
11039
+ );
11040
+ }
10880
11041
  function writeProjectAssignmentUnlocked(runtime, assignment) {
10881
11042
  assignment = upgradeProjectAssignmentEvidence(assignment);
10882
11043
  if (!validProjectAssignment(assignment))
@@ -10939,6 +11100,19 @@ function migrateProjectAssignmentEvidence(runtime, repoKey, branch, expectedAssi
10939
11100
  return upgraded;
10940
11101
  });
10941
11102
  }
11103
+ function migrateProjectAssignmentEvidenceAfter(runtime, expected, signal) {
11104
+ return withProjectAssignmentAuthorityWait(() => {
11105
+ const current = readProjectAssignment(
11106
+ runtime,
11107
+ expected.repoKey,
11108
+ expected.branch
11109
+ );
11110
+ if (!current || !isDeepStrictEqual(current, expected)) return void 0;
11111
+ const upgraded = upgradeProjectAssignmentEvidence(current);
11112
+ if (upgraded !== current) writeProjectAssignmentUnlocked(runtime, upgraded);
11113
+ return upgraded;
11114
+ }, signal);
11115
+ }
10942
11116
  function readProjectAssignment(runtime, repoKey, branch) {
10943
11117
  const path = projectAssignmentPath(runtime, repoKey, branch);
10944
11118
  return readProjectAssignmentFile(path, repoKey, branch);
@@ -12414,6 +12588,44 @@ function currentManagedEvidence(ctx) {
12414
12588
  ...data.currentEvidenceIds ? { currentEvidenceIds: [...data.currentEvidenceIds] } : {}
12415
12589
  };
12416
12590
  }
12591
+ function acceptedCloseProof(entries, ownerSessionId, closed) {
12592
+ const { state } = closed;
12593
+ const child = {
12594
+ id: state.piSessionId ?? "",
12595
+ path: state.piSessionFile ?? "",
12596
+ definition: closed.definition,
12597
+ label: state.agentLabel
12598
+ };
12599
+ if (!child.id || !child.path || state.ownerSessionId !== ownerSessionId || !validId(state.runId) || !validId(state.activeRequestId ?? state.resultError?.requestId ?? ""))
12600
+ return void 0;
12601
+ const requestId = state.activeRequestId ?? state.resultError?.requestId;
12602
+ const accepted = acceptedAssignmentReceipts(
12603
+ entries,
12604
+ ownerSessionId,
12605
+ child
12606
+ ).filter(({ requestId: acceptedId }) => acceptedId === requestId);
12607
+ if (!validId(requestId ?? "") || accepted.length !== 1) return void 0;
12608
+ return {
12609
+ owner_session_id: ownerSessionId,
12610
+ session_id: child.id,
12611
+ session_path: child.path,
12612
+ run_id: state.runId,
12613
+ request_id: requestId,
12614
+ agent: state.agentLabel,
12615
+ definition: closed.definition,
12616
+ pane_id: state.paneId,
12617
+ workspace_id: state.workspaceId
12618
+ };
12619
+ }
12620
+ function validClosedProof(proof, ownerSessionId, child) {
12621
+ if (!proof || typeof proof !== "object" || proof.owner_session_id !== ownerSessionId || proof.session_id !== child.id || proof.definition !== child.definition || proof.agent !== child.label || typeof proof.session_path !== "string" || !validId(proof.run_id) || !validId(proof.request_id) || typeof proof.pane_id !== "string" || !proof.pane_id.trim() || typeof proof.workspace_id !== "string" || !proof.workspace_id.trim())
12622
+ return false;
12623
+ try {
12624
+ return canonicalSessionPath(proof.session_path) === child.path;
12625
+ } catch {
12626
+ return false;
12627
+ }
12628
+ }
12417
12629
  function closedAssignmentReceipt(entries, ownerSessionId, child) {
12418
12630
  const accepted = acceptedAssignmentReceipts(entries, ownerSessionId, child);
12419
12631
  const closed = entries.flatMap((entry, index) => {
@@ -12422,14 +12634,20 @@ function closedAssignmentReceipt(entries, ownerSessionId, child) {
12422
12634
  const message = entry.message;
12423
12635
  const details = message?.details;
12424
12636
  const proof2 = details?.closed_assignment;
12425
- if (message?.role !== "toolResult" || message.toolName !== "close_agent" || message.isError === true || details?.ok !== true || details.action !== "close" || details.cleanup_error !== void 0 || details.cleanup_errors !== void 0 || !proof2 || proof2.owner_session_id !== ownerSessionId || proof2.session_id !== child.id || proof2.definition !== child.definition || proof2.agent !== child.label || typeof proof2.session_path !== "string" || !validId(proof2.run_id) || !validId(proof2.request_id) || typeof proof2.pane_id !== "string" || !proof2.pane_id.trim() || typeof proof2.workspace_id !== "string" || !proof2.workspace_id.trim())
12637
+ if (message?.role !== "toolResult" || message.toolName !== "close_agent" || message.isError === true || details?.ok !== true || details.action !== "close" || details.cleanup_error !== void 0 || details.cleanup_errors !== void 0 || !validClosedProof(proof2, ownerSessionId, child))
12426
12638
  return [];
12427
- try {
12428
- return canonicalSessionPath(proof2.session_path) === child.path ? [{ index, proof: proof2 }] : [];
12429
- } catch {
12639
+ return [{ index, proof: proof2 }];
12640
+ });
12641
+ const stopped = entries.flatMap((entry, index) => {
12642
+ if (!entry || typeof entry !== "object" || !("type" in entry) || entry.type !== "custom" || !("customType" in entry) || entry.customType !== STOP_CLOSURE_ENTRY)
12430
12643
  return [];
12431
- }
12644
+ const data = entry.data;
12645
+ const proof2 = data?.proof;
12646
+ if (data?.version !== 1 || !validClosedProof(proof2, ownerSessionId, child))
12647
+ return [];
12648
+ return [{ index, proof: proof2 }];
12432
12649
  });
12650
+ closed.push(...stopped);
12433
12651
  const latestAccepted = accepted.at(-1);
12434
12652
  const matches = latestAccepted ? closed.filter(
12435
12653
  ({ index, proof: proof2 }) => latestAccepted.index < index && latestAccepted.requestId === proof2.request_id
@@ -12452,7 +12670,7 @@ function acceptedAssignmentReceipts(entries, ownerSessionId, child) {
12452
12670
  ].includes(message.toolName) || message.isError === true || details?.ok !== true || details.owner_session_id !== ownerSessionId || details.session_id !== child.id || details.agent !== child.label || details.definition !== child.definition || typeof details.session_path !== "string" || !validId(details.request_id))
12453
12671
  return [];
12454
12672
  try {
12455
- return canonicalSessionPath(details.session_path) === child.path ? [{ index, requestId: details.request_id }] : [];
12673
+ return canonicalSessionPath(details.session_path) === canonicalSessionPath(child.path) ? [{ index, requestId: details.request_id }] : [];
12456
12674
  } catch {
12457
12675
  return [];
12458
12676
  }
@@ -13380,12 +13598,12 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
13380
13598
  }
13381
13599
  if (!manager) continue;
13382
13600
  visited.add(child.id);
13383
- const found = walk(child.id, manager.getEntries());
13601
+ const found = walk(child.id, manager.getBranch());
13384
13602
  if (found) return found;
13385
13603
  }
13386
13604
  return void 0;
13387
13605
  };
13388
- const resolved = walk(callerId, ctx.sessionManager.getEntries());
13606
+ const resolved = walk(callerId, ctx.sessionManager.getBranch());
13389
13607
  if (!resolved)
13390
13608
  fail(
13391
13609
  "invalid_request",
@@ -14518,8 +14736,16 @@ function createAgentController(pi, options2) {
14518
14736
  fail("internal_failure", message, operation);
14519
14737
  }
14520
14738
  }
14521
- await submitOptions.beforeWrite?.();
14522
- writeRequest(runtime.mailboxPath, request);
14739
+ let requestWritten = false;
14740
+ const publish = () => {
14741
+ if (requestWritten)
14742
+ fail("internal_failure", "Request was already published", operation);
14743
+ writeRequest(runtime.mailboxPath, request);
14744
+ requestWritten = true;
14745
+ options2.afterRequestPublishedForTest?.(runtime.mailboxPath, request);
14746
+ };
14747
+ await submitOptions.beforeWrite?.(publish);
14748
+ if (!requestWritten) publish();
14523
14749
  } catch (error2) {
14524
14750
  if (String(error2).toLowerCase().includes("too large"))
14525
14751
  fail(
@@ -14884,7 +15110,10 @@ function createAgentController(pi, options2) {
14884
15110
  "close"
14885
15111
  );
14886
15112
  const warnings = /* @__PURE__ */ new Map();
15113
+ let descendantContinuationWarning;
15114
+ const closed = [];
14887
15115
  const report = {
15116
+ onClosed: (outcome) => closed.push(outcome),
14888
15117
  onCleanupFailure: (label, message) => warnings.set(label, message)
14889
15118
  };
14890
15119
  try {
@@ -14907,28 +15136,32 @@ function createAgentController(pi, options2) {
14907
15136
  options2.appendError(context, "pi_herdsman_cleanup_error", failure);
14908
15137
  throw failure;
14909
15138
  }
15139
+ const descendants = closed.filter(
15140
+ ({ state: closedState }) => !sameIdentity(closedState, state)
15141
+ );
15142
+ if (descendants.length && options2.persistClosedDescendants) {
15143
+ try {
15144
+ for (const warning of await options2.persistClosedDescendants(
15145
+ context,
15146
+ descendants,
15147
+ state
15148
+ )) {
15149
+ descendantContinuationWarning = warning;
15150
+ break;
15151
+ }
15152
+ } catch {
15153
+ descendantContinuationWarning = "Descendant continuation proof could not be safely persisted";
15154
+ }
15155
+ }
14910
15156
  const ownerSessionId = context.sessionManager.getSessionId();
14911
- const closedRequestId = state.activeRequestId ?? state.resultError?.requestId;
14912
- const closedAssignment = !warnings.size && state.ownerSessionId === ownerSessionId && !!state.piSessionId && !!state.piSessionFile && !!closedRequestId && validId(closedRequestId) && validId(state.runId) && context.sessionManager.getEntries().some((entry) => {
14913
- const message = entry?.message;
14914
- const details = message?.details;
14915
- return entry?.type === "message" && message?.role === "toolResult" && [
14916
- "delegate_agent",
14917
- "continue_agent",
14918
- "agent_delegate",
14919
- "agent_continue"
14920
- ].includes(message.toolName) && message.isError !== true && details?.ok === true && details.owner_session_id === ownerSessionId && details.session_id === state.piSessionId && details.session_path === state.piSessionFile && details.request_id === closedRequestId && details.agent === state.agentLabel && details.definition === candidate.agentDefinition;
14921
- }) ? {
14922
- owner_session_id: ownerSessionId,
14923
- session_id: state.piSessionId,
14924
- session_path: state.piSessionFile,
14925
- run_id: state.runId,
14926
- request_id: closedRequestId,
14927
- agent: state.agentLabel,
14928
- definition: candidate.agentDefinition,
14929
- pane_id: state.paneId,
14930
- workspace_id: state.workspaceId
14931
- } : void 0;
15157
+ const closedAssignment = !warnings.size ? acceptedCloseProof(
15158
+ context.sessionManager.getEntries(),
15159
+ ownerSessionId,
15160
+ {
15161
+ state,
15162
+ definition: candidate.agentDefinition
15163
+ }
15164
+ ) : void 0;
14932
15165
  return {
14933
15166
  ok: true,
14934
15167
  action: "close",
@@ -14936,7 +15169,8 @@ function createAgentController(pi, options2) {
14936
15169
  ...closedAssignment ? { closed_assignment: closedAssignment } : {},
14937
15170
  presentation_agent_definition: candidate.agentDefinition,
14938
15171
  ...warnings.size === 1 ? { cleanup_error: [...warnings.values()][0] } : {},
14939
- ...warnings.size > 1 ? { cleanup_errors: Object.fromEntries(warnings) } : {}
15172
+ ...warnings.size > 1 ? { cleanup_errors: Object.fromEntries(warnings) } : {},
15173
+ ...descendantContinuationWarning ? { descendant_continuation_warning: descendantContinuationWarning } : {}
14940
15174
  };
14941
15175
  };
14942
15176
  const transcriptAction = async (context, agentLabel, signal) => {
@@ -15204,7 +15438,10 @@ function createAgentController(pi, options2) {
15204
15438
  return;
15205
15439
  }
15206
15440
  invalidateRuntime(state.agentLabel, state.workspaceId);
15207
- report?.onClosed?.(state.agentLabel);
15441
+ report?.onClosed?.({
15442
+ state: current,
15443
+ definition: snapshot2.agentDefinition
15444
+ });
15208
15445
  } finally {
15209
15446
  release?.();
15210
15447
  }
@@ -15383,8 +15620,9 @@ function createAgentController(pi, options2) {
15383
15620
  { ids: { label: current.agentLabel, paneId: current.paneId } }
15384
15621
  );
15385
15622
  await closeCascade(context, current, signal, void 0, {
15386
- onClosed: (label) => {
15387
- if (!closed.includes(label)) closed.push(label);
15623
+ onClosed: (outcome) => {
15624
+ if (!closed.some(({ state }) => sameIdentity(state, outcome.state)))
15625
+ closed.push(outcome);
15388
15626
  },
15389
15627
  onCleanupFailure: (label, message) => {
15390
15628
  cleanupFailureReported = true;
@@ -15407,7 +15645,7 @@ function createAgentController(pi, options2) {
15407
15645
  options2.appendError(context, "pi_herdsman_cleanup_error", failure);
15408
15646
  }
15409
15647
  }
15410
- const closedLabels = new Set(closed);
15648
+ const closedLabels = new Set(closed.map(({ state }) => state.agentLabel));
15411
15649
  for (const agent of reportable)
15412
15650
  if (!closedLabels.has(agent.state.agentLabel) && !failures.has(agent.state.agentLabel))
15413
15651
  recordFailure(agent.state.agentLabel, "not closed");
@@ -15430,11 +15668,12 @@ function createAgentController(pi, options2) {
15430
15668
  if (!targets.length)
15431
15669
  return {
15432
15670
  complete,
15433
- summary: complete ? "No owned agents running." : `Owned Agent stop incomplete: ${[...failures.values()].map(({ label, message }) => `${label}: ${message}`).join("; ")}`
15671
+ summary: complete ? "No owned agents running." : `Owned Agent stop incomplete: ${[...failures.values()].map(({ label, message }) => `${label}: ${message}`).join("; ")}`,
15672
+ closures: closed
15434
15673
  };
15435
15674
  const lines = closed.length === reportable.length && !failures.size ? [`Stopped ${closed.length} agents`] : [`Stopped ${closed.length} of ${reportable.length} agents`];
15436
15675
  lines.push(
15437
- ...closed.map((label) => `\u2713 ${label}`),
15676
+ ...closed.map(({ state }) => `\u2713 ${state.agentLabel}`),
15438
15677
  ...[...failures.values()].map(
15439
15678
  ({ label, message }) => `\u2717 ${label}: ${message}`
15440
15679
  )
@@ -15443,7 +15682,8 @@ function createAgentController(pi, options2) {
15443
15682
  lines.push("Discarded:", ...discarded.map((entry) => ` ${entry}`));
15444
15683
  return {
15445
15684
  complete,
15446
- summary: lines.join("\n")
15685
+ summary: lines.join("\n"),
15686
+ closures: closed
15447
15687
  };
15448
15688
  };
15449
15689
  const stopResultWatcher = (runtime, requestId) => {
@@ -16253,7 +16493,7 @@ function createAgentController(pi, options2) {
16253
16493
  )
16254
16494
  );
16255
16495
  const closedReceipt = closedAssignmentReceipt(
16256
- ctx.sessionManager.getEntries(),
16496
+ ctx.sessionManager.getBranch(),
16257
16497
  ctx.sessionManager.getSessionId(),
16258
16498
  resumed
16259
16499
  );
@@ -16319,7 +16559,7 @@ function createAgentController(pi, options2) {
16319
16559
  );
16320
16560
  const projectAssignmentId = nestedEvidence?.projectAssignmentId ?? continuationEvidence?.projectAssignmentId;
16321
16561
  let projectEvidence;
16322
- projectEvidence = scope.kind === "root" ? await options2.projectEvidence?.(ctx) : nestedEvidence && projectAssignmentId ? await options2.managedProjectEvidence?.(
16562
+ projectEvidence = scope.kind === "root" ? await options2.projectEvidence?.(ctx, signal) : nestedEvidence && projectAssignmentId ? await options2.managedProjectEvidence?.(
16323
16563
  ctx,
16324
16564
  nestedEvidence.workspaceId,
16325
16565
  projectAssignmentId
@@ -17153,7 +17393,7 @@ ${result.stderr ?? ""}`.trim(),
17153
17393
  {
17154
17394
  waitForLock: true,
17155
17395
  evidence: evidenceMetadata,
17156
- beforeWrite: async () => {
17396
+ beforeWrite: async (publish) => {
17157
17397
  assertRootDelegationAllowed();
17158
17398
  if (nestedEvidence) {
17159
17399
  const current = currentManagedEvidence(ctx);
@@ -17209,7 +17449,7 @@ ${result.stderr ?? ""}`.trim(),
17209
17449
  return;
17210
17450
  }
17211
17451
  await projectEvidence.revalidate(async () => {
17212
- const current = scope.kind === "root" ? await options2.projectEvidence?.(ctx) : nestedEvidence && projectAssignmentId ? await options2.managedProjectEvidence?.(
17452
+ const current = scope.kind === "root" ? await options2.projectEvidence?.(ctx, signal) : nestedEvidence && projectAssignmentId ? await options2.managedProjectEvidence?.(
17213
17453
  ctx,
17214
17454
  nestedEvidence.workspaceId,
17215
17455
  projectAssignmentId
@@ -17224,6 +17464,18 @@ ${result.stderr ?? ""}`.trim(),
17224
17464
  throw new Error(
17225
17465
  "Project assignment or required evidence changed during Agent startup; retry delegation"
17226
17466
  );
17467
+ if (scope.kind === "root")
17468
+ await current.publishIfCurrent((latest) => {
17469
+ if (!latest || latest.id !== current.assignment.id || !resumed && (JSON.stringify(latest.requiredEvidence ?? []) !== JSON.stringify(
17470
+ current.assignment.requiredEvidence ?? []
17471
+ ) || JSON.stringify(latest.currentEvidenceIds ?? []) !== JSON.stringify(
17472
+ current.assignment.currentEvidenceIds ?? []
17473
+ )))
17474
+ throw new Error(
17475
+ "Project assignment or required evidence changed during Agent startup; retry delegation"
17476
+ );
17477
+ publish();
17478
+ });
17227
17479
  });
17228
17480
  }
17229
17481
  }
@@ -17731,7 +17983,7 @@ ${result.stderr ?? ""}`.trim(),
17731
17983
  ...agentTool,
17732
17984
  name: "close_agent",
17733
17985
  label: "close agent",
17734
- description: "Destructively close an eligible directly owned Agent generation.",
17986
+ description: "Destructively close the verified eligible directly owned Agent generation and cascade through its owned descendants, child-first.",
17735
17987
  parameters: agentTargetParameters,
17736
17988
  promptSnippet: void 0,
17737
17989
  promptGuidelines: void 0,
@@ -18754,7 +19006,7 @@ function collectSessionUsage(ctx, ownedChildren, openOwnedSession, leadRoots = [
18754
19006
  breakdown
18755
19007
  };
18756
19008
  }
18757
- var claimDelegationLock, SHARED_AGENT_INSTRUCTIONS, INTEGRATION_SESSION_RETRY_MS, INTEGRATION_SESSION_RETRIES, HEALTH_STALE_AFTER_MS, HEALTH_STALE_SCAN_MS, HEALTH_STALE_DIAGNOSTIC_TIMEOUT_MS, HEALTH_STALE_DIAGNOSTIC_LINES, HEALTH_ATTENTION_REPEAT_MIN_MS, HEALTH_ATTENTION_FIRST_REPEAT_MS, AGENT_LABEL_PATTERN, validAgentLabel, modelToken, messageLimits, AGENT_DEFINITION_ENTRY, AGENT_EXECUTION_OWNERSHIP_GUIDANCE, AGENT_UNRESOLVED_GUIDANCE, AGENT_DELEGATION_GUIDANCE, AGENT_HANDOFF_GUIDANCE, LEAD_SCOPE_DESCRIPTION, DELEGATING_AGENT_SCOPE_DESCRIPTION, RESULT_REF_ENTRY, TRANSCRIPT_MAX_BYTES, TRANSCRIPT_TOOL_RESULT_MAX_BYTES, TRANSCRIPT_TOOL_RESULT_OMISSION;
19009
+ var claimDelegationLock, SHARED_AGENT_INSTRUCTIONS, INTEGRATION_SESSION_RETRY_MS, INTEGRATION_SESSION_RETRIES, HEALTH_STALE_AFTER_MS, HEALTH_STALE_SCAN_MS, HEALTH_STALE_DIAGNOSTIC_TIMEOUT_MS, HEALTH_STALE_DIAGNOSTIC_LINES, HEALTH_ATTENTION_REPEAT_MIN_MS, HEALTH_ATTENTION_FIRST_REPEAT_MS, AGENT_LABEL_PATTERN, validAgentLabel, modelToken, messageLimits, AGENT_DEFINITION_ENTRY, AGENT_EXECUTION_OWNERSHIP_GUIDANCE, AGENT_UNRESOLVED_GUIDANCE, AGENT_DELEGATION_GUIDANCE, AGENT_HANDOFF_GUIDANCE, LEAD_SCOPE_DESCRIPTION, DELEGATING_AGENT_SCOPE_DESCRIPTION, STOP_CLOSURE_ENTRY, RESULT_REF_ENTRY, TRANSCRIPT_MAX_BYTES, TRANSCRIPT_TOOL_RESULT_MAX_BYTES, TRANSCRIPT_TOOL_RESULT_OMISSION;
18758
19010
  var init_agent_controller = __esm({
18759
19011
  "extension/agent-controller.ts"() {
18760
19012
  init_errors();
@@ -18845,10 +19097,6 @@ blockers, remaining work, and reusable paths or artifacts.`;
18845
19097
  and final technical decisions within your assigned objective. Integrate resolved Agent results and
18846
19098
  carry relevant evidence into onward handoffs. Decompose only as far as useful.
18847
19099
  Reuse adequate existing evidence instead of duplicating work.
18848
- Managed identity is permanent for the exact Pi session. Only a current exact
18849
- ProjectAssignment permits fresh project execution; exactly owned Agent recovery
18850
- remains separate. Use native Pi /fork or /clone for independent ordinary
18851
- continuation; this does not create a separate Git checkout or fresh process configuration.
18852
19100
  Your herd is your internal team: you and your recursively owned Agents.
18853
19101
  Any review conducted within the herd is internal feedback, not user or supervisor
18854
19102
  review or approval.`;
@@ -18864,6 +19112,7 @@ ask_owner follows its normal eligibility rules when you have no unresolved
18864
19112
  direct-agent work. If unresolved direct-agent work exists, every such agent
18865
19113
  must itself be validly waiting on an owner answer; ordinary active or
18866
19114
  pending-result agent work still blocks escalation.`;
19115
+ STOP_CLOSURE_ENTRY = "pi-herdsman-agent-closed-assignment";
18867
19116
  RESULT_REF_ENTRY = "pi-herdsman-result-ref";
18868
19117
  TRANSCRIPT_MAX_BYTES = 16 * 1024;
18869
19118
  TRANSCRIPT_TOOL_RESULT_MAX_BYTES = 4 * 1024;
@@ -18905,7 +19154,7 @@ __export(managed_agent_runtime_exports, {
18905
19154
  sessionContextRetired: () => sessionContextRetired,
18906
19155
  validateManagedAgentIdentity: () => validateManagedAgentIdentity
18907
19156
  });
18908
- import { isAbsolute as isAbsolute4, resolve as resolve5 } from "node:path";
19157
+ import { isAbsolute as isAbsolute5, resolve as resolve5 } from "node:path";
18909
19158
  import { realpathSync as realpathSync4 } from "node:fs";
18910
19159
  import { buildSessionProjection as buildSessionProjection2 } from "@earendil-works/pi-coding-agent";
18911
19160
  import { contentText as contentText3 } from "@earendil-works/pi-ai";
@@ -21054,7 +21303,7 @@ function allowedAgentDefinitionsFromEnv() {
21054
21303
  function managedAgentEnvironmentError() {
21055
21304
  const e = process.env;
21056
21305
  if (!e.PI_HERDSMAN_MAILBOX) return "PI_HERDSMAN_MAILBOX missing";
21057
- if (!isAbsolute4(e.PI_HERDSMAN_MAILBOX))
21306
+ if (!isAbsolute5(e.PI_HERDSMAN_MAILBOX))
21058
21307
  return "PI_HERDSMAN_MAILBOX is not absolute";
21059
21308
  if (!validId(e.PI_HERDSMAN_RUN_ID)) return "PI_HERDSMAN_RUN_ID invalid";
21060
21309
  if (!validId(e.PI_HERDSMAN_OWNER_SESSION_ID))
@@ -21433,14 +21682,14 @@ import {
21433
21682
  SessionManager as SessionManager2
21434
21683
  } from "@earendil-works/pi-coding-agent";
21435
21684
  import { readFileSync as readFileSync13, statSync as statSync7, unlinkSync as unlinkSync12 } from "node:fs";
21436
- import { basename as basename9, dirname as dirname8, resolve as resolve7 } from "node:path";
21685
+ import { basename as basename9, dirname as dirname9, resolve as resolve7 } from "node:path";
21437
21686
  import { setTimeout as delay2 } from "node:timers/promises";
21438
21687
  import { fileURLToPath as fileURLToPath3 } from "node:url";
21439
21688
 
21440
21689
  // package.json
21441
21690
  var package_default = {
21442
21691
  name: "pi-herdsman",
21443
- version: "0.33.0",
21692
+ version: "0.34.0",
21444
21693
  type: "module",
21445
21694
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
21446
21695
  license: "Apache-2.0",
@@ -21603,8 +21852,8 @@ import { getSelectListTheme } from "@earendil-works/pi-coding-agent";
21603
21852
  import { visibleWidth as visibleWidth2 } from "@earendil-works/pi-tui";
21604
21853
  import { contentText as contentText4, getSupportedThinkingLevels } from "@earendil-works/pi-ai";
21605
21854
  import { createHash as createHash12, randomUUID as randomUUID14 } from "node:crypto";
21606
- import { realpathSync as realpathSync5, statSync as statSync6, unlinkSync as unlinkSync11 } from "node:fs";
21607
- import { isAbsolute as isAbsolute5, resolve as resolve6 } from "node:path";
21855
+ import { lstatSync as lstatSync6, realpathSync as realpathSync5, statSync as statSync6, unlinkSync as unlinkSync11 } from "node:fs";
21856
+ import { dirname as dirname8, isAbsolute as isAbsolute6, join as join12, resolve as resolve6 } from "node:path";
21608
21857
 
21609
21858
  // extension/peer-transport.ts
21610
21859
  init_lock();
@@ -22164,6 +22413,7 @@ function queuePeerReply(c, replyId, text, evidence = { attachments: [] }) {
22164
22413
  }
22165
22414
 
22166
22415
  // extension/lead-runtime.ts
22416
+ init_storage();
22167
22417
  var LEAD_INSTANCE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
22168
22418
  function createLeadRuntimeState() {
22169
22419
  return {
@@ -23098,7 +23348,19 @@ Active work or pending results may be discarded.`
23098
23348
  workspaceId,
23099
23349
  host.controller.sessionSignal()
23100
23350
  );
23101
- host.presentStopSummary(result.summary);
23351
+ let persisted = 0;
23352
+ try {
23353
+ persisted = await host.persistStopClosures(
23354
+ ctx,
23355
+ result.closures ?? []
23356
+ );
23357
+ } catch {
23358
+ }
23359
+ const unavailable = (result.closures?.length ?? 0) - persisted;
23360
+ host.presentStopSummary(
23361
+ (result.closures?.length ?? 0) > 0 ? `${result.summary}
23362
+ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s"}; unavailable for ${unavailable}. Agents without saved proof may not be continuable.` : result.summary
23363
+ );
23102
23364
  } finally {
23103
23365
  release();
23104
23366
  }
@@ -23180,6 +23442,12 @@ Active work or pending results may be discarded.`
23180
23442
  description: `Global ${config.autoActivateManager ? "on" : "off"} \xB7 ${projectDescription("autoActivateManager")}`,
23181
23443
  help: "Attempt Manager mode automatically on eligible future session starts. Changing this does not alter the current role."
23182
23444
  },
23445
+ {
23446
+ value: "manager-git-bootstrap-confirmation",
23447
+ label: "Skip Manager Git setup confirmation",
23448
+ description: `Global ${config.managerGitBootstrapWithoutConfirmation ? "on" : "off"}`,
23449
+ help: "Automatically initialize a non-Git workspace when Manager is started explicitly. Off by default."
23450
+ },
23183
23451
  {
23184
23452
  value: "context-retirement",
23185
23453
  label: "Context retirement",
@@ -23222,12 +23490,12 @@ Active work or pending results may be discarded.`
23222
23490
  config.defaultLeadExecution
23223
23491
  );
23224
23492
  if (mode) host.updateConfig("defaultLeadExecution", mode);
23225
- } else if (selected === "context-retirement" || selected === "auto-activate-manager") {
23226
- const key = selected === "context-retirement" ? "contextRetirement" : "autoActivateManager";
23493
+ } else if (selected === "context-retirement" || selected === "auto-activate-manager" || selected === "manager-git-bootstrap-confirmation") {
23494
+ const key = selected === "context-retirement" ? "contextRetirement" : selected === "auto-activate-manager" ? "autoActivateManager" : "managerGitBootstrapWithoutConfirmation";
23227
23495
  const enabled = !host.readConfig()[key];
23228
23496
  host.updateConfig(key, enabled);
23229
23497
  ctx.ui.notify(
23230
- `Global ${key === "contextRetirement" ? "context retirement" : "Manager auto-start"}: ${enabled ? "on" : "off"}`
23498
+ `Global ${key === "contextRetirement" ? "context retirement" : key === "autoActivateManager" ? "Manager auto-start" : "Manager Git setup confirmation skip"}: ${enabled ? "on" : "off"}`
23231
23499
  );
23232
23500
  } else if (selected === "manager-merge") {
23233
23501
  const enabled = !host.readConfig().managerMergeEnabled;
@@ -24297,7 +24565,15 @@ function registerLeadRuntime(pi, options2) {
24297
24565
  const controller = createAgentController(pi, {
24298
24566
  ...options2.controllerServices,
24299
24567
  scope: { kind: "root" },
24300
- projectEvidence: async (ctx) => {
24568
+ persistClosedDescendants: async (ctx, closures, selected) => {
24569
+ const persisted = await projectRuntime.persistNestedStopClosures(ctx, [
24570
+ ...closures,
24571
+ { state: selected, definition: "" }
24572
+ ]);
24573
+ return persisted === closures.length ? [] : ["Some closed descendants lack safely persisted continuation proof"];
24574
+ },
24575
+ projectEvidence: async (ctx, signal) => {
24576
+ const operationSignal = signal ?? ctx.signal;
24301
24577
  if (activeLeadRole(options2.leadRuntime) !== "lead" || !leadExecution?.managed)
24302
24578
  return void 0;
24303
24579
  const assignment = await currentProjectAssignment(ctx);
@@ -24305,18 +24581,30 @@ function registerLeadRuntime(pi, options2) {
24305
24581
  throw new Error(
24306
24582
  "Managed project execution requires a current exact assignment"
24307
24583
  );
24308
- const migrated = migrateProjectAssignmentEvidence(
24309
- options2.coordinationHost.supervisionRuntime(),
24310
- assignment.repoKey,
24311
- assignment.branch,
24312
- assignment.id
24584
+ const needsMigration = assignment.requiredEvidence?.some(
24585
+ (evidence) => !("result" in evidence) && !evidence.ref
24313
24586
  );
24587
+ const migrated = needsMigration ? await migrateProjectAssignmentEvidenceAfter(
24588
+ options2.coordinationHost.supervisionRuntime(),
24589
+ assignment,
24590
+ operationSignal
24591
+ ) : assignment;
24314
24592
  if (!migrated || migrated.id !== assignment.id)
24315
24593
  throw new Error(
24316
24594
  "Managed project execution requires a current exact assignment"
24317
24595
  );
24318
24596
  return {
24319
24597
  assignment: migrated,
24598
+ publishIfCurrent: (operation) => withProjectAssignmentAuthorityWait(
24599
+ () => operation(
24600
+ readProjectAssignment(
24601
+ options2.coordinationHost.supervisionRuntime(),
24602
+ assignment.repoKey,
24603
+ assignment.branch
24604
+ )
24605
+ ),
24606
+ operationSignal
24607
+ ),
24320
24608
  revalidate: (operation) => roleTransitions.withProjectAssignmentLock(
24321
24609
  assignment.repoKey,
24322
24610
  assignment.branch,
@@ -24328,7 +24616,7 @@ function registerLeadRuntime(pi, options2) {
24328
24616
  );
24329
24617
  await operation();
24330
24618
  },
24331
- ctx.signal
24619
+ operationSignal
24332
24620
  )
24333
24621
  };
24334
24622
  },
@@ -24524,6 +24812,9 @@ function registerLeadRuntime(pi, options2) {
24524
24812
  const projectHost = options2.projectHost;
24525
24813
  const projectServices = {
24526
24814
  ...projectHost,
24815
+ retireProjectAssignment: options2.roleTransitionHost.retireProjectAssignment,
24816
+ removeProjectMessagesForAssignment: options2.roleTransitionHost.removeProjectMessagesForAssignment,
24817
+ appendDurableError: options2.herdRunServices.appendDurableError,
24527
24818
  writeProjectAssignment: writeProjectAssignment2,
24528
24819
  liveAgent,
24529
24820
  liveLead,
@@ -24583,6 +24874,7 @@ function registerLeadRuntime(pi, options2) {
24583
24874
  });
24584
24875
  const commandRuntime = createLeadCommandRuntime({
24585
24876
  ...options2.commandHost,
24877
+ persistStopClosures: (ctx, closures) => projectRuntime.persistStopClosures(ctx, closures),
24586
24878
  getRemovalPreauthorization: (ctx) => projectRuntime.getRemovalPreauthorization(ctx),
24587
24879
  setRemovalPreauthorization: (enabled, ctx) => projectRuntime.setRemovalPreauthorization(enabled, ctx),
24588
24880
  collectOwnedSessionUsage: (ctx) => {
@@ -24609,6 +24901,7 @@ function registerLeadRuntime(pi, options2) {
24609
24901
  stopProjectLead: (...args) => projectRuntime.stop(...args),
24610
24902
  activateProjectLead: (...args) => projectRuntime.activateProjectLead(...args),
24611
24903
  removeWorktree: (...args) => projectRuntime.removeWorktree(...args),
24904
+ forgetLegacyProjectAssignment: (...args) => projectRuntime.forgetLegacyProjectAssignment(...args),
24612
24905
  inspectRequiredEvidence: (branch, ctx2) => projectRuntime.inspectRequiredEvidence(branch, ctx2),
24613
24906
  removeRequiredEvidence: (branch, id, assignment, ctx2) => projectRuntime.removeRequiredEvidence(branch, id, assignment, ctx2),
24614
24907
  selectMenu: options2.commandHost.selectMenu
@@ -25120,6 +25413,7 @@ function registerLeadRuntime(pi, options2) {
25120
25413
  remoteChiefAgent,
25121
25414
  liveLead,
25122
25415
  setLeadExecutionMode,
25416
+ sessionKindForPrompt: (ctx) => sessionKind?.sessionId === ctx.sessionManager.getSessionId() ? sessionKind.kind : void 0,
25123
25417
  leadExecutionPresentation: () => sessionKind?.kind === "managed" ? {
25124
25418
  managed: true,
25125
25419
  mode: leadExecution?.mode ?? "orchestrate",
@@ -25289,7 +25583,8 @@ function createLeadSupervisionRuntime(host) {
25289
25583
  ctx,
25290
25584
  [...new Set(agents.map((agent) => agent.workspaceId))],
25291
25585
  workspaceCwds,
25292
- ctx.signal
25586
+ ctx.signal,
25587
+ inventory.workspaces
25293
25588
  );
25294
25589
  const diagnostics = live.some(
25295
25590
  (agent) => (agent?.agent === "pi" || agent?.agent_session?.agent === "pi") && !host.isPiAgent(agent)
@@ -26040,6 +26335,7 @@ function createLeadSupervisionRuntime(host) {
26040
26335
  { value: "stop", label: "Stop Lead" }
26041
26336
  ] : [],
26042
26337
  { value: "remove", label: "Remove worktree\u2026" },
26338
+ ...host.activeRole() === "manager" && selection.status === "paused" ? [{ value: "forget", label: "Forget orphaned assignment\u2026" }] : [],
26043
26339
  ...host.activeRole() === "manager" ? [{ value: "required-evidence", label: "Retained evidence" }] : []
26044
26340
  ];
26045
26341
  const action = await uiActions.selectMenu(ctx, selection.branch, actions);
@@ -26068,6 +26364,16 @@ function createLeadSupervisionRuntime(host) {
26068
26364
  result.content[0]?.text ?? "Removal finished.",
26069
26365
  result.details.ok ? "info" : result.details.cancelled ? "info" : "warning"
26070
26366
  );
26367
+ } else if (action === "forget") {
26368
+ const result = await uiActions.forgetLegacyProjectAssignment(
26369
+ selection.branch,
26370
+ ctx,
26371
+ ctx.signal
26372
+ );
26373
+ ctx.ui.notify(
26374
+ result.content[0]?.text ?? `Forget of ${selection.branch} finished.`,
26375
+ result.details.ok || result.details.cancelled ? "info" : "warning"
26376
+ );
26071
26377
  } else if (action === "required-evidence") {
26072
26378
  const assignment = await uiActions.inspectRequiredEvidence(
26073
26379
  selection.branch,
@@ -26808,6 +27114,139 @@ function restoreHerdRunReportId(entries, sessionId, entryName) {
26808
27114
  return reportId;
26809
27115
  }
26810
27116
  function createLeadProjectRuntime(host) {
27117
+ const stopClosureEntry = "pi-herdsman-agent-closed-assignment";
27118
+ const stopClosureProof = (branch, ownerSessionId, closed) => {
27119
+ return acceptedCloseProof(branch, ownerSessionId, closed);
27120
+ };
27121
+ const persistActiveStopClosures = async (ctx, closures) => {
27122
+ let persisted = 0;
27123
+ const owner = ctx.sessionManager.getSessionId();
27124
+ for (const closed of closures) {
27125
+ if (closed.state.ownerSessionId !== owner) continue;
27126
+ const proof = stopClosureProof(
27127
+ ctx.sessionManager.getBranch(),
27128
+ owner,
27129
+ closed
27130
+ );
27131
+ if (proof) {
27132
+ await host.pi.appendEntry(stopClosureEntry, { version: 1, proof });
27133
+ const entries = ctx.sessionManager.getEntries();
27134
+ const branch = ctx.sessionManager.getBranch();
27135
+ const saved = (entry) => entry?.type === "custom" && entry.customType === stopClosureEntry && entry.data?.version === 1 && JSON.stringify(entry.data.proof) === JSON.stringify(proof);
27136
+ if (entries.filter(saved).length === 1 && branch.filter(saved).length === 1 && stopClosureProof(branch, owner, closed) && JSON.stringify(stopClosureProof(branch, owner, closed)) === JSON.stringify(proof))
27137
+ persisted++;
27138
+ }
27139
+ }
27140
+ return persisted;
27141
+ };
27142
+ const persistNestedStopClosures = async (ctx, closures) => {
27143
+ let persisted = 0;
27144
+ const root2 = ctx.sessionManager.getSessionId();
27145
+ const owners = new Map(
27146
+ closures.flatMap(
27147
+ ({ state }) => state.piSessionId && state.piSessionFile ? [[state.piSessionId, state.piSessionFile]] : []
27148
+ )
27149
+ );
27150
+ for (const closed of closures) {
27151
+ const owner = closed.state.ownerSessionId;
27152
+ const path = owners.get(owner);
27153
+ if (owner === root2 || !path) continue;
27154
+ let release;
27155
+ try {
27156
+ const canonical = realpathSync5(path);
27157
+ release = claimSessionActivationLock(canonical);
27158
+ if (!await stoppedClosureOwner(ctx, owner, root2, closures, ctx.signal))
27159
+ continue;
27160
+ const manager = host.SessionManager.open(canonical);
27161
+ if (manager.getSessionId() !== owner || !manager.getSessionFile() || !host.sameObservedSessionPath(manager.getSessionFile(), canonical))
27162
+ continue;
27163
+ const proof = stopClosureProof(manager.getBranch(), owner, closed);
27164
+ if (!proof) continue;
27165
+ manager.appendCustomEntry(stopClosureEntry, { version: 1, proof });
27166
+ if (manager.getEntries().filter(
27167
+ (entry) => entry?.type === "custom" && entry.customType === stopClosureEntry && entry.data?.version === 1 && JSON.stringify(entry.data.proof) === JSON.stringify(proof)
27168
+ ).length === 1 && manager.getBranch().some(
27169
+ (entry) => entry?.type === "custom" && entry.customType === stopClosureEntry && JSON.stringify(entry.data?.proof) === JSON.stringify(proof)
27170
+ ) && await stoppedClosureOwner(ctx, owner, root2, closures, ctx.signal))
27171
+ persisted++;
27172
+ } catch {
27173
+ } finally {
27174
+ release?.();
27175
+ }
27176
+ }
27177
+ return persisted;
27178
+ };
27179
+ const stoppedClosureOwner = async (ctx, owner, leadSessionId, closures, signal) => {
27180
+ if (owner === leadSessionId)
27181
+ return (await host.liveLead(ctx, leadSessionId)).length === 0;
27182
+ const parent = closures.find(({ state }) => state.piSessionId === owner);
27183
+ if (!parent) return false;
27184
+ const snapshot = await host.herdrSessionSnapshot(host.pi, ctx, signal);
27185
+ if (!Array.isArray(snapshot?.agents)) return false;
27186
+ return !snapshot.agents.some(
27187
+ (agent) => host.herdrSessionId(agent) === owner
27188
+ );
27189
+ };
27190
+ const persistForeignStopClosures = async (ctx, target, ownerSessionId, closures, signal) => {
27191
+ if (!closures.length) return 0;
27192
+ const ownerFiles = /* @__PURE__ */ new Map();
27193
+ const leadPath = host.supervisedSessionFile(target, ownerSessionId);
27194
+ if (leadPath) ownerFiles.set(ownerSessionId, leadPath);
27195
+ for (const closed of closures)
27196
+ if (closed.state.piSessionId && closed.state.piSessionFile)
27197
+ ownerFiles.set(closed.state.piSessionId, closed.state.piSessionFile);
27198
+ let persisted = 0;
27199
+ for (const closed of closures) {
27200
+ const owner = closed.state.ownerSessionId;
27201
+ const ownerFile = ownerFiles.get(owner);
27202
+ if (!ownerFile) continue;
27203
+ let release;
27204
+ try {
27205
+ const canonical = realpathSync5(ownerFile);
27206
+ release = claimSessionActivationLock(canonical);
27207
+ if (!await stoppedClosureOwner(
27208
+ ctx,
27209
+ owner,
27210
+ ownerSessionId,
27211
+ closures,
27212
+ signal
27213
+ ))
27214
+ continue;
27215
+ const manager = host.SessionManager.open(canonical);
27216
+ if (manager.getSessionId() !== owner || !manager.getSessionFile() || !host.sameObservedSessionPath(manager.getSessionFile(), canonical))
27217
+ continue;
27218
+ const proof = stopClosureProof(manager.getBranch(), owner, closed);
27219
+ if (!proof) continue;
27220
+ if (!await stoppedClosureOwner(
27221
+ ctx,
27222
+ owner,
27223
+ ownerSessionId,
27224
+ closures,
27225
+ signal
27226
+ ))
27227
+ continue;
27228
+ manager.appendCustomEntry(stopClosureEntry, { version: 1, proof });
27229
+ const entries = manager.getEntries();
27230
+ const branch = manager.getBranch();
27231
+ if (entries.filter(
27232
+ (entry) => entry?.type === "custom" && entry.customType === stopClosureEntry && entry.data?.version === 1 && JSON.stringify(entry.data.proof) === JSON.stringify(proof)
27233
+ ).length === 1 && branch.some(
27234
+ (entry) => entry?.type === "custom" && entry.customType === stopClosureEntry && entry.data?.version === 1 && JSON.stringify(entry.data.proof) === JSON.stringify(proof)
27235
+ ) && await stoppedClosureOwner(
27236
+ ctx,
27237
+ owner,
27238
+ ownerSessionId,
27239
+ closures,
27240
+ signal
27241
+ ))
27242
+ persisted++;
27243
+ } catch {
27244
+ } finally {
27245
+ release?.();
27246
+ }
27247
+ }
27248
+ return persisted;
27249
+ };
26811
27250
  const stopExecution = async (session, target, ctx, signal) => {
26812
27251
  const release = claimDelegationLock(target.workspace_id, session);
26813
27252
  try {
@@ -26822,6 +27261,14 @@ function createLeadProjectRuntime(host) {
26822
27261
  await host.stopProjectLeadPane(ctx, target, session, signal);
26823
27262
  if ((await host.liveLead(ctx, session)).length)
26824
27263
  throw new Error("Lead remains live after stop; work was preserved");
27264
+ const persisted = await persistForeignStopClosures(
27265
+ ctx,
27266
+ target,
27267
+ session,
27268
+ result.closures ?? [],
27269
+ signal
27270
+ );
27271
+ return { result, persisted };
26825
27272
  } finally {
26826
27273
  release();
26827
27274
  }
@@ -26857,12 +27304,12 @@ function createLeadProjectRuntime(host) {
26857
27304
  );
26858
27305
  if (live.length !== 1)
26859
27306
  throw new Error("Exact live Lead was not found or is ambiguous");
26860
- await stopExecution(session, live[0], ctx, signal);
27307
+ const stopped = await stopExecution(session, live[0], ctx, signal);
26861
27308
  return {
26862
27309
  content: [
26863
27310
  {
26864
27311
  type: "text",
26865
- text: `Lead ${session} stopped; project work preserved.`
27312
+ text: `Lead ${session} stopped; project work preserved.${stopped.persisted ? ` Continuation proof saved for ${stopped.persisted} Agent${stopped.persisted === 1 ? "" : "s"}.` : " Continuation proof could not be safely preserved; stopped Agents may not be continuable."}`
26866
27313
  }
26867
27314
  ],
26868
27315
  details: {
@@ -27175,9 +27622,10 @@ function createLeadProjectRuntime(host) {
27175
27622
  `Checkout: ${candidate.checkoutPath}`,
27176
27623
  "",
27177
27624
  "Removes this checkout and Herdr workspace.",
27178
- "Running managed execution may be stopped.",
27179
- "Preserves the Git branch and Pi conversation.",
27180
- "Retires the assignment after verified removal.",
27625
+ "Removing this worktree automatically stops its running Managed Lead and owned Agents first.",
27626
+ "If a later removal step fails, they are not automatically restarted.",
27627
+ "The Git branch and Pi conversation are preserved.",
27628
+ "The project assignment is retired only after verified checkout removal.",
27181
27629
  "",
27182
27630
  "Type remove to confirm."
27183
27631
  ].join("\n"),
@@ -27441,6 +27889,228 @@ function createLeadProjectRuntime(host) {
27441
27889
  resolvePendingRemoval(selected, ctx);
27442
27890
  return true;
27443
27891
  };
27892
+ const forgetLegacyProjectAssignment = async (branch, ctx, signal) => {
27893
+ const operationSignal = signal ?? ctx.signal;
27894
+ const initialManager = await host.currentManager(ctx);
27895
+ const lease = host.managerLease();
27896
+ if (host.activeRole() !== "manager" || !initialManager || !lease || host.leadRuntime.roleSuspended || !host.sameManagerDescriptor(initialManager, lease.descriptor))
27897
+ throw new Error(
27898
+ "Only the active, lease-verified Manager can forget an assignment"
27899
+ );
27900
+ const before = host.readProjectAssignment(
27901
+ host.supervisionRuntime(),
27902
+ initialManager.repoKey,
27903
+ branch
27904
+ );
27905
+ if (!before) throw new Error("No project assignment exists on this branch");
27906
+ const initialTopology = await host.runHerdr(
27907
+ host.pi,
27908
+ ctx,
27909
+ ["worktree", "list", "--workspace", initialManager.workspaceId],
27910
+ { signal: operationSignal }
27911
+ );
27912
+ if (initialTopology?.source?.repo_key !== initialManager.repoKey || initialTopology?.source?.source_workspace_id !== initialManager.workspaceId || typeof initialTopology?.source?.source_checkout_path !== "string")
27913
+ throw new Error("Herdr worktree topology is unavailable or inconsistent");
27914
+ await host.reconcileProjectAssignments(
27915
+ ctx,
27916
+ initialManager.repoKey,
27917
+ initialManager.workspaceId,
27918
+ initialTopology.source.source_checkout_path,
27919
+ false,
27920
+ branch,
27921
+ false,
27922
+ before.id
27923
+ );
27924
+ const afterReconciliation = host.readProjectAssignment(
27925
+ host.supervisionRuntime(),
27926
+ initialManager.repoKey,
27927
+ branch
27928
+ );
27929
+ if (!afterReconciliation)
27930
+ return {
27931
+ content: [
27932
+ {
27933
+ type: "text",
27934
+ text: `Automatically retired verified absent assignment ${branch}; no manual release was needed.`
27935
+ }
27936
+ ],
27937
+ details: { ok: true, branch, automatic: true }
27938
+ };
27939
+ if (afterReconciliation.id !== before.id)
27940
+ throw new Error("Project assignment changed during reconciliation");
27941
+ const verify = async (expectedId2) => {
27942
+ const manager = await host.currentManager(ctx);
27943
+ if (host.activeRole() !== "manager" || host.leadRuntime.roleSuspended || !manager || !host.sameManagerDescriptor(manager, initialManager) || !host.managerLease() || !host.sameManagerDescriptor(
27944
+ host.managerLease().descriptor,
27945
+ initialManager
27946
+ ))
27947
+ throw new Error(
27948
+ "Manager authority changed; assignment was not retired"
27949
+ );
27950
+ const group = await host.worktreeGroupScope(
27951
+ host.pi,
27952
+ ctx,
27953
+ manager.workspaceId,
27954
+ operationSignal
27955
+ );
27956
+ if (group.repoKey !== manager.repoKey || group.primaryWorkspaceId !== manager.workspaceId)
27957
+ throw new Error("Manager worktree group is not authoritative");
27958
+ const topology = await host.runHerdr(
27959
+ host.pi,
27960
+ ctx,
27961
+ ["worktree", "list", "--workspace", manager.workspaceId],
27962
+ { signal: operationSignal }
27963
+ );
27964
+ if (topology?.source?.repo_key !== manager.repoKey || topology?.source?.source_workspace_id !== manager.workspaceId || typeof topology?.source?.source_checkout_path !== "string" || !Array.isArray(topology.worktrees) || topology.worktrees.some(
27965
+ (worktree) => typeof worktree?.path !== "string" || !worktree.path || worktree.branch !== void 0 && typeof worktree.branch !== "string"
27966
+ ))
27967
+ throw new Error(
27968
+ "Herdr worktree topology is unavailable or inconsistent"
27969
+ );
27970
+ const current = host.readProjectAssignment(
27971
+ host.supervisionRuntime(),
27972
+ manager.repoKey,
27973
+ branch
27974
+ );
27975
+ if (!current || current.id !== expectedId2 || current.branch !== branch)
27976
+ throw new Error("Project assignment changed; nothing was retired");
27977
+ if (current.checkoutPath)
27978
+ throw new Error(
27979
+ "Checkout provenance exists; automatic reconciliation owns this assignment"
27980
+ );
27981
+ if (current.piSessionFile) {
27982
+ try {
27983
+ const session = host.SessionManager.open(current.piSessionFile);
27984
+ if (session.getSessionId() !== current.id)
27985
+ throw new Error("Assignment session identity conflicts");
27986
+ throw new Error("Checkout provenance exists; assignment preserved");
27987
+ } catch (error2) {
27988
+ if (error2 instanceof Error && /Checkout provenance|identity conflicts/u.test(error2.message))
27989
+ throw error2;
27990
+ throw new Error(
27991
+ "Assignment session provenance is unavailable or conflicting"
27992
+ );
27993
+ }
27994
+ }
27995
+ const [git, common, root2] = await Promise.all([
27996
+ host.pi.exec("git", ["worktree", "list", "--porcelain", "-z"], {
27997
+ cwd: topology.source.source_checkout_path,
27998
+ signal: operationSignal,
27999
+ timeout: 1e4
28000
+ }),
28001
+ host.pi.exec(
28002
+ "git",
28003
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
28004
+ {
28005
+ cwd: topology.source.source_checkout_path,
28006
+ signal: operationSignal,
28007
+ timeout: 1e4
28008
+ }
28009
+ ),
28010
+ host.pi.exec("git", ["rev-parse", "--show-toplevel"], {
28011
+ cwd: topology.source.source_checkout_path,
28012
+ signal: operationSignal,
28013
+ timeout: 1e4
28014
+ })
28015
+ ]);
28016
+ const inventory = parseGitWorktreeInventory(String(git.stdout ?? ""));
28017
+ if (git.code !== 0 || git.killed || git.stderr?.trim() || !inventory || common.code !== 0 || common.killed || common.stderr?.trim() || root2.code !== 0 || root2.killed || root2.stderr?.trim() || realpathSync5(String(common.stdout ?? "").trim()) !== realpathSync5(manager.repoKey) || realpathSync5(String(root2.stdout ?? "").trim()) !== realpathSync5(topology.source.source_checkout_path) || !inventory.some(
28018
+ (worktree) => resolve6(worktree.path) === resolve6(topology.source.source_checkout_path)
28019
+ ))
28020
+ throw new Error(
28021
+ "Git worktree inventory is unavailable or inconsistent"
28022
+ );
28023
+ if (inventory.some((worktree) => worktree.branch === branch) || topology.worktrees.some((worktree) => worktree?.branch === branch))
28024
+ throw new Error(
28025
+ "A checkout still uses this branch; assignment preserved"
28026
+ );
28027
+ const [leads, snapshot] = await Promise.all([
28028
+ host.liveLead(ctx, current.id),
28029
+ host.herdrSessionSnapshot(host.pi, ctx, operationSignal)
28030
+ ]);
28031
+ const agentStates = host.scanAgentStates();
28032
+ if (agentStates.issues.length)
28033
+ throw new Error(
28034
+ "Agent ownership inventory is incomplete; assignment preserved"
28035
+ );
28036
+ if (leads.length || snapshot.agents.some(
28037
+ (agent) => host.herdrSessionId(agent) === current.id
28038
+ ) || agentStates.states.some(
28039
+ ({ state }) => state.ownerSessionId === current.id || state.piSessionId === current.id || state.projectAssignmentId === current.id
28040
+ ))
28041
+ throw new Error(
28042
+ "Live or potentially active execution is known; assignment preserved"
28043
+ );
28044
+ return { manager, current };
28045
+ };
28046
+ const assignments = host.listProjectAssignments(host.supervisionRuntime(), initialManager.repoKey).filter((assignment) => assignment.branch === branch);
28047
+ if (assignments.length !== 1)
28048
+ throw new Error(
28049
+ "Branch does not identify exactly one current assignment"
28050
+ );
28051
+ const expectedId = assignments[0].id;
28052
+ await verify(expectedId);
28053
+ if (!ctx.hasUI)
28054
+ throw new Error(
28055
+ "Legacy assignment release requires interactive confirmation"
28056
+ );
28057
+ const answer = await ctx.ui.input(
28058
+ `Release Manager authority for ${branch}?
28059
+
28060
+ This removes the durable project assignment and retires its pending project messages. Git checkouts, branches, Pi conversations, processes, and Agent ownership are not changed.
28061
+
28062
+ No live target execution or matching branch checkout was found, but unobserved execution cannot be ruled out.
28063
+
28064
+ Type forget ${branch} to confirm.`,
28065
+ void 0,
28066
+ { signal: operationSignal }
28067
+ );
28068
+ if (answer !== `forget ${branch}`)
28069
+ return {
28070
+ content: [
28071
+ {
28072
+ type: "text",
28073
+ text: `Forget of ${branch} cancelled; assignment unchanged.`
28074
+ }
28075
+ ],
28076
+ details: { ok: false, cancelled: true, branch }
28077
+ };
28078
+ return host.withProjectWorkLock(
28079
+ `${initialManager.repoKey}\0${branch}`,
28080
+ () => host.withProjectAssignmentLock(
28081
+ initialManager.repoKey,
28082
+ branch,
28083
+ async () => {
28084
+ const { current } = await verify(expectedId);
28085
+ if (!host.retireProjectAssignment(host.supervisionRuntime(), current))
28086
+ throw new Error("Assignment changed; nothing was retired");
28087
+ try {
28088
+ host.removeProjectMessagesForAssignment(
28089
+ host.supervisionRuntime(),
28090
+ current
28091
+ );
28092
+ } catch (error2) {
28093
+ host.appendDurableError(
28094
+ host.pi,
28095
+ ctx,
28096
+ "pi_herdsman_state_error",
28097
+ error2
28098
+ );
28099
+ }
28100
+ return {
28101
+ content: [
28102
+ {
28103
+ type: "text",
28104
+ text: `Released Manager authority for ${branch}; Git and Pi history preserved.`
28105
+ }
28106
+ ],
28107
+ details: { ok: true, branch, assignment_id: expectedId }
28108
+ };
28109
+ },
28110
+ operationSignal
28111
+ )
28112
+ );
28113
+ };
27444
28114
  const setRemovalPreauthorization = async (enabled, ctx) => {
27445
28115
  const manager = await host.currentManager(ctx);
27446
28116
  if (host.activeRole() !== "manager" || !manager || !ctx.hasUI)
@@ -28187,18 +28857,29 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28187
28857
  branch
28188
28858
  );
28189
28859
  const existing = operation.action === "resume" ? migrateProjectAssignmentEvidence(runtime, manager.repoKey, branch) : readProjectAssignment2(runtime, manager.repoKey, branch);
28190
- if (existing && existing.repoKey !== manager.repoKey)
28860
+ if (operation.action === "delegate" && existing) {
28861
+ await host.reconcileProjectAssignments(
28862
+ ctx,
28863
+ manager.repoKey,
28864
+ primaryWorkspaceId,
28865
+ typeof topology.source.source_checkout_path === "string" ? topology.source.source_checkout_path : "",
28866
+ true,
28867
+ branch
28868
+ );
28869
+ }
28870
+ const currentAssignment = operation.action === "delegate" && existing ? readProjectAssignment2(runtime, manager.repoKey, branch) : existing;
28871
+ if (currentAssignment && currentAssignment.repoKey !== manager.repoKey)
28191
28872
  throw new Error("Project assignment belongs to another repository");
28192
- if (operation.action === "delegate" && existing)
28873
+ if (operation.action === "delegate" && currentAssignment)
28193
28874
  throw new Error(
28194
28875
  `Work already exists on ${branch}; resume it with resume_project.`
28195
28876
  );
28196
- if (operation.action === "resume" && !existing)
28877
+ if (operation.action === "resume" && !currentAssignment)
28197
28878
  throw new Error(
28198
28879
  `No existing work was found on ${branch}; start it with delegate_project and a task.`
28199
28880
  );
28200
- const presentationTask = operation.action === "resume" ? projectTaskSummary(existing.text) : void 0;
28201
- const id = operation.action === "resume" ? existing.id : operation.id;
28881
+ const presentationTask = operation.action === "resume" ? projectTaskSummary(currentAssignment.text) : void 0;
28882
+ const id = operation.action === "resume" ? currentAssignment.id : operation.id;
28202
28883
  const branchWorktrees = topology.worktrees.filter(
28203
28884
  (worktree) => worktree?.branch === branch
28204
28885
  );
@@ -28208,7 +28889,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28208
28889
  );
28209
28890
  if (branchWorktrees.length > 1)
28210
28891
  throw new Error(`Multiple Herdr worktrees match branch ${branch}`);
28211
- const live = operation.action === "resume" ? await liveAgent(ctx, existing.id) : [];
28892
+ const live = operation.action === "resume" ? await liveAgent(ctx, currentAssignment.id) : [];
28212
28893
  if (live.length > 1)
28213
28894
  throw new Error(`Assignment ${id} has ambiguous live Lead identity`);
28214
28895
  if (live.length === 1) {
@@ -28233,7 +28914,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28233
28914
  operationName,
28234
28915
  `Lead ${id}`
28235
28916
  );
28236
- await bindLeadSessionFile(existing, live[0]);
28917
+ await bindLeadSessionFile(currentAssignment, live[0]);
28237
28918
  writeChiefMessage2({
28238
28919
  version: 2,
28239
28920
  build: HERDSMAN_BUILD2,
@@ -28243,7 +28924,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28243
28924
  fromSessionId: manager.piSessionId,
28244
28925
  toSessionId: id,
28245
28926
  leadSessionId: id,
28246
- branch: existing.branch,
28927
+ branch: currentAssignment.branch,
28247
28928
  text: "Project assignment ready.",
28248
28929
  createdAt: Date.now()
28249
28930
  });
@@ -28291,7 +28972,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28291
28972
  if (branchWorktrees[0]?.open_workspace_id)
28292
28973
  await assertUnoccupied(branchWorktrees[0].open_workspace_id);
28293
28974
  let assignment;
28294
- if (operation.action === "resume") assignment = existing;
28975
+ if (operation.action === "resume") assignment = currentAssignment;
28295
28976
  else {
28296
28977
  const limits = await messageLimits3(ctx);
28297
28978
  const suppliedFiles = resolveMessageFiles2(
@@ -28432,10 +29113,15 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28432
29113
  timeout: 1e4
28433
29114
  })
28434
29115
  ]);
28435
- if (common.code !== 0 || common.killed || common.stderr?.trim() || branchResult.code !== 0 || branchResult.killed || branchResult.stderr?.trim() || !isAbsolute5(String(common.stdout ?? "").trim()) || realpathSync5(String(common.stdout).trim()) !== realpathSync5(manager.repoKey) || String(branchResult.stdout ?? "").trim() !== assignment.branch)
29116
+ if (common.code !== 0 || common.killed || common.stderr?.trim() || branchResult.code !== 0 || branchResult.killed || branchResult.stderr?.trim() || !isAbsolute6(String(common.stdout ?? "").trim()) || realpathSync5(String(common.stdout).trim()) !== realpathSync5(manager.repoKey) || String(branchResult.stdout ?? "").trim() !== assignment.branch)
28436
29117
  throw new Error(
28437
29118
  "Herdr checkout does not match the assigned repository and branch"
28438
29119
  );
29120
+ if (!isAbsolute6(cwd) || workspaceId === primaryWorkspaceId || realpathSync5(cwd) === realpathSync5(topology.source.source_checkout_path) || matchingWorktrees.length === 1 && realpathSync5(cwd) !== realpathSync5(matchingWorktrees[0].path))
29121
+ throw new Error(
29122
+ "Herdr checkout is not the verified linked project worktree"
29123
+ );
29124
+ assignment = { ...assignment, checkoutPath: realpathSync5(cwd) };
28439
29125
  const fresh = await currentManager(ctx);
28440
29126
  if (!fresh || !sameManagerDescriptor2(fresh, manager))
28441
29127
  throw new Error(
@@ -29286,7 +29972,29 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29286
29972
  ...resultBindings.length ? { resultBindings } : {},
29287
29973
  ...currentEvidenceIds.length ? { currentEvidenceIds } : { currentEvidenceIds: void 0 }
29288
29974
  };
29289
- host.writeProjectAssignment(runtime, written);
29975
+ if (runtime?.assignments)
29976
+ await writeProjectAssignmentAfter(
29977
+ runtime,
29978
+ current,
29979
+ written,
29980
+ ctx.signal,
29981
+ () => {
29982
+ const currentLease2 = host.managerLease();
29983
+ const liveManager = readManagerDescriptor(
29984
+ runtime,
29985
+ managerAuthority.workspaceId
29986
+ );
29987
+ if (host.activeRole() !== "manager" || host.leadRuntime.roleSuspended || !currentLease2 || !host.sameManagerDescriptor(
29988
+ currentLease2.descriptor,
29989
+ managerAuthority
29990
+ ) || currentLease2.descriptor.leaseId !== managerLeaseId || !liveManager || !host.sameManagerDescriptor(liveManager, managerAuthority) || liveManager.repoKey !== assignment.repoKey || liveManager.workspaceId !== managerAuthority.workspaceId)
29991
+ throw new Error(
29992
+ "Manager authority changed before required evidence was updated"
29993
+ );
29994
+ },
29995
+ host.onProjectAssignmentAuthorityWaitOccupied
29996
+ );
29997
+ else host.writeProjectAssignment(runtime, written);
29290
29998
  return written;
29291
29999
  },
29292
30000
  ctx.signal
@@ -29348,6 +30056,10 @@ ${(updated.requiredEvidence ?? []).map((entry) => `- ${entry.id}: ${entry.name}`
29348
30056
  };
29349
30057
  return {
29350
30058
  stopExecution,
30059
+ persistStopClosures: async (ctx, closures) => {
30060
+ return await persistActiveStopClosures(ctx, closures) + await persistNestedStopClosures(ctx, closures);
30061
+ },
30062
+ persistNestedStopClosures,
29351
30063
  stop,
29352
30064
  activateProjectLead,
29353
30065
  removeWorktree,
@@ -29358,6 +30070,7 @@ ${(updated.requiredEvidence ?? []).map((entry) => `- ${entry.id}: ${entry.name}`
29358
30070
  cancelPendingRemoval,
29359
30071
  setRemovalPreauthorization,
29360
30072
  getRemovalPreauthorization,
30073
+ forgetLegacyProjectAssignment,
29361
30074
  executeStaff,
29362
30075
  updateAssignmentEvidence,
29363
30076
  inspectRequiredEvidence,
@@ -30695,9 +31408,11 @@ ${receivedRefs.join("\n")}` : ""}`,
30695
31408
  (item) => (item.role ?? "manager") === activeRole() && matchesReturnRecipient(item, sender) && item.originSession === params.session
30696
31409
  ) : [];
30697
31410
  const target = remoteRoute ? void 0 : await livePeerLead(ctx, params.session);
30698
- if (!sender || (sender.role ?? "lead") !== activeRole() || (remoteRoute ? remoteRoute.role !== activeRole() || ambiguousRemoteSessions.has(params.session) : (!target || (target.role ?? "lead") !== activeRole()) && returnCorrespondences.length !== 1))
31411
+ const noAuthorizedLocalTarget = (!target || (target.role ?? "lead") !== activeRole()) && returnCorrespondences.length !== 1;
31412
+ const rejection = !sender ? "sender_unavailable" : (sender.role ?? "lead") !== activeRole() ? "sender_role_changed" : remoteRoute ? remoteRoute.role !== activeRole() ? "route_role_mismatch" : ambiguousRemoteSessions.has(params.session) ? "route_ambiguous" : void 0 : noAuthorizedLocalTarget ? ambiguousRemoteSessions.has(params.session) ? "route_ambiguous" : "no_authorized_target" : void 0;
31413
+ if (rejection)
30699
31414
  throw new Error(
30700
- "Peer target was not found or is no longer a live same-role peer"
31415
+ `Peer target was not found or is no longer a live same-role peer [${rejection}]`
30701
31416
  );
30702
31417
  const recordId = randomUUID14();
30703
31418
  const createdAt = Date.now();
@@ -32166,7 +32881,7 @@ function parseGitWorktreeInventory(output) {
32166
32881
  else if (/^prunable(?: .*)?$/.test(value2)) prunable = true;
32167
32882
  else if (!/^[^\s]+(?: .*)?$/.test(value2)) return void 0;
32168
32883
  }
32169
- if (!path || !isAbsolute5(path) || (bare ? !!branch || detached : !head || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(head) || !branch && !detached) || branch !== void 0 && !branch)
32884
+ if (!path || !isAbsolute6(path) || (bare ? !!branch || detached : !head || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(head) || !branch && !detached) || branch !== void 0 && !branch)
32170
32885
  return void 0;
32171
32886
  worktrees.push({
32172
32887
  path,
@@ -32520,7 +33235,7 @@ function createLeadRoleTransitions(state, host) {
32520
33235
  return true;
32521
33236
  };
32522
33237
  const gitWorktreeInventory = async (ctx, repoKey, primaryWorkspaceId, sourceCheckoutPath) => {
32523
- if (!isAbsolute5(sourceCheckoutPath)) return void 0;
33238
+ if (!isAbsolute6(sourceCheckoutPath)) return void 0;
32524
33239
  try {
32525
33240
  const scope = await host.worktreeGroupScope(
32526
33241
  ctx,
@@ -32537,7 +33252,7 @@ function createLeadRoleTransitions(state, host) {
32537
33252
  if (rootResult.code !== 0 || rootResult.killed || rootResult.stderr?.trim())
32538
33253
  return void 0;
32539
33254
  const commonDir = String(rootResult.stdout ?? "").trim();
32540
- if (!commonDir || !isAbsolute5(commonDir)) return void 0;
33255
+ if (!commonDir || !isAbsolute6(commonDir)) return void 0;
32541
33256
  const result = await host.pi.exec(
32542
33257
  "git",
32543
33258
  ["worktree", "list", "--porcelain", "-z"],
@@ -32568,7 +33283,7 @@ function createLeadRoleTransitions(state, host) {
32568
33283
  sourceCheckoutPath
32569
33284
  );
32570
33285
  if (!initialInventory) return;
32571
- const knownCheckoutPath = (assignment) => {
33286
+ const knownSessionCheckoutPath = (assignment) => {
32572
33287
  if (!assignment.piSessionFile) return void 0;
32573
33288
  try {
32574
33289
  const session = host.SessionManager.open(assignment.piSessionFile);
@@ -32578,11 +33293,18 @@ function createLeadRoleTransitions(state, host) {
32578
33293
  return void 0;
32579
33294
  }
32580
33295
  };
32581
- const checkoutMaySurvive = (assignment, inventory) => {
32582
- const cwd = knownCheckoutPath(assignment);
32583
- if (cwd)
32584
- return inventory.some(
32585
- (worktree) => resolve6(worktree.path) === cwd && gitPathStatus(worktree.path) !== "absent"
33296
+ const checkoutProvenance = (assignment) => {
33297
+ const recorded = assignment.checkoutPath ? resolve6(assignment.checkoutPath) : void 0;
33298
+ const session = knownSessionCheckoutPath(assignment);
33299
+ return {
33300
+ path: recorded ?? session,
33301
+ conflicting: !!recorded && !!session && recorded !== session
33302
+ };
33303
+ };
33304
+ const checkoutMaySurvive = (assignment, inventory, checkoutPath = checkoutProvenance(assignment).path) => {
33305
+ if (checkoutPath)
33306
+ return gitPathStatus(checkoutPath) !== "absent" || inventory.some(
33307
+ (worktree) => resolve6(worktree.path) === checkoutPath && (worktree.locked || !worktree.prunable || gitPathStatus(worktree.path) !== "absent")
32586
33308
  );
32587
33309
  return inventory.some(
32588
33310
  (worktree) => resolve6(worktree.path) !== resolve6(sourceCheckoutPath) && gitPathStatus(worktree.path) !== "absent"
@@ -32591,7 +33313,18 @@ function createLeadRoleTransitions(state, host) {
32591
33313
  for (const observed of assignments) {
32592
33314
  if (onlyBranch && observed.branch !== onlyBranch || expectedAssignmentId && observed.id !== expectedAssignmentId)
32593
33315
  continue;
32594
- if (checkoutMaySurvive(observed, initialInventory)) continue;
33316
+ const observedProvenance = checkoutProvenance(observed);
33317
+ if (observedProvenance.conflicting) {
33318
+ host.appendDurableError(
33319
+ host.pi,
33320
+ ctx,
33321
+ "pi_herdsman_state_error",
33322
+ new Error("Project assignment has conflicting checkout provenance")
33323
+ );
33324
+ continue;
33325
+ }
33326
+ if (checkoutMaySurvive(observed, initialInventory, observedProvenance.path))
33327
+ continue;
32595
33328
  const initialMatches = initialInventory.filter(
32596
33329
  (worktree) => worktree.branch === observed.branch
32597
33330
  );
@@ -32621,7 +33354,9 @@ function createLeadRoleTransitions(state, host) {
32621
33354
  sourceCheckoutPath
32622
33355
  );
32623
33356
  if (!inventory) return;
32624
- if (checkoutMaySurvive(current, inventory)) return;
33357
+ const currentProvenance = checkoutProvenance(current);
33358
+ if (currentProvenance.conflicting || checkoutMaySurvive(current, inventory, currentProvenance.path))
33359
+ return;
32625
33360
  const matches = inventory.filter(
32626
33361
  (worktree) => worktree.branch === observed.branch
32627
33362
  );
@@ -32985,15 +33720,15 @@ function createLeadRoleTransitions(state, host) {
32985
33720
  };
32986
33721
  const activateManager = async (ctx) => {
32987
33722
  if (state.controllerRole === "manager" && !state.roleSuspended) {
32988
- const sessionId = ctx.sessionManager.getSessionId();
33723
+ const sessionId2 = ctx.sessionManager.getSessionId();
32989
33724
  const lease2 = state.managerLease;
32990
33725
  await ctx.waitForIdle();
32991
- if (ctx.sessionManager.getSessionId() !== sessionId || state.controllerRole !== "manager" || state.roleSuspended || !lease2 || state.managerLease !== lease2)
33726
+ if (ctx.sessionManager.getSessionId() !== sessionId2 || state.controllerRole !== "manager" || state.roleSuspended || !lease2 || state.managerLease !== lease2)
32992
33727
  throw new Error("Manager mode changed during profile refresh");
32993
33728
  const replacement = host.prepareSupervisoryProfile(ctx, "manager");
32994
33729
  const previous = host.currentSupervisoryProfile(ctx, "manager");
32995
33730
  const previousTools2 = host.pi.getActiveTools();
32996
- const stillCurrent = () => ctx.sessionManager.getSessionId() === sessionId && state.controllerRole === "manager" && !state.roleSuspended && state.managerLease === lease2;
33731
+ const stillCurrent = () => ctx.sessionManager.getSessionId() === sessionId2 && state.controllerRole === "manager" && !state.roleSuspended && state.managerLease === lease2;
32997
33732
  try {
32998
33733
  host.commitSupervisoryProfile(replacement);
32999
33734
  host.reconcileRoleTools();
@@ -33015,9 +33750,230 @@ function createLeadRoleTransitions(state, host) {
33015
33750
  const { paneId, tabId, workspaceId } = host.identity;
33016
33751
  if (!paneId || !tabId || !workspaceId)
33017
33752
  throw new Error("/manager requires a Herdr Lead identity");
33018
- const scope = await host.worktreeGroupScope(ctx, workspaceId);
33753
+ const sessionId = ctx.sessionManager.getSessionId();
33754
+ let scope;
33755
+ try {
33756
+ scope = await host.worktreeGroupScope(ctx, workspaceId);
33757
+ } catch (error2) {
33758
+ if (!(error2 instanceof OperationError) || error2.detail.details?.herdrCode !== "not_git_worktree")
33759
+ throw error2;
33760
+ const skipConfirmation = readConfig().managerGitBootstrapWithoutConfirmation;
33761
+ if (!ctx.hasUI && !skipConfirmation)
33762
+ throw new Error(
33763
+ "/manager requires interactive confirmation to initialize Git"
33764
+ );
33765
+ const target = realpathSync5(resolve6(ctx.cwd));
33766
+ const targetStat = statSync6(target, { bigint: true });
33767
+ if (!targetStat.isDirectory() || targetStat.dev === 0n || targetStat.ino === 0n)
33768
+ throw new Error("Manager Git target is not a directory");
33769
+ const sameDirectory = (leftPath, rightPath) => {
33770
+ try {
33771
+ const left = statSync6(leftPath, { bigint: true });
33772
+ const right = statSync6(rightPath, { bigint: true });
33773
+ return left.isDirectory() && right.isDirectory() && left.dev !== 0n && right.dev !== 0n && left.ino !== 0n && right.ino !== 0n && left.dev === right.dev && left.ino === right.ino;
33774
+ } catch {
33775
+ return false;
33776
+ }
33777
+ };
33778
+ const verifyHerdrTarget = async () => {
33779
+ const pane = (await host.runHerdr(host.pi, ctx, ["pane", "get", paneId], {
33780
+ signal: ctx.signal
33781
+ }))?.pane;
33782
+ const workspace2 = (await host.runHerdr(host.pi, ctx, ["workspace", "get", workspaceId], {
33783
+ signal: ctx.signal
33784
+ }))?.workspace;
33785
+ const paneCwd = pane?.cwd;
33786
+ if (pane?.pane_id !== paneId || pane?.tab_id !== tabId || pane?.workspace_id !== workspaceId || workspace2?.workspace_id !== workspaceId || typeof paneCwd !== "string" || !isAbsolute6(paneCwd) || !sameDirectory(paneCwd, target))
33787
+ throw new Error(
33788
+ "Manager activation cancelled because Herdr workspace identity does not match the approved directory"
33789
+ );
33790
+ };
33791
+ await verifyHerdrTarget();
33792
+ if ([
33793
+ "GIT_DIR",
33794
+ "GIT_WORK_TREE",
33795
+ "GIT_INDEX_FILE",
33796
+ "GIT_COMMON_DIR",
33797
+ "GIT_OBJECT_DIRECTORY",
33798
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
33799
+ "GIT_CEILING_DIRECTORIES",
33800
+ "GIT_PREFIX"
33801
+ ].some((key) => process.env[key]))
33802
+ throw new Error(
33803
+ "Cannot initialize Git while repository-redirection environment variables are set"
33804
+ );
33805
+ if (!skipConfirmation && !await ctx.ui.confirm(
33806
+ "Initialize Git repository?",
33807
+ `Initialize ${target} with an empty initial commit, then start Manager mode? Existing files will not be committed.`
33808
+ ))
33809
+ throw new Error("Manager activation cancelled.");
33810
+ await verifyHerdrTarget();
33811
+ if (ctx.sessionManager.getSessionId() !== sessionId || host.identity.workspaceId !== workspaceId || host.identity.paneId !== paneId || host.identity.tabId !== tabId || !sameDirectory(resolve6(ctx.cwd), target) || (() => {
33812
+ const current = statSync6(target, { bigint: true });
33813
+ return current.dev !== targetStat.dev || current.ino !== targetStat.ino;
33814
+ })())
33815
+ throw new Error(
33816
+ "Manager activation cancelled because the workspace changed"
33817
+ );
33818
+ const runGit = async (args) => {
33819
+ const result = await host.pi.exec("git", args, {
33820
+ cwd: target,
33821
+ signal: ctx.signal,
33822
+ timeout: 3e4
33823
+ });
33824
+ if (result.code !== 0 || result.killed)
33825
+ throw new Error(
33826
+ `Git ${args[0]} failed: ${result.stderr?.trim() || "process unsuccessful"}`
33827
+ );
33828
+ return result.stdout.trim();
33829
+ };
33830
+ const probeRoot = async () => {
33831
+ const result = await host.pi.exec(
33832
+ "git",
33833
+ ["rev-parse", "--show-toplevel"],
33834
+ { cwd: target, signal: ctx.signal, timeout: 3e4 }
33835
+ );
33836
+ if (result.code === 0 && !result.killed)
33837
+ return String(result.stdout ?? "").trim();
33838
+ if (result.killed) throw new Error("Git repository inspection failed");
33839
+ return void 0;
33840
+ };
33841
+ const bootstrapLock = host.acquireProcessLock(
33842
+ join12(
33843
+ herdsmanTempRoot(),
33844
+ "locks",
33845
+ `manager-bootstrap-${createHash12("sha256").update(target).digest("hex")}`
33846
+ ),
33847
+ { name: "Manager Git bootstrap" }
33848
+ );
33849
+ try {
33850
+ const hasRepositoryMetadata = () => {
33851
+ let directory2 = target;
33852
+ while (true) {
33853
+ try {
33854
+ lstatSync6(resolve6(directory2, ".git"));
33855
+ return true;
33856
+ } catch (error3) {
33857
+ if (error3.code !== "ENOENT")
33858
+ throw error3;
33859
+ }
33860
+ const parent = dirname8(directory2);
33861
+ if (parent === directory2) return false;
33862
+ directory2 = parent;
33863
+ }
33864
+ };
33865
+ let root2 = await probeRoot();
33866
+ if (!root2) {
33867
+ const bare = await host.pi.exec(
33868
+ "git",
33869
+ ["rev-parse", "--is-bare-repository"],
33870
+ { cwd: target, signal: ctx.signal, timeout: 3e4 }
33871
+ );
33872
+ if (bare.killed)
33873
+ throw new Error("Git repository type inspection failed");
33874
+ const bareStatus = String(bare.stdout ?? "").trim();
33875
+ if (bare.code === 0 && bareStatus === "true")
33876
+ throw new Error(
33877
+ "Cannot initialize Manager Git inside an existing bare repository"
33878
+ );
33879
+ if (bare.code === 0 && bareStatus !== "false")
33880
+ throw new Error("Git repository type inspection failed");
33881
+ if (hasRepositoryMetadata())
33882
+ throw new Error(
33883
+ "Refusing to initialize: existing Git metadata is invalid or conflicting"
33884
+ );
33885
+ await runGit(["init", "--initial-branch=main"]);
33886
+ root2 = await probeRoot();
33887
+ }
33888
+ if (root2 && !sameDirectory(root2, target))
33889
+ throw new Error(
33890
+ "Refusing to initialize inside an enclosing Git repository"
33891
+ );
33892
+ if (!root2)
33893
+ throw new Error(
33894
+ "Git initialization could not verify its working-tree root"
33895
+ );
33896
+ const actualRoot = await runGit(["rev-parse", "--show-toplevel"]);
33897
+ if (!sameDirectory(actualRoot, target))
33898
+ throw new Error(
33899
+ "Git repository root does not match the approved directory"
33900
+ );
33901
+ const inspectHead = async () => {
33902
+ const result = await host.pi.exec(
33903
+ "git",
33904
+ ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
33905
+ { cwd: target, signal: ctx.signal, timeout: 3e4 }
33906
+ );
33907
+ if (result.code === 0 && !result.killed)
33908
+ return String(result.stdout ?? "").trim();
33909
+ if (result.killed || result.code !== 1)
33910
+ throw new Error(
33911
+ `Git HEAD inspection failed: ${String(result.stderr ?? "").trim() || "process unsuccessful"}`
33912
+ );
33913
+ return void 0;
33914
+ };
33915
+ let head = await inspectHead();
33916
+ let createdInitialCommit = false;
33917
+ if (!head) {
33918
+ const staged = await host.pi.exec(
33919
+ "git",
33920
+ ["diff", "--cached", "--quiet"],
33921
+ { cwd: target, signal: ctx.signal, timeout: 3e4 }
33922
+ );
33923
+ const index = await runGit(["ls-files", "--stage"]);
33924
+ if (staged.killed || staged.code !== 0 && staged.code !== 1 || index)
33925
+ throw new Error(
33926
+ "Refusing to complete an unborn repository with an existing or unreadable index"
33927
+ );
33928
+ await runGit([
33929
+ "commit",
33930
+ "--only",
33931
+ "--allow-empty",
33932
+ "-m",
33933
+ "chore: initialize repository"
33934
+ ]);
33935
+ createdInitialCommit = true;
33936
+ head = await inspectHead();
33937
+ }
33938
+ if (!head) throw new Error("Git did not create an initial commit");
33939
+ if (createdInitialCommit) {
33940
+ const parents = await runGit([
33941
+ "rev-list",
33942
+ "--parents",
33943
+ "-n",
33944
+ "1",
33945
+ "HEAD"
33946
+ ]);
33947
+ if (parents.trim().split(/\s+/).length !== 1)
33948
+ throw new Error("Initial Git commit is not a root commit");
33949
+ const tree = await runGit(["rev-parse", "HEAD^{tree}"]);
33950
+ if (tree !== await runGit(["mktree"]))
33951
+ throw new Error("Initial Git commit is not empty");
33952
+ }
33953
+ await verifyHerdrTarget();
33954
+ const gitCommonDir = await runGit([
33955
+ "rev-parse",
33956
+ "--path-format=absolute",
33957
+ "--git-common-dir"
33958
+ ]);
33959
+ scope = await host.worktreeGroupScope(ctx, workspaceId);
33960
+ if (!scope || scope.primaryWorkspaceId !== workspaceId || !sameDirectory(scope.repoKey, gitCommonDir))
33961
+ throw new Error(
33962
+ "Manager activation could not verify the initialized repository in Herdr"
33963
+ );
33964
+ } finally {
33965
+ bootstrapLock.release();
33966
+ }
33967
+ }
33968
+ if (!scope)
33969
+ throw new Error("Manager workspace could not be verified in Herdr");
33019
33970
  if (scope.primaryWorkspaceId !== workspaceId)
33020
33971
  throw new Error("/manager is available only in the primary workspace");
33972
+ if (ctx.sessionManager.getSessionId() !== sessionId)
33973
+ throw new Error(
33974
+ "Manager activation cancelled because the session changed"
33975
+ );
33976
+ host.activationGuard(sessionId, "Manager");
33021
33977
  const profile = host.prepareSupervisoryProfile(ctx, "manager");
33022
33978
  host.captureInheritedTools?.();
33023
33979
  const previousTools = host.getLeadTools() ?? host.normalizeLeadTools(host.pi.getActiveTools());
@@ -33025,7 +33981,7 @@ function createLeadRoleTransitions(state, host) {
33025
33981
  try {
33026
33982
  lease = host.claimManagerLease({
33027
33983
  build: host.build,
33028
- piSessionId: ctx.sessionManager.getSessionId(),
33984
+ piSessionId: sessionId,
33029
33985
  piSessionFile: ctx.sessionManager.getSessionFile(),
33030
33986
  paneId,
33031
33987
  tabId,
@@ -33543,28 +34499,26 @@ var LEAD_COORDINATION_TOOLS = [
33543
34499
  ...PEER_TOOLS
33544
34500
  ];
33545
34501
  var CHIEF_TOOLS = STAFF_TOOLS;
33546
- var LEAD_SUPERVISOR_PEER_GUIDANCE = "Use message_supervisor for material nonblocking coordination with your direct supervisor. Use list_peers/message_peer for peer coordination.";
33547
- var LEAD_ROLE_CHARTER = `## Lead role
33548
- You are the Lead for this Pi session.
33549
- ${LEAD_SCOPE_DESCRIPTION}
34502
+ var LEAD_SUPERVISOR_PEER_GUIDANCE = "Use message_supervisor for material coordination or evidence your direct supervisor needs. Use list_peers/message_peer for concrete, task-relevant coordination with eligible peers. Avoid unsolicited routine progress updates, unnecessary acknowledgments, and redundant result announcements. Continue work or report normally when no coordination is needed.";
34503
+ var COMMON_LEAD_GUIDANCE = `${LEAD_SCOPE_DESCRIPTION}
33550
34504
  ${LEAD_SUPERVISOR_PEER_GUIDANCE}
34505
+ ${FILE_HANDOFF_GUIDANCE}`;
34506
+ var ORDINARY_LEAD_CHARTER = `## Lead role
34507
+ You are an ordinary Lead for this Pi session.
34508
+ ${COMMON_LEAD_GUIDANCE}
34509
+ Your Agent assignments and file handoffs are recipient-specific. Peer messages coordinate work but do not independently transfer execution ownership.`;
34510
+ var MANAGED_LEAD_GUIDANCE = `Managed Lead identity is permanent for this exact Pi session. Only a current exact ProjectAssignment permits fresh managed project execution; unavailable or retired assignment state does not grant ordinary Lead execution authority. Exactly owned Agent recovery remains separate. Use native Pi /fork or /clone for independent ordinary continuation; this does not create a separate Git checkout or fresh process configuration.
33551
34511
  For a verified managed project assignment, required project evidence is automatically inherited by newly accepted descendant Agent assignments.
33552
- Ordinary Leads have no automatic required-evidence scope.
33553
34512
  A Lead's delegation task and ordinary files are recipient-specific; they do not create project-wide requirements.
33554
34513
  Only the Manager can designate continuing project requirements.
33555
- Send proposed continuing requirements and available supporting
33556
- evidence to the Manager for evaluation.
33557
- For assigned project work, include routine proposed requirements,
33558
- completion, and review readiness in your normal response;
33559
- Herdsman delivers it to the Manager automatically.
33560
- For assigned project work, use message_supervisor for timely
33561
- coordination or explicit evidence transfer, not for a separate
33562
- completion announcement.
33563
- For assigned project work, automatic result handoffs contain summary
33564
- text but no file attachments. When the Manager needs an actual artifact
33565
- for review, decision-making, or onward delegation, explicitly transfer
33566
- the relevant evidence through message_supervisor.files.
33567
- ${FILE_HANDOFF_GUIDANCE}`;
34514
+ Send proposed continuing requirements and available supporting evidence to the Manager for evaluation.
34515
+ For assigned project work, include routine proposed requirements, completion, and review readiness in your normal response; Herdsman delivers it to the Manager automatically.
34516
+ For assigned project work, use message_supervisor for timely coordination or explicit evidence transfer, not for a separate completion announcement.
34517
+ 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.`;
34518
+ var MANAGED_LEAD_CHARTER = `## Lead role
34519
+ You are a Managed Lead for this Pi session.
34520
+ ${COMMON_LEAD_GUIDANCE}
34521
+ ${MANAGED_LEAD_GUIDANCE}`;
33568
34522
  var SUPERVISION_EVENT_GUIDANCE = "Supervision is event-driven. Do not poll staff tools, send repeated messages, or sleep solely to wait for Lead progress. When no independent work remains, end the turn; incoming Lead updates resume coordination.";
33569
34523
  var MANAGER_ROLE_CONTRACT = `## Manager role
33570
34524
  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. Unless this repository has been explicitly preauthorized by a human, the tool registers a pending approval and returns promptly. Direct the user to /manager remove to review it, then continue unrelated coordination. Do not repeat or poll a pending request; its result is not evidence of removal.
@@ -33670,67 +34624,94 @@ function expectedSession2(id, path) {
33670
34624
  function isPiAgent(agent) {
33671
34625
  return sessionIdentity(agent?.agent_session) !== void 0;
33672
34626
  }
33673
- async function workspacePresentationProvenance(pi, ctx, workspaceIds, workspaceCwds, signal) {
33674
- const entries = await Promise.all(
33675
- workspaceIds.map(async (workspaceId) => {
33676
- let workspace2;
33677
- try {
33678
- workspace2 = (await runHerdr(pi, ctx, ["workspace", "get", workspaceId], {
33679
- signal
33680
- }))?.workspace;
33681
- } catch {
33682
- return [
33683
- workspaceId,
33684
- projectWorkspaceProvenance(
34627
+ async function workspacePresentationProvenance(pi, ctx, workspaceIds, workspaceCwds, signal, snapshotWorkspaces) {
34628
+ const workspaces = /* @__PURE__ */ new Map();
34629
+ if (snapshotWorkspaces) {
34630
+ for (const workspace2 of snapshotWorkspaces)
34631
+ if (typeof workspace2?.workspace_id === "string")
34632
+ workspaces.set(workspace2.workspace_id, workspace2);
34633
+ } else {
34634
+ const records = await Promise.all(
34635
+ workspaceIds.map(async (workspaceId) => {
34636
+ try {
34637
+ return [
33685
34638
  workspaceId,
33686
- void 0,
33687
- void 0,
33688
- workspaceCwds.get(workspaceId)
33689
- )
33690
- ];
33691
- }
33692
- if (!hasWorkspaceWorktree(workspace2))
33693
- return [
34639
+ (await runHerdr(pi, ctx, ["workspace", "get", workspaceId], {
34640
+ signal
34641
+ }))?.workspace
34642
+ ];
34643
+ } catch {
34644
+ return [workspaceId, void 0];
34645
+ }
34646
+ })
34647
+ );
34648
+ for (const [workspaceId, workspace2] of records)
34649
+ if (workspace2) workspaces.set(workspaceId, workspace2);
34650
+ }
34651
+ const sources = /* @__PURE__ */ new Map();
34652
+ for (const workspaceId of new Set(workspaceIds)) {
34653
+ const workspace2 = workspaces.get(workspaceId);
34654
+ if (!workspace2) continue;
34655
+ const repoKey = workspace2?.worktree?.repo_key;
34656
+ const repoRoot = workspace2?.worktree?.repo_root;
34657
+ if (typeof repoKey !== "string" || !repoKey || typeof repoRoot !== "string" || !repoRoot)
34658
+ continue;
34659
+ const key = `${repoKey}\0${repoRoot}`;
34660
+ if (!sources.has(key)) sources.set(key, { workspaceId, repoKey, repoRoot });
34661
+ }
34662
+ const topologyByRepo = /* @__PURE__ */ new Map();
34663
+ for (const [key, source] of sources) {
34664
+ if (signal?.aborted) break;
34665
+ try {
34666
+ const topology = await runHerdr(
34667
+ pi,
34668
+ ctx,
34669
+ ["worktree", "list", "--workspace", source.workspaceId],
34670
+ { signal }
34671
+ );
34672
+ if (topology?.source?.repo_key === source.repoKey && topology?.source?.repo_root === source.repoRoot && Array.isArray(topology?.worktrees))
34673
+ topologyByRepo.set(key, topology);
34674
+ } catch {
34675
+ }
34676
+ }
34677
+ const topologyByWorkspace = /* @__PURE__ */ new Map();
34678
+ if (!snapshotWorkspaces)
34679
+ for (const workspaceId of new Set(workspaceIds)) {
34680
+ const workspace2 = workspaces.get(workspaceId);
34681
+ const repoKey = workspace2?.worktree?.repo_key;
34682
+ const repoRoot = workspace2?.worktree?.repo_root;
34683
+ if (!hasWorkspaceWorktree(workspace2) || typeof repoKey === "string" && repoKey && typeof repoRoot === "string" && repoRoot)
34684
+ continue;
34685
+ try {
34686
+ topologyByWorkspace.set(
33694
34687
  workspaceId,
33695
- projectWorkspaceProvenance(
33696
- workspaceId,
33697
- workspace2,
33698
- void 0,
33699
- workspaceCwds.get(workspaceId)
34688
+ await runHerdr(
34689
+ pi,
34690
+ ctx,
34691
+ ["worktree", "list", "--workspace", workspaceId],
34692
+ { signal }
33700
34693
  )
33701
- ];
33702
- let worktreeInfo;
33703
- try {
33704
- worktreeInfo = await runHerdr(
33705
- pi,
33706
- ctx,
33707
- ["worktree", "list", "--workspace", workspaceId],
33708
- { signal }
33709
34694
  );
33710
34695
  } catch {
33711
- return [
33712
- workspaceId,
33713
- projectWorkspaceProvenance(
33714
- workspaceId,
33715
- workspace2,
33716
- void 0,
33717
- workspaceCwds.get(workspaceId),
33718
- true
33719
- )
33720
- ];
33721
34696
  }
34697
+ }
34698
+ return new Map(
34699
+ workspaceIds.map((workspaceId) => {
34700
+ const workspace2 = workspaces.get(workspaceId);
34701
+ const repoKey = workspace2?.worktree?.repo_key;
34702
+ const repoRoot = workspace2?.worktree?.repo_root;
34703
+ const key = typeof repoKey === "string" && typeof repoRoot === "string" ? `${repoKey}\0${repoRoot}` : void 0;
33722
34704
  return [
33723
34705
  workspaceId,
33724
34706
  projectWorkspaceProvenance(
33725
34707
  workspaceId,
33726
34708
  workspace2,
33727
- worktreeInfo,
34709
+ (key ? topologyByRepo.get(key) : void 0) ?? topologyByWorkspace.get(workspaceId),
33728
34710
  workspaceCwds.get(workspaceId)
33729
34711
  )
33730
34712
  ];
33731
34713
  })
33732
34714
  );
33733
- return new Map(entries);
33734
34715
  }
33735
34716
  function registerExtensionForTest(pi, lockHooks) {
33736
34717
  registerExtensionImpl(pi, lockHooks);
@@ -33871,6 +34852,7 @@ If needed, install the Pi integration once:
33871
34852
  }
33872
34853
  const controllerScope = processRole === "lead" ? { kind: "root" } : void 0;
33873
34854
  const controllerServices = {
34855
+ afterRequestPublishedForTest: lockHooks?.afterRequestPublished,
33874
34856
  extensionPath: HERDSMAN_EXTENSION_PATH,
33875
34857
  isContextRetired: (manager) => retiredManagedSession(manager),
33876
34858
  snapshotDependencies: {
@@ -34168,7 +35150,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
34168
35150
  const chiefSystemPrompt = (options2, body) => {
34169
35151
  const agentDir = resolve7(getAgentDir3());
34170
35152
  const globalInstructions = (options2?.contextFiles ?? []).filter(
34171
- ({ path, content }) => typeof path === "string" && typeof content === "string" && resolve7(dirname8(path)) === agentDir && content.length > 0
35153
+ ({ path, content }) => typeof path === "string" && typeof content === "string" && resolve7(dirname9(path)) === agentDir && content.length > 0
34172
35154
  ).map(({ content }) => content).join("\n\n");
34173
35155
  return [
34174
35156
  CHIEF_ROLE_CONTRACT,
@@ -34242,6 +35224,7 @@ ${globalInstructions}
34242
35224
  writeProjectMessage,
34243
35225
  afterProjectAssignmentLockAcquired: lockHooks?.afterAcquired,
34244
35226
  afterProjectAssignmentLockOccupied: lockHooks?.afterOccupied,
35227
+ onProjectAssignmentAuthorityWaitOccupied: lockHooks?.onAuthorityWaitOccupied,
34245
35228
  retireProjectAssignment,
34246
35229
  removeProjectMessagesForAssignment,
34247
35230
  recoverStaleProjectMessages,
@@ -34313,6 +35296,7 @@ ${globalInstructions}
34313
35296
  resolveMessageFiles,
34314
35297
  projectAssignmentBytes,
34315
35298
  writeProjectAssignment,
35299
+ onProjectAssignmentAuthorityWaitOccupied: lockHooks?.onAuthorityWaitOccupied,
34316
35300
  delay: delay2,
34317
35301
  startHerdrAgentInPane,
34318
35302
  sessionIdentity,
@@ -34351,9 +35335,15 @@ ${globalInstructions}
34351
35335
  if (leadRuntime.roleSuspended || role2 === "chief" && !isCurrentChief(ctx) || role2 === "manager" && !leadRuntime.managerLease)
34352
35336
  return `## Herdsman role
34353
35337
  No active Herdsman role is verified for this Pi session.`;
34354
- return role2 === "manager" ? `${MANAGER_ROLE_CONTRACT}
35338
+ if (role2 === "manager")
35339
+ return `${MANAGER_ROLE_CONTRACT}
34355
35340
 
34356
- ${leadRuntimes.supervisoryProfileBody(ctx, "manager")}` : LEAD_ROLE_CHARTER;
35341
+ ${leadRuntimes.supervisoryProfileBody(ctx, "manager")}`;
35342
+ const kind = leadRuntimes.sessionKindForPrompt(ctx);
35343
+ if (kind === "ordinary") return ORDINARY_LEAD_CHARTER;
35344
+ if (kind === "managed") return MANAGED_LEAD_CHARTER;
35345
+ return `## Herdsman role
35346
+ No active Herdsman role is verified for this Pi session.`;
34357
35347
  },
34358
35348
  supervisoryProfileBody: (ctx, role2) => leadRuntimes.supervisoryProfileBody(ctx, role2),
34359
35349
  currentChiefAllowedTools: (ctx) => leadRuntimes.currentChiefAllowedTools(ctx),
@@ -34602,22 +35592,24 @@ ${summary}`,
34602
35592
  });
34603
35593
  if (process.env.HERDR_PANE_ID)
34604
35594
  pi.registerCommand("manager", {
34605
- description: "Activate Manager mode, open its overview, or remove an assigned worktree",
35595
+ description: "Activate Manager mode, open its overview, remove a worktree, or forget a legacy assignment",
34606
35596
  getArgumentCompletions: (prefix) => {
34607
35597
  const input = prefix.trimStart();
34608
35598
  const [command, branchPrefix] = input.split(/\s+/u);
34609
35599
  if (!command)
34610
- return ["leave", "remove", "remove-preapproval"].map((value2) => ({
34611
- value: value2,
34612
- label: value2
34613
- }));
35600
+ return ["leave", "remove", "forget", "remove-preapproval"].map(
35601
+ (value2) => ({
35602
+ value: value2,
35603
+ label: value2
35604
+ })
35605
+ );
34614
35606
  if (command === "remove-preapproval")
34615
35607
  return input.trim().split(/\s+/u).length === 2 ? ["on", "off"].filter((value2) => value2.startsWith(branchPrefix ?? "")).map((value2) => ({
34616
35608
  value: `remove-preapproval ${value2}`,
34617
35609
  label: value2
34618
35610
  })) : null;
34619
- if (command !== "remove")
34620
- return input.includes(" ") ? null : ["leave", "remove", "remove-preapproval"].filter((value2) => value2.startsWith(command)).map((value2) => ({ value: value2, label: value2 }));
35611
+ if (command !== "remove" && command !== "forget")
35612
+ return input.includes(" ") ? null : ["leave", "remove", "forget", "remove-preapproval"].filter((value2) => value2.startsWith(command)).map((value2) => ({ value: value2, label: value2 }));
34621
35613
  if (input === "remove") return [];
34622
35614
  if (input.trim().split(/\s+/u).length > 2) return null;
34623
35615
  const lease = leadRuntime.managerLease;
@@ -34627,7 +35619,7 @@ ${summary}`,
34627
35619
  supervisionRuntime(),
34628
35620
  lease.descriptor.repoKey
34629
35621
  ).map(({ branch }) => branch).filter((branch) => branch.startsWith(branchPrefix ?? "")).map((branch) => ({
34630
- value: `remove ${branch}`,
35622
+ value: `${command} ${branch}`,
34631
35623
  label: branch
34632
35624
  }));
34633
35625
  } catch {
@@ -34727,6 +35719,21 @@ ${summary}`,
34727
35719
  );
34728
35720
  return;
34729
35721
  }
35722
+ if (args[0] === "forget") {
35723
+ if (args.length !== 2) {
35724
+ ctx.ui.notify("Usage: /manager forget <branch>", "error");
35725
+ return;
35726
+ }
35727
+ const result = await projectRuntime.forgetLegacyProjectAssignment(
35728
+ args[1],
35729
+ ctx
35730
+ );
35731
+ ctx.ui.notify(
35732
+ result.content[0]?.text ?? `Forget of ${args[1]} finished.`,
35733
+ result.details.ok || result.details.cancelled ? "info" : "warning"
35734
+ );
35735
+ return;
35736
+ }
34730
35737
  await leadCommandRuntime.runRoleCommand("manager", rawArgs, ctx);
34731
35738
  }
34732
35739
  });
@@ -34743,7 +35750,7 @@ ${summary}`,
34743
35750
  label: "message supervisor",
34744
35751
  exposure: "model-only",
34745
35752
  promptSnippet: "Send nonblocking material coordination to your direct supervisor",
34746
- description: "Send a nonblocking question, clarification, warning, risk, scope change, or other material coordination to your direct supervisor.",
35753
+ description: "Send a nonblocking question, clarification, warning, risk, decision, scope change, or evidence only when it is material or needed by your direct supervisor. Avoid unsolicited routine progress updates and duplicate result announcements.",
34747
35754
  executionMode: "sequential",
34748
35755
  parameters: supervisorMessageParameters,
34749
35756
  execute: (...args) => leadRuntimes.coordinationRuntime.supervisorMessage(...args),
@@ -34762,7 +35769,7 @@ ${summary}`,
34762
35769
  label: "message peer",
34763
35770
  exposure: "model-only",
34764
35771
  promptSnippet: "Discover same-role peers, including remote ordinary Leads, and reply through existing correspondences",
34765
- description: "Send to an eligible same-role Lead or Manager by exact session ID. Ordinary Leads and Managers may discover eligible same-role peers on reachable saved Herdr machines; remote Leads must be ordinary and unassigned. An existing return correspondence may allow a reply-only target without independent discovery or current availability. Use only the exact session from list_peers; optional name/workspace labels are advisory display context.",
35772
+ description: "Send task-relevant communication needed by another eligible coordinator, not routine broadcasts or gratuitous acknowledgments. Send to an eligible same-role Lead or Manager by exact session ID. Ordinary Leads and Managers may discover eligible same-role peers on reachable saved Herdr machines; remote Leads must be ordinary and unassigned. An existing return correspondence may allow a reply-only target without independent discovery or current availability. Use only the exact session from list_peers; optional name/workspace labels are advisory display context.",
34766
35773
  executionMode: "sequential",
34767
35774
  parameters: peerMessageParameters,
34768
35775
  execute: (...args) => leadRuntimes.coordinationRuntime.peerMessage(...args),
@@ -34877,7 +35884,7 @@ ${summary}`,
34877
35884
  ...staffTool,
34878
35885
  name: "resume_project",
34879
35886
  label: "resume project",
34880
- description: "Resume existing unresolved project work by its exact Git branch.",
35887
+ description: "Reuse an already-running Lead for the exact branch; otherwise resume its existing assignment without creating a duplicate.",
34881
35888
  parameters: staffBranchParameters,
34882
35889
  promptSnippet: void 0,
34883
35890
  execute: (id, p, signal, update, ctx) => staffTool.execute(
@@ -34894,7 +35901,7 @@ ${summary}`,
34894
35901
  ...staffTool,
34895
35902
  name: "remove_worktree",
34896
35903
  label: "remove worktree",
34897
- description: "Remove an explicitly requested assigned project's linked worktree. When project preauthorization is enabled, execute the guarded removal. Otherwise create an actionable human approval request and return promptly. Do not repeat or poll a pending request.",
35904
+ description: "Remove an explicitly requested assigned project's linked worktree. After authorization, automatically stop any running assigned Lead and its owned Agents before removal; no separate stop call is needed. The Git branch and Pi conversation are preserved. Pending human approval performs no cleanup. When project preauthorization is enabled, execute the guarded removal. Otherwise create an actionable human approval request and return promptly. Do not repeat or poll a pending request.",
34898
35905
  parameters: staffBranchParameters,
34899
35906
  promptSnippet: void 0,
34900
35907
  execute: (id, p, signal, update, ctx) => staffTool.execute(
@@ -34911,7 +35918,7 @@ ${summary}`,
34911
35918
  ...staffTool,
34912
35919
  name: "merge_project",
34913
35920
  label: "merge project",
34914
- description: "Integrate an assigned local branch into the verified primary branch using fast-forward-only Git. Supply the exact full source SHA accepted after validation. This may finalize and remove the source checkout when authorized.",
35921
+ description: "Integrate an assigned local branch into the verified primary branch using fast-forward-only Git. Supply the exact full source SHA accepted after validation. This may stop running managed execution before integration. If a later step fails after execution stops, it is not automatically restarted. Verified integration triggers guarded cleanup, but integration and cleanup can complete separately; do not treat integration alone as full finalization.",
34915
35922
  parameters: Type3.Object(
34916
35923
  {
34917
35924
  branch: Type3.String({
@@ -35082,7 +36089,7 @@ ${summary}`,
35082
36089
  listProjectMessageHeaders,
35083
36090
  readProjectMessage,
35084
36091
  listProjectMessages,
35085
- removeProjectMessage,
36092
+ removeProjectMessage: lockHooks?.removeProjectMessage ?? removeProjectMessage,
35086
36093
  readProjectAssignment,
35087
36094
  importResultBindings
35088
36095
  },
@@ -35253,6 +36260,7 @@ ${summary}`,
35253
36260
  }
35254
36261
  export {
35255
36262
  extension_default as default,
35256
- registerExtensionForTest
36263
+ registerExtensionForTest,
36264
+ workspacePresentationProvenance
35257
36265
  };
35258
36266
  //# sourceMappingURL=index.js.map