pi-herdsman 0.46.0 → 0.47.1

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
@@ -1262,6 +1262,8 @@ function validate(value2, kind) {
1262
1262
  "workspaceId",
1263
1263
  "agentLabel",
1264
1264
  "paneId",
1265
+ "terminalId",
1266
+ "launchShellPid",
1265
1267
  "piSessionId",
1266
1268
  "rootSessionId",
1267
1269
  "piSessionFile",
@@ -1387,6 +1389,12 @@ function validate(value2, kind) {
1387
1389
  };
1388
1390
  if (kind === "state") {
1389
1391
  finite("updatedAt");
1392
+ if (v.terminalId === void 0 !== (v.launchShellPid === void 0))
1393
+ throw new Error("Launch terminal identity fields must be paired");
1394
+ if (v.terminalId !== void 0 && (typeof v.terminalId !== "string" || !v.terminalId.trim() || v.terminalId.length > 512))
1395
+ throw new Error("Invalid mailbox terminal identity");
1396
+ if (v.launchShellPid !== void 0 && (typeof v.launchShellPid !== "number" || !Number.isInteger(v.launchShellPid) || !Number.isFinite(v.launchShellPid) || v.launchShellPid <= 0))
1397
+ throw new Error("Invalid mailbox launch shell PID");
1390
1398
  if (v.rootSessionId !== void 0 && (typeof v.rootSessionId !== "string" || !v.rootSessionId.trim() || v.rootSessionId.length > 512))
1391
1399
  throw new Error("Invalid mailbox root session identity");
1392
1400
  if (v.lastActivityAt !== void 0 && (typeof v.lastActivityAt !== "number" || !Number.isInteger(v.lastActivityAt) || !Number.isFinite(v.lastActivityAt) || v.lastActivityAt < 0))
@@ -3360,15 +3368,61 @@ function agentDefinitionDelegationEnabled(definition) {
3360
3368
  function contextInheritance(definition) {
3361
3369
  const project = definition.frontmatter.inheritProjectContext === true || definition.frontmatter.inheritProjectContext === void 0 && definition.name === "delegate";
3362
3370
  const global2 = definition.frontmatter.inheritGlobalContext === true || definition.frontmatter.inheritGlobalContext === void 0 && project;
3363
- return { global: global2, project };
3371
+ const ancestor = definition.frontmatter.inheritAncestorContext === true || definition.frontmatter.inheritAncestorContext === void 0 && project;
3372
+ return { global: global2, ancestor, project };
3373
+ }
3374
+ function isWithinDirectory(directory2, root2) {
3375
+ const rel = relative(root2, directory2);
3376
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
3377
+ }
3378
+ function contextProjectRoot(cwd) {
3379
+ const canonicalCwd2 = realpathSync2(cwd);
3380
+ let output;
3381
+ try {
3382
+ output = execFileSync("git", ["rev-parse", "--show-cdup"], {
3383
+ cwd: canonicalCwd2,
3384
+ env: { ...process.env, LC_ALL: "C" },
3385
+ encoding: "utf8",
3386
+ timeout: 2e3,
3387
+ maxBuffer: 8192,
3388
+ stdio: ["ignore", "pipe", "pipe"],
3389
+ windowsHide: true
3390
+ });
3391
+ } catch (error2) {
3392
+ const failure = error2;
3393
+ const diagnostic = failure.stderr?.toString() ?? "";
3394
+ if (failure.code === "ENOENT" || failure.status === 128 && /not a git repository/u.test(diagnostic))
3395
+ return canonicalCwd2;
3396
+ throw new Error(
3397
+ `Cannot resolve context worktree for ${cwd}: ${diagnostic.trimEnd() || failure.message}`,
3398
+ { cause: error2 }
3399
+ );
3400
+ }
3401
+ const cdup = output.replace(/\r?\n$/u, "");
3402
+ if (cdup.includes("\n") || cdup.includes("\r") || isAbsolute(cdup))
3403
+ throw new Error(
3404
+ `Invalid Git worktree-relative directory for ${cwd}: ${cdup}`
3405
+ );
3406
+ const canonicalRoot = realpathSync2(resolve3(canonicalCwd2, cdup || "."));
3407
+ if (!isWithinDirectory(canonicalCwd2, canonicalRoot))
3408
+ throw new Error(
3409
+ `Git worktree root does not contain ${cwd}: ${canonicalRoot}`
3410
+ );
3411
+ return canonicalRoot;
3364
3412
  }
3365
3413
  function selectedAgentContextFiles(definition, cwd, loader = loadProjectContextFiles) {
3366
3414
  const inheritance = contextInheritance(definition);
3367
- if (!inheritance.global && !inheritance.project) return [];
3415
+ if (!inheritance.global && !inheritance.ancestor && !inheritance.project)
3416
+ return [];
3368
3417
  const agentDir = getAgentDir();
3369
- return loader({ cwd, agentDir }).filter((context) => {
3370
- const isGlobal = resolve3(dirname5(context.path)) === resolve3(agentDir);
3371
- return isGlobal ? inheritance.global : inheritance.project;
3418
+ const discovered = loader({ cwd, agentDir });
3419
+ const boundary = inheritance.project === inheritance.ancestor ? void 0 : contextProjectRoot(cwd);
3420
+ return discovered.filter((context) => {
3421
+ const contextDir = dirname5(context.path);
3422
+ const isGlobal = resolve3(contextDir) === resolve3(agentDir);
3423
+ if (isGlobal) return inheritance.global;
3424
+ if (boundary === void 0) return inheritance.project;
3425
+ return isWithinDirectory(realpathSync2(contextDir), boundary) ? inheritance.project : inheritance.ancestor;
3372
3426
  });
3373
3427
  }
3374
3428
  function agentLaunchArgs(agent, options) {
@@ -3420,7 +3474,7 @@ function agentLaunchArgs(agent, options) {
3420
3474
  bodyPromptPathForLaunch
3421
3475
  );
3422
3476
  const inheritance = contextInheritance(agent);
3423
- if (!inheritance.global || !inheritance.project) {
3477
+ if (!inheritance.global || !inheritance.ancestor || !inheritance.project) {
3424
3478
  args.push("--no-context-files");
3425
3479
  for (const context of selectedAgentContextFiles(
3426
3480
  agent,
@@ -3512,6 +3566,7 @@ var init_agent_definitions = __esm({
3512
3566
  "noSkills",
3513
3567
  "noExtensions",
3514
3568
  "inheritGlobalContext",
3569
+ "inheritAncestorContext",
3515
3570
  "inheritProjectContext",
3516
3571
  "inheritSkills"
3517
3572
  ]);
@@ -4215,10 +4270,11 @@ async function reportLeadMetadata(pi, ctx, metadata) {
4215
4270
  noResult: true
4216
4271
  });
4217
4272
  }
4218
- function isUnstructuredResultFailure(value2) {
4273
+ function shouldCaptureStartupDiagnostic(value2) {
4219
4274
  if (!(value2 instanceof OperationError)) return false;
4220
- const classification = value2.detail.details?.result;
4221
- return classification?.classification === "empty" || classification?.classification === "malformed";
4275
+ const details = value2.detail.details;
4276
+ const classification = details?.result?.classification;
4277
+ return classification === "empty" || classification === "malformed" || details?.herdrCode === "timeout";
4222
4278
  }
4223
4279
  function startupCallTimeout(deadline, cap = Infinity) {
4224
4280
  const remaining = deadline - START_DIAGNOSTIC_TIMEOUT - Date.now();
@@ -4642,7 +4698,7 @@ async function startHerdrAgent(pi, ctx, options) {
4642
4698
  continue;
4643
4699
  }
4644
4700
  if (!busy) attempt.launchMayHaveStarted = true;
4645
- if (isUnstructuredResultFailure(failure))
4701
+ if (shouldCaptureStartupDiagnostic(failure))
4646
4702
  throw withStartupDiagnostic(
4647
4703
  failure,
4648
4704
  await captureStartupDiagnostic(
@@ -4824,7 +4880,7 @@ async function startHerdrAgentInPane(pi, ctx, options) {
4824
4880
  continue;
4825
4881
  }
4826
4882
  if (!busy) attempt.launchMayHaveStarted = true;
4827
- if (isUnstructuredResultFailure(failure))
4883
+ if (shouldCaptureStartupDiagnostic(failure))
4828
4884
  throw withStartupDiagnostic(
4829
4885
  failure,
4830
4886
  await captureStartupDiagnostic(
@@ -5234,6 +5290,92 @@ async function proveExactRunningAgent(pi, ctx, herdrAgent, expected, processOwne
5234
5290
  process: observed
5235
5291
  };
5236
5292
  }
5293
+ function sameRetainedPaneObservation(left, right) {
5294
+ return JSON.stringify(left.pane) === JSON.stringify(right.pane) && JSON.stringify(left.process) === JSON.stringify(right.process);
5295
+ }
5296
+ async function retainedPaneObservation(pi, ctx, target, signal) {
5297
+ if (!target.workspaceId || !target.paneId || !target.terminalId || !Number.isInteger(target.launchShellPid) || target.launchShellPid <= 0 || !target.cwd || !target.alias || !target.session.id && !target.session.path)
5298
+ return void 0;
5299
+ const snapshot = await herdrSessionSnapshot(pi, ctx, signal);
5300
+ if (!snapshot.workspaces.some(
5301
+ (item) => item?.workspace_id === target.workspaceId
5302
+ ) || snapshot.workspaces.filter(
5303
+ (item) => item?.workspace_id === target.workspaceId
5304
+ ).length !== 1)
5305
+ return void 0;
5306
+ const panes = snapshot.panes.filter((pane2) => pane2.pane_id === target.paneId);
5307
+ const pane = panes[0];
5308
+ if (panes.length !== 1 || !pane || pane.workspace_id !== target.workspaceId || pane.terminal_id !== target.terminalId || !sameCwd(pane.cwd, target.cwd) || pane.agent_session != null && !matchesExpectedSession(pane.agent_session, target.session))
5309
+ return void 0;
5310
+ const sessionPanes = snapshot.panes.filter(
5311
+ (item) => item.pane_id !== target.paneId && matchesExpectedSession(item.agent_session, target.session)
5312
+ );
5313
+ const sessionAgents = snapshot.agents.filter(
5314
+ (agent) => matchesExpectedSession(agent.agent_session, target.session)
5315
+ );
5316
+ if (sessionPanes.length > 0 || snapshot.agents.some(
5317
+ (agent) => agent.name === target.alias || agent.pane_id === target.paneId
5318
+ ) || sessionAgents.length > 0)
5319
+ return void 0;
5320
+ const process2 = await paneProcess(
5321
+ pi,
5322
+ ctx,
5323
+ target.paneId,
5324
+ signal,
5325
+ void 0,
5326
+ true
5327
+ );
5328
+ if (!process2 || process2.pane_id !== target.paneId || process2.shell_pid !== target.launchShellPid || !settledShell(
5329
+ { pane_id: target.paneId, shell_pid: target.launchShellPid },
5330
+ process2
5331
+ ))
5332
+ return void 0;
5333
+ return {
5334
+ pane: {
5335
+ pane_id: pane.pane_id,
5336
+ workspace_id: pane.workspace_id,
5337
+ terminal_id: pane.terminal_id,
5338
+ cwd: pane.cwd,
5339
+ agent_session: pane.agent_session ?? null
5340
+ },
5341
+ process: process2
5342
+ };
5343
+ }
5344
+ async function proveRetainedHerdrPane(pi, ctx, target, signal) {
5345
+ try {
5346
+ const first = await retainedPaneObservation(pi, ctx, target, signal);
5347
+ if (!first) return false;
5348
+ const second = await retainedPaneObservation(pi, ctx, target, signal);
5349
+ return !!second && sameRetainedPaneObservation(first, second);
5350
+ } catch {
5351
+ return false;
5352
+ }
5353
+ }
5354
+ async function verifyRetainedHerdrPane(pi, ctx, target, signal) {
5355
+ return proveRetainedHerdrPane(pi, ctx, target, signal);
5356
+ }
5357
+ async function closeRetainedHerdrPane(pi, ctx, target, signal) {
5358
+ const release = await lockLifecycle(ctx, signal);
5359
+ try {
5360
+ if (!await proveRetainedHerdrPane(pi, ctx, target, signal))
5361
+ error("close", `retained pane ${target.paneId} ownership is unproven`);
5362
+ await runHerdr(pi, ctx, ["pane", "close", target.paneId], {
5363
+ signal,
5364
+ noResult: true
5365
+ });
5366
+ await verifyHerdrPaneClosed(
5367
+ pi,
5368
+ ctx,
5369
+ target.alias,
5370
+ target.workspaceId,
5371
+ target.paneId,
5372
+ "close",
5373
+ signal
5374
+ );
5375
+ } finally {
5376
+ release();
5377
+ }
5378
+ }
5237
5379
  async function verifyHerdrPaneClosed(pi, ctx, herdrAgent, workspaceId, paneId, operation, signal) {
5238
5380
  const deadline = Date.now() + SETTLE_TIMEOUT;
5239
5381
  while (Date.now() < deadline) {
@@ -8460,6 +8602,7 @@ function summarizeDefinitionLayerChanges(layer) {
8460
8602
  "extensions",
8461
8603
  "agents",
8462
8604
  "inheritGlobalContext",
8605
+ "inheritAncestorContext",
8463
8606
  "inheritProjectContext",
8464
8607
  "inheritSkills"
8465
8608
  ];
@@ -16344,68 +16487,95 @@ async function managedAgentSnapshots(pi, ctx, dependencies, signal, proveRoot =
16344
16487
  pendingOwners.add(`${state.workspaceId}\0${state.ownerSessionId}`);
16345
16488
  return pending;
16346
16489
  });
16347
- const agents = mailboxes.map(({ path, state }, index) => {
16348
- const presence = managedAgentPresence(state, inventory);
16349
- const agent = presence.kind === "live" ? presence.agent : void 0;
16350
- let agentDefinition;
16351
- try {
16352
- const cached = dependencies.runtimeForLabel(state.agentLabel);
16353
- agentDefinition = agentDefinitionForRuntime(
16354
- agent,
16355
- state,
16356
- cached,
16357
- allowTranscriptDefinitionFallback
16358
- );
16359
- } catch {
16360
- agentDefinition = "unknown";
16361
- }
16362
- const session = agent && sessionIdentity(agent.agent_session);
16363
- const piSessionId = session?.kind === "id" ? session.value : state.piSessionId;
16364
- const piSessionPath = session?.kind === "path" ? session.value : state.piSessionFile;
16365
- const lifecycleState = agent ? normalizeHerdrLifecycleState(agent) : "unknown";
16366
- const controlLifecycleState = lifecycleState === "idle" || lifecycleState === "working" || lifecycleState === "blocked" || lifecycleState === "done" ? lifecycleState : "unknown";
16367
- const completionPending = completedResultsPending[index];
16368
- const handoffPending = unacknowledgedRequestExists(path, state);
16369
- const liveState = agent ? agentControlState(
16370
- controlLifecycleState,
16371
- state.activeRequestId,
16372
- completionPending,
16373
- handoffPending,
16374
- !!state.pendingAskId,
16375
- !!state.resultError
16376
- ) : "unknown";
16377
- const pendingDirectChildWork = pendingOwners.has(durableIdentityKey(state));
16378
- const waitingForChildren = !!state.activeRequestId && pendingDirectChildWork && (lifecycleState === "idle" || lifecycleState === "done") && !completionPending && !handoffPending && !state.resultError;
16379
- const existingLiveProjection = waitingForChildren ? "blocked" : liveState;
16380
- const projectedState = completionPending || state.resultError ? "settling" : presence.kind === "lost" ? "lost" : presence.kind === "unknown" ? "unknown" : existingLiveProjection;
16381
- const steerable = presence.kind === "live" && !state.pendingAskId && (projectedState === "working" || waitingForChildren);
16382
- const now = Date.now();
16383
- const listed = {
16384
- label: state.agentLabel,
16385
- kind: "pi",
16386
- state: projectedState,
16387
- steerable,
16388
- workspace_id: state.workspaceId,
16389
- pane_id: agent?.pane_id ?? state.paneId,
16390
- ...agent?.tab_id ? { tab_id: agent.tab_id } : {},
16391
- cwd: agent?.cwd ?? state.cwd,
16392
- ...agent?.agent_session ? { agent_session: agent.agent_session } : {},
16393
- pi_session_id: piSessionId,
16394
- pi_session_path: piSessionPath,
16395
- managed: true,
16396
- owner_session_id: state.ownerSessionId,
16397
- agent_definition: agentDefinition,
16398
- active_request_id: state.activeRequestId,
16399
- ...presence.kind === "unknown" ? { recovery_only: true, diagnostic: presence.diagnostic } : {},
16400
- ...state.resultError ? { result_error: state.resultError } : {},
16401
- ...state.lastActivityAt !== void 0 ? {
16402
- last_activity_at: state.lastActivityAt,
16403
- ...presence.kind === "live" && existingLiveProjection === "working" && state.activeRequestId && state.lastActivityAt <= now && now - state.lastActivityAt >= dependencies.staleAfterMs ? { stale: true, inactive_ms: now - state.lastActivityAt } : {}
16404
- } : {},
16405
- ...agent?.tokens ? { tokens: agent.tokens } : {}
16406
- };
16407
- return { state, agentDefinition, lifecycleState, listed, presence };
16408
- });
16490
+ const agents = await Promise.all(
16491
+ mailboxes.map(async ({ path, state }, index) => {
16492
+ let presence = managedAgentPresence(state, inventory);
16493
+ if (presence.kind === "unknown" && state.terminalId && state.launchShellPid !== void 0 && inventory.panes.some(
16494
+ (pane) => pane.pane_id === state.paneId && pane.workspace_id === state.workspaceId
16495
+ )) {
16496
+ const proven = await verifyRetainedHerdrPane(
16497
+ pi,
16498
+ ctx,
16499
+ {
16500
+ workspaceId: state.workspaceId,
16501
+ paneId: state.paneId,
16502
+ terminalId: state.terminalId,
16503
+ launchShellPid: state.launchShellPid,
16504
+ cwd: state.cwd,
16505
+ alias: herdrAgentAlias(
16506
+ state.workspaceId,
16507
+ state.agentLabel,
16508
+ state.runId
16509
+ ),
16510
+ session: { id: state.piSessionId, path: state.piSessionFile }
16511
+ },
16512
+ signal
16513
+ );
16514
+ if (proven) presence = { kind: "lost", retainedPane: true };
16515
+ }
16516
+ const agent = presence.kind === "live" ? presence.agent : void 0;
16517
+ let agentDefinition;
16518
+ try {
16519
+ const cached = dependencies.runtimeForLabel(state.agentLabel);
16520
+ agentDefinition = agentDefinitionForRuntime(
16521
+ agent,
16522
+ state,
16523
+ cached,
16524
+ allowTranscriptDefinitionFallback
16525
+ );
16526
+ } catch {
16527
+ agentDefinition = "unknown";
16528
+ }
16529
+ const session = agent && sessionIdentity(agent.agent_session);
16530
+ const piSessionId = session?.kind === "id" ? session.value : state.piSessionId;
16531
+ const piSessionPath = session?.kind === "path" ? session.value : state.piSessionFile;
16532
+ const lifecycleState = agent ? normalizeHerdrLifecycleState(agent) : "unknown";
16533
+ const controlLifecycleState = lifecycleState === "idle" || lifecycleState === "working" || lifecycleState === "blocked" || lifecycleState === "done" ? lifecycleState : "unknown";
16534
+ const completionPending = completedResultsPending[index];
16535
+ const handoffPending = unacknowledgedRequestExists(path, state);
16536
+ const liveState = agent ? agentControlState(
16537
+ controlLifecycleState,
16538
+ state.activeRequestId,
16539
+ completionPending,
16540
+ handoffPending,
16541
+ !!state.pendingAskId,
16542
+ !!state.resultError
16543
+ ) : "unknown";
16544
+ const pendingDirectChildWork = pendingOwners.has(
16545
+ durableIdentityKey(state)
16546
+ );
16547
+ const waitingForChildren = !!state.activeRequestId && pendingDirectChildWork && (lifecycleState === "idle" || lifecycleState === "done") && !completionPending && !handoffPending && !state.resultError;
16548
+ const existingLiveProjection = waitingForChildren ? "blocked" : liveState;
16549
+ const projectedState = completionPending || state.resultError ? "settling" : presence.kind === "lost" ? "lost" : presence.kind === "unknown" ? "unknown" : existingLiveProjection;
16550
+ const steerable = presence.kind === "live" && !state.pendingAskId && (projectedState === "working" || waitingForChildren);
16551
+ const now = Date.now();
16552
+ const listed = {
16553
+ label: state.agentLabel,
16554
+ kind: "pi",
16555
+ state: projectedState,
16556
+ steerable,
16557
+ workspace_id: state.workspaceId,
16558
+ pane_id: agent?.pane_id ?? state.paneId,
16559
+ ...agent?.tab_id ? { tab_id: agent.tab_id } : {},
16560
+ cwd: agent?.cwd ?? state.cwd,
16561
+ ...agent?.agent_session ? { agent_session: agent.agent_session } : {},
16562
+ pi_session_id: piSessionId,
16563
+ pi_session_path: piSessionPath,
16564
+ managed: true,
16565
+ owner_session_id: state.ownerSessionId,
16566
+ agent_definition: agentDefinition,
16567
+ active_request_id: state.activeRequestId,
16568
+ ...presence.kind === "unknown" ? { recovery_only: true, diagnostic: presence.diagnostic } : {},
16569
+ ...state.resultError ? { result_error: state.resultError } : {},
16570
+ ...state.lastActivityAt !== void 0 ? {
16571
+ last_activity_at: state.lastActivityAt,
16572
+ ...presence.kind === "live" && existingLiveProjection === "working" && state.activeRequestId && state.lastActivityAt <= now && now - state.lastActivityAt >= dependencies.staleAfterMs ? { stale: true, inactive_ms: now - state.lastActivityAt } : {}
16573
+ } : {},
16574
+ ...agent?.tokens ? { tokens: agent.tokens } : {}
16575
+ };
16576
+ return { state, agentDefinition, lifecycleState, listed, presence };
16577
+ })
16578
+ );
16409
16579
  let rootOwners = [];
16410
16580
  if (proveRoot) {
16411
16581
  try {
@@ -17152,6 +17322,19 @@ function createAgentController(pi, options) {
17152
17322
  operation,
17153
17323
  `Agent ${current.agentLabel}`
17154
17324
  );
17325
+ if (submitOptions.launchIdentity) {
17326
+ if (current.terminalId !== void 0 || current.launchShellPid !== void 0)
17327
+ fail(
17328
+ "target_ambiguous",
17329
+ "Agent already has unexpected launch identity",
17330
+ operation
17331
+ );
17332
+ writeAgentState(runtime.mailboxPath, {
17333
+ ...current,
17334
+ ...submitOptions.launchIdentity,
17335
+ updatedAt: Date.now()
17336
+ });
17337
+ }
17155
17338
  if (kind === "steer" && readUnacknowledgedRequest(runtime.mailboxPath, current))
17156
17339
  fail(
17157
17340
  "agent_busy",
@@ -17872,10 +18055,31 @@ function createAgentController(pi, options) {
17872
18055
  "Managed agent has a durable result; close result delivery first",
17873
18056
  "close"
17874
18057
  );
17875
- const presence = managedAgentPresence(
17876
- current,
17877
- await herdrSessionSnapshot(pi, context, signal)
17878
- );
18058
+ const inventory = await herdrSessionSnapshot(pi, context, signal);
18059
+ let presence = managedAgentPresence(current, inventory);
18060
+ const currentPaneId = current.paneId;
18061
+ const currentWorkspaceId = current.workspaceId;
18062
+ if (presence.kind === "unknown" && current.terminalId && current.launchShellPid !== void 0 && inventory.panes.some(
18063
+ (pane) => pane.pane_id === currentPaneId && pane.workspace_id === currentWorkspaceId
18064
+ ) && await verifyRetainedHerdrPane(
18065
+ pi,
18066
+ context,
18067
+ {
18068
+ workspaceId: current.workspaceId,
18069
+ paneId: current.paneId,
18070
+ terminalId: current.terminalId,
18071
+ launchShellPid: current.launchShellPid,
18072
+ cwd: current.cwd,
18073
+ alias: herdrAgentAlias(
18074
+ current.workspaceId,
18075
+ current.agentLabel,
18076
+ current.runId
18077
+ ),
18078
+ session: { id: current.piSessionId, path: current.piSessionFile }
18079
+ },
18080
+ signal
18081
+ ))
18082
+ presence = { kind: "lost", retainedPane: true };
17879
18083
  if (presence.kind === "unknown")
17880
18084
  fail(
17881
18085
  "target_ambiguous",
@@ -17930,6 +18134,40 @@ function createAgentController(pi, options) {
17930
18134
  "Managed agent has a durable result; close result delivery first",
17931
18135
  "close"
17932
18136
  );
18137
+ if (presence.kind === "lost" && presence.retainedPane) {
18138
+ if (current.terminalId !== state.terminalId || current.launchShellPid !== state.launchShellPid || !current.terminalId || current.launchShellPid === void 0)
18139
+ fail(
18140
+ "target_ambiguous",
18141
+ "Original retained pane identity changed before close",
18142
+ "close"
18143
+ );
18144
+ await closeRetainedHerdrPane(
18145
+ pi,
18146
+ context,
18147
+ {
18148
+ workspaceId: current.workspaceId,
18149
+ paneId: current.paneId,
18150
+ terminalId: current.terminalId,
18151
+ launchShellPid: current.launchShellPid,
18152
+ cwd: current.cwd,
18153
+ alias: herdrAgentAlias(
18154
+ current.workspaceId,
18155
+ current.agentLabel,
18156
+ current.runId
18157
+ ),
18158
+ session: { id: current.piSessionId, path: current.piSessionFile }
18159
+ },
18160
+ signal
18161
+ );
18162
+ const after = readAgentState(mailbox);
18163
+ if (!after || !sameIdentity(after, current) || after.terminalId !== current.terminalId || after.launchShellPid !== current.launchShellPid || hasDurableResult(mailbox, after))
18164
+ fail(
18165
+ "target_ambiguous",
18166
+ "Managed agent changed or produced a result during retained-pane close",
18167
+ "close"
18168
+ );
18169
+ current = after;
18170
+ }
17933
18171
  }
17934
18172
  try {
17935
18173
  if (preserveOwnerMessages && !clearConfirmedOwnerMessages(mailbox, current, context))
@@ -20236,6 +20474,17 @@ ${result.stderr ?? ""}`.trim(),
20236
20474
  p.action,
20237
20475
  `Agent ${label} in pane ${started.paneId}`
20238
20476
  );
20477
+ const shellPid = started.shellProcess?.shell_pid;
20478
+ if (!Number.isInteger(shellPid) || shellPid <= 0 || !started.terminalId?.trim())
20479
+ fail(
20480
+ "target_ambiguous",
20481
+ "Original pane shell is unproven",
20482
+ p.action
20483
+ );
20484
+ const launchIdentity = {
20485
+ terminalId: started.terminalId,
20486
+ launchShellPid: shellPid
20487
+ };
20239
20488
  const expectedHerdrAgent = herdrAgentAlias(
20240
20489
  workspaceId,
20241
20490
  label,
@@ -20356,6 +20605,7 @@ ${result.stderr ?? ""}`.trim(),
20356
20605
  assignmentInput.resultBindings,
20357
20606
  {
20358
20607
  waitForLock: true,
20608
+ launchIdentity,
20359
20609
  evidence: evidenceMetadata,
20360
20610
  beforeWrite: async (publish) => {
20361
20611
  assertRootDelegationAllowed();
@@ -21166,7 +21416,7 @@ ${result.stderr ?? ""}`.trim(),
21166
21416
  return [];
21167
21417
  }
21168
21418
  });
21169
- const prepareAgentLoss = (ctx, state, snapshotAgentDefinition, availableActions, nextReminderMs, signal) => {
21419
+ const prepareAgentLoss = (ctx, state, snapshotAgentDefinition, availableActions, nextReminderMs, signal, retainedPane = false) => {
21170
21420
  const mailbox = agentMailboxPath(state.workspaceId, state.agentLabel);
21171
21421
  const current = readAgentState(mailbox);
21172
21422
  if (!current || !sameIdentity(current, state) || current.ownerSessionId !== ctx.sessionManager.getSessionId())
@@ -21203,7 +21453,7 @@ ${result.stderr ?? ""}`.trim(),
21203
21453
  return {
21204
21454
  customType: "pi-herdsman-agent-lost",
21205
21455
  content: [
21206
- `Agent ${current.agentLabel} is still lost and its assignment remains unresolved.`,
21456
+ retainedPane ? `Agent ${current.agentLabel}'s managed execution is lost. Its original pane is verified as settled, but the assignment remains unresolved.` : `Agent ${current.agentLabel} is still lost and its assignment remains unresolved.`,
21207
21457
  ...latestRequestId ? [`Request: ${latestRequestId}`] : [],
21208
21458
  `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21209
21459
  `Next reminder if unresolved: ~${formatHealthAttentionDuration(nextReminderMs)}`,
@@ -21327,6 +21577,7 @@ ${result.stderr ?? ""}`.trim(),
21327
21577
  }
21328
21578
  if (agent.presence.kind === "lost" && !state.completedRequestId) {
21329
21579
  const episode2 = "lost";
21580
+ const retainedPane = agent.presence.retainedPane === true;
21330
21581
  if (!attentionDue(state.runId, episode2, now)) continue;
21331
21582
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
21332
21583
  const message = prepareAgentLoss(
@@ -21335,7 +21586,8 @@ ${result.stderr ?? ""}`.trim(),
21335
21586
  agent.agentDefinition,
21336
21587
  availableActions,
21337
21588
  intervalMs2,
21338
- signal
21589
+ signal,
21590
+ retainedPane
21339
21591
  );
21340
21592
  if (message)
21341
21593
  stageAttention({
@@ -21348,7 +21600,8 @@ ${result.stderr ?? ""}`.trim(),
21348
21600
  agent.agentDefinition,
21349
21601
  availableActions,
21350
21602
  intervalMs2,
21351
- signal
21603
+ signal,
21604
+ retainedPane
21352
21605
  ),
21353
21606
  onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
21354
21607
  });
@@ -22248,9 +22501,11 @@ var init_agent_controller = __esm({
22248
22501
  SHARED_AGENT_INSTRUCTIONS = `Work only on the assigned objective and preserve its stated scope, constraints,
22249
22502
  authority, and acceptance criteria.
22250
22503
 
22251
- Treat supplied files as message evidence. Complete strict UTF-8 text may be
22252
- embedded; other files are canonical local references and are not copied or
22253
- snapshotted. Reuse adequate existing evidence instead of repeating completed
22504
+ Treat supplied files as message evidence. Explicit Agent attachments must contain
22505
+ complete supported UTF-8 text within configured limits, or the handoff is
22506
+ rejected. Retained assignment evidence may instead be presented by an authorized
22507
+ semantic reference and retrieved with \`read_evidence\`. Reuse adequate existing
22508
+ evidence instead of repeating completed
22254
22509
  work.
22255
22510
  Do not overlap writers in a worktree or file-ownership boundary. For dependent
22256
22511
  work, pass reusable direct-agent result refs through \`files\`. Preserve
@@ -22310,7 +22565,7 @@ blockers, remaining work, and reusable paths or artifacts.`;
22310
22565
  AGENT_EXECUTION_OWNERSHIP_GUIDANCE = "Each unresolved unit of work has one executor. Using delegate_agent transfers that assignment's execution ownership to the Agent until it resolves. After delegation succeeds, stop executing, inspecting, or analyzing that delegated scope locally; do not assign overlapping work. Continue only concrete, necessary work clearly outside the delegated scope that you still own.";
22311
22566
  AGENT_UNRESOLVED_GUIDANCE = "Use list_agents when fresh Agent state or ownership is materially needed for a control or recovery decision, or to refresh the definition roster; do not use it for progress polling. Follow current available_tools and revalidation: steer_agent queues a cooperative correction for Pi to deliver after the current assistant turn and its tool calls reach a steering boundary; it does not preempt the current operation. interrupt_agent cancels the current operation and replaces its direction. Use reply_agent only to answer that Agent's exact pending await_owner question. stop_agent abandons an eligible Agent generation and its unfinished assignment. inspect_agent provides bounded live terminal/process evidence; read_agent_transcript provides bounded persisted conversation/tool evidence. When Agent work is unresolved, handle required control, then continue only necessary work you still own or end the turn without concluding; results or attention resume the session automatically. Do not poll with status requests, sleep, or other waiting mechanisms. Stale health attention is diagnosis, not progress polling: use attached evidence first and, when absent or insufficient, perform at most one bounded diagnostic read before passive waiting. A repeated reminder for the same stale episode is additional recovery evidence: unchanged qualifying activity means the Agent has not crossed an execution boundary since the previous reminder. A steer queued during that unchanged episode cannot have taken effect yet. Do not repeat diagnostic reads solely because a reminder fired. Continue waiting only while existing evidence still positively supports a legitimate long-running operation; otherwise use interrupt_agent to stop the current operation and continue the same assignment. A proven lost Agent remains unresolved; physical disappearance is not completion. A physically unknown Agent remains fail-closed: do not control, close, replace, or infer completion of that generation. Unknown Agent identity does not by itself prove a currently active competing writer. For a concrete recovery decision, use available current evidence and at most one bounded diagnostic read when necessary; distinguish historical Agent identity from current execution and delegated scope. Continue necessary independent work that remains authorized and has no unresolved execution conflict. Do not take over the Agent's unresolved assignment. Do not take over or replace unresolved delegated work until the current generation is resolved or explicitly closed. If evidence is insufficient to exclude competing execution, preserve the affected scope and identify the specific missing evidence or external action. Do not repeat the same identity investigation without new evidence.";
22312
22567
  AGENT_DELEGATION_GUIDANCE = "Delegate bounded execution work when an Agent can reasonably own it and delegation is useful. Keep work local when it is trivial, inseparable from work you must own, otherwise unsuitable for an Agent, or delegation would add more coordination than value.";
22313
- AGENT_HANDOFF_GUIDANCE = "When delegating a bounded task, prefer continue_agent if a known exact historical managed-Agent Pi session carries substantial context relevant to that task and remains eligible; otherwise use delegate_agent to start fresh from a definition. When a result ref is shown, prefer it to the exact session UUID or path. Retired sessions cannot be continued while context retirement is enabled. If further work is needed, delegate a fresh Agent with the prior handoff and relevant files. Each live Agent generation exists for one assignment; after its terminal result is delivered, Herdsman cleans up that generation. Agent labels identify the current live generation; exact Pi sessions identify historical context and continuation. For new or updated assignments, `task`/`message` and `files` carry assignment evidence. Accepted managed-Agent tasks are retained for descendants as context, not authority; ordinary attachments remain per handoff unless retained. Complete strict UTF-8 text may be embedded; other files remain canonical local references and are not copied or snapshotted. Do not attach or mention agent instruction files such as AGENTS.md, CLAUDE.md, GEMINI.md, or equivalents merely because they exist. Rely on normal project or runtime discovery when it supplies those instructions. Attach such a file only when the task itself requires inspecting, modifying, comparing, or transmitting it, the user explicitly requests it, or required instructions would not otherwise reach the target. Skills are separate; attach SKILL.md only when the task needs it and the selected definition does not already provide that skill.";
22568
+ AGENT_HANDOFF_GUIDANCE = "When delegating a bounded task, prefer continue_agent if a known exact historical managed-Agent Pi session carries substantial context relevant to that task and remains eligible; otherwise use delegate_agent to start fresh from a definition. When a result ref is shown, prefer it to the exact session UUID or path. Retired sessions cannot be continued while context retirement is enabled. If further work is needed, delegate a fresh Agent with the prior handoff and relevant files. Each live Agent generation exists for one assignment; after its terminal result is delivered, Herdsman cleans up that generation. Agent labels identify the current live generation; exact Pi sessions identify historical context and continuation. For new or updated assignments, `task`/`message` and `files` carry assignment evidence. Accepted managed-Agent tasks are retained for descendants as context, not authority; ordinary attachments remain per handoff unless retained. Explicit Agent attachments must contain complete supported UTF-8 text within configured limits, or the handoff is rejected. Retained assignment evidence can instead be presented by an authorized semantic reference and retrieved with read_evidence. Do not attach or mention agent instruction files such as AGENTS.md, CLAUDE.md, GEMINI.md, or equivalents merely because they exist. Rely on normal project or runtime discovery when it supplies those instructions. Attach such a file only when the task itself requires inspecting, modifying, comparing, or transmitting it, the user explicitly requests it, or required instructions would not otherwise reach the target. Skills are separate; attach SKILL.md only when the task needs it and the selected definition does not already provide that skill.";
22314
22569
  LEAD_SCOPE_DESCRIPTION = `Own architecture, approved scope, acceptance of Agent outputs, integration, conflict resolution,
22315
22570
  and final technical decisions within your assigned objective. Integrate resolved Agent results.
22316
22571
  Pass relevant available files and artifacts, including completed-Agent result refs for
@@ -22394,7 +22649,7 @@ import { buildSessionProjection as buildSessionProjection2 } from "@earendil-wor
22394
22649
  import { contentText as contentText3 } from "@earendil-works/pi-ai";
22395
22650
  import { randomUUID as randomUUID11 } from "node:crypto";
22396
22651
  import { Type as Type2 } from "typebox";
22397
- import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
22652
+ import { isDeepStrictEqual as isDeepStrictEqual3, stripVTControlCharacters } from "node:util";
22398
22653
  import { readFileSync as readFileSync8 } from "node:fs";
22399
22654
  import { TextDecoder as TextDecoder3 } from "node:util";
22400
22655
  function evidencePageContent(page) {
@@ -22784,6 +23039,37 @@ function managedAgentControllerIdentity(ctx) {
22784
23039
  const state = managedAgentIdentity(ctx);
22785
23040
  return validateManagedAgentControllerIdentity(ctx, state);
22786
23041
  }
23042
+ function executionFailureMessage(message) {
23043
+ const sanitize = (value2) => typeof value2 !== "string" ? "" : stripVTControlCharacters(value2).replace(new RegExp("\\p{Cc}", "gu"), " ").replace(/\b(Bearer|Basic)\s+[^\s,"';}]+/gi, "$1 [REDACTED]").replace(/((?:https?:\/\/))[^\s/@]+@/gi, "$1[REDACTED]@").replace(
23044
+ /([?&](?:api[_-]?key|(?:access[_-]?|refresh[_-]?)?token|secret|authorization|password|cookie)=)[^&#\s]*/gi,
23045
+ "$1[REDACTED]"
23046
+ ).replace(
23047
+ /(["']?\b(?:api[_-]?key|(?:access[_-]?|refresh[_-]?)?token|secret|authorization|password|cookie)["']?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)/gi,
23048
+ "$1[REDACTED]"
23049
+ ).replace(
23050
+ /\b(?:sk-|pk-|ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_-]+/g,
23051
+ "[REDACTED]"
23052
+ ).replace(/\s+/g, " ").trim();
23053
+ const bound = (text, bytes) => {
23054
+ if (Buffer.byteLength(text, "utf8") <= bytes) return text;
23055
+ const marker = "\u2026 [truncated]";
23056
+ let prefix = "";
23057
+ let used = Buffer.byteLength(marker, "utf8");
23058
+ for (const character of text) {
23059
+ used += Buffer.byteLength(character, "utf8");
23060
+ if (used > bytes) break;
23061
+ prefix += character;
23062
+ }
23063
+ return prefix + marker;
23064
+ };
23065
+ const cause = sanitize(message.errorMessage);
23066
+ if (!cause) return void 0;
23067
+ const identity = [message.provider, message.model].map((value2) => bound(sanitize(value2), 128)).filter(Boolean).join("/");
23068
+ return bound(
23069
+ `Agent model execution failed${identity ? ` (${identity})` : ""}: ${cause}`,
23070
+ 1024
23071
+ );
23072
+ }
22787
23073
  function createManagedAgentExecutionState() {
22788
23074
  return {
22789
23075
  assignment: void 0,
@@ -23913,6 +24199,7 @@ function registerManagedAgentActivityHandlers(pi, execution, options) {
23913
24199
  const observation = execution.observation ?? (execution.observation = { requestId: state.activeRequestId });
23914
24200
  if (observation.requestId === state.activeRequestId) {
23915
24201
  observation.outcome = event.outcome;
24202
+ observation.executionErrorMessage = event.outcome === "error" ? executionFailureMessage(event.message) : void 0;
23916
24203
  observation.responseEntryId = event.messageEntryId;
23917
24204
  observation.responseText = contentText3(
23918
24205
  event.message.content,
@@ -24065,7 +24352,7 @@ function registerManagedAgentSettlementHandlers(pi, execution, options) {
24065
24352
  } : {
24066
24353
  error: {
24067
24354
  code: aborted ? "aborted" : handoffSelectionError || outcome === "error" ? "execution_error" : "empty_result",
24068
- message: aborted ? "Agent execution was cancelled" : handoffSelectionError ? "Selected handoff evidence could not be verified" : outcome === "error" ? "Agent model execution failed" : observation?.requestId === state.activeRequestId && observation.askOwnerCapacityError ? `Agent produced no assistant text. Earlier in this execution, await_owner rejected its attachments: ${observation.askOwnerCapacityError}. The question was not sent.` : "Agent produced no assistant text"
24355
+ message: aborted ? "Agent execution was cancelled" : handoffSelectionError ? "Selected handoff evidence could not be verified" : outcome === "error" ? observation?.executionErrorMessage ?? "Agent model execution failed" : observation?.requestId === state.activeRequestId && observation.askOwnerCapacityError ? `Agent produced no assistant text. Earlier in this execution, await_owner rejected its attachments: ${observation.askOwnerCapacityError}. The question was not sent.` : "Agent produced no assistant text"
24069
24356
  }
24070
24357
  },
24071
24358
  contextUsage: ctx.getContextUsage(),
@@ -25572,7 +25859,7 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
25572
25859
  // package.json
25573
25860
  var package_default = {
25574
25861
  name: "pi-herdsman",
25575
- version: "0.46.0",
25862
+ version: "0.47.1",
25576
25863
  type: "module",
25577
25864
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
25578
25865
  license: "Apache-2.0",
@@ -28521,9 +28808,18 @@ Subsequent explicitly requested removals here can proceed without a per-removal
28521
28808
  const requiredEvidence = [projectBrief, ...attachedEvidence];
28522
28809
  const prepared = prepareMessageInput2(
28523
28810
  operation.task,
28524
- attachedEvidence.flatMap(
28525
- (evidence) => "path" in evidence ? [evidence.path] : [evidence.result]
28526
- ),
28811
+ attachedEvidence.map((evidence) => {
28812
+ if ("result" in evidence) return evidence.result;
28813
+ if (!evidence.ref)
28814
+ throw new Error("Required evidence has no semantic reference");
28815
+ return {
28816
+ kind: "retainedEvidence",
28817
+ ref: evidence.ref,
28818
+ name: evidence.name,
28819
+ path: evidence.path,
28820
+ sha256: evidence.sha256
28821
+ };
28822
+ }),
28527
28823
  ctx.cwd,
28528
28824
  "delegate_work",
28529
28825
  "Task",
@@ -30528,7 +30824,15 @@ function createLeadCommandRuntime(host) {
30528
30824
  })) : [];
30529
30825
  const contextFiles = current.name === "chief" ? chiefContextFiles : roleProfile ? activeRole ? roleContextFiles : futureContextFiles : futureContextFiles;
30530
30826
  const contextCount = inheritance ? String(contextFiles.length) : current.name === "chief" ? String(chiefContextFiles.length) : activeRole ? String(roleContextFiles.length) : "session-dependent";
30531
- const contextMode = current.name === "chief" ? "Chief forced prompt includes only global user instructions; project context excluded" : inheritance ? inheritance.global && inheritance.project ? "Pi context inherited globally and from the project" : inheritance.global ? "Selected global Pi context" : inheritance.project ? "Selected project Pi context" : "Pi context files disabled" : activeRole ? "Current Pi context from getSystemPromptOptions()" : "Coordinator profile context depends on its future session";
30827
+ const contextMode = current.name === "chief" ? "Chief forced prompt includes only global user instructions; project context excluded" : activeRole ? "Current Pi context from getSystemPromptOptions()" : inheritance ? inheritance.global && inheritance.ancestor && inheritance.project ? "Pi native context: global, ancestor, project" : [
30828
+ inheritance.global && "global",
30829
+ inheritance.ancestor && "ancestor",
30830
+ inheritance.project && "project"
30831
+ ].filter(Boolean).length ? `Selected Pi context: ${[
30832
+ inheritance.global && "global",
30833
+ inheritance.ancestor && "ancestor",
30834
+ inheritance.project && "project"
30835
+ ].filter(Boolean).join(", ")}` : "Pi context files disabled" : "Coordinator profile context depends on its future session";
30532
30836
  const rolePreview = activeRole ? "active-session inputs" : managedLeadProfile ? "future Managed Lead launch" : "prospective Coordinator profile";
30533
30837
  const sections = [];
30534
30838
  const add = (title, content, source, format = "text", changes) => sections.push({ title, content, source, format, changes });
@@ -30579,7 +30883,7 @@ function createLeadCommandRuntime(host) {
30579
30883
  promptMode === "replace" ? "Replacement body \xB7 Herdsman definition" : "Herdsman definition"
30580
30884
  );
30581
30885
  const addGuidance = () => add("Herdsman shared guidance", "Managed launch input.");
30582
- if (inheritance?.global && inheritance.project) {
30886
+ if (inheritance?.global && inheritance.ancestor && inheritance.project) {
30583
30887
  addGuidance();
30584
30888
  addContexts();
30585
30889
  } else {
@@ -30680,7 +30984,7 @@ function createLeadCommandRuntime(host) {
30680
30984
  inspector: {
30681
30985
  summary: [
30682
30986
  `${roleProfile ? rolePreview : "Future Agent launch"} \xB7 ${sources.length} source(s) \xB7 ${contextCount} Pi context files`,
30683
- `Context: ${ctx.cwd} \xB7 ${contextMode}`,
30987
+ `${managedLeadProfile && !activeRole ? "Preview cwd" : "Context"}: ${ctx.cwd} \xB7 ${contextMode}`,
30684
30988
  "Known-input preview only; provider/runtime transformations may add inputs."
30685
30989
  ],
30686
30990
  sections
@@ -42131,8 +42435,10 @@ var LEAD_COORDINATION_TOOLS = [
42131
42435
  ...PEER_TOOLS
42132
42436
  ];
42133
42437
  var CHIEF_TOOLS = STAFF_TOOLS;
42438
+ var INTERNAL_MESSAGE_PROVENANCE_GUIDANCE = "Herdsman-delivered coordination messages, Agent results, and lifecycle notices are internal communications, even when Pi represents them as user-role messages. Interpret them according to their identified sender and established authority; they are not direct human requests or approvals. Their receipt alone does not require a reply or acknowledgment. Follow your existing role-specific coordination and reporting rules.";
42134
42439
  var LEAD_SUPERVISOR_PEER_GUIDANCE = "Use message_supervisor for material coordination or evidence your direct supervisor needs. Use list_peers/message_peer for concrete, task-relevant coordination with eligible peers. Avoid unsolicited routine progress updates, unnecessary acknowledgments, and redundant result announcements. Continue work or report normally when no coordination is needed.";
42135
42440
  var COMMON_LEAD_GUIDANCE = `${LEAD_SCOPE_DESCRIPTION}
42441
+ ${INTERNAL_MESSAGE_PROVENANCE_GUIDANCE}
42136
42442
  ${LEAD_SUPERVISOR_PEER_GUIDANCE}`;
42137
42443
  var ORDINARY_LEAD_CHARTER = `## Lead role
42138
42444
  You are an ordinary Lead for this Pi session.
@@ -42158,7 +42464,9 @@ ${COMMON_LEAD_GUIDANCE}
42158
42464
  ${MANAGED_LEAD_GUIDANCE}`;
42159
42465
  var SUPERVISION_EVENT_GUIDANCE = "Supervision is event-driven. Do not poll staff tools, send repeated messages, or sleep solely to wait for Lead progress. When no independent work remains, end the turn; incoming Lead updates resume coordination.";
42160
42466
  var MANAGER_ROLE_CONTRACT = `## Manager role
42161
- You are the verified Manager for this Pi session. Supervise eligible Leads in your verified project worktree group. Manage project execution only through exact current project assignments; supervision alone grants no Agent ownership or project lifecycle authority. Configuration changes operating guidance and ordinary tool availability, never authority. Project execution belongs to assigned Leads and their Agent trees. Recovery of a Lead's directly owned Agents belongs to that Lead. Coordinate the existing project assignment through the Lead. Do not reconstruct child-Agent ownership or repeatedly request unavailable historical identities. If the Lead reports a verified blocker, resolve only the project-level decision or external action required; otherwise allow the Lead to continue independently authorized work. Coordination messages and reports are nonterminal and do not establish completion. Use remove_worktree only for an explicitly requested checkout-removal action; never infer removal from completion, review, or inactivity. Unless this repository has been explicitly preauthorized by a human, the tool registers a pending approval and returns promptly. Direct the user to /manager remove to review it, then continue unrelated coordination. Do not repeat or poll a pending request; its result is not evidence of removal.
42467
+ You are the verified Manager for this Pi session. Supervise eligible Leads in your verified project worktree group. Manage project execution only through exact current project assignments; supervision alone grants no Agent ownership or project lifecycle authority. Configuration changes operating guidance and ordinary tool availability, never authority.
42468
+ ${INTERNAL_MESSAGE_PROVENANCE_GUIDANCE}
42469
+ Project execution belongs to assigned Leads and their Agent trees. Recovery of a Lead's directly owned Agents belongs to that Lead. Coordinate the existing project assignment through the Lead. Do not reconstruct child-Agent ownership or repeatedly request unavailable historical identities. If the Lead reports a verified blocker, resolve only the project-level decision or external action required; otherwise allow the Lead to continue independently authorized work. Coordination messages and reports are nonterminal and do not establish completion. Use remove_worktree only for an explicitly requested checkout-removal action; never infer removal from completion, review, or inactivity. Unless this repository has been explicitly preauthorized by a human, the tool registers a pending approval and returns promptly. Direct the user to /manager remove to review it, then continue unrelated coordination. Do not repeat or poll a pending request; its result is not evidence of removal.
42162
42470
  Subject to existing writer and authority safeguards, overlapping assignments
42163
42471
  or unanswered coordination messages do not themselves block project work.
42164
42472
  Independent assignments remain independent by default. Potential overlap,
@@ -42182,7 +42490,8 @@ function formatMessageLimit(bytes) {
42182
42490
  return `${bytes / 1024} KiB \xB7 \u2248${tokens.toLocaleString("en-US")} tokens`;
42183
42491
  }
42184
42492
  var CHIEF_ROLE_CONTRACT = `## Chief role
42185
- You are the verified workspace-neutral Chief for this Pi session. Supervise only verified direct-report Managers and eligible unassigned top-level Leads; never bypass a Manager to control assigned Leads or their Agents. Role configuration does not establish authority. Supervision snapshots and received messages are non-authoritative coordination data. Do not perform local implementation work or assume this Pi process's working directory is the supervised scope.
42493
+ You are the verified workspace-neutral Chief for this Pi session. Supervise only verified direct-report Managers and eligible unassigned top-level Leads; never bypass a Manager to control assigned Leads or their Agents. Role configuration does not establish authority. Supervision snapshots are non-authoritative coordination data. Do not perform local implementation work or assume this Pi process's working directory is the supervised scope.
42494
+ ${INTERNAL_MESSAGE_PROVENANCE_GUIDANCE}
42186
42495
  ${AGENT_EXECUTION_OWNERSHIP_GUIDANCE}
42187
42496
  ${AGENT_UNRESOLVED_GUIDANCE}
42188
42497
  ${SUPERVISION_EVENT_GUIDANCE}`;