pi-herdsman 0.43.0 → 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
@@ -2490,6 +2490,12 @@ function configuredToolPolicy(definition, requiredTools) {
2490
2490
  excluded
2491
2491
  };
2492
2492
  }
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
+ }
2493
2499
  function readOptionalAgentDefinitions(root2, category, onWarning) {
2494
2500
  const stats = statSync3(root2, { throwIfNoEntry: false });
2495
2501
  if (!stats) return [];
@@ -6151,6 +6157,8 @@ async function drainCoordinationInbox(options) {
6151
6157
  let delivered = 0;
6152
6158
  let examined = 0;
6153
6159
  for (const path of allChiefMessagePaths(options.runtime, options.sessionId)) {
6160
+ if (options.maxDeliveries !== void 0 && delivered >= options.maxDeliveries)
6161
+ break;
6154
6162
  if (examined >= COORDINATION_INBOX_SCAN_LIMIT) break;
6155
6163
  if (options.signal?.aborted) break;
6156
6164
  const id = basename5(path, ".json");
@@ -6322,7 +6330,7 @@ async function drainCoordinationInbox(options) {
6322
6330
  },
6323
6331
  {
6324
6332
  deliverAs: deliverAs ?? "followUp",
6325
- triggerTurn: record.kind !== "project_assignment" || !hasResumeInstruction
6333
+ triggerTurn: options.forceNonTriggering ? false : record.kind !== "project_assignment" || !hasResumeInstruction
6326
6334
  },
6327
6335
  record
6328
6336
  );
@@ -7504,7 +7512,7 @@ function writeProjectMessageUnlocked(record, runtime) {
7504
7512
  }
7505
7513
  if (cleanupFailed) throw cleanupError;
7506
7514
  }
7507
- function listProjectMessageHeaders(runtime, repoKey, branch) {
7515
+ function listProjectMessageHeaders(runtime, repoKey, branch, onReadError) {
7508
7516
  const directory2 = projectMessageDirectory(runtime, repoKey, branch);
7509
7517
  let entries;
7510
7518
  try {
@@ -7524,6 +7532,10 @@ function listProjectMessageHeaders(runtime, repoKey, branch) {
7524
7532
  } catch (error2) {
7525
7533
  if (error2 instanceof Error && error2.cause?.code === "ENOENT")
7526
7534
  return [];
7535
+ if (onReadError) {
7536
+ onReadError(error2);
7537
+ return [];
7538
+ }
7527
7539
  throw error2;
7528
7540
  }
7529
7541
  }).sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
@@ -8072,6 +8084,46 @@ var init_supervision = __esm({
8072
8084
  }
8073
8085
  });
8074
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
+
8075
8127
  // extension/presentation.ts
8076
8128
  import {
8077
8129
  DynamicBorder,
@@ -13845,7 +13897,12 @@ function createAgentStatusRuntime() {
13845
13897
  statusRefresh = false;
13846
13898
  statusInFlight = false;
13847
13899
  onStatusChange = void 0;
13848
- presentedStatus = { agents: [], stale: false, unavailable: true };
13900
+ lastValidStatus = {
13901
+ agents: [],
13902
+ stale: false,
13903
+ unavailable: true
13904
+ };
13905
+ presentedStatus = lastValidStatus;
13849
13906
  },
13850
13907
  prepareSession: (ctx, beforeActivate) => {
13851
13908
  clearTimer();
@@ -17723,7 +17780,7 @@ function createAgentController(pi, options) {
17723
17780
  const path = join9(runtime.mailboxPath, filename);
17724
17781
  stopResultWatcher(runtime, requestId);
17725
17782
  const check = () => {
17726
- if (active && runtimes.get(runtime.label) === runtime)
17783
+ if (active && context.isIdle() && runtimes.get(runtime.label) === runtime)
17727
17784
  try {
17728
17785
  const result = readResult(runtime.mailboxPath, requestId);
17729
17786
  if (result) void deliverResult(runtime, context, result, signal);
@@ -17744,6 +17801,7 @@ function createAgentController(pi, options) {
17744
17801
  stopAskWatcher(runtime);
17745
17802
  const check = () => {
17746
17803
  if (!active || runtimes.get(runtime.label) !== runtime) return;
17804
+ if (!context.isIdle()) return;
17747
17805
  try {
17748
17806
  deliverPendingAsk(runtime, context, signal);
17749
17807
  } catch (error2) {
@@ -18000,9 +18058,9 @@ function createAgentController(pi, options) {
18000
18058
  }, 250)
18001
18059
  );
18002
18060
  };
18003
- const deliverPendingAsk = (runtime, context, signal) => {
18061
+ const deliverPendingAsk = (runtime, context, signal, triggerTurn = true, budget) => {
18004
18062
  const state = readAgentState(runtime.mailboxPath);
18005
- if (!state?.pendingAskId) return;
18063
+ if (!state?.pendingAskId) return false;
18006
18064
  try {
18007
18065
  requireCompatibleBuild(
18008
18066
  options.build,
@@ -18022,27 +18080,37 @@ function createAgentController(pi, options) {
18022
18080
  options.onChanged();
18023
18081
  }
18024
18082
  const ask = readPendingAsk(runtime.mailboxPath, state);
18025
- 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.`;
18026
18089
  const key = `${runtime.mailboxPath}:${ask.askId}`;
18027
- if (askDeliveryInFlight.has(key)) return;
18090
+ if (askDeliveryInFlight.has(key)) return false;
18028
18091
  askDeliveryInFlight.add(key);
18029
18092
  try {
18030
- 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)
18031
- 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;
18032
18095
  const delivered = hasDeliveredAsk(
18033
18096
  context.sessionManager.getBranch(),
18034
18097
  ask
18035
18098
  );
18036
18099
  if (!delivered) {
18100
+ if (budget && !includeFanInMessage({ ...budget }, content))
18101
+ return false;
18037
18102
  importResultBindings(pi, context, ask.resultBindings, "ask_owner");
18038
- options.sendAskMessage(context, ask);
18103
+ options.sendAskMessage(context, ask, triggerTurn);
18104
+ if (budget) includeFanInMessage(budget, content);
18039
18105
  }
18040
18106
  cancelAskRetry(runtime, ask.askId);
18041
18107
  clearCleanupError(runtime, "Ask delivery failed");
18108
+ return !delivered;
18042
18109
  } catch (error2) {
18043
18110
  if (error2 instanceof OperationError && error2.detail.category === "incompatible_build")
18044
- return;
18111
+ return false;
18045
18112
  scheduleAskRetry(runtime, context, ask, signal, error2);
18113
+ return false;
18046
18114
  } finally {
18047
18115
  askDeliveryInFlight.delete(key);
18048
18116
  }
@@ -18161,6 +18229,7 @@ function createAgentController(pi, options) {
18161
18229
  setTimeout(() => {
18162
18230
  resultDeliveryRetries.delete(key);
18163
18231
  if (!active || runtimes.get(runtime.label) !== runtime) return;
18232
+ if (!context.isIdle()) return;
18164
18233
  try {
18165
18234
  const current = readResult(runtime.mailboxPath, result.requestId);
18166
18235
  if (current) void deliverResult(runtime, context, current, signal);
@@ -18182,16 +18251,17 @@ function createAgentController(pi, options) {
18182
18251
  if (timer) clearTimeout(timer);
18183
18252
  map.delete(key);
18184
18253
  };
18185
- const deliverResult = async (runtime, context, result, signal) => {
18186
- if (!active) return;
18254
+ const deliverResult = async (runtime, context, result, signal, triggerTurn = true, budget) => {
18255
+ if (!active) return false;
18187
18256
  const key = `${runtime.mailboxPath}:${result.requestId}`;
18188
- if (resultDeliveryInFlight.has(key)) return;
18257
+ if (resultDeliveryInFlight.has(key)) return false;
18189
18258
  resultDeliveryInFlight.add(key);
18259
+ let submitted = false;
18190
18260
  try {
18191
18261
  const expected = resultIdentity(runtime, result.requestId);
18192
18262
  const persistedState = readAgentState(runtime.mailboxPath);
18193
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);
18194
- if (identityMismatch) return;
18264
+ if (identityMismatch) return false;
18195
18265
  let entries = context.sessionManager.getEntries();
18196
18266
  const evidenceKey = JSON.stringify(Object.values(expected));
18197
18267
  if (!hasDeliveredResult(entries, expected) && !resultDeliveryEvidence.has(evidenceKey)) {
@@ -18301,10 +18371,21 @@ function createAgentController(pi, options) {
18301
18371
  } : {},
18302
18372
  error: result.error
18303
18373
  };
18304
- 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;
18305
18386
  resultDeliveryEvidence.add(evidenceKey);
18306
18387
  }
18307
- if (!active || runtimes.get(runtime.label) !== runtime) return;
18388
+ if (!active || runtimes.get(runtime.label) !== runtime) return false;
18308
18389
  stopResultWatcher(runtime, result.requestId);
18309
18390
  stopAskWatcher(runtime);
18310
18391
  cancelAskRetries(runtime);
@@ -18319,8 +18400,10 @@ function createAgentController(pi, options) {
18319
18400
  scheduleResultCleanupRetry(runtime, result, context, signal);
18320
18401
  clearCleanupError(runtime, "Result delivery failed; retrying:");
18321
18402
  cancelResultRetry(resultDeliveryRetries, runtime, result.requestId);
18403
+ return submitted;
18322
18404
  } catch (error2) {
18323
18405
  scheduleResultDeliveryRetry(runtime, result, context, signal, error2);
18406
+ return false;
18324
18407
  } finally {
18325
18408
  resultDeliveryInFlight.delete(key);
18326
18409
  }
@@ -18365,6 +18448,45 @@ function createAgentController(pi, options) {
18365
18448
  await deliverResult(runtime, context, result, signal);
18366
18449
  }
18367
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
+ };
18368
18490
  const actionUnsafe = async (ctx, p, signal) => {
18369
18491
  if (p.action === "delegate") p.retentionPersisted = false;
18370
18492
  const scope = options.scope;
@@ -20954,6 +21076,11 @@ ${result.stderr ?? ""}`.trim(),
20954
21076
  }
20955
21077
  schedule();
20956
21078
  };
21079
+ if (options.registerRecipientFanIn !== false)
21080
+ registerRecipientFanIn(
21081
+ pi,
21082
+ (ctx, phase, budget) => drainReadyOwnerNotifications(ctx, phase, budget)
21083
+ );
20957
21084
  return {
20958
21085
  listAgentStates,
20959
21086
  managedAgentSnapshots: snapshot,
@@ -21066,6 +21193,7 @@ ${result.stderr ?? ""}`.trim(),
21066
21193
  settleResults(context, signal) {
21067
21194
  return settleResults(context, signal);
21068
21195
  },
21196
+ drainReadyOwnerNotifications,
21069
21197
  shutdown() {
21070
21198
  active = false;
21071
21199
  recoveryComplete = false;
@@ -21265,6 +21393,7 @@ var init_agent_controller = __esm({
21265
21393
  "extension/agent-controller.ts"() {
21266
21394
  "use strict";
21267
21395
  init_errors();
21396
+ init_recipient_fan_in();
21268
21397
  init_mailbox();
21269
21398
  init_presentation();
21270
21399
  init_storage();
@@ -24348,7 +24477,7 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
24348
24477
  // package.json
24349
24478
  var package_default = {
24350
24479
  name: "pi-herdsman",
24351
- version: "0.43.0",
24480
+ version: "0.44.0",
24352
24481
  type: "module",
24353
24482
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
24354
24483
  license: "Apache-2.0",
@@ -24621,6 +24750,7 @@ import {
24621
24750
  init_supervision();
24622
24751
  init_errors();
24623
24752
  init_herdr();
24753
+ init_mailbox();
24624
24754
  init_lock();
24625
24755
  init_config();
24626
24756
  init_core();
@@ -26001,6 +26131,115 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26001
26131
  );
26002
26132
  };
26003
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
+ };
26004
26243
  const operationSignal = signal ?? ctx.signal;
26005
26244
  operationSignal?.throwIfAborted();
26006
26245
  if (!/^[0-9a-f]{40,64}$/i.test(expectedHead))
@@ -26363,6 +26602,12 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26363
26602
  alreadyIntegrated: true
26364
26603
  };
26365
26604
  }
26605
+ const eligibility = await currentExecutionEligibility(current);
26606
+ if (eligibility)
26607
+ return {
26608
+ kind: "tool-result",
26609
+ result: completionRefusal(eligibility)
26610
+ };
26366
26611
  const preStopFastForward = await ancestry(
26367
26612
  preStopTarget,
26368
26613
  expectedHead
@@ -26463,10 +26708,29 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26463
26708
  };
26464
26709
  expectedMergeTree = tree;
26465
26710
  }
26466
- if (current.liveLead)
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)
26467
26731
  await stopExecution(
26468
- current.assignment.id,
26469
- current.liveLead,
26732
+ stopTarget.assignment.id,
26733
+ stopTarget.liveLead,
26470
26734
  ctx,
26471
26735
  operationSignal,
26472
26736
  heldLocks
@@ -30042,6 +30306,7 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
30042
30306
  init_supervision();
30043
30307
  init_supervision();
30044
30308
  init_errors();
30309
+ init_recipient_fan_in();
30045
30310
  init_herdr();
30046
30311
  init_lock();
30047
30312
  init_config();
@@ -30071,6 +30336,7 @@ import {
30071
30336
  init_supervision();
30072
30337
  init_supervision();
30073
30338
  init_errors();
30339
+ init_recipient_fan_in();
30074
30340
  init_core();
30075
30341
  init_storage();
30076
30342
  init_agent_controller();
@@ -30786,7 +31052,10 @@ function createLeadCoordinationRuntime(host) {
30786
31052
  } = host;
30787
31053
  const requireCompatibleBuild2 = host.requireCompatibleBuild;
30788
31054
  const reportedProjectMessageCleanupErrors = /* @__PURE__ */ new Set();
31055
+ const reportedProjectMessageSubmissionErrors = /* @__PURE__ */ new Set();
30789
31056
  const reportedProjectMessageReadErrors = /* @__PURE__ */ new Set();
31057
+ const projectMessageSubmissions = /* @__PURE__ */ new Map();
31058
+ let projectStartupEligibility;
30790
31059
  const reportedRetirementErrors = /* @__PURE__ */ new Set();
30791
31060
  const retirementCursors = /* @__PURE__ */ new Map();
30792
31061
  const prepareCoordinationInput = async (ctx, text, files, operation, heading, recordForInput) => {
@@ -32512,8 +32781,8 @@ ${receivedRefs.join("\n")}` : ""}`,
32512
32781
  );
32513
32782
  return pass;
32514
32783
  };
32515
- const drainProjectMessages = async (ctx) => {
32516
- 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")
32517
32786
  return 0;
32518
32787
  const lease = leadRuntime.managerLease;
32519
32788
  if (!lease) return 0;
@@ -32521,6 +32790,10 @@ ${receivedRefs.join("\n")}` : ""}`,
32521
32790
  if (!mightHaveProjectMessages(runtime, lease.descriptor.repoKey)) return 0;
32522
32791
  const manager = await currentManager(ctx);
32523
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);
32524
32797
  const hasProjectMessageReceipt = (record) => ctx.sessionManager.getEntries().some(
32525
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
32526
32799
  );
@@ -32528,6 +32801,7 @@ ${receivedRefs.join("\n")}` : ""}`,
32528
32801
  try {
32529
32802
  removeProjectMessage2(runtime, record.repoKey, record.branch, record.id);
32530
32803
  reportedProjectMessageCleanupErrors.delete(record.id);
32804
+ reportedProjectMessageSubmissionErrors.delete(record.id);
32531
32805
  reportedProjectMessageReadErrors.delete(record.id);
32532
32806
  } catch (error2) {
32533
32807
  if (!reportedProjectMessageCleanupErrors.has(record.id)) {
@@ -32536,13 +32810,20 @@ ${receivedRefs.join("\n")}` : ""}`,
32536
32810
  }
32537
32811
  }
32538
32812
  };
32813
+ let submitted = 0;
32539
32814
  for (const assignment of listProjectAssignments2(runtime, manager.repoKey)) {
32540
32815
  let pending;
32541
32816
  try {
32542
32817
  pending = listProjectMessageHeaders2(
32543
32818
  runtime,
32544
32819
  manager.repoKey,
32545
- 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
+ }
32546
32827
  );
32547
32828
  } catch (error2) {
32548
32829
  appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
@@ -32550,17 +32831,29 @@ ${receivedRefs.join("\n")}` : ""}`,
32550
32831
  }
32551
32832
  for (const record of pending) {
32552
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;
32553
32836
  if (hasProjectMessageReceipt(record)) {
32837
+ projectMessageSubmissions.delete(
32838
+ `${ctx.sessionManager.getSessionId()}:${manager.createdAt}:${record.id}`
32839
+ );
32554
32840
  consumeProjectMessage(record);
32555
32841
  continue;
32556
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
+ }
32557
32850
  const current = await currentManager(ctx);
32558
32851
  const stillAssigned = readProjectAssignment2(
32559
32852
  runtime,
32560
32853
  manager.repoKey,
32561
32854
  assignment.branch
32562
32855
  );
32563
- 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)
32564
32857
  return 0;
32565
32858
  let message;
32566
32859
  try {
@@ -32586,31 +32879,62 @@ ${receivedRefs.join("\n")}` : ""}`,
32586
32879
  );
32587
32880
  const backlog = message.createdAt < manager.createdAt;
32588
32881
  const actionableFailure = backlog && message.kind === "execution_failure";
32589
- pi.sendMessage(
32590
- {
32591
- customType: "pi-herdsman-project_message",
32592
- content: projectMessageEnvelope(
32593
- message.kind,
32594
- message.branch,
32595
- message.fromSessionId
32596
- ) + message.text + senderEnvironmentAnnotation(message.senderEnvironment),
32597
- display: true,
32598
- details: {
32599
- id: message.id,
32600
- repoKey: message.repoKey,
32601
- branch: message.branch,
32602
- fromSessionId: message.fromSessionId,
32603
- kind: message.kind,
32604
- ...message.senderEnvironment ? { senderEnvironment: message.senderEnvironment } : {}
32605
- }
32606
- },
32607
- backlog && !actionableFailure ? { triggerTurn: false } : { deliverAs: "followUp", triggerTurn: true }
32608
- );
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
+ }
32609
32932
  if (hasProjectMessageReceipt(message)) consumeProjectMessage(message);
32610
- return 1;
32933
+ submitted++;
32934
+ if (phase === "idle") return submitted;
32611
32935
  }
32612
32936
  }
32613
- return 0;
32937
+ return submitted;
32614
32938
  };
32615
32939
  return {
32616
32940
  persistCoordinatorState,
@@ -32639,6 +32963,16 @@ ${receivedRefs.join("\n")}` : ""}`,
32639
32963
  enterCoordinationPublication,
32640
32964
  drainRetirementNotices,
32641
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
+ },
32642
32976
  supervisorMessage: executeSupervisorMessage,
32643
32977
  peerMessage: executePeerMessage,
32644
32978
  latestCustomMessageText,
@@ -32689,14 +33023,16 @@ function createLeadToolState(getAllTools, ownedNames, leadCoordinationNames) {
32689
33023
  };
32690
33024
  const projectRoleTools = (baseline, definition, requiredTools) => {
32691
33025
  const policy = configuredToolPolicy(definition, requiredTools);
33026
+ const required = new Set(requiredTools);
32692
33027
  const selected = policy.explicit ? policy.tools.flatMap(
32693
33028
  (pattern) => [...registeredToolNames()].filter(
32694
33029
  (name) => matchesToolPattern(pattern, name)
32695
33030
  )
32696
33031
  ) : [...baseline];
32697
- const excluded = (name) => policy.excluded.some((pattern) => matchesToolPattern(pattern, name));
32698
33032
  return appendRegisteredTools(
32699
- normalizeBaseTools(selected.filter((name) => !excluded(name))),
33033
+ normalizeBaseTools(
33034
+ selected.filter((name) => toolPolicyAllowsName(policy, required, name))
33035
+ ),
32700
33036
  requiredTools
32701
33037
  );
32702
33038
  };
@@ -33954,7 +34290,10 @@ function registerLeadRuntime(pi, options) {
33954
34290
  schedulePeerPresence: (ctx) => coordinationRuntime.schedulePeerPresence(ctx),
33955
34291
  removePeerPresence: () => coordinationRuntime.removePeerPresence(),
33956
34292
  clearNormalUI: () => statusRuntime.clear(),
33957
- startNormalUI: (ctx) => statusRuntime.start(ctx),
34293
+ startNormalUI: (ctx) => {
34294
+ statusRuntime.clear();
34295
+ statusRuntime.start(ctx);
34296
+ },
33958
34297
  startSupervisionUI,
33959
34298
  clearSupervisionUI,
33960
34299
  publishLeadRole,
@@ -34017,8 +34356,13 @@ function registerLeadRuntime(pi, options) {
34017
34356
  projectAssignmentForScope: (...args) => roleTransitions.projectAssignmentForScope(...args),
34018
34357
  resolveEffectiveSupervisor: (...args) => roleTransitions.resolveEffectiveSupervisor(...args),
34019
34358
  currentPeerPresenceValid: async (ctx) => (sessionKind?.kind !== "managed" || managedLifecycle === "assigned") && await coordinationRuntime.currentPeerPresenceValid(ctx),
34020
- drainProjectMessages: (ctx) => coordinationRuntime.drainRetirementNotices(ctx).then(
34021
- 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
+ )
34022
34366
  ),
34023
34367
  reconcileRemotePeers: async (ctx, signal) => {
34024
34368
  if (activeLeadRole(leadRuntime) === "manager" || activeLeadRole(leadRuntime) === "lead")
@@ -34166,6 +34510,7 @@ function registerLeadRuntime(pi, options) {
34166
34510
  };
34167
34511
  const controller = createAgentController(pi, {
34168
34512
  ...options.controllerServices,
34513
+ registerRecipientFanIn: false,
34169
34514
  scope: { kind: "root" },
34170
34515
  managerEvidence,
34171
34516
  persistClosedDescendants: async (ctx, closures, selected) => {
@@ -35217,6 +35562,16 @@ function registerLeadRuntime(pi, options) {
35217
35562
  herdRun: herdRunRuntime
35218
35563
  });
35219
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
+ });
35220
35575
  pi.on("before_agent_start", (event, ctx) => {
35221
35576
  if (!isQuarantinedSession(ctx))
35222
35577
  return agentEvents.beforeAgentStart(event, ctx);
@@ -37623,6 +37978,7 @@ function createLeadInboxRuntime(host) {
37623
37978
  let remoteReconciliationInFlight = false;
37624
37979
  let currentSubmittedAt;
37625
37980
  let settledSubmissions = /* @__PURE__ */ new Set();
37981
+ let runBoundaryDrain;
37626
37982
  const chiefStartPreflights = [];
37627
37983
  const {
37628
37984
  leadRuntime,
@@ -38020,6 +38376,7 @@ function createLeadInboxRuntime(host) {
38020
38376
  }
38021
38377
  };
38022
38378
  const startChiefInbox = (ctx) => {
38379
+ runBoundaryDrain = void 0;
38023
38380
  const generation = ++chiefInboxGeneration;
38024
38381
  const socket = process.env.HERDR_SOCKET_PATH;
38025
38382
  if (!socket) return;
@@ -38050,7 +38407,7 @@ function createLeadInboxRuntime(host) {
38050
38407
  if (transaction.role === "inactive" && activeRole() !== "manager")
38051
38408
  assertCurrentLeadCoordination(ctx);
38052
38409
  };
38053
- const inboxOptions = (verifyLease, inboxRuntime = runtime) => {
38410
+ const inboxOptions = (verifyLease, inboxRuntime = runtime, phase, budget) => {
38054
38411
  if (!isCurrent()) throw new Error("Stale inbox transaction (options)");
38055
38412
  return {
38056
38413
  runtime: inboxRuntime,
@@ -38069,6 +38426,13 @@ function createLeadInboxRuntime(host) {
38069
38426
  return void 0;
38070
38427
  }
38071
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
+ }
38072
38436
  if (role2 === "lead" && record.kind === "manager_message") {
38073
38437
  let authorized;
38074
38438
  try {
@@ -38077,11 +38441,15 @@ function createLeadInboxRuntime(host) {
38077
38441
  return void 0;
38078
38442
  }
38079
38443
  if (!authorized) return "followUp";
38444
+ if (!phase && !ctx.isIdle()) return void 0;
38080
38445
  return "steer";
38081
38446
  }
38082
38447
  const supervisorDownlink = role2 === "lead" && record.kind === "chief_message" || role2 === "manager" && record.kind === "chief_message";
38083
- if (supervisorDownlink) return "steer";
38084
- 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;
38085
38453
  },
38086
38454
  senderTarget: (record) => {
38087
38455
  if (record.kind === "peer_message") {
@@ -38143,6 +38511,7 @@ function createLeadInboxRuntime(host) {
38143
38511
  }
38144
38512
  },
38145
38513
  sendMessage: async (message, options, record) => {
38514
+ let reservedContent;
38146
38515
  const projectAssignment = typeof message === "object" && message !== null && "customType" in message && message.customType === "pi-herdsman-project_assignment";
38147
38516
  try {
38148
38517
  let payload = message;
@@ -38212,6 +38581,14 @@ function createLeadInboxRuntime(host) {
38212
38581
  if (messageDelivered(ctx, record)) return;
38213
38582
  if (record.kind === "peer_message" && !await authorizePeerRecord(record, ctx))
38214
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
+ };
38215
38592
  let result;
38216
38593
  try {
38217
38594
  if (record.kind === "peer_message") {
@@ -38257,6 +38634,7 @@ function createLeadInboxRuntime(host) {
38257
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)))
38258
38635
  throw new Error("Peer eligibility changed before delivery");
38259
38636
  importResultBindings2(pi, ctx, resultBindings, record.kind);
38637
+ reservePayload();
38260
38638
  submitted = pi.sendMessage(payload, options);
38261
38639
  };
38262
38640
  if (source.role === "manager" && recipientContext.role === "manager")
@@ -38265,6 +38643,7 @@ function createLeadInboxRuntime(host) {
38265
38643
  result = submitted;
38266
38644
  } else {
38267
38645
  importResultBindings2(pi, ctx, resultBindings, record.kind);
38646
+ reservePayload();
38268
38647
  result = pi.sendMessage(payload, options);
38269
38648
  }
38270
38649
  } catch (error2) {
@@ -38292,6 +38671,8 @@ function createLeadInboxRuntime(host) {
38292
38671
  }
38293
38672
  return;
38294
38673
  } catch (error2) {
38674
+ if (reservedContent && budget)
38675
+ releaseFanInMessage(budget, reservedContent);
38295
38676
  managerDiagnostic("inbox_catch", { category: "send" });
38296
38677
  if (projectAssignment)
38297
38678
  managerDiagnostic("project_assignment_send", {
@@ -38303,6 +38684,8 @@ function createLeadInboxRuntime(host) {
38303
38684
  },
38304
38685
  transaction: {
38305
38686
  begin: (record) => {
38687
+ if (transactions.has(record.id))
38688
+ throw new Error("Inbox record already has an active drain");
38306
38689
  const token = {
38307
38690
  id: record.id,
38308
38691
  record,
@@ -38315,9 +38698,9 @@ function createLeadInboxRuntime(host) {
38315
38698
  transactions.set(record.id, token);
38316
38699
  return token;
38317
38700
  },
38318
- revalidate: (token, phase) => {
38701
+ revalidate: (token, phase2) => {
38319
38702
  try {
38320
- revalidateTransaction(token, phase);
38703
+ revalidateTransaction(token, phase2);
38321
38704
  } catch (error2) {
38322
38705
  managerDiagnostic("inbox_catch", { category: "transaction" });
38323
38706
  throw error2;
@@ -38330,6 +38713,8 @@ function createLeadInboxRuntime(host) {
38330
38713
  }
38331
38714
  }
38332
38715
  },
38716
+ forceNonTriggering: !!phase,
38717
+ maxDeliveries: budget ? Math.max(0, COORDINATION_INBOX_SCAN_LIMIT - budget.count) : void 0,
38333
38718
  accepted: async (record) => {
38334
38719
  if (record.kind === "peer_message")
38335
38720
  writePeerDeliveryReceipt(peerInboxRuntime, record);
@@ -38348,7 +38733,7 @@ function createLeadInboxRuntime(host) {
38348
38733
  }
38349
38734
  };
38350
38735
  };
38351
- const drainInbox = async (initial = false) => {
38736
+ const drainInbox = async (initial = false, phase, budget) => {
38352
38737
  if (initial) managerDiagnostic("initial_inbox_drain_start");
38353
38738
  const sessionId = ctx.sessionManager.getSessionId();
38354
38739
  const complete = (count) => {
@@ -38361,7 +38746,8 @@ function createLeadInboxRuntime(host) {
38361
38746
  const held = chiefStartPreflightHeld(ctx);
38362
38747
  managerDiagnostic("inbox_preflight", { reason: held ? "held" : "pass" });
38363
38748
  if (held) return complete(0);
38364
- 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(
38365
38751
  (path) => !chiefMessageQuarantined2(
38366
38752
  runtime,
38367
38753
  sessionId,
@@ -38391,27 +38777,38 @@ function createLeadInboxRuntime(host) {
38391
38777
  }
38392
38778
  }
38393
38779
  if (initial) {
38394
- const chief2 = await drainCoordinationInbox2(inboxOptions(false));
38780
+ const chief2 = await drainCoordinationInbox2(
38781
+ inboxOptions(false, runtime, phase, budget)
38782
+ );
38395
38783
  const peerPresent2 = await currentPeerPresenceValid(ctx);
38396
38784
  managerDiagnostic("inbox_peer_presence", {
38397
38785
  reason: peerPresent2 ? "pass" : "missing"
38398
38786
  });
38399
38787
  const peer2 = await drainCoordinationInbox2(
38400
- inboxOptions(false, peerInboxRuntime)
38788
+ inboxOptions(false, peerInboxRuntime, phase, budget)
38401
38789
  );
38402
- return complete(chief2 + peer2 + await drainProjectMessages(ctx));
38790
+ const project2 = await drainProjectMessages(
38791
+ ctx,
38792
+ phase ?? "idle",
38793
+ budget
38794
+ );
38795
+ return complete(phase ? budget?.count ?? 0 : chief2 + peer2 + project2);
38403
38796
  }
38404
38797
  const active = leadRuntime.chiefMode === "active" || activeRole() === "manager";
38405
- const chief = await drainCoordinationInbox2(inboxOptions(active));
38798
+ const chief = await drainCoordinationInbox2(
38799
+ inboxOptions(active, runtime, phase, budget)
38800
+ );
38406
38801
  const peerPresent = await currentPeerPresenceValid(ctx);
38407
38802
  managerDiagnostic("inbox_peer_presence", {
38408
38803
  reason: peerPresent ? "pass" : "missing"
38409
38804
  });
38410
38805
  const peer = await drainCoordinationInbox2(
38411
- inboxOptions(active, peerInboxRuntime)
38806
+ inboxOptions(active, peerInboxRuntime, phase, budget)
38412
38807
  );
38413
- 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);
38414
38810
  };
38811
+ runBoundaryDrain = (boundaryCtx, phase, budget) => boundaryCtx.sessionManager.getSessionId() === ctx.sessionManager.getSessionId() ? drainInbox(false, phase, budget) : Promise.resolve(0);
38415
38812
  const schedule = () => {
38416
38813
  if (generation !== chiefInboxGeneration || chiefInboxAbortController?.signal.aborted)
38417
38814
  return;
@@ -38455,6 +38852,7 @@ function createLeadInboxRuntime(host) {
38455
38852
  };
38456
38853
  return {
38457
38854
  start: startChiefInbox,
38855
+ drainBoundary: (ctx, phase, budget) => runBoundaryDrain?.(ctx, phase, budget) ?? Promise.resolve(0),
38458
38856
  cleanupManagedPeerInbox,
38459
38857
  isStartPreflightHeld: chiefStartPreflightHeld,
38460
38858
  clearStartPreflight,
@@ -40822,7 +41220,9 @@ If needed, install the Pi integration once:
40822
41220
  }
40823
41221
  ),
40824
41222
  workspaceId: () => process.env.PI_HERDSMAN_WORKSPACE_ID ?? process.env.HERDR_WORKSPACE_ID,
40825
- 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");
40826
41226
  pi.sendMessage(
40827
41227
  {
40828
41228
  customType: "pi-herdsman-agent-result",
@@ -40830,10 +41230,15 @@ If needed, install the Pi integration once:
40830
41230
  display: true,
40831
41231
  details
40832
41232
  },
40833
- { triggerTurn: true, deliverAs: "steer" }
41233
+ {
41234
+ triggerTurn,
41235
+ ...triggerTurn ? { deliverAs: "steer" } : {}
41236
+ }
40834
41237
  );
40835
41238
  },
40836
- 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");
40837
41242
  pi.sendMessage(
40838
41243
  {
40839
41244
  customType: "pi-herdsman-agent-ask",
@@ -40854,7 +41259,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
40854
41259
  piSessionId: ask.piSessionId
40855
41260
  }
40856
41261
  },
40857
- { triggerTurn: true }
41262
+ { triggerTurn }
40858
41263
  );
40859
41264
  },
40860
41265
  sessionRetired: (ctx, runtime) => {
@@ -41814,7 +42219,7 @@ ${summary}`,
41814
42219
  ...staffTool,
41815
42220
  name: "integrate_branch",
41816
42221
  label: "integrate branch",
41817
- 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. 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.",
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.",
41818
42223
  parameters: Type3.Object(
41819
42224
  {
41820
42225
  branch: Type3.String({