@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,36 @@
1
+ /**
2
+ * Display-only delivery for human-facing `/shepherd` command output (spec 013).
3
+ *
4
+ * `ctx.session.prompt({ sessionID, text })` admits a normal user message,
5
+ * which the TUI renders in full, but also wakes the model into a new turn.
6
+ * OpenCode's session layer skips that wake when `resume: false` is passed
7
+ * (`if (input.resume !== false) yield* execution.wake(sessionID)`), so the
8
+ * command result is shown as a normal message without starting an assistant
9
+ * turn. Synthetic messages are NOT suitable here: the TUI renders them as a
10
+ * single-line, truncated notice using `description ?? text`, so a multi-line
11
+ * agent list collapses to a bare label.
12
+ *
13
+ * Parent-session notices elsewhere in the adapter intentionally use
14
+ * `session.prompt` without `resume: false` because those must wake the model.
15
+ */
16
+
17
+ export interface PromptSessionSink {
18
+ prompt(input: { sessionID: string; text: string; resume?: boolean }): Promise<unknown>;
19
+ }
20
+
21
+ /** True when the host exposes the session-prompt primitive. */
22
+ export function supportsDisplayOnly(ctx: any): ctx is { session: PromptSessionSink } {
23
+ return typeof ctx?.session?.prompt === "function";
24
+ }
25
+
26
+ /**
27
+ * Show `text` in the session as a normal message without starting a turn.
28
+ * Throws a clear error on hosts that lack the primitive rather than silently
29
+ * degrading to a turn-starting call.
30
+ */
31
+ export async function displayCommandOutput(ctx: any, sessionID: string, text: string): Promise<void> {
32
+ if (!supportsDisplayOnly(ctx)) {
33
+ throw new Error("OpenCode session.prompt is unavailable; cannot display command output")
34
+ }
35
+ await ctx.session.prompt({ sessionID, text, resume: false });
36
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * OpenCode parent artifact-session resolution (spec 013, Phase 4).
3
+ *
4
+ * The OpenCode adapter resolves the parent fieldnotes session on the same
5
+ * durable layout Pi uses: `<projectRoot>/.shepherd/sessions/NNNN-<slug>/`.
6
+ * The OpenCode session id is the opaque parent identity and the session's
7
+ * cwd is the project root, mirroring Pi's
8
+ * `(parent session identity, effective project root)` binding key. The
9
+ * shared engine resolver is imported directly — no layout is duplicated and
10
+ * no Pi adapter code is involved (FR-006, FR-008).
11
+ */
12
+
13
+ import { resolveOrCreateParentArtifactSession, type ArtifactSession } from '../core/artifact-sessions.ts';
14
+ import { loadSettings } from '../core/config.ts';
15
+
16
+ /** Minimal shape needed to resolve a parent session; avoids an adapter cycle. */
17
+ export interface FieldnotesActionContext {
18
+ cwd: string;
19
+ sessionId?: string;
20
+ }
21
+
22
+ /**
23
+ * Fieldnotes are snapshotted for one parent session, like Pi's session-scoped
24
+ * setting. A persisted change takes effect in the next session; it never
25
+ * silently changes the contract of agents already running here.
26
+ */
27
+ const sessionFieldnotes = new Map<string, boolean>();
28
+
29
+ function fieldnotesEnabledFor(ctx: FieldnotesActionContext): boolean {
30
+ const key = `${ctx.sessionId ?? ''}\u0000${ctx.cwd}`;
31
+ let enabled = sessionFieldnotes.get(key);
32
+ if (enabled === undefined) {
33
+ enabled = loadSettings(ctx.cwd).fieldnotes;
34
+ sessionFieldnotes.set(key, enabled);
35
+ }
36
+ return enabled;
37
+ }
38
+
39
+ /** Test-only: drop per-session setting snapshots. */
40
+ export function resetOpencodeFieldnotesCache(): void {
41
+ sessionFieldnotes.clear();
42
+ }
43
+
44
+ /**
45
+ * Resolve (or lazily allocate) the one durable fieldnotes session owned by
46
+ * this OpenCode parent session and project. Returns undefined when fieldnotes
47
+ * are disabled; throws when the parent identity is unavailable for a tool
48
+ * call that needs one.
49
+ */
50
+ export function parentArtifactSession(ctx: FieldnotesActionContext): ArtifactSession | undefined {
51
+ if (!fieldnotesEnabledFor(ctx)) return undefined;
52
+ const parentSessionId = ctx.sessionId;
53
+ if (!parentSessionId) {
54
+ throw new Error('Unable to resolve the parent OpenCode session identity.');
55
+ }
56
+ return resolveOrCreateParentArtifactSession({
57
+ parentPiSessionId: parentSessionId,
58
+ projectRoot: ctx.cwd,
59
+ });
60
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * OpenCode host capabilities (spec 013, Phase 2).
3
+ *
4
+ * Pi-owned surface: this module is the OpenCode adapter's counterpart to the
5
+ * Pi extension entry. It installs engine host values appropriate for
6
+ * OpenCode: the global OpenCode dir as agent dir, `.opencode` as project
7
+ * config dir, and a YAML-frontmatter parser identical in behavior to Pi's
8
+ * (same `---` splitting + `yaml` parse; `yaml` is a declared dependency).
9
+ * The data subdir stays `pi-shepherd` (frozen per FR-013).
10
+ */
11
+
12
+ import * as os from 'node:os';
13
+ import * as path from 'node:path';
14
+ import { parse as parseYaml } from 'yaml';
15
+ import { setHostCapabilities, type FrontmatterResult } from '../core/host.ts';
16
+
17
+ /** Env prefix for the child capability handoff on the OpenCode path. */
18
+ export const OPENCODE_ENV_PREFIX = 'SHEPHERD_';
19
+
20
+ /** Full shell command booting an interactive OpenCode child in a pane. */
21
+ export const OPENCODE_CHILD_COMMAND = 'opencode';
22
+
23
+ /** Launch overrides passed through the runtime contexts for OpenCode sheep. */
24
+ export const OPENCODE_LAUNCH_OVERRIDES = {
25
+ command: OPENCODE_CHILD_COMMAND,
26
+ envPrefix: OPENCODE_ENV_PREFIX,
27
+ } as const;
28
+
29
+ function extractFrontmatter(content: string): { yamlString: string | null; body: string } {
30
+ const normalized = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
31
+ if (!normalized.startsWith('---')) return { yamlString: null, body: normalized };
32
+ const endIndex = normalized.indexOf('\n---', 3);
33
+ if (endIndex === -1) return { yamlString: null, body: normalized };
34
+ return {
35
+ yamlString: normalized.slice(4, endIndex),
36
+ body: normalized.slice(endIndex + 4).trim(),
37
+ };
38
+ }
39
+
40
+ /** Same observable behavior as Pi's parseFrontmatter for definition files. */
41
+ export function parseOpencodeFrontmatter<T>(content: string): FrontmatterResult<T> {
42
+ const { yamlString, body } = extractFrontmatter(content);
43
+ if (!yamlString) return { frontmatter: {} as T, body };
44
+ return { frontmatter: (parseYaml(yamlString) ?? {}) as T, body };
45
+ }
46
+
47
+ /** Global OpenCode dir (overridable for tests via OPENCODE_CONFIG_DIR). */
48
+ export function opencodeAgentDir(): string {
49
+ const override = process.env.OPENCODE_CONFIG_DIR?.trim();
50
+ if (override) return override;
51
+ return path.join(os.homedir(), '.config', 'opencode');
52
+ }
53
+
54
+ /** Install the OpenCode host values into the shared engine. Idempotent. */
55
+ export function installOpencodeHost(): void {
56
+ setHostCapabilities({
57
+ getAgentDir: opencodeAgentDir,
58
+ projectConfigDirName: '.opencode',
59
+ dataDirName: 'pi-shepherd',
60
+ parseFrontmatter: parseOpencodeFrontmatter,
61
+ });
62
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Orphan detection and reap for the OpenCode adapter (spec 013 reload item).
3
+ *
4
+ * A plugin reload/server restart loses all module-local SheepRecords while
5
+ * the Herdr panes/hc terminals and their on-disk ownership registries survive.
6
+ * Rather than pretend those sheep are still manageable, surface them once and
7
+ * offer an explicit, ownership-checked reap. Native pane/terminal ids are
8
+ * never accepted from a tool argument; they come only from the registry.
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { hostCapabilities } from '../core/host.ts';
14
+ import {
15
+ forgetOwnedPane,
16
+ herdrExecSync,
17
+ loadCreatedPanes,
18
+ paneExists,
19
+ pruneStaleCreatedPanes,
20
+ } from '../runtimes/herdr/herdr.ts';
21
+ import {
22
+ forgetOwnedTerminal,
23
+ killHcTerminal,
24
+ loadCreatedTerminals,
25
+ pruneStaleCreatedTerminals,
26
+ terminalExists,
27
+ } from '../runtimes/hc/hc.ts';
28
+ import { isManagedTransport } from './bridge.ts';
29
+ import { displayCommandOutput } from './display.ts';
30
+
31
+ export interface Orphan {
32
+ transportId: string;
33
+ name: string;
34
+ cwd: string;
35
+ ownerSession?: string;
36
+ backend: 'herdr' | 'hc';
37
+ }
38
+
39
+ function markerFile(): string {
40
+ const host = hostCapabilities();
41
+ return path.join(host.getAgentDir(), host.dataDirName, 'orphan-notices.json');
42
+ }
43
+
44
+ function readMarker(): Record<string, string[]> {
45
+ try {
46
+ const parsed = JSON.parse(fs.readFileSync(markerFile(), 'utf8'));
47
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
48
+ } catch {
49
+ return {};
50
+ }
51
+ }
52
+
53
+ function writeMarker(marker: Record<string, string[]>): void {
54
+ try {
55
+ const file = markerFile();
56
+ fs.mkdirSync(path.dirname(file), { recursive: true });
57
+ const tmp = `${file}.tmp-${process.pid}`;
58
+ fs.writeFileSync(tmp, JSON.stringify(marker, null, 2));
59
+ fs.renameSync(tmp, file);
60
+ } catch {
61
+ /* notice tracking is best effort */
62
+ }
63
+ }
64
+
65
+ /** Live owned transports that no in-memory SheepRecord currently manages. */
66
+ export function findOrphans(sessionId?: string): Orphan[] {
67
+ pruneStaleCreatedPanes();
68
+ pruneStaleCreatedTerminals();
69
+ const owned = (owner?: string): boolean =>
70
+ !sessionId || owner === sessionId || owner === undefined;
71
+ const orphans: Orphan[] = [];
72
+ for (const entry of loadCreatedPanes()) {
73
+ if (owned(entry.ownerSession) && paneExists(entry.paneId) && !isManagedTransport(entry.paneId)) {
74
+ orphans.push({
75
+ transportId: entry.paneId,
76
+ name: entry.name,
77
+ cwd: entry.cwd,
78
+ ownerSession: entry.ownerSession,
79
+ backend: 'herdr',
80
+ });
81
+ }
82
+ }
83
+ for (const entry of loadCreatedTerminals()) {
84
+ if (
85
+ owned(entry.ownerSession) &&
86
+ terminalExists(entry.terminalId) &&
87
+ !isManagedTransport(entry.terminalId)
88
+ ) {
89
+ orphans.push({
90
+ transportId: entry.terminalId,
91
+ name: entry.name,
92
+ cwd: entry.cwd,
93
+ ownerSession: entry.ownerSession,
94
+ backend: 'hc',
95
+ });
96
+ }
97
+ }
98
+ return orphans;
99
+ }
100
+
101
+ /** One display-only notice per previously unreported orphan set. */
102
+ export async function noticeNewOrphans(ctx: any): Promise<void> {
103
+ const orphans = findOrphans();
104
+ if (orphans.length === 0) return;
105
+ const marker = readMarker();
106
+ const byOwner = new Map<string, Orphan[]>();
107
+ for (const orphan of orphans) {
108
+ const owner = orphan.ownerSession ?? '';
109
+ byOwner.set(owner, [...(byOwner.get(owner) ?? []), orphan]);
110
+ }
111
+ for (const [owner, entries] of byOwner) {
112
+ if (!owner) continue;
113
+ const seen = new Set(marker[owner] ?? []);
114
+ const fresh = entries.filter(entry => !seen.has(entry.transportId));
115
+ if (fresh.length === 0) continue;
116
+ const lines = [
117
+ 'Shepherd restarted while some sheep were still running. Their opaque ids were lost, so they cannot be delegated to or closed until reaped.',
118
+ `Orphaned sheep (${fresh.length}):`,
119
+ ...fresh.map(entry =>
120
+ `- ${entry.name} (${entry.backend}) cwd ${entry.cwd}`.trimEnd()
121
+ ),
122
+ 'Use the shepherd tool with action "reap" to close them, or respawn and close the old panes manually. Fieldnotes and queued envelopes remain on disk.',
123
+ ];
124
+ try {
125
+ await displayCommandOutput(ctx, owner, lines.join('\n'));
126
+ marker[owner] = [...seen, ...fresh.map(entry => entry.transportId)];
127
+ writeMarker(marker);
128
+ } catch {
129
+ /* host may not have this session any more; try again next startup */
130
+ }
131
+ }
132
+ }
133
+
134
+ /** Close live but unmanaged owned transports, then drop their registrations. */
135
+ export function reapOrphans(sessionId?: string): string {
136
+ const orphans = findOrphans(sessionId);
137
+ if (orphans.length === 0) return 'No orphaned sheep to reap.';
138
+ const reaped: string[] = [];
139
+ const failed: string[] = [];
140
+ for (const orphan of orphans) {
141
+ let closed = false;
142
+ try {
143
+ if (orphan.backend === 'herdr') {
144
+ herdrExecSync(['pane', 'close', orphan.transportId]);
145
+ closed = !paneExists(orphan.transportId);
146
+ if (closed) forgetOwnedPane(orphan.transportId, sessionId);
147
+ } else {
148
+ killHcTerminal(orphan.transportId);
149
+ closed = !terminalExists(orphan.transportId);
150
+ if (closed) forgetOwnedTerminal(orphan.transportId, sessionId);
151
+ }
152
+ } catch {
153
+ closed = false;
154
+ }
155
+ (closed ? reaped : failed).push(orphan.name || orphan.transportId);
156
+ }
157
+ const lines = [`reaped ${reaped.length} orphaned sheep.`, ...reaped.map(name => `- ${name}`)];
158
+ if (failed.length) {
159
+ lines.push(`could not close ${failed.length}:`, ...failed.map(name => `- ${name}`));
160
+ }
161
+ return lines.join('\n');
162
+ }