pi-herdsman 0.34.0 → 0.35.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
@@ -1139,6 +1139,7 @@ function validate(value2, kind) {
1139
1139
  "status",
1140
1140
  "text",
1141
1141
  "error",
1142
+ "resultBindings",
1142
1143
  "contextUsage",
1143
1144
  "completedAt"
1144
1145
  ];
@@ -1294,6 +1295,8 @@ function validate(value2, kind) {
1294
1295
  if (v.status !== "completed" && v.status !== "failed")
1295
1296
  throw new Error("Invalid result status");
1296
1297
  finite("completedAt");
1298
+ if (v.resultBindings !== void 0 && (!Array.isArray(v.resultBindings) || !v.resultBindings.every(isResultBinding) || new Set(v.resultBindings.map((binding) => binding.ref)).size !== v.resultBindings.length))
1299
+ throw new Error("Invalid or conflicting result bindings");
1297
1300
  if (v.status === "completed" && (typeof v.text !== "string" || !v.text.trim() || v.error !== void 0))
1298
1301
  throw new Error("Invalid completed result");
1299
1302
  if (v.status === "failed") {
@@ -1309,6 +1312,8 @@ function validate(value2, kind) {
1309
1312
  throw new Error("Invalid failed result");
1310
1313
  if (v.text !== void 0)
1311
1314
  throw new Error("Failed result cannot contain text");
1315
+ if (v.resultBindings !== void 0)
1316
+ throw new Error("Failed result cannot contain result bindings");
1312
1317
  }
1313
1318
  if (v.contextUsage !== void 0) {
1314
1319
  const usage = v.contextUsage;
@@ -2665,7 +2670,12 @@ function agentLaunchArgs(agent, options2) {
2665
2670
  }
2666
2671
  if (sharedPromptPath) args.push("--append-system-prompt", sharedPromptPath);
2667
2672
  const requiredTools = [
2668
- ...managedAgent ? agentDefinitionDelegationEnabled(agent) ? [...AGENT_COORDINATION_TOOLS, "ask_owner", "read_evidence"] : ["ask_owner", "read_evidence"] : [],
2673
+ ...managedAgent ? agentDefinitionDelegationEnabled(agent) ? [
2674
+ ...AGENT_COORDINATION_TOOLS,
2675
+ "ask_owner",
2676
+ "read_evidence",
2677
+ "attach_handoff"
2678
+ ] : ["ask_owner", "read_evidence", "attach_handoff"] : [],
2669
2679
  ...options2.requiredTools ?? []
2670
2680
  ].filter((tool, index, all) => all.indexOf(tool) === index);
2671
2681
  const policy = configuredToolPolicy(agent, requiredTools);
@@ -2803,10 +2813,11 @@ import {
2803
2813
  mkdirSync as mkdirSync5,
2804
2814
  openSync as openSync5,
2805
2815
  readSync as readSync2,
2806
- realpathSync as realpathSync2
2816
+ realpathSync as realpathSync2,
2817
+ statSync as statSync4
2807
2818
  } from "node:fs";
2808
2819
  import { createConnection } from "node:net";
2809
- import { join as join5, resolve as resolve3 } from "node:path";
2820
+ import { isAbsolute as isAbsolute2, join as join5, resolve as resolve3 } from "node:path";
2810
2821
  import { StringDecoder } from "node:string_decoder";
2811
2822
  import { setTimeout as sleep } from "node:timers/promises";
2812
2823
  function parseHerdrVersion(value2) {
@@ -3001,6 +3012,66 @@ async function runHerdr(pi, ctx, args, options2 = {}) {
3001
3012
  );
3002
3013
  return stdoutJson.result;
3003
3014
  }
3015
+ function sameDirectory(left, right) {
3016
+ try {
3017
+ const leftPath = realpathSync2(left);
3018
+ const rightPath = realpathSync2(right);
3019
+ const leftStat = statSync4(leftPath, { bigint: true });
3020
+ const rightStat = statSync4(rightPath, { bigint: true });
3021
+ if (!leftStat.isDirectory() || !rightStat.isDirectory()) return false;
3022
+ if (leftStat.dev !== 0n && rightStat.dev !== 0n && leftStat.ino !== 0n && rightStat.ino !== 0n)
3023
+ return leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
3024
+ return leftPath === rightPath;
3025
+ } catch {
3026
+ return false;
3027
+ }
3028
+ }
3029
+ async function localRepositoryScope(pi, ctx, workspaceId, signal) {
3030
+ const listed = await runHerdr(
3031
+ pi,
3032
+ ctx,
3033
+ ["worktree", "list", "--cwd", ctx.cwd],
3034
+ { signal }
3035
+ );
3036
+ const workspace2 = (await runHerdr(pi, ctx, ["workspace", "get", workspaceId], { signal }))?.workspace;
3037
+ const source = listed?.source;
3038
+ if (workspace2?.workspace_id !== workspaceId || typeof source?.repo_key !== "string" || !isAbsolute2(source.repo_key) || typeof source?.repo_name !== "string" || !source.repo_name || !Array.isArray(listed?.worktrees))
3039
+ throw new Error("Herdr local repository identity is unavailable");
3040
+ const gitPath = async (argument) => {
3041
+ const result = await pi.exec(
3042
+ "git",
3043
+ ["rev-parse", "--path-format=absolute", argument],
3044
+ {
3045
+ cwd: ctx.cwd,
3046
+ signal,
3047
+ timeout: 1e4
3048
+ }
3049
+ );
3050
+ const path = String(result.stdout ?? "").trim();
3051
+ if (result.code !== 0 || result.killed || result.stderr?.trim() || !isAbsolute2(path))
3052
+ throw new Error("Git local repository identity is unavailable");
3053
+ return realpathSync2(path);
3054
+ };
3055
+ const [checkoutPath, gitDir, commonDir] = await Promise.all([
3056
+ gitPath("--show-toplevel"),
3057
+ gitPath("--git-dir"),
3058
+ gitPath("--git-common-dir")
3059
+ ]);
3060
+ const isPrimary = sameDirectory(gitDir, commonDir);
3061
+ if (!sameDirectory(commonDir, source.repo_key))
3062
+ throw new Error("Herdr repository does not match the current checkout");
3063
+ const membership = workspace2.worktree;
3064
+ if (membership != null && (typeof membership.repo_key !== "string" || typeof membership.checkout_path !== "string" || typeof membership.is_linked_worktree !== "boolean" || !sameDirectory(membership.repo_key, commonDir) || !sameDirectory(membership.checkout_path, checkoutPath) || membership.is_linked_worktree !== !isPrimary))
3065
+ throw new Error(
3066
+ "Herdr workspace association does not match the current checkout"
3067
+ );
3068
+ return {
3069
+ repoKey: source.repo_key,
3070
+ repoName: source.repo_name,
3071
+ checkoutPath,
3072
+ isPrimary
3073
+ };
3074
+ }
3004
3075
  async function worktreeGroupScope(pi, ctx, workspaceId, signal, timeout) {
3005
3076
  const listed = await runHerdr(
3006
3077
  pi,
@@ -4842,7 +4913,7 @@ import {
4842
4913
  writeFileSync as writeFileSync3
4843
4914
  } from "node:fs";
4844
4915
  import { homedir as homedir3 } from "node:os";
4845
- import { basename as basename5, dirname as dirname5, isAbsolute as isAbsolute2, join as join6, relative, sep as sep2 } from "node:path";
4916
+ import { basename as basename5, dirname as dirname5, isAbsolute as isAbsolute3, join as join6, relative, sep as sep2 } from "node:path";
4846
4917
  function populateMenuFrame(container, theme, title, body, footer, help) {
4847
4918
  container.clear();
4848
4919
  container.addChild(new DynamicBorder((line) => theme.fg("border", line)));
@@ -5012,8 +5083,8 @@ function lifecycleMarker(state) {
5012
5083
  function compactModelToken(model) {
5013
5084
  return model?.split("/").at(-1) ?? "";
5014
5085
  }
5015
- function activityIndicator(state, frame) {
5016
- return state === "working" || state === "settling" || state === "starting" ? spinner[frame % spinner.length] : lifecycleMarker(state);
5086
+ function activityIndicator(state, frame, animate = true) {
5087
+ return animate && animates(state) ? spinner[frame % spinner.length] : lifecycleMarker(state);
5017
5088
  }
5018
5089
  function managedExecutionLabel(lifecycle) {
5019
5090
  return lifecycle === "retired" || lifecycle === "unavailable" ? `managed \xB7 ${lifecycle}` : "managed";
@@ -5029,11 +5100,15 @@ function buildStatusRows(agents, options2) {
5029
5100
  ...agent.paneId ? { paneId: agent.paneId } : {},
5030
5101
  ...agent.sessionId ? { sessionId: agent.sessionId } : {},
5031
5102
  tree,
5032
- indicator: activityIndicator(agent.state, options2.frame ?? 0),
5103
+ indicator: activityIndicator(
5104
+ agent.state,
5105
+ options2.frame ?? 0,
5106
+ options2.animate
5107
+ ),
5033
5108
  definition: agent.definition || "?",
5034
5109
  agentLabel: agent.label,
5035
5110
  state: lifecycleLabel(agent.state),
5036
- elapsed: formatElapsed(agent.startedAt, options2.now) ?? "",
5111
+ elapsed: options2.now === void 0 ? "" : formatElapsed(agent.startedAt, options2.now) ?? "",
5037
5112
  model: compactModelToken(agent.model),
5038
5113
  thinking: agent.thinking ?? "",
5039
5114
  context: Number.isInteger(agent.contextPercent) ? `${agent.contextPercent}%` : "",
@@ -5090,7 +5165,7 @@ function layoutWidth(columns, layout) {
5090
5165
  function renderIdentity(row, definitionWidth, identityWidth, theme) {
5091
5166
  const definition = padVisible(row.definition, definitionWidth);
5092
5167
  const raw = `${row.tree}${row.indicator} ${definition} ${row.agentLabel}`;
5093
- return themed(theme, "muted", `${row.tree}${row.indicator} `) + (theme?.bold?.(definition) ?? definition) + themed(theme, "muted", ` ${row.agentLabel}`) + " ".repeat(Math.max(0, identityWidth - visibleWidth(raw)));
5168
+ return themed(theme, "muted", row.tree) + themed(theme, STATE_COLOR[row.state] ?? "muted", `${row.indicator} `) + (theme?.bold?.(definition) ?? definition) + themed(theme, "muted", ` ${row.agentLabel}`) + " ".repeat(Math.max(0, identityWidth - visibleWidth(raw)));
5094
5169
  }
5095
5170
  function renderStatusLine(row, columns, layout, width, theme) {
5096
5171
  const { definitionWidth, widths } = columns;
@@ -5218,12 +5293,12 @@ function presentationReports(reports) {
5218
5293
  );
5219
5294
  }
5220
5295
  function classifySupervisedLead(lead) {
5221
- if (lead.runtimeState === "working") return "WORKING";
5296
+ if (lead.runtimeState === "working" || lead.runtimeState === "starting" || lead.runtimeState === "settling")
5297
+ return "ACTIVE/TRANSITIONAL";
5222
5298
  if (lead.runtimeState === "blocked") return "BLOCKED";
5223
- if (lead.runtimeState === "unknown") return "UNKNOWN";
5224
5299
  if (lead.runtimeState === "idle" || lead.runtimeState === "done")
5225
5300
  return "IDLE/DONE";
5226
- return "UNKNOWN";
5301
+ return "UNRESOLVED";
5227
5302
  }
5228
5303
  function buildSupervisedLeadDisplays(leads) {
5229
5304
  const byDisplay = /* @__PURE__ */ new Map();
@@ -5304,14 +5379,6 @@ function groupSupervisedLeads(leads) {
5304
5379
  groups.get(group).sort((a, b) => a.displayName.localeCompare(b.displayName));
5305
5380
  return groups;
5306
5381
  }
5307
- function groupOrderedSupervisedLeads(leads) {
5308
- const groups = new Map(
5309
- SUPERVISION_GROUPS.map((group) => [group, []])
5310
- );
5311
- for (const lead of leads)
5312
- groups.get(classifySupervisedLead(lead)).push(lead);
5313
- return groups;
5314
- }
5315
5382
  function orderedSupervisionLeads(leads) {
5316
5383
  const displays = buildSupervisedLeadDisplays(leads);
5317
5384
  const groups = groupSupervisedLeads(displays);
@@ -5359,33 +5426,67 @@ function managerSupervisionItems(snapshot) {
5359
5426
  }))
5360
5427
  ];
5361
5428
  }
5429
+ function supervisionActivityMarker(state, activeAgents) {
5430
+ return (state === "idle" || state === "done") && activeAgents > 0 ? "\u25C9" : lifecycleMarker(state);
5431
+ }
5362
5432
  function supervisionLeadMarker(lead) {
5363
- return (lead.runtimeState === "idle" || lead.runtimeState === "done") && (lead.agentCounts?.active ?? 0) > 0 ? "\u25C9" : lifecycleMarker(lead.runtimeState);
5433
+ return supervisionActivityMarker(
5434
+ lead.runtimeState,
5435
+ lead.agentCounts?.active ?? 0
5436
+ );
5364
5437
  }
5365
5438
  function lifecycleColor(state) {
5366
5439
  return STATE_COLOR[lifecycleLabel(state)] ?? "muted";
5367
5440
  }
5441
+ function supervisionLeadColor(lead) {
5442
+ return supervisionLeadMarker(lead) === "\u25C9" ? "accent" : lifecycleColor(lead.runtimeState);
5443
+ }
5368
5444
  function identifyingLabelVisible(text, label, width, expectedStart) {
5369
5445
  if (expectedStart !== void 0)
5370
5446
  return label.length > 0 && expectedStart + visibleWidth(label) <= width;
5371
5447
  const start = text.lastIndexOf(label);
5372
5448
  return label.length > 0 && start >= 0 && visibleWidth(text.slice(0, start + label.length)) <= width;
5373
5449
  }
5450
+ function renderSupervisionHeader(label, status, width, theme) {
5451
+ const marker = themed(theme, "success", "\u25CF");
5452
+ const markerWidth = visibleWidth("\u25CF");
5453
+ const identity = themed(theme, "muted", label);
5454
+ const freshnessText = status === "fresh" ? "" : `\xB7 ${status}`;
5455
+ const freshness = freshnessText ? themed(theme, "warning", freshnessText) : "";
5456
+ if (!freshness)
5457
+ return safeLine(
5458
+ `${marker} ${truncateToWidth(identity, Math.max(0, width - markerWidth - 1), "\u2026")}`,
5459
+ width
5460
+ );
5461
+ const freshnessWidth = visibleWidth(freshnessText);
5462
+ const identityWidth = width - markerWidth - freshnessWidth - 2;
5463
+ if (identityWidth > 0)
5464
+ return safeLine(
5465
+ `${marker} ${truncateToWidth(identity, identityWidth, "\u2026")} ${freshness}`,
5466
+ width
5467
+ );
5468
+ if (width >= markerWidth + visibleWidth(` ${status}`))
5469
+ return safeLine(`${marker} ${themed(theme, "warning", status)}`, width);
5470
+ return safeLine(
5471
+ `${truncateToWidth(marker, width, "")}${themed(
5472
+ theme,
5473
+ "warning",
5474
+ truncateToWidth(status, Math.max(0, width - markerWidth), "\u2026")
5475
+ )}`,
5476
+ width
5477
+ );
5478
+ }
5374
5479
  function renderSupervisionRows(reports, width, options2 = {}, selectedLead) {
5375
5480
  const status = options2.status ?? "fresh";
5376
5481
  const role2 = options2.role ?? "chief";
5377
5482
  if (status === "unavailable")
5378
5483
  return [
5379
5484
  {
5380
- text: safeLine(
5381
- `${themed(options2.theme, "success", "\u25CF")} ${themed(options2.theme, "muted", `${role2} \xB7 unavailable`)}`,
5382
- width
5383
- )
5485
+ text: renderSupervisionHeader(role2, status, width, options2.theme)
5384
5486
  }
5385
5487
  ];
5386
5488
  const displays = orderedSupervisionLeads(presentationReports(reports));
5387
- const groups = groupOrderedSupervisedLeads(displays);
5388
- const ordinary = SUPERVISION_GROUPS.flatMap((group) => groups.get(group));
5489
+ const ordinary = displays;
5389
5490
  const cap = options2.ordinaryCap ?? 6;
5390
5491
  const shown = ordinary.slice(0, Math.max(0, cap));
5391
5492
  const hidden = ordinary.length - Math.min(ordinary.length, Math.max(0, cap));
@@ -5400,18 +5501,20 @@ function renderSupervisionRows(reports, width, options2 = {}, selectedLead) {
5400
5501
  ).length;
5401
5502
  const managerSnapshot = role2 === "manager" && !Array.isArray(reports) ? reports : void 0;
5402
5503
  const project = managerSnapshot && "project" in managerSnapshot ? managerSnapshot.project : void 0;
5403
- const header = `${themed(options2.theme, "success", "\u25CF")} ${themed(
5404
- options2.theme,
5405
- "muted",
5406
- role2 === "manager" ? `manager${project ? ` \xB7 ${project}` : ""}${status === "stale" ? " \xB7 stale" : ""}` : `chief \xB7 ${supervisionCountLabel(managers, leads)}${incompatible ? ` \xB7 ${incompatible} incompatible` : ""}${status === "stale" ? " \xB7 stale" : ""}`
5407
- )}`;
5504
+ const headerText = role2 === "manager" ? `manager${project ? ` \xB7 ${project}` : ""}` : `chief \xB7 ${supervisionCountLabel(managers, leads)}${incompatible ? ` \xB7 ${incompatible} incompatible` : ""}`;
5505
+ const header = renderSupervisionHeader(
5506
+ headerText,
5507
+ status,
5508
+ width,
5509
+ options2.theme
5510
+ );
5408
5511
  if (managerSnapshot && "leads" in managerSnapshot && !("managers" in managerSnapshot)) {
5409
5512
  const items = managerSupervisionItems(managerSnapshot);
5410
5513
  const visible = items.slice(0, Math.max(0, cap));
5411
5514
  const remaining = items.length - visible.length;
5412
5515
  const now = Date.now();
5413
5516
  const metadata = visible.map((item) => ({
5414
- elapsed: formatElapsed(
5517
+ elapsed: status === "stale" ? "" : formatElapsed(
5415
5518
  item.kind === "work" ? item.lead?.herdRunStartedAt : void 0,
5416
5519
  now
5417
5520
  ) ?? "",
@@ -5420,7 +5523,7 @@ function renderSupervisionRows(reports, width, options2 = {}, selectedLead) {
5420
5523
  ) ? `${item.kind === "work" ? item.lead.contextPercent : ""}%` : ""
5421
5524
  }));
5422
5525
  const workMarkers = {
5423
- active: "\u25CF",
5526
+ active: "\xB7",
5424
5527
  paused: "\u25CB",
5425
5528
  conflict: "!"
5426
5529
  };
@@ -5428,7 +5531,7 @@ function renderSupervisionRows(reports, width, options2 = {}, selectedLead) {
5428
5531
  (candidate) => visible.every((item, index) => {
5429
5532
  if (item.kind !== "work") return true;
5430
5533
  const branch = index === visible.length - 1 && !remaining ? "\u2514\u2500" : "\u251C\u2500";
5431
- const marker = item.lead?.compatibility === "incompatible" ? "!" : item.work.status === "active" && item.lead ? `${item.lead.runtimeState === "blocked" ? "!" : ""}${supervisionLeadMarker(item.lead)}` : workMarkers[item.work.status];
5534
+ const marker = item.lead?.compatibility === "incompatible" ? "!" : item.work.status === "active" && item.lead ? supervisionLeadMarker(item.lead) : workMarkers[item.work.status];
5432
5535
  const prefixWidth = visibleWidth(`${branch} ${marker} `);
5433
5536
  const suffixWidth = visibleWidth(
5434
5537
  item.lead?.compatibility === "incompatible" ? " \xB7 build mismatch" : ` \xB7 ${item.work.status}`
@@ -5446,7 +5549,7 @@ function renderSupervisionRows(reports, width, options2 = {}, selectedLead) {
5446
5549
  if (item.kind === "lead")
5447
5550
  return {
5448
5551
  text: safeLine(
5449
- `${themed(options2.theme, item.lead.compatibility === "incompatible" ? "warning" : lifecycleColor(item.lead.runtimeState), `${branch} ${navigation}${item.lead.compatibility === "incompatible" ? "!" : supervisionLeadMarker(item.lead)}`)} ${themed(options2.theme, "muted", `${item.lead.branch ?? item.lead.displayName} \xB7 Lead${item.lead.compatibility === "incompatible" ? " \xB7 build mismatch" : ""}`)}`,
5552
+ `${themed(options2.theme, item.lead.compatibility === "incompatible" ? "warning" : supervisionLeadColor(item.lead), `${branch} ${navigation}${item.lead.compatibility === "incompatible" ? "!" : supervisionLeadMarker(item.lead)}`)} ${themed(options2.theme, "muted", `${item.lead.branch ?? item.lead.displayName} \xB7 Lead${item.lead.compatibility === "incompatible" ? " \xB7 build mismatch" : ""}`)}`,
5450
5553
  width
5451
5554
  ),
5452
5555
  ...status === "fresh" && item.lead.compatibility !== "incompatible" ? {
@@ -5457,7 +5560,7 @@ function renderSupervisionRows(reports, width, options2 = {}, selectedLead) {
5457
5560
  }
5458
5561
  } : {}
5459
5562
  };
5460
- const marker = lead?.compatibility === "incompatible" ? "!" : item.work.status === "active" && lead ? `${lead.runtimeState === "blocked" ? "!" : ""}${supervisionLeadMarker(lead)}` : workMarkers[item.work.status];
5563
+ const marker = lead?.compatibility === "incompatible" ? "!" : item.work.status === "active" && lead ? supervisionLeadMarker(lead) : workMarkers[item.work.status];
5461
5564
  const prefix = `${branch} ${navigation}${marker} `;
5462
5565
  const suffix = lead?.compatibility === "incompatible" ? " \xB7 build mismatch" : ` \xB7 ${item.work.status}`;
5463
5566
  const telemetry = [
@@ -5468,19 +5571,26 @@ function renderSupervisionRows(reports, width, options2 = {}, selectedLead) {
5468
5571
  (total, value2) => total + visibleWidth(value2) + 2,
5469
5572
  0
5470
5573
  );
5471
- const markerColor = lead?.compatibility === "incompatible" ? "warning" : item.work.status === "active" && lead ? lifecycleColor(lead.runtimeState) : item.work.status === "active" ? "success" : item.work.status === "conflict" ? "warning" : "muted";
5574
+ const markerColor = lead?.compatibility === "incompatible" ? "warning" : item.work.status === "active" && lead ? supervisionLeadColor(lead) : item.work.status === "active" ? "muted" : item.work.status === "conflict" ? "warning" : "muted";
5472
5575
  const markerText = themed(options2.theme, markerColor, marker);
5473
5576
  const branchWidth = width - visibleWidth(prefix) - visibleWidth(suffix) - telemetryWidth;
5474
5577
  const displayedBranch = safeLine(item.work.branch, branchWidth);
5475
5578
  const branchText = themed(options2.theme, "muted", displayedBranch);
5579
+ const truncatedBranch = displayedBranch !== item.work.branch;
5580
+ const clickRegion = truncatedBranch && visibleWidth(displayedBranch) > visibleWidth("\u2026") ? {
5581
+ from: visibleWidth(prefix),
5582
+ to: visibleWidth(prefix) + visibleWidth(displayedBranch)
5583
+ } : void 0;
5584
+ const canFocusLead = status === "fresh" && item.work.status === "active" && lead && lead.compatibility !== "incompatible";
5476
5585
  return {
5477
5586
  text: safeLine(
5478
5587
  `${themed(options2.theme, "muted", `${branch} ${navigation}`)}${markerText} ${branchText}${themed(options2.theme, "muted", suffix)}${telemetry.map((value2) => themed(options2.theme, "muted", ` ${value2}`)).join("")}`,
5479
5588
  width
5480
5589
  ),
5481
- ...status === "fresh" && item.work.status === "active" && lead && lead.compatibility !== "incompatible" && displayedBranch === item.work.branch ? {
5590
+ ...canFocusLead && (!truncatedBranch || clickRegion) ? {
5482
5591
  label: item.work.branch,
5483
- intent: { kind: "session", sessionId: lead.lead }
5592
+ intent: { kind: "session", sessionId: lead.lead },
5593
+ ...clickRegion ? { clickRegion } : {}
5484
5594
  } : {}
5485
5595
  };
5486
5596
  }),
@@ -5500,7 +5610,7 @@ function renderSupervisionRows(reports, width, options2 = {}, selectedLead) {
5500
5610
  const intent = status === "fresh" && !isIncompatible ? { kind: "session", sessionId: lead.lead } : void 0;
5501
5611
  const row = {
5502
5612
  text: safeLine(
5503
- `${themed(options2.theme, isIncompatible ? "warning" : lifecycleColor(lead.runtimeState), `${branch} ${indicators}${marker}`)} ${themed(options2.theme, "muted", `${lead.displayName}${isIncompatible ? " \xB7 build mismatch" : `${counts?.total ? ` \xB7 ${counts.total} compatible lead${counts.total === 1 ? "" : "s"}` : ""}${incompatibleLeads ? ` \xB7 ${incompatibleLeads} incompatible` : ""}${lead.agentCounts?.total ? ` \xB7 ${lead.agentCounts.total} agent${lead.agentCounts.total === 1 ? "" : "s"}` : ""}`}`)}`,
5613
+ `${themed(options2.theme, isIncompatible ? "warning" : supervisionLeadColor(lead), `${branch} ${indicators}${marker}`)} ${themed(options2.theme, "muted", `${lead.displayName}${isIncompatible ? " \xB7 build mismatch" : `${counts?.total ? ` \xB7 ${counts.total} compatible lead${counts.total === 1 ? "" : "s"}` : ""}${incompatibleLeads ? ` \xB7 ${incompatibleLeads} incompatible` : ""}${lead.agentCounts?.total ? ` \xB7 ${lead.agentCounts.total} agent${lead.agentCounts.total === 1 ? "" : "s"}` : ""}`}`)}`,
5504
5614
  width
5505
5615
  ),
5506
5616
  ...intent ? { intent } : {},
@@ -5512,9 +5622,13 @@ function renderSupervisionRows(reports, width, options2 = {}, selectedLead) {
5512
5622
  row,
5513
5623
  ...children.map((child, childIndex) => {
5514
5624
  const childBranch = childIndex === children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
5625
+ const childMarker = supervisionActivityMarker(
5626
+ child.runtime_state,
5627
+ child.agent_counts?.active ?? 0
5628
+ );
5515
5629
  return {
5516
5630
  text: safeLine(
5517
- child.compatibility === "incompatible" ? `${themed(options2.theme, "warning", `${childIndent}${childBranch} !`)} ${themed(options2.theme, "muted", `${child.branch ?? child.display_name} \xB7 build mismatch`)}` : `${themed(options2.theme, "muted", `${childIndent}${childBranch} ${child.branch ?? child.display_name} \xB7 `)}${themed(options2.theme, lifecycleColor(child.runtime_state), child.runtime_state)}${themed(options2.theme, "muted", `${child.agent_counts?.total ? ` \xB7 ${child.agent_counts.total} agent${child.agent_counts.total === 1 ? "" : "s"}` : ""}`)}`,
5631
+ child.compatibility === "incompatible" ? `${themed(options2.theme, "warning", `${childIndent}${childBranch} !`)} ${themed(options2.theme, "muted", `${child.branch ?? child.display_name} \xB7 build mismatch`)}` : `${themed(options2.theme, "muted", `${childIndent}${childBranch} ${child.branch ?? child.display_name} \xB7 `)}${themed(options2.theme, childMarker === "\u25C9" ? "accent" : lifecycleColor(child.runtime_state), childMarker)} ${themed(options2.theme, lifecycleColor(child.runtime_state), child.runtime_state)}${themed(options2.theme, "muted", `${child.agent_counts?.total ? ` \xB7 ${child.agent_counts.total} agent${child.agent_counts.total === 1 ? "" : "s"}` : ""}`)}`,
5518
5632
  width
5519
5633
  ),
5520
5634
  ...status === "fresh" && child.compatibility !== "incompatible" ? {
@@ -5548,7 +5662,7 @@ function formatSupervisionNotification(reports, status = "fresh") {
5548
5662
  const lines = [
5549
5663
  `Pi Herdsman \xB7 ${supervisionCountLabel(managers, leads)}${incompatible ? ` \xB7 ${incompatible} incompatible` : ""}${status === "stale" ? " \xB7 stale" : ""}`,
5550
5664
  ...ordered.slice(0, 8).map(
5551
- (lead) => `${lead.compatibility === "incompatible" ? `incompatible ${lead.role} \xB7 ` : `${lead.role === "lead" ? "direct lead \xB7 " : "manager \xB7 "}${classifySupervisedLead(lead).toLowerCase()}: `}${lead.displayName}${lead.compatibility === "incompatible" ? " \xB7 build mismatch" : `${lead.leadCounts?.total ? ` \xB7 ${lead.leadCounts.total} compatible lead${lead.leadCounts.total === 1 ? "" : "s"}` : ""}${lead.incompatibleLeadCount ? ` \xB7 ${lead.incompatibleLeadCount} incompatible lead${lead.incompatibleLeadCount === 1 ? "" : "s"}` : ""}${lead.agentCounts?.total ? ` \xB7 ${leadAgentCounts(lead)}` : ""}`}`
5665
+ (lead) => `${lead.compatibility === "incompatible" ? `incompatible ${lead.role} \xB7 ` : `${lead.role === "lead" ? "direct lead \xB7 " : "manager \xB7 "}${lead.runtimeState}: `}${lead.displayName}${lead.compatibility === "incompatible" ? " \xB7 build mismatch" : `${lead.leadCounts?.total ? ` \xB7 ${lead.leadCounts.total} compatible lead${lead.leadCounts.total === 1 ? "" : "s"}` : ""}${lead.incompatibleLeadCount ? ` \xB7 ${lead.incompatibleLeadCount} incompatible lead${lead.incompatibleLeadCount === 1 ? "" : "s"}` : ""}${lead.agentCounts?.total ? ` \xB7 ${leadAgentCounts(lead)}` : ""}`}`
5552
5666
  )
5553
5667
  ];
5554
5668
  if (ordered.length > 8) lines.push(`\u2026 ${ordered.length - 8} more \xB7 /chief`);
@@ -5724,13 +5838,17 @@ function createSupervisionWidget(getLeads, getStatus, role2 = "chief", theme, on
5724
5838
  }).filter(({ text }) => text.length > 0);
5725
5839
  hits = [];
5726
5840
  rows.forEach((row, index) => {
5727
- if (row.intent && row.label && identifyingLabelVisible(row.text, row.label, width))
5841
+ if (!row.intent || !row.label) return;
5842
+ if (row.clickRegion) {
5843
+ hits.push({ row: index, ...row.clickRegion, intent: row.intent });
5844
+ } else if (identifyingLabelVisible(row.text, row.label, width)) {
5728
5845
  hits.push({
5729
5846
  row: index,
5730
5847
  from: 0,
5731
5848
  to: Math.min(width, visibleWidth(row.text)),
5732
5849
  intent: row.intent
5733
5850
  });
5851
+ }
5734
5852
  });
5735
5853
  return rows.map(({ text }) => text);
5736
5854
  },
@@ -5797,6 +5915,35 @@ function value(v) {
5797
5915
  function peerMessageStatus(details) {
5798
5916
  return details.accepted === true ? "accepted remotely" : details.accepted === false ? "queued for remote retry" : details.remoteSessionId ? "reply queued" : "peer message queued";
5799
5917
  }
5918
+ function peerRemoteDiagnosticLines(diagnostics, reportedOmitted) {
5919
+ const lines = [];
5920
+ const visibleDiagnostics = diagnostics.slice(0, maxRemoteDiagnostics);
5921
+ for (const item of visibleDiagnostics) {
5922
+ if (!item || typeof item !== "object") continue;
5923
+ const diagnostic = item;
5924
+ const message = remoteDiagnosticMessages[value(diagnostic.reason)];
5925
+ if (!message) continue;
5926
+ const machine = collapseDisplayText(value(diagnostic.machine), 80);
5927
+ const peer = collapseDisplayText(value(diagnostic.peer), 80);
5928
+ const subject = [machine, peer].filter(Boolean).join(" \xB7 ");
5929
+ lines.push(` ${subject || "saved machines"} \xB7 ${message[0]}`);
5930
+ const localBuild = collapseDisplayText(value(diagnostic.local_build), 48);
5931
+ const remoteBuild = collapseDisplayText(value(diagnostic.remote_build), 48);
5932
+ if (localBuild) lines.push(` local ${localBuild}`);
5933
+ if (remoteBuild) lines.push(` remote ${remoteBuild}`);
5934
+ lines.push(` Check: ${message[1]}`);
5935
+ }
5936
+ const omitted = reportedOmitted + Math.max(0, diagnostics.length - visibleDiagnostics.length);
5937
+ if (omitted)
5938
+ lines.push(
5939
+ ` ${omitted} additional diagnostic${omitted === 1 ? "" : "s"} omitted`
5940
+ );
5941
+ return lines;
5942
+ }
5943
+ function remoteDiagnosticOmittedCount(details) {
5944
+ const count = details.remote_diagnostics_omitted;
5945
+ return typeof count === "number" && Number.isSafeInteger(count) && count > 0 ? count : 0;
5946
+ }
5800
5947
  function agentDefinitionSuffix(label, definition) {
5801
5948
  const name = value(definition);
5802
5949
  return name && name !== label ? ` \xB7 ${name}` : "";
@@ -5912,7 +6059,7 @@ function formatAgentDefinitions(definitions) {
5912
6059
  }
5913
6060
  function displayHomePath(path) {
5914
6061
  const home = homedir3();
5915
- if (!isAbsolute2(path)) return path;
6062
+ if (!isAbsolute3(path)) return path;
5916
6063
  const remainder = relative(home, path);
5917
6064
  if (remainder === "") return "~";
5918
6065
  if (remainder !== ".." && !remainder.startsWith(`..${sep2}`))
@@ -6393,7 +6540,7 @@ function coordinationBody(action, args) {
6393
6540
  return typeof text === "string" && text.trim() ? { label, text } : void 0;
6394
6541
  }
6395
6542
  function coordinationHeader(tool, verb, target, theme) {
6396
- const title = tool === "agent" ? verb === "list" ? "list agents" : verb === "transcript" ? "read agent transcript" : `${verb} agent` : tool === "staff" ? verb === "transcript" ? "read staff transcript" : `${verb} ${verb === "delegate" || verb === "resume" ? "project" : verb === "stop" ? "lead" : verb === "remove" ? "worktree" : "staff"}` : tool === "peer" ? verb === "list" ? "list peers" : "message peer" : `${verb} supervisor`;
6543
+ const title = tool === "agent" ? verb === "list" ? "list agents" : verb === "transcript" ? "read agent transcript" : `${verb} agent` : tool === "staff" ? verb === "transcript" ? "read staff transcript" : verb === "merge" ? "integrate branch" : `${verb} ${verb === "delegate" || verb === "resume" ? "work" : verb === "stop" ? "lead" : verb === "remove" ? "worktree" : "staff"}` : tool === "peer" ? verb === "list" ? "list peers" : "message peer" : `${verb} supervisor`;
6397
6544
  return `${humanText(theme, "toolTitle", theme.bold(title))}${target ? ` ${humanText(theme, "accent", target)}` : ""}`;
6398
6545
  }
6399
6546
  function renderExpandedCoordinationCall(tool, action, args, theme, header) {
@@ -6598,7 +6745,8 @@ function agentHierarchy(details) {
6598
6745
  }
6599
6746
  function expandedResultLines(tool, action, details, args, theme, activeRole) {
6600
6747
  const display = value(details.display_name) || value(details.agent) || value(details.label) || value(details.session) || value(args.agent) || value(args.label) || "agent";
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}`;
6748
+ const staffWorkOutcome = tool === "staff" && details.ok === true ? action === "delegate" ? "work assigned" : action === "resume" ? details.already_running === true ? "work already running" : "work resumed" : void 0 : void 0;
6749
+ const heading = staffWorkOutcome ?? (tool === "staff" && action === "merge" && details.ok === true ? "integrate branch" : 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}`);
6602
6750
  const lines = [heading];
6603
6751
  const fields = [
6604
6752
  ["definition", details.definition ?? details.agent_definition],
@@ -6707,12 +6855,13 @@ function expandedResultLines(tool, action, details, args, theme, activeRole) {
6707
6855
  ];
6708
6856
  })
6709
6857
  );
6710
- const unavailableMachines = Array.isArray(details.unavailable_machines) ? details.unavailable_machines : [];
6711
- if (unavailableMachines.length)
6712
- lines.push(
6713
- "",
6714
- `unavailable machines ${unavailableMachines.map(value).join(", ")}`
6715
- );
6858
+ const remoteDiagnostics = Array.isArray(details.remote_diagnostics) ? details.remote_diagnostics : [];
6859
+ const diagnosticLines = peerRemoteDiagnosticLines(
6860
+ remoteDiagnostics,
6861
+ remoteDiagnosticOmittedCount(details)
6862
+ );
6863
+ if (diagnosticLines.length)
6864
+ lines.push("", "remote diagnostics", ...diagnosticLines);
6716
6865
  return lines;
6717
6866
  }
6718
6867
  const reports = Array.isArray(details.reports) ? details.reports : [];
@@ -6720,7 +6869,7 @@ function expandedResultLines(tool, action, details, args, theme, activeRole) {
6720
6869
  lines.push(
6721
6870
  "",
6722
6871
  ...work.length ? [
6723
- "project work:",
6872
+ "Managed work:",
6724
6873
  ...work.flatMap((item) => {
6725
6874
  if (!item || typeof item !== "object") return [];
6726
6875
  const branch = value(item.branch) || "unknown";
@@ -6883,7 +7032,7 @@ ${expandedResultLines(tool, action, details, args, theme, context?.activeRole).s
6883
7032
  }
6884
7033
  if (!expanded && tool === "staff" && ["delegate", "resume", "stop"].includes(action)) {
6885
7034
  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`;
7035
+ const outcome = action === "delegate" ? `work assigned \xB7 ${branch}` : action === "resume" ? details.already_running === true ? `work already running \xB7 ${branch}` : `work resumed \xB7 ${branch}` : `Lead stopped \xB7 ${branch} preserved`;
6887
7036
  return new WidthSafeText(statusLine(theme, "success", "\u2713", outcome), 0, 0);
6888
7037
  }
6889
7038
  if (expanded)
@@ -6953,7 +7102,14 @@ ${humanText(theme, "warning", ` ! descendant continuation warning \xB7 Ctrl+O`)
6953
7102
  if (tool === "peer" && action === "list") {
6954
7103
  const peers = Array.isArray(details.peers) ? details.peers : [];
6955
7104
  const replyOnly = Array.isArray(details.reply_only) ? details.reply_only : [];
6956
- const summary = replyOnly.length ? `peer \xB7 ${peers.length} discovered \xB7 ${replyOnly.length} reply-only` : `peer \xB7 ${peers.length} peer${peers.length === 1 ? "" : "s"}`;
7105
+ const diagnostics = Array.isArray(details.remote_diagnostics) ? details.remote_diagnostics : [];
7106
+ const warningCount = diagnostics.length + remoteDiagnosticOmittedCount(details);
7107
+ const peerCount = warningCount || replyOnly.length ? `${peers.length} discovered` : `${peers.length} peer${peers.length === 1 ? "" : "s"}`;
7108
+ const summary = [
7109
+ `peer \xB7 ${peerCount}`,
7110
+ ...replyOnly.length ? [`${replyOnly.length} reply-only`] : [],
7111
+ ...warningCount ? [`${warningCount} warning${warningCount === 1 ? "" : "s"}`] : []
7112
+ ].join(" \xB7 ");
6957
7113
  return new WidthSafeText(humanText(theme, "toolTitle", summary), 0, 0);
6958
7114
  }
6959
7115
  if (tool === "peer" && action === "message")
@@ -7143,7 +7299,7 @@ function renderCoordinationMessage(kind, message, options2, theme) {
7143
7299
  `;
7144
7300
  break;
7145
7301
  case "project_message":
7146
- heading = d?.branch ? `Project message \xB7 ${d.branch}` : "Project message";
7302
+ heading = d?.branch ? `Assignment update \xB7 ${d.branch}` : "Assignment update";
7147
7303
  if (d?.branch && d?.fromSessionId)
7148
7304
  prefix = `Project ${d.branch} from lead ${d.fromSessionId}:
7149
7305
 
@@ -7390,7 +7546,7 @@ function renderAgentLostMessage(message, options2, theme) {
7390
7546
  function createStatusWidget(invalidate, theme, onFocus) {
7391
7547
  return new StatusWidget(invalidate, theme, onFocus);
7392
7548
  }
7393
- var LIFECYCLE, STATE_COLOR, MIN_TASK_WIDTH, STATUS_LAYOUTS, SUPERVISION_GROUPS, MANAGER_METADATA_LAYOUTS, SUPERVISION_CONTEXT_MAX_BYTES, WidthSafeText, spinner, StatusWidget;
7549
+ var LIFECYCLE, animates, STATE_COLOR, MIN_TASK_WIDTH, STATUS_LAYOUTS, SUPERVISION_GROUPS, MANAGER_METADATA_LAYOUTS, SUPERVISION_CONTEXT_MAX_BYTES, remoteDiagnosticMessages, maxRemoteDiagnostics, WidthSafeText, spinner, StatusWidget;
7394
7550
  var init_presentation = __esm({
7395
7551
  "extension/presentation.ts"() {
7396
7552
  init_agent_definitions();
@@ -7406,6 +7562,7 @@ var init_presentation = __esm({
7406
7562
  unknown: ["?", "unknown"],
7407
7563
  lost: ["\xD7", "lost"]
7408
7564
  };
7565
+ animates = (state) => state === "working" || state === "starting";
7409
7566
  STATE_COLOR = {
7410
7567
  [lifecycleLabel("working")]: "success",
7411
7568
  [lifecycleLabel("blocked")]: "warning",
@@ -7422,10 +7579,10 @@ var init_presentation = __esm({
7422
7579
  { task: false, elapsed: false, context: false }
7423
7580
  ];
7424
7581
  SUPERVISION_GROUPS = [
7425
- "WORKING",
7582
+ "ACTIVE/TRANSITIONAL",
7426
7583
  "BLOCKED",
7427
7584
  "IDLE/DONE",
7428
- "UNKNOWN"
7585
+ "UNRESOLVED"
7429
7586
  ];
7430
7587
  MANAGER_METADATA_LAYOUTS = [
7431
7588
  { elapsed: true, context: true },
@@ -7433,6 +7590,30 @@ var init_presentation = __esm({
7433
7590
  { elapsed: false, context: false }
7434
7591
  ];
7435
7592
  SUPERVISION_CONTEXT_MAX_BYTES = 16 * 1024;
7593
+ remoteDiagnosticMessages = {
7594
+ machine_list_failed: [
7595
+ "Saved Herdr machines could not be listed",
7596
+ "Check Herdr machine status."
7597
+ ],
7598
+ herdr_not_reachable: [
7599
+ "Herdr reachability not confirmed",
7600
+ "Check Herdr machine status; reconnect interactively if needed."
7601
+ ],
7602
+ probe_failed: [
7603
+ "Remote peer probe failed",
7604
+ "Check Herdr machine status and the remote Pi session."
7605
+ ],
7606
+ build_mismatch: ["Peer build mismatch", "Reload the outdated Pi session."],
7607
+ build_unverified: [
7608
+ "Peer build could not be verified",
7609
+ "Reload the remote Pi session to publish build identity."
7610
+ ],
7611
+ eligibility_unverified: [
7612
+ "Ordinary-Lead eligibility could not be verified",
7613
+ "Check the remote assignment scan before relying on Lead results."
7614
+ ]
7615
+ };
7616
+ maxRemoteDiagnostics = 20;
7436
7617
  WidthSafeText = class extends Text {
7437
7618
  render(width) {
7438
7619
  return super.render(width).map(
@@ -7466,9 +7647,7 @@ var init_presentation = __esm({
7466
7647
  this.snapshot = snapshot;
7467
7648
  this.hits = [];
7468
7649
  this.renderedWidth = -1;
7469
- const animated = snapshot.agents.some(
7470
- (agent) => agent.state === "working" || agent.state === "settling" || agent.state === "starting"
7471
- );
7650
+ const animated = !snapshot.stale && !snapshot.unavailable && snapshot.agents.some((agent) => animates(agent.state));
7472
7651
  if (animated && !this.timer)
7473
7652
  this.timer = setInterval(() => {
7474
7653
  this.frame++;
@@ -7487,16 +7666,25 @@ var init_presentation = __esm({
7487
7666
  const s = this.snapshot;
7488
7667
  this.renderedWidth = width;
7489
7668
  this.hits = [];
7490
- const suffix = s.unavailable ? "unavailable" : `${formatStatusCounts(s.agents)}${s.stale ? " \xB7 stale" : ""}`;
7491
7669
  const availableWidth = Math.max(0, width);
7492
7670
  const execution = s.execution ? ` \xB7 ${s.execution.kind === "managed" ? managedExecutionLabel(s.execution.lifecycle) : s.execution.mode}` : "";
7493
- const elapsed = formatElapsed(s.herdRunStartedAt, Date.now());
7671
+ const observedNow = s.stale ? s.refreshedAt : Date.now();
7672
+ const elapsed = observedNow === void 0 ? void 0 : formatElapsed(s.herdRunStartedAt, observedNow);
7494
7673
  let run2 = !s.identityOnly && elapsed ? ` \xB7 ${elapsed}` : "";
7495
- const suffixText = s.identityOnly || !suffix ? "" : ` ${suffix}`;
7674
+ const counts = s.identityOnly || s.unavailable ? "" : formatStatusCounts(s.agents);
7675
+ const freshness = s.unavailable ? "unavailable" : s.stale ? "stale" : "";
7676
+ const freshnessSuffix = freshness ? ` ${freshness}` : "";
7677
+ const fullSuffix = s.unavailable ? freshnessSuffix : counts ? ` ${counts}${s.stale ? " \xB7 stale" : ""}` : freshnessSuffix;
7678
+ const fullSuffixWidth = visibleWidth(fullSuffix);
7679
+ const freshnessSuffixWidth = visibleWidth(freshnessSuffix);
7496
7680
  const breadcrumbSegments = s.breadcrumb ?? [{ text: "?" }];
7681
+ const fullIdentityWidth = visibleWidth(
7682
+ renderBreadcrumb(breadcrumbSegments, Number.MAX_SAFE_INTEGER).text
7683
+ );
7684
+ const reservedSuffixWidth = freshness && fullSuffixWidth + fullIdentityWidth <= availableWidth ? fullSuffixWidth : freshnessSuffixWidth || (fullSuffixWidth + fullIdentityWidth <= availableWidth ? fullSuffixWidth : 0);
7497
7685
  const renderedBreadcrumb = renderBreadcrumb(
7498
7686
  breadcrumbSegments,
7499
- availableWidth
7687
+ Math.max(0, availableWidth - reservedSuffixWidth)
7500
7688
  );
7501
7689
  const breadcrumb = renderedBreadcrumb.text;
7502
7690
  if (!s.stale && !s.unavailable) this.hits.push(...renderedBreadcrumb.hits);
@@ -7504,6 +7692,9 @@ var init_presentation = __esm({
7504
7692
  0,
7505
7693
  availableWidth - visibleWidth(breadcrumb)
7506
7694
  );
7695
+ const includeCounts = !!counts && visibleWidth(fullSuffix) <= remainingWidth;
7696
+ const suffixBody = includeCounts ? `${counts}${s.stale ? " \xB7 stale" : ""}` : freshness;
7697
+ const suffixText = suffixBody ? `${breadcrumb ? " " : ""}${suffixBody}` : "";
7507
7698
  const executionFits = !!execution && visibleWidth(execution) + visibleWidth(suffixText) <= remainingWidth;
7508
7699
  const shownExecution = executionFits ? execution : "";
7509
7700
  if (!s.stale && !s.unavailable && executionFits && s.execution?.kind === "managed" && (!s.execution.lifecycle || s.execution.lifecycle === "assigned")) {
@@ -7528,13 +7719,15 @@ var init_presentation = __esm({
7528
7719
  const styledExecution = shownExecution ? this.theme.fg("muted", shownExecution) : "";
7529
7720
  const styledTools = tools ? this.theme.fg("muted", tools) : "";
7530
7721
  const styledRun = run2 ? this.theme.fg("accent", run2) : "";
7531
- const styledSuffix = suffixText ? this.theme.fg("muted", suffixText) : "";
7722
+ const styledSuffix = !suffixText ? "" : s.unavailable ? this.theme.fg("warning", suffixText) : s.stale ? `${includeCounts ? this.theme.fg("muted", `${breadcrumb ? " " : ""}${counts} \xB7 `) : breadcrumb ? " " : ""}${this.theme.fg("warning", "stale")}` : this.theme.fg("muted", suffixText);
7532
7723
  const header = `${styledBreadcrumb}${styledExecution}${styledTools}${styledRun}${styledSuffix}`;
7533
- const out = [truncateToWidth(header, availableWidth, "\u2026")];
7724
+ const compactStaleHeader = s.stale && !s.unavailable && !breadcrumb && visibleWidth("\u25CF stale") <= availableWidth ? `${this.theme.fg("success", "\u25CF")} ${this.theme.fg("warning", "stale")}` : header;
7725
+ const out = [truncateToWidth(compactStaleHeader, availableWidth, "\u2026")];
7534
7726
  if (s.identityOnly) return out;
7535
7727
  const rows = renderStatusRows(s.agents, {
7536
- now: Date.now(),
7728
+ now: observedNow,
7537
7729
  frame: this.frame,
7730
+ animate: !s.stale && !s.unavailable,
7538
7731
  width: Math.max(0, width),
7539
7732
  theme: this.theme
7540
7733
  });
@@ -9590,13 +9783,13 @@ import {
9590
9783
  openSync as openSync8,
9591
9784
  readFileSync as readFileSync8,
9592
9785
  readSync as readSync3,
9593
- statSync as statSync4,
9786
+ statSync as statSync5,
9594
9787
  renameSync as renameSync7,
9595
9788
  unlinkSync as unlinkSync7,
9596
9789
  writeFileSync as writeFileSync5
9597
9790
  } from "node:fs";
9598
9791
  import { createHash as createHash8, randomUUID as randomUUID9 } from "node:crypto";
9599
- import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute3, join as join8, normalize } from "node:path";
9792
+ import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute4, join as join8, normalize } from "node:path";
9600
9793
  import { isDeepStrictEqual } from "node:util";
9601
9794
  function readSessionKind(entries, sessionId) {
9602
9795
  let identity;
@@ -9953,7 +10146,7 @@ function removeMalformedChiefMessageUnlocked(runtime, toSessionId, id) {
9953
10146
  } catch (error2) {
9954
10147
  if (error2.code === "ENOENT") {
9955
10148
  try {
9956
- statSync4(path);
10149
+ statSync5(path);
9957
10150
  errors.push(
9958
10151
  new Error("Unable to confirm malformed Chief message removal")
9959
10152
  );
@@ -10030,7 +10223,7 @@ function writeChiefMessageUnlocked(record, runtime, clearQuarantine) {
10030
10223
  const path = chiefMessagePath(runtime, record.toSessionId, record.id);
10031
10224
  if (record.kind !== "project_assignment") {
10032
10225
  try {
10033
- statSync4(path);
10226
+ statSync5(path);
10034
10227
  const existing = readChiefMessage(path);
10035
10228
  if (!isDeepStrictEqual(existing, record))
10036
10229
  throw new Error(
@@ -10097,7 +10290,7 @@ function writeChiefMessageUnlocked(record, runtime, clearQuarantine) {
10097
10290
  function conclusivelyMalformedChiefMessage(path) {
10098
10291
  let content;
10099
10292
  try {
10100
- if (statSync4(path).size > COORDINATION_MESSAGE_MAX_BYTES) return true;
10293
+ if (statSync5(path).size > COORDINATION_MESSAGE_MAX_BYTES) return true;
10101
10294
  content = readFileSync8(path, "utf8");
10102
10295
  } catch {
10103
10296
  return false;
@@ -10115,7 +10308,7 @@ function assertChiefMessageNotQuarantined(runtime, toSessionId, id) {
10115
10308
  function readStoredChiefMessage(path) {
10116
10309
  let size;
10117
10310
  try {
10118
- size = statSync4(path).size;
10311
+ size = statSync5(path).size;
10119
10312
  } catch (error2) {
10120
10313
  throw new Error("Unable to read Chief message", { cause: error2 });
10121
10314
  }
@@ -10260,7 +10453,7 @@ function quarantineChiefMessageUnlocked(runtime, toSessionId, id) {
10260
10453
  }
10261
10454
  function chiefMessageQuarantined(runtime, toSessionId, id) {
10262
10455
  try {
10263
- statSync4(`${chiefMessagePath(runtime, toSessionId, id)}.quarantine`);
10456
+ statSync5(`${chiefMessagePath(runtime, toSessionId, id)}.quarantine`);
10264
10457
  return true;
10265
10458
  } catch (error2) {
10266
10459
  if (error2.code === "ENOENT") return false;
@@ -10700,7 +10893,7 @@ function listPeerLeadRecords(runtime = peerRuntime()) {
10700
10893
  return entries.filter((entry) => /^[0-9a-f]{64}\.json$/.test(entry)).sort().flatMap((entry) => {
10701
10894
  try {
10702
10895
  const path = join8(runtime.peers, entry);
10703
- if (statSync4(path).size > PEER_LEAD_RECORD_MAX_BYTES) return [];
10896
+ if (statSync5(path).size > PEER_LEAD_RECORD_MAX_BYTES) return [];
10704
10897
  const text = readFileSync8(path, "utf8");
10705
10898
  const value2 = JSON.parse(text);
10706
10899
  if (!validPeerLeadRecord(value2) || peerLeadRecordFilename(value2.piSessionId) !== entry)
@@ -10869,13 +11062,13 @@ function readManagerDescriptorStatus(runtime, workspaceId) {
10869
11062
  const lockPath = `${path}.lock`;
10870
11063
  let content;
10871
11064
  try {
10872
- if (statSync4(path).size > CHIEF_DESCRIPTOR_MAX_BYTES)
11065
+ if (statSync5(path).size > CHIEF_DESCRIPTOR_MAX_BYTES)
10873
11066
  throw new Error("descriptor too large");
10874
11067
  content = readFileSync8(path, "utf8");
10875
11068
  } catch (error2) {
10876
11069
  if (error2.code === "ENOENT") {
10877
11070
  try {
10878
- if (!statSync4(lockPath, { throwIfNoEntry: false })) return void 0;
11071
+ if (!statSync5(lockPath, { throwIfNoEntry: false })) return void 0;
10879
11072
  } catch (lockError) {
10880
11073
  throw new Error("Unable to verify Manager descriptor", {
10881
11074
  cause: lockError
@@ -10909,7 +11102,7 @@ function readManagerDescriptor(runtime, workspaceId) {
10909
11102
  throw new Error("Unable to verify Manager supervision lease");
10910
11103
  return status.descriptor;
10911
11104
  }
10912
- function listManagerDescriptors(runtime = supervisionRuntime()) {
11105
+ function listManagerDescriptors(runtime = supervisionRuntime(), strict = false) {
10913
11106
  let entries;
10914
11107
  try {
10915
11108
  entries = readdirSync5(runtime.managers);
@@ -10920,13 +11113,18 @@ function listManagerDescriptors(runtime = supervisionRuntime()) {
10920
11113
  return entries.filter((entry) => /^[0-9a-f]{64}\.json$/.test(entry)).sort().flatMap((entry) => {
10921
11114
  try {
10922
11115
  const path = join8(runtime.managers, entry);
10923
- if (statSync4(path).size > CHIEF_DESCRIPTOR_MAX_BYTES) return [];
11116
+ if (statSync5(path).size > CHIEF_DESCRIPTOR_MAX_BYTES)
11117
+ throw new Error("Manager descriptor too large");
10924
11118
  const candidate = JSON.parse(readFileSync8(path, "utf8"));
10925
11119
  if (!validManagerDescriptor(candidate) || basename7(managerDescriptorPath(runtime, candidate.workspaceId)) !== entry)
10926
- return [];
10927
- const verified = readManagerDescriptor(runtime, candidate.workspaceId);
10928
- return verified ? [verified] : [];
10929
- } catch {
11120
+ throw new Error("Invalid Manager descriptor");
11121
+ const status = readManagerDescriptorStatus(
11122
+ runtime,
11123
+ candidate.workspaceId
11124
+ );
11125
+ return status?.live ? [status.descriptor] : [];
11126
+ } catch (error2) {
11127
+ if (strict) throw error2;
10930
11128
  return [];
10931
11129
  }
10932
11130
  });
@@ -11006,7 +11204,7 @@ function validProjectAssignment(value2) {
11006
11204
  ];
11007
11205
  return required.every((key) => Object.hasOwn(r, key)) && Object.keys(r).every(
11008
11206
  (key) => required.includes(key) || optional.includes(key)
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(
11207
+ ) && 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" && isAbsolute4(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(
11010
11208
  (evidence) => "result" in evidence || evidence.sourceAssignmentId === r.id
11011
11209
  ) && 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(
11012
11210
  (id) => typeof id === "string" && r.requiredEvidence?.some(
@@ -11592,7 +11790,7 @@ function removeProjectMessage(runtime, repoKey, branch, id) {
11592
11790
  if (!UUID3.test(id)) throw new Error("Invalid project message ID");
11593
11791
  const directory2 = projectMessageDirectory(runtime, repoKey, branch);
11594
11792
  try {
11595
- if (!statSync4(directory2).isDirectory())
11793
+ if (!statSync5(directory2).isDirectory())
11596
11794
  throw new Error("Invalid project message directory");
11597
11795
  } catch (error2) {
11598
11796
  if (error2.code === "ENOENT") return;
@@ -11634,7 +11832,7 @@ function readProjectMessageFile(path) {
11634
11832
  }
11635
11833
  function readStoredProjectMessageFile(path) {
11636
11834
  try {
11637
- if (statSync4(path).size > COORDINATION_MESSAGE_MAX_BYTES)
11835
+ if (statSync5(path).size > COORDINATION_MESSAGE_MAX_BYTES)
11638
11836
  throw new Error("large");
11639
11837
  const stored = JSON.parse(readFileSync8(path, "utf8"));
11640
11838
  if (!validProjectMessage(stored) || basename7(path) !== `${stored.id}.json`)
@@ -12088,7 +12286,7 @@ import {
12088
12286
  truncateTail as truncateTail2
12089
12287
  } from "@earendil-works/pi-coding-agent";
12090
12288
  import { contentText as contentText2 } from "@earendil-works/pi-ai";
12091
- import { realpathSync as realpathSync3, statSync as statSync5 } from "node:fs";
12289
+ import { realpathSync as realpathSync3, statSync as statSync6 } from "node:fs";
12092
12290
  import { unlinkSync as unlinkSync8 } from "node:fs";
12093
12291
  import { createHash as createHash9, randomUUID as randomUUID10 } from "node:crypto";
12094
12292
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
@@ -13384,7 +13582,7 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
13384
13582
  "continue"
13385
13583
  );
13386
13584
  try {
13387
- statSync5(
13585
+ statSync6(
13388
13586
  agentMailboxPath(
13389
13587
  historicalClose.workspace_id,
13390
13588
  historicalClose.agent
@@ -13437,7 +13635,7 @@ function resolveAssignmentSession(ctx, raw, options2 = {}) {
13437
13635
  );
13438
13636
  if (!historicalClose) {
13439
13637
  try {
13440
- statSync5(
13638
+ statSync6(
13441
13639
  agentMailboxPath(
13442
13640
  historicalTerminal.workspaceId,
13443
13641
  historicalTerminal.agentLabel
@@ -14142,7 +14340,7 @@ function createAgentController(pi, options2) {
14142
14340
  const persistedTranscriptReady2 = (state) => {
14143
14341
  if (!state.piSessionId || !state.piSessionFile) return false;
14144
14342
  try {
14145
- const file2 = statSync5(state.piSessionFile, { throwIfNoEntry: false });
14343
+ const file2 = statSync6(state.piSessionFile, { throwIfNoEntry: false });
14146
14344
  return !!file2?.isFile() && file2.size > 0;
14147
14345
  } catch {
14148
14346
  return false;
@@ -16182,9 +16380,15 @@ function createAgentController(pi, options2) {
16182
16380
  const expected = resultIdentity(runtime, result.requestId);
16183
16381
  const identityMismatch = runtimes.get(runtime.label) !== runtime || result.runId !== runtime.runId || result.ownerSessionId !== runtime.ownerSessionId || result.workspaceId !== runtime.workspaceId || result.agentLabel !== runtime.label || result.paneId !== runtime.paneId || result.requestId !== (runtime.activeRequestId ?? runtime.completedRequestId);
16184
16382
  if (identityMismatch) return;
16185
- const entries = context.sessionManager.getEntries();
16383
+ let entries = context.sessionManager.getEntries();
16186
16384
  const evidenceKey = JSON.stringify(Object.values(expected));
16187
16385
  if (!hasDeliveredResult(entries, expected) && !resultDeliveryEvidence.has(evidenceKey)) {
16386
+ const forwardedResultBindings = result.status === "completed" ? result.resultBindings ?? [] : [];
16387
+ if (forwardedResultBindings.length) {
16388
+ validateMessageFiles(forwardedResultBindings, runtime.cwd, "result");
16389
+ importResultBindings(pi, context, forwardedResultBindings, "result");
16390
+ entries = context.sessionManager.getEntries();
16391
+ }
16188
16392
  const elapsedMs = result.status === "completed" && Number.isFinite(runtime.startedAt) && runtime.startedAt !== void 0 && runtime.startedAt >= 0 && Number.isFinite(result.completedAt) && result.completedAt >= 0 && result.completedAt >= runtime.startedAt ? result.completedAt - runtime.startedAt : void 0;
16189
16393
  const completion = truncateModelText(
16190
16394
  result.status === "completed" ? result.text : result.error?.message ?? "Agent failed",
@@ -16229,6 +16433,9 @@ function createAgentController(pi, options2) {
16229
16433
  const content = [
16230
16434
  header,
16231
16435
  ...semanticResult ? [`Result ref: ${semanticResult.ref}`] : [],
16436
+ ...forwardedResultBindings.length ? [
16437
+ `Forwardable result evidence: ${forwardedResultBindings.map((binding) => binding.ref).join(", ")}`
16438
+ ] : [],
16232
16439
  ...retirement ? [retirement] : [],
16233
16440
  completion.content,
16234
16441
  ...status ? [status.content] : []
@@ -17649,7 +17856,7 @@ ${result.stderr ?? ""}`.trim(),
17649
17856
  options2.onChanged();
17650
17857
  }
17651
17858
  for (const promptPath of promptPaths)
17652
- if (statSync5(promptPath, { throwIfNoEntry: false }))
17859
+ if (statSync6(promptPath, { throwIfNoEntry: false }))
17653
17860
  unlinkSync8(promptPath);
17654
17861
  if (releaseClaim) releaseClaim();
17655
17862
  }
@@ -19052,6 +19259,11 @@ Do not overlap writers in a worktree or file-ownership boundary. For dependent
19052
19259
  work, pass reusable direct-agent result refs through \`files\`. Preserve
19053
19260
  canonical result:<request-id> refs already supplied as file evidence exactly
19054
19261
  when forwarding them.
19262
+ Before completing, a managed Agent may call attach_handoff({files}) to select
19263
+ verified semantic result refs for its ordinary final handoff to its direct
19264
+ owner. This is non-blocking selection, not a separate evidence transfer; a ref
19265
+ mentioned only in completion text is not forwardable. Use exact refs only, and
19266
+ do not select evidence unless the owner needs it.
19055
19267
  Do not silently broaden scope or make an unapproved scope, architecture,
19056
19268
  security, protocol, repository-boundary, product, or operational decision.
19057
19269
 
@@ -19141,6 +19353,7 @@ __export(managed_agent_runtime_exports, {
19141
19353
  readEvidencePage: () => readEvidencePage,
19142
19354
  registerManagedAgentActivityHandlers: () => registerManagedAgentActivityHandlers,
19143
19355
  registerManagedAgentAskOwnerTool: () => registerManagedAgentAskOwnerTool,
19356
+ registerManagedAgentAttachHandoffTool: () => registerManagedAgentAttachHandoffTool,
19144
19357
  registerManagedAgentContextHandlers: () => registerManagedAgentContextHandlers,
19145
19358
  registerManagedAgentInputHandlers: () => registerManagedAgentInputHandlers,
19146
19359
  registerManagedAgentResultCapture: () => registerManagedAgentResultCapture,
@@ -19154,7 +19367,7 @@ __export(managed_agent_runtime_exports, {
19154
19367
  sessionContextRetired: () => sessionContextRetired,
19155
19368
  validateManagedAgentIdentity: () => validateManagedAgentIdentity
19156
19369
  });
19157
- import { isAbsolute as isAbsolute5, resolve as resolve5 } from "node:path";
19370
+ import { isAbsolute as isAbsolute6, resolve as resolve5 } from "node:path";
19158
19371
  import { realpathSync as realpathSync4 } from "node:fs";
19159
19372
  import { buildSessionProjection as buildSessionProjection2 } from "@earendil-works/pi-coding-agent";
19160
19373
  import { contentText as contentText3 } from "@earendil-works/pi-ai";
@@ -19945,6 +20158,89 @@ function createManagedAgentAskOwnerHandler(options2) {
19945
20158
  };
19946
20159
  };
19947
20160
  }
20161
+ function handoffSelectionDetails(state, resultBindings) {
20162
+ return {
20163
+ version: 1,
20164
+ assignmentRequestId: state.activeRequestId,
20165
+ runId: state.runId,
20166
+ ownerSessionId: state.ownerSessionId,
20167
+ workspaceId: state.workspaceId,
20168
+ agentLabel: state.agentLabel,
20169
+ paneId: state.paneId,
20170
+ piSessionId: state.piSessionId,
20171
+ resultBindings: [...resultBindings]
20172
+ };
20173
+ }
20174
+ function latestHandoffSelection(ctx, state) {
20175
+ let selected;
20176
+ const expectedKeys = [
20177
+ "version",
20178
+ "assignmentRequestId",
20179
+ "runId",
20180
+ "ownerSessionId",
20181
+ "workspaceId",
20182
+ "agentLabel",
20183
+ "paneId",
20184
+ "piSessionId",
20185
+ "resultBindings"
20186
+ ];
20187
+ for (const entry of ctx.sessionManager.getBranch()) {
20188
+ const message = entry?.type === "message" ? entry.message : void 0;
20189
+ if (message?.role !== "toolResult" || message.toolName !== ATTACH_HANDOFF_TOOL || message.isError !== false)
20190
+ continue;
20191
+ const details = message.details;
20192
+ if (!details || typeof details !== "object" || details.assignmentRequestId !== state.activeRequestId)
20193
+ continue;
20194
+ if (Object.keys(details).length !== expectedKeys.length || Object.keys(details).some((key) => !expectedKeys.includes(key)) || details.version !== 1 || details.runId !== state.runId || details.ownerSessionId !== state.ownerSessionId || details.workspaceId !== state.workspaceId || details.agentLabel !== state.agentLabel || details.paneId !== state.paneId || details.piSessionId !== state.piSessionId || !Array.isArray(details.resultBindings) || !details.resultBindings.every(isResultBinding) || new Set(
20195
+ details.resultBindings.map((binding) => binding.ref)
20196
+ ).size !== details.resultBindings.length)
20197
+ throw new Error("Invalid or conflicting handoff selection metadata");
20198
+ selected = [...details.resultBindings];
20199
+ }
20200
+ return selected;
20201
+ }
20202
+ function verifyHandoffSelection(ctx, selected) {
20203
+ const resolved = resolveMessageFiles(
20204
+ ctx,
20205
+ selected.map((binding) => binding.ref),
20206
+ ATTACH_HANDOFF_TOOL
20207
+ );
20208
+ if (resolved.length !== selected.length || resolved.some(
20209
+ (binding, index) => !isResultBinding(binding) || !isDeepStrictEqual3(binding, selected[index])
20210
+ ))
20211
+ throw new Error("Selected result binding is unavailable on this branch");
20212
+ validateMessageFiles(
20213
+ resolved,
20214
+ ctx.cwd,
20215
+ ATTACH_HANDOFF_TOOL
20216
+ );
20217
+ return resolved;
20218
+ }
20219
+ function registerManagedAgentAttachHandoffTool(pi, execute) {
20220
+ pi.registerTool({
20221
+ name: ATTACH_HANDOFF_TOOL,
20222
+ label: "Attach handoff evidence",
20223
+ exposure: "model-only",
20224
+ promptSnippet: "Select reusable results for this assignment's final handoff",
20225
+ description: "Select verified semantic result references for your eventual completion to your direct owner. This is non-blocking and does not send evidence now. Use only exact result:<agent>#<index> references; text-only mentions do not grant access.",
20226
+ executionMode: "sequential",
20227
+ parameters: Type2.Object(
20228
+ {
20229
+ files: Type2.Array(
20230
+ Type2.String({
20231
+ minLength: 1,
20232
+ description: "Exact semantic result reference, such as result:scout#21."
20233
+ }),
20234
+ {
20235
+ description: "Semantic result references to select for the eventual completion; an empty list clears the selection."
20236
+ }
20237
+ )
20238
+ },
20239
+ { additionalProperties: false }
20240
+ ),
20241
+ execute
20242
+ });
20243
+ }
19948
20244
  function registerManagedAgentAskOwnerTool(pi, execute) {
19949
20245
  const files = Type2.Optional(
19950
20246
  Type2.Array(
@@ -20547,7 +20843,19 @@ function registerManagedAgentSettlementHandlers(pi, execution, options2) {
20547
20843
  const observation = execution.observation;
20548
20844
  const outcome = observation?.requestId === state.activeRequestId ? observation.outcome : void 0;
20549
20845
  const responseText = observation?.requestId === state.activeRequestId && observation.outcome === "completed" && observation.responseEntryId ? observation.responseText?.trim() ?? "" : "";
20550
- const completed = !aborted && outcome === "completed" && !!responseText;
20846
+ let completed = !aborted && outcome === "completed" && !!responseText;
20847
+ let resultBindings;
20848
+ let handoffSelectionError = false;
20849
+ if (completed) {
20850
+ try {
20851
+ const selected = latestHandoffSelection(ctx, state);
20852
+ if (selected?.length)
20853
+ resultBindings = verifyHandoffSelection(ctx, selected);
20854
+ } catch {
20855
+ completed = false;
20856
+ handoffSelectionError = true;
20857
+ }
20858
+ }
20551
20859
  const result = {
20552
20860
  version: 5,
20553
20861
  runId: state.runId,
@@ -20557,10 +20865,13 @@ function registerManagedAgentSettlementHandlers(pi, execution, options2) {
20557
20865
  agentLabel: state.agentLabel,
20558
20866
  paneId: state.paneId,
20559
20867
  status: completed ? "completed" : "failed",
20560
- ...completed ? { text: responseText } : {
20868
+ ...completed ? {
20869
+ text: responseText,
20870
+ ...resultBindings?.length ? { resultBindings } : {}
20871
+ } : {
20561
20872
  error: {
20562
- code: aborted ? "aborted" : outcome === "error" ? "execution_error" : "empty_result",
20563
- message: aborted ? "Agent execution was cancelled" : outcome === "error" ? "Agent model execution failed" : "Agent produced no assistant text"
20873
+ code: aborted ? "aborted" : handoffSelectionError || outcome === "error" ? "execution_error" : "empty_result",
20874
+ message: aborted ? "Agent execution was cancelled" : handoffSelectionError ? "Selected handoff evidence could not be verified" : outcome === "error" ? "Agent model execution failed" : "Agent produced no assistant text"
20564
20875
  }
20565
20876
  },
20566
20877
  contextUsage: ctx.getContextUsage(),
@@ -20598,9 +20909,10 @@ function registerManagedAgentSettlementHandlers(pi, execution, options2) {
20598
20909
  ...current,
20599
20910
  status: "failed",
20600
20911
  text: void 0,
20912
+ resultBindings: void 0,
20601
20913
  error: {
20602
20914
  code: "result_too_large",
20603
- message: "Agent assistant response exceeded the mailbox result limit"
20915
+ message: "Agent result exceeded the mailbox result limit"
20604
20916
  }
20605
20917
  };
20606
20918
  execution.resultWriteAttempts = 0;
@@ -20977,6 +21289,60 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
20977
21289
  controller.sessionTreeChanged(ctx, controller.sessionSignal());
20978
21290
  });
20979
21291
  }
21292
+ registerManagedAgentAttachHandoffTool(
21293
+ pi,
21294
+ async (_id, params, _signal, _update, ctx) => {
21295
+ const state = execution.assignment;
21296
+ if (!state?.activeRequestId || state.completedRequestId || execution.pendingResult)
21297
+ fail(
21298
+ "invalid_request",
21299
+ "There is no matching active assignment for handoff selection",
21300
+ ATTACH_HANDOFF_TOOL
21301
+ );
21302
+ const managed = managedAgentIdentity(ctx);
21303
+ const assignmentMatches = (current) => current.activeRequestId === state.activeRequestId && state.activeRequestId === managed.activeRequestId && sameManagedAgentIdentity(state, current);
21304
+ if (!assignmentMatches(managed))
21305
+ fail(
21306
+ "invalid_request",
21307
+ "There is no matching active assignment for handoff selection",
21308
+ ATTACH_HANDOFF_TOOL
21309
+ );
21310
+ if (!params.files.every((ref) => parseSemanticResultRef(ref)))
21311
+ fail(
21312
+ "invalid_request",
21313
+ "Handoff selection accepts semantic result references only",
21314
+ ATTACH_HANDOFF_TOOL
21315
+ );
21316
+ const resolved = resolveMessageFiles(
21317
+ ctx,
21318
+ params.files,
21319
+ ATTACH_HANDOFF_TOOL
21320
+ );
21321
+ if (resolved.some((binding) => !isResultBinding(binding)) || new Set(resolved.map((binding) => binding.ref)).size !== resolved.length)
21322
+ fail(
21323
+ "invalid_request",
21324
+ "Handoff selection contains invalid or duplicate result references",
21325
+ ATTACH_HANDOFF_TOOL
21326
+ );
21327
+ const bindings = verifyHandoffSelection(ctx, resolved);
21328
+ const latest = managedAgentIdentity(ctx);
21329
+ if (!assignmentMatches(latest) || latest.activeRequestId !== state.activeRequestId)
21330
+ fail(
21331
+ "invalid_request",
21332
+ "Managed-agent assignment changed during handoff selection",
21333
+ ATTACH_HANDOFF_TOOL
21334
+ );
21335
+ return {
21336
+ content: [
21337
+ {
21338
+ type: "text",
21339
+ text: bindings.length ? `Selected ${bindings.length} semantic result reference${bindings.length === 1 ? "" : "s"} for your eventual completion. This does not send evidence now.` : "Cleared the selected semantic result references for your eventual completion."
21340
+ }
21341
+ ],
21342
+ details: handoffSelectionDetails(state, bindings)
21343
+ };
21344
+ }
21345
+ );
20980
21346
  registerManagedAgentAskOwnerTool(
20981
21347
  pi,
20982
21348
  createManagedAgentAskOwnerHandler({
@@ -21303,7 +21669,7 @@ function allowedAgentDefinitionsFromEnv() {
21303
21669
  function managedAgentEnvironmentError() {
21304
21670
  const e = process.env;
21305
21671
  if (!e.PI_HERDSMAN_MAILBOX) return "PI_HERDSMAN_MAILBOX missing";
21306
- if (!isAbsolute5(e.PI_HERDSMAN_MAILBOX))
21672
+ if (!isAbsolute6(e.PI_HERDSMAN_MAILBOX))
21307
21673
  return "PI_HERDSMAN_MAILBOX is not absolute";
21308
21674
  if (!validId(e.PI_HERDSMAN_RUN_ID)) return "PI_HERDSMAN_RUN_ID invalid";
21309
21675
  if (!validId(e.PI_HERDSMAN_OWNER_SESSION_ID))
@@ -21641,7 +22007,7 @@ function registerManagedAgentSessionStartHandler(pi, execution, options2) {
21641
22007
  }
21642
22008
  });
21643
22009
  }
21644
- var DELEGATING_AGENT_ROLE_CHARTER, AGENT_REQUIRED_EVIDENCE_ENTRY, READ_EVIDENCE_MAX_BYTES, READ_EVIDENCE_MAX_LINES, SESSION_REQUEST_ID, EVIDENCE_CONTINUATION_RESERVE, AGENT_LABEL_PATTERN2, RESERVED_PREFIX, AGENT_CONTEXT_RETIRED_ENTRY, CONTEXT_RETIREMENT_INSTRUCTION, CONTEXT_RETIREMENT_REMINDER;
22010
+ var DELEGATING_AGENT_ROLE_CHARTER, AGENT_REQUIRED_EVIDENCE_ENTRY, READ_EVIDENCE_MAX_BYTES, READ_EVIDENCE_MAX_LINES, SESSION_REQUEST_ID, EVIDENCE_CONTINUATION_RESERVE, AGENT_LABEL_PATTERN2, RESERVED_PREFIX, AGENT_CONTEXT_RETIRED_ENTRY, CONTEXT_RETIREMENT_INSTRUCTION, CONTEXT_RETIREMENT_REMINDER, ATTACH_HANDOFF_TOOL;
21645
22011
  var init_managed_agent_runtime = __esm({
21646
22012
  "extension/managed-agent-runtime.ts"() {
21647
22013
  init_mailbox();
@@ -21670,6 +22036,7 @@ ${FILE_HANDOFF_GUIDANCE}`;
21670
22036
  AGENT_CONTEXT_RETIRED_ENTRY = "pi-herdsman-agent-context-retired";
21671
22037
  CONTEXT_RETIREMENT_INSTRUCTION = "Context pressure has retired this session. Do not start new work or new agents. Finish the current coherent operation at the next safe point. Avoid nonessential tool calls and validation; perform only what is needed for a reliable handoff. Resolve already-running dependent work, then complete this assignment with a self-contained handoff covering completed work, current state, relevant files, validation performed, unresolved issues, and exact next steps. This session will not be continued or forked.";
21672
22038
  CONTEXT_RETIREMENT_REMINDER = "This session is retired. Do not start new work or agents. Finish the current assignment and return a self-contained handoff.";
22039
+ ATTACH_HANDOFF_TOOL = "attach_handoff";
21673
22040
  }
21674
22041
  });
21675
22042
 
@@ -21681,7 +22048,7 @@ import {
21681
22048
  getSelectListTheme as getSelectListTheme2,
21682
22049
  SessionManager as SessionManager2
21683
22050
  } from "@earendil-works/pi-coding-agent";
21684
- import { readFileSync as readFileSync13, statSync as statSync7, unlinkSync as unlinkSync12 } from "node:fs";
22051
+ import { readFileSync as readFileSync13, statSync as statSync8, unlinkSync as unlinkSync12 } from "node:fs";
21685
22052
  import { basename as basename9, dirname as dirname9, resolve as resolve7 } from "node:path";
21686
22053
  import { setTimeout as delay2 } from "node:timers/promises";
21687
22054
  import { fileURLToPath as fileURLToPath3 } from "node:url";
@@ -21689,7 +22056,7 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
21689
22056
  // package.json
21690
22057
  var package_default = {
21691
22058
  name: "pi-herdsman",
21692
- version: "0.34.0",
22059
+ version: "0.35.0",
21693
22060
  type: "module",
21694
22061
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
21695
22062
  license: "Apache-2.0",
@@ -21852,8 +22219,8 @@ import { getSelectListTheme } from "@earendil-works/pi-coding-agent";
21852
22219
  import { visibleWidth as visibleWidth2 } from "@earendil-works/pi-tui";
21853
22220
  import { contentText as contentText4, getSupportedThinkingLevels } from "@earendil-works/pi-ai";
21854
22221
  import { createHash as createHash12, randomUUID as randomUUID14 } from "node:crypto";
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";
22222
+ import { lstatSync as lstatSync6, realpathSync as realpathSync5, statSync as statSync7, unlinkSync as unlinkSync11 } from "node:fs";
22223
+ import { dirname as dirname8, isAbsolute as isAbsolute7, join as join12, resolve as resolve6 } from "node:path";
21857
22224
 
21858
22225
  // extension/peer-transport.ts
21859
22226
  init_lock();
@@ -24132,7 +24499,7 @@ function registerLeadRuntime(pi, options2) {
24132
24499
  options2.supervisionHost.contextType
24133
24500
  ),
24134
24501
  persistedTranscriptReady: (target) => persistedTranscriptReady(target, (path) => {
24135
- const file2 = (options2.supervisionHost.statSync ?? statSync6)(path, {
24502
+ const file2 = (options2.supervisionHost.statSync ?? statSync7)(path, {
24136
24503
  throwIfNoEntry: false
24137
24504
  });
24138
24505
  return !!file2?.isFile() && file2.size > 0;
@@ -25483,7 +25850,7 @@ function createLeadSupervisionRuntime(host) {
25483
25850
  manager.workspaceId,
25484
25851
  ctx.signal
25485
25852
  );
25486
- if (group.repoKey !== manager.repoKey || group.primaryWorkspaceId !== manager.workspaceId)
25853
+ if (group.repoKey !== manager.repoKey)
25487
25854
  throw new Error("Manager workspace is not the assigned project");
25488
25855
  const incompatible = [];
25489
25856
  const [leads, topology] = await Promise.all([
@@ -25501,7 +25868,7 @@ function createLeadSupervisionRuntime(host) {
25501
25868
  await host.reconcileProjectAssignments?.(
25502
25869
  ctx,
25503
25870
  group.repoKey,
25504
- group.primaryWorkspaceId,
25871
+ manager.workspaceId,
25505
25872
  topology.source.source_checkout_path
25506
25873
  );
25507
25874
  const assignments = host.listProjectAssignments(
@@ -25645,7 +26012,41 @@ function createLeadSupervisionRuntime(host) {
25645
26012
  const sessions = new Set(assignments.map((assignment) => assignment.id));
25646
26013
  if (sessions.size !== assignments.length)
25647
26014
  throw new Error("Multiple project assignments match a Lead session");
25648
- return snapshot2.leads.filter((lead) => scope.workspaceIds.includes(lead.workspaceId)).map((lead) => ({
26015
+ const repoManagers = host.listManagerDescriptors(host.supervisionRuntime()).filter((candidate) => candidate.repoKey === manager.repoKey);
26016
+ const ordinarySupervisionAvailable = repoManagers.length === 1 && host.sameManagerDescriptor(repoManagers[0], manager);
26017
+ const leads = await Promise.all(
26018
+ snapshot2.leads.map(async (lead) => {
26019
+ try {
26020
+ const descriptor = {
26021
+ piSessionId: lead.lead,
26022
+ piSessionFile: lead.piSessionFile,
26023
+ paneId: lead.paneId,
26024
+ tabId: lead.tabId,
26025
+ workspaceId: lead.workspaceId
26026
+ };
26027
+ const agent = await host.remoteChiefAgent(ctx, descriptor);
26028
+ if (typeof agent?.cwd !== "string" || !agent.cwd) return void 0;
26029
+ const repository = await localRepositoryScope(
26030
+ host.pi,
26031
+ { ...ctx, cwd: agent.cwd },
26032
+ lead.workspaceId,
26033
+ ctx.signal
26034
+ );
26035
+ if (repository.repoKey !== manager.repoKey) return void 0;
26036
+ const current = await host.remoteChiefAgent(ctx, descriptor);
26037
+ if (!current || current.cwd !== agent.cwd) return void 0;
26038
+ return lead;
26039
+ } catch (error2) {
26040
+ if (ctx.signal?.aborted) throw ctx.signal.reason;
26041
+ if (error2 instanceof Error && error2.name === "AbortError")
26042
+ throw error2;
26043
+ return void 0;
26044
+ }
26045
+ })
26046
+ );
26047
+ return leads.filter((lead) => lead !== void 0).filter(
26048
+ (lead) => sessions.has(lead.lead) || ordinarySupervisionAvailable
26049
+ ).map((lead) => ({
25649
26050
  ...lead,
25650
26051
  relationship: sessions.has(lead.lead) ? "assigned" : "supervised"
25651
26052
  }));
@@ -26381,7 +26782,7 @@ function createLeadSupervisionRuntime(host) {
26381
26782
  );
26382
26783
  const entries = assignment.requiredEvidence ?? [];
26383
26784
  if (!entries.length) {
26384
- ctx.ui.notify("This project has no required evidence.", "info");
26785
+ ctx.ui.notify("This assignment has no required evidence.", "info");
26385
26786
  } else {
26386
26787
  const selectedEvidence = await uiActions.selectMenu(
26387
26788
  ctx,
@@ -27341,15 +27742,23 @@ function createLeadProjectRuntime(host) {
27341
27742
  manager.workspaceId,
27342
27743
  signal
27343
27744
  );
27344
- if (group.repoKey !== manager.repoKey || group.primaryWorkspaceId !== manager.workspaceId)
27745
+ if (group.repoKey !== manager.repoKey)
27345
27746
  throw new Error("Manager worktree group is not authoritative");
27747
+ const localScope = await localRepositoryScope(
27748
+ host.pi,
27749
+ ctx,
27750
+ manager.workspaceId,
27751
+ signal
27752
+ );
27753
+ if (!localScope.isPrimary || localScope.repoKey !== manager.repoKey)
27754
+ throw new Error("Manager checkout is not the verified primary checkout");
27346
27755
  const topology = await host.runHerdr(
27347
27756
  host.pi,
27348
27757
  ctx,
27349
27758
  ["worktree", "list", "--workspace", manager.workspaceId],
27350
27759
  { signal }
27351
27760
  );
27352
- if (topology?.source?.source_workspace_id !== manager.workspaceId || topology?.source?.repo_key !== manager.repoKey || typeof topology?.source?.source_checkout_path !== "string" || !Array.isArray(topology?.worktrees))
27761
+ if (topology?.source?.repo_key !== manager.repoKey || typeof topology?.source?.source_checkout_path !== "string" || realpathSync5(topology.source.source_checkout_path) !== localScope.checkoutPath || !Array.isArray(topology?.worktrees))
27353
27762
  throw new Error("Herdr worktree topology is not authoritative");
27354
27763
  const assignments = host.listProjectAssignments(host.supervisionRuntime(), manager.repoKey).filter((assignment2) => assignment2.branch === branch);
27355
27764
  if (assignments.length !== 1)
@@ -27903,13 +28312,21 @@ function createLeadProjectRuntime(host) {
27903
28312
  branch
27904
28313
  );
27905
28314
  if (!before) throw new Error("No project assignment exists on this branch");
28315
+ const localScope = await localRepositoryScope(
28316
+ host.pi,
28317
+ ctx,
28318
+ initialManager.workspaceId,
28319
+ operationSignal
28320
+ );
28321
+ if (!localScope.isPrimary || localScope.repoKey !== initialManager.repoKey)
28322
+ throw new Error("Manager checkout is not the verified primary checkout");
27906
28323
  const initialTopology = await host.runHerdr(
27907
28324
  host.pi,
27908
28325
  ctx,
27909
28326
  ["worktree", "list", "--workspace", initialManager.workspaceId],
27910
28327
  { signal: operationSignal }
27911
28328
  );
27912
- if (initialTopology?.source?.repo_key !== initialManager.repoKey || initialTopology?.source?.source_workspace_id !== initialManager.workspaceId || typeof initialTopology?.source?.source_checkout_path !== "string")
28329
+ if (initialTopology?.source?.repo_key !== initialManager.repoKey || typeof initialTopology?.source?.source_checkout_path !== "string" || realpathSync5(initialTopology.source.source_checkout_path) !== localScope.checkoutPath)
27913
28330
  throw new Error("Herdr worktree topology is unavailable or inconsistent");
27914
28331
  await host.reconcileProjectAssignments(
27915
28332
  ctx,
@@ -27953,15 +28370,25 @@ function createLeadProjectRuntime(host) {
27953
28370
  manager.workspaceId,
27954
28371
  operationSignal
27955
28372
  );
27956
- if (group.repoKey !== manager.repoKey || group.primaryWorkspaceId !== manager.workspaceId)
28373
+ if (group.repoKey !== manager.repoKey)
27957
28374
  throw new Error("Manager worktree group is not authoritative");
28375
+ const localScope2 = await localRepositoryScope(
28376
+ host.pi,
28377
+ ctx,
28378
+ manager.workspaceId,
28379
+ operationSignal
28380
+ );
28381
+ if (!localScope2.isPrimary || localScope2.repoKey !== manager.repoKey)
28382
+ throw new Error(
28383
+ "Manager checkout is not the verified primary checkout"
28384
+ );
27958
28385
  const topology = await host.runHerdr(
27959
28386
  host.pi,
27960
28387
  ctx,
27961
28388
  ["worktree", "list", "--workspace", manager.workspaceId],
27962
28389
  { signal: operationSignal }
27963
28390
  );
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(
28391
+ if (topology?.source?.repo_key !== manager.repoKey || typeof topology?.source?.source_checkout_path !== "string" || realpathSync5(topology.source.source_checkout_path) !== localScope2.checkoutPath || !Array.isArray(topology.worktrees) || topology.worktrees.some(
27965
28392
  (worktree) => typeof worktree?.path !== "string" || !worktree.path || worktree.branch !== void 0 && typeof worktree.branch !== "string"
27966
28393
  ))
27967
28394
  throw new Error(
@@ -28123,7 +28550,7 @@ Type forget ${branch} to confirm.`,
28123
28550
  manager.workspaceId,
28124
28551
  ctx.signal
28125
28552
  );
28126
- if (group.repoKey !== manager.repoKey || group.primaryWorkspaceId !== manager.workspaceId)
28553
+ if (group.repoKey !== manager.repoKey)
28127
28554
  throw new Error("Manager worktree group is not authoritative");
28128
28555
  if (enabled) {
28129
28556
  const answer = await ctx.ui.input(
@@ -28153,7 +28580,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28153
28580
  manager.workspaceId,
28154
28581
  ctx.signal
28155
28582
  );
28156
- if (group.repoKey !== manager.repoKey || group.primaryWorkspaceId !== manager.workspaceId)
28583
+ if (group.repoKey !== manager.repoKey)
28157
28584
  throw new Error("Manager worktree group is not authoritative");
28158
28585
  const current = await host.currentManager(ctx);
28159
28586
  if (!current || !host.sameManagerDescriptor(current, manager))
@@ -28281,13 +28708,23 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28281
28708
  manager
28282
28709
  ))
28283
28710
  throw sourceError;
28711
+ const localScope = await localRepositoryScope(
28712
+ host.pi,
28713
+ ctx,
28714
+ manager.workspaceId,
28715
+ operationSignal
28716
+ );
28717
+ if (!localScope.isPrimary || localScope.repoKey !== manager.repoKey)
28718
+ throw new Error(
28719
+ "Manager checkout is not the verified primary checkout"
28720
+ );
28284
28721
  const topology = await host.runHerdr(
28285
28722
  host.pi,
28286
28723
  ctx,
28287
28724
  ["worktree", "list", "--workspace", manager.workspaceId],
28288
28725
  { signal: operationSignal }
28289
28726
  );
28290
- if (topology?.source?.source_workspace_id !== manager.workspaceId || topology?.source?.repo_key !== manager.repoKey || typeof topology?.source?.source_checkout_path !== "string")
28727
+ if (topology?.source?.repo_key !== manager.repoKey || typeof topology?.source?.source_checkout_path !== "string" || realpathSync5(topology.source.source_checkout_path) !== localScope.checkoutPath)
28291
28728
  throw sourceError;
28292
28729
  const targetPath2 = topology.source.source_checkout_path;
28293
28730
  const sourceRef = await host.pi.exec(
@@ -28445,7 +28882,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28445
28882
  if (probe.code !== 0 || probe.killed || probe.stderr?.trim())
28446
28883
  throw new Error("Git operation state is unverifiable");
28447
28884
  try {
28448
- statSync6(resolve6(path, String(probe.stdout ?? "").trim()));
28885
+ statSync7(resolve6(path, String(probe.stdout ?? "").trim()));
28449
28886
  throw new Error(`Git operation ${state} is in progress`);
28450
28887
  } catch (error2) {
28451
28888
  if (error2.code !== "ENOENT" && !(error2 instanceof Error && error2.message.startsWith("Git operation ")))
@@ -28688,7 +29125,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28688
29125
  continue;
28689
29126
  }
28690
29127
  try {
28691
- statSync6(
29128
+ statSync7(
28692
29129
  resolve6(targetPath, String(path.stdout ?? "").trim())
28693
29130
  );
28694
29131
  operationStates.push(state);
@@ -28822,30 +29259,28 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28822
29259
  }
28823
29260
  };
28824
29261
  const activateProjectLeadLocked = async (operation, ctx, signal) => {
28825
- const operationName = operation.action === "resume" ? "resume_project" : "delegate_project";
29262
+ const operationName = operation.action === "resume" ? "resume_work" : "delegate_work";
28826
29263
  const manager = await currentManager(ctx);
28827
29264
  if (!manager || !leadRuntime.managerLease || !sameManagerDescriptor2(manager, leadRuntime.managerLease.descriptor))
28828
29265
  throw new Error("Manager lease is no longer active");
28829
- const group = await worktreeGroupScope2(
29266
+ const localScope = await localRepositoryScope(
28830
29267
  pi,
28831
29268
  ctx,
28832
29269
  manager.workspaceId,
28833
29270
  signal
28834
29271
  );
28835
- if (group.repoKey !== manager.repoKey || group.primaryWorkspaceId !== manager.workspaceId)
28836
- throw new Error(
28837
- "Manager workspace is not the primary workspace of its Herdr worktree group"
28838
- );
28839
- const primaryWorkspaceId = group.primaryWorkspaceId;
29272
+ if (!localScope.isPrimary || localScope.repoKey !== manager.repoKey)
29273
+ throw new Error("Manager checkout is not the verified primary checkout");
29274
+ const primaryWorkspaceId = manager.workspaceId;
28840
29275
  const runtime = supervisionRuntime3();
28841
29276
  const branch = operation.branch;
28842
29277
  const topology = await runHerdr2(
28843
29278
  pi,
28844
29279
  ctx,
28845
- ["worktree", "list", "--workspace", primaryWorkspaceId],
29280
+ ["worktree", "list", "--cwd", localScope.checkoutPath],
28846
29281
  { signal }
28847
29282
  );
28848
- if (topology?.source?.source_workspace_id !== primaryWorkspaceId || topology?.source?.repo_key !== manager.repoKey || !Array.isArray(topology?.worktrees))
29283
+ if (topology?.source?.repo_key !== manager.repoKey || !Array.isArray(topology?.worktrees))
28849
29284
  throw new Error("Herdr worktree topology is not authoritative");
28850
29285
  if (operation.action === "resume")
28851
29286
  await host.reconcileProjectAssignments(
@@ -28872,11 +29307,11 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28872
29307
  throw new Error("Project assignment belongs to another repository");
28873
29308
  if (operation.action === "delegate" && currentAssignment)
28874
29309
  throw new Error(
28875
- `Work already exists on ${branch}; resume it with resume_project.`
29310
+ `Work already exists on ${branch}; resume it with resume_work.`
28876
29311
  );
28877
29312
  if (operation.action === "resume" && !currentAssignment)
28878
29313
  throw new Error(
28879
- `No existing work was found on ${branch}; start it with delegate_project and a task.`
29314
+ `No existing work was found on ${branch}; start it with delegate_work and a task.`
28880
29315
  );
28881
29316
  const presentationTask = operation.action === "resume" ? projectTaskSummary(currentAssignment.text) : void 0;
28882
29317
  const id = operation.action === "resume" ? currentAssignment.id : operation.id;
@@ -28978,7 +29413,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28978
29413
  const suppliedFiles = resolveMessageFiles2(
28979
29414
  ctx,
28980
29415
  operation.files,
28981
- "delegate_project"
29416
+ "delegate_work"
28982
29417
  );
28983
29418
  const projectBrief = persistRequiredEvidenceSnapshot(
28984
29419
  id,
@@ -28988,7 +29423,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28988
29423
  const attachedEvidence = [];
28989
29424
  for (const file2 of suppliedFiles)
28990
29425
  attachedEvidence.push(
28991
- ...typeof file2 === "string" ? persistRequiredTextFiles(id, [file2], ctx.cwd, "delegate_project") : [{ id: randomUUID14(), name: file2.ref, result: file2 }]
29426
+ ...typeof file2 === "string" ? persistRequiredTextFiles(id, [file2], ctx.cwd, "delegate_work") : [{ id: randomUUID14(), name: file2.ref, result: file2 }]
28992
29427
  );
28993
29428
  const requiredEvidence = [projectBrief, ...attachedEvidence];
28994
29429
  const prepared = prepareMessageInput2(
@@ -28997,7 +29432,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28997
29432
  (evidence) => "path" in evidence ? [evidence.path] : [evidence.result]
28998
29433
  ),
28999
29434
  ctx.cwd,
29000
- "delegate_project",
29435
+ "delegate_work",
29001
29436
  "Task",
29002
29437
  {
29003
29438
  inlineLimitBytes: limits.inline.bytes,
@@ -29028,6 +29463,15 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29028
29463
  }
29029
29464
  const promptPaths = [];
29030
29465
  try {
29466
+ const currentScope = await localRepositoryScope(
29467
+ pi,
29468
+ ctx,
29469
+ manager.workspaceId,
29470
+ signal
29471
+ );
29472
+ const current = await currentManager(ctx);
29473
+ if (!currentScope.isPrimary || currentScope.repoKey !== manager.repoKey || currentScope.checkoutPath !== localScope.checkoutPath || !current || !sameManagerDescriptor2(current, manager))
29474
+ throw new Error("Manager identity changed before project activation");
29031
29475
  let workspaceId;
29032
29476
  let paneId;
29033
29477
  let tabId;
@@ -29053,8 +29497,8 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29053
29497
  [
29054
29498
  "worktree",
29055
29499
  "open",
29056
- "--workspace",
29057
- primaryWorkspaceId,
29500
+ "--cwd",
29501
+ localScope.checkoutPath,
29058
29502
  "--branch",
29059
29503
  assignment.branch,
29060
29504
  "--no-focus"
@@ -29076,8 +29520,8 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29076
29520
  const args = [
29077
29521
  "worktree",
29078
29522
  "create",
29079
- "--workspace",
29080
- primaryWorkspaceId,
29523
+ "--cwd",
29524
+ localScope.checkoutPath,
29081
29525
  "--branch",
29082
29526
  assignment.branch,
29083
29527
  "--no-focus"
@@ -29113,11 +29557,11 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29113
29557
  timeout: 1e4
29114
29558
  })
29115
29559
  ]);
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)
29560
+ if (common.code !== 0 || common.killed || common.stderr?.trim() || branchResult.code !== 0 || branchResult.killed || branchResult.stderr?.trim() || !isAbsolute7(String(common.stdout ?? "").trim()) || realpathSync5(String(common.stdout).trim()) !== realpathSync5(manager.repoKey) || String(branchResult.stdout ?? "").trim() !== assignment.branch)
29117
29561
  throw new Error(
29118
29562
  "Herdr checkout does not match the assigned repository and branch"
29119
29563
  );
29120
- if (!isAbsolute6(cwd) || workspaceId === primaryWorkspaceId || realpathSync5(cwd) === realpathSync5(topology.source.source_checkout_path) || matchingWorktrees.length === 1 && realpathSync5(cwd) !== realpathSync5(matchingWorktrees[0].path))
29564
+ if (!isAbsolute7(cwd) || workspaceId === primaryWorkspaceId || realpathSync5(cwd) === realpathSync5(topology.source.source_checkout_path) || matchingWorktrees.length === 1 && realpathSync5(cwd) !== realpathSync5(matchingWorktrees[0].path))
29121
29565
  throw new Error(
29122
29566
  "Herdr checkout is not the verified linked project worktree"
29123
29567
  );
@@ -29133,7 +29577,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29133
29577
  () => {
29134
29578
  if (readProjectAssignment2(runtime, manager.repoKey, assignment.branch))
29135
29579
  throw new Error(
29136
- `Work already exists on ${assignment.branch}; resume it with resume_project.`
29580
+ `Work already exists on ${assignment.branch}; resume it with resume_work.`
29137
29581
  );
29138
29582
  writeProjectAssignment2(runtime, assignment);
29139
29583
  },
@@ -29429,7 +29873,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29429
29873
  throw error2;
29430
29874
  } finally {
29431
29875
  for (const promptPath of promptPaths)
29432
- if (statSync6(promptPath, { throwIfNoEntry: false }))
29876
+ if (statSync7(promptPath, { throwIfNoEntry: false }))
29433
29877
  unlinkSync11(promptPath);
29434
29878
  }
29435
29879
  };
@@ -29660,7 +30104,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29660
30104
  const currentLead2 = (await directReports(ctx)).find(
29661
30105
  (candidate) => reportSession(candidate) === params.session
29662
30106
  );
29663
- if (!currentAuthority || currentAuthority.leaseId !== authority.leaseId || !currentLead2 || !sameLeadIdentity(currentLead2, lead) || !currentLead2.availableActions.includes("inspect"))
30107
+ if (!currentAuthority || currentAuthority.leaseId !== authority.leaseId || !currentLead2 || !sameLeadIdentity(currentLead2, lead) || currentLead2.relationship !== lead.relationship || !currentLead2.availableActions.includes("inspect"))
29664
30108
  throw new Error("Lead changed during inspection");
29665
30109
  return result({
29666
30110
  ok: true,
@@ -29837,7 +30281,9 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29837
30281
  };
29838
30282
  const updateAssignmentEvidence = async (_id, params, _signal, _update, ctx, onPersisted) => {
29839
30283
  if (host.activeRole() !== "manager")
29840
- throw new Error("Only the Manager can update project required evidence");
30284
+ throw new Error(
30285
+ "Only the Manager can update assignment required evidence"
30286
+ );
29841
30287
  if (!params.branch?.trim())
29842
30288
  throw new Error("Manager must provide the exact assigned project branch");
29843
30289
  const manager = await host.currentManager(ctx);
@@ -29852,7 +30298,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29852
30298
  manager.workspaceId,
29853
30299
  ctx.signal
29854
30300
  );
29855
- if (scope.repoKey !== manager.repoKey || scope.primaryWorkspaceId !== manager.workspaceId)
30301
+ if (scope.repoKey !== manager.repoKey)
29856
30302
  throw new Error("Manager workspace authority could not be verified");
29857
30303
  const assignment = host.readProjectAssignment(
29858
30304
  host.supervisionRuntime(),
@@ -29899,7 +30345,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
29899
30345
  currentManager2.workspaceId,
29900
30346
  ctx.signal
29901
30347
  );
29902
- if (currentScope.repoKey !== assignment.repoKey || currentScope.primaryWorkspaceId !== currentManager2.workspaceId)
30348
+ if (currentScope.repoKey !== assignment.repoKey)
29903
30349
  throw new Error(
29904
30350
  "Manager workspace authority changed before required evidence was updated"
29905
30351
  );
@@ -30021,7 +30467,7 @@ ${(updated.requiredEvidence ?? []).map((entry) => `- ${entry.id}: ${entry.name}`
30021
30467
  };
30022
30468
  const inspectRequiredEvidence = async (branch, ctx) => {
30023
30469
  if (host.activeRole() !== "manager")
30024
- throw new Error("Only the Manager can inspect project requirements");
30470
+ throw new Error("Only the Manager can inspect assignment requirements");
30025
30471
  const manager = await host.currentManager(ctx);
30026
30472
  const lease = host.managerLease();
30027
30473
  if (!manager || !lease || host.leadRuntime.roleSuspended || !host.sameManagerDescriptor(manager, lease.descriptor))
@@ -30036,7 +30482,7 @@ ${(updated.requiredEvidence ?? []).map((entry) => `- ${entry.id}: ${entry.name}`
30036
30482
  };
30037
30483
  const removeRequiredEvidence = async (branch, id, expectedAssignment, ctx) => {
30038
30484
  if (host.activeRole() !== "manager")
30039
- throw new Error("Only the Manager can remove project requirements");
30485
+ throw new Error("Only the Manager can remove assignment requirements");
30040
30486
  await updateAssignmentEvidence(
30041
30487
  "manager-required-evidence",
30042
30488
  {
@@ -30702,6 +31148,7 @@ function createLeadCoordinationRuntime(host) {
30702
31148
  latestCustomMessageText(ctx, supervisorStateType)
30703
31149
  );
30704
31150
  };
31151
+ const maxRemoteDiagnostics2 = 20;
30705
31152
  const remotePeerRoutes = /* @__PURE__ */ new Map();
30706
31153
  const ambiguousRemoteSessions = /* @__PURE__ */ new Set();
30707
31154
  const lastPeerCorrespondenceErrors = /* @__PURE__ */ new Map();
@@ -30982,11 +31429,26 @@ ${conflicts.map((binding) => `${binding.ref} \u2192 ${binding.canonicalRef}`).jo
30982
31429
  workspace_label: record2.workspaceLabel ?? ""
30983
31430
  });
30984
31431
  }
30985
- const unavailableMachines = [];
31432
+ const remoteDiagnostics = [];
31433
+ let remoteDiagnosticsOmitted = 0;
31434
+ const addRemoteDiagnostic = (diagnostic) => {
31435
+ if (remoteDiagnostics.length < maxRemoteDiagnostics2)
31436
+ remoteDiagnostics.push(diagnostic);
31437
+ else remoteDiagnosticsOmitted++;
31438
+ };
31439
+ const diagnosticLabel = (value2, fallback) => {
31440
+ const text = typeof value2 === "string" ? value2.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, " ").replace(/\s+/gu, " ").trim() : "";
31441
+ if (!text) return fallback;
31442
+ const characters = Array.from(text);
31443
+ return characters.length > 80 ? `${characters.slice(0, 79).join("")}\u2026` : text;
31444
+ };
31445
+ const diagnosticBuild = (build) => diagnosticLabel(formatRuntimeBuild(build), "unknown");
30986
31446
  const localPeerSessions = new Set(peers.map((peer) => peer.session));
30987
31447
  const discoveredRemotePeerRoutes = new Map(remotePeerRoutes);
30988
31448
  const previousAmbiguousSessions = new Set(ambiguousRemoteSessions);
30989
31449
  const discoveredAmbiguousSessions = /* @__PURE__ */ new Set();
31450
+ let machineListingFailed = false;
31451
+ let machineDiscoveryIncomplete = false;
30990
31452
  if (remoteDiscoveryEligible) {
30991
31453
  let machines;
30992
31454
  let machineListingSucceeded = false;
@@ -30995,7 +31457,9 @@ ${conflicts.map((binding) => `${binding.ref} \u2192 ${binding.canonicalRef}`).jo
30995
31457
  machineListingSucceeded = true;
30996
31458
  } catch {
30997
31459
  machines = [];
30998
- unavailableMachines.push("saved machines");
31460
+ machineListingFailed = true;
31461
+ machineDiscoveryIncomplete = true;
31462
+ addRemoteDiagnostic({ reason: "machine_list_failed" });
30999
31463
  }
31000
31464
  if (machineListingSucceeded) {
31001
31465
  const listedMachines = new Map(
@@ -31015,7 +31479,11 @@ ${conflicts.map((binding) => `${binding.ref} \u2192 ${binding.canonicalRef}`).jo
31015
31479
  for (const machine of machines) {
31016
31480
  if (signal?.aborted) break;
31017
31481
  if (!machine.reachable) {
31018
- unavailableMachines.push(machine.label);
31482
+ machineDiscoveryIncomplete = true;
31483
+ addRemoteDiagnostic({
31484
+ machine: diagnosticLabel(machine.label, "machine"),
31485
+ reason: "herdr_not_reachable"
31486
+ });
31019
31487
  continue;
31020
31488
  }
31021
31489
  let identityEstablished = false;
@@ -31023,24 +31491,51 @@ ${conflicts.map((binding) => `${binding.ref} \u2192 ${binding.canonicalRef}`).jo
31023
31491
  const snapshot = await probePeerEndpoint(machine, signal);
31024
31492
  if (signal?.aborted) break;
31025
31493
  identityEstablished = true;
31494
+ const ordinaryLeadScanIncomplete = activeRole() === "lead" && snapshot.ordinaryLeadsComplete !== true;
31495
+ if (ordinaryLeadScanIncomplete) {
31496
+ machineDiscoveryIncomplete = true;
31497
+ addRemoteDiagnostic({
31498
+ machine: diagnosticLabel(machine.label, "machine"),
31499
+ reason: "eligibility_unverified"
31500
+ });
31501
+ }
31026
31502
  for (const [session, route] of discoveredRemotePeerRoutes)
31027
- if (route.machine.id === machine.id)
31503
+ if (route.machine.id === machine.id && (!ordinaryLeadScanIncomplete || route.role !== "lead"))
31028
31504
  discoveredRemotePeerRoutes.delete(session);
31505
+ if (ordinaryLeadScanIncomplete)
31506
+ for (const [session, route] of remotePeerRoutes) {
31507
+ if (route.machine.id !== machine.id || route.role !== "lead")
31508
+ continue;
31509
+ if (discoveredRemotePeerRoutes.has(session)) {
31510
+ discoveredAmbiguousSessions.add(session);
31511
+ discoveredRemotePeerRoutes.delete(session);
31512
+ } else discoveredRemotePeerRoutes.set(session, route);
31513
+ }
31029
31514
  for (const remote of snapshot.peers) {
31030
31515
  const remoteRole = activeRole();
31031
31516
  if (remote.role !== remoteRole || remoteRole === "lead" && (snapshot.ordinaryLeadsComplete !== true || remote.sessionKind !== "ordinary") || remote.piSessionId === self || localPeerSessions.has(remote.piSessionId) || !remote.claim?.id || discoveredAmbiguousSessions.has(remote.piSessionId))
31032
31517
  continue;
31033
- if (remote.build) {
31034
- try {
31035
- requireCompatibleBuild2(
31036
- HERDSMAN_BUILD2,
31037
- remote.build,
31038
- "peer_message",
31039
- `remote ${remoteRole} ${remote.piSessionId}`
31040
- );
31041
- } catch {
31042
- continue;
31043
- }
31518
+ const peerHint = diagnosticLabel(
31519
+ remote.name,
31520
+ `peer-${remote.piSessionId.slice(0, 8)}`
31521
+ );
31522
+ if (!isRuntimeBuild(remote.build)) {
31523
+ addRemoteDiagnostic({
31524
+ machine: diagnosticLabel(machine.label, "machine"),
31525
+ reason: "build_unverified",
31526
+ peer: peerHint
31527
+ });
31528
+ continue;
31529
+ }
31530
+ if (!sameRuntimeBuild2(HERDSMAN_BUILD2, remote.build)) {
31531
+ addRemoteDiagnostic({
31532
+ machine: diagnosticLabel(machine.label, "machine"),
31533
+ reason: "build_mismatch",
31534
+ peer: peerHint,
31535
+ local_build: diagnosticBuild(HERDSMAN_BUILD2),
31536
+ remote_build: diagnosticBuild(remote.build)
31537
+ });
31538
+ continue;
31044
31539
  }
31045
31540
  const route = discoveredRemotePeerRoutes.get(remote.piSessionId);
31046
31541
  if (route) {
@@ -31320,7 +31815,11 @@ ${receivedRefs.join("\n")}` : ""}`,
31320
31815
  if (identityEstablished) {
31321
31816
  appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
31322
31817
  } else {
31323
- unavailableMachines.push(machine.label);
31818
+ machineDiscoveryIncomplete = true;
31819
+ addRemoteDiagnostic({
31820
+ machine: diagnosticLabel(machine.label, "machine"),
31821
+ reason: "probe_failed"
31822
+ });
31324
31823
  for (const [session, route] of discoveredRemotePeerRoutes)
31325
31824
  if (route.machine.id === machine.id)
31326
31825
  discoveredRemotePeerRoutes.delete(session);
@@ -31337,7 +31836,7 @@ ${receivedRefs.join("\n")}` : ""}`,
31337
31836
  }
31338
31837
  }
31339
31838
  }
31340
- if (unavailableMachines.length > 0) {
31839
+ if (machineDiscoveryIncomplete) {
31341
31840
  for (const session of previousAmbiguousSessions)
31342
31841
  discoveredAmbiguousSessions.add(session);
31343
31842
  }
@@ -31350,7 +31849,7 @@ ${receivedRefs.join("\n")}` : ""}`,
31350
31849
  if (index >= 0) peers.splice(index, 1);
31351
31850
  }
31352
31851
  }
31353
- if ((activeRole() === "manager" || activeRole() === "lead") && discovery === latestPeerDiscovery && !signal?.aborted && !unavailableMachines.includes("saved machines")) {
31852
+ if ((activeRole() === "manager" || activeRole() === "lead") && discovery === latestPeerDiscovery && !signal?.aborted && !machineListingFailed) {
31354
31853
  remotePeerRoutes.clear();
31355
31854
  for (const [session, route] of discoveredRemotePeerRoutes)
31356
31855
  remotePeerRoutes.set(session, route);
@@ -31380,25 +31879,26 @@ ${receivedRefs.join("\n")}` : ""}`,
31380
31879
  ...correspondence.originDisplay?.name ? { name: correspondence.originDisplay.name } : {},
31381
31880
  ...correspondence.originDisplay?.workspaceLabel ? { workspace_label: correspondence.originDisplay.workspaceLabel } : {}
31382
31881
  }));
31882
+ const discoveryPayload = {
31883
+ self,
31884
+ peers,
31885
+ ...replyOnly.length ? { reply_only: replyOnly } : {},
31886
+ ...remoteDiagnostics.length ? {
31887
+ remote_diagnostics: remoteDiagnostics,
31888
+ ...remoteDiagnosticsOmitted ? { remote_diagnostics_omitted: remoteDiagnosticsOmitted } : {}
31889
+ } : {}
31890
+ };
31383
31891
  return {
31384
31892
  content: [
31385
31893
  {
31386
31894
  type: "text",
31387
- text: JSON.stringify({
31388
- self,
31389
- peers,
31390
- ...replyOnly.length ? { reply_only: replyOnly } : {},
31391
- ...unavailableMachines.length ? { unavailable_machines: [...new Set(unavailableMachines)] } : {}
31392
- })
31895
+ text: JSON.stringify(discoveryPayload)
31393
31896
  }
31394
31897
  ],
31395
31898
  details: {
31396
31899
  ok: true,
31397
31900
  action: "list",
31398
- self,
31399
- peers,
31400
- ...replyOnly.length ? { reply_only: replyOnly } : {},
31401
- ...unavailableMachines.length ? { unavailable_machines: [...new Set(unavailableMachines)] } : {}
31901
+ ...discoveryPayload
31402
31902
  }
31403
31903
  };
31404
31904
  }
@@ -31965,7 +32465,24 @@ function createLeadInboxRuntime(host) {
31965
32465
  });
31966
32466
  return authorized;
31967
32467
  };
32468
+ const recordedManagerSender = (record) => {
32469
+ const senders = listManagerDescriptors2(supervisionRuntime3()).filter(
32470
+ (manager) => manager.piSessionId === record.fromSessionId
32471
+ );
32472
+ if (senders.length === 1) return senders[0];
32473
+ if (senders.length > 1) return void 0;
32474
+ try {
32475
+ listManagerDescriptors2(supervisionRuntime3(), true);
32476
+ } catch (error2) {
32477
+ throw new Error(
32478
+ "Manager descriptor verification is temporarily unavailable",
32479
+ { cause: error2 }
32480
+ );
32481
+ }
32482
+ return void 0;
32483
+ };
31968
32484
  const authorizeChiefRecord = async (record, ctx, verifyLiveChief = true) => {
32485
+ const sameLiveLead = (current, original) => current.workspace_id === original.workspace_id && current.pane_id === original.pane_id && current.tab_id === original.tab_id && current.cwd === original.cwd;
31969
32486
  const sessionId = ctx.sessionManager.getSessionId();
31970
32487
  if (record.toSessionId !== sessionId) return false;
31971
32488
  if (!record.build || !sameRuntimeBuild2(record.build, HERDSMAN_BUILD2))
@@ -31982,12 +32499,12 @@ function createLeadInboxRuntime(host) {
31982
32499
  managerDiagnostic("project_assignment_scope_complete");
31983
32500
  if (!scope.workspaceIds.includes(workspaceId2))
31984
32501
  return projectAssignmentAuthorized(false, "workspace_scope_mismatch");
31985
- const assignment = record.branch ? readProjectAssignment2(
32502
+ const assignment2 = record.branch ? readProjectAssignment2(
31986
32503
  supervisionRuntime3(),
31987
32504
  scope.repoKey,
31988
32505
  record.branch
31989
32506
  ) : void 0;
31990
- if (!assignment || assignment.id !== sessionId || record.id !== assignment.id)
32507
+ if (!assignment2 || assignment2.id !== sessionId || record.id !== assignment2.id)
31991
32508
  return projectAssignmentAuthorized(
31992
32509
  false,
31993
32510
  "assignment_evidence_mismatch"
@@ -32003,7 +32520,7 @@ function createLeadInboxRuntime(host) {
32003
32520
  if (topology?.source?.source_workspace_id !== scope.primaryWorkspaceId || topology?.source?.repo_key !== scope.repoKey || !Array.isArray(topology?.worktrees))
32004
32521
  return projectAssignmentAuthorized(false, "worktree_topology_mismatch");
32005
32522
  const worktrees = topology.worktrees.filter(
32006
- (worktree) => worktree.branch === assignment.branch
32523
+ (worktree) => worktree.branch === assignment2.branch
32007
32524
  );
32008
32525
  if (worktrees.length !== 1)
32009
32526
  return projectAssignmentAuthorized(false, "branch_placement_mismatch");
@@ -32025,7 +32542,7 @@ function createLeadInboxRuntime(host) {
32025
32542
  }
32026
32543
  if (leadRuntime.chiefMode === "active") {
32027
32544
  const chief = await currentChiefAuthority(ctx, true);
32028
- if (!chief || record.leaseId !== chief.leaseId || record.leadSessionId !== record.fromSessionId)
32545
+ if (!chief || record.kind !== "manager_message" && record.leaseId !== chief.leaseId || record.leadSessionId !== record.fromSessionId)
32029
32546
  return false;
32030
32547
  if (record.kind === "lead_message") {
32031
32548
  const leads = await liveLead(ctx, record.fromSessionId);
@@ -32046,29 +32563,37 @@ function createLeadInboxRuntime(host) {
32046
32563
  supervisionRuntime3(),
32047
32564
  record.leadSessionId
32048
32565
  );
32049
- const supervisor2 = await host.resolveEffectiveSupervisor(
32566
+ const supervisor = await host.resolveEffectiveSupervisor(
32050
32567
  ctx,
32051
32568
  record.fromSessionId,
32052
32569
  leads[0].workspace_id,
32053
32570
  scope2
32054
32571
  );
32055
- return !!state2 && (state2.role ?? "lead") === "lead" && supervisor2.kind === "chief" && supervisor2.chief.piSessionId === chief.piSessionId && supervisor2.chief.leaseId === chief.leaseId;
32572
+ return !!state2 && (state2.role ?? "lead") === "lead" && supervisor.kind === "chief" && supervisor.chief.piSessionId === chief.piSessionId && supervisor.chief.leaseId === chief.leaseId;
32056
32573
  }
32057
32574
  if (record.kind !== "manager_message") return false;
32058
- const manager2 = listManagerDescriptors2(supervisionRuntime3()).find(
32059
- (x) => x.piSessionId === record.fromSessionId
32575
+ const manager2 = recordedManagerSender(record);
32576
+ if (!manager2) return false;
32577
+ if (record.leaseId !== manager2.leaseId) return false;
32578
+ const managerState2 = readLeadCoordinationState2(
32579
+ supervisionRuntime3(),
32580
+ manager2.piSessionId
32060
32581
  );
32061
- if (!manager2 || listManagerDescriptors2(supervisionRuntime3()).filter(
32062
- (x) => x.piSessionId === manager2.piSessionId
32063
- ).length !== 1 || !await remoteChiefAgent(ctx, manager2))
32582
+ if (!managerState2)
32583
+ throw new Error(
32584
+ "Manager coordination state is temporarily unavailable"
32585
+ );
32586
+ if (managerState2.role !== "manager" || managerState2.piSessionId !== manager2.piSessionId || !sameRuntimeBuild2(manager2.build, HERDSMAN_BUILD2) || !sameRuntimeBuild2(managerState2.build, HERDSMAN_BUILD2))
32064
32587
  return false;
32588
+ if (!await remoteChiefAgent(ctx, manager2))
32589
+ throw new Error("Manager live identity is temporarily unavailable");
32065
32590
  const scope = await worktreeGroupScope2(
32066
32591
  pi,
32067
32592
  ctx,
32068
32593
  manager2.workspaceId,
32069
32594
  ctx.signal
32070
32595
  );
32071
- return scope.primaryWorkspaceId === manager2.workspaceId && scope.repoKey === manager2.repoKey;
32596
+ return scope.repoKey === manager2.repoKey;
32072
32597
  }
32073
32598
  if (activeRole() === "manager" && !leadRuntime.roleSuspended) {
32074
32599
  if (record.kind === "chief_message") {
@@ -32079,49 +32604,102 @@ function createLeadInboxRuntime(host) {
32079
32604
  if (!manager2 || record.leaseId !== manager2.leaseId || record.kind !== "lead_message" || record.leadSessionId !== record.fromSessionId)
32080
32605
  return false;
32081
32606
  const leads = await liveLead(ctx, record.fromSessionId);
32082
- if (leads.length !== 1) return false;
32083
- const scope = await worktreeGroupScope2(
32607
+ if (leads.length !== 1 || typeof leads[0].cwd !== "string") return false;
32608
+ const lead = leads[0];
32609
+ const scope = await localRepositoryScope(
32084
32610
  pi,
32085
- ctx,
32086
- manager2.workspaceId,
32611
+ { ...ctx, cwd: lead.cwd },
32612
+ lead.workspace_id,
32087
32613
  ctx.signal
32088
32614
  );
32089
- const state2 = readLeadCoordinationState2(
32090
- supervisionRuntime3(),
32091
- record.leadSessionId
32092
- );
32093
- const supervisor2 = await host.resolveEffectiveSupervisor(
32615
+ const supervisor = await host.resolveEffectiveSupervisor(
32094
32616
  ctx,
32095
32617
  record.fromSessionId,
32096
- leads[0].workspace_id,
32618
+ lead.workspace_id,
32097
32619
  scope
32098
32620
  );
32099
- return scope.workspaceIds.includes(leads[0].workspace_id) && supervisor2.kind === "manager" && supervisor2.manager.piSessionId === manager2.piSessionId && supervisor2.manager.leaseId === manager2.leaseId && scope.primaryWorkspaceId === manager2.workspaceId && scope.repoKey === manager2.repoKey && !!state2 && (state2.role ?? "lead") === "lead";
32621
+ const [refreshedManager, currentLeads] = await Promise.all([
32622
+ host.currentManager(ctx),
32623
+ liveLead(ctx, record.fromSessionId)
32624
+ ]);
32625
+ const state2 = readLeadCoordinationState2(
32626
+ supervisionRuntime3(),
32627
+ record.leadSessionId
32628
+ );
32629
+ return !!refreshedManager && refreshedManager.piSessionId === manager2.piSessionId && refreshedManager.leaseId === manager2.leaseId && refreshedManager.repoKey === manager2.repoKey && currentLeads.length === 1 && sameLiveLead(currentLeads[0], lead) && supervisor.kind === "manager" && supervisor.manager.piSessionId === manager2.piSessionId && supervisor.manager.leaseId === manager2.leaseId && scope.repoKey === manager2.repoKey && !!state2 && (state2.role ?? "lead") === "lead";
32100
32630
  }
32101
32631
  if (activeRole() !== "lead" || leadRuntime.roleSuspended) return false;
32102
32632
  if (record.kind === "chief_message") {
32103
32633
  const chief = await currentChiefAuthority(ctx);
32104
32634
  const workspaceId2 = host.workspaceId();
32105
32635
  if (!workspaceId2) return false;
32106
- const supervisor2 = await host.resolveEffectiveSupervisor(
32636
+ let localScope2;
32637
+ try {
32638
+ localScope2 = await localRepositoryScope(
32639
+ pi,
32640
+ ctx,
32641
+ workspaceId2,
32642
+ ctx.signal
32643
+ );
32644
+ } catch (error2) {
32645
+ if (!(error2 instanceof OperationError && error2.detail.details?.herdrCode === "not_git_worktree"))
32646
+ throw error2;
32647
+ }
32648
+ const supervisor = await host.resolveEffectiveSupervisor(
32107
32649
  ctx,
32108
32650
  sessionId,
32109
- workspaceId2
32651
+ workspaceId2,
32652
+ localScope2
32110
32653
  );
32654
+ let currentLocalScope = localScope2;
32655
+ if (localScope2) {
32656
+ currentLocalScope = await localRepositoryScope(
32657
+ pi,
32658
+ ctx,
32659
+ workspaceId2,
32660
+ ctx.signal
32661
+ );
32662
+ if (currentLocalScope.repoKey !== localScope2.repoKey || currentLocalScope.checkoutPath !== localScope2.checkoutPath)
32663
+ return false;
32664
+ }
32665
+ const currentChief = await currentChiefAuthority(ctx);
32666
+ if (host.workspaceId() !== workspaceId2 || ctx.sessionManager.getSessionId() !== sessionId)
32667
+ return false;
32111
32668
  const state2 = readLeadCoordinationState2(supervisionRuntime3(), sessionId);
32112
- return !!chief && supervisor2.kind === "chief" && supervisor2.chief.piSessionId === chief.piSessionId && supervisor2.chief.leaseId === chief.leaseId && !!state2 && chief.piSessionId === record.fromSessionId && chief.leaseId === record.leaseId && record.leadSessionId === sessionId;
32669
+ return !!chief && !!currentChief && currentChief.piSessionId === chief.piSessionId && currentChief.leaseId === chief.leaseId && (!localScope2 || !!currentLocalScope) && supervisor.kind === "chief" && supervisor.chief.piSessionId === chief.piSessionId && supervisor.chief.leaseId === chief.leaseId && !!state2 && chief.piSessionId === record.fromSessionId && chief.leaseId === record.leaseId && record.leadSessionId === sessionId;
32113
32670
  }
32114
32671
  if (record.kind !== "manager_message") return false;
32672
+ const manager = recordedManagerSender(record);
32673
+ if (!manager) return false;
32674
+ if (record.leaseId !== manager.leaseId || record.leadSessionId !== sessionId)
32675
+ return false;
32676
+ const managerState = readLeadCoordinationState2(
32677
+ supervisionRuntime3(),
32678
+ manager.piSessionId
32679
+ );
32680
+ if (!managerState)
32681
+ throw new Error("Manager coordination state is temporarily unavailable");
32682
+ if (managerState.role !== "manager" || managerState.piSessionId !== manager.piSessionId || !sameRuntimeBuild2(manager.build, HERDSMAN_BUILD2) || !sameRuntimeBuild2(managerState.build, HERDSMAN_BUILD2))
32683
+ return false;
32684
+ if (!await remoteChiefAgent(ctx, manager))
32685
+ throw new Error("Manager live identity is temporarily unavailable");
32115
32686
  const workspaceId = host.workspaceId();
32116
32687
  if (!workspaceId) throw new Error("Project scope cannot be verified");
32117
- const supervisor = await host.resolveEffectiveSupervisor(
32688
+ const localScope = await localRepositoryScope(
32689
+ pi,
32118
32690
  ctx,
32119
- sessionId,
32120
- workspaceId
32691
+ workspaceId,
32692
+ ctx.signal
32121
32693
  );
32122
- const manager = supervisor.kind === "assigned" ? await currentManager(ctx, supervisor.scope) : supervisor.kind === "manager" ? supervisor.manager : void 0;
32123
- if (supervisor.kind === "assigned" ? supervisor.assignment.branch !== record.branch : record.branch !== void 0 || supervisor.kind !== "manager")
32124
- return false;
32694
+ if (localScope.repoKey !== manager.repoKey) return false;
32695
+ const assignment = host.projectAssignmentForScope(localScope, sessionId);
32696
+ if (assignment) {
32697
+ if (assignment.branch !== record.branch) return false;
32698
+ } else {
32699
+ const supervisor = host.managerForScope(localScope);
32700
+ if (!supervisor || supervisor.piSessionId !== manager.piSessionId || supervisor.leaseId !== manager.leaseId || record.branch !== void 0)
32701
+ return false;
32702
+ }
32125
32703
  let state;
32126
32704
  try {
32127
32705
  state = readLeadCoordinationState2(supervisionRuntime3(), sessionId);
@@ -32133,8 +32711,6 @@ function createLeadInboxRuntime(host) {
32133
32711
  return false;
32134
32712
  throw error2;
32135
32713
  }
32136
- if (!manager)
32137
- throw new Error("Manager authority is temporarily unavailable");
32138
32714
  if (!state)
32139
32715
  throw new Error("Lead coordination state is temporarily unavailable");
32140
32716
  return (state.role ?? "lead") === "lead" && record.leaseId === manager.leaseId && record.fromSessionId === manager.piSessionId && record.leadSessionId === sessionId && record.kind === "manager_message";
@@ -32228,7 +32804,7 @@ function createLeadInboxRuntime(host) {
32228
32804
  if (record.kind === "peer_message")
32229
32805
  return authorizePeerRecord(record, ctx);
32230
32806
  try {
32231
- if (verifyLease) {
32807
+ if (verifyLease && !(record.kind === "manager_message" && (activeRole() === "lead" || activeRole() === "chief"))) {
32232
32808
  const chief = activeRole() === "chief" || activeRole() === "manager" && record.kind === "chief_message" ? await currentChiefAuthority(ctx) : await currentManager(ctx);
32233
32809
  if (!chief)
32234
32810
  throw new Error("Supervisor lease could not be verified");
@@ -32733,11 +33309,11 @@ async function resolveLeadControllerRole(state, ctx, requestedRole, deps, option
32733
33309
  const { paneId, tabId, workspaceId } = deps.identity;
32734
33310
  if (requestedRole !== "manager" && !optional || !paneId || !tabId || !workspaceId)
32735
33311
  return;
32736
- if (optional)
32737
- deps.activationGuard(ctx.sessionManager.getSessionId(), "Manager");
33312
+ const sessionId = ctx.sessionManager.getSessionId();
33313
+ deps.activationGuard(sessionId, "Manager");
32738
33314
  let scope;
32739
33315
  try {
32740
- scope = await deps.worktreeGroupScope(workspaceId, ctx.signal);
33316
+ scope = await deps.localRepositoryScope(workspaceId, ctx.signal);
32741
33317
  } catch (error2) {
32742
33318
  if (!deps.isCurrent()) return;
32743
33319
  if (error2 instanceof OperationError && error2.detail.details?.herdrCode === "not_git_worktree") {
@@ -32747,25 +33323,35 @@ async function resolveLeadControllerRole(state, ctx, requestedRole, deps, option
32747
33323
  if (!optional) state.roleSuspended = true;
32748
33324
  throw error2;
32749
33325
  }
32750
- if (!deps.isCurrent()) return;
32751
- if (scope.primaryWorkspaceId !== workspaceId) {
33326
+ if (!deps.isCurrent() || ctx.sessionManager.getSessionId() !== sessionId)
33327
+ return;
33328
+ if (!scope.isPrimary) {
32752
33329
  if (!optional) deps.persistLeadRole();
32753
33330
  return;
32754
33331
  }
33332
+ if (!await deps.verifyCurrentIdentity() || !deps.isCurrent() || ctx.sessionManager.getSessionId() !== sessionId)
33333
+ return;
33334
+ deps.activationGuard(sessionId, "Manager");
32755
33335
  try {
32756
33336
  const lease = deps.claimManagerLease({
32757
33337
  build: deps.build,
32758
- piSessionId: ctx.sessionManager.getSessionId(),
33338
+ piSessionId: sessionId,
32759
33339
  piSessionFile: ctx.sessionManager.getSessionFile(),
32760
33340
  paneId,
32761
33341
  tabId,
32762
33342
  workspaceId,
32763
33343
  repoKey: scope.repoKey
32764
33344
  });
32765
- if (optional) {
33345
+ {
32766
33346
  let verified;
32767
33347
  try {
32768
33348
  verified = await deps.verifyManagerIdentity(lease.descriptor);
33349
+ const currentScope = await deps.localRepositoryScope(
33350
+ workspaceId,
33351
+ ctx.signal
33352
+ );
33353
+ if (!currentScope.isPrimary || currentScope.repoKey !== scope.repoKey || !await deps.verifyCurrentIdentity() || ctx.sessionManager.getSessionId() !== sessionId)
33354
+ throw new Error("Manager identity changed during restoration");
32769
33355
  } catch (error2) {
32770
33356
  if (!deps.isCurrent()) {
32771
33357
  lease.release();
@@ -32834,7 +33420,7 @@ async function resolveLeadControllerRole(state, ctx, requestedRole, deps, option
32834
33420
  }
32835
33421
  function gitPathStatus(path) {
32836
33422
  try {
32837
- return statSync6(path).isDirectory() ? "present" : "unknown";
33423
+ return statSync7(path).isDirectory() ? "present" : "unknown";
32838
33424
  } catch (error2) {
32839
33425
  const code = error2.code;
32840
33426
  return code === "ENOENT" || code === "ENOTDIR" ? "absent" : "unknown";
@@ -32881,7 +33467,7 @@ function parseGitWorktreeInventory(output) {
32881
33467
  else if (/^prunable(?: .*)?$/.test(value2)) prunable = true;
32882
33468
  else if (!/^[^\s]+(?: .*)?$/.test(value2)) return void 0;
32883
33469
  }
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)
33470
+ if (!path || !isAbsolute7(path) || (bare ? !!branch || detached : !head || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(head) || !branch && !detached) || branch !== void 0 && !branch)
32885
33471
  return void 0;
32886
33472
  worktrees.push({
32887
33473
  path,
@@ -32921,6 +33507,17 @@ function createLeadRoleTransitions(state, host) {
32921
33507
  throw error2;
32922
33508
  }
32923
33509
  };
33510
+ const currentLocalRepositoryScope = async (ctx) => {
33511
+ const workspaceId = host.workspaceId();
33512
+ if (!workspaceId) return void 0;
33513
+ try {
33514
+ return await localRepositoryScope(host.pi, ctx, workspaceId, ctx.signal);
33515
+ } catch (error2) {
33516
+ if (error2 instanceof OperationError && error2.detail.details?.herdrCode === "not_git_worktree")
33517
+ return void 0;
33518
+ throw error2;
33519
+ }
33520
+ };
32924
33521
  const projectAssignmentForScope = (scope, sessionId) => {
32925
33522
  const assignments = host.findProjectAssignmentBySession(
32926
33523
  host.supervisionRuntime(),
@@ -33068,17 +33665,20 @@ function createLeadRoleTransitions(state, host) {
33068
33665
  };
33069
33666
  const managerForScope = (scope) => {
33070
33667
  if (!scope) return void 0;
33071
- const status = host.readManagerDescriptorStatus(
33072
- host.supervisionRuntime(),
33073
- scope.primaryWorkspaceId
33668
+ const managers = listManagerDescriptors(host.supervisionRuntime()).filter(
33669
+ (manager) => manager.repoKey === scope.repoKey
33074
33670
  );
33075
- if (!status || !status.live) return void 0;
33076
- if (status.descriptor.repoKey !== scope.repoKey)
33077
- throw new Error("Manager authority does not match project");
33078
- return status.descriptor;
33671
+ if (managers.length > 1)
33672
+ throw new Error("Manager supervisor is ambiguous for this repository");
33673
+ return managers[0];
33079
33674
  };
33080
33675
  const currentManager = async (ctx, scope) => {
33081
- const descriptor = managerForScope(
33676
+ const ownLease = activeLeadRole(state) === "manager" && !state.roleSuspended ? state.managerLease : void 0;
33677
+ const ownStatus = ownLease && host.readManagerDescriptorStatus(
33678
+ host.supervisionRuntime(),
33679
+ ownLease.descriptor.workspaceId
33680
+ );
33681
+ const descriptor = ownLease ? ownStatus?.live && host.sameManagerDescriptor(ownStatus.descriptor, ownLease.descriptor) ? ownStatus.descriptor : void 0 : managerForScope(
33082
33682
  scope === null || scope === void 0 ? await currentWorktreeScope2(ctx) : scope
33083
33683
  );
33084
33684
  if (!descriptor) return void 0;
@@ -33204,12 +33804,12 @@ function createLeadRoleTransitions(state, host) {
33204
33804
  ctx.sessionManager.getSessionId()
33205
33805
  );
33206
33806
  if (identity?.kind === "managed") {
33207
- const scope2 = await currentWorktreeScope2(ctx);
33807
+ const scope2 = await currentLocalRepositoryScope(ctx);
33208
33808
  if (!scope2 || scope2.repoKey !== identity.repoKey) return void 0;
33209
33809
  const assignment = projectAssignmentForScope(scope2, identity.sessionId);
33210
33810
  return assignment && assignment.branch === identity.branch ? currentManager(ctx, scope2) : void 0;
33211
33811
  }
33212
- const scope = await currentWorktreeScope2(ctx);
33812
+ const scope = await currentLocalRepositoryScope(ctx);
33213
33813
  if (!scope) return host.currentChiefAuthority(ctx);
33214
33814
  const workspaceId = host.workspaceId();
33215
33815
  if (!workspaceId) return host.currentChiefAuthority(ctx);
@@ -33235,15 +33835,14 @@ function createLeadRoleTransitions(state, host) {
33235
33835
  return true;
33236
33836
  };
33237
33837
  const gitWorktreeInventory = async (ctx, repoKey, primaryWorkspaceId, sourceCheckoutPath) => {
33238
- if (!isAbsolute6(sourceCheckoutPath)) return void 0;
33838
+ if (!isAbsolute7(sourceCheckoutPath)) return void 0;
33239
33839
  try {
33240
33840
  const scope = await host.worktreeGroupScope(
33241
33841
  ctx,
33242
33842
  primaryWorkspaceId,
33243
33843
  ctx.signal
33244
33844
  );
33245
- if (scope.repoKey !== repoKey || scope.primaryWorkspaceId !== primaryWorkspaceId)
33246
- return void 0;
33845
+ if (scope.repoKey !== repoKey) return void 0;
33247
33846
  const rootResult = await host.pi.exec(
33248
33847
  "git",
33249
33848
  ["rev-parse", "--path-format=absolute", "--git-common-dir"],
@@ -33252,7 +33851,7 @@ function createLeadRoleTransitions(state, host) {
33252
33851
  if (rootResult.code !== 0 || rootResult.killed || rootResult.stderr?.trim())
33253
33852
  return void 0;
33254
33853
  const commonDir = String(rootResult.stdout ?? "").trim();
33255
- if (!commonDir || !isAbsolute6(commonDir)) return void 0;
33854
+ if (!commonDir || !isAbsolute7(commonDir)) return void 0;
33256
33855
  const result = await host.pi.exec(
33257
33856
  "git",
33258
33857
  ["worktree", "list", "--porcelain", "-z"],
@@ -33416,7 +34015,7 @@ function createLeadRoleTransitions(state, host) {
33416
34015
  ["worktree", "list", "--workspace", manager.workspaceId],
33417
34016
  { signal: ctx.signal }
33418
34017
  );
33419
- if (topology?.source?.repo_key !== manager.repoKey || topology?.source?.source_workspace_id !== manager.workspaceId || typeof topology?.source?.source_checkout_path !== "string")
34018
+ if (topology?.source?.repo_key !== manager.repoKey || typeof topology?.source?.source_checkout_path !== "string")
33420
34019
  throw new Error("Manager worktree topology is not authoritative");
33421
34020
  await reconcileProjectAssignments(
33422
34021
  ctx,
@@ -33753,7 +34352,7 @@ function createLeadRoleTransitions(state, host) {
33753
34352
  const sessionId = ctx.sessionManager.getSessionId();
33754
34353
  let scope;
33755
34354
  try {
33756
- scope = await host.worktreeGroupScope(ctx, workspaceId);
34355
+ scope = await localRepositoryScope(host.pi, ctx, workspaceId, ctx.signal);
33757
34356
  } catch (error2) {
33758
34357
  if (!(error2 instanceof OperationError) || error2.detail.details?.herdrCode !== "not_git_worktree")
33759
34358
  throw error2;
@@ -33763,18 +34362,9 @@ function createLeadRoleTransitions(state, host) {
33763
34362
  "/manager requires interactive confirmation to initialize Git"
33764
34363
  );
33765
34364
  const target = realpathSync5(resolve6(ctx.cwd));
33766
- const targetStat = statSync6(target, { bigint: true });
34365
+ const targetStat = statSync7(target, { bigint: true });
33767
34366
  if (!targetStat.isDirectory() || targetStat.dev === 0n || targetStat.ino === 0n)
33768
34367
  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
34368
  const verifyHerdrTarget = async () => {
33779
34369
  const pane = (await host.runHerdr(host.pi, ctx, ["pane", "get", paneId], {
33780
34370
  signal: ctx.signal
@@ -33783,7 +34373,7 @@ function createLeadRoleTransitions(state, host) {
33783
34373
  signal: ctx.signal
33784
34374
  }))?.workspace;
33785
34375
  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))
34376
+ if (pane?.pane_id !== paneId || pane?.tab_id !== tabId || pane?.workspace_id !== workspaceId || workspace2?.workspace_id !== workspaceId || typeof paneCwd !== "string" || !isAbsolute7(paneCwd) || !sameDirectory(paneCwd, target))
33787
34377
  throw new Error(
33788
34378
  "Manager activation cancelled because Herdr workspace identity does not match the approved directory"
33789
34379
  );
@@ -33809,7 +34399,7 @@ function createLeadRoleTransitions(state, host) {
33809
34399
  throw new Error("Manager activation cancelled.");
33810
34400
  await verifyHerdrTarget();
33811
34401
  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 });
34402
+ const current = statSync7(target, { bigint: true });
33813
34403
  return current.dev !== targetStat.dev || current.ino !== targetStat.ino;
33814
34404
  })())
33815
34405
  throw new Error(
@@ -33956,8 +34546,13 @@ function createLeadRoleTransitions(state, host) {
33956
34546
  "--path-format=absolute",
33957
34547
  "--git-common-dir"
33958
34548
  ]);
33959
- scope = await host.worktreeGroupScope(ctx, workspaceId);
33960
- if (!scope || scope.primaryWorkspaceId !== workspaceId || !sameDirectory(scope.repoKey, gitCommonDir))
34549
+ scope = await localRepositoryScope(
34550
+ host.pi,
34551
+ ctx,
34552
+ workspaceId,
34553
+ ctx.signal
34554
+ );
34555
+ if (!scope || !scope.isPrimary || !sameDirectory(scope.repoKey, gitCommonDir))
33961
34556
  throw new Error(
33962
34557
  "Manager activation could not verify the initialized repository in Herdr"
33963
34558
  );
@@ -33967,8 +34562,16 @@ function createLeadRoleTransitions(state, host) {
33967
34562
  }
33968
34563
  if (!scope)
33969
34564
  throw new Error("Manager workspace could not be verified in Herdr");
33970
- if (scope.primaryWorkspaceId !== workspaceId)
34565
+ if (!scope.isPrimary)
33971
34566
  throw new Error("/manager is available only in the primary workspace");
34567
+ if (!await host.remoteChiefAgent(ctx, {
34568
+ piSessionId: sessionId,
34569
+ piSessionFile: ctx.sessionManager.getSessionFile(),
34570
+ paneId,
34571
+ tabId,
34572
+ workspaceId
34573
+ }))
34574
+ throw new Error("Manager identity changed during activation");
33972
34575
  if (ctx.sessionManager.getSessionId() !== sessionId)
33973
34576
  throw new Error(
33974
34577
  "Manager activation cancelled because the session changed"
@@ -34004,6 +34607,14 @@ function createLeadRoleTransitions(state, host) {
34004
34607
  throw new Error("Manager coordination state could not be persisted");
34005
34608
  if (!await host.remoteChiefAgent(ctx, lease.descriptor))
34006
34609
  throw new Error("Manager could not be verified in Herdr");
34610
+ const currentScope = await localRepositoryScope(
34611
+ host.pi,
34612
+ ctx,
34613
+ workspaceId,
34614
+ ctx.signal
34615
+ );
34616
+ if (!currentScope.isPrimary || !sameDirectory(currentScope.repoKey, scope.repoKey) || !await host.remoteChiefAgent(ctx, lease.descriptor) || ctx.sessionManager.getSessionId() !== sessionId)
34617
+ throw new Error("Manager identity changed during activation");
34007
34618
  host.reconcileRoleTools();
34008
34619
  host.clearNormalUI();
34009
34620
  host.startSupervisionUI(ctx);
@@ -34283,10 +34894,15 @@ function createLeadRoleTransitions(state, host) {
34283
34894
  {
34284
34895
  identity: host.identity,
34285
34896
  build: host.build,
34286
- worktreeGroupScope: (workspaceId, signal) => host.worktreeGroupScope(ctx, workspaceId, signal),
34897
+ localRepositoryScope: (workspaceId, signal) => localRepositoryScope(host.pi, ctx, workspaceId, signal),
34287
34898
  claimManagerLease: host.claimManagerLease,
34288
34899
  coordinationHealthy: host.coordinationHealthy,
34289
34900
  verifyManagerIdentity: (descriptor) => host.remoteChiefAgent(ctx, descriptor),
34901
+ verifyCurrentIdentity: () => host.remoteChiefAgent(ctx, {
34902
+ piSessionId: ctx.sessionManager.getSessionId(),
34903
+ piSessionFile: ctx.sessionManager.getSessionFile(),
34904
+ ...host.identity
34905
+ }),
34290
34906
  unresolvedManagerLease: () => {
34291
34907
  host.markLeadCoordinationUnhealthy(ctx);
34292
34908
  reconcileRoleTools();
@@ -34487,11 +35103,11 @@ var MANAGER_TOOLS = [
34487
35103
  ...SUPERVISOR_TOOLS,
34488
35104
  ...PEER_TOOLS,
34489
35105
  ...STAFF_TOOLS,
34490
- "delegate_project",
34491
- "resume_project",
35106
+ "delegate_work",
35107
+ "resume_work",
34492
35108
  "stop_lead",
34493
35109
  "remove_worktree",
34494
- "merge_project"
35110
+ "integrate_branch"
34495
35111
  ];
34496
35112
  var LEAD_COORDINATION_TOOLS = [
34497
35113
  ...AGENT_COORDINATION_TOOLS,
@@ -34507,10 +35123,10 @@ var ORDINARY_LEAD_CHARTER = `## Lead role
34507
35123
  You are an ordinary Lead for this Pi session.
34508
35124
  ${COMMON_LEAD_GUIDANCE}
34509
35125
  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.
34511
- For a verified managed project assignment, required project evidence is automatically inherited by newly accepted descendant Agent assignments.
34512
- A Lead's delegation task and ordinary files are recipient-specific; they do not create project-wide requirements.
34513
- Only the Manager can designate continuing project requirements.
35126
+ var MANAGED_LEAD_GUIDANCE = `Managed Lead identity is permanent for this exact Pi session. Only a current exact work assignment permits execution of that assignment; 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.
35127
+ For a verified managed project assignment, assignment required evidence is automatically inherited by newly accepted descendant Agent assignments; sibling Lead assignments do not automatically inherit it.
35128
+ A Lead's delegation task and ordinary files are recipient-specific; they do not create assignment requirements.
35129
+ Only the Manager can designate continuing requirements for an assignment.
34514
35130
  Send proposed continuing requirements and available supporting evidence to the Manager for evaluation.
34515
35131
  For assigned project work, include routine proposed requirements, completion, and review readiness in your normal response; Herdsman delivers it to the Manager automatically.
34516
35132
  For assigned project work, use message_supervisor for timely coordination or explicit evidence transfer, not for a separate completion announcement.
@@ -34915,7 +35531,7 @@ If needed, install the Pi integration once:
34915
35531
  };
34916
35532
  },
34917
35533
  persistedTranscriptReady: (state) => persistedTranscriptReady(state, (path) => {
34918
- const file2 = statSync7(path, { throwIfNoEntry: false });
35534
+ const file2 = statSync8(path, { throwIfNoEntry: false });
34919
35535
  return !!file2?.isFile() && file2.size > 0;
34920
35536
  }),
34921
35537
  agentDefinitions: async (ctx) => (await contextAgentDefinitions(ctx)).definitions,
@@ -34923,7 +35539,7 @@ If needed, install the Pi integration once:
34923
35539
  state,
34924
35540
  (path) => readFileSync13(path, "utf8"),
34925
35541
  (path) => {
34926
- const file2 = statSync7(path, { throwIfNoEntry: false });
35542
+ const file2 = statSync8(path, { throwIfNoEntry: false });
34927
35543
  return !!file2?.isFile() && file2.size > 0;
34928
35544
  }
34929
35545
  ),
@@ -35099,7 +35715,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
35099
35715
  sessionId,
35100
35716
  (cwd, id) => SessionManager2.findById(cwd, id)
35101
35717
  ),
35102
- statSync: statSync7,
35718
+ statSync: statSync8,
35103
35719
  workspacePresentationProvenance,
35104
35720
  normalizeHerdrLifecycleState,
35105
35721
  appendDurableError,
@@ -35126,11 +35742,11 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
35126
35742
  ...PEER_TOOLS,
35127
35743
  ...STAFF_TOOLS,
35128
35744
  "read_evidence",
35129
- "delegate_project",
35130
- "resume_project",
35745
+ "delegate_work",
35746
+ "resume_work",
35131
35747
  "stop_lead",
35132
35748
  "remove_worktree",
35133
- "merge_project"
35749
+ "integrate_branch"
35134
35750
  ];
35135
35751
  if (processRole === "managed-agent") {
35136
35752
  leadStatusRuntime = createAgentStatusRuntime();
@@ -35194,7 +35810,7 @@ ${globalInstructions}
35194
35810
  tabId: process.env.HERDR_TAB_ID,
35195
35811
  workspaceId: process.env.HERDR_WORKSPACE_ID
35196
35812
  },
35197
- statSync: statSync7,
35813
+ statSync: statSync8,
35198
35814
  readChiefDescriptor,
35199
35815
  chiefLeaseIsHeld,
35200
35816
  sameChiefDescriptor,
@@ -35313,7 +35929,7 @@ ${globalInstructions}
35313
35929
  target,
35314
35930
  (path) => readFileSync13(path, "utf8"),
35315
35931
  (path) => {
35316
- const file2 = statSync7(path, { throwIfNoEntry: false });
35932
+ const file2 = statSync8(path, { throwIfNoEntry: false });
35317
35933
  return !!file2?.isFile() && file2.size > 0;
35318
35934
  }
35319
35935
  )
@@ -35864,9 +36480,9 @@ ${summary}`,
35864
36480
  });
35865
36481
  pi.registerTool({
35866
36482
  ...staffTool,
35867
- name: "delegate_project",
35868
- label: "delegate project",
35869
- description: "Start new project work, reusing an unoccupied Herdr worktree when available. The initial task and supplied files become required project evidence; use resume_project for existing work.",
36483
+ name: "delegate_work",
36484
+ label: "delegate work",
36485
+ description: "Start a new work assignment, reusing an unoccupied Herdr worktree when available. The initial task and supplied files become required assignment evidence; use resume_work for existing work.",
35870
36486
  parameters: staffDelegateParameters,
35871
36487
  promptSnippet: void 0,
35872
36488
  promptGuidelines: [FILE_HANDOFF_GUIDANCE],
@@ -35882,8 +36498,8 @@ ${summary}`,
35882
36498
  });
35883
36499
  pi.registerTool({
35884
36500
  ...staffTool,
35885
- name: "resume_project",
35886
- label: "resume project",
36501
+ name: "resume_work",
36502
+ label: "resume work",
35887
36503
  description: "Reuse an already-running Lead for the exact branch; otherwise resume its existing assignment without creating a duplicate.",
35888
36504
  parameters: staffBranchParameters,
35889
36505
  promptSnippet: void 0,
@@ -35916,8 +36532,8 @@ ${summary}`,
35916
36532
  });
35917
36533
  pi.registerTool({
35918
36534
  ...staffTool,
35919
- name: "merge_project",
35920
- label: "merge project",
36535
+ name: "integrate_branch",
36536
+ label: "integrate branch",
35921
36537
  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.",
35922
36538
  parameters: Type3.Object(
35923
36539
  {