@luminascale/shepherd 0.0.0-stage → 0.6.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.
Files changed (203) hide show
  1. package/.agents/agents/README.md +12 -0
  2. package/.agents/agents/planner.md +38 -0
  3. package/.agents/agents/reviewer.md +38 -0
  4. package/.agents/agents/scout.md +43 -0
  5. package/.agents/agents/worker.md +33 -0
  6. package/.agents/skills/smoke-test/SKILL.md +155 -0
  7. package/.agents/skills/smoke-test/references/forensics.md +46 -0
  8. package/.agents/skills/smoke-test/scripts/live-smoke-poll.mjs +130 -0
  9. package/.github/workflows/publish.yml +77 -0
  10. package/.pi/prompts/release.md +21 -0
  11. package/.prettierrc +10 -0
  12. package/AGENTS.md +88 -0
  13. package/CONTRIBUTING.md +177 -0
  14. package/LICENSE +201 -0
  15. package/README.md +424 -2
  16. package/docs/README.md +25 -0
  17. package/docs/guides/agent-definitions.md +42 -0
  18. package/docs/guides/diagnostics.md +199 -0
  19. package/docs/guides/tool-reference.md +55 -0
  20. package/docs/manual-tests/ping-pong-peer-messaging.md +147 -0
  21. package/docs/plans/agent-labels.md +257 -0
  22. package/docs/plans/architecture.md +110 -0
  23. package/docs/plans/settings-scope.md +163 -0
  24. package/docs/plans/tool-surface-split.md +278 -0
  25. package/docs/reference/dictionary +26 -0
  26. package/docs/releasing.md +47 -0
  27. package/docs/specs/005-agent-messaging-and-task-lifecycle/baseline.md +115 -0
  28. package/docs/specs/005-agent-messaging-and-task-lifecycle/handoff.md +564 -0
  29. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase10-notes.md +109 -0
  30. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase6-notes.md +69 -0
  31. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase7-notes.md +100 -0
  32. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase8-notes.md +127 -0
  33. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase9-notes.md +104 -0
  34. package/docs/specs/005-agent-messaging-and-task-lifecycle/plan.md +1093 -0
  35. package/docs/specs/005-agent-messaging-and-task-lifecycle/spec.md +583 -0
  36. package/docs/specs/005-agent-messaging-and-task-lifecycle/tasks.md +838 -0
  37. package/docs/specs/006-shepherd-tool-rendering/plan.md +175 -0
  38. package/docs/specs/006-shepherd-tool-rendering/spec.md +469 -0
  39. package/index.ts +599 -0
  40. package/package.json +112 -4
  41. package/scripts/capture-system-prompt.mjs +45 -0
  42. package/scripts/extract-pi-system-prompt.mjs +277 -0
  43. package/scripts/host-impact.mjs +74 -0
  44. package/scripts/resolve-agent.mjs +43 -0
  45. package/scripts/show-shepherd-orchestrator.mjs +58 -0
  46. package/scripts/show-shepherd-prompt.mjs +96 -0
  47. package/scripts/verify-suites.mjs +67 -0
  48. package/specs/001-artifacts/spec.md +436 -0
  49. package/specs/002-simplify-agent-orchestration/plan.md +287 -0
  50. package/specs/002-simplify-agent-orchestration/spec.md +323 -0
  51. package/specs/002-simplify-agent-orchestration/tasks.md +212 -0
  52. package/specs/003-orchestrator-session-artifacts/plan.md +396 -0
  53. package/specs/003-orchestrator-session-artifacts/spec.md +453 -0
  54. package/specs/003-orchestrator-session-artifacts/tasks.md +141 -0
  55. package/specs/004-asynchronous-prompt-watchers/plan.md +139 -0
  56. package/specs/004-asynchronous-prompt-watchers/spec.md +202 -0
  57. package/specs/004-asynchronous-prompt-watchers/tasks.md +126 -0
  58. package/specs/005-per-workspace-settings/plan.md +230 -0
  59. package/specs/005-per-workspace-settings/spec.md +368 -0
  60. package/specs/005-per-workspace-settings/tasks.md +178 -0
  61. package/specs/006-dual-runtime-herdr-durable/intent.md +86 -0
  62. package/specs/006-dual-runtime-herdr-durable/journal.md +80 -0
  63. package/specs/006-dual-runtime-herdr-durable/plan.md +242 -0
  64. package/specs/006-dual-runtime-herdr-durable/spec.md +389 -0
  65. package/specs/006-dual-runtime-herdr-durable/tasks.md +199 -0
  66. package/specs/007-unwatched-completion-notice/journal.md +145 -0
  67. package/specs/007-unwatched-completion-notice/plan.md +186 -0
  68. package/specs/007-unwatched-completion-notice/spec.md +284 -0
  69. package/specs/007-unwatched-completion-notice/tasks.md +147 -0
  70. package/specs/008-remote-machine-sheep/intent.md +174 -0
  71. package/specs/008-remote-machine-sheep/journal.md +57 -0
  72. package/specs/008-remote-machine-sheep/prerequisites.md +219 -0
  73. package/specs/009-hc-runtime/intent.md +44 -0
  74. package/specs/009-hc-runtime/plan.md +49 -0
  75. package/specs/009-hc-runtime/spec.md +118 -0
  76. package/specs/009-hc-runtime/tasks.md +62 -0
  77. package/specs/010-unseen-watch-parity/intent.md +57 -0
  78. package/specs/010-unseen-watch-parity/journal.md +172 -0
  79. package/specs/010-unseen-watch-parity/plan.md +74 -0
  80. package/specs/010-unseen-watch-parity/spec.md +191 -0
  81. package/specs/010-unseen-watch-parity/tasks.md +119 -0
  82. package/specs/011-hc-background-poll/intent.md +57 -0
  83. package/specs/011-hc-background-poll/journal.md +95 -0
  84. package/specs/011-hc-background-poll/plan.md +87 -0
  85. package/specs/011-hc-background-poll/spec.md +141 -0
  86. package/specs/011-hc-background-poll/tasks.md +83 -0
  87. package/specs/012-steer-default/intent.md +12 -0
  88. package/specs/012-steer-default/journal.md +40 -0
  89. package/specs/012-steer-default/plan.md +7 -0
  90. package/specs/012-steer-default/spec.md +42 -0
  91. package/specs/012-steer-default/tasks.md +6 -0
  92. package/specs/013-opencode-shepherd/handoff-t011.md +94 -0
  93. package/specs/013-opencode-shepherd/intent.md +59 -0
  94. package/specs/013-opencode-shepherd/plan.md +204 -0
  95. package/specs/013-opencode-shepherd/spec.md +258 -0
  96. package/specs/013-opencode-shepherd/tasks.md +259 -0
  97. package/src/core/artifact-sessions.ts +835 -0
  98. package/src/core/config.ts +329 -0
  99. package/src/core/discovery.ts +342 -0
  100. package/src/core/herdr.ts +1 -0
  101. package/src/core/host.ts +77 -0
  102. package/src/core/ids.ts +78 -0
  103. package/src/core/lifecycle.ts +1 -0
  104. package/src/core/messaging.ts +1 -0
  105. package/src/core/migration.ts +55 -0
  106. package/src/core/orchestration.ts +1 -0
  107. package/src/core/types.ts +143 -0
  108. package/src/core/unseen-completions.ts +114 -0
  109. package/src/extension/cli.ts +417 -0
  110. package/src/extension/config.ts +1 -0
  111. package/src/extension/settings-ui.ts +296 -0
  112. package/src/extension/shepherd-done.ts +768 -0
  113. package/src/extension/shepherd.ts +2548 -0
  114. package/src/extension/system-prompt.ts +38 -0
  115. package/src/extension/unseen-completions.ts +237 -0
  116. package/src/opencode/actions.ts +794 -0
  117. package/src/opencode/bridge.ts +777 -0
  118. package/src/opencode/display.ts +36 -0
  119. package/src/opencode/fieldnotes.ts +60 -0
  120. package/src/opencode/host.ts +62 -0
  121. package/src/opencode/orphans.ts +162 -0
  122. package/src/opencode/server.ts +458 -0
  123. package/src/runtimes/backend.ts +119 -0
  124. package/src/runtimes/detect.ts +102 -0
  125. package/src/runtimes/hc/hc.ts +527 -0
  126. package/src/runtimes/hc/runtime.ts +1898 -0
  127. package/src/runtimes/herdr/herdr.ts +912 -0
  128. package/src/runtimes/herdr/lifecycle.ts +1712 -0
  129. package/src/runtimes/herdr/messaging.ts +703 -0
  130. package/src/runtimes/herdr/orchestration.ts +1583 -0
  131. package/src/runtimes/herdr/runtime.ts +224 -0
  132. package/src/runtimes/runtime.ts +133 -0
  133. package/src/runtimes/settle-observations.ts +114 -0
  134. package/test/fixtures/context-project/AGENTS.md +2 -0
  135. package/test/fixtures/home/.agents/agents/same.md +6 -0
  136. package/test/fixtures/home/.agents/agents/shared-only.md +6 -0
  137. package/test/fixtures/home/.pi/agent/agents/invalid-thinking.md +6 -0
  138. package/test/fixtures/home/.pi/agent/agents/model-empty.md +7 -0
  139. package/test/fixtures/home/.pi/agent/agents/model-explicit.md +7 -0
  140. package/test/fixtures/home/.pi/agent/agents/omit-context-absent.md +5 -0
  141. package/test/fixtures/home/.pi/agent/agents/omit-context-false.md +6 -0
  142. package/test/fixtures/home/.pi/agent/agents/omit-context-invalid.md +6 -0
  143. package/test/fixtures/home/.pi/agent/agents/omit-context-true.md +6 -0
  144. package/test/fixtures/home/.pi/agent/agents/omit-false.md +6 -0
  145. package/test/fixtures/home/.pi/agent/agents/omit-invalid.md +6 -0
  146. package/test/fixtures/home/.pi/agent/agents/omit-pi-docs.md +7 -0
  147. package/test/fixtures/home/.pi/agent/agents/omit-true.md +6 -0
  148. package/test/fixtures/home/.pi/agent/agents/only-user.md +9 -0
  149. package/test/fixtures/home/.pi/agent/agents/same.md +6 -0
  150. package/test/fixtures/proj/.agents/agents/proj-shared.md +6 -0
  151. package/test/fixtures/proj/.pi/agents/project-pi.md +6 -0
  152. package/test/fixtures/proj/.pi/agents/same.md +6 -0
  153. package/test/helpers/fake-clock.mjs +39 -0
  154. package/test/helpers/feature-contracts.mjs +44 -0
  155. package/test/helpers/test-utils.mjs +44 -0
  156. package/test/verify-artifact-sessions.mjs +258 -0
  157. package/test/verify-backend.mjs +297 -0
  158. package/test/verify-child-mislabel.mjs +135 -0
  159. package/test/verify-child-surface.mjs +321 -0
  160. package/test/verify-cli.mjs +197 -0
  161. package/test/verify-command-ux.mjs +100 -0
  162. package/test/verify-compat.mjs +32 -0
  163. package/test/verify-cross-host-notes.mjs +128 -0
  164. package/test/verify-delegate.mjs +161 -0
  165. package/test/verify-detect.mjs +151 -0
  166. package/test/verify-discovery.mjs +239 -0
  167. package/test/verify-done-nudge.mjs +238 -0
  168. package/test/verify-effective-prompt.mjs +98 -0
  169. package/test/verify-hc-matrix.mjs +246 -0
  170. package/test/verify-hc-poll.mjs +260 -0
  171. package/test/verify-host-docs.mjs +35 -0
  172. package/test/verify-host-impact.mjs +49 -0
  173. package/test/verify-ids.mjs +141 -0
  174. package/test/verify-launch.mjs +183 -0
  175. package/test/verify-message-routing.mjs +560 -0
  176. package/test/verify-messaging.mjs +303 -0
  177. package/test/verify-migration-notice.mjs +69 -0
  178. package/test/verify-multi-wait.mjs +42 -0
  179. package/test/verify-opencode-display.mjs +47 -0
  180. package/test/verify-opencode-fieldnotes.mjs +121 -0
  181. package/test/verify-opencode-notice.mjs +77 -0
  182. package/test/verify-opencode-nudge.mjs +116 -0
  183. package/test/verify-opencode-orphans.mjs +160 -0
  184. package/test/verify-opencode-surface.mjs +107 -0
  185. package/test/verify-packaging.mjs +82 -0
  186. package/test/verify-parent-surface.mjs +118 -0
  187. package/test/verify-phase0.mjs +95 -0
  188. package/test/verify-registry.mjs +124 -0
  189. package/test/verify-rename-migration.mjs +111 -0
  190. package/test/verify-rendering.mjs +379 -0
  191. package/test/verify-session-boundary.mjs +146 -0
  192. package/test/verify-settings.mjs +260 -0
  193. package/test/verify-stale-wait.mjs +339 -0
  194. package/test/verify-status-widget.mjs +377 -0
  195. package/test/verify-status.mjs +172 -0
  196. package/test/verify-task-completion.mjs +156 -0
  197. package/test/verify-task-failures.mjs +201 -0
  198. package/test/verify-task-mislabel.mjs +143 -0
  199. package/test/verify-task-registry.mjs +194 -0
  200. package/test/verify-task-watchers.mjs +217 -0
  201. package/test/verify-tool-schemas.mjs +120 -0
  202. package/test/verify-unseen-completions.mjs +1211 -0
  203. package/test/verify-watchers.mjs +181 -0
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Herdr implementation of the Shepherd runtime contract.
3
+ *
4
+ * Thin delegation layer over the moved Herdr primitives: it introduces no new
5
+ * behavior. Every id accepted or returned here is the same opaque lifecycle id
6
+ * the pi-coding-agent surface exposes; Herdr pane ids stay internal to
7
+ * registry lookups (`read` resolves a handle to its pane only for the
8
+ * diagnostic tail).
9
+ *
10
+ * Mapping notes where the contract and the Herdr primitives do not line up
11
+ * exactly are documented on each method.
12
+ */
13
+
14
+ import type { ShepherdSession } from '../../core/artifact-sessions.ts';
15
+ import type { AgentThinkingLevel } from '../../core/discovery.ts';
16
+ import { readPaneTail } from './herdr.ts';
17
+ import {
18
+ closeAgent,
19
+ delegateAgent,
20
+ sendParentMessage,
21
+ startAgent,
22
+ statusAgent,
23
+ } from './lifecycle.ts';
24
+ import {
25
+ LifecycleError,
26
+ lifecycleRegistry,
27
+ type AgentLifecycleState,
28
+ type AgentStatus,
29
+ type TaskResult,
30
+ type TaskState,
31
+ } from './orchestration.ts';
32
+ import type {
33
+ Completion,
34
+ RuntimeProcState,
35
+ RuntimeStatus,
36
+ RuntimeTaskState,
37
+ ShepherdRuntime,
38
+ } from '../runtime.ts';
39
+
40
+ /**
41
+ * Execution context captured by the adapter for the parent session it serves.
42
+ * `spawn` inherits the parent model/thinking level and the fieldnotes session
43
+ * the same way the pi-coding-agent surface does; `delegate` reuses the parent
44
+ * session identity for its broker.
45
+ */
46
+ export interface HerdrRuntimeContext {
47
+ cwd?: string;
48
+ model?: { provider: string; id: string };
49
+ thinkingLevel?: AgentThinkingLevel;
50
+ hasUI?: boolean;
51
+ ui?: any;
52
+ sessionId?: string;
53
+ /** Parent fieldnotes session, resolved by the calling surface. */
54
+ artifactSession?: ShepherdSession;
55
+ /**
56
+ * Child launch overrides (binary/command/env prefix). The Pi path omits
57
+ * this; other hosts pass their own CLI shape here.
58
+ */
59
+ launch?: {
60
+ binary?: string;
61
+ extensionEntry?: string;
62
+ envPrefix?: string;
63
+ command?: string;
64
+ };
65
+ }
66
+
67
+ function toProcState(state: AgentLifecycleState): RuntimeProcState {
68
+ if (state === 'idle') return 'idle';
69
+ if (state === 'working') return 'working';
70
+ // blocked/done/failed/closed/unknown have no 3-value equivalent.
71
+ return 'unknown';
72
+ }
73
+
74
+ function toTaskState(state: TaskState): RuntimeTaskState {
75
+ switch (state) {
76
+ case 'created':
77
+ case 'running':
78
+ return 'running';
79
+ case 'waiting':
80
+ return 'waiting';
81
+ case 'completed':
82
+ return 'done';
83
+ case 'blocked':
84
+ return 'blocked';
85
+ case 'failed':
86
+ case 'cancelled':
87
+ case 'timed_out':
88
+ return 'failed';
89
+ }
90
+ }
91
+
92
+ function toCompletion(result: TaskResult): Completion {
93
+ const completion: Completion = {
94
+ taskId: result.taskId,
95
+ agentId: result.agentId,
96
+ status: result.status,
97
+ ok: result.ok,
98
+ returnCode: result.returnCode,
99
+ ...(result.text !== undefined ? { text: result.text } : {}),
100
+ ...(result.error !== undefined ? { error: result.error } : {}),
101
+ completedAt: result.completedAt,
102
+ };
103
+ try {
104
+ const handle = lifecycleRegistry.canonicalAgentHandle(result.agentId);
105
+ return {
106
+ ...completion,
107
+ agent: handle.agent,
108
+ ...(handle.label ? { label: handle.label } : {}),
109
+ };
110
+ } catch {
111
+ // Display identity is optional; a retired session simply omits it.
112
+ return completion;
113
+ }
114
+ }
115
+
116
+ function toRuntimeStatus(status: AgentStatus): RuntimeStatus {
117
+ return {
118
+ proc: toProcState(status.state),
119
+ // No open task means no task to run: report the terminal projection.
120
+ task: status.task ? toTaskState(status.task.state) : 'done',
121
+ ...(status.task?.pendingRequestMessageId
122
+ ? { waitingOn: status.task.pendingRequestMessageId }
123
+ : {}),
124
+ ...(status.task?.stale ? { stale: true } : {}),
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Build the Herdr runtime for one parent session context. The adapter holds no
130
+ * state of its own; the lifecycle registries remain the single source of truth.
131
+ */
132
+ export function createHerdrRuntime(context: HerdrRuntimeContext = {}): ShepherdRuntime {
133
+ const cwd = context.cwd ?? process.cwd();
134
+ const execContext = {
135
+ cwd,
136
+ model: context.model,
137
+ thinkingLevel: context.thinkingLevel,
138
+ hasUI: context.hasUI,
139
+ ui: context.ui,
140
+ sessionId: context.sessionId,
141
+ };
142
+ return {
143
+ // Delegates to startAgent, which owns discovery, scope, and the
144
+ // project-agent confirmation gate. The definition supplies the name only.
145
+ // Only the opaque id crosses the contract; the internal handle record
146
+ // (pane id included) stays inside the Herdr backend.
147
+ async spawn(def, opts) {
148
+ const handle = await startAgent(
149
+ def.name,
150
+ {
151
+ label: opts.label,
152
+ placement: opts.placement,
153
+ cwd: opts.cwd,
154
+ artifactSession: context.artifactSession,
155
+ ...(context.launch ? { launch: context.launch } : {}),
156
+ },
157
+ execContext
158
+ );
159
+ return handle.id;
160
+ },
161
+
162
+ // `requestId` has no Herdr dedup equivalent: the task id is minted by the
163
+ // registry and a retried submit is a second call by design here.
164
+ async delegate(agentId, task, opts) {
165
+ const handle = await delegateAgent(agentId, task, {
166
+ ...(opts.timeoutMin !== undefined ? { timeoutMs: opts.timeoutMin * 60_000 } : {}),
167
+ sessionId: context.sessionId,
168
+ });
169
+ return handle.id;
170
+ },
171
+
172
+ // Child-to-parent sends use the child broker surface, not the parent
173
+ // runtime; refuse rather than silently misroute.
174
+ async message(target, msg, opts) {
175
+ if (target === 'parent') {
176
+ throw new LifecycleError(
177
+ 'invalid_handle',
178
+ 'Herdr runtime adapter cannot address "parent": child-to-parent messages use the child broker surface.'
179
+ );
180
+ }
181
+ const result = sendParentMessage({
182
+ target,
183
+ message: msg,
184
+ taskId: opts.taskId,
185
+ expectsReply: opts.expectsReply,
186
+ replyTo: opts.replyTo,
187
+ delivery: opts.delivery,
188
+ });
189
+ return result.messageId;
190
+ },
191
+
192
+ // Closest blocking primitive: waitForTasks settles every task, then each
193
+ // registry result is projected onto the backend-neutral Completion shape.
194
+ async watch(taskIds) {
195
+ const results = await lifecycleRegistry.waitForTasks(taskIds);
196
+ return results.map(toCompletion);
197
+ },
198
+
199
+ async status(agentId) {
200
+ return toRuntimeStatus(statusAgent(agentId));
201
+ },
202
+
203
+ async close(agentId) {
204
+ closeAgent(agentId);
205
+ },
206
+
207
+ // Handle -> pane resolution stays inside the registry; `lines` narrows the
208
+ // fixed 120-line tail after the read because readPaneTail takes no options.
209
+ async read(agentId, opts) {
210
+ const handle = lifecycleRegistry.canonicalAgentHandle(agentId);
211
+ if (!handle.paneId) {
212
+ throw new LifecycleError('unknown_handle', `Agent "${agentId}" has no Herdr pane to read.`);
213
+ }
214
+ const tail = await readPaneTail(handle.paneId);
215
+ const limit = opts?.lines;
216
+ if (limit === undefined || !Number.isFinite(limit) || limit <= 0) return tail;
217
+ const count = Math.trunc(limit);
218
+ if (count <= 0) return '';
219
+ const lines = tail.split('\n');
220
+ while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
221
+ return lines.slice(-count).join('\n');
222
+ },
223
+ };
224
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Shepherd runtime contract.
3
+ *
4
+ * One backend-neutral surface for the execution substrate behind the
5
+ * `shepherd_*` tools: Herdr panes today, durable owned conversations/tasks as
6
+ * a future opt-in backend. This module is a pure contract — it must not import
7
+ * the `herdr` CLI, `pi-durable`, an implementation module, or anything with
8
+ * side effects.
9
+ *
10
+ * Every id crossing this interface is opaque and session-scoped. An
11
+ * implementation maps an opaque `AgentHandle` internally to either a Herdr
12
+ * `paneId` or a durable `{ conversationId, submissionId, taskId }` triple.
13
+ * Native ids are implementation detail: Herdr pane ids and durable
14
+ * conversation ids must never be returned from `spawn` / `delegate` /
15
+ * `message`, accepted as `AgentHandle` / `TaskId` / `MessageId` inputs, or
16
+ * exposed by `status` / `read`. A Herdr pane id is diagnostic metadata only
17
+ * (for example, the pane `read` tails); it is never a valid opaque id.
18
+ */
19
+
20
+ import type { AgentConfig } from '../core/discovery.ts';
21
+
22
+ /** Opaque, session-scoped agent id returned by `spawn`; never a Herdr pane id. */
23
+ export type AgentHandle = string;
24
+
25
+ /** Message-addressing alias for an opaque agent id (`AgentHandle`). */
26
+ export type AgentId = AgentHandle;
27
+
28
+ /** Opaque task id returned by `delegate`; never a native submission id. */
29
+ export type TaskId = string;
30
+
31
+ /** Opaque message id returned by `message`; never a native envelope id. */
32
+ export type MessageId = string;
33
+
34
+ /**
35
+ * Where a spawn is placed. One optional value, matching the public
36
+ * `shepherd_spawn` surface. Durable execution ignores placement; `auto` may
37
+ * honor it for read-only viewer panes.
38
+ */
39
+ export type SpawnPlacement = 'pane_right' | 'pane_down' | 'tab' | 'workspace';
40
+
41
+ /**
42
+ * One settled task in backend-neutral terms: callers see the opaque task and
43
+ * agent ids plus the public result shape, never pane, conversation, or
44
+ * submission ids.
45
+ */
46
+ export interface Completion {
47
+ taskId: TaskId;
48
+ agentId: AgentHandle;
49
+ /** Terminal task state; a successful durable `done` maps to `completed`. */
50
+ status: 'completed' | 'blocked' | 'failed' | 'cancelled' | 'timed_out';
51
+ ok: boolean;
52
+ /** Stable process-style outcome: 0 success, 1 failure, 2 blocked, 124 timeout, 130 cancelled. */
53
+ returnCode: number;
54
+ text?: string;
55
+ error?: string;
56
+ completedAt: number;
57
+ /** Agent definition name; display identity only, not an id. */
58
+ agent?: string;
59
+ /** User-supplied label; display identity only, not an id. */
60
+ label?: string;
61
+ }
62
+
63
+ /**
64
+ * Three-value live process state. Backend states with no live equivalent —
65
+ * including terminal states such as done/failed/closed — map to `unknown`;
66
+ * task outcome is carried by `RuntimeTaskState`, never widened here.
67
+ */
68
+ export type RuntimeProcState = 'idle' | 'working' | 'unknown';
69
+
70
+ export type RuntimeTaskState = 'running' | 'waiting' | 'done' | 'blocked' | 'failed';
71
+
72
+ /**
73
+ * Backend-neutral status for one sheep: process state plus the state of its
74
+ * active task (independent, so an idle process can own a waiting task).
75
+ */
76
+ export interface RuntimeStatus {
77
+ proc: RuntimeProcState;
78
+ task: RuntimeTaskState;
79
+ /**
80
+ * Opaque `MessageId` of the request/message being awaited, when the task is
81
+ * parked on a reply. Never a pane, conversation, or submission id.
82
+ */
83
+ waitingOn?: MessageId;
84
+ /** True once the stale-wait monitor has already reminded for this wait episode. */
85
+ stale?: boolean;
86
+ }
87
+
88
+ /**
89
+ * Lifecycle-only runtime. Introspection for `/shepherd herd|agents|prune` and
90
+ * the widget (owned-agent/registry summaries, ownership checks) stays on the
91
+ * concrete runtime module; this interface carries no native ids either.
92
+ */
93
+ export interface ShepherdRuntime {
94
+ /** Launch a sheep from a discovered agent definition. */
95
+ spawn(
96
+ def: AgentConfig,
97
+ opts: { cwd?: string; label?: string; placement?: SpawnPlacement }
98
+ ): Promise<AgentHandle>;
99
+
100
+ /** Submit a task to an owned sheep. `requestId` dedups retried submissions. */
101
+ delegate(
102
+ agentId: AgentHandle,
103
+ task: string,
104
+ opts: { requestId?: string; timeoutMin?: number }
105
+ ): Promise<TaskId>;
106
+
107
+ /** Send a message to an owned sheep or to `parent`. */
108
+ message(
109
+ target: AgentId | 'parent',
110
+ msg: string,
111
+ opts: {
112
+ taskId?: TaskId;
113
+ expectsReply?: boolean;
114
+ replyTo?: MessageId;
115
+ delivery?: 'followUp' | 'steer';
116
+ }
117
+ ): Promise<MessageId>;
118
+
119
+ /**
120
+ * Block until every given task settles and return one completion per task.
121
+ * Implementations may reject an empty id list.
122
+ */
123
+ watch(taskIds: TaskId[]): Promise<Completion[]>;
124
+
125
+ /** Current process/task state for an owned sheep. */
126
+ status(agentId: AgentHandle): Promise<RuntimeStatus>;
127
+
128
+ /** Close/abort an owned sheep. Only shepherd-created work may be closed. */
129
+ close(agentId: AgentHandle): Promise<void>;
130
+
131
+ /** Tail human-readable output for an owned sheep. */
132
+ read(agentId: AgentHandle, opts?: { lines?: number }): Promise<string>;
133
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Settlement observation seam (010 Phase 1) — the bridge subscribes through
3
+ * the active runtime's registry instead of importing the Herdr module
4
+ * directly.
5
+ *
6
+ * Both runtimes expose `onTaskSettled` with identical semantics (007 §1):
7
+ * fires once per actual transition into a terminal task state, after the
8
+ * watcher fan-out, with a shallow result copy and a fresh `{ hadWatchers,
9
+ * agent?, label?, source? }` context. This module is the single place that
10
+ * knows both registries; the unseen bridge (`src/extension/
11
+ * unseen-completions.ts`) subscribes here, resolved per command through the
12
+ * same `resolveBackend` + `detectCaller` seam as `doAction`.
13
+ *
14
+ * A parent session may settle tasks on either backend across commands (the
15
+ * backend pin can change mid-session), so the bridge subscribes to both
16
+ * registries unconditionally. The resolved backend is exposed for diagnostics
17
+ * and future narrowing but never narrows the subscription — that is what
18
+ * keeps no-watch done → settle-or-idle-wake working on both backends.
19
+ */
20
+
21
+ import { resolveBackend, type ResolvedBackend } from './backend.ts';
22
+ import { detectCaller } from './detect.ts';
23
+ import { loadSettings } from '../core/config.ts';
24
+ import {
25
+ lifecycleRegistry,
26
+ type TaskSettledListener,
27
+ } from './herdr/orchestration.ts';
28
+ import {
29
+ onTaskSettled as onHcTaskSettled,
30
+ type HcTaskSettledListener,
31
+ } from './hc/runtime.ts';
32
+
33
+ /** Backend-neutral settlement observation context (both runtimes agree). */
34
+ export interface UnifiedSettlementContext {
35
+ hadWatchers: boolean;
36
+ agent?: string;
37
+ label?: string;
38
+ source?: 'delegate-submission-failure';
39
+ }
40
+
41
+ /** Structural settlement result; both runtimes satisfy this shape. */
42
+ export interface UnifiedSettlementResult {
43
+ taskId: string;
44
+ agentId: string;
45
+ status: 'completed' | 'blocked' | 'failed' | 'cancelled' | 'timed_out';
46
+ ok: boolean;
47
+ returnCode: number;
48
+ text?: string;
49
+ error?: string;
50
+ }
51
+
52
+ export type UnifiedSettledListener = (
53
+ result: UnifiedSettlementResult,
54
+ context: UnifiedSettlementContext
55
+ ) => void;
56
+
57
+ function asUnified(listener: UnifiedSettledListener): {
58
+ herdr: TaskSettledListener;
59
+ hc: HcTaskSettledListener;
60
+ } {
61
+ const herdr: TaskSettledListener = (result, context) =>
62
+ listener(
63
+ result as unknown as UnifiedSettlementResult,
64
+ context as unknown as UnifiedSettlementContext
65
+ );
66
+ const hc: HcTaskSettledListener = (result, context) =>
67
+ listener(
68
+ result as unknown as UnifiedSettlementResult,
69
+ context as unknown as UnifiedSettlementContext
70
+ );
71
+ return { herdr, hc };
72
+ }
73
+
74
+ /**
75
+ * Resolve the active backend for one command (same resolver as `doAction`:
76
+ * explicit pin wins, else run where called from). May throw when no backend
77
+ * is reachable — callers fall back to subscribing broadly.
78
+ */
79
+ export function resolveActiveSettlementBackend(cwd?: string): ResolvedBackend {
80
+ return resolveBackend(loadSettings(cwd).backend, detectCaller());
81
+ }
82
+
83
+ /** Registry handle for one backend (open question 1: beside resolveBackend). */
84
+ export function settlementRegistryFor(backend: ResolvedBackend): {
85
+ onTaskSettled: (listener: UnifiedSettledListener) => () => void;
86
+ } {
87
+ if (backend === 'hc') {
88
+ return {
89
+ onTaskSettled: listener => onHcTaskSettled(asUnified(listener).hc),
90
+ };
91
+ }
92
+ return {
93
+ onTaskSettled: listener => lifecycleRegistry.onTaskSettled(asUnified(listener).herdr),
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Subscribe to task settlements on BOTH backends with one handler. Returns a
99
+ * single unsubscribe releasing both registrations. This is the only
100
+ * subscription the unseen bridge uses: whichever runtime settles a task,
101
+ * the bridge records it and schedules the idle wake.
102
+ */
103
+ export function subscribeToTaskSettlements(listener: UnifiedSettledListener): () => void {
104
+ const { herdr, hc } = asUnified(listener);
105
+ const offHerdr = lifecycleRegistry.onTaskSettled(herdr);
106
+ const offHc = onHcTaskSettled(hc);
107
+ let released = false;
108
+ return () => {
109
+ if (released) return;
110
+ released = true;
111
+ offHerdr();
112
+ offHc();
113
+ };
114
+ }
@@ -0,0 +1,2 @@
1
+ UNIQUE_CONTEXT_FIXTURE_MARKER_7f3d2c9a
2
+ This project context must only appear when Pi context-file loading is enabled.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: same
3
+ description: user2-same (should LOSE to user1)
4
+ tools: read
5
+ ---
6
+ Shared cross-tool user agent "same".
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: shared-only
3
+ description: shared-only (user2 only)
4
+ tools: grep
5
+ ---
6
+ Defined only in shared user dir.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: invalid-thinking
3
+ description: invalid thinking is isolated from discovery
4
+ thinking: none
5
+ ---
6
+ Invalid definition.
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: model-empty
3
+ description: empty model inherits
4
+ model:
5
+ thinking:
6
+ ---
7
+ Empty model.
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: model-explicit
3
+ description: explicit model is retained
4
+ model: anthropic/claude-sonnet-4-5
5
+ thinking: high
6
+ ---
7
+ Explicit model.
@@ -0,0 +1,5 @@
1
+ ---
2
+ name: omit-context-absent
3
+ description: absent context omission setting
4
+ ---
5
+ Absent context omission prompt.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: omit-context-false
3
+ description: boolean false context omission setting
4
+ omit-context-files: false
5
+ ---
6
+ False context omission prompt.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: omit-context-invalid
3
+ description: quoted context omission setting
4
+ omit-context-files: "true"
5
+ ---
6
+ Invalid context omission prompt.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: omit-context-true
3
+ description: boolean true context omission setting
4
+ omit-context-files: true
5
+ ---
6
+ True context omission prompt.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: omit-false
3
+ description: boolean false omit setting
4
+ omit-system-prompt: false
5
+ ---
6
+ False prompt.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: omit-invalid
3
+ description: invalid omit setting
4
+ omit-system-prompt: "true"
5
+ ---
6
+ Invalid prompt.
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: omit-pi-docs
3
+ description: Omits Pi documentation guidance
4
+ omit-pi-documentation: true
5
+ ---
6
+
7
+ Use this agent for focused work.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: omit-true
3
+ description: boolean true omit setting
4
+ omit-system-prompt: true
5
+ ---
6
+ True prompt.
@@ -0,0 +1,9 @@
1
+ ---
2
+ name: only-user
3
+ description: only-user (should appear only in user/both)
4
+ tools:
5
+ - read
6
+ - find
7
+ user-invocable: true
8
+ ---
9
+ Only defined at user level.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: same
3
+ description: user1-same (should WIN over user2/project)
4
+ tools: read, grep
5
+ ---
6
+ User-level pi agent "same".
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: proj-shared
3
+ description: proj-shared (project shared dir only)
4
+ tools: find
5
+ ---
6
+ Defined in project .agents dir.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: project-pi
3
+ description: project-pi (project only)
4
+ tools: read
5
+ ---
6
+ Defined in project .pi dir.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: same
3
+ description: proj-pi-same (wins in project scope; loses to user1 in both)
4
+ tools: read, bash
5
+ ---
6
+ Project .pi agent "same".
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Small dependency-free clock for lifecycle tests. Production code should
3
+ * accept a clock/read-now function rather than patching Date.now; this helper
4
+ * gives those tests one consistent clock contract.
5
+ */
6
+ export function createManualClock(start = 0) {
7
+ if (!Number.isFinite(start)) throw new TypeError('Clock start must be finite.');
8
+ let current = start;
9
+ return {
10
+ now: () => current,
11
+ set(value) {
12
+ if (!Number.isFinite(value)) throw new TypeError('Clock value must be finite.');
13
+ current = value;
14
+ return current;
15
+ },
16
+ advance(milliseconds) {
17
+ if (!Number.isFinite(milliseconds) || milliseconds < 0) {
18
+ throw new TypeError('Clock advance must be a non-negative finite number.');
19
+ }
20
+ current += milliseconds;
21
+ return current;
22
+ },
23
+ };
24
+ }
25
+
26
+ /**
27
+ * Run a callback with a controlled Date.now value. This is reserved for tests
28
+ * around legacy code that cannot yet receive an injected clock directly.
29
+ */
30
+ export async function withFakeDateNow(start, callback) {
31
+ const clock = createManualClock(start);
32
+ const originalNow = Date.now;
33
+ Date.now = clock.now;
34
+ try {
35
+ return await callback(clock);
36
+ } finally {
37
+ Date.now = originalNow;
38
+ }
39
+ }