pi-herdsman 0.42.1 → 0.44.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
@@ -2321,7 +2321,7 @@ import {
2321
2321
  import { execFileSync } from "node:child_process";
2322
2322
  import { randomUUID as randomUUID5 } from "node:crypto";
2323
2323
  import { homedir as homedir2 } from "node:os";
2324
- import { dirname as dirname4, isAbsolute, join as join4, resolve as resolve2, sep } from "node:path";
2324
+ import { dirname as dirname4, isAbsolute, join as join4, relative, resolve as resolve2, sep } from "node:path";
2325
2325
  import { fileURLToPath as fileURLToPath2 } from "node:url";
2326
2326
  import {
2327
2327
  CONFIG_DIR_NAME,
@@ -2342,8 +2342,8 @@ function markdownFiles(root2) {
2342
2342
  return (entry.isFile() || entry.isSymbolicLink()) && entry.name.endsWith(".md") ? [path] : [];
2343
2343
  });
2344
2344
  }
2345
- function readAgentDefinitions(root2) {
2346
- const definitions = markdownFiles(root2).filter((path) => !path.endsWith(".example.md")).sort().map((path) => {
2345
+ function readAgentDefinitions(root2, category, onWarning) {
2346
+ const definitions = markdownFiles(root2).filter((path) => !path.endsWith(".example.md")).sort().flatMap((path) => {
2347
2347
  const content = readFileSync5(path, "utf8").replace(/^\uFEFF/u, "");
2348
2348
  let parsed;
2349
2349
  try {
@@ -2354,6 +2354,18 @@ function readAgentDefinitions(root2) {
2354
2354
  }
2355
2355
  if (!isPlainObject(parsed.frontmatter))
2356
2356
  throw new Error(`${path}: frontmatter must be a YAML mapping`);
2357
+ const name = parsed.frontmatter.name;
2358
+ if (category && typeof name === "string" && name.length > 0 && isReservedRoleDefinition(name) !== (category === "role")) {
2359
+ const destination = join4(
2360
+ dirname4(root2),
2361
+ category === "agent" ? "coordinators" : "agents",
2362
+ relative(root2, path)
2363
+ );
2364
+ onWarning?.(
2365
+ `${path}: definition belongs in ${destination}; file excluded from discovery`
2366
+ );
2367
+ return [];
2368
+ }
2357
2369
  const frontmatter = parsed.frontmatter;
2358
2370
  const definition = {
2359
2371
  name: typeof frontmatter.name === "string" ? frontmatter.name : "",
@@ -2362,7 +2374,7 @@ function readAgentDefinitions(root2) {
2362
2374
  body: resolveBodyFileReferences(parsed.body, path)
2363
2375
  };
2364
2376
  validateDefinition(definition, { allowBodyMode: true });
2365
- return definition;
2377
+ return [definition];
2366
2378
  });
2367
2379
  const pathsByName = /* @__PURE__ */ new Map();
2368
2380
  for (const definition of definitions)
@@ -2478,12 +2490,18 @@ function configuredToolPolicy(definition, requiredTools) {
2478
2490
  excluded
2479
2491
  };
2480
2492
  }
2481
- function readOptionalAgentDefinitions(root2) {
2493
+ function toolPolicyAllowsName(policy, requiredTools, name) {
2494
+ if (requiredTools.has(name)) return true;
2495
+ if (policy.excluded.some((pattern) => matchesToolPattern(pattern, name)))
2496
+ return false;
2497
+ return !policy.explicit || policy.tools.some((pattern) => matchesToolPattern(pattern, name));
2498
+ }
2499
+ function readOptionalAgentDefinitions(root2, category, onWarning) {
2482
2500
  const stats = statSync3(root2, { throwIfNoEntry: false });
2483
2501
  if (!stats) return [];
2484
2502
  if (!stats.isDirectory())
2485
2503
  throw new Error(`agent directory is not a directory: ${root2}`);
2486
- return readAgentDefinitions(root2);
2504
+ return readAgentDefinitions(root2, category, onWarning);
2487
2505
  }
2488
2506
  function assertNoLegacyCoordinatorProfiles(legacy, canonical) {
2489
2507
  const stats = statSync3(legacy, { throwIfNoEntry: false });
@@ -2616,6 +2634,11 @@ function discoverEffectiveDefinitions(options = {}, category = "agent", validate
2616
2634
  const bundled = readAgentDefinitions(
2617
2635
  role2 ? BUILTIN_ROLE_DIR : BUILTIN_AGENT_DIR
2618
2636
  );
2637
+ for (const definition of bundled)
2638
+ if (isReservedRoleDefinition(definition.name) !== role2)
2639
+ throw new Error(
2640
+ `${definition.path}: ${role2 ? "non-coordinator name in coordinators directory" : "reserved coordinator name in agents directory; use coordinators"}`
2641
+ );
2619
2642
  const directory2 = role2 ? "coordinators" : "agents";
2620
2643
  const privateRoot = options.projectRoot ? privateRepositoryRoot(options.projectRoot) : void 0;
2621
2644
  if (role2) {
@@ -2636,21 +2659,20 @@ function discoverEffectiveDefinitions(options = {}, category = "agent", validate
2636
2659
  );
2637
2660
  }
2638
2661
  const project = options.projectRoot ? readOptionalAgentDefinitions(
2639
- join4(options.projectRoot, CONFIG_DIR_NAME, directory2)
2662
+ join4(options.projectRoot, CONFIG_DIR_NAME, directory2),
2663
+ category,
2664
+ options.onWarning
2640
2665
  ) : [];
2641
- const privateRepository = privateRoot ? readOptionalAgentDefinitions(join4(privateRoot, directory2)) : [];
2642
- const user = readOptionalAgentDefinitions(join4(getAgentDir(), directory2));
2643
- for (const definition of [
2644
- ...bundled,
2645
- ...project,
2646
- ...user,
2647
- ...privateRepository
2648
- ]) {
2649
- if (isReservedRoleDefinition(definition.name) !== role2)
2650
- throw new Error(
2651
- `${definition.path}: ${role2 ? "non-coordinator name in coordinators directory" : "reserved coordinator name in agents directory; use coordinators"}`
2652
- );
2653
- }
2666
+ const privateRepository = privateRoot ? readOptionalAgentDefinitions(
2667
+ join4(privateRoot, directory2),
2668
+ category,
2669
+ options.onWarning
2670
+ ) : [];
2671
+ const user = readOptionalAgentDefinitions(
2672
+ join4(getAgentDir(), directory2),
2673
+ category,
2674
+ options.onWarning
2675
+ );
2654
2676
  const definitions = new Map(
2655
2677
  bundled.map((definition) => [definition.name, definition])
2656
2678
  );
@@ -2710,9 +2732,26 @@ function withDefaultEnabled(definition) {
2710
2732
  }
2711
2733
  };
2712
2734
  }
2713
- async function contextAgentDefinitions(ctx) {
2735
+ function notifyDefinitionWarning(ctx, message) {
2736
+ const manager = ctx.sessionManager;
2737
+ const sessionId = manager.getSessionId();
2738
+ let state = definitionWarningSessions.get(manager);
2739
+ if (!state || state.sessionId !== sessionId) {
2740
+ state = { sessionId, messages: /* @__PURE__ */ new Set() };
2741
+ definitionWarningSessions.set(manager, state);
2742
+ }
2743
+ if (state.messages.has(message)) return;
2744
+ state.messages.add(message);
2745
+ if (ctx.hasUI) ctx.ui.notify(message, "warning");
2746
+ else process.emitWarning(message, { code: "PI_HERDSMAN_DEFINITION" });
2747
+ }
2748
+ async function contextAgentDefinitions(ctx, onWarning) {
2714
2749
  const projectTrusted = ctx.isProjectTrusted();
2715
2750
  const options = projectTrusted ? { projectRoot: ctx.cwd } : {};
2751
+ options.onWarning = (message) => {
2752
+ notifyDefinitionWarning(ctx, message);
2753
+ onWarning?.(message);
2754
+ };
2716
2755
  const effective = discoverAgentDefinitions(options);
2717
2756
  return {
2718
2757
  projectTrusted,
@@ -2963,8 +3002,17 @@ function configuredModel(frontmatter) {
2963
3002
  return typeof frontmatter.model === "string" && frontmatter.model ? frontmatter.model : void 0;
2964
3003
  }
2965
3004
  function resolveChildModel(input) {
2966
- if (input.configured !== void 0 && input.configured.trim() !== "")
2967
- return { kind: "use", model: input.configured, extensionDiscovery: false };
3005
+ if (input.configured !== void 0 && input.configured.trim() !== "") {
3006
+ const model = input.configured;
3007
+ let extensionDiscovery = false;
3008
+ for (let slash = model.lastIndexOf("/"); slash > 0; slash = model.lastIndexOf("/", slash - 1)) {
3009
+ if (input.isForeignProvider(model.slice(0, slash).trim().toLowerCase())) {
3010
+ extensionDiscovery = true;
3011
+ break;
3012
+ }
3013
+ }
3014
+ return { kind: "use", model, extensionDiscovery };
3015
+ }
2968
3016
  if (input.inherited === void 0) {
2969
3017
  const saved = input.saved;
2970
3018
  return {
@@ -3146,7 +3194,7 @@ function agentLaunchArgs(agent, options) {
3146
3194
  args.push("--append-system-prompt", `<active_agent name="${agent.name}"/>`);
3147
3195
  return args;
3148
3196
  }
3149
- var VALID_THINKING_LEVELS, THINKING_LEVELS, SYSTEM_PROMPT_MODES, BODY_MODES, STRING_FIELDS, BOOLEAN_CAPABILITY_FIELDS, ARRAY_FIELDS, SUPPORTED_FIELDS, BODY_FILE_REFERENCE, BUILTIN_AGENT_DIR, BUILTIN_ROLE_DIR, FLEXIBLE_LEAD_DEFINITION_NAME, ORCHESTRATOR_LEAD_DEFINITION_NAME, MANAGED_LEAD_DEFINITION_NAME, MANAGER_DEFINITION_NAME, CHIEF_DEFINITION_NAME, RESERVED_ROLE_DEFINITION_NAMES, RESERVED_ROLE_DEFINITION_NAME_SET, RUNTIME_LEAD_FIELDS, AGENT_COORDINATION_TOOLS;
3197
+ var VALID_THINKING_LEVELS, THINKING_LEVELS, SYSTEM_PROMPT_MODES, BODY_MODES, STRING_FIELDS, BOOLEAN_CAPABILITY_FIELDS, ARRAY_FIELDS, SUPPORTED_FIELDS, BODY_FILE_REFERENCE, BUILTIN_AGENT_DIR, BUILTIN_ROLE_DIR, FLEXIBLE_LEAD_DEFINITION_NAME, ORCHESTRATOR_LEAD_DEFINITION_NAME, MANAGED_LEAD_DEFINITION_NAME, MANAGER_DEFINITION_NAME, CHIEF_DEFINITION_NAME, RESERVED_ROLE_DEFINITION_NAMES, RESERVED_ROLE_DEFINITION_NAME_SET, RUNTIME_LEAD_FIELDS, AGENT_COORDINATION_TOOLS, definitionWarningSessions;
3150
3198
  var init_agent_definitions = __esm({
3151
3199
  "extension/agent-definitions.ts"() {
3152
3200
  "use strict";
@@ -3236,6 +3284,7 @@ var init_agent_definitions = __esm({
3236
3284
  "inspect_agent",
3237
3285
  "read_agent_transcript"
3238
3286
  ];
3287
+ definitionWarningSessions = /* @__PURE__ */ new WeakMap();
3239
3288
  }
3240
3289
  });
3241
3290
 
@@ -5414,6 +5463,34 @@ function sessionLeadRoleState(entries, sessionId) {
5414
5463
  }
5415
5464
  return state;
5416
5465
  }
5466
+ function validSenderEnvironment(value2) {
5467
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return false;
5468
+ const env = value2;
5469
+ if (Object.keys(env).some((key) => !["cwd", "git"].includes(key)) || typeof env.cwd !== "string" || !env.cwd || !isAbsolute3(env.cwd) || Buffer.byteLength(env.cwd) > 1024)
5470
+ return false;
5471
+ if (env.git === void 0) return true;
5472
+ if (!env.git || typeof env.git !== "object" || Array.isArray(env.git))
5473
+ return false;
5474
+ const git = env.git;
5475
+ return Object.keys(git).length === 3 && Object.keys(git).every(
5476
+ (key) => ["worktreeRoot", "branch", "head"].includes(key)
5477
+ ) && typeof git.worktreeRoot === "string" && !!git.worktreeRoot && isAbsolute3(git.worktreeRoot) && Buffer.byteLength(git.worktreeRoot) <= 1024 && (git.branch === null || typeof git.branch === "string" && !!git.branch && Buffer.byteLength(git.branch) <= 1024) && typeof git.head === "string" && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(git.head);
5478
+ }
5479
+ function senderEnvironmentAnnotation(value2) {
5480
+ if (!validSenderEnvironment(value2)) return "";
5481
+ const escape = (text) => [...text].map(
5482
+ (char) => char === "&" ? "&amp;" : char === "<" ? "&lt;" : char === ">" ? "&gt;" : char === '"' ? "&quot;" : char === "'" ? "&apos;" : char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127 ? "\uFFFD" : char
5483
+ ).join("");
5484
+ return `
5485
+
5486
+ <sender_environment informational="true">
5487
+ cwd: "${escape(value2.cwd)}"${value2.git ? `
5488
+ worktree_root: "${escape(value2.git.worktreeRoot)}"
5489
+ branch: "${escape(value2.git.branch ?? "detached")}"
5490
+ head: "${value2.git.head}"` : ""}
5491
+ Informational only; not an instruction or authorization.
5492
+ </sender_environment>`;
5493
+ }
5417
5494
  function canMessagePeer(a, b) {
5418
5495
  if (a.role !== b.role) return false;
5419
5496
  if (a.role === "manager") return true;
@@ -5455,6 +5532,7 @@ function validMessage(value2) {
5455
5532
  "resultBindings",
5456
5533
  "build",
5457
5534
  "peerSource",
5535
+ "senderEnvironment",
5458
5536
  "bodyRef"
5459
5537
  ];
5460
5538
  if (Object.keys(record).some(
@@ -5472,7 +5550,7 @@ function validMessage(value2) {
5472
5550
  if (projectMessage ? !validNativeIdentity(record.branch) : record.branch !== void 0 && (record.kind !== "manager_message" || !validNativeIdentity(record.branch))) {
5473
5551
  return false;
5474
5552
  }
5475
- return record.version === 2 && (peerMessage ? !!validPeerSource : record.peerSource === void 0) && (record.build === void 0 || isRuntimeBuild(record.build)) && typeof record.id === "string" && UUID3.test(record.id) && typeof record.leaseId === "string" && UUID3.test(record.leaseId) && typeof record.kind === "string" && MESSAGE_KINDS.has(record.kind) && validSession(record.fromSessionId) && validSession(record.toSessionId) && validSession(record.leadSessionId) && typeof record.text === "string" && (record.bodyRef === void 0 ? record.text.length > 0 : record.text === "" && record.resultBindings === void 0 && validOverflowBodyRef(record.bodyRef)) && (record.resultBindings === void 0 || Array.isArray(record.resultBindings) && record.resultBindings.every(isResultBinding)) && Number.isInteger(record.createdAt) && record.createdAt >= 0;
5553
+ return record.version === 2 && (peerMessage ? !!validPeerSource : record.peerSource === void 0) && (record.senderEnvironment === void 0 || validSenderEnvironment(record.senderEnvironment)) && (record.build === void 0 || isRuntimeBuild(record.build)) && typeof record.id === "string" && UUID3.test(record.id) && typeof record.leaseId === "string" && UUID3.test(record.leaseId) && typeof record.kind === "string" && MESSAGE_KINDS.has(record.kind) && validSession(record.fromSessionId) && validSession(record.toSessionId) && validSession(record.leadSessionId) && typeof record.text === "string" && (record.bodyRef === void 0 ? record.text.length > 0 : record.text === "" && record.resultBindings === void 0 && validOverflowBodyRef(record.bodyRef)) && (record.resultBindings === void 0 || Array.isArray(record.resultBindings) && record.resultBindings.every(isResultBinding)) && Number.isInteger(record.createdAt) && record.createdAt >= 0;
5476
5554
  }
5477
5555
  function chiefMessageBytes(record) {
5478
5556
  return Buffer.byteLength(`${JSON.stringify(record)}
@@ -5539,6 +5617,7 @@ function coordinationMessageDigest(record) {
5539
5617
  text: record.text,
5540
5618
  resultBindings: record.resultBindings,
5541
5619
  peerSource: record.peerSource,
5620
+ ...record.senderEnvironment ? { senderEnvironment: record.senderEnvironment } : {},
5542
5621
  createdAt: record.createdAt
5543
5622
  };
5544
5623
  return createHash8("sha256").update(JSON.stringify(canonical(content))).digest("hex");
@@ -6072,12 +6151,14 @@ function deliveredMessageContent(record, senderTarget) {
6072
6151
  const content = record.kind === "project_assignment" ? `Project assignment for branch ${record.branch}:
6073
6152
 
6074
6153
  ${record.text}` : `${prefix}${record.text}`;
6075
- return content;
6154
+ return content + senderEnvironmentAnnotation(record.senderEnvironment);
6076
6155
  }
6077
6156
  async function drainCoordinationInbox(options) {
6078
6157
  let delivered = 0;
6079
6158
  let examined = 0;
6080
6159
  for (const path of allChiefMessagePaths(options.runtime, options.sessionId)) {
6160
+ if (options.maxDeliveries !== void 0 && delivered >= options.maxDeliveries)
6161
+ break;
6081
6162
  if (examined >= COORDINATION_INBOX_SCAN_LIMIT) break;
6082
6163
  if (options.signal?.aborted) break;
6083
6164
  const id = basename5(path, ".json");
@@ -6243,12 +6324,13 @@ async function drainCoordinationInbox(options) {
6243
6324
  leadSessionId: record.leadSessionId,
6244
6325
  ...senderTarget ? { senderTarget } : {},
6245
6326
  ...record.branch ? { branch: record.branch } : {},
6327
+ ...record.senderEnvironment ? { senderEnvironment: record.senderEnvironment } : {},
6246
6328
  ...record.kind === "peer_message" ? { digest: coordinationMessageDigest(record) } : {}
6247
6329
  }
6248
6330
  },
6249
6331
  {
6250
6332
  deliverAs: deliverAs ?? "followUp",
6251
- triggerTurn: record.kind !== "project_assignment" || !hasResumeInstruction
6333
+ triggerTurn: options.forceNonTriggering ? false : record.kind !== "project_assignment" || !hasResumeInstruction
6252
6334
  },
6253
6335
  record
6254
6336
  );
@@ -7327,7 +7409,8 @@ function validProjectMessage(value2) {
7327
7409
  "kind",
7328
7410
  "createdAt",
7329
7411
  "resultBindings",
7330
- "bodyRef"
7412
+ "bodyRef",
7413
+ "senderEnvironment"
7331
7414
  ].includes(key)
7332
7415
  ) && Object.keys(r).length >= 7 && [
7333
7416
  "version",
@@ -7337,7 +7420,7 @@ function validProjectMessage(value2) {
7337
7420
  "fromSessionId",
7338
7421
  "text",
7339
7422
  "createdAt"
7340
- ].every((key) => Object.hasOwn(r, key)) && r.version === 2 && UUID3.test(String(r.id)) && validNativeIdentity(r.repoKey) && validNativeIdentity(r.branch) && validSession(r.fromSessionId) && typeof r.text === "string" && (r.bodyRef === void 0 ? r.text.length > 0 : r.text === "" && r.resultBindings === void 0 && validOverflowBodyRef(r.bodyRef)) && (r.kind === void 0 || [
7423
+ ].every((key) => Object.hasOwn(r, key)) && r.version === 2 && (r.senderEnvironment === void 0 || validSenderEnvironment(r.senderEnvironment)) && UUID3.test(String(r.id)) && validNativeIdentity(r.repoKey) && validNativeIdentity(r.branch) && validSession(r.fromSessionId) && typeof r.text === "string" && (r.bodyRef === void 0 ? r.text.length > 0 : r.text === "" && r.resultBindings === void 0 && validOverflowBodyRef(r.bodyRef)) && (r.kind === void 0 || [
7341
7424
  "supervisor_message",
7342
7425
  "direct_response",
7343
7426
  "herd_settlement",
@@ -7429,7 +7512,7 @@ function writeProjectMessageUnlocked(record, runtime) {
7429
7512
  }
7430
7513
  if (cleanupFailed) throw cleanupError;
7431
7514
  }
7432
- function listProjectMessageHeaders(runtime, repoKey, branch) {
7515
+ function listProjectMessageHeaders(runtime, repoKey, branch, onReadError) {
7433
7516
  const directory2 = projectMessageDirectory(runtime, repoKey, branch);
7434
7517
  let entries;
7435
7518
  try {
@@ -7449,6 +7532,10 @@ function listProjectMessageHeaders(runtime, repoKey, branch) {
7449
7532
  } catch (error2) {
7450
7533
  if (error2 instanceof Error && error2.cause?.code === "ENOENT")
7451
7534
  return [];
7535
+ if (onReadError) {
7536
+ onReadError(error2);
7537
+ return [];
7538
+ }
7452
7539
  throw error2;
7453
7540
  }
7454
7541
  }).sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
@@ -7997,6 +8084,46 @@ var init_supervision = __esm({
7997
8084
  }
7998
8085
  });
7999
8086
 
8087
+ // extension/recipient-fan-in.ts
8088
+ function recipientFanInBudget() {
8089
+ return { count: 0, bytes: 0 };
8090
+ }
8091
+ function includeFanInMessage(budget, content, maximumBytes = MAX_BYTES) {
8092
+ const bytes = Buffer.byteLength(content, "utf8");
8093
+ if (budget.count >= COORDINATION_INBOX_SCAN_LIMIT || budget.count > 0 && budget.bytes + bytes > maximumBytes)
8094
+ return false;
8095
+ budget.count++;
8096
+ budget.bytes += bytes;
8097
+ return true;
8098
+ }
8099
+ function releaseFanInMessage(budget, content) {
8100
+ budget.count = Math.max(0, budget.count - 1);
8101
+ budget.bytes = Math.max(0, budget.bytes - Buffer.byteLength(content, "utf8"));
8102
+ }
8103
+ function registerRecipientFanIn(pi, drain) {
8104
+ pi.on("before_agent_start", async (event, ctx) => {
8105
+ await drain(ctx, "startup", recipientFanInBudget());
8106
+ });
8107
+ pi.on("turn_end", async (event, ctx) => {
8108
+ if (event?.outcome !== "completed") return;
8109
+ const count = await drain(ctx, "turn", recipientFanInBudget());
8110
+ if (count > 0) return { continue: true };
8111
+ });
8112
+ pi.on("agent_before_settle", async (event, ctx) => {
8113
+ if (event?.outcome !== "completed") return;
8114
+ const count = await drain(ctx, "settle", recipientFanInBudget());
8115
+ if (count > 0) return { continue: true };
8116
+ });
8117
+ }
8118
+ var MAX_BYTES;
8119
+ var init_recipient_fan_in = __esm({
8120
+ "extension/recipient-fan-in.ts"() {
8121
+ "use strict";
8122
+ init_supervision();
8123
+ MAX_BYTES = 256 * 1024;
8124
+ }
8125
+ });
8126
+
8000
8127
  // extension/presentation.ts
8001
8128
  import {
8002
8129
  DynamicBorder,
@@ -8028,7 +8155,7 @@ import {
8028
8155
  writeFileSync as writeFileSync4
8029
8156
  } from "node:fs";
8030
8157
  import { homedir as homedir3 } from "node:os";
8031
- import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative, sep as sep2 } from "node:path";
8158
+ import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative as relative2, sep as sep2 } from "node:path";
8032
8159
  function populateMenuFrame(container, theme, title, body, footer, help) {
8033
8160
  container.clear();
8034
8161
  container.addChild(new DynamicBorder((line) => theme.fg("border", line)));
@@ -8577,23 +8704,76 @@ function supervisionActivityMarker(state, activeAgents) {
8577
8704
  function supervisionLeadMarker(lead) {
8578
8705
  return supervisionActivityMarker(
8579
8706
  lead.runtimeState,
8580
- lead.agentCounts?.active ?? 0
8707
+ (lead.agentCounts?.active ?? 0) + (lead.leadCounts?.active ?? 0)
8581
8708
  );
8582
8709
  }
8583
8710
  function lifecycleColor(state) {
8584
8711
  return STATE_COLOR[lifecycleLabel(state)] ?? "muted";
8585
8712
  }
8713
+ function headerActivity(local, active) {
8714
+ const marker = supervisionActivityMarker(local, active ? 1 : 0);
8715
+ return {
8716
+ marker,
8717
+ color: marker === "\u25C9" ? "accent" : lifecycleColor(local)
8718
+ };
8719
+ }
8720
+ function activeStaffSnapshot(reports, fresh) {
8721
+ return fresh && presentationReports(reports).some(
8722
+ (report) => report.compatibility !== "incompatible" && (["working", "starting", "settling"].includes(report.runtimeState) || (report.agentCounts?.active ?? 0) > 0 || (report.leadCounts?.active ?? 0) > 0)
8723
+ );
8724
+ }
8586
8725
  function supervisionLeadColor(lead) {
8587
8726
  return supervisionLeadMarker(lead) === "\u25C9" ? "accent" : lifecycleColor(lead.runtimeState);
8588
8727
  }
8728
+ function formatGitChangeStats(git) {
8729
+ return git.additions !== void 0 && git.deletions !== void 0 && git.changedFiles !== void 0 ? git.additions + git.deletions > 0 ? `+${git.additions} -${git.deletions}` : git.changedFiles > 0 ? `${git.changedFiles}f` : "\xB10" : "";
8730
+ }
8731
+ function formatGitHeaderNumeric(git, theme) {
8732
+ const stats = formatGitChangeStats(git);
8733
+ if (!stats) return "";
8734
+ const lineChanges = git.additions !== void 0 && git.deletions !== void 0 && git.additions + git.deletions > 0;
8735
+ return [
8736
+ lineChanges ? themed(
8737
+ theme,
8738
+ git.additions > 0 ? "success" : "muted",
8739
+ `+${git.additions}`
8740
+ ) : themed(theme, "muted", stats),
8741
+ lineChanges ? ` ${themed(
8742
+ theme,
8743
+ git.deletions > 0 ? "error" : "muted",
8744
+ `-${git.deletions}`
8745
+ )}` : "",
8746
+ git.dirty ? themed(theme, "warning", "*") : ""
8747
+ ].join("");
8748
+ }
8749
+ function formatGitHeaderSuffix(git, theme, width) {
8750
+ const stats = formatGitChangeStats(git);
8751
+ const numeric = stats ? `${stats}${git.dirty ? "*" : ""}` : "";
8752
+ const styledNumeric = formatGitHeaderNumeric(git, theme);
8753
+ const branch = git.checkedOutBranch ? `\u2387 ${git.checkedOutBranch}` : "";
8754
+ if (!branch)
8755
+ return numeric && visibleWidth(numeric) <= width ? styledNumeric : !numeric && git.dirty && width >= 1 ? themed(theme, "warning", "*") : "";
8756
+ const dirtyMarker = !numeric && git.dirty ? "*" : "";
8757
+ const branchWidth = width - (numeric ? visibleWidth(numeric) + 1 : 0) - visibleWidth(dirtyMarker);
8758
+ if (branchWidth < visibleWidth("\u2387 \u2026"))
8759
+ return numeric && visibleWidth(numeric) <= width ? styledNumeric : "";
8760
+ const shownBranch = truncateToWidth(branch, branchWidth, "\u2026");
8761
+ if (visibleWidth(shownBranch) > branchWidth) return "";
8762
+ return `${themed(theme, "muted", shownBranch)}${dirtyMarker ? themed(theme, "warning", dirtyMarker) : ""}${numeric ? ` ${styledNumeric}` : ""}`;
8763
+ }
8589
8764
  function identifyingLabelVisible(text, label, width) {
8590
8765
  const start = text.lastIndexOf(label);
8591
8766
  return label.length > 0 && start >= 0 && visibleWidth(text.slice(0, start + label.length)) <= width;
8592
8767
  }
8593
- function renderSupervisionHeader(label, status, width, theme) {
8594
- const marker = themed(theme, "success", "\u25CF");
8595
- const markerWidth = visibleWidth("\u25CF");
8596
- const identity = themed(theme, "muted", label);
8768
+ function renderSupervisionHeader(role2, label, status, width, theme, local = "unknown", activeDescendants = false) {
8769
+ const { marker: markerValue, color } = headerActivity(
8770
+ local,
8771
+ activeDescendants
8772
+ );
8773
+ const marker = themed(theme, color, markerValue);
8774
+ const markerWidth = visibleWidth(markerValue);
8775
+ const roleText = themed(theme, "text", theme?.bold?.(role2) ?? role2);
8776
+ const identity = `${roleText}${themed(theme, "muted", label.slice(role2.length))}`;
8597
8777
  const freshnessText = status === "fresh" ? "" : `\xB7 ${status}`;
8598
8778
  const freshness = freshnessText ? themed(theme, "warning", freshnessText) : "";
8599
8779
  if (!freshness)
@@ -8625,7 +8805,15 @@ function renderSupervisionRows(reports, width, options = {}, selectedLead, getGi
8625
8805
  if (status === "unavailable")
8626
8806
  return [
8627
8807
  {
8628
- text: renderSupervisionHeader(role2, status, width, options.theme)
8808
+ text: renderSupervisionHeader(
8809
+ role2,
8810
+ role2,
8811
+ status,
8812
+ width,
8813
+ options.theme,
8814
+ options.localActivity,
8815
+ options.activeDescendants
8816
+ )
8629
8817
  }
8630
8818
  ];
8631
8819
  const displays = orderedSupervisionLeads(presentationReports(reports));
@@ -8646,10 +8834,13 @@ function renderSupervisionRows(reports, width, options = {}, selectedLead, getGi
8646
8834
  const project = managerSnapshot && "project" in managerSnapshot ? managerSnapshot.project : void 0;
8647
8835
  const headerText = role2 === "manager" ? `manager${project ? ` \xB7 ${project}` : ""}` : `chief \xB7 ${supervisionCountLabel(managers, leads)}${incompatible ? ` \xB7 ${incompatible} incompatible` : ""}`;
8648
8836
  const header = renderSupervisionHeader(
8837
+ role2,
8649
8838
  headerText,
8650
8839
  status,
8651
8840
  width,
8652
- options.theme
8841
+ options.theme,
8842
+ options.localActivity,
8843
+ options.activeDescendants
8653
8844
  );
8654
8845
  if (managerSnapshot && "leads" in managerSnapshot && !("managers" in managerSnapshot)) {
8655
8846
  const items = managerSupervisionItems(managerSnapshot);
@@ -8702,7 +8893,7 @@ function renderSupervisionRows(reports, width, options = {}, selectedLead, getGi
8702
8893
  const elapsed = metadata[index].elapsed;
8703
8894
  const context = metadata[index].context;
8704
8895
  const git = metadata[index].git;
8705
- const diff = git?.additions !== void 0 && git.deletions !== void 0 && git.changedFiles !== void 0 ? git.additions + git.deletions > 0 ? `+${git.additions} -${git.deletions}` : git.changedFiles > 0 ? `${git.changedFiles}f` : "\xB10" : "";
8896
+ const diff = git ? formatGitChangeStats(git) : "";
8706
8897
  const changedBranch = git?.checkedOutBranch !== void 0 && git.checkedOutBranch !== item.work.branch;
8707
8898
  const optionsToFit = [
8708
8899
  ...context ? [{ value: context, kind: "context" }] : [],
@@ -8958,6 +9149,29 @@ function formatSupervisionContext(snapshot, options) {
8958
9149
  ]
8959
9150
  ];
8960
9151
  const sections = [];
9152
+ const gitLines = [
9153
+ ...options.git?.managerSession ? [
9154
+ " manager_session:",
9155
+ ` cwd: ${supervisionValue(options.git.managerSession.cwd)}`,
9156
+ ` worktree_root: ${supervisionValue(options.git.managerSession.worktreeRoot)}`,
9157
+ ` branch: ${supervisionValue(options.git.managerSession.branch ?? "detached")}`,
9158
+ ` head: ${options.git.managerSession.head}`
9159
+ ] : [],
9160
+ ...options.git?.manager ? [
9161
+ " manager_checkout:",
9162
+ ` branch: ${supervisionValue(options.git.manager.branch ?? "detached")}`,
9163
+ ` head: ${options.git.manager.head}`
9164
+ ] : [],
9165
+ ...[...options.git?.assignments ?? /* @__PURE__ */ new Map()].map(
9166
+ ([assignment, observation]) => ` assignment ${supervisionValue(assignment)}: checkout_branch=${supervisionValue(observation.branch ?? "detached")} head=${observation.head}`
9167
+ ),
9168
+ ...[...options.git?.supervisedLeads ?? []].flatMap(
9169
+ ([session, observation]) => options.targets?.has(session) ? [
9170
+ ` supervised_lead ${supervisionValue(options.targets.get(session))}: checkout_branch=${supervisionValue(observation.branch ?? "detached")} head=${observation.head}`
9171
+ ] : []
9172
+ )
9173
+ ];
9174
+ const gitSection = gitLines.length ? ["git_observations:", ...gitLines].join("\n") : void 0;
8961
9175
  if (snapshot?.diagnostics?.length)
8962
9176
  sections.push(
8963
9177
  [
@@ -9052,6 +9266,7 @@ function formatSupervisionContext(snapshot, options) {
9052
9266
  included.pop();
9053
9267
  included.push(...notice);
9054
9268
  }
9269
+ if (gitSection && fits([...included, gitSection])) included.push(gitSection);
9055
9270
  return [...included, closing].join("\n");
9056
9271
  }
9057
9272
  function boundedWidgetRows(supervision, agents, maxRows, width) {
@@ -9069,28 +9284,49 @@ function boundedWidgetRows(supervision, agents, maxRows, width) {
9069
9284
  { text: safeLine("\u2026 more", width) }
9070
9285
  ];
9071
9286
  }
9072
- function createSupervisionWidget(getLeads, getStatus, role2 = "chief", theme, onFocus, getGitSummary, ownedAgents, getMaxRows = () => 8) {
9287
+ function createSupervisionWidget(getLeads, getStatus, role2 = "chief", theme, onFocus, getGitSummary, ownedAgents, getMaxRows = () => 8, getHeaderGitSummary, getLocalActivity) {
9073
9288
  let renderedWidth = -1;
9074
9289
  let hits = [];
9075
9290
  return {
9076
9291
  render(width) {
9077
9292
  renderedWidth = width;
9293
+ const status = getStatus();
9294
+ const supervision = getLeads();
9078
9295
  const snapshot = ownedAgents?.getSnapshot();
9296
+ const activeOwned = !!snapshot && !snapshot.stale && !snapshot.unavailable && snapshot.agents.some(
9297
+ (agent) => ["working", "starting", "settling"].includes(agent.state)
9298
+ );
9299
+ const activeDescendants = activeStaffSnapshot(supervision, status === "fresh") || activeOwned;
9079
9300
  const showAgents = !!snapshot && (snapshot.agents.length > 0 || snapshot.stale || snapshot.unavailable);
9080
9301
  const rows = renderSupervisionRows(
9081
- getLeads(),
9302
+ supervision,
9082
9303
  width,
9083
9304
  {
9084
- status: getStatus(),
9305
+ status,
9085
9306
  ordinaryCap: getMaxRows(),
9086
9307
  childCap: getMaxRows(),
9087
9308
  role: role2,
9088
9309
  theme,
9089
- hasFollowingGroup: showAgents
9310
+ hasFollowingGroup: showAgents,
9311
+ localActivity: getLocalActivity?.() ?? "unknown",
9312
+ activeDescendants
9090
9313
  },
9091
9314
  void 0,
9092
9315
  getGitSummary
9093
9316
  ).filter(({ text }, index) => index === 0 || text.length > 0);
9317
+ if (role2 === "manager" && status === "fresh") {
9318
+ const git = getHeaderGitSummary?.();
9319
+ if (git && rows[0]) {
9320
+ const header = rows[0].text;
9321
+ const suffix = formatGitHeaderSuffix(
9322
+ git,
9323
+ theme,
9324
+ width - visibleWidth(header) - 2
9325
+ );
9326
+ if (suffix && visibleWidth(header) + 2 + visibleWidth(suffix) <= width)
9327
+ rows[0].text = `${header}${" ".repeat(width - visibleWidth(header) - visibleWidth(suffix))}${suffix}`;
9328
+ }
9329
+ }
9094
9330
  const agentRows = [];
9095
9331
  if (showAgents && snapshot) {
9096
9332
  const freshness = snapshot.unavailable ? "unavailable" : snapshot.stale ? "stale" : String(snapshot.agents.length);
@@ -9297,14 +9533,13 @@ function safeDisplaySegment(value2) {
9297
9533
  return code <= 31 || code === 127 ? " " : character;
9298
9534
  }).replace(/\s+/gu, " ").trim();
9299
9535
  }
9300
- function renderBreadcrumb(segments, width) {
9536
+ function renderBreadcrumb(segments, width, marker = "?", theme) {
9301
9537
  if (width <= 0) return { text: "", hits: [] };
9302
9538
  const visible = segments.map((segment) => ({ ...segment, text: safeDisplaySegment(segment.text) })).filter((segment) => segment.text);
9303
9539
  const current = visible.at(-1) ?? { text: "?" };
9304
- const marker = "\u25CF";
9305
9540
  if (width <= visibleWidth(marker))
9306
9541
  return { text: truncateToWidth(marker, width, ""), hits: [] };
9307
- const prefix = `${marker} `;
9542
+ const prefix = `${marker}${themed(theme, "muted", " ")}`;
9308
9543
  const available = width - visibleWidth(prefix);
9309
9544
  if (available <= 0) return { text: marker, hits: [] };
9310
9545
  const currentText = tailTruncate(current.text, available);
@@ -9315,7 +9550,10 @@ function renderBreadcrumb(segments, width) {
9315
9550
  if (visibleWidth(candidateText) <= width) included.unshift(visible[index]);
9316
9551
  else break;
9317
9552
  }
9318
- const text = `${prefix}${included.map(({ text: text2 }) => text2).join(" \u2192 ")}`;
9553
+ const text = `${prefix}${included.map((segment, index) => {
9554
+ const role2 = index === included.length - 1 && segment.role && segment.text.startsWith(segment.role) ? segment.role : void 0;
9555
+ return role2 ? `${themed(theme, "text", theme?.bold?.(role2) ?? role2)}${themed(theme, "muted", segment.text.slice(role2.length))}` : themed(theme, "muted", segment.text);
9556
+ }).join(" \u2192 ")}`;
9319
9557
  const hits = [];
9320
9558
  let x = visibleWidth(prefix);
9321
9559
  included.forEach((segment, index) => {
@@ -9393,7 +9631,7 @@ function formatAgentDefinitions(definitions) {
9393
9631
  function displayHomePath(path) {
9394
9632
  const home = homedir3();
9395
9633
  if (!isAbsolute4(path)) return path;
9396
- const remainder = relative(home, path);
9634
+ const remainder = relative2(home, path);
9397
9635
  if (remainder === "") return "~";
9398
9636
  if (remainder !== ".." && !remainder.startsWith(`..${sep2}`))
9399
9637
  return `~/${remainder}`;
@@ -9695,8 +9933,8 @@ function formatToolModelResult(action, v) {
9695
9933
  }
9696
9934
  if (action === "interrupt") {
9697
9935
  return [
9698
- `Interrupt accepted for agent ${value(v.agent) || "unknown"}.`,
9699
- "The current Pi operation was asked to stop and the replacement instruction continues the same assignment.",
9936
+ v.delivered_as === "steer" ? `Interrupt request delivered via steering for agent ${value(v.agent) || "unknown"}.` : `Interrupt accepted for agent ${value(v.agent) || "unknown"}.`,
9937
+ v.delivered_as === "steer" ? value(v.note) || "The agent was waiting for child work. The message was delivered via steering; nothing was interrupted." : "The current Pi operation was asked to stop and the replacement instruction continues the same assignment.",
9700
9938
  ...value(v.session_id) ? [`Session: ${v.session_id}`] : [],
9701
9939
  ...value(v.request_id) ? [`Request: ${v.request_id}`] : [],
9702
9940
  ...value(v.assignment_request_id) ? [`Assignment request: ${v.assignment_request_id}`] : [],
@@ -9769,6 +10007,7 @@ function formatToolModelResult(action, v) {
9769
10007
  ...value(v.request_id) ? [`Request: ${v.request_id}`] : [],
9770
10008
  ...value(v.assignment_request_id) ? [`Assignment request: ${v.assignment_request_id}`] : [],
9771
10009
  ...action === "reply" && value(v.ask_id) ? [`Ask: ${v.ask_id}`] : [],
10010
+ ...value(v.history_warning) ? [`History warning: ${value(v.history_warning)}`] : [],
9772
10011
  ...(action === "delegate" || action === "continue") && v.evidence && typeof v.evidence === "object" ? (() => {
9773
10012
  const evidence = v.evidence;
9774
10013
  const lines = [
@@ -10655,6 +10894,7 @@ function renderCoordinationMessage(kind, message, options, theme) {
10655
10894
  toDisplayName: optionalString("toDisplayName"),
10656
10895
  kind: projectKind
10657
10896
  };
10897
+ const senderEnvironment = validSenderEnvironment(rawDetails.senderEnvironment) ? rawDetails.senderEnvironment : void 0;
10658
10898
  const branch = d?.branch ?? "project work";
10659
10899
  const messageContent = contentText(message.content ?? "");
10660
10900
  let heading = "";
@@ -10691,7 +10931,8 @@ function renderCoordinationMessage(kind, message, options, theme) {
10691
10931
  break;
10692
10932
  }
10693
10933
  }
10694
- let body = messageContent;
10934
+ const annotation = senderEnvironment ? senderEnvironmentAnnotation(senderEnvironment) : "";
10935
+ let body = annotation && messageContent.endsWith(annotation) ? messageContent.slice(0, -annotation.length) : messageContent;
10695
10936
  if (prefix && body.startsWith(prefix)) body = body.slice(prefix.length);
10696
10937
  const content = new Container();
10697
10938
  content.addChild(new WidthSafeText(heading, 0, 0));
@@ -10700,7 +10941,15 @@ function renderCoordinationMessage(kind, message, options, theme) {
10700
10941
  ...d?.branch ? [`branch: ${d.branch}`] : [],
10701
10942
  ...senderRole && d?.fromSessionId ? [`from session: ${d.fromSessionId}`] : [],
10702
10943
  ...senderRole && d?.toSessionId ? [`to session: ${d.toSessionId}`] : [],
10703
- ...!senderRole && kind !== "project_assignment" && (d?.fromSessionId ?? d?.leadSessionId) ? [`session: ${d?.fromSessionId ?? d?.leadSessionId}`] : []
10944
+ ...!senderRole && kind !== "project_assignment" && (d?.fromSessionId ?? d?.leadSessionId) ? [`session: ${d?.fromSessionId ?? d?.leadSessionId}`] : [],
10945
+ ...senderEnvironment ? [
10946
+ `sender cwd: ${senderEnvironment.cwd}`,
10947
+ ...senderEnvironment.git ? [
10948
+ `worktree: ${senderEnvironment.git.worktreeRoot}`,
10949
+ `checked-out branch: ${senderEnvironment.git.branch ?? "detached"}`,
10950
+ `HEAD: ${senderEnvironment.git.head}`
10951
+ ] : []
10952
+ ] : []
10704
10953
  ];
10705
10954
  if (metadata.length) {
10706
10955
  content.addChild(new Spacer(1));
@@ -10956,8 +11205,15 @@ function renderAgentLostMessage(message, options, theme) {
10956
11205
  options.outputPad ?? 0
10957
11206
  );
10958
11207
  }
10959
- function createStatusWidget(invalidate, theme, onFocus, getMaxRows) {
10960
- return new StatusWidget(invalidate, theme, onFocus, getMaxRows);
11208
+ function createStatusWidget(invalidate, theme, onFocus, getMaxRows, getGitSummary, getLocalActivity) {
11209
+ return new StatusWidget(
11210
+ invalidate,
11211
+ theme,
11212
+ onFocus,
11213
+ getMaxRows,
11214
+ getGitSummary,
11215
+ getLocalActivity
11216
+ );
10961
11217
  }
10962
11218
  var LIFECYCLE, animates, STATE_COLOR, MIN_TASK_WIDTH, STATUS_LAYOUTS, SUPERVISION_GROUPS, SUPERVISION_CONTEXT_MAX_BYTES, remoteDiagnosticMessages, maxRemoteDiagnostics, WidthSafeText, spinner, StatusWidget;
10963
11219
  var init_presentation = __esm({
@@ -11046,10 +11302,14 @@ var init_presentation = __esm({
11046
11302
  renderedWidth = -1;
11047
11303
  hits = [];
11048
11304
  getMaxRows;
11049
- constructor(invalidateUI, theme, onFocus, getMaxRows = () => 8) {
11305
+ getGitSummary;
11306
+ getLocalActivity;
11307
+ constructor(invalidateUI, theme, onFocus, getMaxRows = () => 8, getGitSummary, getLocalActivity = () => "unknown") {
11050
11308
  this.invalidateUI = invalidateUI;
11051
11309
  this.getMaxRows = getMaxRows;
11052
11310
  this.onFocus = onFocus;
11311
+ this.getGitSummary = getGitSummary;
11312
+ this.getLocalActivity = getLocalActivity;
11053
11313
  this.theme = theme ?? {
11054
11314
  fg: (_color, text) => text,
11055
11315
  bold: (text) => text
@@ -11076,6 +11336,13 @@ var init_presentation = __esm({
11076
11336
  }
11077
11337
  render(width) {
11078
11338
  const s = this.snapshot;
11339
+ const local = this.getLocalActivity();
11340
+ const marker = headerActivity(
11341
+ local,
11342
+ !s.stale && !s.unavailable && s.agents.some(
11343
+ (agent) => ["working", "starting", "settling"].includes(agent.state)
11344
+ )
11345
+ ).marker;
11079
11346
  this.renderedWidth = width;
11080
11347
  this.hits = [];
11081
11348
  const availableWidth = Math.max(0, width);
@@ -11091,12 +11358,19 @@ var init_presentation = __esm({
11091
11358
  const freshnessSuffixWidth = visibleWidth(freshnessSuffix);
11092
11359
  const breadcrumbSegments = s.breadcrumb ?? [{ text: "?" }];
11093
11360
  const fullIdentityWidth = visibleWidth(
11094
- renderBreadcrumb(breadcrumbSegments, Number.MAX_SAFE_INTEGER).text
11361
+ renderBreadcrumb(
11362
+ breadcrumbSegments,
11363
+ Number.MAX_SAFE_INTEGER,
11364
+ marker,
11365
+ this.theme
11366
+ ).text
11095
11367
  );
11096
11368
  const reservedSuffixWidth = freshness && fullSuffixWidth + fullIdentityWidth <= availableWidth ? fullSuffixWidth : freshnessSuffixWidth || (fullSuffixWidth + fullIdentityWidth <= availableWidth ? fullSuffixWidth : 0);
11097
11369
  const renderedBreadcrumb = renderBreadcrumb(
11098
11370
  breadcrumbSegments,
11099
- Math.max(0, availableWidth - reservedSuffixWidth)
11371
+ Math.max(0, availableWidth - reservedSuffixWidth),
11372
+ marker,
11373
+ this.theme
11100
11374
  );
11101
11375
  const breadcrumb = renderedBreadcrumb.text;
11102
11376
  if (!s.stale && !s.unavailable) this.hits.push(...renderedBreadcrumb.hits);
@@ -11127,14 +11401,30 @@ var init_presentation = __esm({
11127
11401
  );
11128
11402
  if (visibleWidth(breadcrumb) + visibleWidth(shownExecution) + visibleWidth(tools) + visibleWidth(run2) + visibleWidth(suffixText) > availableWidth)
11129
11403
  run2 = "";
11130
- const styledBreadcrumb = this.theme.fg("success", breadcrumb);
11404
+ const markerColor = headerActivity(local, marker === "\u25C9").color;
11405
+ const styledBreadcrumb = breadcrumb.startsWith(marker) ? `${this.theme.fg(markerColor, marker)}${breadcrumb.slice(marker.length)}` : breadcrumb;
11131
11406
  const styledExecution = shownExecution ? this.theme.fg("muted", shownExecution) : "";
11132
11407
  const styledTools = tools ? this.theme.fg("muted", tools) : "";
11133
11408
  const styledRun = run2 ? this.theme.fg("accent", run2) : "";
11134
11409
  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);
11135
- const header = `${styledBreadcrumb}${styledExecution}${styledTools}${styledRun}${styledSuffix}`;
11136
- const compactStaleHeader = s.stale && !s.unavailable && !breadcrumb && visibleWidth("\u25CF stale") <= availableWidth ? `${this.theme.fg("success", "\u25CF")} ${this.theme.fg("warning", "stale")}` : header;
11137
- const out = [truncateToWidth(compactStaleHeader, availableWidth, "\u2026")];
11410
+ const builtHeader = `${styledBreadcrumb}${styledExecution}${styledTools}${styledRun}${styledSuffix}`;
11411
+ const compactStaleHeader = s.stale && !s.unavailable && !breadcrumb && visibleWidth(`${marker} stale`) <= availableWidth ? `${this.theme.fg(markerColor, marker)} ${this.theme.fg("warning", "stale")}` : builtHeader;
11412
+ let header = truncateToWidth(compactStaleHeader, availableWidth, "\u2026");
11413
+ const observedGit = !s.stale && !s.unavailable ? this.getGitSummary?.() : void 0;
11414
+ const gitSummary = observedGit && s.execution?.kind === "managed" && s.execution.lifecycle !== "assigned" ? observedGit.checkedOutBranch ? {
11415
+ dirty: observedGit.dirty,
11416
+ checkedOutBranch: observedGit.checkedOutBranch
11417
+ } : void 0 : observedGit;
11418
+ if (gitSummary) {
11419
+ const suffix = formatGitHeaderSuffix(
11420
+ gitSummary,
11421
+ this.theme,
11422
+ availableWidth - visibleWidth(header) - 2
11423
+ );
11424
+ if (suffix && visibleWidth(header) + 2 + visibleWidth(suffix) <= availableWidth)
11425
+ header = `${header}${" ".repeat(availableWidth - visibleWidth(header) - visibleWidth(suffix))}${suffix}`;
11426
+ }
11427
+ const out = [header];
11138
11428
  if (s.identityOnly) return out;
11139
11429
  const rows = renderStatusRows(s.agents, {
11140
11430
  now: observedNow,
@@ -12780,6 +13070,9 @@ import {
12780
13070
  } from "node:fs";
12781
13071
  import { randomUUID as randomUUID9 } from "node:crypto";
12782
13072
  import { basename as basename7, dirname as dirname7, join as join8 } from "node:path";
13073
+ function validManagerMergeSetting(value2) {
13074
+ return typeof value2 === "boolean" || value2 === "divergent";
13075
+ }
12783
13076
  function validByteLimit(value2) {
12784
13077
  return typeof value2 === "number" && Number.isInteger(value2) && value2 >= MIN_BYTE_LIMIT && value2 <= MAX_BYTE_LIMIT;
12785
13078
  }
@@ -12806,7 +13099,7 @@ function containsControlCharacter(value2) {
12806
13099
  }
12807
13100
  function validManagerMergeOverrides(value2) {
12808
13101
  return !!value2 && typeof value2 === "object" && !Array.isArray(value2) && Object.entries(value2).every(
12809
- ([repoKey, enabled]) => validRepoIdentity(repoKey) && typeof enabled === "boolean"
13102
+ ([repoKey, enabled]) => validRepoIdentity(repoKey) && validManagerMergeSetting(enabled)
12810
13103
  );
12811
13104
  }
12812
13105
  function parseRawConfig(content) {
@@ -12863,7 +13156,7 @@ function parseRawConfig(content) {
12863
13156
  result.managerGitBootstrapWithoutConfirmation = record.managerGitBootstrapWithoutConfirmation;
12864
13157
  }
12865
13158
  if ("managerMergeEnabled" in record) {
12866
- if (typeof record.managerMergeEnabled !== "boolean")
13159
+ if (!validManagerMergeSetting(record.managerMergeEnabled))
12867
13160
  throw new Error("Invalid Pi Herdsman config field managerMergeEnabled");
12868
13161
  result.managerMergeEnabled = record.managerMergeEnabled;
12869
13162
  }
@@ -12898,12 +13191,17 @@ function effectiveMergePolicy(config, repoKey) {
12898
13191
  if (!validRepoIdentity(repoKey))
12899
13192
  throw new Error("A verified repository identity is required");
12900
13193
  const override = config.managerMergeOverrides[repoKey];
12901
- return !Object.hasOwn(config.managerMergeOverrides, repoKey) ? { enabled: config.managerMergeEnabled, source: "global" } : { enabled: override, source: "repository" };
13194
+ const setting = !Object.hasOwn(config.managerMergeOverrides, repoKey) ? config.managerMergeEnabled : override;
13195
+ return {
13196
+ enabled: setting !== false,
13197
+ allowDivergence: setting === "divergent",
13198
+ source: Object.hasOwn(config.managerMergeOverrides, repoKey) ? "repository" : "global"
13199
+ };
12902
13200
  }
12903
13201
  function setManagerMergeOverride(repoKey, enabled) {
12904
- if (!validRepoIdentity(repoKey) || enabled !== void 0 && typeof enabled !== "boolean")
13202
+ if (!validRepoIdentity(repoKey) || enabled !== void 0 && !validManagerMergeSetting(enabled))
12905
13203
  throw new Error(
12906
- "A verified repository identity and optional boolean policy are required"
13204
+ "A verified repository identity and optional merge policy are required"
12907
13205
  );
12908
13206
  const path = herdsmanConfigPath();
12909
13207
  const release = claimProcessLock(`${path}.lock`, {
@@ -13156,7 +13454,7 @@ function updateConfig(key, value2) {
13156
13454
  throw new Error(
13157
13455
  "Invalid Pi Herdsman config field managerGitBootstrapWithoutConfirmation"
13158
13456
  );
13159
- if (key === "managerMergeEnabled" && typeof value2 !== "boolean")
13457
+ if (key === "managerMergeEnabled" && !validManagerMergeSetting(value2))
13160
13458
  throw new Error("Invalid Pi Herdsman config field managerMergeEnabled");
13161
13459
  if (key === "managerMergeOverrides" && !validManagerMergeOverrides(value2))
13162
13460
  throw new Error(
@@ -13247,7 +13545,7 @@ import { setTimeout as delay } from "node:timers/promises";
13247
13545
  import { StringEnum } from "@earendil-works/pi-ai";
13248
13546
  import { Type } from "typebox";
13249
13547
  function rootStatusBreadcrumb(role2) {
13250
- return [{ text: role2 ?? "owner/controller" }];
13548
+ return [{ text: role2 ?? "owner/controller", ...role2 ? { role: role2 } : {} }];
13251
13549
  }
13252
13550
  function buildAgentStatusSnapshot(view, ctx, host) {
13253
13551
  const ownerSessionId = ctx.sessionManager.getSessionId();
@@ -13304,6 +13602,35 @@ function buildAgentStatusSnapshot(view, ctx, host) {
13304
13602
  refreshedAt: Date.now()
13305
13603
  };
13306
13604
  }
13605
+ function observeLocalHeaderActivity(pi, invalidate) {
13606
+ let promptSession;
13607
+ pi.on("ui_prompt_start", (_event, ctx) => {
13608
+ promptSession = ctx.sessionManager.getSessionId();
13609
+ invalidate();
13610
+ });
13611
+ pi.on("ui_prompt_end", (_event, ctx) => {
13612
+ if (promptSession === ctx.sessionManager.getSessionId())
13613
+ promptSession = void 0;
13614
+ invalidate();
13615
+ });
13616
+ pi.on("agent_start", invalidate);
13617
+ pi.on("agent_settled", invalidate);
13618
+ pi.on("session_start", () => {
13619
+ promptSession = void 0;
13620
+ invalidate();
13621
+ });
13622
+ pi.on("session_shutdown", () => {
13623
+ promptSession = void 0;
13624
+ });
13625
+ return (ctx) => {
13626
+ try {
13627
+ if (ctx.isIdle()) return "idle";
13628
+ return promptSession === ctx.sessionManager.getSessionId() ? "blocked" : "working";
13629
+ } catch {
13630
+ return "unknown";
13631
+ }
13632
+ };
13633
+ }
13307
13634
  function createAgentStatusRuntime() {
13308
13635
  let options;
13309
13636
  let statusWidget;
@@ -13392,6 +13719,12 @@ function createAgentStatusRuntime() {
13392
13719
  lastValidStatus = snapshot;
13393
13720
  reconcilePendingStarts(snapshot);
13394
13721
  publishStatus(snapshot);
13722
+ if (statusWidget) {
13723
+ try {
13724
+ configured.onFreshStatus?.(ctx, snapshot);
13725
+ } catch {
13726
+ }
13727
+ }
13395
13728
  syncNewAgentWatch(ctx, generation);
13396
13729
  } catch {
13397
13730
  if (generation === statusGeneration && ctx === statusContext)
@@ -13451,6 +13784,10 @@ function createAgentStatusRuntime() {
13451
13784
  void refresh(ctx, generation);
13452
13785
  };
13453
13786
  const removeWidget = () => {
13787
+ try {
13788
+ options?.onWidgetStop?.();
13789
+ } catch {
13790
+ }
13454
13791
  if (statusWidget) {
13455
13792
  statusContext?.ui.setWidget("pi-herdsman", void 0);
13456
13793
  statusWidget.dispose();
@@ -13470,6 +13807,8 @@ function createAgentStatusRuntime() {
13470
13807
  void refresh(statusContext, statusGeneration);
13471
13808
  },
13472
13809
  getSnapshot: () => presentedStatus,
13810
+ invalidateWidget: () => statusWidget?.invalidate(),
13811
+ isWidgetActive: () => !!statusWidget,
13473
13812
  startObserver: (ctx, onChange) => {
13474
13813
  if (ctx.mode !== "tui" || !ctx.hasUI) return;
13475
13814
  const primed = statusPrimed && ctx === statusContext;
@@ -13500,6 +13839,7 @@ function createAgentStatusRuntime() {
13500
13839
  const primed = statusPrimed && ctx === statusContext;
13501
13840
  const generation = ctx === statusContext && requestActive ? statusGeneration : ++statusGeneration;
13502
13841
  clearTimer();
13842
+ removeWidget();
13503
13843
  statusContext = ctx;
13504
13844
  ctx.ui.setWidget("pi-herdsman", (tui, theme) => {
13505
13845
  let widget;
@@ -13523,12 +13863,20 @@ function createAgentStatusRuntime() {
13523
13863
  if (generation === statusGeneration) focusInFlight = false;
13524
13864
  });
13525
13865
  },
13526
- () => statusWidgetMaxRows
13866
+ () => statusWidgetMaxRows,
13867
+ () => options?.getGitSummary?.(),
13868
+ () => options?.getLocalActivity?.(ctx) ?? "unknown"
13527
13869
  );
13528
13870
  widget.setSnapshot(widgetSnapshot(presentedStatus, true));
13529
13871
  if (generation === statusGeneration && ctx === statusContext) {
13530
13872
  statusWidget = widget;
13531
13873
  statusWidgetGeneration = generation;
13874
+ if (primed) {
13875
+ try {
13876
+ options?.onFreshStatus?.(ctx, lastValidStatus);
13877
+ } catch {
13878
+ }
13879
+ }
13532
13880
  } else widget.dispose();
13533
13881
  return widget;
13534
13882
  });
@@ -13542,16 +13890,19 @@ function createAgentStatusRuntime() {
13542
13890
  clear: () => {
13543
13891
  ++statusGeneration;
13544
13892
  clearTimer();
13545
- if (statusContext) statusContext.ui.setWidget("pi-herdsman", void 0);
13546
- statusWidget?.dispose();
13547
- statusWidget = void 0;
13893
+ removeWidget();
13548
13894
  requestActive = false;
13549
13895
  focusInFlight = false;
13550
13896
  statusPrimed = false;
13551
13897
  statusRefresh = false;
13552
13898
  statusInFlight = false;
13553
13899
  onStatusChange = void 0;
13554
- presentedStatus = { agents: [], stale: false, unavailable: true };
13900
+ lastValidStatus = {
13901
+ agents: [],
13902
+ stale: false,
13903
+ unavailable: true
13904
+ };
13905
+ presentedStatus = lastValidStatus;
13555
13906
  },
13556
13907
  prepareSession: (ctx, beforeActivate) => {
13557
13908
  clearTimer();
@@ -13581,10 +13932,10 @@ function createAgentStatusRuntime() {
13581
13932
  shutdown: () => {
13582
13933
  ++statusGeneration;
13583
13934
  clearTimer();
13935
+ removeWidget();
13584
13936
  statusRefresh = false;
13585
13937
  statusInFlight = false;
13586
13938
  focusInFlight = false;
13587
- removeWidget();
13588
13939
  statusWidgetGeneration = 0;
13589
13940
  statusContext = void 0;
13590
13941
  requestActive = false;
@@ -13988,48 +14339,120 @@ function closedAssignmentReceipt(entries, ownerSessionId, child) {
13988
14339
  return [];
13989
14340
  const message = entry.message;
13990
14341
  const details = message?.details;
13991
- const proof2 = details?.closed_assignment;
13992
- if (message?.role !== "toolResult" || !(message.toolName === "close_agent" && details?.action === "close" || message.toolName === "stop_agent" && details?.action === "stop") || message.isError === true || details?.ok !== true || details.cleanup_error !== void 0 || details.cleanup_errors !== void 0 || !validClosedProof(proof2, ownerSessionId, child))
14342
+ const proof = details?.closed_assignment;
14343
+ if (message?.role !== "toolResult" || !(message.toolName === "close_agent" && details?.action === "close" || message.toolName === "stop_agent" && details?.action === "stop") || message.isError === true || details?.ok !== true || details.cleanup_error !== void 0 || details.cleanup_errors !== void 0 || !validClosedProof(proof, ownerSessionId, child))
13993
14344
  return [];
13994
- return [{ index, proof: proof2 }];
14345
+ return [{ index, proof }];
13995
14346
  });
13996
14347
  const stopped = entries.flatMap((entry, index) => {
13997
14348
  if (!entry || typeof entry !== "object" || !("type" in entry) || entry.type !== "custom" || !("customType" in entry) || entry.customType !== STOP_CLOSURE_ENTRY)
13998
14349
  return [];
13999
14350
  const data = entry.data;
14000
- const proof2 = data?.proof;
14001
- if (data?.version !== 1 || !validClosedProof(proof2, ownerSessionId, child))
14351
+ const proof = data?.proof;
14352
+ if (data?.version !== 1 || !validClosedProof(proof, ownerSessionId, child))
14002
14353
  return [];
14003
- return [{ index, proof: proof2 }];
14354
+ return [{ index, proof }];
14004
14355
  });
14005
14356
  closed.push(...stopped);
14006
14357
  const latestAccepted = accepted.at(-1);
14007
14358
  const matches = latestAccepted ? closed.filter(
14008
- ({ index, proof: proof2 }) => latestAccepted.index < index && latestAccepted.requestId === proof2.request_id
14359
+ ({ index, proof }) => latestAccepted.index < index && latestAccepted.requestId === proof.request_id
14009
14360
  ) : [];
14010
- if (!matches.length || matches.length !== 1) return void 0;
14011
- const { proof } = matches[0];
14012
- return proof;
14013
- }
14014
- function acceptedAssignmentReceipts(entries, ownerSessionId, child) {
14015
- return entries.flatMap((entry, index) => {
14016
- if (!entry || typeof entry !== "object" || !("type" in entry) || entry.type !== "message" || !("message" in entry))
14017
- return [];
14018
- const message = entry.message;
14019
- const details = message?.details;
14020
- if (message?.role !== "toolResult" || ![
14021
- "delegate_agent",
14022
- "continue_agent",
14023
- "agent_delegate",
14024
- "agent_continue"
14025
- ].includes(message.toolName) || message.isError === true || details?.ok !== true || details.owner_session_id !== ownerSessionId || details.session_id !== child.id || details.agent !== child.label || details.definition !== child.definition || typeof details.session_path !== "string" || !validId(details.request_id))
14361
+ if (!matches.length) return void 0;
14362
+ const proofs = [];
14363
+ for (const { proof } of matches)
14364
+ if (!proofs.some((candidate) => isDeepStrictEqual2(candidate, proof)))
14365
+ proofs.push(proof);
14366
+ return proofs.length === 1 ? proofs[0] : void 0;
14367
+ }
14368
+ function acceptedAssignmentEvidence(entries, ownerSessionId, unavailable) {
14369
+ const parsed = entries.flatMap((entry, index) => {
14370
+ let details;
14371
+ let action;
14372
+ let legacyResult = false;
14373
+ if (entry && typeof entry === "object" && "type" in entry && entry.type === "custom" && "customType" in entry && entry.customType === ACCEPTED_ASSIGNMENT_ENTRY) {
14374
+ const data = entry.data;
14375
+ const fields = [
14376
+ "version",
14377
+ "action",
14378
+ "owner_session_id",
14379
+ "session_id",
14380
+ "session_path",
14381
+ "request_id",
14382
+ "agent",
14383
+ "definition"
14384
+ ];
14385
+ if (!data || typeof data !== "object" || Array.isArray(data) || data.version !== 1 || Object.keys(data).length !== fields.length || !fields.every((field) => Object.hasOwn(data, field)))
14386
+ return [];
14387
+ details = data;
14388
+ action = data.action;
14389
+ } else if (entry && typeof entry === "object" && "type" in entry && entry.type === "message" && "message" in entry) {
14390
+ const message = entry.message;
14391
+ legacyResult = true;
14392
+ if (message?.role !== "toolResult" || message.isError === true || message.details?.ok !== true)
14393
+ return [];
14394
+ const actions = {
14395
+ delegate_agent: "delegate",
14396
+ agent_delegate: "delegate",
14397
+ continue_agent: "continue",
14398
+ agent_continue: "continue"
14399
+ };
14400
+ action = actions[message.toolName];
14401
+ details = message.details;
14402
+ } else return [];
14403
+ if (action !== "delegate" && action !== "continue" || !validId(details?.owner_session_id) || !validId(details?.session_id) || !validId(details?.request_id) || typeof details?.session_path !== "string" || typeof details?.agent !== "string" || !details.agent.trim() || typeof details?.definition !== "string" || !details.definition.trim()) {
14404
+ if (legacyResult && details?.owner_session_id === ownerSessionId)
14405
+ unavailable?.();
14026
14406
  return [];
14407
+ }
14408
+ const assignmentAction = action;
14027
14409
  try {
14028
- return canonicalSessionPath(details.session_path) === canonicalSessionPath(child.path) ? [{ index, requestId: details.request_id }] : [];
14410
+ return [
14411
+ {
14412
+ index,
14413
+ action: assignmentAction,
14414
+ ownerSessionId: details.owner_session_id,
14415
+ sessionId: details.session_id,
14416
+ sessionPath: canonicalSessionPath(details.session_path),
14417
+ requestId: details.request_id,
14418
+ agent: details.agent,
14419
+ definition: details.definition
14420
+ }
14421
+ ];
14029
14422
  } catch {
14423
+ if (legacyResult && details.owner_session_id === ownerSessionId)
14424
+ unavailable?.();
14030
14425
  return [];
14031
14426
  }
14032
14427
  });
14428
+ const byRequest = /* @__PURE__ */ new Map();
14429
+ for (const item of parsed)
14430
+ byRequest.set(item.requestId, [
14431
+ ...byRequest.get(item.requestId) ?? [],
14432
+ item
14433
+ ]);
14434
+ return [...byRequest.values()].flatMap((items) => {
14435
+ const identities = new Set(
14436
+ items.map(({ index: _index, ...identity }) => JSON.stringify(identity))
14437
+ );
14438
+ if (identities.size !== 1) return [];
14439
+ return [
14440
+ items.reduce(
14441
+ (earliest, item) => item.index < earliest.index ? item : earliest
14442
+ )
14443
+ ];
14444
+ }).filter((receipt) => receipt.ownerSessionId === ownerSessionId).sort((a, b) => a.index - b.index);
14445
+ }
14446
+ function acceptedAssignmentReceipts(entries, ownerSessionId, child) {
14447
+ let path;
14448
+ try {
14449
+ path = canonicalSessionPath(child.path);
14450
+ } catch {
14451
+ return [];
14452
+ }
14453
+ return acceptedAssignmentEvidence(entries, ownerSessionId).filter(
14454
+ (receipt) => receipt.sessionId === child.id && receipt.sessionPath === path && receipt.agent === child.label && receipt.definition === child.definition
14455
+ ).map(({ index, requestId }) => ({ index, requestId }));
14033
14456
  }
14034
14457
  function closedAssignmentChildren(entries, ownerSessionId) {
14035
14458
  const candidates = ownedAssignmentChildren(entries, ownerSessionId, true);
@@ -14202,13 +14625,15 @@ function statusBreadcrumb(snapshot, candidate, identity, sameIdentity) {
14202
14625
  return [
14203
14626
  { text: "?" },
14204
14627
  {
14205
- text: identity.definition && identity.label ? displayIdentity(identity.definition, identity.label) : identity.definition ?? "?"
14628
+ text: identity.definition && identity.label ? displayIdentity(identity.definition, identity.label) : identity.definition ?? "?",
14629
+ ...identity.definition ? { role: identity.definition } : {}
14206
14630
  }
14207
14631
  ];
14208
14632
  const definitions = [
14209
14633
  {
14210
14634
  text: displayIdentity(current.agentDefinition, current.state.agentLabel),
14211
- sessionId: current.state.piSessionId
14635
+ sessionId: current.state.piSessionId,
14636
+ role: current.agentDefinition
14212
14637
  }
14213
14638
  ];
14214
14639
  const visited = /* @__PURE__ */ new Set([current.state.piSessionId]);
@@ -14225,7 +14650,8 @@ function statusBreadcrumb(snapshot, candidate, identity, sameIdentity) {
14225
14650
  visited.add(parent.state.piSessionId);
14226
14651
  definitions.push({
14227
14652
  text: displayIdentity(parent.agentDefinition, parent.state.agentLabel),
14228
- sessionId: parent.state.piSessionId
14653
+ sessionId: parent.state.piSessionId,
14654
+ role: parent.agentDefinition
14229
14655
  });
14230
14656
  ownerSessionId = parent.state.ownerSessionId;
14231
14657
  continue;
@@ -14238,7 +14664,11 @@ function statusBreadcrumb(snapshot, candidate, identity, sameIdentity) {
14238
14664
  (root2) => root2.sessionId === ownerSessionId
14239
14665
  );
14240
14666
  return roots.length === 1 ? [
14241
- { text: roots[0].role, sessionId: ownerSessionId },
14667
+ {
14668
+ text: roots[0].role,
14669
+ sessionId: ownerSessionId,
14670
+ role: roots[0].role
14671
+ },
14242
14672
  ...definitions.reverse()
14243
14673
  ] : [{ text: "?" }, ...definitions.reverse()];
14244
14674
  }
@@ -14602,34 +15032,25 @@ function ownedAssignmentResult(entry, ownerSessionId, unavailable) {
14602
15032
  label: data.agentLabel
14603
15033
  };
14604
15034
  }
14605
- function ownedAssignmentToolResult(entry, ownerSessionId, unavailable) {
14606
- if (!entry || typeof entry !== "object" || !("type" in entry) || entry.type !== "message" || !("message" in entry))
14607
- return void 0;
14608
- const message = entry.message;
14609
- if (!message || typeof message !== "object" || !("role" in message) || message.role !== "toolResult" || !("toolName" in message) || message.toolName !== "delegate_agent" && message.toolName !== "continue_agent" && message.toolName !== "agent_delegate" && message.toolName !== "agent_continue" || "isError" in message && message.isError === true || !("details" in message))
14610
- return void 0;
14611
- const details = message.details;
14612
- if (!details || typeof details !== "object" || Array.isArray(details) || !("ok" in details) || details.ok !== true || !("owner_session_id" in details) || details.owner_session_id !== ownerSessionId)
14613
- return void 0;
14614
- if (!("session_id" in details) || typeof details.session_id !== "string" || !validId(details.session_id) || !("session_path" in details) || typeof details.session_path !== "string" || !details.session_path.trim() || !("agent" in details) || typeof details.agent !== "string" || !details.agent.trim() || !("definition" in details) || typeof details.definition !== "string" || !details.definition.trim()) {
14615
- unavailable();
14616
- return void 0;
14617
- }
14618
- return {
14619
- id: details.session_id,
14620
- path: details.session_path,
14621
- label: details.agent,
14622
- definition: details.definition
14623
- };
14624
- }
14625
15035
  function ownedAssignmentChildren(entries, ownerSessionId, includeReceipts = false, unavailable) {
14626
15036
  const children = /* @__PURE__ */ new Map();
14627
- for (const entry of entries) {
14628
- const child = (includeReceipts ? ownedAssignmentToolResult(
14629
- entry,
15037
+ if (includeReceipts) {
15038
+ for (const receipt of acceptedAssignmentEvidence(
15039
+ entries,
14630
15040
  ownerSessionId,
14631
- () => unavailable?.()
14632
- ) : void 0) ?? ownedAssignmentResult(entry, ownerSessionId, unavailable);
15041
+ unavailable
15042
+ )) {
15043
+ const child = {
15044
+ id: receipt.sessionId,
15045
+ path: receipt.sessionPath,
15046
+ definition: receipt.definition,
15047
+ label: receipt.agent
15048
+ };
15049
+ children.set(`${child.id}\0${child.path}`, child);
15050
+ }
15051
+ }
15052
+ for (const entry of entries) {
15053
+ const child = ownedAssignmentResult(entry, ownerSessionId, unavailable);
14633
15054
  if (!child) continue;
14634
15055
  try {
14635
15056
  const path = canonicalSessionPath(child.path);
@@ -15515,7 +15936,7 @@ async function managedAgentSnapshots(pi, ctx, dependencies, signal, proveRoot =
15515
15936
  const waitingForChildren = !!state.activeRequestId && pendingDirectChildWork && (lifecycleState === "idle" || lifecycleState === "done") && !completionPending && !handoffPending && !state.resultError;
15516
15937
  const existingLiveProjection = waitingForChildren ? "blocked" : liveState;
15517
15938
  const projectedState = completionPending || state.resultError ? "settling" : presence.kind === "lost" ? "lost" : presence.kind === "unknown" ? "unknown" : existingLiveProjection;
15518
- const steerable = presence.kind === "live" && !state.pendingAskId && projectedState === "working";
15939
+ const steerable = presence.kind === "live" && !state.pendingAskId && (projectedState === "working" || waitingForChildren);
15519
15940
  const now = Date.now();
15520
15941
  const listed = {
15521
15942
  label: state.agentLabel,
@@ -16286,6 +16707,15 @@ function createAgentController(pi, options) {
16286
16707
  operation,
16287
16708
  `Agent ${current.agentLabel}`
16288
16709
  );
16710
+ if (kind === "steer" && readUnacknowledgedRequest(runtime.mailboxPath, current))
16711
+ fail(
16712
+ "agent_busy",
16713
+ "Agent has an unacknowledged control request",
16714
+ operation,
16715
+ {
16716
+ nextAction: "Resolve the pending control request before steering again."
16717
+ }
16718
+ );
16289
16719
  if (current.lastAck) {
16290
16720
  try {
16291
16721
  removeRequest(runtime.mailboxPath, current.lastAck.requestId);
@@ -16325,11 +16755,67 @@ function createAgentController(pi, options) {
16325
16755
  let acknowledgementObserved = false;
16326
16756
  options.onChanged();
16327
16757
  try {
16328
- const state = await waitForState(
16329
- runtime.mailboxPath,
16330
- (candidate) => candidate.lastAck?.requestId === requestId,
16331
- { timeoutMs: 5e3, signal }
16332
- );
16758
+ let state;
16759
+ try {
16760
+ state = await waitForState(
16761
+ runtime.mailboxPath,
16762
+ (candidate) => candidate.lastAck?.requestId === requestId,
16763
+ { timeoutMs: 5e3, signal }
16764
+ );
16765
+ } catch (error2) {
16766
+ if (kind !== "steer" || !["TimeoutError", "AbortError"].includes(error2?.name))
16767
+ throw error2;
16768
+ const reconcileRelease = tryClaimAssignmentLock(runtime.mailboxPath);
16769
+ if (!reconcileRelease)
16770
+ fail(
16771
+ "internal_failure",
16772
+ "Steering outcome is indeterminate; the assignment lock is occupied",
16773
+ operation
16774
+ );
16775
+ try {
16776
+ const current = readAgentState(runtime.mailboxPath);
16777
+ if (!current || !sameIdentity(current, {
16778
+ version: current.version,
16779
+ build: options.build,
16780
+ runId: runtime.runId,
16781
+ ownerSessionId: runtime.ownerSessionId,
16782
+ workspaceId: runtime.workspaceId,
16783
+ agentLabel: runtime.label,
16784
+ paneId: runtime.paneId,
16785
+ rootSessionId: runtime.rootSessionId,
16786
+ piSessionId: runtime.piSessionId ?? "",
16787
+ piSessionFile: runtime.piSessionFile,
16788
+ cwd: runtime.cwd,
16789
+ updatedAt: current.updatedAt
16790
+ }))
16791
+ fail(
16792
+ "internal_failure",
16793
+ "Steering outcome is indeterminate; agent identity changed",
16794
+ operation
16795
+ );
16796
+ if (current.lastAck?.requestId === requestId) state = current;
16797
+ else {
16798
+ const pending = readRequest(runtime.mailboxPath, requestId);
16799
+ if (!pending || !isDeepStrictEqual2(pending, request))
16800
+ fail(
16801
+ "internal_failure",
16802
+ "Steering outcome is indeterminate; the exact request is no longer present",
16803
+ operation
16804
+ );
16805
+ removeRequest(runtime.mailboxPath, requestId);
16806
+ fail(
16807
+ "agent_busy",
16808
+ "Steering request was cancelled before receiver acknowledgement",
16809
+ operation,
16810
+ {
16811
+ nextAction: "The instruction was not confirmed; refresh list_agents before deciding whether to steer again."
16812
+ }
16813
+ );
16814
+ }
16815
+ } finally {
16816
+ reconcileRelease();
16817
+ }
16818
+ }
16333
16819
  if (!state || state.lastAck?.requestId !== requestId)
16334
16820
  fail(
16335
16821
  "internal_failure",
@@ -16472,18 +16958,22 @@ function createAgentController(pi, options) {
16472
16958
  };
16473
16959
  }
16474
16960
  const operation = params.action;
16475
- if (operation === "steer" && agent.steerable !== true)
16961
+ const fallbackToSteer = operation === "interrupt" && controlState === "blocked" && agent.steerable === true;
16962
+ const kind = fallbackToSteer ? "steer" : operation;
16963
+ if (kind === "steer" && agent.steerable !== true) {
16964
+ const current = readAgentState(runtime.mailboxPath);
16965
+ const pendingRequest = current ? readUnacknowledgedRequest(runtime.mailboxPath, current) : void 0;
16966
+ const nextAction = current?.pendingAskId ? "Answer the pending ask_owner question with reply_agent." : controlState === "settling" || pendingRequest ? "Allow the current control or completion transition to finish." : controlState === "unknown" ? "Diagnose or recover the exact managed session before steering." : "Refresh list_agents after the underlying state changes and use steer_agent only when available_tools includes it.";
16476
16967
  fail(
16477
16968
  "agent_busy",
16478
16969
  `Agent is not currently accepting steering: ${controlState}`,
16479
16970
  "steer",
16480
- {
16481
- nextAction: "Refresh with list_agents and use steer_agent only when available_tools includes it."
16482
- }
16971
+ { nextAction }
16483
16972
  );
16484
- if (operation === "steer" && !runtime.activeRequestId)
16485
- fail("agent_busy", "Agent has no active assignment", "steer");
16486
- if (operation === "interrupt" && controlState !== "working")
16973
+ }
16974
+ if (kind === "steer" && !runtime.activeRequestId)
16975
+ fail("agent_busy", "Agent has no active assignment", operation);
16976
+ if (operation === "interrupt" && controlState !== "working" && !fallbackToSteer)
16487
16977
  fail(
16488
16978
  "agent_busy",
16489
16979
  `Agent has no interruptible active operation: ${controlState}`,
@@ -16492,7 +16982,7 @@ function createAgentController(pi, options) {
16492
16982
  nextAction: "Use interrupt_agent only when available_tools includes it. Use steer_agent for non-preemptive assignment changes."
16493
16983
  }
16494
16984
  );
16495
- if ((operation === "steer" || operation === "interrupt") && !runtime.activeRequestId)
16985
+ if (operation === "interrupt" && !runtime.activeRequestId)
16496
16986
  fail("agent_busy", "Agent has no active assignment", operation);
16497
16987
  let askId;
16498
16988
  let createdAt = Date.now();
@@ -16536,7 +17026,6 @@ function createAgentController(pi, options) {
16536
17026
  "reply"
16537
17027
  );
16538
17028
  }
16539
- const kind = operation;
16540
17029
  const limits = readConfig();
16541
17030
  const manager = await options.managerEvidence?.(
16542
17031
  context,
@@ -16591,6 +17080,10 @@ function createAgentController(pi, options) {
16591
17080
  return {
16592
17081
  ok: true,
16593
17082
  action: operation,
17083
+ ...fallbackToSteer ? {
17084
+ delivered_as: "steer",
17085
+ note: "Agent was waiting for child work. Message delivered via steering; nothing was interrupted."
17086
+ } : {},
16594
17087
  agent: runtime.label,
16595
17088
  presentation_agent_definition: runtime.agentDefinition,
16596
17089
  request_id: sentRequestId,
@@ -17287,7 +17780,7 @@ function createAgentController(pi, options) {
17287
17780
  const path = join9(runtime.mailboxPath, filename);
17288
17781
  stopResultWatcher(runtime, requestId);
17289
17782
  const check = () => {
17290
- if (active && runtimes.get(runtime.label) === runtime)
17783
+ if (active && context.isIdle() && runtimes.get(runtime.label) === runtime)
17291
17784
  try {
17292
17785
  const result = readResult(runtime.mailboxPath, requestId);
17293
17786
  if (result) void deliverResult(runtime, context, result, signal);
@@ -17308,6 +17801,7 @@ function createAgentController(pi, options) {
17308
17801
  stopAskWatcher(runtime);
17309
17802
  const check = () => {
17310
17803
  if (!active || runtimes.get(runtime.label) !== runtime) return;
17804
+ if (!context.isIdle()) return;
17311
17805
  try {
17312
17806
  deliverPendingAsk(runtime, context, signal);
17313
17807
  } catch (error2) {
@@ -17564,9 +18058,9 @@ function createAgentController(pi, options) {
17564
18058
  }, 250)
17565
18059
  );
17566
18060
  };
17567
- const deliverPendingAsk = (runtime, context, signal) => {
18061
+ const deliverPendingAsk = (runtime, context, signal, triggerTurn = true, budget) => {
17568
18062
  const state = readAgentState(runtime.mailboxPath);
17569
- if (!state?.pendingAskId) return;
18063
+ if (!state?.pendingAskId) return false;
17570
18064
  try {
17571
18065
  requireCompatibleBuild(
17572
18066
  options.build,
@@ -17586,27 +18080,37 @@ function createAgentController(pi, options) {
17586
18080
  options.onChanged();
17587
18081
  }
17588
18082
  const ask = readPendingAsk(runtime.mailboxPath, state);
17589
- if (!ask || !active) return;
18083
+ if (!ask || !active) return false;
18084
+ const content = `Agent ${ask.agentLabel} needs your input:
18085
+
18086
+ ${ask.question}
18087
+
18088
+ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
17590
18089
  const key = `${runtime.mailboxPath}:${ask.askId}`;
17591
- if (askDeliveryInFlight.has(key)) return;
18090
+ if (askDeliveryInFlight.has(key)) return false;
17592
18091
  askDeliveryInFlight.add(key);
17593
18092
  try {
17594
- if (!context.isIdle() || runtimes.get(runtime.label) !== runtime || context.sessionManager.getSessionId() !== runtime.ownerSessionId || state.runId !== runtime.runId || state.ownerSessionId !== runtime.ownerSessionId || state.workspaceId !== runtime.workspaceId || state.agentLabel !== runtime.label || state.paneId !== runtime.paneId || !sameCwd(state.cwd, runtime.cwd) || state.piSessionId !== runtime.piSessionId || !sameSessionPath3(state.piSessionFile, runtime.piSessionFile) || ask.askId !== state.pendingAskId || ask.requestId !== state.activeRequestId || ask.runId !== state.runId || ask.ownerSessionId !== state.ownerSessionId || ask.workspaceId !== state.workspaceId || ask.agentLabel !== state.agentLabel || ask.paneId !== state.paneId || ask.piSessionId !== state.piSessionId)
17595
- return;
18093
+ if (triggerTurn && !context.isIdle() || runtimes.get(runtime.label) !== runtime || context.sessionManager.getSessionId() !== runtime.ownerSessionId || state.runId !== runtime.runId || state.ownerSessionId !== runtime.ownerSessionId || state.workspaceId !== runtime.workspaceId || state.agentLabel !== runtime.label || state.paneId !== runtime.paneId || !sameCwd(state.cwd, runtime.cwd) || state.piSessionId !== runtime.piSessionId || !sameSessionPath3(state.piSessionFile, runtime.piSessionFile) || ask.askId !== state.pendingAskId || ask.requestId !== state.activeRequestId || ask.runId !== state.runId || ask.ownerSessionId !== state.ownerSessionId || ask.workspaceId !== state.workspaceId || ask.agentLabel !== state.agentLabel || ask.paneId !== state.paneId || ask.piSessionId !== state.piSessionId)
18094
+ return false;
17596
18095
  const delivered = hasDeliveredAsk(
17597
18096
  context.sessionManager.getBranch(),
17598
18097
  ask
17599
18098
  );
17600
18099
  if (!delivered) {
18100
+ if (budget && !includeFanInMessage({ ...budget }, content))
18101
+ return false;
17601
18102
  importResultBindings(pi, context, ask.resultBindings, "ask_owner");
17602
- options.sendAskMessage(context, ask);
18103
+ options.sendAskMessage(context, ask, triggerTurn);
18104
+ if (budget) includeFanInMessage(budget, content);
17603
18105
  }
17604
18106
  cancelAskRetry(runtime, ask.askId);
17605
18107
  clearCleanupError(runtime, "Ask delivery failed");
18108
+ return !delivered;
17606
18109
  } catch (error2) {
17607
18110
  if (error2 instanceof OperationError && error2.detail.category === "incompatible_build")
17608
- return;
18111
+ return false;
17609
18112
  scheduleAskRetry(runtime, context, ask, signal, error2);
18113
+ return false;
17610
18114
  } finally {
17611
18115
  askDeliveryInFlight.delete(key);
17612
18116
  }
@@ -17725,6 +18229,7 @@ function createAgentController(pi, options) {
17725
18229
  setTimeout(() => {
17726
18230
  resultDeliveryRetries.delete(key);
17727
18231
  if (!active || runtimes.get(runtime.label) !== runtime) return;
18232
+ if (!context.isIdle()) return;
17728
18233
  try {
17729
18234
  const current = readResult(runtime.mailboxPath, result.requestId);
17730
18235
  if (current) void deliverResult(runtime, context, current, signal);
@@ -17746,16 +18251,17 @@ function createAgentController(pi, options) {
17746
18251
  if (timer) clearTimeout(timer);
17747
18252
  map.delete(key);
17748
18253
  };
17749
- const deliverResult = async (runtime, context, result, signal) => {
17750
- if (!active) return;
18254
+ const deliverResult = async (runtime, context, result, signal, triggerTurn = true, budget) => {
18255
+ if (!active) return false;
17751
18256
  const key = `${runtime.mailboxPath}:${result.requestId}`;
17752
- if (resultDeliveryInFlight.has(key)) return;
18257
+ if (resultDeliveryInFlight.has(key)) return false;
17753
18258
  resultDeliveryInFlight.add(key);
18259
+ let submitted = false;
17754
18260
  try {
17755
18261
  const expected = resultIdentity(runtime, result.requestId);
17756
18262
  const persistedState = readAgentState(runtime.mailboxPath);
17757
18263
  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.rootSessionId !== runtime.rootSessionId || result.rootSessionId !== persistedState?.rootSessionId || result.requestId !== (runtime.activeRequestId ?? runtime.completedRequestId);
17758
- if (identityMismatch) return;
18264
+ if (identityMismatch) return false;
17759
18265
  let entries = context.sessionManager.getEntries();
17760
18266
  const evidenceKey = JSON.stringify(Object.values(expected));
17761
18267
  if (!hasDeliveredResult(entries, expected) && !resultDeliveryEvidence.has(evidenceKey)) {
@@ -17865,10 +18371,21 @@ function createAgentController(pi, options) {
17865
18371
  } : {},
17866
18372
  error: result.error
17867
18373
  };
17868
- options.sendResultMessage(context, runtime, result, content, details);
18374
+ if (budget && !includeFanInMessage({ ...budget }, content))
18375
+ return false;
18376
+ options.sendResultMessage(
18377
+ context,
18378
+ runtime,
18379
+ result,
18380
+ content,
18381
+ details,
18382
+ triggerTurn
18383
+ );
18384
+ if (budget) includeFanInMessage(budget, content);
18385
+ submitted = true;
17869
18386
  resultDeliveryEvidence.add(evidenceKey);
17870
18387
  }
17871
- if (!active || runtimes.get(runtime.label) !== runtime) return;
18388
+ if (!active || runtimes.get(runtime.label) !== runtime) return false;
17872
18389
  stopResultWatcher(runtime, result.requestId);
17873
18390
  stopAskWatcher(runtime);
17874
18391
  cancelAskRetries(runtime);
@@ -17883,8 +18400,10 @@ function createAgentController(pi, options) {
17883
18400
  scheduleResultCleanupRetry(runtime, result, context, signal);
17884
18401
  clearCleanupError(runtime, "Result delivery failed; retrying:");
17885
18402
  cancelResultRetry(resultDeliveryRetries, runtime, result.requestId);
18403
+ return submitted;
17886
18404
  } catch (error2) {
17887
18405
  scheduleResultDeliveryRetry(runtime, result, context, signal, error2);
18406
+ return false;
17888
18407
  } finally {
17889
18408
  resultDeliveryInFlight.delete(key);
17890
18409
  }
@@ -17929,6 +18448,45 @@ function createAgentController(pi, options) {
17929
18448
  await deliverResult(runtime, context, result, signal);
17930
18449
  }
17931
18450
  };
18451
+ const drainReadyOwnerNotifications = async (context, phase, budget) => {
18452
+ if (!active) return 0;
18453
+ let ownerId;
18454
+ try {
18455
+ ownerId = context.sessionManager.getSessionId();
18456
+ } catch {
18457
+ return 0;
18458
+ }
18459
+ let submitted = 0;
18460
+ for (const runtime of runtimes.values()) {
18461
+ if (runtime.ownerSessionId !== ownerId || !active) continue;
18462
+ const requestId = runtime.activeRequestId ?? runtime.completedRequestId;
18463
+ if (requestId) {
18464
+ try {
18465
+ const result = readResult(runtime.mailboxPath, requestId);
18466
+ if (result && await deliverResult(
18467
+ runtime,
18468
+ context,
18469
+ result,
18470
+ context.signal,
18471
+ false,
18472
+ budget
18473
+ ))
18474
+ submitted++;
18475
+ } catch (error2) {
18476
+ options.reportWatcherError(context, error2);
18477
+ }
18478
+ }
18479
+ if (phase === "settle")
18480
+ try {
18481
+ if (deliverPendingAsk(runtime, context, context.signal, false, budget))
18482
+ submitted++;
18483
+ } catch (error2) {
18484
+ if (!(error2 instanceof OperationError && error2.detail.category === "incompatible_build"))
18485
+ options.reportWatcherError(context, error2);
18486
+ }
18487
+ }
18488
+ return submitted;
18489
+ };
17932
18490
  const actionUnsafe = async (ctx, p, signal) => {
17933
18491
  if (p.action === "delegate") p.retentionPersisted = false;
17934
18492
  const scope = options.scope;
@@ -18863,14 +19421,16 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
18863
19421
  "PI_OFFLINE=1"
18864
19422
  ];
18865
19423
  const registeredProviderIds = new Set(
18866
- ctx.modelRegistry?.getRegisteredProviderIds?.() ?? []
19424
+ (ctx.modelRegistry?.getRegisteredProviderIds?.() ?? []).map(
19425
+ (id) => id.toLowerCase()
19426
+ )
18867
19427
  );
18868
19428
  const childModel = resolveChildModel({
18869
19429
  configured: configuredModel(effectiveDefinition.frontmatter),
18870
19430
  inherited: !resumed && ctx.model ? { provider: ctx.model.provider, token: modelToken(ctx.model) } : void 0,
18871
19431
  saved: resumed?.savedModel,
18872
19432
  savedUnresolved: resumed?.savedModelUnresolved,
18873
- isForeignProvider: (providerId) => registeredProviderIds.has(providerId),
19433
+ isForeignProvider: (providerId) => registeredProviderIds.has(providerId.toLowerCase()),
18874
19434
  isKnownModel: (provider, id) => ctx.modelRegistry.find(provider, id) !== void 0
18875
19435
  });
18876
19436
  if ((resumed?.savedModel || resumed?.savedModelUnresolved) && !configuredModel(effectiveDefinition.frontmatter))
@@ -19234,6 +19794,23 @@ ${result.stderr ?? ""}`.trim(),
19234
19794
  }
19235
19795
  );
19236
19796
  accepted = true;
19797
+ let historyWarning;
19798
+ try {
19799
+ if (ctx.sessionManager.getSessionId() !== runtime.ownerSessionId)
19800
+ throw new Error("Owner session changed");
19801
+ pi.appendEntry(ACCEPTED_ASSIGNMENT_ENTRY, {
19802
+ version: 1,
19803
+ action: p.action,
19804
+ owner_session_id: runtime.ownerSessionId,
19805
+ session_id: runtime.piSessionId,
19806
+ session_path: runtime.piSessionFile,
19807
+ request_id: requestId,
19808
+ agent: label,
19809
+ definition: agentDefinition
19810
+ });
19811
+ } catch {
19812
+ historyWarning = "Assignment accepted, but its history receipt could not be saved. Historical continuation may be unavailable.";
19813
+ }
19237
19814
  options.onChanged();
19238
19815
  const inlineNames = new Set(
19239
19816
  (assignmentInput?.attachments ?? []).filter((attachment) => attachment.inline && attachment.ref).map((attachment) => attachment.ref)
@@ -19260,7 +19837,8 @@ ${result.stderr ?? ""}`.trim(),
19260
19837
  session_id: runtime.piSessionId,
19261
19838
  session_path: runtime.piSessionFile,
19262
19839
  request_id: requestId,
19263
- evidence: evidenceReceipt
19840
+ evidence: evidenceReceipt,
19841
+ ...historyWarning ? { history_warning: historyWarning } : {}
19264
19842
  };
19265
19843
  } catch (caught) {
19266
19844
  if (historicalMailboxPreflightFailed) throw caught;
@@ -19436,7 +20014,7 @@ ${result.stderr ?? ""}`.trim(),
19436
20014
  pi.registerTool({
19437
20015
  name: "read_evidence",
19438
20016
  label: "Read accepted evidence",
19439
- exposure: "model-only",
20017
+ exposure: "direct",
19440
20018
  description: "Read a bounded page from evidence accepted by this assigned project Lead.",
19441
20019
  parameters: Type.Object(
19442
20020
  {
@@ -19543,7 +20121,7 @@ ${result.stderr ?? ""}`.trim(),
19543
20121
  { agent: Type.String({ pattern: AGENT_LABEL_PATTERN.source }) },
19544
20122
  { additionalProperties: false }
19545
20123
  );
19546
- const agentExposure = "model-only";
20124
+ const agentExposure = "direct";
19547
20125
  const agentExecutionMode = "sequential";
19548
20126
  const agentTool = {
19549
20127
  name: "list_agents",
@@ -19566,6 +20144,16 @@ ${result.stderr ?? ""}`.trim(),
19566
20144
  p = raw;
19567
20145
  presentationAction = p.action;
19568
20146
  const value2 = await action(ctx, p, signal);
20147
+ if (p.action === "stop" && value2.ok === true && value2.closed_assignment && value2.cleanup_error === void 0 && value2.cleanup_errors === void 0) {
20148
+ try {
20149
+ pi.appendEntry(STOP_CLOSURE_ENTRY, {
20150
+ version: 1,
20151
+ proof: value2.closed_assignment
20152
+ });
20153
+ } catch {
20154
+ value2.history_warning = "Agent stopped, but its clean-stop receipt could not be saved.";
20155
+ }
20156
+ }
19569
20157
  options.onChanged();
19570
20158
  if (controllerScope.kind === "root" && (p.action === "delegate" || p.action === "continue") && value2.ok === true)
19571
20159
  onAssignmentStarted?.(ctx);
@@ -19663,6 +20251,7 @@ ${result.stderr ?? ""}`.trim(),
19663
20251
  ...agentTool,
19664
20252
  name: "delegate_agent",
19665
20253
  label: "delegate agent",
20254
+ exposure: "direct",
19666
20255
  description: "Start one fresh bounded assignment. Choose the most focused eligible Agent definition capable of completing the full task. Use a general-purpose definition when broader capabilities are needed or no focused definition fits.",
19667
20256
  parameters: agentDelegateParameters,
19668
20257
  promptSnippet: void 0,
@@ -19681,6 +20270,7 @@ ${result.stderr ?? ""}`.trim(),
19681
20270
  ...agentTool,
19682
20271
  name: "continue_agent",
19683
20272
  label: "continue agent",
20273
+ exposure: "direct",
19684
20274
  description: "Start one bounded assignment from an eligible historical managed-Agent Pi session selected by a directly owned result ref, exact path, or UUID. Retired sessions cannot be continued while context retirement is enabled.",
19685
20275
  parameters: agentContinueParameters,
19686
20276
  promptSnippet: void 0,
@@ -19717,7 +20307,7 @@ ${result.stderr ?? ""}`.trim(),
19717
20307
  ...agentTool,
19718
20308
  name: "interrupt_agent",
19719
20309
  label: "interrupt agent",
19720
- description: "Cancel a live Agent's current Pi operation and continue the same assignment with replacement direction.",
20310
+ description: "Cancel a live Agent's current Pi operation and continue the same assignment with replacement direction. If the Agent is blocked waiting for verified direct-child work, the message is delivered via steering instead; no operation is interrupted.",
19721
20311
  parameters: agentMessageParameters,
19722
20312
  promptSnippet: void 0,
19723
20313
  promptGuidelines: [FILE_HANDOFF_GUIDANCE],
@@ -20486,6 +21076,11 @@ ${result.stderr ?? ""}`.trim(),
20486
21076
  }
20487
21077
  schedule();
20488
21078
  };
21079
+ if (options.registerRecipientFanIn !== false)
21080
+ registerRecipientFanIn(
21081
+ pi,
21082
+ (ctx, phase, budget) => drainReadyOwnerNotifications(ctx, phase, budget)
21083
+ );
20489
21084
  return {
20490
21085
  listAgentStates,
20491
21086
  managedAgentSnapshots: snapshot,
@@ -20598,6 +21193,7 @@ ${result.stderr ?? ""}`.trim(),
20598
21193
  settleResults(context, signal) {
20599
21194
  return settleResults(context, signal);
20600
21195
  },
21196
+ drainReadyOwnerNotifications,
20601
21197
  shutdown() {
20602
21198
  active = false;
20603
21199
  recoveryComplete = false;
@@ -20792,11 +21388,12 @@ function collectSessionUsage(ctx, ownedChildren, openOwnedSession, leadRoots = [
20792
21388
  breakdown
20793
21389
  };
20794
21390
  }
20795
- var delegationLockPath, claimDelegationLock, waitForDelegationLock, SHARED_AGENT_INSTRUCTIONS, INTEGRATION_SESSION_RETRY_MS, INTEGRATION_SESSION_RETRIES, HEALTH_STALE_AFTER_MS, HEALTH_STALE_SCAN_MS, HEALTH_STALE_DIAGNOSTIC_TIMEOUT_MS, HEALTH_STALE_DIAGNOSTIC_LINES, HEALTH_ATTENTION_REPEAT_MIN_MS, HEALTH_ATTENTION_FIRST_REPEAT_MS, AGENT_LABEL_PATTERN, validAgentLabel, modelToken, messageLimits, AGENT_DEFINITION_ENTRY, AGENT_EXECUTION_OWNERSHIP_GUIDANCE, AGENT_UNRESOLVED_GUIDANCE, AGENT_DELEGATION_GUIDANCE, AGENT_HANDOFF_GUIDANCE, LEAD_SCOPE_DESCRIPTION, DELEGATING_AGENT_SCOPE_DESCRIPTION, STOP_CLOSURE_ENTRY, RESULT_REF_ENTRY, TRANSCRIPT_MAX_BYTES, TRANSCRIPT_TOOL_RESULT_MAX_BYTES, TRANSCRIPT_TOOL_RESULT_OMISSION;
21391
+ var delegationLockPath, claimDelegationLock, waitForDelegationLock, SHARED_AGENT_INSTRUCTIONS, INTEGRATION_SESSION_RETRY_MS, INTEGRATION_SESSION_RETRIES, HEALTH_STALE_AFTER_MS, HEALTH_STALE_SCAN_MS, HEALTH_STALE_DIAGNOSTIC_TIMEOUT_MS, HEALTH_STALE_DIAGNOSTIC_LINES, HEALTH_ATTENTION_REPEAT_MIN_MS, HEALTH_ATTENTION_FIRST_REPEAT_MS, AGENT_LABEL_PATTERN, validAgentLabel, modelToken, messageLimits, AGENT_DEFINITION_ENTRY, AGENT_EXECUTION_OWNERSHIP_GUIDANCE, AGENT_UNRESOLVED_GUIDANCE, AGENT_DELEGATION_GUIDANCE, AGENT_HANDOFF_GUIDANCE, LEAD_SCOPE_DESCRIPTION, DELEGATING_AGENT_SCOPE_DESCRIPTION, STOP_CLOSURE_ENTRY, ACCEPTED_ASSIGNMENT_ENTRY, RESULT_REF_ENTRY, TRANSCRIPT_MAX_BYTES, TRANSCRIPT_TOOL_RESULT_MAX_BYTES, TRANSCRIPT_TOOL_RESULT_OMISSION;
20796
21392
  var init_agent_controller = __esm({
20797
21393
  "extension/agent-controller.ts"() {
20798
21394
  "use strict";
20799
21395
  init_errors();
21396
+ init_recipient_fan_in();
20800
21397
  init_mailbox();
20801
21398
  init_presentation();
20802
21399
  init_storage();
@@ -20936,6 +21533,7 @@ direct-agent work. If unresolved direct-agent work exists, every such agent
20936
21533
  must itself be validly waiting on an owner answer; ordinary active or
20937
21534
  pending-result agent work still blocks escalation.`;
20938
21535
  STOP_CLOSURE_ENTRY = "pi-herdsman-agent-closed-assignment";
21536
+ ACCEPTED_ASSIGNMENT_ENTRY = "pi-herdsman-agent-accepted-assignment";
20939
21537
  RESULT_REF_ENTRY = "pi-herdsman-result-ref";
20940
21538
  TRANSCRIPT_MAX_BYTES = 16 * 1024;
20941
21539
  TRANSCRIPT_TOOL_RESULT_MAX_BYTES = 4 * 1024;
@@ -20981,7 +21579,7 @@ __export(managed_agent_runtime_exports, {
20981
21579
  sessionContextRetired: () => sessionContextRetired,
20982
21580
  validateManagedAgentIdentity: () => validateManagedAgentIdentity
20983
21581
  });
20984
- import { isAbsolute as isAbsolute5, resolve as resolve5 } from "node:path";
21582
+ import { isAbsolute as isAbsolute5, join as join10, resolve as resolve5 } from "node:path";
20985
21583
  import { existsSync as existsSync2, realpathSync as realpathSync5 } from "node:fs";
20986
21584
  import { buildSessionProjection as buildSessionProjection2 } from "@earendil-works/pi-coding-agent";
20987
21585
  import { contentText as contentText3 } from "@earendil-works/pi-ai";
@@ -21693,7 +22291,8 @@ function createManagedAgentLeafStatus(options) {
21693
22291
  text: process.env.PI_HERDSMAN_AGENT_DEFINITION && process.env.PI_HERDSMAN_LABEL ? displayIdentity(
21694
22292
  process.env.PI_HERDSMAN_AGENT_DEFINITION,
21695
22293
  process.env.PI_HERDSMAN_LABEL
21696
- ) : process.env.PI_HERDSMAN_AGENT_DEFINITION ?? "?"
22294
+ ) : process.env.PI_HERDSMAN_AGENT_DEFINITION ?? "?",
22295
+ ...process.env.PI_HERDSMAN_AGENT_DEFINITION ? { role: process.env.PI_HERDSMAN_AGENT_DEFINITION } : {}
21697
22296
  }
21698
22297
  ],
21699
22298
  ...ownToolsSnapshot(),
@@ -21705,6 +22304,9 @@ function createManagedAgentLeafStatus(options) {
21705
22304
  };
21706
22305
  return {
21707
22306
  reset,
22307
+ invalidate() {
22308
+ widget?.invalidate();
22309
+ },
21708
22310
  captureOwnTools(tools) {
21709
22311
  ownTools = tools;
21710
22312
  },
@@ -21732,7 +22334,9 @@ function createManagedAgentLeafStatus(options) {
21732
22334
  if (activeGeneration === generation) focusInFlight = false;
21733
22335
  });
21734
22336
  },
21735
- () => statusWidgetMaxRows
22337
+ () => statusWidgetMaxRows,
22338
+ void 0,
22339
+ () => options.getLocalActivity?.(ctx) ?? "unknown"
21736
22340
  );
21737
22341
  next.setSnapshot({
21738
22342
  agents: [],
@@ -21744,7 +22348,8 @@ function createManagedAgentLeafStatus(options) {
21744
22348
  text: process.env.PI_HERDSMAN_AGENT_DEFINITION && process.env.PI_HERDSMAN_LABEL ? displayIdentity(
21745
22349
  process.env.PI_HERDSMAN_AGENT_DEFINITION,
21746
22350
  process.env.PI_HERDSMAN_LABEL
21747
- ) : process.env.PI_HERDSMAN_AGENT_DEFINITION ?? "?"
22351
+ ) : process.env.PI_HERDSMAN_AGENT_DEFINITION ?? "?",
22352
+ ...process.env.PI_HERDSMAN_AGENT_DEFINITION ? { role: process.env.PI_HERDSMAN_AGENT_DEFINITION } : {}
21748
22353
  }
21749
22354
  ],
21750
22355
  ...ownToolsSnapshot(),
@@ -21896,7 +22501,7 @@ function registerManagedAgentAttachHandoffTool(pi, execute) {
21896
22501
  pi.registerTool({
21897
22502
  name: ATTACH_HANDOFF_TOOL,
21898
22503
  label: "Attach handoff evidence",
21899
- exposure: "model-only",
22504
+ exposure: "direct",
21900
22505
  promptSnippet: "Select reusable results for this assignment's final handoff",
21901
22506
  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.",
21902
22507
  executionMode: "sequential",
@@ -22698,6 +23303,8 @@ function registerManagedAgentShutdownHandler(pi, execution, options) {
22698
23303
  });
22699
23304
  }
22700
23305
  function registerManagedAgentRuntime(pi, options) {
23306
+ let leafStatus;
23307
+ let getLocalActivity = () => "unknown";
22701
23308
  pi.on("tool_call", (event) => {
22702
23309
  if (event.toolName !== "bash" && event.toolName !== "powershell") return;
22703
23310
  const tool = pi.getAllTools().find((candidate) => candidate.name === event.toolName);
@@ -22734,6 +23341,7 @@ function registerManagedAgentRuntime(pi, options) {
22734
23341
  depth: agentDepth
22735
23342
  };
22736
23343
  options.statusRuntime.configure({
23344
+ getLocalActivity: (ctx) => getLocalActivity(ctx),
22737
23345
  pendingStartEntries: () => controller.pendingStartEntries(),
22738
23346
  hasPendingStart: (label) => controller.hasPendingStart(label),
22739
23347
  clearPendingStart: (label, expected) => controller.clearPendingStart(label, expected),
@@ -22848,7 +23456,7 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
22848
23456
  });
22849
23457
  const execution = createManagedAgentExecutionState();
22850
23458
  const metadataPublisher = createManagedAgentMetadataPublisher(pi);
22851
- const leafStatus = createManagedAgentLeafStatus({
23459
+ leafStatus = createManagedAgentLeafStatus({
22852
23460
  snapshot: (ctx, signal) => managedAgentSnapshots(
22853
23461
  pi,
22854
23462
  ctx,
@@ -22862,6 +23470,7 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
22862
23470
  identity: (ctx) => managedAgentEnvironmentIdentity(ctx, options.build),
22863
23471
  sameIdentity: sameManagedAgentIdentity,
22864
23472
  signal: () => metadataPublisher.signal,
23473
+ getLocalActivity: (ctx) => getLocalActivity(ctx),
22865
23474
  focusTarget: async (ctx, intent, isCurrent) => {
22866
23475
  if (intent.kind !== "session")
22867
23476
  throw new Error("Manager navigation is unavailable from an Agent.");
@@ -23221,6 +23830,10 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23221
23830
  hasActiveAssignment: () => !!execution.assignment?.activeRequestId,
23222
23831
  reportConfigError: (ctx, error2) => options.appendError(ctx, "pi_herdsman_config_error", error2)
23223
23832
  });
23833
+ getLocalActivity = observeLocalHeaderActivity(pi, () => {
23834
+ options.statusRuntime.invalidateWidget();
23835
+ leafStatus?.invalidate();
23836
+ });
23224
23837
  }
23225
23838
  function createManagedAgentRequestState(pi, options) {
23226
23839
  let requestPumpErrorReported = false;
@@ -23228,18 +23841,24 @@ function createManagedAgentRequestState(pi, options) {
23228
23841
  const acknowledge = (requestId, accepted, code, message) => {
23229
23842
  const state = options.state();
23230
23843
  if (!state) return false;
23231
- const next = options.mutateState((current) => ({
23232
- ...current,
23233
- lastAck: {
23234
- requestId,
23235
- accepted,
23236
- ...code ? { code } : {},
23237
- ...message ? { message } : {},
23238
- acknowledgedAt: Date.now()
23239
- },
23240
- updatedAt: Date.now()
23241
- }));
23242
- if (next) {
23844
+ const mailbox = process.env.PI_HERDSMAN_MAILBOX;
23845
+ let requestPresent = false;
23846
+ const next = options.mutateState((current) => {
23847
+ if (!readRequest(mailbox, requestId)) return current;
23848
+ requestPresent = true;
23849
+ return {
23850
+ ...current,
23851
+ lastAck: {
23852
+ requestId,
23853
+ accepted,
23854
+ ...code ? { code } : {},
23855
+ ...message ? { message } : {},
23856
+ acknowledgedAt: Date.now()
23857
+ },
23858
+ updatedAt: Date.now()
23859
+ };
23860
+ });
23861
+ if (requestPresent && next) {
23243
23862
  acknowledgementErrorReported = false;
23244
23863
  return true;
23245
23864
  }
@@ -23254,6 +23873,7 @@ function createManagedAgentRequestState(pi, options) {
23254
23873
  try {
23255
23874
  const current = readAgentState(mailbox);
23256
23875
  if (!current || !options.sameIdentity(current, state)) return;
23876
+ if (!existsSync2(join10(mailbox, `request-${requestId}.json`))) return;
23257
23877
  const next = {
23258
23878
  ...current,
23259
23879
  lastAck: {
@@ -23857,7 +24477,7 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
23857
24477
  // package.json
23858
24478
  var package_default = {
23859
24479
  name: "pi-herdsman",
23860
- version: "0.42.1",
24480
+ version: "0.44.0",
23861
24481
  type: "module",
23862
24482
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
23863
24483
  license: "Apache-2.0",
@@ -24130,6 +24750,7 @@ import {
24130
24750
  init_supervision();
24131
24751
  init_errors();
24132
24752
  init_herdr();
24753
+ init_mailbox();
24133
24754
  init_lock();
24134
24755
  init_config();
24135
24756
  init_core();
@@ -24177,7 +24798,7 @@ function requiredFiles(id, files, retained, cwd, operation) {
24177
24798
  });
24178
24799
  }
24179
24800
  function createLeadProjectRuntime(host) {
24180
- const stopClosureEntry = "pi-herdsman-agent-closed-assignment";
24801
+ const stopClosureEntry = STOP_CLOSURE_ENTRY;
24181
24802
  const stopClosureProof = (branch, ownerSessionId, closed) => {
24182
24803
  return acceptedCloseProof(branch, ownerSessionId, closed);
24183
24804
  };
@@ -25510,6 +26131,115 @@ Subsequent explicitly requested removals here can proceed without a per-removal
25510
26131
  );
25511
26132
  };
25512
26133
  const mergeProject = async (branch, expectedHead, ctx, signal) => {
26134
+ const completionRefusal = (reason) => ({
26135
+ content: [
26136
+ {
26137
+ type: "text",
26138
+ text: `Cannot integrate ${branch}: current Lead completion evidence is not eligible (${reason}). Assignment and checkout preserved.`
26139
+ }
26140
+ ],
26141
+ details: {
26142
+ ok: false,
26143
+ action: "merge",
26144
+ branch,
26145
+ source_head: expectedHead,
26146
+ status: "blocked",
26147
+ reason,
26148
+ integrated: false,
26149
+ checkout_removed: false,
26150
+ assignment_retired: false
26151
+ }
26152
+ });
26153
+ const completionEligibility = (target, managerBranch) => {
26154
+ const outcomes = managerBranch.filter((entry) => {
26155
+ const details = entry?.details;
26156
+ return entry?.type === "custom_message" && entry.customType === "pi-herdsman-project_message" && details?.repoKey === target.assignment.repoKey && details?.branch === target.assignment.branch && details?.fromSessionId === target.assignment.id && [
26157
+ "direct_response",
26158
+ "herd_settlement",
26159
+ "execution_failure",
26160
+ "execution_cancelled"
26161
+ ].includes(details.kind);
26162
+ });
26163
+ const report = outcomes.at(-1);
26164
+ if (!report || report.details.kind === "execution_failure" || report.details.kind === "execution_cancelled")
26165
+ return "completion_handoff_missing";
26166
+ const sender = report.details.senderEnvironment;
26167
+ if (!validSenderEnvironment(sender) || sender.git?.head !== expectedHead || sender.git?.branch !== target.checkedOutBranch || !sameDirectory(sender.git?.worktreeRoot, target.checkoutPath))
26168
+ return "completion_revision_mismatch";
26169
+ try {
26170
+ if (!target.assignment.piSessionFile)
26171
+ return "completion_evidence_unavailable";
26172
+ const session = host.SessionManager.open(
26173
+ target.assignment.piSessionFile
26174
+ );
26175
+ if (session.getSessionId() !== target.assignment.id)
26176
+ return "completion_evidence_unavailable";
26177
+ const entries = session.getBranch();
26178
+ if (!Array.isArray(entries)) return "completion_evidence_unavailable";
26179
+ const receipt = entries.findIndex(
26180
+ (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-herd-run" && entry.data?.phase === "report_sent" && entry.data?.reportId === report.details.id && entry.data?.sessionId === target.assignment.id && entry.data?.kind === report.details.kind
26181
+ );
26182
+ if (receipt < 0) return "completion_evidence_unavailable";
26183
+ if (entries.slice(receipt + 1).some(
26184
+ (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-herd-run" && entry.data?.sessionId === target.assignment.id && [
26185
+ "lead_started",
26186
+ "lead_start_unpersisted",
26187
+ "report_pending"
26188
+ ].includes(entry.data?.phase) || entry?.type === "message" && (entry.message?.role === "user" || entry.message?.role === "assistant")
26189
+ ))
26190
+ return "completion_evidence_superseded";
26191
+ } catch {
26192
+ return "completion_evidence_unavailable";
26193
+ }
26194
+ if (target.liveLead && !["idle", "done"].includes(
26195
+ normalizeHerdrLifecycleState(target.liveLead)
26196
+ ))
26197
+ return "lead_execution_active";
26198
+ return void 0;
26199
+ };
26200
+ const currentExecutionEligibility = async (target) => {
26201
+ let managerBranch;
26202
+ try {
26203
+ managerBranch = ctx.sessionManager.getBranch();
26204
+ } catch {
26205
+ return "completion_evidence_unavailable";
26206
+ }
26207
+ const completion = completionEligibility(target, managerBranch);
26208
+ if (completion) return completion;
26209
+ const inventory = host.scanAgentStates();
26210
+ if (inventory.issues.length) return "owned_work_unresolved";
26211
+ const owned = /* @__PURE__ */ new Set([target.assignment.id]);
26212
+ let changed = true;
26213
+ while (changed) {
26214
+ changed = false;
26215
+ for (const { state } of inventory.states) {
26216
+ if ((state.projectAssignmentId === target.assignment.id || owned.has(state.ownerSessionId)) && !owned.has(state.piSessionId)) {
26217
+ owned.add(state.piSessionId);
26218
+ changed = true;
26219
+ }
26220
+ }
26221
+ }
26222
+ for (const { path, state } of inventory.states) {
26223
+ if (!owned.has(state.piSessionId) || state.piSessionId === target.assignment.id)
26224
+ continue;
26225
+ try {
26226
+ if (state.activeRequestId || state.pendingAskId || state.resultError || state.lastAck?.accepted === false || state.lastAck?.code === "delivery" || unacknowledgedRequestExists(path, state) || state.completedRequestId && readResult(path, state.completedRequestId))
26227
+ return "owned_work_unresolved";
26228
+ } catch {
26229
+ return "owned_work_unresolved";
26230
+ }
26231
+ }
26232
+ const descendants = await host.herdrSessionSnapshot(
26233
+ host.pi,
26234
+ ctx,
26235
+ operationSignal
26236
+ );
26237
+ if (descendants.agents.some(
26238
+ (agent) => agent.workspace_id === target.worktree.open_workspace_id && owned.has(host.herdrSessionId(agent) ?? "") && !["idle", "done"].includes(normalizeHerdrLifecycleState(agent))
26239
+ ))
26240
+ return "owned_work_unresolved";
26241
+ return void 0;
26242
+ };
25513
26243
  const operationSignal = signal ?? ctx.signal;
25514
26244
  operationSignal?.throwIfAborted();
25515
26245
  if (!/^[0-9a-f]{40,64}$/i.test(expectedHead))
@@ -25706,6 +26436,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
25706
26436
  "HEAD"
25707
26437
  ]);
25708
26438
  const targetHead = await output(targetPath, ["rev-parse", "HEAD"]);
26439
+ const initialTargetHead = targetHead;
25709
26440
  const clean = async (path) => {
25710
26441
  const status = await runGit(path, [
25711
26442
  "status",
@@ -25765,8 +26496,34 @@ Subsequent explicitly requested removals here can proceed without a per-removal
25765
26496
  return false;
25766
26497
  throw new Error("Git ancestry could not be verified");
25767
26498
  };
26499
+ const verifyPreviouslyIntegratedMerges = async (head) => {
26500
+ const history = await runGit(targetPath, [
26501
+ "log",
26502
+ "--format=%H %P",
26503
+ "--min-parents=2",
26504
+ "--ancestry-path",
26505
+ `${expectedHead}..${head}`
26506
+ ]);
26507
+ if (history.code !== 0 || history.killed || history.stderr?.trim())
26508
+ return false;
26509
+ for (const line of String(history.stdout ?? "").trim().split("\n")) {
26510
+ if (!line) continue;
26511
+ const [mergeHead, ...parents] = line.split(/\s+/);
26512
+ if (!mergeHead || !/^[0-9a-f]{40,64}$/i.test(mergeHead) || parents.length < 2 || parents.some((parent) => !/^[0-9a-f]{40,64}$/i.test(parent)))
26513
+ return false;
26514
+ const firstParent = parents[0];
26515
+ if (await ancestry(expectedHead, firstParent)) continue;
26516
+ const includesAcceptedSource = await Promise.all(
26517
+ parents.slice(1).map((parent) => ancestry(expectedHead, parent))
26518
+ );
26519
+ if (!includesAcceptedSource.some(Boolean)) continue;
26520
+ return false;
26521
+ }
26522
+ return true;
26523
+ };
25768
26524
  const initiallyIntegrated = await ancestry(expectedHead, targetHead);
25769
- if (!initiallyIntegrated && !await ancestry(targetHead, expectedHead))
26525
+ const initiallyFastForwardable = initiallyIntegrated ? false : await ancestry(targetHead, expectedHead);
26526
+ if (!initiallyIntegrated && !initiallyFastForwardable && !permission().allowDivergence)
25770
26527
  return {
25771
26528
  content: [
25772
26529
  {
@@ -25782,6 +26539,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
25782
26539
  source_head: expectedHead,
25783
26540
  target_head: targetHead,
25784
26541
  status: "needs_update",
26542
+ reason: "divergent_fast_forward_only",
25785
26543
  integrated: false,
25786
26544
  checkout_removed: false,
25787
26545
  assignment_retired: false
@@ -25828,7 +26586,33 @@ Subsequent explicitly requested removals here can proceed without a per-removal
25828
26586
  "rev-parse",
25829
26587
  "HEAD"
25830
26588
  ]);
25831
- if (!await ancestry(expectedHead, preStopTarget) && !await ancestry(preStopTarget, expectedHead))
26589
+ if (await ancestry(expectedHead, preStopTarget)) {
26590
+ if (!await verifyPreviouslyIntegratedMerges(preStopTarget))
26591
+ return {
26592
+ kind: "blocked",
26593
+ targetHead: preStopTarget,
26594
+ targetBranch,
26595
+ integrated: true,
26596
+ reason: "already_integrated_divergent_merge_unverified"
26597
+ };
26598
+ return {
26599
+ kind: "integrated",
26600
+ targetHead: preStopTarget,
26601
+ targetBranch,
26602
+ alreadyIntegrated: true
26603
+ };
26604
+ }
26605
+ const eligibility = await currentExecutionEligibility(current);
26606
+ if (eligibility)
26607
+ return {
26608
+ kind: "tool-result",
26609
+ result: completionRefusal(eligibility)
26610
+ };
26611
+ const preStopFastForward = await ancestry(
26612
+ preStopTarget,
26613
+ expectedHead
26614
+ );
26615
+ if (!preStopFastForward && !permission().allowDivergence)
25832
26616
  return {
25833
26617
  kind: "tool-result",
25834
26618
  result: {
@@ -25846,16 +26630,107 @@ Subsequent explicitly requested removals here can proceed without a per-removal
25846
26630
  source_head: expectedHead,
25847
26631
  target_head: preStopTarget,
25848
26632
  status: "needs_update",
26633
+ reason: "divergent_fast_forward_only",
25849
26634
  integrated: false,
25850
26635
  checkout_removed: false,
25851
26636
  assignment_retired: false
25852
26637
  }
25853
26638
  }
25854
26639
  };
25855
- if (current.liveLead)
26640
+ let expectedMergeTree;
26641
+ if (!preStopFastForward) {
26642
+ if (preStopTarget !== initialTargetHead)
26643
+ return {
26644
+ kind: "blocked",
26645
+ targetHead: preStopTarget,
26646
+ targetBranch,
26647
+ integrated: false,
26648
+ reason: "target_changed_before_merge"
26649
+ };
26650
+ let preview;
26651
+ try {
26652
+ preview = await runGit(targetPath, [
26653
+ "merge-tree",
26654
+ "--write-tree",
26655
+ preStopTarget,
26656
+ expectedHead
26657
+ ]);
26658
+ } catch {
26659
+ return {
26660
+ kind: "blocked",
26661
+ targetHead: preStopTarget,
26662
+ targetBranch,
26663
+ integrated: false,
26664
+ reason: operationSignal?.aborted ? "merge_preview_interrupted" : "merge_preview_unavailable"
26665
+ };
26666
+ }
26667
+ if (preview.killed || operationSignal?.aborted)
26668
+ return {
26669
+ kind: "blocked",
26670
+ targetHead: preStopTarget,
26671
+ targetBranch,
26672
+ integrated: false,
26673
+ reason: "merge_preview_interrupted"
26674
+ };
26675
+ if (preview.code === 1)
26676
+ return {
26677
+ kind: "tool-result",
26678
+ result: {
26679
+ content: [
26680
+ {
26681
+ type: "text",
26682
+ text: `Branch ${branch} conflicts with target ${targetBranch}; the Lead was not stopped and neither checkout was changed.`
26683
+ }
26684
+ ],
26685
+ details: {
26686
+ ok: false,
26687
+ action: "merge",
26688
+ branch,
26689
+ target_branch: targetBranch,
26690
+ source_head: expectedHead,
26691
+ target_head: preStopTarget,
26692
+ status: "needs_update",
26693
+ reason: "merge_conflict",
26694
+ integrated: false,
26695
+ checkout_removed: false,
26696
+ assignment_retired: false
26697
+ }
26698
+ }
26699
+ };
26700
+ const tree = String(preview.stdout ?? "").trim();
26701
+ if (preview.code !== 0 || !/^[0-9a-f]{40,64}$/i.test(tree))
26702
+ return {
26703
+ kind: "blocked",
26704
+ targetHead: preStopTarget,
26705
+ targetBranch,
26706
+ integrated: false,
26707
+ reason: "merge_preview_unavailable"
26708
+ };
26709
+ expectedMergeTree = tree;
26710
+ }
26711
+ const stopTarget = await inspectRemovalTarget(
26712
+ branch,
26713
+ ctx,
26714
+ operationSignal
26715
+ );
26716
+ if (stopTarget.assignment.id !== current.assignment.id || stopTarget.checkoutPath !== current.checkoutPath || stopTarget.checkedOutBranch !== sourceBranch || stopTarget.sourceCheckoutPath !== targetPath)
26717
+ return {
26718
+ kind: "tool-result",
26719
+ result: completionRefusal(
26720
+ "completion_evidence_superseded"
26721
+ )
26722
+ };
26723
+ assertCandidateLeadUnchanged(current, stopTarget);
26724
+ const finalEligibility = await currentExecutionEligibility(stopTarget);
26725
+ if (finalEligibility)
26726
+ return {
26727
+ kind: "tool-result",
26728
+ result: completionRefusal(finalEligibility)
26729
+ };
26730
+ if (stopTarget.liveLead)
25856
26731
  await stopExecution(
25857
- current.assignment.id,
25858
- current.liveLead,
26732
+ stopTarget.assignment.id,
26733
+ stopTarget.liveLead,
25859
26734
  ctx,
25860
26735
  operationSignal,
25861
26736
  heldLocks
@@ -25906,14 +26781,23 @@ Subsequent explicitly requested removals here can proceed without a per-removal
25906
26781
  throw new Error(
25907
26782
  "Primary target branch changed before integration"
25908
26783
  );
25909
- if (await ancestry(expectedHead, currentTarget))
26784
+ if (await ancestry(expectedHead, currentTarget)) {
26785
+ if (!await verifyPreviouslyIntegratedMerges(currentTarget))
26786
+ return {
26787
+ kind: "blocked",
26788
+ targetHead: currentTarget,
26789
+ targetBranch,
26790
+ integrated: true,
26791
+ reason: "already_integrated_divergent_merge_unverified"
26792
+ };
25910
26793
  return {
25911
26794
  kind: "integrated",
25912
26795
  targetHead: currentTarget,
25913
26796
  targetBranch,
25914
26797
  alreadyIntegrated: true
25915
26798
  };
25916
- if (!await ancestry(currentTarget, expectedHead))
26799
+ }
26800
+ if (!await ancestry(currentTarget, expectedHead) && !permission().allowDivergence)
25917
26801
  return {
25918
26802
  kind: "tool-result",
25919
26803
  result: {
@@ -25937,14 +26821,22 @@ Subsequent explicitly requested removals here can proceed without a per-removal
25937
26821
  }
25938
26822
  }
25939
26823
  };
25940
- if (!permission().enabled)
26824
+ if (!preStopFastForward && currentTarget !== preStopTarget)
26825
+ return {
26826
+ kind: "blocked",
26827
+ targetHead: currentTarget,
26828
+ targetBranch,
26829
+ integrated: false,
26830
+ reason: "target_changed_before_merge"
26831
+ };
26832
+ if (!permission().enabled || !preStopFastForward && !permission().allowDivergence)
25941
26833
  throw new Error(
25942
26834
  "Manager local merge permission was revoked"
25943
26835
  );
25944
26836
  let mergeError;
25945
26837
  const merged = await runGit(targetPath, [
25946
26838
  "merge",
25947
- "--ff-only",
26839
+ ...preStopFastForward ? ["--ff-only"] : ["--no-ff", "--no-edit", "-s", "ort"],
25948
26840
  "--no-autostash",
25949
26841
  "--no-overwrite-ignore",
25950
26842
  expectedHead
@@ -25978,6 +26870,20 @@ Subsequent explicitly requested removals here can proceed without a per-removal
25978
26870
  ["merge-base", "--is-ancestor", expectedHead, "HEAD"],
25979
26871
  { cwd: targetPath, timeout: 1e4 }
25980
26872
  );
26873
+ const parents = !preStopFastForward ? await host.pi.exec(
26874
+ "git",
26875
+ ["show", "-s", "--format=%P", "HEAD"],
26876
+ { cwd: targetPath, timeout: 1e4 }
26877
+ ) : void 0;
26878
+ const mergedTree = !preStopFastForward ? await host.pi.exec("git", ["rev-parse", "HEAD^{tree}"], {
26879
+ cwd: targetPath,
26880
+ timeout: 1e4
26881
+ }) : void 0;
26882
+ const containsOriginalTarget = !preStopFastForward ? await host.pi.exec(
26883
+ "git",
26884
+ ["merge-base", "--is-ancestor", preStopTarget, "HEAD"],
26885
+ { cwd: targetPath, timeout: 1e4 }
26886
+ ) : void 0;
25981
26887
  const observedBranch = await host.pi.exec(
25982
26888
  "git",
25983
26889
  ["symbolic-ref", "--quiet", "--short", "HEAD"],
@@ -26014,13 +26920,14 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26014
26920
  const observedHead = observed.code === 0 && !observed.killed ? String(observed.stdout ?? "").trim() : "";
26015
26921
  const integrationVerified = !!observedHead && containsAccepted.code === 0 && !containsAccepted.killed && observedBranch.code === 0 && !observedBranch.killed && !observedBranch.stderr?.trim() && String(observedBranch.stdout ?? "").trim() === targetBranch;
26016
26922
  const gitStateClean = status.code === 0 && !status.killed && !status.stderr?.trim() && !status.stdout?.trim() && index.code === 0 && !index.killed && !index.stdout?.trim() && !stateUnknown && operationStates.length === 0;
26017
- if (!integrationVerified || !gitStateClean || merged.code !== 0 && !interrupted)
26923
+ const divergentVerified = preStopFastForward || !!parents && parents.code === 0 && !parents.killed && String(parents.stdout ?? "").trim() === `${preStopTarget} ${expectedHead}` && !!mergedTree && mergedTree.code === 0 && !mergedTree.killed && String(mergedTree.stdout ?? "").trim() === expectedMergeTree && containsOriginalTarget?.code === 0 && !containsOriginalTarget.killed;
26924
+ if (!integrationVerified || !gitStateClean || !divergentVerified || merged.code !== 0 && !interrupted)
26018
26925
  return {
26019
26926
  kind: "blocked",
26020
26927
  targetHead: observedHead || currentTarget,
26021
26928
  targetBranch,
26022
26929
  integrated: integrationVerified,
26023
- reason: !integrationVerified ? "accepted_revision_not_verified_after_merge" : `git_state_after_merge:${stateUnknown ? "unknown" : operationStates.join(",") || (index.stdout?.trim() ? "unmerged_index" : status.stdout?.trim() ? "dirty_worktree" : mergeError || merged.stderr || "merge_failed")}`
26930
+ reason: !integrationVerified ? "accepted_revision_not_verified_after_merge" : !divergentVerified ? "divergent_merge_verification_failed" : `git_state_after_merge:${stateUnknown ? "unknown" : operationStates.join(",") || (index.stdout?.trim() ? "unmerged_index" : status.stdout?.trim() ? "dirty_worktree" : mergeError || merged.stderr || "merge_failed")}`
26024
26931
  };
26025
26932
  return {
26026
26933
  kind: "integrated",
@@ -26203,6 +27110,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26203
27110
  );
26204
27111
  const presentationTask = operation.action === "resume" ? projectTaskSummary(currentAssignment.text) : void 0;
26205
27112
  const id = operation.action === "resume" ? currentAssignment.id : operation.id;
27113
+ let resumeSenderEnvironment;
26206
27114
  const resumeRecord = (text, resultBindings, createdAt) => ({
26207
27115
  version: 2,
26208
27116
  build: HERDSMAN_BUILD2,
@@ -26214,6 +27122,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26214
27122
  leadSessionId: id,
26215
27123
  branch: currentAssignment.branch,
26216
27124
  text,
27125
+ ...resumeSenderEnvironment ? { senderEnvironment: resumeSenderEnvironment } : {},
26217
27126
  ...resultBindings.length ? { resultBindings: [...resultBindings] } : {},
26218
27127
  createdAt
26219
27128
  });
@@ -26221,6 +27130,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26221
27130
  let resumeEvidenceScope;
26222
27131
  const prepareResumeHandoff = async () => {
26223
27132
  if (operation.action !== "resume") return;
27133
+ resumeSenderEnvironment = await captureSenderEnvironment(host.pi, ctx);
26224
27134
  resumeMessageId ??= randomUUID12();
26225
27135
  try {
26226
27136
  const handoff = await prepareStaffHandoffEvidence(
@@ -26289,6 +27199,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26289
27199
  leadSessionId: id,
26290
27200
  branch: currentAssignment.branch,
26291
27201
  text: "Project assignment ready.",
27202
+ ...resumeSenderEnvironment ? { senderEnvironment: resumeSenderEnvironment } : {},
26292
27203
  createdAt
26293
27204
  });
26294
27205
  };
@@ -26823,13 +27734,18 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26823
27734
  }
26824
27735
  const definition = discoverRoleDefinition(
26825
27736
  MANAGED_LEAD_DEFINITION_NAME,
26826
- projectTrusted ? { projectRoot: cwd } : {}
27737
+ {
27738
+ ...projectTrusted ? { projectRoot: cwd } : {},
27739
+ onWarning: (message) => notifyDefinitionWarning(ctx, message)
27740
+ }
26827
27741
  );
26828
27742
  const body = expandAgentBodyFiles(definition.body, [], operationName);
26829
27743
  const effectiveDefinition = body === definition.body ? definition : { ...definition, body };
26830
27744
  if (body) promptPaths.push(...writePrivatePromptSnapshots([body]));
26831
27745
  const registeredProviderIds = new Set(
26832
- ctx.modelRegistry?.getRegisteredProviderIds?.() ?? []
27746
+ (ctx.modelRegistry?.getRegisteredProviderIds?.() ?? []).map(
27747
+ (id2) => id2.toLowerCase()
27748
+ )
26833
27749
  );
26834
27750
  const modelDecision = resolveChildModel({
26835
27751
  configured: configuredModel(effectiveDefinition.frontmatter),
@@ -26839,7 +27755,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26839
27755
  } : void 0,
26840
27756
  saved: operation.action === "resume" && savedModel?.kind === "resolved" ? savedModel.model : void 0,
26841
27757
  savedUnresolved: operation.action === "resume" && (savedModel === void 0 || savedModel.kind === "unresolved"),
26842
- isForeignProvider: (providerId) => registeredProviderIds.has(providerId),
27758
+ isForeignProvider: (providerId) => registeredProviderIds.has(providerId.toLowerCase()),
26843
27759
  isKnownModel: (provider, modelId) => ctx.modelRegistry.find(provider, modelId) !== void 0
26844
27760
  });
26845
27761
  const launchArgs = agentLaunchArgs(effectiveDefinition, {
@@ -27000,7 +27916,8 @@ Subsequent explicitly requested removals here can proceed without a per-removal
27000
27916
  `Lead ${assignment.id}`
27001
27917
  );
27002
27918
  assignment = await bindLeadSessionFile(assignment, lead, signal);
27003
- if (operation.action !== "resume")
27919
+ if (operation.action !== "resume") {
27920
+ const senderEnvironment = await captureSenderEnvironment(host.pi, ctx);
27004
27921
  writeChiefMessage2({
27005
27922
  version: 2,
27006
27923
  build: HERDSMAN_BUILD2,
@@ -27012,8 +27929,10 @@ Subsequent explicitly requested removals here can proceed without a per-removal
27012
27929
  leadSessionId,
27013
27930
  branch: assignment.branch,
27014
27931
  text: "Project assignment ready.",
27932
+ ...senderEnvironment ? { senderEnvironment } : {},
27015
27933
  createdAt: Date.now()
27016
27934
  });
27935
+ }
27017
27936
  let rediscovered;
27018
27937
  while (Date.now() < deadline) {
27019
27938
  const exact = (await liveLead(ctx, assignment.id)).filter(
@@ -27634,6 +28553,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
27634
28553
  throw error2;
27635
28554
  }
27636
28555
  try {
28556
+ const senderEnvironment = activeRole() === "manager" ? await captureSenderEnvironment(host.pi, ctx) : void 0;
27637
28557
  const prepared = await prepareCoordinationInput(
27638
28558
  ctx,
27639
28559
  params.message,
@@ -27651,6 +28571,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
27651
28571
  leadSessionId: reportSession(lead),
27652
28572
  ...initialAssignment ? { branch: initialAssignment.branch } : {},
27653
28573
  text: candidate,
28574
+ ...senderEnvironment ? { senderEnvironment } : {},
27654
28575
  ...resultBindings.length ? { resultBindings: [...resultBindings] } : {},
27655
28576
  createdAt
27656
28577
  })
@@ -27686,6 +28607,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
27686
28607
  leadSessionId: reportSession(lead),
27687
28608
  ...initialAssignment ? { branch: initialAssignment.branch } : {},
27688
28609
  text: prepared.text,
28610
+ ...senderEnvironment ? { senderEnvironment } : {},
27689
28611
  ...prepared.resultBindings.length ? { resultBindings: prepared.resultBindings } : {},
27690
28612
  createdAt
27691
28613
  };
@@ -28073,6 +28995,7 @@ function parseGitWorktreeInventory(output) {
28073
28995
  return void 0;
28074
28996
  worktrees.push({
28075
28997
  path,
28998
+ ...!bare && head ? { head } : {},
28076
28999
  ...branch ? { branch } : {},
28077
29000
  ...detached ? { detached: true } : {},
28078
29001
  ...locked ? { locked: true } : {},
@@ -28083,6 +29006,43 @@ function parseGitWorktreeInventory(output) {
28083
29006
  return void 0;
28084
29007
  return worktrees;
28085
29008
  }
29009
+ async function captureSenderEnvironment(pi, ctx) {
29010
+ const cwd = ctx.cwd;
29011
+ if (typeof cwd !== "string" || !isAbsolute6(cwd) || !cwd || Buffer.byteLength(cwd) > 1024)
29012
+ return void 0;
29013
+ try {
29014
+ const rootResult = await pi.exec("git", ["rev-parse", "--show-toplevel"], {
29015
+ cwd,
29016
+ signal: ctx.signal,
29017
+ timeout: 3e3
29018
+ });
29019
+ const root2 = String(rootResult.stdout ?? "").trim();
29020
+ if (rootResult.code !== 0 || rootResult.killed || rootResult.stderr?.trim() || !isAbsolute6(root2) || Buffer.byteLength(root2) > 1024)
29021
+ return { cwd };
29022
+ const inventoryResult = await pi.exec(
29023
+ "git",
29024
+ ["worktree", "list", "--porcelain", "-z"],
29025
+ { cwd, signal: ctx.signal, timeout: 3e3 }
29026
+ );
29027
+ if (inventoryResult.code !== 0 || inventoryResult.killed || inventoryResult.stderr?.trim())
29028
+ return { cwd };
29029
+ const matches = parseGitWorktreeInventory(String(inventoryResult.stdout ?? ""))?.filter(
29030
+ (entry2) => !entry2.prunable && sameDirectory(entry2.path, root2)
29031
+ ) ?? [];
29032
+ const entry = matches.length === 1 ? matches[0] : void 0;
29033
+ if (!entry?.head || !entry.detached && !entry.branch) return { cwd };
29034
+ return {
29035
+ cwd,
29036
+ git: {
29037
+ worktreeRoot: root2,
29038
+ branch: entry.detached ? null : entry.branch,
29039
+ head: entry.head
29040
+ }
29041
+ };
29042
+ } catch {
29043
+ return { cwd };
29044
+ }
29045
+ }
28086
29046
 
28087
29047
  // extension/lead/commands.ts
28088
29048
  init_config();
@@ -28215,9 +29175,13 @@ function createLeadCommandRuntime(host) {
28215
29175
  async openDefinitionsMenu(ctx) {
28216
29176
  let selectedSection = "agents";
28217
29177
  const selectedDefinitions = {};
28218
- const loadDefinitions = async (section, includeProject = true) => section === "agents" ? (await host.contextAgentDefinitions(ctx)).definitions : discoverRoleDefinitions(
28219
- includeProject && ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
28220
- );
29178
+ const loadDefinitions = async (section, includeProject = true, onWarning) => section === "agents" ? (await host.contextAgentDefinitions(ctx, onWarning)).definitions : discoverRoleDefinitions({
29179
+ ...includeProject && ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {},
29180
+ onWarning: (message) => {
29181
+ notifyDefinitionWarning(ctx, message);
29182
+ onWarning?.(message);
29183
+ }
29184
+ });
28221
29185
  const resolveDefinition = async (name) => {
28222
29186
  const loaded = await loadDefinitions(
28223
29187
  isReservedRoleDefinition(name) ? "roles" : "agents"
@@ -28245,8 +29209,13 @@ function createLeadCommandRuntime(host) {
28245
29209
  if (section !== "agents" && section !== "roles") return;
28246
29210
  selectedSection = section;
28247
29211
  definitionList: while (true) {
28248
- const availableDefinitions = await loadDefinitions(section);
28249
- if (!availableDefinitions.length) {
29212
+ const warnings = [];
29213
+ const availableDefinitions = await loadDefinitions(
29214
+ section,
29215
+ true,
29216
+ (message) => warnings.push(message)
29217
+ );
29218
+ if (!availableDefinitions.length && !warnings.length) {
28250
29219
  ctx.ui.notify(
28251
29220
  `No ${section === "agents" ? "Agent definitions" : "Coordinator profiles"} are available.`
28252
29221
  );
@@ -28274,6 +29243,16 @@ function createLeadCommandRuntime(host) {
28274
29243
  ...typeof definition2.frontmatter.description === "string" ? { help: definition2.frontmatter.description } : {}
28275
29244
  };
28276
29245
  });
29246
+ let warningValue = "__definition_warnings__";
29247
+ while (availableDefinitions.some(({ name }) => name === warningValue))
29248
+ warningValue += "_";
29249
+ if (warnings.length)
29250
+ options.unshift({
29251
+ value: warningValue,
29252
+ label: `\u26A0 ${warnings.length} misplaced definition(s)`,
29253
+ description: "Select to inspect paths",
29254
+ help: warnings[0]
29255
+ });
28277
29256
  const selected = await host.selectMenu(
28278
29257
  ctx,
28279
29258
  section === "agents" ? "Agents" : "Coordinators",
@@ -28282,6 +29261,10 @@ function createLeadCommandRuntime(host) {
28282
29261
  );
28283
29262
  if (selected === void 0) break definitionList;
28284
29263
  if (!selected) continue;
29264
+ if (selected === warningValue) {
29265
+ for (const warning of warnings) ctx.ui.notify(warning, "warning");
29266
+ continue;
29267
+ }
28285
29268
  const selectedEntry = availableDefinitions.find(
28286
29269
  (definition2) => definition2.name === selected
28287
29270
  );
@@ -28768,8 +29751,8 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
28768
29751
  {
28769
29752
  value: "manager-merge",
28770
29753
  label: "Manager local merge",
28771
- description: `Global ${config.managerMergeEnabled ? "on" : "off"}`,
28772
- help: "Allow the Manager to fast-forward accepted local project branches and automatically clean up integrated source worktrees."
29754
+ description: `Global ${config.managerMergeEnabled === "divergent" ? "conflict-free merges" : config.managerMergeEnabled ? "fast-forward only" : "off"}`,
29755
+ help: "Choose whether Managers may integrate accepted local branches only by fast-forward or also by clean divergent merge, with guarded cleanup."
28773
29756
  },
28774
29757
  {
28775
29758
  value: "status-widget-rows",
@@ -28907,17 +29890,29 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
28907
29890
  `Global ${key === "contextRetirement" ? "context retirement" : key === "autoActivateManager" ? "Manager auto-start" : "Manager Git setup confirmation skip"}: ${enabled ? "on" : "off"}`
28908
29891
  );
28909
29892
  } else if (selected === "manager-merge") {
28910
- const enabled = !host.readConfig().managerMergeEnabled;
28911
- if (enabled) {
29893
+ const current = host.readConfig().managerMergeEnabled;
29894
+ const choice = await host.selectMenu(
29895
+ ctx,
29896
+ "Global Manager local merge",
29897
+ [
29898
+ { value: "off", label: "Off" },
29899
+ { value: "fast-forward", label: "Fast-forward only" },
29900
+ { value: "divergent", label: "Conflict-free merges" }
29901
+ ],
29902
+ current === false ? "off" : current === true ? "fast-forward" : "divergent"
29903
+ );
29904
+ if (!choice) continue;
29905
+ const setting = choice === "off" ? false : choice === "fast-forward" ? true : "divergent";
29906
+ if (setting !== false && (current === false || setting === "divergent" && current !== "divergent")) {
28912
29907
  const confirm = await ctx.ui.input(
28913
- "Enable Manager local merge? This authorizes fast-forward integration and automatic cleanup of successfully integrated source worktrees. Type enable to confirm.",
29908
+ setting === "divergent" ? "Enable conflict-free divergent Manager merges? Git may create a new merge commit, and successful integration can automatically remove the exact source worktree. Type enable to confirm." : "Enable fast-forward Manager integration and automatic cleanup of successfully integrated source worktrees. Type enable to confirm.",
28914
29909
  void 0
28915
29910
  );
28916
29911
  if (confirm !== "enable") continue;
28917
29912
  }
28918
- host.updateConfig("managerMergeEnabled", enabled);
29913
+ host.updateConfig("managerMergeEnabled", setting);
28919
29914
  ctx.ui.notify(
28920
- `Global Manager local merge: ${enabled ? "on" : "off"}`
29915
+ `Global Manager local merge: ${setting === "divergent" ? "conflict-free merges" : setting ? "fast-forward only" : "off"}`
28921
29916
  );
28922
29917
  }
28923
29918
  }
@@ -28982,8 +29977,8 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
28982
29977
  ...mergePolicy ? [
28983
29978
  {
28984
29979
  value: "merge-permission",
28985
- label: `Manager local merge \xB7 ${mergePolicy.enabled ? "on" : "off"} (${mergePolicy.source})`,
28986
- help: `Controls local fast-forward integration and automatic cleanup for verified repository ${mergePolicy.repoKey}.`
29980
+ label: `Manager local merge \xB7 ${!mergePolicy.enabled ? "off" : mergePolicy.allowDivergence ? "conflict-free merges" : "fast-forward only"} (${mergePolicy.source})`,
29981
+ help: `Controls local integration and guarded cleanup for verified repository ${mergePolicy.repoKey}.`
28987
29982
  }
28988
29983
  ] : []
28989
29984
  ];
@@ -29029,18 +30024,19 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
29029
30024
  [
29030
30025
  {
29031
30026
  value: "inherit",
29032
- label: `Inherit global (${global3 ? "on" : "off"})`
30027
+ label: `Inherit global (${global3 === "divergent" ? "conflict-free merges" : global3 ? "fast-forward only" : "off"})`
29033
30028
  },
29034
- { value: "on", label: "On for this project" },
29035
- { value: "off", label: "Off for this project" }
30029
+ { value: "off", label: "Off" },
30030
+ { value: "fast-forward", label: "Fast-forward only" },
30031
+ { value: "divergent", label: "Conflict-free merges" }
29036
30032
  ],
29037
- current.source === "global" ? "inherit" : current.enabled ? "on" : "off"
30033
+ current.source === "global" ? "inherit" : !current.enabled ? "off" : current.allowDivergence ? "divergent" : "fast-forward"
29038
30034
  );
29039
30035
  if (!choice2) continue;
29040
- const enabled = choice2 === "inherit" ? void 0 : choice2 === "on";
29041
- if (enabled === true && !(current.enabled && current.source === "repository")) {
30036
+ const enabled = choice2 === "inherit" ? void 0 : choice2 === "off" ? false : choice2 === "fast-forward" ? true : "divergent";
30037
+ if (enabled !== void 0 && enabled !== false && (current.source !== "repository" || !current.enabled || enabled === "divergent" && !current.allowDivergence)) {
29042
30038
  const confirm = await ctx.ui.input(
29043
- "Enabling Manager local merge allows automatic cleanup of successfully integrated source worktrees. Type enable to confirm.",
30039
+ enabled === "divergent" ? "Enable conflict-free divergent Manager merges? Git may create a new merge commit, and successful integration can automatically remove the exact source worktree. Type enable to confirm." : "Enable fast-forward Manager integration and automatic cleanup of successfully integrated source worktrees. Type enable to confirm.",
29044
30040
  void 0
29045
30041
  );
29046
30042
  if (confirm !== "enable") continue;
@@ -29052,7 +30048,7 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
29052
30048
  );
29053
30049
  setManagerMergeOverride(mergePolicy.repoKey, enabled);
29054
30050
  ctx.ui.notify(
29055
- `Manager local merge ${enabled === void 0 ? "inherits global" : enabled ? "enabled" : "disabled"} for ${mergePolicy.repoKey}.`
30051
+ `Manager local merge ${enabled === void 0 ? "inherits global" : enabled === "divergent" ? "allows conflict-free merges" : enabled ? "allows fast-forward only" : "disabled"} for ${mergePolicy.repoKey}.`
29056
30052
  );
29057
30053
  continue;
29058
30054
  }
@@ -29310,6 +30306,7 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
29310
30306
  init_supervision();
29311
30307
  init_supervision();
29312
30308
  init_errors();
30309
+ init_recipient_fan_in();
29313
30310
  init_herdr();
29314
30311
  init_lock();
29315
30312
  init_config();
@@ -29330,7 +30327,7 @@ import { lstatSync as lstatSync7, realpathSync as realpathSync7, statSync as sta
29330
30327
  import {
29331
30328
  dirname as dirname8,
29332
30329
  isAbsolute as isAbsolute7,
29333
- join as join12,
30330
+ join as join13,
29334
30331
  resolve as resolve7,
29335
30332
  toNamespacedPath
29336
30333
  } from "node:path";
@@ -29339,6 +30336,7 @@ import {
29339
30336
  init_supervision();
29340
30337
  init_supervision();
29341
30338
  init_errors();
30339
+ init_recipient_fan_in();
29342
30340
  init_core();
29343
30341
  init_storage();
29344
30342
  init_agent_controller();
@@ -29360,7 +30358,7 @@ import {
29360
30358
  } from "node:fs";
29361
30359
  import { createHash as createHash11, randomUUID as randomUUID13 } from "node:crypto";
29362
30360
  import { spawn } from "node:child_process";
29363
- import { join as join10 } from "node:path";
30361
+ import { join as join11 } from "node:path";
29364
30362
  function peerRecoveryRequest(request, expectedDataRoot) {
29365
30363
  return JSON.stringify({ ...request, expectedDataRoot });
29366
30364
  }
@@ -29419,7 +30417,7 @@ function resolveRemotePeerOutboundRetry(outbound, status, snapshot) {
29419
30417
  return { kind: "retry", envelope: JSON.stringify(envelope) };
29420
30418
  }
29421
30419
  function outboundDirectoryPath() {
29422
- return join10(herdsmanDataRoot(), "runtime", "peers-v2", "remote-outbound");
30420
+ return join11(herdsmanDataRoot(), "runtime", "peers-v2", "remote-outbound");
29423
30421
  }
29424
30422
  function outboundDirectory() {
29425
30423
  const path = outboundDirectoryPath();
@@ -29430,7 +30428,7 @@ function outboundDirectory() {
29430
30428
  function tryClaimRemotePeerOutbound(id) {
29431
30429
  try {
29432
30430
  return acquireProcessLock(
29433
- join10(outboundDirectory(), `${id}.delivery.lock`),
30431
+ join11(outboundDirectory(), `${id}.delivery.lock`),
29434
30432
  { name: "peer outbound delivery" }
29435
30433
  ).release;
29436
30434
  } catch (error2) {
@@ -29443,7 +30441,7 @@ function persistRemotePeerOutbound(outbound) {
29443
30441
  const recordBytes = Buffer.byteLength(JSON.stringify(outbound), "utf8");
29444
30442
  if (!UUID4.test(outbound.id) || frameBytes > PEER_TRANSPORT_FRAME_LIMIT_BYTES || recordBytes > OUTBOUND_RECORD_LIMIT_BYTES)
29445
30443
  throw new Error("invalid remote peer outbound record");
29446
- const path = join10(outboundDirectory(), `${outbound.id}.json`);
30444
+ const path = join11(outboundDirectory(), `${outbound.id}.json`);
29447
30445
  writeFileSync6(path, `${JSON.stringify(outbound)}
29448
30446
  `, {
29449
30447
  encoding: "utf8",
@@ -29453,7 +30451,7 @@ function persistRemotePeerOutbound(outbound) {
29453
30451
  });
29454
30452
  }
29455
30453
  function retargetRemotePeerOutbound(id, digest, recipientSession, envelope) {
29456
- const path = join10(outboundDirectory(), `${id}.json`);
30454
+ const path = join11(outboundDirectory(), `${id}.json`);
29457
30455
  const lock = acquireProcessLock(`${path}.lock`, {
29458
30456
  name: "peer outbound update"
29459
30457
  });
@@ -29499,7 +30497,7 @@ function loadRemotePeerOutbound(path, id) {
29499
30497
  function readRemotePeerOutbound(id) {
29500
30498
  if (!UUID4.test(id)) return void 0;
29501
30499
  return loadRemotePeerOutbound(
29502
- join10(outboundDirectoryPath(), `${id}.json`),
30500
+ join11(outboundDirectoryPath(), `${id}.json`),
29503
30501
  id
29504
30502
  );
29505
30503
  }
@@ -29507,7 +30505,7 @@ function listRemotePeerOutbounds() {
29507
30505
  const directory2 = outboundDirectory();
29508
30506
  return readdirSync7(directory2).filter((name) => UUID4.test(name.slice(0, -5)) && name.endsWith(".json")).flatMap((name) => {
29509
30507
  const outbound = loadRemotePeerOutbound(
29510
- join10(directory2, name),
30508
+ join11(directory2, name),
29511
30509
  name.slice(0, -5)
29512
30510
  );
29513
30511
  return outbound ? [outbound] : [];
@@ -29516,7 +30514,7 @@ function listRemotePeerOutbounds() {
29516
30514
  function removeRemotePeerOutbound(id) {
29517
30515
  if (!UUID4.test(id)) return;
29518
30516
  try {
29519
- unlinkSync10(join10(outboundDirectory(), `${id}.json`));
30517
+ unlinkSync10(join11(outboundDirectory(), `${id}.json`));
29520
30518
  } catch (error2) {
29521
30519
  if (error2.code !== "ENOENT") throw error2;
29522
30520
  }
@@ -29688,7 +30686,7 @@ import {
29688
30686
  unlinkSync as unlinkSync11,
29689
30687
  writeFileSync as writeFileSync7
29690
30688
  } from "node:fs";
29691
- import { join as join11 } from "node:path";
30689
+ import { join as join12 } from "node:path";
29692
30690
  function resolvePeerResultBindings(bindings, existingRefs) {
29693
30691
  const accepted = [];
29694
30692
  const conflicts = [];
@@ -29723,7 +30721,7 @@ function assertPeerDataRoot(actual, expected) {
29723
30721
  throw new Error("peer endpoint data root does not match the active route");
29724
30722
  }
29725
30723
  function directory() {
29726
- const path = join11(herdsmanDataRoot(), "runtime", "peer-correspondences");
30724
+ const path = join12(herdsmanDataRoot(), "runtime", "peer-correspondences");
29727
30725
  mkdirSync10(path, { recursive: true, mode: 448 });
29728
30726
  chmodSync9(path, 448);
29729
30727
  return path;
@@ -29744,7 +30742,7 @@ function valid(value2) {
29744
30742
  );
29745
30743
  }
29746
30744
  function save(c) {
29747
- const path = join11(directory(), `${c.id}.json`);
30745
+ const path = join12(directory(), `${c.id}.json`);
29748
30746
  const tmp = `${path}.${randomUUID14()}.tmp`;
29749
30747
  writeFileSync7(tmp, `${JSON.stringify(c)}
29750
30748
  `, {
@@ -29759,7 +30757,7 @@ function mutate(id, action) {
29759
30757
  const deadline = Date.now() + 15e3;
29760
30758
  while (!lock) {
29761
30759
  try {
29762
- lock = acquireProcessLock(join11(directory(), `${id}.lock`), {
30760
+ lock = acquireProcessLock(join12(directory(), `${id}.lock`), {
29763
30761
  name: "peer correspondence mutation"
29764
30762
  });
29765
30763
  } catch (error2) {
@@ -29822,7 +30820,7 @@ function storePeerCorrespondence(c) {
29822
30820
  }
29823
30821
  function readPeerCorrespondence(id) {
29824
30822
  if (!ID.test(id)) throw new Error("invalid peer correspondence id");
29825
- const path = join11(
30823
+ const path = join12(
29826
30824
  herdsmanDataRoot(),
29827
30825
  "runtime",
29828
30826
  "peer-correspondences",
@@ -29870,7 +30868,7 @@ function listPeerCorrespondences() {
29870
30868
  return [];
29871
30869
  try {
29872
30870
  const c = JSON.parse(
29873
- readFileSync10(join11(directory(), name), "utf8")
30871
+ readFileSync10(join12(directory(), name), "utf8")
29874
30872
  );
29875
30873
  return valid(c) ? [c] : [];
29876
30874
  } catch {
@@ -30054,7 +31052,10 @@ function createLeadCoordinationRuntime(host) {
30054
31052
  } = host;
30055
31053
  const requireCompatibleBuild2 = host.requireCompatibleBuild;
30056
31054
  const reportedProjectMessageCleanupErrors = /* @__PURE__ */ new Set();
31055
+ const reportedProjectMessageSubmissionErrors = /* @__PURE__ */ new Set();
30057
31056
  const reportedProjectMessageReadErrors = /* @__PURE__ */ new Set();
31057
+ const projectMessageSubmissions = /* @__PURE__ */ new Map();
31058
+ let projectStartupEligibility;
30058
31059
  const reportedRetirementErrors = /* @__PURE__ */ new Set();
30059
31060
  const retirementCursors = /* @__PURE__ */ new Map();
30060
31061
  const prepareCoordinationInput = async (ctx, text, files, operation, heading, recordForInput) => {
@@ -30406,7 +31407,7 @@ function createLeadCoordinationRuntime(host) {
30406
31407
  if (!recipientContext || !source) return false;
30407
31408
  return canMessagePeer(source, recipientContext);
30408
31409
  };
30409
- const queuePeerRecord = async (text, targetSessionId, ctx, expectedSender, expectedTarget, recordId = randomUUID15(), createdAt = Date.now(), resultBindings = [], verifyEvidence) => {
31410
+ const queuePeerRecord = async (text, targetSessionId, ctx, expectedSender, expectedTarget, recordId = randomUUID15(), createdAt = Date.now(), resultBindings = [], verifyEvidence, capturedEnvironment) => {
30410
31411
  if (controllerScope?.kind !== "root" || leadRuntime.chiefMode !== "inactive" || leadRuntime.roleSuspended)
30411
31412
  throw new Error("Peer is unavailable in this role");
30412
31413
  if (leadRuntime.controllerRole === "manager" && (!leadRuntime.managerLease || (await currentManager(ctx))?.leaseId !== leadRuntime.managerLease.descriptor.leaseId))
@@ -30459,6 +31460,7 @@ function createLeadCoordinationRuntime(host) {
30459
31460
  "peer_message",
30460
31461
  `peer ${target.piSessionId}`
30461
31462
  );
31463
+ const senderEnvironment = capturedEnvironment === void 0 ? await captureSenderEnvironment(host.pi, ctx) : capturedEnvironment;
30462
31464
  const record = {
30463
31465
  version: 2,
30464
31466
  build: HERDSMAN_BUILD2,
@@ -30470,6 +31472,7 @@ function createLeadCoordinationRuntime(host) {
30470
31472
  leadSessionId: sender.piSessionId,
30471
31473
  peerSource: senderContext,
30472
31474
  text,
31475
+ ...senderEnvironment ? { senderEnvironment } : {},
30473
31476
  ...resultBindings.length ? { resultBindings: [...resultBindings] } : {},
30474
31477
  createdAt
30475
31478
  };
@@ -30501,7 +31504,7 @@ function createLeadCoordinationRuntime(host) {
30501
31504
  };
30502
31505
  return !verifyEvidence && senderContext.role === "manager" && targetContext.role === "manager" ? publish() : withProjectAssignmentAuthority(publish);
30503
31506
  };
30504
- const queueChiefRecord = async (kind, text, ctx, recordId, createdAt = Date.now(), runtimeOverride, expectedSupervisor, resultBindings = [], verifyEvidence) => {
31507
+ const queueChiefRecord = async (kind, text, ctx, recordId, createdAt = Date.now(), runtimeOverride, expectedSupervisor, resultBindings = [], verifyEvidence, capturedEnvironment) => {
30505
31508
  assertCurrentLeadCoordination(ctx);
30506
31509
  if (leadRuntime.controllerRole === "manager" && (!leadRuntime.managerLease || (await currentManager(ctx))?.leaseId !== leadRuntime.managerLease.descriptor.leaseId))
30507
31510
  throw new Error("Manager lease is no longer active");
@@ -30512,6 +31515,7 @@ function createLeadCoordinationRuntime(host) {
30512
31515
  const leadSessionId = ctx.sessionManager.getSessionId();
30513
31516
  if (chief.piSessionId === leadSessionId)
30514
31517
  throw new Error("Supervisor target is invalid");
31518
+ const senderEnvironment = capturedEnvironment === void 0 ? await captureSenderEnvironment(host.pi, ctx) : capturedEnvironment;
30515
31519
  const record = {
30516
31520
  version: 2,
30517
31521
  build: HERDSMAN_BUILD2,
@@ -30522,6 +31526,7 @@ function createLeadCoordinationRuntime(host) {
30522
31526
  toSessionId: chief.piSessionId,
30523
31527
  leadSessionId,
30524
31528
  text,
31529
+ ...senderEnvironment ? { senderEnvironment } : {},
30525
31530
  ...resultBindings.length ? { resultBindings: [...resultBindings] } : {},
30526
31531
  createdAt
30527
31532
  };
@@ -30715,6 +31720,7 @@ function createLeadCoordinationRuntime(host) {
30715
31720
  const recordId = randomUUID15();
30716
31721
  const createdAt = Date.now();
30717
31722
  const evidenceScope = hasManagerEvidenceSelectors(params.files ?? []) ? await host.managerEvidence?.(ctx, params.files ?? []) : void 0;
31723
+ const senderEnvironment = await captureSenderEnvironment(host.pi, ctx);
30718
31724
  const prepared = await prepareCoordinationInput(
30719
31725
  ctx,
30720
31726
  params.message,
@@ -30737,6 +31743,7 @@ function createLeadCoordinationRuntime(host) {
30737
31743
  toSessionId: chief.piSessionId,
30738
31744
  leadSessionId: ctx.sessionManager.getSessionId(),
30739
31745
  text: candidate,
31746
+ ...senderEnvironment ? { senderEnvironment } : {},
30740
31747
  ...resultBindings.length ? { resultBindings: [...resultBindings] } : {},
30741
31748
  createdAt
30742
31749
  })
@@ -30751,7 +31758,8 @@ function createLeadCoordinationRuntime(host) {
30751
31758
  void 0,
30752
31759
  void 0,
30753
31760
  prepared.resultBindings,
30754
- evidenceScope?.verify
31761
+ evidenceScope?.verify,
31762
+ senderEnvironment ?? null
30755
31763
  );
30756
31764
  };
30757
31765
  if (evidenceScope) await evidenceScope.revalidate(queue);
@@ -31428,6 +32436,7 @@ ${receivedRefs.join("\n")}` : ""}`,
31428
32436
  "Peer is unavailable or outside the permitted project scope. Run `list_peers` again."
31429
32437
  );
31430
32438
  const evidenceScope = hasManagerEvidenceSelectors(params.files ?? []) ? await host.managerEvidence?.(ctx, params.files ?? []) : void 0;
32439
+ const senderEnvironment = remoteRoute ? null : await captureSenderEnvironment(host.pi, ctx);
31431
32440
  const prepared = await prepareCoordinationInput(
31432
32441
  ctx,
31433
32442
  params.message,
@@ -31451,6 +32460,7 @@ ${receivedRefs.join("\n")}` : ""}`,
31451
32460
  leadSessionId: sender.piSessionId,
31452
32461
  peerSource: remoteRoute && activeRole() === "lead" ? { role: "lead", remoteOrdinary: true } : submissionSource,
31453
32462
  text: candidate,
32463
+ ...senderEnvironment ? { senderEnvironment } : {},
31454
32464
  ...resultBindings.length ? { resultBindings: [...resultBindings] } : {},
31455
32465
  createdAt
31456
32466
  })
@@ -31655,7 +32665,8 @@ ${receivedRefs.join("\n")}` : ""}`,
31655
32665
  recordId,
31656
32666
  createdAt,
31657
32667
  prepared.resultBindings,
31658
- evidenceScope?.verify
32668
+ evidenceScope?.verify,
32669
+ senderEnvironment
31659
32670
  );
31660
32671
  };
31661
32672
  if (evidenceScope) await evidenceScope.revalidate(queue);
@@ -31770,8 +32781,8 @@ ${receivedRefs.join("\n")}` : ""}`,
31770
32781
  );
31771
32782
  return pass;
31772
32783
  };
31773
- const drainProjectMessages = async (ctx) => {
31774
- if (activeRole() !== "manager" || leadRuntime.roleSuspended || !ctx.isIdle())
32784
+ const drainProjectMessages = async (ctx, phase = "idle", budget = { count: 0, bytes: 0 }) => {
32785
+ if (activeRole() !== "manager" || leadRuntime.roleSuspended || phase === "idle" && !ctx.isIdle() || phase === "turn")
31775
32786
  return 0;
31776
32787
  const lease = leadRuntime.managerLease;
31777
32788
  if (!lease) return 0;
@@ -31779,6 +32790,10 @@ ${receivedRefs.join("\n")}` : ""}`,
31779
32790
  if (!mightHaveProjectMessages(runtime, lease.descriptor.repoKey)) return 0;
31780
32791
  const manager = await currentManager(ctx);
31781
32792
  if (!manager || !sameManagerDescriptor2(manager, lease.descriptor)) return 0;
32793
+ const submissionPrefix = `${ctx.sessionManager.getSessionId()}:${manager.createdAt}:`;
32794
+ for (const key of projectMessageSubmissions.keys())
32795
+ if (!key.startsWith(submissionPrefix))
32796
+ projectMessageSubmissions.delete(key);
31782
32797
  const hasProjectMessageReceipt = (record) => ctx.sessionManager.getEntries().some(
31783
32798
  (entry) => entry?.customType === "pi-herdsman-project_message" && entry?.details?.id === record.id && entry?.details?.repoKey === record.repoKey && entry?.details?.branch === record.branch && entry?.details?.fromSessionId === record.fromSessionId
31784
32799
  );
@@ -31786,6 +32801,7 @@ ${receivedRefs.join("\n")}` : ""}`,
31786
32801
  try {
31787
32802
  removeProjectMessage2(runtime, record.repoKey, record.branch, record.id);
31788
32803
  reportedProjectMessageCleanupErrors.delete(record.id);
32804
+ reportedProjectMessageSubmissionErrors.delete(record.id);
31789
32805
  reportedProjectMessageReadErrors.delete(record.id);
31790
32806
  } catch (error2) {
31791
32807
  if (!reportedProjectMessageCleanupErrors.has(record.id)) {
@@ -31794,13 +32810,20 @@ ${receivedRefs.join("\n")}` : ""}`,
31794
32810
  }
31795
32811
  }
31796
32812
  };
32813
+ let submitted = 0;
31797
32814
  for (const assignment of listProjectAssignments2(runtime, manager.repoKey)) {
31798
32815
  let pending;
31799
32816
  try {
31800
32817
  pending = listProjectMessageHeaders2(
31801
32818
  runtime,
31802
32819
  manager.repoKey,
31803
- assignment.branch
32820
+ assignment.branch,
32821
+ (error2) => {
32822
+ const key = `header:${String(error2)}`;
32823
+ if (reportedProjectMessageReadErrors.has(key)) return;
32824
+ reportedProjectMessageReadErrors.add(key);
32825
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
32826
+ }
31804
32827
  );
31805
32828
  } catch (error2) {
31806
32829
  appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
@@ -31808,17 +32831,29 @@ ${receivedRefs.join("\n")}` : ""}`,
31808
32831
  }
31809
32832
  for (const record of pending) {
31810
32833
  if (record.fromSessionId !== assignment.id) continue;
32834
+ if (phase === "startup" && (projectStartupEligibility?.sessionId !== ctx.sessionManager.getSessionId() || projectStartupEligibility.managerCreatedAt !== manager.createdAt || record.createdAt > projectStartupEligibility.through))
32835
+ continue;
31811
32836
  if (hasProjectMessageReceipt(record)) {
32837
+ projectMessageSubmissions.delete(
32838
+ `${ctx.sessionManager.getSessionId()}:${manager.createdAt}:${record.id}`
32839
+ );
31812
32840
  consumeProjectMessage(record);
31813
32841
  continue;
31814
32842
  }
32843
+ const submissionKey = `${ctx.sessionManager.getSessionId()}:${manager.createdAt}:${record.id}`;
32844
+ const previousSubmission = projectMessageSubmissions.get(submissionKey);
32845
+ if (previousSubmission !== void 0) {
32846
+ if (Date.now() - previousSubmission < 3e4 || phase !== "idle")
32847
+ continue;
32848
+ projectMessageSubmissions.delete(submissionKey);
32849
+ }
31815
32850
  const current = await currentManager(ctx);
31816
32851
  const stillAssigned = readProjectAssignment2(
31817
32852
  runtime,
31818
32853
  manager.repoKey,
31819
32854
  assignment.branch
31820
32855
  );
31821
- if (!ctx.isIdle() || !current || !sameManagerDescriptor2(current, manager) || !stillAssigned || stillAssigned.id !== assignment.id)
32856
+ if (phase === "idle" && !ctx.isIdle() || !current || !sameManagerDescriptor2(current, manager) || !stillAssigned || stillAssigned.id !== assignment.id)
31822
32857
  return 0;
31823
32858
  let message;
31824
32859
  try {
@@ -31844,30 +32879,62 @@ ${receivedRefs.join("\n")}` : ""}`,
31844
32879
  );
31845
32880
  const backlog = message.createdAt < manager.createdAt;
31846
32881
  const actionableFailure = backlog && message.kind === "execution_failure";
31847
- pi.sendMessage(
31848
- {
31849
- customType: "pi-herdsman-project_message",
31850
- content: projectMessageEnvelope(
31851
- message.kind,
31852
- message.branch,
31853
- message.fromSessionId
31854
- ) + message.text,
31855
- display: true,
31856
- details: {
31857
- id: message.id,
31858
- repoKey: message.repoKey,
31859
- branch: message.branch,
31860
- fromSessionId: message.fromSessionId,
31861
- kind: message.kind
31862
- }
31863
- },
31864
- backlog && !actionableFailure ? { triggerTurn: false } : { deliverAs: "followUp", triggerTurn: true }
31865
- );
32882
+ const concurrentSubmission = projectMessageSubmissions.get(submissionKey);
32883
+ if (concurrentSubmission !== void 0) {
32884
+ if (phase !== "idle" || Date.now() - concurrentSubmission < 3e4)
32885
+ continue;
32886
+ projectMessageSubmissions.delete(submissionKey);
32887
+ }
32888
+ const content = projectMessageEnvelope(
32889
+ message.kind,
32890
+ message.branch,
32891
+ message.fromSessionId
32892
+ ) + message.text + senderEnvironmentAnnotation(message.senderEnvironment);
32893
+ if (!includeFanInMessage(budget, content)) continue;
32894
+ const submittedAt = Date.now();
32895
+ projectMessageSubmissions.set(submissionKey, submittedAt);
32896
+ try {
32897
+ const delivery = pi.sendMessage(
32898
+ {
32899
+ customType: "pi-herdsman-project_message",
32900
+ content,
32901
+ display: true,
32902
+ details: {
32903
+ id: message.id,
32904
+ repoKey: message.repoKey,
32905
+ branch: message.branch,
32906
+ fromSessionId: message.fromSessionId,
32907
+ kind: message.kind,
32908
+ ...message.senderEnvironment ? { senderEnvironment: message.senderEnvironment } : {}
32909
+ }
32910
+ },
32911
+ phase !== "idle" || backlog && !actionableFailure ? { triggerTurn: false } : { deliverAs: "followUp", triggerTurn: true }
32912
+ );
32913
+ if (phase !== "idle") await delivery;
32914
+ else
32915
+ void Promise.resolve(delivery).catch((error2) => {
32916
+ if (projectMessageSubmissions.get(submissionKey) === submittedAt)
32917
+ projectMessageSubmissions.delete(submissionKey);
32918
+ if (!reportedProjectMessageSubmissionErrors.has(record.id)) {
32919
+ reportedProjectMessageSubmissionErrors.add(record.id);
32920
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
32921
+ }
32922
+ });
32923
+ } catch (error2) {
32924
+ projectMessageSubmissions.delete(submissionKey);
32925
+ releaseFanInMessage(budget, content);
32926
+ if (!reportedProjectMessageSubmissionErrors.has(record.id)) {
32927
+ reportedProjectMessageSubmissionErrors.add(record.id);
32928
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
32929
+ }
32930
+ continue;
32931
+ }
31866
32932
  if (hasProjectMessageReceipt(message)) consumeProjectMessage(message);
31867
- return 1;
32933
+ submitted++;
32934
+ if (phase === "idle") return submitted;
31868
32935
  }
31869
32936
  }
31870
- return 0;
32937
+ return submitted;
31871
32938
  };
31872
32939
  return {
31873
32940
  persistCoordinatorState,
@@ -31896,6 +32963,16 @@ ${receivedRefs.join("\n")}` : ""}`,
31896
32963
  enterCoordinationPublication,
31897
32964
  drainRetirementNotices,
31898
32965
  drainProjectMessages,
32966
+ beginProjectMessageStartup: (ctx) => {
32967
+ const descriptor = leadRuntime.managerLease?.descriptor;
32968
+ if (activeRole() !== "manager" || leadRuntime.roleSuspended || !descriptor || !ctx.isIdle())
32969
+ return;
32970
+ projectStartupEligibility = {
32971
+ sessionId: ctx.sessionManager.getSessionId(),
32972
+ managerCreatedAt: descriptor.createdAt,
32973
+ through: Date.now()
32974
+ };
32975
+ },
31899
32976
  supervisorMessage: executeSupervisorMessage,
31900
32977
  peerMessage: executePeerMessage,
31901
32978
  latestCustomMessageText,
@@ -31946,14 +33023,16 @@ function createLeadToolState(getAllTools, ownedNames, leadCoordinationNames) {
31946
33023
  };
31947
33024
  const projectRoleTools = (baseline, definition, requiredTools) => {
31948
33025
  const policy = configuredToolPolicy(definition, requiredTools);
33026
+ const required = new Set(requiredTools);
31949
33027
  const selected = policy.explicit ? policy.tools.flatMap(
31950
33028
  (pattern) => [...registeredToolNames()].filter(
31951
33029
  (name) => matchesToolPattern(pattern, name)
31952
33030
  )
31953
33031
  ) : [...baseline];
31954
- const excluded = (name) => policy.excluded.some((pattern) => matchesToolPattern(pattern, name));
31955
33032
  return appendRegisteredTools(
31956
- normalizeBaseTools(selected.filter((name) => !excluded(name))),
33033
+ normalizeBaseTools(
33034
+ selected.filter((name) => toolPolicyAllowsName(policy, required, name))
33035
+ ),
31957
33036
  requiredTools
31958
33037
  );
31959
33038
  };
@@ -31989,6 +33068,116 @@ function sessionLeadExecutionState(entries, sessionId) {
31989
33068
  }
31990
33069
  return state;
31991
33070
  }
33071
+ async function readGitWorktreeState(git, cwd) {
33072
+ const status = (await git(cwd, [
33073
+ "--no-optional-locks",
33074
+ "status",
33075
+ "--porcelain=v2",
33076
+ "--branch",
33077
+ "-z",
33078
+ "--untracked-files=normal"
33079
+ ])).split("\0");
33080
+ let headerEnd = 0;
33081
+ const headers = /* @__PURE__ */ new Map();
33082
+ while (headerEnd < status.length && status[headerEnd]?.startsWith("# ")) {
33083
+ const match = /^# (branch\.(?:head|oid)) (.*)$/u.exec(status[headerEnd]);
33084
+ if (match) headers.set(match[1], match[2]);
33085
+ headerEnd++;
33086
+ }
33087
+ const branchHead = headers.get("branch.head");
33088
+ const oid = headers.get("branch.oid");
33089
+ const checkedOutBranch = branchHead === "(detached)" ? "detached" : branchHead;
33090
+ if (!checkedOutBranch || checkedOutBranch === "(unknown)" || !/^(?:detached|[^\s\0]+)$/u.test(checkedOutBranch) || !oid || oid !== "(initial)" && !/^[0-9a-f]{40,64}$/iu.test(oid))
33091
+ return void 0;
33092
+ return {
33093
+ checkedOutBranch,
33094
+ dirty: status.slice(headerEnd).some((entry) => entry.length > 0),
33095
+ ...oid === "(initial)" ? {} : { head: oid }
33096
+ };
33097
+ }
33098
+ async function observeGitChangeSummary(git, checkoutPath, repoKey, comparisonHead) {
33099
+ const root2 = (await git(checkoutPath, ["rev-parse", "--show-toplevel"])).trim();
33100
+ const common = resolve7(
33101
+ checkoutPath,
33102
+ (await git(checkoutPath, ["rev-parse", "--git-common-dir"])).trim()
33103
+ );
33104
+ if (!sameDirectory(root2, checkoutPath) || !sameDirectory(common, repoKey))
33105
+ return void 0;
33106
+ const state = await readGitWorktreeState(git, checkoutPath);
33107
+ if (!state) return void 0;
33108
+ let additions;
33109
+ let deletions;
33110
+ let changedFiles;
33111
+ let comparisonSha;
33112
+ if (state.head) {
33113
+ try {
33114
+ const head = (await comparisonHead()).trim();
33115
+ if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(head)) {
33116
+ const bases = (await git(checkoutPath, ["merge-base", "--all", head, state.head])).trim().split(/\s+/u);
33117
+ if (bases.length === 1 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(bases[0]))
33118
+ comparisonSha = bases[0];
33119
+ }
33120
+ } catch {
33121
+ }
33122
+ }
33123
+ if (comparisonSha) {
33124
+ try {
33125
+ const output = await git(checkoutPath, [
33126
+ "--no-optional-locks",
33127
+ "diff",
33128
+ "--numstat",
33129
+ "-z",
33130
+ "--find-renames",
33131
+ comparisonSha,
33132
+ "--"
33133
+ ]);
33134
+ const records = output.split("\0");
33135
+ let valid2 = output === "" || output.endsWith("\0");
33136
+ if (valid2) records.pop();
33137
+ let added = 0, deleted = 0, files = 0;
33138
+ for (let i = 0; valid2 && i < records.length; ) {
33139
+ const match = /^(\d+|-)\t(\d+|-)\t(.*)$/su.exec(records[i++]);
33140
+ if (!match) {
33141
+ valid2 = false;
33142
+ break;
33143
+ }
33144
+ const [, a, d, path] = match;
33145
+ if (!path && (!records[i++] || !records[i++])) {
33146
+ valid2 = false;
33147
+ break;
33148
+ }
33149
+ if (a === "-" && d === "-") {
33150
+ files++;
33151
+ continue;
33152
+ }
33153
+ if (!/^\d+$/u.test(a) || !/^\d+$/u.test(d)) {
33154
+ valid2 = false;
33155
+ break;
33156
+ }
33157
+ added += Number(a);
33158
+ deleted += Number(d);
33159
+ files++;
33160
+ if (!Number.isSafeInteger(added) || !Number.isSafeInteger(deleted)) {
33161
+ valid2 = false;
33162
+ break;
33163
+ }
33164
+ }
33165
+ if (valid2) {
33166
+ additions = added;
33167
+ deletions = deleted;
33168
+ changedFiles = files;
33169
+ }
33170
+ } catch {
33171
+ }
33172
+ }
33173
+ return {
33174
+ dirty: state.dirty,
33175
+ additions,
33176
+ deletions,
33177
+ changedFiles,
33178
+ checkedOutBranch: state.checkedOutBranch
33179
+ };
33180
+ }
31992
33181
  function createLeadShutdownRuntime(host) {
31993
33182
  const isRoot = () => host.isRoot();
31994
33183
  let shutDown = false;
@@ -32334,6 +33523,13 @@ function createLeadAgentEventRuntime(host) {
32334
33523
  sections.pi_herdsman_role = host.roleCharter(ctx);
32335
33524
  return;
32336
33525
  }
33526
+ try {
33527
+ if (host.currentLeadAllowedTools?.() !== void 0)
33528
+ host.reconcileRoleTools?.();
33529
+ } catch (error2) {
33530
+ host.setActiveTools([]);
33531
+ throw error2;
33532
+ }
32337
33533
  const activeLead = host.isActiveLead() && !host.isRoleSuspended();
32338
33534
  const supervisorStateMessage2 = activeLead ? await host.prepareLeadSupervisorStateMessage(ctx) : void 0;
32339
33535
  if (supervisorStateMessage2) host.sendMessage(supervisorStateMessage2);
@@ -32383,7 +33579,21 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
32383
33579
  reason: "Tool is unavailable in the active Chief profile."
32384
33580
  };
32385
33581
  }
32386
- if (!host.isActiveManager()) return void 0;
33582
+ if (!host.isActiveManager()) {
33583
+ try {
33584
+ const allowed = host.currentLeadAllowedTools?.();
33585
+ if (!allowed || allowed.includes(event.toolName)) return void 0;
33586
+ } catch {
33587
+ return {
33588
+ block: true,
33589
+ reason: "Lead tool authorization is unavailable."
33590
+ };
33591
+ }
33592
+ return {
33593
+ block: true,
33594
+ reason: "Tool is unavailable in the active Lead profile."
33595
+ };
33596
+ }
32387
33597
  try {
32388
33598
  if ((host.currentManagerAllowedTools?.(ctx) ?? host.managerTools ?? []).includes(event.toolName))
32389
33599
  return void 0;
@@ -32402,6 +33612,9 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
32402
33612
  }
32403
33613
  function registerLeadRuntime(pi, options) {
32404
33614
  const statusRuntime = createAgentStatusRuntime();
33615
+ let invalidateSupervisionWidget = () => {
33616
+ };
33617
+ let getLocalActivity = () => "unknown";
32405
33618
  const leadRuntime = options.leadRuntime ?? createLeadRuntimeState();
32406
33619
  const leadToolState = options.leadToolState ?? createLeadToolState(
32407
33620
  () => pi.getAllTools(),
@@ -32413,6 +33626,7 @@ function registerLeadRuntime(pi, options) {
32413
33626
  options.onLeadRuntimeReady?.(leadRuntime, leadToolState);
32414
33627
  let leadExecution;
32415
33628
  let sessionKind;
33629
+ let verifiedManagedAssignment;
32416
33630
  let managedLifecycle = "unavailable";
32417
33631
  let assignmentVerificationGeneration = 0;
32418
33632
  let leadExecutionPending = false;
@@ -32424,10 +33638,10 @@ function registerLeadRuntime(pi, options) {
32424
33638
  let inheritedProjection;
32425
33639
  const prepareSupervisoryProfile = (ctx, role2) => {
32426
33640
  const name = role2 === "manager" ? MANAGER_DEFINITION_NAME : CHIEF_DEFINITION_NAME;
32427
- const definition = options.commandHost.discoverRoleDefinition(
32428
- name,
32429
- ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
32430
- );
33641
+ const definition = options.commandHost.discoverRoleDefinition(name, {
33642
+ ...ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {},
33643
+ onWarning: (message) => notifyDefinitionWarning(ctx, message)
33644
+ });
32431
33645
  const prepared = {
32432
33646
  ...definition,
32433
33647
  body: expandAgentBodyFiles(definition.body, [], `${role2} role profile`)
@@ -32528,7 +33742,18 @@ function registerLeadRuntime(pi, options) {
32528
33742
  validateRoleAgentDefinitionReferences(
32529
33743
  profile.definition,
32530
33744
  discoverAgentDefinitions(
32531
- leadRuntime.leadContext.isProjectTrusted() ? { projectRoot: leadRuntime.leadContext.cwd } : {}
33745
+ leadRuntime.leadContext.isProjectTrusted() ? {
33746
+ projectRoot: leadRuntime.leadContext.cwd,
33747
+ onWarning: (message) => notifyDefinitionWarning(
33748
+ leadRuntime.leadContext,
33749
+ message
33750
+ )
33751
+ } : {
33752
+ onWarning: (message) => notifyDefinitionWarning(
33753
+ leadRuntime.leadContext,
33754
+ message
33755
+ )
33756
+ }
32532
33757
  )
32533
33758
  );
32534
33759
  return new Set(profile.definition.frontmatter.agents ?? []);
@@ -32669,6 +33894,10 @@ function registerLeadRuntime(pi, options) {
32669
33894
  state: leadRuntime,
32670
33895
  activeRole: () => activeLeadRole(leadRuntime),
32671
33896
  pi,
33897
+ getLocalActivity: (ctx) => getLocalActivity(ctx),
33898
+ onActivityChange: (invalidate) => {
33899
+ invalidateSupervisionWidget = invalidate;
33900
+ },
32672
33901
  isCurrentChief: (ctx) => leadRuntime.chiefMode === "active" && !!leadRuntime.chiefLease && leadRuntime.chiefLease.descriptor.piSessionId === ctx.sessionManager.getSessionId(),
32673
33902
  currentManager: (...args) => roleTransitions.currentManager(...args),
32674
33903
  resolveEffectiveSupervisor: (...args) => roleTransitions.resolveEffectiveSupervisor(...args),
@@ -32991,17 +34220,21 @@ function registerLeadRuntime(pi, options) {
32991
34220
  return restrictLeadAgentTools(tools, policy, leadRuntime.leadContext);
32992
34221
  };
32993
34222
  if (!sessionKind) return [];
32994
- if (sessionKind.kind === "managed" && managedLifecycle !== "assigned")
32995
- return leadRuntime.leadContext ? ownedAgentManagementTools(leadRuntime.leadContext) : [];
32996
- if (leadExecutionPending)
32997
- return restrict(leadToolState.normalizeLeadTools([]));
32998
- if (sessionKind.kind === "managed")
34223
+ const managedRecoveryTools = () => leadRuntime.leadContext ? ownedAgentManagementTools(leadRuntime.leadContext) : [];
34224
+ if (sessionKind.kind === "managed") {
34225
+ if (managedLifecycle !== "assigned" || leadRuntime.roleSuspended || leadRuntime.chiefMode === "suspended" || leadExecutionPending || !leadExecution?.valid || !leadExecution.managed)
34226
+ return managedRecoveryTools();
34227
+ const definition = leadExecution.definition;
34228
+ const managedBaseline = definition.frontmatter.noTools === true && definition.frontmatter.tools === void 0 ? [] : baseline;
32999
34229
  return restrict(
33000
34230
  leadToolState.appendRegisteredTools(
33001
- leadToolState.normalizeLeadTools(baseline),
34231
+ leadToolState.projectLeadTools(managedBaseline, definition),
33002
34232
  ["read_evidence"]
33003
34233
  )
33004
34234
  );
34235
+ }
34236
+ if (leadExecutionPending)
34237
+ return restrict(leadToolState.normalizeLeadTools([]));
33005
34238
  if (!leadExecution)
33006
34239
  return restrict(leadToolState.normalizeLeadTools(baseline));
33007
34240
  if (!leadExecution.valid)
@@ -33021,6 +34254,7 @@ function registerLeadRuntime(pi, options) {
33021
34254
  const roleTransitionControllerScope = { kind: "root" };
33022
34255
  const roleTransitionServices = {
33023
34256
  ...roleHost,
34257
+ isManagedSession: () => sessionKind?.kind === "managed",
33024
34258
  prepareSupervisoryProfile,
33025
34259
  commitSupervisoryProfile,
33026
34260
  currentSupervisoryProfile,
@@ -33056,7 +34290,10 @@ function registerLeadRuntime(pi, options) {
33056
34290
  schedulePeerPresence: (ctx) => coordinationRuntime.schedulePeerPresence(ctx),
33057
34291
  removePeerPresence: () => coordinationRuntime.removePeerPresence(),
33058
34292
  clearNormalUI: () => statusRuntime.clear(),
33059
- startNormalUI: (ctx) => statusRuntime.start(ctx),
34293
+ startNormalUI: (ctx) => {
34294
+ statusRuntime.clear();
34295
+ statusRuntime.start(ctx);
34296
+ },
33060
34297
  startSupervisionUI,
33061
34298
  clearSupervisionUI,
33062
34299
  publishLeadRole,
@@ -33119,8 +34356,13 @@ function registerLeadRuntime(pi, options) {
33119
34356
  projectAssignmentForScope: (...args) => roleTransitions.projectAssignmentForScope(...args),
33120
34357
  resolveEffectiveSupervisor: (...args) => roleTransitions.resolveEffectiveSupervisor(...args),
33121
34358
  currentPeerPresenceValid: async (ctx) => (sessionKind?.kind !== "managed" || managedLifecycle === "assigned") && await coordinationRuntime.currentPeerPresenceValid(ctx),
33122
- drainProjectMessages: (ctx) => coordinationRuntime.drainRetirementNotices(ctx).then(
33123
- async (count) => count + await coordinationRuntime.drainProjectMessages(ctx)
34359
+ beginProjectMessageStartup: (ctx) => coordinationRuntime.beginProjectMessageStartup(ctx),
34360
+ drainProjectMessages: (ctx, phase, budget) => phase && phase !== "idle" ? coordinationRuntime.drainProjectMessages(ctx, phase, budget) : coordinationRuntime.drainRetirementNotices(ctx).then(
34361
+ async (count) => count + await coordinationRuntime.drainProjectMessages(
34362
+ ctx,
34363
+ "idle",
34364
+ budget
34365
+ )
33124
34366
  ),
33125
34367
  reconcileRemotePeers: async (ctx, signal) => {
33126
34368
  if (activeLeadRole(leadRuntime) === "manager" || activeLeadRole(leadRuntime) === "lead")
@@ -33268,6 +34510,7 @@ function registerLeadRuntime(pi, options) {
33268
34510
  };
33269
34511
  const controller = createAgentController(pi, {
33270
34512
  ...options.controllerServices,
34513
+ registerRecipientFanIn: false,
33271
34514
  scope: { kind: "root" },
33272
34515
  managerEvidence,
33273
34516
  persistClosedDescendants: async (ctx, closures, selected) => {
@@ -33412,10 +34655,14 @@ function registerLeadRuntime(pi, options) {
33412
34655
  if (isLead && sessionKind?.kind === "managed") {
33413
34656
  const previous = managedLifecycle;
33414
34657
  try {
33415
- await currentProjectAssignment(ctx);
34658
+ const assignment = await currentProjectAssignment(ctx);
34659
+ verifiedManagedAssignment = assignment ? { sessionId: sessionKind.sessionId, assignment } : void 0;
33416
34660
  } catch {
34661
+ verifiedManagedAssignment = void 0;
33417
34662
  }
33418
34663
  if (previous !== managedLifecycle) roleTransitions.reconcileRoleTools();
34664
+ } else {
34665
+ verifiedManagedAssignment = void 0;
33419
34666
  }
33420
34667
  const snapshot = buildAgentStatusSnapshot(view, ctx, {
33421
34668
  ...options.statusSnapshotHost,
@@ -33505,14 +34752,124 @@ function registerLeadRuntime(pi, options) {
33505
34752
  }
33506
34753
  );
33507
34754
  };
34755
+ let leadGitCache;
34756
+ let leadGitLastAttemptAt = 0;
34757
+ let leadGitSampling;
34758
+ let leadGitAbort;
34759
+ let leadGitGeneration = 0;
34760
+ let leadGitIdentity;
34761
+ let leadGitContext;
34762
+ const cancelLeadGitSampling = (resetRate = true) => {
34763
+ leadGitGeneration++;
34764
+ leadGitAbort?.abort();
34765
+ leadGitAbort = void 0;
34766
+ leadGitSampling = void 0;
34767
+ leadGitCache = void 0;
34768
+ leadGitIdentity = void 0;
34769
+ leadGitContext = void 0;
34770
+ if (resetRate) leadGitLastAttemptAt = 0;
34771
+ };
34772
+ const sameLeadGitIdentity = (left, right) => left.sessionId === right.sessionId && left.comparison === right.comparison && left.repoKey === right.repoKey && left.assignmentBranch === right.assignmentBranch && sameDirectory(left.checkoutPath, right.checkoutPath);
34773
+ const sampleLeadGit = (ctx, snapshot) => {
34774
+ const verified = verifiedManagedAssignment;
34775
+ const sessionId = ctx.sessionManager.getSessionId();
34776
+ const assignment = verified?.assignment;
34777
+ const comparison = sessionKind?.kind === "managed" && managedLifecycle === "assigned" && verified?.sessionId === sessionId && !!assignment;
34778
+ if (activeLeadRole(leadRuntime) !== "lead" || !sessionKind || sessionKind.sessionId !== sessionId || snapshot.stale || snapshot.unavailable || !statusRuntime.isWidgetActive()) {
34779
+ cancelLeadGitSampling();
34780
+ return;
34781
+ }
34782
+ const identity = {
34783
+ sessionId,
34784
+ checkoutPath: ctx.cwd,
34785
+ comparison,
34786
+ ...comparison ? { repoKey: assignment.repoKey, assignmentBranch: assignment.branch } : {}
34787
+ };
34788
+ if (leadGitIdentity && !sameLeadGitIdentity(leadGitIdentity, identity))
34789
+ cancelLeadGitSampling();
34790
+ leadGitIdentity = identity;
34791
+ leadGitContext = ctx;
34792
+ if (leadGitCache && !sameLeadGitIdentity(leadGitCache.identity, identity))
34793
+ leadGitCache = void 0;
34794
+ if (leadGitSampling) return;
34795
+ if (Date.now() - leadGitLastAttemptAt < 3e4) return;
34796
+ leadGitLastAttemptAt = Date.now();
34797
+ const generation = ++leadGitGeneration;
34798
+ const abort = new AbortController();
34799
+ leadGitAbort = abort;
34800
+ const contextSignal = ctx.signal;
34801
+ const abortFromContext = () => abort.abort(contextSignal?.reason);
34802
+ contextSignal?.addEventListener("abort", abortFromContext, { once: true });
34803
+ const deadline = setTimeout(() => abort.abort(), 15e3);
34804
+ deadline.unref?.();
34805
+ const stillCurrent = () => {
34806
+ const latest = statusRuntime.getSnapshot();
34807
+ return generation === leadGitGeneration && statusRuntime.isWidgetActive() && activeLeadRole(leadRuntime) === "lead" && sessionKind?.sessionId === identity.sessionId && ctx.sessionManager.getSessionId() === identity.sessionId && (!identity.comparison || managedLifecycle === "assigned" && verifiedManagedAssignment?.sessionId === identity.sessionId && verifiedManagedAssignment.assignment.repoKey === identity.repoKey && verifiedManagedAssignment.assignment.branch === identity.assignmentBranch) && sameDirectory(ctx.cwd, identity.checkoutPath) && !latest.stale && !latest.unavailable && leadGitIdentity !== void 0 && sameLeadGitIdentity(leadGitIdentity, identity);
34808
+ };
34809
+ const current = () => !abort.signal.aborted && stillCurrent();
34810
+ const git = async (cwd, args) => {
34811
+ if (!current()) throw new Error("Git sampling cancelled");
34812
+ const result = await pi.exec("git", args, {
34813
+ cwd,
34814
+ signal: abort.signal,
34815
+ timeout: 3e3
34816
+ });
34817
+ if (!current() || result.code !== 0 || result.killed)
34818
+ throw new Error("Git observation unavailable");
34819
+ return String(result.stdout ?? "");
34820
+ };
34821
+ const sampling = (async () => {
34822
+ let summary;
34823
+ try {
34824
+ if (identity.comparison) {
34825
+ summary = await observeGitChangeSummary(
34826
+ git,
34827
+ identity.checkoutPath,
34828
+ identity.repoKey,
34829
+ async () => git(identity.checkoutPath, [
34830
+ "rev-parse",
34831
+ "--verify",
34832
+ "main-worktree/HEAD^{commit}"
34833
+ ])
34834
+ );
34835
+ } else {
34836
+ const state = await readGitWorktreeState(git, identity.checkoutPath);
34837
+ summary = state ? { dirty: state.dirty, checkedOutBranch: state.checkedOutBranch } : void 0;
34838
+ }
34839
+ } catch {
34840
+ }
34841
+ if (!stillCurrent()) return;
34842
+ leadGitCache = summary && !abort.signal.aborted ? { identity, summary } : void 0;
34843
+ statusRuntime.invalidateWidget();
34844
+ })().finally(() => {
34845
+ clearTimeout(deadline);
34846
+ contextSignal?.removeEventListener("abort", abortFromContext);
34847
+ if (leadGitSampling === sampling) {
34848
+ leadGitSampling = void 0;
34849
+ if (leadGitAbort === abort) leadGitAbort = void 0;
34850
+ }
34851
+ });
34852
+ leadGitSampling = sampling;
34853
+ };
33508
34854
  statusRuntime.configure({
34855
+ getLocalActivity: (ctx) => getLocalActivity(ctx),
33509
34856
  ...options.statusSnapshotHost,
33510
34857
  pendingStartEntries: () => controller.pendingStartEntries(),
33511
34858
  hasPendingStart: (label) => controller.hasPendingStart(label),
33512
34859
  clearPendingStart: (label, expected) => controller.clearPendingStart(label, expected),
33513
34860
  loadSnapshot: (ctx) => loadStatusSnapshot(ctx, controller.sessionSignal(), false),
33514
34861
  runtimeForLabel: (label) => controller.runtimeForLabel(label),
33515
- focusTarget
34862
+ focusTarget,
34863
+ getGitSummary: () => {
34864
+ const snapshot = statusRuntime.getSnapshot();
34865
+ const cached = leadGitCache;
34866
+ const identity = cached?.identity;
34867
+ if (!identity || activeLeadRole(leadRuntime) !== "lead" || !sessionKind || sessionKind.sessionId !== identity.sessionId || leadGitContext?.sessionManager.getSessionId() !== identity.sessionId || snapshot.stale || snapshot.unavailable || !sameDirectory(identity.checkoutPath, leadGitContext.cwd))
34868
+ return void 0;
34869
+ return !identity.comparison || managedLifecycle === "assigned" && verifiedManagedAssignment?.sessionId === identity.sessionId && verifiedManagedAssignment.assignment.repoKey === identity.repoKey && verifiedManagedAssignment.assignment.branch === identity.assignmentBranch ? cached.summary : void 0;
34870
+ },
34871
+ onFreshStatus: sampleLeadGit,
34872
+ onWidgetStop: () => cancelLeadGitSampling()
33516
34873
  });
33517
34874
  let projectRuntime;
33518
34875
  const projectHost = options.projectHost;
@@ -33820,17 +35177,18 @@ function registerLeadRuntime(pi, options) {
33820
35177
  };
33821
35178
  const resolveExecutionDefinition = (ctx, mode, definitions) => {
33822
35179
  const name = mode === "flexible" ? FLEXIBLE_LEAD_DEFINITION_NAME : ORCHESTRATOR_LEAD_DEFINITION_NAME;
33823
- const definition = definitions ? definitions.find((candidate) => candidate.name === name) : options.commandHost.discoverRoleDefinition(
33824
- name,
33825
- ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
33826
- );
35180
+ const definition = definitions ? definitions.find((candidate) => candidate.name === name) : options.commandHost.discoverRoleDefinition(name, {
35181
+ ...ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {},
35182
+ onWarning: (message) => notifyDefinitionWarning(ctx, message)
35183
+ });
33827
35184
  if (!definition) throw new Error(`Lead definition ${name} not found`);
33828
35185
  if (definitions && definition.frontmatter.agents?.length)
33829
35186
  validateRoleAgentDefinitionReferences(
33830
35187
  definition,
33831
- discoverAgentDefinitions(
33832
- ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
33833
- )
35188
+ discoverAgentDefinitions({
35189
+ ...ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {},
35190
+ onWarning: (message) => notifyDefinitionWarning(ctx, message)
35191
+ })
33834
35192
  );
33835
35193
  return {
33836
35194
  ...definition,
@@ -33841,10 +35199,10 @@ function registerLeadRuntime(pi, options) {
33841
35199
  )
33842
35200
  };
33843
35201
  };
33844
- const managedLeadDefinition = (ctx) => options.commandHost.discoverRoleDefinition(
33845
- MANAGED_LEAD_DEFINITION_NAME,
33846
- ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
33847
- );
35202
+ const managedLeadDefinition = (ctx) => options.commandHost.discoverRoleDefinition(MANAGED_LEAD_DEFINITION_NAME, {
35203
+ ...ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {},
35204
+ onWarning: (message) => notifyDefinitionWarning(ctx, message)
35205
+ });
33848
35206
  const verifyManagedLeadModelRestoration = async (ctx, signal) => {
33849
35207
  if (sessionKind?.kind !== "managed") return;
33850
35208
  coordinationRuntime.invalidateStartupCoordinationState(
@@ -34091,6 +35449,19 @@ function registerLeadRuntime(pi, options) {
34091
35449
  };
34092
35450
  const agentEvents = createLeadAgentEventRuntime({
34093
35451
  ...options.agentEventOptions,
35452
+ currentLeadAllowedTools: () => {
35453
+ if (sessionKind?.kind === "managed") {
35454
+ if (managedLifecycle !== "assigned" || leadExecutionPending || leadRuntime.roleSuspended || leadRuntime.chiefMode === "suspended" || !leadExecution?.valid || !leadExecution.managed)
35455
+ return executionTools();
35456
+ const policy2 = leadExecution.definition.frontmatter;
35457
+ return policy2.tools !== void 0 || (policy2.excludeTools?.length ?? 0) > 0 || policy2.noTools === true ? executionTools() : void 0;
35458
+ }
35459
+ if (activeLeadRole(leadRuntime) !== "lead" || leadRuntime.roleSuspended || !leadExecution || leadExecution.managed)
35460
+ return void 0;
35461
+ if (!leadExecution.valid) return executionTools();
35462
+ const policy = leadExecution.definition.frontmatter;
35463
+ return policy.tools !== void 0 || (policy.excludeTools?.length ?? 0) > 0 ? executionTools() : void 0;
35464
+ },
34094
35465
  executionPrompt: () => leadExecution && !leadExecution.managed && leadExecution.valid ? leadExecution.definition.body : void 0,
34095
35466
  leadInboxRuntime: inboxRuntime,
34096
35467
  herdRun: herdRunRuntime,
@@ -34113,9 +35484,10 @@ function registerLeadRuntime(pi, options) {
34113
35484
  discoverSessionDefinitions: async (ctx) => {
34114
35485
  let roleDefinitions = [];
34115
35486
  try {
34116
- roleDefinitions = discoverRoleDefinitions(
34117
- ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
34118
- );
35487
+ roleDefinitions = discoverRoleDefinitions({
35488
+ ...ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {},
35489
+ onWarning: (message) => notifyDefinitionWarning(ctx, message)
35490
+ });
34119
35491
  } catch (error2) {
34120
35492
  options.sessionStartOptions.appendDefinitionError(ctx, error2);
34121
35493
  }
@@ -34190,6 +35562,16 @@ function registerLeadRuntime(pi, options) {
34190
35562
  herdRun: herdRunRuntime
34191
35563
  });
34192
35564
  pi.on("turn_start", () => controller.resetAssignmentGuidance());
35565
+ registerRecipientFanIn(pi, async (ctx, phase, budget) => {
35566
+ if (isQuarantinedSession(ctx)) return 0;
35567
+ const agentNotifications = await controller.drainReadyOwnerNotifications(
35568
+ ctx,
35569
+ phase,
35570
+ budget
35571
+ );
35572
+ const inboxMessages = await inboxRuntime.drainBoundary(ctx, phase, budget);
35573
+ return agentNotifications + inboxMessages;
35574
+ });
34193
35575
  pi.on("before_agent_start", (event, ctx) => {
34194
35576
  if (!isQuarantinedSession(ctx))
34195
35577
  return agentEvents.beforeAgentStart(event, ctx);
@@ -34259,6 +35641,10 @@ This session belongs to a managed Agent restored without its authorized launch c
34259
35641
  inheritedProjection = void 0;
34260
35642
  return shutdown.shutdown(ctx);
34261
35643
  });
35644
+ getLocalActivity = observeLocalHeaderActivity(pi, () => {
35645
+ statusRuntime.invalidateWidget();
35646
+ invalidateSupervisionWidget();
35647
+ });
34262
35648
  return {
34263
35649
  roleTransitions,
34264
35650
  publishLeadRole,
@@ -34940,6 +36326,7 @@ function createLeadSupervisionRuntime(host) {
34940
36326
  let statusConfigError;
34941
36327
  let widgetFocusInFlight = false;
34942
36328
  let supervisionWidgetGeneration = 0;
36329
+ let managerHeaderGit;
34943
36330
  const gitSummaries = /* @__PURE__ */ new Map();
34944
36331
  let gitSampling;
34945
36332
  let gitLastAttemptAt = 0;
@@ -34950,6 +36337,7 @@ function createLeadSupervisionRuntime(host) {
34950
36337
  gitAbort = void 0;
34951
36338
  gitSampling = void 0;
34952
36339
  gitSummaries.clear();
36340
+ managerHeaderGit = void 0;
34953
36341
  if (resetRate) gitLastAttemptAt = 0;
34954
36342
  };
34955
36343
  const generation = (ctx) => [
@@ -34977,10 +36365,6 @@ function createLeadSupervisionRuntime(host) {
34977
36365
  const entries = host.managerSupervisionItems(value2).slice(0, statusWidgetMaxRows - 1).filter(
34978
36366
  (item) => item.kind === "work" && (item.work.status === "active" || item.work.status === "paused") && !!item.work.checkoutPath
34979
36367
  );
34980
- if (!entries.length) {
34981
- gitSummaries.clear();
34982
- return;
34983
- }
34984
36368
  gitLastAttemptAt = Date.now();
34985
36369
  const abort = new AbortController();
34986
36370
  gitAbort = abort;
@@ -34991,6 +36375,7 @@ function createLeadSupervisionRuntime(host) {
34991
36375
  overallTimeout.unref?.();
34992
36376
  const run2 = async () => {
34993
36377
  const next = /* @__PURE__ */ new Map();
36378
+ let headerSummary;
34994
36379
  const current = () => !abort.signal.aborted && uiContext === ctx && generation(ctx) === expectedGeneration && host.activeRole() === "manager" && !host.state.roleSuspended;
34995
36380
  const git = async (cwd, args) => {
34996
36381
  if (!current()) throw new Error("Git sampling cancelled");
@@ -35014,132 +36399,50 @@ function createLeadSupervisionRuntime(host) {
35014
36399
  managerCheckoutPath,
35015
36400
  host.state.managerLease.descriptor.repoKey
35016
36401
  )) {
35017
- if (current()) gitSummaries.clear();
36402
+ if (current()) {
36403
+ gitSummaries.clear();
36404
+ managerHeaderGit = void 0;
36405
+ }
35018
36406
  return;
35019
36407
  }
35020
36408
  let managerHead;
36409
+ try {
36410
+ const state = await readGitWorktreeState(git, managerCheckoutPath);
36411
+ if (state) {
36412
+ headerSummary = {
36413
+ dirty: state.dirty,
36414
+ checkedOutBranch: state.checkedOutBranch
36415
+ };
36416
+ managerHead = state.head;
36417
+ }
36418
+ } catch {
36419
+ }
35021
36420
  for (const item of entries) {
35022
36421
  if (!current()) return;
35023
36422
  if (item.kind !== "work") continue;
35024
36423
  const work = item.work;
35025
36424
  const checkoutPath = work.checkoutPath;
35026
36425
  try {
35027
- if (!await identity(
36426
+ const summary = await observeGitChangeSummary(
36427
+ git,
35028
36428
  checkoutPath,
35029
- host.state.managerLease.descriptor.repoKey
35030
- ))
35031
- continue;
35032
- const status2 = (await git(checkoutPath, [
35033
- "--no-optional-locks",
35034
- "status",
35035
- "--porcelain=v2",
35036
- "--branch",
35037
- "-z",
35038
- "--untracked-files=normal"
35039
- ])).split("\0");
35040
- let headerEnd = 0;
35041
- const headers = /* @__PURE__ */ new Map();
35042
- while (headerEnd < status2.length && status2[headerEnd]?.startsWith("# ")) {
35043
- const match = /^# (branch\.(?:head|oid)) (.*)$/u.exec(
35044
- status2[headerEnd]
35045
- );
35046
- if (match) headers.set(match[1], match[2]);
35047
- headerEnd++;
35048
- }
35049
- const leadHead = headers.get("branch.oid");
35050
- const branchHead = headers.get("branch.head");
35051
- if (!branchHead || !leadHead || !/^[0-9a-f]{40,64}$/iu.test(leadHead))
35052
- continue;
35053
- const checkedOutBranch = branchHead === "(detached)" ? "detached" : branchHead;
35054
- if (checkedOutBranch === "(unknown)" || !/^(?:detached|[^\s\0]+)$/u.test(checkedOutBranch))
35055
- continue;
35056
- const dirty = status2.slice(headerEnd).some((entry) => entry.length > 0);
35057
- let additions;
35058
- let deletions;
35059
- let changedFiles;
35060
- let comparisonSha;
35061
- try {
35062
- managerHead ??= (await git(managerCheckoutPath, [
35063
- "rev-parse",
35064
- "--verify",
35065
- "HEAD^{commit}"
35066
- ])).trim();
35067
- if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(managerHead)) {
35068
- const bases = (await git(checkoutPath, [
35069
- "merge-base",
35070
- "--all",
35071
- managerHead,
35072
- leadHead
35073
- ])).trim().split(/\s+/u);
35074
- if (bases.length === 1 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(bases[0]))
35075
- comparisonSha = bases[0];
36429
+ host.state.managerLease.descriptor.repoKey,
36430
+ async () => {
36431
+ managerHead ??= (await git(managerCheckoutPath, [
36432
+ "rev-parse",
36433
+ "--verify",
36434
+ "HEAD^{commit}"
36435
+ ])).trim();
36436
+ return managerHead;
35076
36437
  }
35077
- } catch {
35078
- }
35079
- if (comparisonSha) {
35080
- try {
35081
- const output = await git(checkoutPath, [
35082
- "--no-optional-locks",
35083
- "diff",
35084
- "--numstat",
35085
- "-z",
35086
- "--find-renames",
35087
- comparisonSha,
35088
- "--"
35089
- ]);
35090
- const records = output.split("\0");
35091
- let valid2 = output === "" || output.endsWith("\0");
35092
- if (valid2) records.pop();
35093
- let added = 0, deleted = 0, files = 0;
35094
- for (let i = 0; valid2 && i < records.length; ) {
35095
- const match = /^(\d+|-)\t(\d+|-)\t(.*)$/su.exec(
35096
- records[i++]
35097
- );
35098
- if (!match) {
35099
- valid2 = false;
35100
- break;
35101
- }
35102
- const [, a, d, path] = match;
35103
- if (!path && (!records[i++] || !records[i++])) {
35104
- valid2 = false;
35105
- break;
35106
- }
35107
- if (a === "-" && d === "-") {
35108
- files++;
35109
- continue;
35110
- }
35111
- if (!/^\d+$/u.test(a) || !/^\d+$/u.test(d)) {
35112
- valid2 = false;
35113
- break;
35114
- }
35115
- added += Number(a);
35116
- deleted += Number(d);
35117
- files++;
35118
- if (!Number.isSafeInteger(added) || !Number.isSafeInteger(deleted)) {
35119
- valid2 = false;
35120
- break;
35121
- }
35122
- }
35123
- if (valid2) {
35124
- additions = added;
35125
- deletions = deleted;
35126
- changedFiles = files;
35127
- }
35128
- } catch {
35129
- }
35130
- }
36438
+ );
36439
+ if (!summary) continue;
35131
36440
  next.set(work.session, {
35132
36441
  generation: expectedGeneration,
35133
36442
  checkoutPath,
35134
36443
  branch: work.branch,
35135
36444
  managerCheckoutPath,
35136
- summary: {
35137
- dirty,
35138
- additions,
35139
- deletions,
35140
- changedFiles,
35141
- checkedOutBranch
35142
- }
36445
+ summary
35143
36446
  });
35144
36447
  } catch {
35145
36448
  }
@@ -35147,9 +36450,18 @@ function createLeadSupervisionRuntime(host) {
35147
36450
  if (!current()) return;
35148
36451
  gitSummaries.clear();
35149
36452
  for (const [session, result] of next) gitSummaries.set(session, result);
36453
+ managerHeaderGit = headerSummary ? {
36454
+ generation: expectedGeneration,
36455
+ checkoutPath: managerCheckoutPath,
36456
+ repoKey: host.state.managerLease.descriptor.repoKey,
36457
+ summary: headerSummary
36458
+ } : void 0;
35150
36459
  renderWidget?.();
35151
36460
  } catch {
35152
- if (current()) gitSummaries.clear();
36461
+ if (current()) {
36462
+ gitSummaries.clear();
36463
+ managerHeaderGit = void 0;
36464
+ }
35153
36465
  }
35154
36466
  };
35155
36467
  const sampling = run2().finally(() => {
@@ -35778,6 +37090,79 @@ Origin: ${"sourceAssignmentId" in entry ? `project assignment ${entry.sourceAssi
35778
37090
  if (!isCurrent()) return;
35779
37091
  const contextStatus = status(ctx);
35780
37092
  const targets = /* @__PURE__ */ new Map();
37093
+ let git;
37094
+ if (host.activeRole() === "manager" && contextStatus === "fresh" && snapshot && "managerCheckoutPath" in snapshot && snapshot.managerCheckoutPath && "work" in snapshot) {
37095
+ try {
37096
+ const checkout = snapshot.managerCheckoutPath;
37097
+ const common = await host.pi.exec(
37098
+ "git",
37099
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
37100
+ { cwd: checkout, signal: ctx.signal, timeout: 3e3 }
37101
+ );
37102
+ const managerAuthority = await host.currentManager(ctx);
37103
+ if (common.code === 0 && !common.killed && !common.stderr?.trim() && managerAuthority && sameDirectory(
37104
+ String(common.stdout ?? "").trim(),
37105
+ managerAuthority.repoKey
37106
+ )) {
37107
+ const sessionRootResult = ctx.cwd ? await host.pi.exec("git", ["rev-parse", "--show-toplevel"], {
37108
+ cwd: ctx.cwd,
37109
+ signal: ctx.signal,
37110
+ timeout: 3e3
37111
+ }) : void 0;
37112
+ const sessionRoot = sessionRootResult?.code === 0 && !sessionRootResult.killed && !sessionRootResult.stderr?.trim() ? String(sessionRootResult.stdout ?? "").trim() : void 0;
37113
+ const result = await host.pi.exec(
37114
+ "git",
37115
+ ["worktree", "list", "--porcelain", "-z"],
37116
+ { cwd: checkout, signal: ctx.signal, timeout: 3e3 }
37117
+ );
37118
+ const inventory = result.code === 0 && !result.killed && !result.stderr?.trim() ? parseGitWorktreeInventory(String(result.stdout ?? "")) : void 0;
37119
+ const observation = (path) => {
37120
+ const matches = inventory?.filter(
37121
+ (entry2) => !entry2.prunable && sameDirectory(entry2.path, path)
37122
+ ) ?? [];
37123
+ const entry = matches.length === 1 ? matches[0] : void 0;
37124
+ return entry?.head && (entry.detached || entry.branch) ? {
37125
+ branch: entry.detached ? null : entry.branch,
37126
+ head: entry.head
37127
+ } : void 0;
37128
+ };
37129
+ const manager = observation(checkout);
37130
+ const managerSessionObservation = sessionRoot ? observation(sessionRoot) : void 0;
37131
+ const managerSession = sessionRoot && managerSessionObservation ? {
37132
+ cwd: ctx.cwd,
37133
+ worktreeRoot: sessionRoot,
37134
+ ...managerSessionObservation
37135
+ } : void 0;
37136
+ if (manager) {
37137
+ const assignments = /* @__PURE__ */ new Map();
37138
+ const supervisedLeads = /* @__PURE__ */ new Map();
37139
+ for (const work of snapshot.work ?? [])
37140
+ if (work.checkoutPath) {
37141
+ const observed = observation(work.checkoutPath);
37142
+ if (observed) assignments.set(work.branch, observed);
37143
+ }
37144
+ if ("openWorkspaces" in snapshot)
37145
+ for (const lead of snapshot.leads ?? []) {
37146
+ if (lead.relationship !== "supervised") continue;
37147
+ const workspaces = snapshot.openWorkspaces?.filter(
37148
+ (workspace2) => workspace2.workspaceId === lead.workspaceId
37149
+ ) ?? [];
37150
+ if (workspaces.length !== 1) continue;
37151
+ const observed = observation(workspaces[0].path);
37152
+ if (observed) supervisedLeads.set(lead.lead, observed);
37153
+ }
37154
+ git = {
37155
+ manager,
37156
+ ...managerSession ? { managerSession } : {},
37157
+ assignments,
37158
+ supervisedLeads
37159
+ };
37160
+ }
37161
+ }
37162
+ } catch {
37163
+ }
37164
+ }
37165
+ if (!isCurrent()) return;
35781
37166
  const candidates = [];
35782
37167
  if (contextStatus !== "unavailable" && snapshot) {
35783
37168
  for (const report of host.presentationReports(snapshot)) {
@@ -35797,7 +37182,8 @@ Origin: ${"sourceAssignmentId" in entry ? `project assignment ${entry.sourceAssi
35797
37182
  {
35798
37183
  status: contextStatus,
35799
37184
  role: host.activeRole() === "manager" ? "manager" : "chief",
35800
- targets
37185
+ targets,
37186
+ ...git ? { git } : {}
35801
37187
  }
35802
37188
  );
35803
37189
  for (const candidate of candidates)
@@ -35829,6 +37215,7 @@ Origin: ${"sourceAssignmentId" in entry ? `project assignment ${entry.sourceAssi
35829
37215
  widgetFocusInFlight = false;
35830
37216
  ctx.ui.setWidget("pi-herdsman-staff", (tui, theme) => {
35831
37217
  renderWidget = () => tui.requestRender();
37218
+ host.onActivityChange?.(() => renderWidget?.());
35832
37219
  return createSupervisionWidget(
35833
37220
  () => snapshot,
35834
37221
  () => status(ctx),
@@ -35886,7 +37273,14 @@ Origin: ${"sourceAssignmentId" in entry ? `project assignment ${entry.sourceAssi
35886
37273
  });
35887
37274
  }
35888
37275
  },
35889
- () => statusWidgetMaxRows
37276
+ () => statusWidgetMaxRows,
37277
+ () => {
37278
+ const cached = managerHeaderGit;
37279
+ const currentSnapshot = isProjectSnapshot(snapshot) ? snapshot : void 0;
37280
+ const lease = host.state.managerLease;
37281
+ return cached && host.activeRole() === "manager" && status(ctx) === "fresh" && currentSnapshot?.managerCheckoutPath && cached.generation === generation(ctx) && cached.checkoutPath === currentSnapshot.managerCheckoutPath && cached.repoKey === lease?.descriptor.repoKey ? cached.summary : void 0;
37282
+ },
37283
+ () => host.getLocalActivity?.(ctx) ?? "unknown"
35890
37284
  );
35891
37285
  });
35892
37286
  } catch {
@@ -36584,6 +37978,7 @@ function createLeadInboxRuntime(host) {
36584
37978
  let remoteReconciliationInFlight = false;
36585
37979
  let currentSubmittedAt;
36586
37980
  let settledSubmissions = /* @__PURE__ */ new Set();
37981
+ let runBoundaryDrain;
36587
37982
  const chiefStartPreflights = [];
36588
37983
  const {
36589
37984
  leadRuntime,
@@ -36981,6 +38376,7 @@ function createLeadInboxRuntime(host) {
36981
38376
  }
36982
38377
  };
36983
38378
  const startChiefInbox = (ctx) => {
38379
+ runBoundaryDrain = void 0;
36984
38380
  const generation = ++chiefInboxGeneration;
36985
38381
  const socket = process.env.HERDR_SOCKET_PATH;
36986
38382
  if (!socket) return;
@@ -37011,7 +38407,7 @@ function createLeadInboxRuntime(host) {
37011
38407
  if (transaction.role === "inactive" && activeRole() !== "manager")
37012
38408
  assertCurrentLeadCoordination(ctx);
37013
38409
  };
37014
- const inboxOptions = (verifyLease, inboxRuntime = runtime) => {
38410
+ const inboxOptions = (verifyLease, inboxRuntime = runtime, phase, budget) => {
37015
38411
  if (!isCurrent()) throw new Error("Stale inbox transaction (options)");
37016
38412
  return {
37017
38413
  runtime: inboxRuntime,
@@ -37030,6 +38426,13 @@ function createLeadInboxRuntime(host) {
37030
38426
  return void 0;
37031
38427
  }
37032
38428
  const role2 = activeRole();
38429
+ if (phase === "turn") {
38430
+ if (role2 === "lead" && record.kind === "manager_message" && await authorizeChiefRecord(record, ctx))
38431
+ return "steer";
38432
+ if ((role2 === "lead" || role2 === "manager") && record.kind === "chief_message")
38433
+ return "steer";
38434
+ return void 0;
38435
+ }
37033
38436
  if (role2 === "lead" && record.kind === "manager_message") {
37034
38437
  let authorized;
37035
38438
  try {
@@ -37038,11 +38441,15 @@ function createLeadInboxRuntime(host) {
37038
38441
  return void 0;
37039
38442
  }
37040
38443
  if (!authorized) return "followUp";
38444
+ if (!phase && !ctx.isIdle()) return void 0;
37041
38445
  return "steer";
37042
38446
  }
37043
38447
  const supervisorDownlink = role2 === "lead" && record.kind === "chief_message" || role2 === "manager" && record.kind === "chief_message";
37044
- if (supervisorDownlink) return "steer";
37045
- return ctx.isIdle() ? "followUp" : void 0;
38448
+ if (supervisorDownlink && phase !== "settle") {
38449
+ if (!phase && !ctx.isIdle()) return void 0;
38450
+ return "steer";
38451
+ }
38452
+ return phase === "settle" || phase === "startup" || ctx.isIdle() ? "followUp" : void 0;
37046
38453
  },
37047
38454
  senderTarget: (record) => {
37048
38455
  if (record.kind === "peer_message") {
@@ -37104,6 +38511,7 @@ function createLeadInboxRuntime(host) {
37104
38511
  }
37105
38512
  },
37106
38513
  sendMessage: async (message, options, record) => {
38514
+ let reservedContent;
37107
38515
  const projectAssignment = typeof message === "object" && message !== null && "customType" in message && message.customType === "pi-herdsman-project_assignment";
37108
38516
  try {
37109
38517
  let payload = message;
@@ -37173,6 +38581,14 @@ function createLeadInboxRuntime(host) {
37173
38581
  if (messageDelivered(ctx, record)) return;
37174
38582
  if (record.kind === "peer_message" && !await authorizePeerRecord(record, ctx))
37175
38583
  throw new Error("Peer eligibility changed before delivery");
38584
+ if (phase) options = { ...options, triggerTurn: false };
38585
+ const reservePayload = () => {
38586
+ if (!phase || !budget || typeof payload.content !== "string")
38587
+ return;
38588
+ if (!includeFanInMessage(budget, payload.content))
38589
+ throw new Error("Recipient fan-in budget exhausted");
38590
+ reservedContent = payload.content;
38591
+ };
37176
38592
  let result;
37177
38593
  try {
37178
38594
  if (record.kind === "peer_message") {
@@ -37218,6 +38634,7 @@ function createLeadInboxRuntime(host) {
37218
38634
  if (!current || !samePeerLeadAuthority(current, recipient) || current.group?.repoKey !== recipient.group?.repoKey || current.group?.primaryWorkspaceId !== recipient.group?.primaryWorkspaceId || !contextCurrent || (remoteOrdinarySource ? recipientContext.role !== "lead" || !snapshot || !isRemoteOrdinaryLead(current, snapshot) : !localSource || !canMessagePeer(localSource, recipientContext)))
37219
38635
  throw new Error("Peer eligibility changed before delivery");
37220
38636
  importResultBindings2(pi, ctx, resultBindings, record.kind);
38637
+ reservePayload();
37221
38638
  submitted = pi.sendMessage(payload, options);
37222
38639
  };
37223
38640
  if (source.role === "manager" && recipientContext.role === "manager")
@@ -37226,6 +38643,7 @@ function createLeadInboxRuntime(host) {
37226
38643
  result = submitted;
37227
38644
  } else {
37228
38645
  importResultBindings2(pi, ctx, resultBindings, record.kind);
38646
+ reservePayload();
37229
38647
  result = pi.sendMessage(payload, options);
37230
38648
  }
37231
38649
  } catch (error2) {
@@ -37253,6 +38671,8 @@ function createLeadInboxRuntime(host) {
37253
38671
  }
37254
38672
  return;
37255
38673
  } catch (error2) {
38674
+ if (reservedContent && budget)
38675
+ releaseFanInMessage(budget, reservedContent);
37256
38676
  managerDiagnostic("inbox_catch", { category: "send" });
37257
38677
  if (projectAssignment)
37258
38678
  managerDiagnostic("project_assignment_send", {
@@ -37264,6 +38684,8 @@ function createLeadInboxRuntime(host) {
37264
38684
  },
37265
38685
  transaction: {
37266
38686
  begin: (record) => {
38687
+ if (transactions.has(record.id))
38688
+ throw new Error("Inbox record already has an active drain");
37267
38689
  const token = {
37268
38690
  id: record.id,
37269
38691
  record,
@@ -37276,9 +38698,9 @@ function createLeadInboxRuntime(host) {
37276
38698
  transactions.set(record.id, token);
37277
38699
  return token;
37278
38700
  },
37279
- revalidate: (token, phase) => {
38701
+ revalidate: (token, phase2) => {
37280
38702
  try {
37281
- revalidateTransaction(token, phase);
38703
+ revalidateTransaction(token, phase2);
37282
38704
  } catch (error2) {
37283
38705
  managerDiagnostic("inbox_catch", { category: "transaction" });
37284
38706
  throw error2;
@@ -37291,6 +38713,8 @@ function createLeadInboxRuntime(host) {
37291
38713
  }
37292
38714
  }
37293
38715
  },
38716
+ forceNonTriggering: !!phase,
38717
+ maxDeliveries: budget ? Math.max(0, COORDINATION_INBOX_SCAN_LIMIT - budget.count) : void 0,
37294
38718
  accepted: async (record) => {
37295
38719
  if (record.kind === "peer_message")
37296
38720
  writePeerDeliveryReceipt(peerInboxRuntime, record);
@@ -37309,7 +38733,7 @@ function createLeadInboxRuntime(host) {
37309
38733
  }
37310
38734
  };
37311
38735
  };
37312
- const drainInbox = async (initial = false) => {
38736
+ const drainInbox = async (initial = false, phase, budget) => {
37313
38737
  if (initial) managerDiagnostic("initial_inbox_drain_start");
37314
38738
  const sessionId = ctx.sessionManager.getSessionId();
37315
38739
  const complete = (count) => {
@@ -37322,7 +38746,8 @@ function createLeadInboxRuntime(host) {
37322
38746
  const held = chiefStartPreflightHeld(ctx);
37323
38747
  managerDiagnostic("inbox_preflight", { reason: held ? "held" : "pass" });
37324
38748
  if (held) return complete(0);
37325
- if ((leadRuntime.chiefMode === "active" || activeRole() === "manager") && ctx.isIdle() && listChiefMessagePaths2(runtime, sessionId).some(
38749
+ if (!phase && ctx.isIdle()) host.beginProjectMessageStartup?.(ctx);
38750
+ if (!phase && (leadRuntime.chiefMode === "active" || activeRole() === "manager") && ctx.isIdle() && listChiefMessagePaths2(runtime, sessionId).some(
37326
38751
  (path) => !chiefMessageQuarantined2(
37327
38752
  runtime,
37328
38753
  sessionId,
@@ -37352,27 +38777,38 @@ function createLeadInboxRuntime(host) {
37352
38777
  }
37353
38778
  }
37354
38779
  if (initial) {
37355
- const chief2 = await drainCoordinationInbox2(inboxOptions(false));
38780
+ const chief2 = await drainCoordinationInbox2(
38781
+ inboxOptions(false, runtime, phase, budget)
38782
+ );
37356
38783
  const peerPresent2 = await currentPeerPresenceValid(ctx);
37357
38784
  managerDiagnostic("inbox_peer_presence", {
37358
38785
  reason: peerPresent2 ? "pass" : "missing"
37359
38786
  });
37360
38787
  const peer2 = await drainCoordinationInbox2(
37361
- inboxOptions(false, peerInboxRuntime)
38788
+ inboxOptions(false, peerInboxRuntime, phase, budget)
38789
+ );
38790
+ const project2 = await drainProjectMessages(
38791
+ ctx,
38792
+ phase ?? "idle",
38793
+ budget
37362
38794
  );
37363
- return complete(chief2 + peer2 + await drainProjectMessages(ctx));
38795
+ return complete(phase ? budget?.count ?? 0 : chief2 + peer2 + project2);
37364
38796
  }
37365
38797
  const active = leadRuntime.chiefMode === "active" || activeRole() === "manager";
37366
- const chief = await drainCoordinationInbox2(inboxOptions(active));
38798
+ const chief = await drainCoordinationInbox2(
38799
+ inboxOptions(active, runtime, phase, budget)
38800
+ );
37367
38801
  const peerPresent = await currentPeerPresenceValid(ctx);
37368
38802
  managerDiagnostic("inbox_peer_presence", {
37369
38803
  reason: peerPresent ? "pass" : "missing"
37370
38804
  });
37371
38805
  const peer = await drainCoordinationInbox2(
37372
- inboxOptions(active, peerInboxRuntime)
38806
+ inboxOptions(active, peerInboxRuntime, phase, budget)
37373
38807
  );
37374
- return complete(chief + peer + await drainProjectMessages(ctx));
38808
+ const project = await drainProjectMessages(ctx, phase ?? "idle", budget);
38809
+ return complete(phase ? budget?.count ?? 0 : chief + peer + project);
37375
38810
  };
38811
+ runBoundaryDrain = (boundaryCtx, phase, budget) => boundaryCtx.sessionManager.getSessionId() === ctx.sessionManager.getSessionId() ? drainInbox(false, phase, budget) : Promise.resolve(0);
37376
38812
  const schedule = () => {
37377
38813
  if (generation !== chiefInboxGeneration || chiefInboxAbortController?.signal.aborted)
37378
38814
  return;
@@ -37416,6 +38852,7 @@ function createLeadInboxRuntime(host) {
37416
38852
  };
37417
38853
  return {
37418
38854
  start: startChiefInbox,
38855
+ drainBoundary: (ctx, phase, budget) => runBoundaryDrain?.(ctx, phase, budget) ?? Promise.resolve(0),
37419
38856
  cleanupManagedPeerInbox,
37420
38857
  isStartPreflightHeld: chiefStartPreflightHeld,
37421
38858
  clearStartPreflight,
@@ -37804,6 +39241,7 @@ function createLeadRoleTransitions(state, host) {
37804
39241
  }
37805
39242
  };
37806
39243
  const publishProjectMessage = async (ctx, assignment, message, files = [], operation = "message_supervisor", reportId, kind, signal) => {
39244
+ const senderEnvironment = await captureSenderEnvironment(host.pi, ctx);
37807
39245
  const sessionId = ctx.sessionManager.getSessionId();
37808
39246
  const runtime = host.supervisionRuntime();
37809
39247
  const current = host.readProjectAssignment(
@@ -37828,6 +39266,7 @@ function createLeadRoleTransitions(state, host) {
37828
39266
  fromSessionId: sessionId,
37829
39267
  text: candidate,
37830
39268
  ...kind ? { kind } : {},
39269
+ ...senderEnvironment ? { senderEnvironment } : {},
37831
39270
  ...resultBindings.length ? { resultBindings: [...resultBindings] } : {},
37832
39271
  createdAt
37833
39272
  })
@@ -37840,6 +39279,7 @@ function createLeadRoleTransitions(state, host) {
37840
39279
  fromSessionId: sessionId,
37841
39280
  text: prepared.text,
37842
39281
  ...kind ? { kind } : {},
39282
+ ...senderEnvironment ? { senderEnvironment } : {},
37843
39283
  ...prepared.resultBindings.length ? { resultBindings: prepared.resultBindings } : {},
37844
39284
  createdAt
37845
39285
  };
@@ -38631,7 +40071,7 @@ function createLeadRoleTransitions(state, host) {
38631
40071
  return void 0;
38632
40072
  };
38633
40073
  const bootstrapLock = host.acquireProcessLock(
38634
- join12(
40074
+ join13(
38635
40075
  herdsmanTempRoot(),
38636
40076
  "locks",
38637
40077
  `manager-bootstrap-${createHash14("sha256").update(target).digest("hex")}`
@@ -39056,6 +40496,10 @@ function createLeadRoleTransitions(state, host) {
39056
40496
  }
39057
40497
  if (state.roleSuspended || state.chiefMode === "suspended") {
39058
40498
  host.setInheritedProjection?.(void 0);
40499
+ if (host.isManagedSession?.()) {
40500
+ host.pi.setActiveTools(host.executionTools?.() ?? []);
40501
+ return;
40502
+ }
39059
40503
  const baseline = host.normalizeBaseTools(
39060
40504
  host.getLeadTools() ?? host.pi.getActiveTools()
39061
40505
  );
@@ -39776,7 +41220,9 @@ If needed, install the Pi integration once:
39776
41220
  }
39777
41221
  ),
39778
41222
  workspaceId: () => process.env.PI_HERDSMAN_WORKSPACE_ID ?? process.env.HERDR_WORKSPACE_ID,
39779
- sendResultMessage: (ctx, _runtime, _result, content, details) => {
41223
+ sendResultMessage: (ctx, _runtime, _result, content, details, triggerTurn = true) => {
41224
+ if (triggerTurn && !ctx.isIdle())
41225
+ throw new Error("Agent result owner is no longer idle");
39780
41226
  pi.sendMessage(
39781
41227
  {
39782
41228
  customType: "pi-herdsman-agent-result",
@@ -39784,10 +41230,15 @@ If needed, install the Pi integration once:
39784
41230
  display: true,
39785
41231
  details
39786
41232
  },
39787
- { triggerTurn: true, deliverAs: "steer" }
41233
+ {
41234
+ triggerTurn,
41235
+ ...triggerTurn ? { deliverAs: "steer" } : {}
41236
+ }
39788
41237
  );
39789
41238
  },
39790
- sendAskMessage: (_ctx, ask) => {
41239
+ sendAskMessage: (ctx, ask, triggerTurn = true) => {
41240
+ if (triggerTurn && !ctx.isIdle())
41241
+ throw new Error("Agent ask owner is no longer idle");
39791
41242
  pi.sendMessage(
39792
41243
  {
39793
41244
  customType: "pi-herdsman-agent-ask",
@@ -39808,7 +41259,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
39808
41259
  piSessionId: ask.piSessionId
39809
41260
  }
39810
41261
  },
39811
- { triggerTurn: true }
41262
+ { triggerTurn }
39812
41263
  );
39813
41264
  },
39814
41265
  sessionRetired: (ctx, runtime) => {
@@ -40591,7 +42042,7 @@ ${summary}`,
40591
42042
  supervisorTool = {
40592
42043
  name: "message_supervisor",
40593
42044
  label: "message supervisor",
40594
- exposure: "model-only",
42045
+ exposure: "direct",
40595
42046
  promptSnippet: "Send nonblocking material coordination to your direct supervisor",
40596
42047
  description: "Send a nonblocking question, clarification, warning, risk, decision, scope change, or evidence only when it is material or needed by your direct supervisor. Avoid unsolicited routine progress updates and duplicate result announcements.",
40597
42048
  executionMode: "sequential",
@@ -40610,7 +42061,7 @@ ${summary}`,
40610
42061
  peerTool = {
40611
42062
  name: "message_peer",
40612
42063
  label: "message peer",
40613
- exposure: "model-only",
42064
+ exposure: "direct",
40614
42065
  promptSnippet: "Discover same-role peers, including remote ordinary Leads, and reply through existing correspondences",
40615
42066
  description: "Send task-relevant communication needed by another eligible coordinator, not routine broadcasts or gratuitous acknowledgments. Send to an eligible same-role Lead or Manager using its stable target. Ordinary Leads and Managers may discover eligible same-role peers on reachable saved Herdr machines; remote Leads must be ordinary and unassigned. An existing return correspondence may allow a reply-only target without independent discovery or current availability. Use only the exact target from list_peers; optional name/workspace labels are advisory display context.",
40616
42067
  executionMode: "sequential",
@@ -40626,7 +42077,7 @@ ${summary}`,
40626
42077
  name: "message_staff",
40627
42078
  label: "message staff",
40628
42079
  defaultActive: false,
40629
- exposure: "model-only",
42080
+ exposure: "direct",
40630
42081
  promptSnippet: "Supervise direct reports; Managers may delegate new linked-worktree Leads",
40631
42082
  executionMode: "sequential",
40632
42083
  parameters: staffMessageParameters,
@@ -40768,7 +42219,7 @@ ${summary}`,
40768
42219
  ...staffTool,
40769
42220
  name: "integrate_branch",
40770
42221
  label: "integrate branch",
40771
- 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.",
42222
+ description: "Integrate an assigned local branch into the verified primary branch using fast-forward Git, or a clean divergent merge when explicitly authorized. Supply the exact full source SHA accepted after validation. New integration requires a matching completed Lead handoff for that revision and no unresolved assigned execution; a visible SHA, idle status, or interim supervisor message is insufficient. If the handoff is missing or stale, wait for the normal completion handoff or request a fresh completion report; do not poll staff or integration tools. A completed handoff is not proof that tests passed or that the work is acceptable. A divergent merge may create a merge commit; actual conflicts are distinguished from divergent ancestry. Merge preflight failure/conflict occurs before stopping the Lead. If a later step fails after execution stops, it is not automatically restarted. Git integration does not prove tests or semantic acceptance. Verified integration triggers separately guarded cleanup; integration and cleanup can complete separately, so do not treat integration alone as full finalization. An already-integrated accepted SHA follows the existing guarded cleanup-recovery path.",
40772
42223
  parameters: Type3.Object(
40773
42224
  {
40774
42225
  branch: Type3.String({
@@ -41080,7 +42531,7 @@ ${summary}`,
41080
42531
  pi.registerTool({
41081
42532
  name: "read_evidence",
41082
42533
  label: "Read accepted evidence",
41083
- exposure: "model-only",
42534
+ exposure: "direct",
41084
42535
  description: "Read a bounded page from evidence accepted by this managed Agent.",
41085
42536
  parameters: Type3.Object(
41086
42537
  {