pi-herdsman 0.33.0 → 0.33.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/README.md CHANGED
@@ -7,14 +7,14 @@
7
7
  [![Platforms](https://img.shields.io/badge/platforms-Linux%20%7C%20macOS%20%7C%20Windows-blue)](https://github.com/boadij/pi-herdsman/actions/workflows/validate.yml)
8
8
  [![License](https://img.shields.io/npm/l/pi-herdsman)](LICENSE)
9
9
 
10
- Pi Herdsman lets your AI coding assistant delegate tasks to other assistants
11
- running in the background, while you continue using your main conversation.
12
- Start with one Agent, or coordinate independent work across a larger project.
10
+ **The orchestration layer between [Pi](https://github.com/earendil-works/pi) and [herdr](https://github.com/herdrdev/herdr).**
13
11
 
14
- [Pi](https://github.com/earendil-works/pi) runs the coding assistants,
15
- [herdr](https://github.com/herdrdev/herdr)
16
- manages their terminal sessions and workspaces, and Herdsman coordinates their
17
- work.
12
+ Pi Herdsman lets your AI coding assistant delegate tasks to background Agents
13
+ while your main conversation stays interactive. Start with one Agent, or
14
+ coordinate parallel, branch-based project work across independent Leads.
15
+
16
+ Pi runs the coding-agent conversations; herdr manages their terminal sessions
17
+ and workspaces; Herdsman coordinates delegation, ownership, and supervision.
18
18
 
19
19
  ## Demo
20
20
 
@@ -28,7 +28,7 @@ _Advanced orchestration: a live Manager → Lead → Agent workflow._
28
28
  - **Parallel and nested delegation.** Run independent work concurrently and let explicitly enabled Agents delegate their own bounded subtasks.
29
29
  - **Project orchestration.** A Manager coordinates durable branch-based work across independent Leads and their Agent trees.
30
30
  - **Direct supervision.** Chief, Manager, Lead, and Agent responsibilities stay explicit instead of collapsing into one global controller.
31
- - **Peer communication.** Leads can exchange messages locally; Managers can also collaborate across connected machines.
31
+ - **Peer communication.** Leads can message eligible peers locally; unassigned ordinary Leads and Managers can also collaborate across connected machines.
32
32
  - **Owned usage visibility.** Inspect Pi-native token usage and cost for the current session and its transitively owned managed Agents. An active Manager also sees the Leads in its current durable project assignments and their owned Agent trees.
33
33
  - **Your workflow stays yours.** Bring your own Agent definitions, models, tools, skills, extensions, and development process.
34
34
 
package/SKILL.md CHANGED
@@ -58,7 +58,8 @@ Use these high-salience rules for the model-facing agent boundary:
58
58
  requests, steering, sleep, or
59
59
  other waiting mechanisms, and do not invent work merely to remain active.
60
60
 
61
- Ordinary Leads use `list_peers` and `message_peer` for other ordinary Lead sessions;
61
+ Leads use `list_peers` and `message_peer` for eligible same-role peers.
62
+ Managed Leads are limited to their verified project worktree group and socket;
62
63
  managed agents are not peers. `list_peers` identifies this Lead as `self` and
63
64
  returns other live Leads as `peers` with exact session IDs. Incoming peer messages are already
64
65
  addressed to this Lead; `Peer message from <sender lead ID>: <body>` identifies
@@ -179,14 +180,16 @@ objective. Decompose only as far as useful. Reuse adequate existing evidence
179
180
  instead of duplicating work. The active Lead execution profile determines the
180
181
  balance between direct and delegated work. Ordinary Leads use `flexible-lead`
181
182
  or `orchestrator-lead` according to their persisted `flexible` or
182
- `orchestrate` execution mode. Manager-assigned Leads use `managed-lead`; the
183
- exact current `ProjectAssignment`, not the profile, establishes Manager
184
- authority. Managed identity is permanent for the exact Pi session, including
185
- when assignment evidence is unavailable or the assignment is retired. Only a
186
- current exact assignment permits fresh project execution; exactly owned Agent
187
- recovery remains separate. Use native Pi `/fork` or `/clone` for independent
188
- ordinary continuation, not a separate Git checkout or fresh process configuration.
189
- Lead execution configuration does not change Agent ownership semantics.
183
+ `orchestrate` execution mode. These ordinary sessions execute their authorized
184
+ independent Lead work without requiring a `ProjectAssignment`. Manager-assigned
185
+ Leads use `managed-lead`; the exact current `ProjectAssignment`, not the profile,
186
+ establishes Manager authority. Managed identity is permanent for the exact Pi
187
+ session, including when assignment evidence is unavailable or the assignment
188
+ is retired. Only a current exact assignment permits fresh managed project
189
+ execution; exactly owned Agent recovery remains separate. Use native Pi
190
+ `/fork` or `/clone` for independent ordinary continuation, not a separate Git
191
+ checkout or fresh process configuration. Lead execution configuration does
192
+ not change Agent ownership semantics.
190
193
 
191
194
  <!-- pi-herdsman-runtime-lead:end -->
192
195
 
@@ -409,10 +412,10 @@ through `files`.
409
412
  Chief uses `list_staff`, `inspect_staff`, `read_staff_transcript`, and
410
413
  `message_staff`. Manager has those same direct-report tools, peer tools, and
411
414
  `delegate_project`, `resume_project`, and `stop_lead`.
412
- For administrative removal of a project-owned evidence requirement, use the
413
- Manager project-assignment action menu: **Retained evidence**, inspect the
414
- entry, then **Remove** and confirm. Inherited requirements are protected; this
415
- does not delete snapshots or change evidence already accepted by Agents.
415
+ For administrative removal of project-owned evidence, use the Manager's
416
+ **Retained evidence** menu and its **Remove requirement…** action. Inherited
417
+ requirements are protected; snapshots and accepted Agent evidence remain
418
+ unchanged.
416
419
  `inspect_staff` provides bounded live terminal/process evidence;
417
420
  `read_staff_transcript` provides bounded persisted Pi conversation/tool evidence.
418
421
  Target a Lead by the exact full Pi session ID in a fresh snapshot or
@@ -448,9 +451,10 @@ Pi Herdsman uses one durable vocabulary:
448
451
  - a **Manager** explicitly assumes dedicated project coordination from that
449
452
  group's primary workspace and does not own supervised Leads' Agents. It may
450
453
  separately delegate directly to definitions in its effective `agents`
451
- profile. Manager controls only Leads named by current project assignments;
452
- project scope alone does not make a Lead a Manager report. Leads own technical
453
- decisions and orchestrate execution through their Agent trees;
454
+ profile. Project operations control only currently assigned Leads; eligible
455
+ ordinary Leads in the verified worktree group are direct reports for
456
+ observation and communication. Leads own technical decisions and orchestrate
457
+ execution through their Agent trees;
454
458
  - project work belongs to the project, not a Manager session. The project
455
459
  assignment represents open work and its Git branch is the work handle. A
456
460
  Manager uses `delegate_project` with a task and optional branch to start new
@@ -12,5 +12,9 @@ human's objectives.
12
12
  Interpret reports, resolve cross-project priorities and decisions, and
13
13
  synthesize useful outcomes for the human.
14
14
 
15
+ When eligible same-role direct reports need technical coordination, prefer
16
+ having them communicate directly rather than relaying their messages.
17
+ Retain cross-project priorities, decisions, and synthesis.
18
+
15
19
  Prefer focused coordination over unnecessary intervention. Treat routine
16
20
  progress as informational.
@@ -8,8 +8,11 @@ tools: []
8
8
 
9
9
  Coordinate assigned project work through Leads.
10
10
 
11
- Set priorities, resolve project-level decisions and dependencies, review
12
- outcomes, and request corrections through the responsible Lead.
11
+ Set priorities, resolve project-level decisions and dependency sequencing,
12
+ review outcomes, and request corrections through the responsible Lead.
13
+ When assigned Leads need to exchange technical information, prefer having
14
+ them coordinate directly when eligible; mediate when project-level decisions
15
+ or unavailable peer communication require it.
13
16
  Leave technical investigation, implementation, review, validation, and
14
17
  integration to that Lead and its Agents rather than doing or delegating
15
18
  the work yourself.
package/dist/index.js CHANGED
@@ -718,8 +718,26 @@ function acquireProcessLock(path, options2 = {}) {
718
718
  let staleOwner;
719
719
  try {
720
720
  staleOwner = readProcessLockOwner(claimDir, observedOwner);
721
- } catch {
722
- throw new Error(verifyMessage);
721
+ } catch (error3) {
722
+ if (error3.code === "ENOENT") {
723
+ let currentOwner;
724
+ try {
725
+ ({ owner: currentOwner } = lockOwnerEntry(claimDir));
726
+ } catch (checkError) {
727
+ if (checkError.code === "ENOENT")
728
+ throw new ProcessLockOccupiedError(occupiedMessage);
729
+ throw new Error(verifyMessage, { cause: checkError });
730
+ }
731
+ if (currentOwner !== observedOwner) {
732
+ try {
733
+ readProcessLockOwner(claimDir, currentOwner);
734
+ } catch (checkError) {
735
+ throw new Error(verifyMessage, { cause: checkError });
736
+ }
737
+ throw new ProcessLockOccupiedError(occupiedMessage);
738
+ }
739
+ }
740
+ throw new Error(verifyMessage, { cause: error3 });
723
741
  }
724
742
  try {
725
743
  if (processOwnerExists(staleOwner))
@@ -3173,9 +3191,13 @@ async function listAllHerdrAgents(pi, ctx, signal) {
3173
3191
  async function herdrSessionSnapshot(pi, ctx, signal) {
3174
3192
  const result = await runHerdr(pi, ctx, ["api", "snapshot"], { signal });
3175
3193
  const snapshot = result?.snapshot;
3176
- if (!Array.isArray(snapshot?.panes) || !Array.isArray(snapshot?.agents))
3194
+ if (!Array.isArray(snapshot?.panes) || !Array.isArray(snapshot?.agents) || !Array.isArray(snapshot?.workspaces))
3177
3195
  error("session snapshot", "Herdr session inventory is unavailable");
3178
- return { panes: snapshot.panes, agents: snapshot.agents };
3196
+ return {
3197
+ panes: snapshot.panes,
3198
+ agents: snapshot.agents,
3199
+ workspaces: snapshot.workspaces
3200
+ };
3179
3201
  }
3180
3202
  function watchHerdrLifecycle(socketPath2, signal, onChange) {
3181
3203
  let socket;
@@ -4853,7 +4875,7 @@ function projectWorkspaceProvenance(workspaceId, workspace2, worktreeInfo, fallb
4853
4875
  );
4854
4876
  const repoName = typeof worktree.repo_name === "string" ? worktree.repo_name : typeof worktreeInfo?.source?.repo_name === "string" ? worktreeInfo.source.repo_name : void 0;
4855
4877
  const branch = typeof currentWorktree?.branch === "string" ? currentWorktree.branch : void 0;
4856
- const workspaceCwd = typeof worktreeInfo?.source?.source_checkout_path === "string" ? worktreeInfo.source.source_checkout_path : fallbackCwd;
4878
+ const workspaceCwd = typeof currentWorktree?.path === "string" ? currentWorktree.path : typeof worktree?.checkout_path === "string" ? worktree.checkout_path : fallbackCwd;
4857
4879
  return {
4858
4880
  ...workspaceLabel ? { workspaceLabel } : {},
4859
4881
  ...workspaceCwd ? { workspaceCwd } : {},
@@ -10421,6 +10443,11 @@ function withProjectAssignmentLock(operation) {
10421
10443
  lease.release();
10422
10444
  }
10423
10445
  }
10446
+ function withCurrentProjectAssignment(runtime, repoKey, branch, operation) {
10447
+ return withProjectAssignmentLock(
10448
+ () => operation(readProjectAssignment(runtime, repoKey, branch))
10449
+ );
10450
+ }
10424
10451
  function peerRuntime(_socket) {
10425
10452
  const root2 = join8(herdsmanDataRoot(), "runtime", "peers-v2");
10426
10453
  return {
@@ -14518,8 +14545,16 @@ function createAgentController(pi, options2) {
14518
14545
  fail("internal_failure", message, operation);
14519
14546
  }
14520
14547
  }
14521
- await submitOptions.beforeWrite?.();
14522
- writeRequest(runtime.mailboxPath, request);
14548
+ let requestWritten = false;
14549
+ const publish = () => {
14550
+ if (requestWritten)
14551
+ fail("internal_failure", "Request was already published", operation);
14552
+ writeRequest(runtime.mailboxPath, request);
14553
+ requestWritten = true;
14554
+ options2.afterRequestPublishedForTest?.(runtime.mailboxPath, request);
14555
+ };
14556
+ await submitOptions.beforeWrite?.(publish);
14557
+ if (!requestWritten) publish();
14523
14558
  } catch (error2) {
14524
14559
  if (String(error2).toLowerCase().includes("too large"))
14525
14560
  fail(
@@ -17153,7 +17188,7 @@ ${result.stderr ?? ""}`.trim(),
17153
17188
  {
17154
17189
  waitForLock: true,
17155
17190
  evidence: evidenceMetadata,
17156
- beforeWrite: async () => {
17191
+ beforeWrite: async (publish) => {
17157
17192
  assertRootDelegationAllowed();
17158
17193
  if (nestedEvidence) {
17159
17194
  const current = currentManagedEvidence(ctx);
@@ -17224,6 +17259,18 @@ ${result.stderr ?? ""}`.trim(),
17224
17259
  throw new Error(
17225
17260
  "Project assignment or required evidence changed during Agent startup; retry delegation"
17226
17261
  );
17262
+ if (scope.kind === "root")
17263
+ current.publishIfCurrent((latest) => {
17264
+ if (!latest || latest.id !== current.assignment.id || !resumed && (JSON.stringify(latest.requiredEvidence ?? []) !== JSON.stringify(
17265
+ current.assignment.requiredEvidence ?? []
17266
+ ) || JSON.stringify(latest.currentEvidenceIds ?? []) !== JSON.stringify(
17267
+ current.assignment.currentEvidenceIds ?? []
17268
+ )))
17269
+ throw new Error(
17270
+ "Project assignment or required evidence changed during Agent startup; retry delegation"
17271
+ );
17272
+ publish();
17273
+ });
17227
17274
  });
17228
17275
  }
17229
17276
  }
@@ -18845,10 +18892,6 @@ blockers, remaining work, and reusable paths or artifacts.`;
18845
18892
  and final technical decisions within your assigned objective. Integrate resolved Agent results and
18846
18893
  carry relevant evidence into onward handoffs. Decompose only as far as useful.
18847
18894
  Reuse adequate existing evidence instead of duplicating work.
18848
- Managed identity is permanent for the exact Pi session. Only a current exact
18849
- ProjectAssignment permits fresh project execution; exactly owned Agent recovery
18850
- remains separate. Use native Pi /fork or /clone for independent ordinary
18851
- continuation; this does not create a separate Git checkout or fresh process configuration.
18852
18895
  Your herd is your internal team: you and your recursively owned Agents.
18853
18896
  Any review conducted within the herd is internal feedback, not user or supervisor
18854
18897
  review or approval.`;
@@ -21440,7 +21483,7 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
21440
21483
  // package.json
21441
21484
  var package_default = {
21442
21485
  name: "pi-herdsman",
21443
- version: "0.33.0",
21486
+ version: "0.33.1",
21444
21487
  type: "module",
21445
21488
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
21446
21489
  license: "Apache-2.0",
@@ -24305,18 +24348,27 @@ function registerLeadRuntime(pi, options2) {
24305
24348
  throw new Error(
24306
24349
  "Managed project execution requires a current exact assignment"
24307
24350
  );
24308
- const migrated = migrateProjectAssignmentEvidence(
24351
+ const needsMigration = assignment.requiredEvidence?.some(
24352
+ (evidence) => !("result" in evidence) && !evidence.ref
24353
+ );
24354
+ const migrated = needsMigration ? migrateProjectAssignmentEvidence(
24309
24355
  options2.coordinationHost.supervisionRuntime(),
24310
24356
  assignment.repoKey,
24311
24357
  assignment.branch,
24312
24358
  assignment.id
24313
- );
24359
+ ) : assignment;
24314
24360
  if (!migrated || migrated.id !== assignment.id)
24315
24361
  throw new Error(
24316
24362
  "Managed project execution requires a current exact assignment"
24317
24363
  );
24318
24364
  return {
24319
24365
  assignment: migrated,
24366
+ publishIfCurrent: (operation) => withCurrentProjectAssignment(
24367
+ options2.coordinationHost.supervisionRuntime(),
24368
+ assignment.repoKey,
24369
+ assignment.branch,
24370
+ operation
24371
+ ),
24320
24372
  revalidate: (operation) => roleTransitions.withProjectAssignmentLock(
24321
24373
  assignment.repoKey,
24322
24374
  assignment.branch,
@@ -25120,6 +25172,7 @@ function registerLeadRuntime(pi, options2) {
25120
25172
  remoteChiefAgent,
25121
25173
  liveLead,
25122
25174
  setLeadExecutionMode,
25175
+ sessionKindForPrompt: (ctx) => sessionKind?.sessionId === ctx.sessionManager.getSessionId() ? sessionKind.kind : void 0,
25123
25176
  leadExecutionPresentation: () => sessionKind?.kind === "managed" ? {
25124
25177
  managed: true,
25125
25178
  mode: leadExecution?.mode ?? "orchestrate",
@@ -25289,7 +25342,8 @@ function createLeadSupervisionRuntime(host) {
25289
25342
  ctx,
25290
25343
  [...new Set(agents.map((agent) => agent.workspaceId))],
25291
25344
  workspaceCwds,
25292
- ctx.signal
25345
+ ctx.signal,
25346
+ inventory.workspaces
25293
25347
  );
25294
25348
  const diagnostics = live.some(
25295
25349
  (agent) => (agent?.agent === "pi" || agent?.agent_session?.agent === "pi") && !host.isPiAgent(agent)
@@ -30695,9 +30749,11 @@ ${receivedRefs.join("\n")}` : ""}`,
30695
30749
  (item) => (item.role ?? "manager") === activeRole() && matchesReturnRecipient(item, sender) && item.originSession === params.session
30696
30750
  ) : [];
30697
30751
  const target = remoteRoute ? void 0 : await livePeerLead(ctx, params.session);
30698
- if (!sender || (sender.role ?? "lead") !== activeRole() || (remoteRoute ? remoteRoute.role !== activeRole() || ambiguousRemoteSessions.has(params.session) : (!target || (target.role ?? "lead") !== activeRole()) && returnCorrespondences.length !== 1))
30752
+ const noAuthorizedLocalTarget = (!target || (target.role ?? "lead") !== activeRole()) && returnCorrespondences.length !== 1;
30753
+ const rejection = !sender ? "sender_unavailable" : (sender.role ?? "lead") !== activeRole() ? "sender_role_changed" : remoteRoute ? remoteRoute.role !== activeRole() ? "route_role_mismatch" : ambiguousRemoteSessions.has(params.session) ? "route_ambiguous" : void 0 : noAuthorizedLocalTarget ? ambiguousRemoteSessions.has(params.session) ? "route_ambiguous" : "no_authorized_target" : void 0;
30754
+ if (rejection)
30699
30755
  throw new Error(
30700
- "Peer target was not found or is no longer a live same-role peer"
30756
+ `Peer target was not found or is no longer a live same-role peer [${rejection}]`
30701
30757
  );
30702
30758
  const recordId = randomUUID14();
30703
30759
  const createdAt = Date.now();
@@ -33544,27 +33600,25 @@ var LEAD_COORDINATION_TOOLS = [
33544
33600
  ];
33545
33601
  var CHIEF_TOOLS = STAFF_TOOLS;
33546
33602
  var LEAD_SUPERVISOR_PEER_GUIDANCE = "Use message_supervisor for material nonblocking coordination with your direct supervisor. Use list_peers/message_peer for peer coordination.";
33547
- var LEAD_ROLE_CHARTER = `## Lead role
33548
- You are the Lead for this Pi session.
33549
- ${LEAD_SCOPE_DESCRIPTION}
33603
+ var COMMON_LEAD_GUIDANCE = `${LEAD_SCOPE_DESCRIPTION}
33550
33604
  ${LEAD_SUPERVISOR_PEER_GUIDANCE}
33605
+ ${FILE_HANDOFF_GUIDANCE}`;
33606
+ var ORDINARY_LEAD_CHARTER = `## Lead role
33607
+ You are an ordinary Lead for this Pi session.
33608
+ ${COMMON_LEAD_GUIDANCE}
33609
+ Your Agent assignments and file handoffs are recipient-specific. Peer messages coordinate work but do not independently transfer execution ownership.`;
33610
+ var MANAGED_LEAD_GUIDANCE = `Managed Lead identity is permanent for this exact Pi session. Only a current exact ProjectAssignment permits fresh managed project execution; unavailable or retired assignment state does not grant ordinary Lead execution authority. Exactly owned Agent recovery remains separate. Use native Pi /fork or /clone for independent ordinary continuation; this does not create a separate Git checkout or fresh process configuration.
33551
33611
  For a verified managed project assignment, required project evidence is automatically inherited by newly accepted descendant Agent assignments.
33552
- Ordinary Leads have no automatic required-evidence scope.
33553
33612
  A Lead's delegation task and ordinary files are recipient-specific; they do not create project-wide requirements.
33554
33613
  Only the Manager can designate continuing project requirements.
33555
- Send proposed continuing requirements and available supporting
33556
- evidence to the Manager for evaluation.
33557
- For assigned project work, include routine proposed requirements,
33558
- completion, and review readiness in your normal response;
33559
- Herdsman delivers it to the Manager automatically.
33560
- For assigned project work, use message_supervisor for timely
33561
- coordination or explicit evidence transfer, not for a separate
33562
- completion announcement.
33563
- For assigned project work, automatic result handoffs contain summary
33564
- text but no file attachments. When the Manager needs an actual artifact
33565
- for review, decision-making, or onward delegation, explicitly transfer
33566
- the relevant evidence through message_supervisor.files.
33567
- ${FILE_HANDOFF_GUIDANCE}`;
33614
+ Send proposed continuing requirements and available supporting evidence to the Manager for evaluation.
33615
+ For assigned project work, include routine proposed requirements, completion, and review readiness in your normal response; Herdsman delivers it to the Manager automatically.
33616
+ For assigned project work, use message_supervisor for timely coordination or explicit evidence transfer, not for a separate completion announcement.
33617
+ For assigned project work, automatic result handoffs contain summary text but no file attachments. When the Manager needs an actual artifact for review, decision-making, or onward delegation, explicitly transfer the relevant evidence through message_supervisor.files.`;
33618
+ var MANAGED_LEAD_CHARTER = `## Lead role
33619
+ You are a Managed Lead for this Pi session.
33620
+ ${COMMON_LEAD_GUIDANCE}
33621
+ ${MANAGED_LEAD_GUIDANCE}`;
33568
33622
  var SUPERVISION_EVENT_GUIDANCE = "Supervision is event-driven. Do not poll staff tools, send repeated messages, or sleep solely to wait for Lead progress. When no independent work remains, end the turn; incoming Lead updates resume coordination.";
33569
33623
  var MANAGER_ROLE_CONTRACT = `## Manager role
33570
33624
  You are the verified Manager for this Pi session. Supervise eligible Leads in your verified project worktree group. Manage project execution only through exact current project assignments; supervision alone grants no Agent ownership or project lifecycle authority. Configuration changes operating guidance and ordinary tool availability, never authority. Project execution belongs to assigned Leads and their Agent trees. Coordination messages and reports are nonterminal and do not establish completion. Use remove_worktree only for an explicitly requested checkout-removal action; never infer removal from completion, review, or inactivity. Unless this repository has been explicitly preauthorized by a human, the tool registers a pending approval and returns promptly. Direct the user to /manager remove to review it, then continue unrelated coordination. Do not repeat or poll a pending request; its result is not evidence of removal.
@@ -33670,67 +33724,94 @@ function expectedSession2(id, path) {
33670
33724
  function isPiAgent(agent) {
33671
33725
  return sessionIdentity(agent?.agent_session) !== void 0;
33672
33726
  }
33673
- async function workspacePresentationProvenance(pi, ctx, workspaceIds, workspaceCwds, signal) {
33674
- const entries = await Promise.all(
33675
- workspaceIds.map(async (workspaceId) => {
33676
- let workspace2;
33677
- try {
33678
- workspace2 = (await runHerdr(pi, ctx, ["workspace", "get", workspaceId], {
33679
- signal
33680
- }))?.workspace;
33681
- } catch {
33682
- return [
33683
- workspaceId,
33684
- projectWorkspaceProvenance(
33727
+ async function workspacePresentationProvenance(pi, ctx, workspaceIds, workspaceCwds, signal, snapshotWorkspaces) {
33728
+ const workspaces = /* @__PURE__ */ new Map();
33729
+ if (snapshotWorkspaces) {
33730
+ for (const workspace2 of snapshotWorkspaces)
33731
+ if (typeof workspace2?.workspace_id === "string")
33732
+ workspaces.set(workspace2.workspace_id, workspace2);
33733
+ } else {
33734
+ const records = await Promise.all(
33735
+ workspaceIds.map(async (workspaceId) => {
33736
+ try {
33737
+ return [
33685
33738
  workspaceId,
33686
- void 0,
33687
- void 0,
33688
- workspaceCwds.get(workspaceId)
33689
- )
33690
- ];
33691
- }
33692
- if (!hasWorkspaceWorktree(workspace2))
33693
- return [
33739
+ (await runHerdr(pi, ctx, ["workspace", "get", workspaceId], {
33740
+ signal
33741
+ }))?.workspace
33742
+ ];
33743
+ } catch {
33744
+ return [workspaceId, void 0];
33745
+ }
33746
+ })
33747
+ );
33748
+ for (const [workspaceId, workspace2] of records)
33749
+ if (workspace2) workspaces.set(workspaceId, workspace2);
33750
+ }
33751
+ const sources = /* @__PURE__ */ new Map();
33752
+ for (const workspaceId of new Set(workspaceIds)) {
33753
+ const workspace2 = workspaces.get(workspaceId);
33754
+ if (!workspace2) continue;
33755
+ const repoKey = workspace2?.worktree?.repo_key;
33756
+ const repoRoot = workspace2?.worktree?.repo_root;
33757
+ if (typeof repoKey !== "string" || !repoKey || typeof repoRoot !== "string" || !repoRoot)
33758
+ continue;
33759
+ const key = `${repoKey}\0${repoRoot}`;
33760
+ if (!sources.has(key)) sources.set(key, { workspaceId, repoKey, repoRoot });
33761
+ }
33762
+ const topologyByRepo = /* @__PURE__ */ new Map();
33763
+ for (const [key, source] of sources) {
33764
+ if (signal?.aborted) break;
33765
+ try {
33766
+ const topology = await runHerdr(
33767
+ pi,
33768
+ ctx,
33769
+ ["worktree", "list", "--workspace", source.workspaceId],
33770
+ { signal }
33771
+ );
33772
+ if (topology?.source?.repo_key === source.repoKey && topology?.source?.repo_root === source.repoRoot && Array.isArray(topology?.worktrees))
33773
+ topologyByRepo.set(key, topology);
33774
+ } catch {
33775
+ }
33776
+ }
33777
+ const topologyByWorkspace = /* @__PURE__ */ new Map();
33778
+ if (!snapshotWorkspaces)
33779
+ for (const workspaceId of new Set(workspaceIds)) {
33780
+ const workspace2 = workspaces.get(workspaceId);
33781
+ const repoKey = workspace2?.worktree?.repo_key;
33782
+ const repoRoot = workspace2?.worktree?.repo_root;
33783
+ if (!hasWorkspaceWorktree(workspace2) || typeof repoKey === "string" && repoKey && typeof repoRoot === "string" && repoRoot)
33784
+ continue;
33785
+ try {
33786
+ topologyByWorkspace.set(
33694
33787
  workspaceId,
33695
- projectWorkspaceProvenance(
33696
- workspaceId,
33697
- workspace2,
33698
- void 0,
33699
- workspaceCwds.get(workspaceId)
33788
+ await runHerdr(
33789
+ pi,
33790
+ ctx,
33791
+ ["worktree", "list", "--workspace", workspaceId],
33792
+ { signal }
33700
33793
  )
33701
- ];
33702
- let worktreeInfo;
33703
- try {
33704
- worktreeInfo = await runHerdr(
33705
- pi,
33706
- ctx,
33707
- ["worktree", "list", "--workspace", workspaceId],
33708
- { signal }
33709
33794
  );
33710
33795
  } catch {
33711
- return [
33712
- workspaceId,
33713
- projectWorkspaceProvenance(
33714
- workspaceId,
33715
- workspace2,
33716
- void 0,
33717
- workspaceCwds.get(workspaceId),
33718
- true
33719
- )
33720
- ];
33721
33796
  }
33797
+ }
33798
+ return new Map(
33799
+ workspaceIds.map((workspaceId) => {
33800
+ const workspace2 = workspaces.get(workspaceId);
33801
+ const repoKey = workspace2?.worktree?.repo_key;
33802
+ const repoRoot = workspace2?.worktree?.repo_root;
33803
+ const key = typeof repoKey === "string" && typeof repoRoot === "string" ? `${repoKey}\0${repoRoot}` : void 0;
33722
33804
  return [
33723
33805
  workspaceId,
33724
33806
  projectWorkspaceProvenance(
33725
33807
  workspaceId,
33726
33808
  workspace2,
33727
- worktreeInfo,
33809
+ (key ? topologyByRepo.get(key) : void 0) ?? topologyByWorkspace.get(workspaceId),
33728
33810
  workspaceCwds.get(workspaceId)
33729
33811
  )
33730
33812
  ];
33731
33813
  })
33732
33814
  );
33733
- return new Map(entries);
33734
33815
  }
33735
33816
  function registerExtensionForTest(pi, lockHooks) {
33736
33817
  registerExtensionImpl(pi, lockHooks);
@@ -33871,6 +33952,7 @@ If needed, install the Pi integration once:
33871
33952
  }
33872
33953
  const controllerScope = processRole === "lead" ? { kind: "root" } : void 0;
33873
33954
  const controllerServices = {
33955
+ afterRequestPublishedForTest: lockHooks?.afterRequestPublished,
33874
33956
  extensionPath: HERDSMAN_EXTENSION_PATH,
33875
33957
  isContextRetired: (manager) => retiredManagedSession(manager),
33876
33958
  snapshotDependencies: {
@@ -34351,9 +34433,15 @@ ${globalInstructions}
34351
34433
  if (leadRuntime.roleSuspended || role2 === "chief" && !isCurrentChief(ctx) || role2 === "manager" && !leadRuntime.managerLease)
34352
34434
  return `## Herdsman role
34353
34435
  No active Herdsman role is verified for this Pi session.`;
34354
- return role2 === "manager" ? `${MANAGER_ROLE_CONTRACT}
34436
+ if (role2 === "manager")
34437
+ return `${MANAGER_ROLE_CONTRACT}
34355
34438
 
34356
- ${leadRuntimes.supervisoryProfileBody(ctx, "manager")}` : LEAD_ROLE_CHARTER;
34439
+ ${leadRuntimes.supervisoryProfileBody(ctx, "manager")}`;
34440
+ const kind = leadRuntimes.sessionKindForPrompt(ctx);
34441
+ if (kind === "ordinary") return ORDINARY_LEAD_CHARTER;
34442
+ if (kind === "managed") return MANAGED_LEAD_CHARTER;
34443
+ return `## Herdsman role
34444
+ No active Herdsman role is verified for this Pi session.`;
34357
34445
  },
34358
34446
  supervisoryProfileBody: (ctx, role2) => leadRuntimes.supervisoryProfileBody(ctx, role2),
34359
34447
  currentChiefAllowedTools: (ctx) => leadRuntimes.currentChiefAllowedTools(ctx),
@@ -35253,6 +35341,7 @@ ${summary}`,
35253
35341
  }
35254
35342
  export {
35255
35343
  extension_default as default,
35256
- registerExtensionForTest
35344
+ registerExtensionForTest,
35345
+ workspacePresentationProvenance
35257
35346
  };
35258
35347
  //# sourceMappingURL=index.js.map