@luminascale/shepherd 0.0.0-stage → 0.6.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.
Files changed (204) 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 +397 -2
  16. package/docs/README.md +26 -0
  17. package/docs/guides/agent-definitions.md +42 -0
  18. package/docs/guides/diagnostics.md +199 -0
  19. package/docs/guides/installation.md +61 -0
  20. package/docs/guides/tool-reference.md +55 -0
  21. package/docs/manual-tests/ping-pong-peer-messaging.md +147 -0
  22. package/docs/plans/agent-labels.md +257 -0
  23. package/docs/plans/architecture.md +110 -0
  24. package/docs/plans/settings-scope.md +163 -0
  25. package/docs/plans/tool-surface-split.md +278 -0
  26. package/docs/reference/dictionary +26 -0
  27. package/docs/releasing.md +47 -0
  28. package/docs/specs/005-agent-messaging-and-task-lifecycle/baseline.md +115 -0
  29. package/docs/specs/005-agent-messaging-and-task-lifecycle/handoff.md +564 -0
  30. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase10-notes.md +109 -0
  31. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase6-notes.md +69 -0
  32. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase7-notes.md +100 -0
  33. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase8-notes.md +127 -0
  34. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase9-notes.md +104 -0
  35. package/docs/specs/005-agent-messaging-and-task-lifecycle/plan.md +1093 -0
  36. package/docs/specs/005-agent-messaging-and-task-lifecycle/spec.md +583 -0
  37. package/docs/specs/005-agent-messaging-and-task-lifecycle/tasks.md +838 -0
  38. package/docs/specs/006-shepherd-tool-rendering/plan.md +175 -0
  39. package/docs/specs/006-shepherd-tool-rendering/spec.md +469 -0
  40. package/index.ts +602 -0
  41. package/package.json +112 -4
  42. package/scripts/capture-system-prompt.mjs +45 -0
  43. package/scripts/extract-pi-system-prompt.mjs +277 -0
  44. package/scripts/host-impact.mjs +74 -0
  45. package/scripts/resolve-agent.mjs +43 -0
  46. package/scripts/show-shepherd-orchestrator.mjs +58 -0
  47. package/scripts/show-shepherd-prompt.mjs +96 -0
  48. package/scripts/verify-suites.mjs +67 -0
  49. package/specs/001-artifacts/spec.md +436 -0
  50. package/specs/002-simplify-agent-orchestration/plan.md +287 -0
  51. package/specs/002-simplify-agent-orchestration/spec.md +323 -0
  52. package/specs/002-simplify-agent-orchestration/tasks.md +212 -0
  53. package/specs/003-orchestrator-session-artifacts/plan.md +396 -0
  54. package/specs/003-orchestrator-session-artifacts/spec.md +453 -0
  55. package/specs/003-orchestrator-session-artifacts/tasks.md +141 -0
  56. package/specs/004-asynchronous-prompt-watchers/plan.md +139 -0
  57. package/specs/004-asynchronous-prompt-watchers/spec.md +202 -0
  58. package/specs/004-asynchronous-prompt-watchers/tasks.md +126 -0
  59. package/specs/005-per-workspace-settings/plan.md +230 -0
  60. package/specs/005-per-workspace-settings/spec.md +368 -0
  61. package/specs/005-per-workspace-settings/tasks.md +178 -0
  62. package/specs/006-dual-runtime-herdr-durable/intent.md +86 -0
  63. package/specs/006-dual-runtime-herdr-durable/journal.md +80 -0
  64. package/specs/006-dual-runtime-herdr-durable/plan.md +242 -0
  65. package/specs/006-dual-runtime-herdr-durable/spec.md +389 -0
  66. package/specs/006-dual-runtime-herdr-durable/tasks.md +199 -0
  67. package/specs/007-unwatched-completion-notice/journal.md +145 -0
  68. package/specs/007-unwatched-completion-notice/plan.md +186 -0
  69. package/specs/007-unwatched-completion-notice/spec.md +284 -0
  70. package/specs/007-unwatched-completion-notice/tasks.md +147 -0
  71. package/specs/008-remote-machine-sheep/intent.md +174 -0
  72. package/specs/008-remote-machine-sheep/journal.md +57 -0
  73. package/specs/008-remote-machine-sheep/prerequisites.md +219 -0
  74. package/specs/009-hc-runtime/intent.md +44 -0
  75. package/specs/009-hc-runtime/plan.md +49 -0
  76. package/specs/009-hc-runtime/spec.md +118 -0
  77. package/specs/009-hc-runtime/tasks.md +62 -0
  78. package/specs/010-unseen-watch-parity/intent.md +57 -0
  79. package/specs/010-unseen-watch-parity/journal.md +172 -0
  80. package/specs/010-unseen-watch-parity/plan.md +74 -0
  81. package/specs/010-unseen-watch-parity/spec.md +191 -0
  82. package/specs/010-unseen-watch-parity/tasks.md +119 -0
  83. package/specs/011-hc-background-poll/intent.md +57 -0
  84. package/specs/011-hc-background-poll/journal.md +95 -0
  85. package/specs/011-hc-background-poll/plan.md +87 -0
  86. package/specs/011-hc-background-poll/spec.md +141 -0
  87. package/specs/011-hc-background-poll/tasks.md +83 -0
  88. package/specs/012-steer-default/intent.md +12 -0
  89. package/specs/012-steer-default/journal.md +40 -0
  90. package/specs/012-steer-default/plan.md +7 -0
  91. package/specs/012-steer-default/spec.md +42 -0
  92. package/specs/012-steer-default/tasks.md +6 -0
  93. package/specs/013-opencode-shepherd/handoff-t011.md +94 -0
  94. package/specs/013-opencode-shepherd/intent.md +59 -0
  95. package/specs/013-opencode-shepherd/plan.md +204 -0
  96. package/specs/013-opencode-shepherd/spec.md +258 -0
  97. package/specs/013-opencode-shepherd/tasks.md +263 -0
  98. package/src/core/artifact-sessions.ts +835 -0
  99. package/src/core/config.ts +329 -0
  100. package/src/core/discovery.ts +342 -0
  101. package/src/core/herdr.ts +1 -0
  102. package/src/core/host.ts +77 -0
  103. package/src/core/ids.ts +78 -0
  104. package/src/core/lifecycle.ts +1 -0
  105. package/src/core/messaging.ts +1 -0
  106. package/src/core/migration.ts +55 -0
  107. package/src/core/orchestration.ts +1 -0
  108. package/src/core/types.ts +143 -0
  109. package/src/core/unseen-completions.ts +114 -0
  110. package/src/extension/cli.ts +417 -0
  111. package/src/extension/config.ts +1 -0
  112. package/src/extension/settings-ui.ts +296 -0
  113. package/src/extension/shepherd-done.ts +768 -0
  114. package/src/extension/shepherd.ts +2548 -0
  115. package/src/extension/system-prompt.ts +38 -0
  116. package/src/extension/unseen-completions.ts +237 -0
  117. package/src/opencode/actions.ts +794 -0
  118. package/src/opencode/bridge.ts +777 -0
  119. package/src/opencode/display.ts +36 -0
  120. package/src/opencode/fieldnotes.ts +60 -0
  121. package/src/opencode/host.ts +62 -0
  122. package/src/opencode/orphans.ts +162 -0
  123. package/src/opencode/server.ts +458 -0
  124. package/src/runtimes/backend.ts +119 -0
  125. package/src/runtimes/detect.ts +102 -0
  126. package/src/runtimes/hc/hc.ts +527 -0
  127. package/src/runtimes/hc/runtime.ts +1898 -0
  128. package/src/runtimes/herdr/herdr.ts +912 -0
  129. package/src/runtimes/herdr/lifecycle.ts +1712 -0
  130. package/src/runtimes/herdr/messaging.ts +703 -0
  131. package/src/runtimes/herdr/orchestration.ts +1583 -0
  132. package/src/runtimes/herdr/runtime.ts +224 -0
  133. package/src/runtimes/runtime.ts +133 -0
  134. package/src/runtimes/settle-observations.ts +114 -0
  135. package/test/fixtures/context-project/AGENTS.md +2 -0
  136. package/test/fixtures/home/.agents/agents/same.md +6 -0
  137. package/test/fixtures/home/.agents/agents/shared-only.md +6 -0
  138. package/test/fixtures/home/.pi/agent/agents/invalid-thinking.md +6 -0
  139. package/test/fixtures/home/.pi/agent/agents/model-empty.md +7 -0
  140. package/test/fixtures/home/.pi/agent/agents/model-explicit.md +7 -0
  141. package/test/fixtures/home/.pi/agent/agents/omit-context-absent.md +5 -0
  142. package/test/fixtures/home/.pi/agent/agents/omit-context-false.md +6 -0
  143. package/test/fixtures/home/.pi/agent/agents/omit-context-invalid.md +6 -0
  144. package/test/fixtures/home/.pi/agent/agents/omit-context-true.md +6 -0
  145. package/test/fixtures/home/.pi/agent/agents/omit-false.md +6 -0
  146. package/test/fixtures/home/.pi/agent/agents/omit-invalid.md +6 -0
  147. package/test/fixtures/home/.pi/agent/agents/omit-pi-docs.md +7 -0
  148. package/test/fixtures/home/.pi/agent/agents/omit-true.md +6 -0
  149. package/test/fixtures/home/.pi/agent/agents/only-user.md +9 -0
  150. package/test/fixtures/home/.pi/agent/agents/same.md +6 -0
  151. package/test/fixtures/proj/.agents/agents/proj-shared.md +6 -0
  152. package/test/fixtures/proj/.pi/agents/project-pi.md +6 -0
  153. package/test/fixtures/proj/.pi/agents/same.md +6 -0
  154. package/test/helpers/fake-clock.mjs +39 -0
  155. package/test/helpers/feature-contracts.mjs +44 -0
  156. package/test/helpers/test-utils.mjs +44 -0
  157. package/test/verify-artifact-sessions.mjs +258 -0
  158. package/test/verify-backend.mjs +297 -0
  159. package/test/verify-child-mislabel.mjs +135 -0
  160. package/test/verify-child-surface.mjs +321 -0
  161. package/test/verify-cli.mjs +197 -0
  162. package/test/verify-command-ux.mjs +100 -0
  163. package/test/verify-compat.mjs +32 -0
  164. package/test/verify-cross-host-notes.mjs +128 -0
  165. package/test/verify-delegate.mjs +161 -0
  166. package/test/verify-detect.mjs +151 -0
  167. package/test/verify-discovery.mjs +239 -0
  168. package/test/verify-done-nudge.mjs +238 -0
  169. package/test/verify-effective-prompt.mjs +98 -0
  170. package/test/verify-hc-matrix.mjs +246 -0
  171. package/test/verify-hc-poll.mjs +260 -0
  172. package/test/verify-host-docs.mjs +66 -0
  173. package/test/verify-host-impact.mjs +49 -0
  174. package/test/verify-ids.mjs +141 -0
  175. package/test/verify-launch.mjs +183 -0
  176. package/test/verify-message-routing.mjs +560 -0
  177. package/test/verify-messaging.mjs +303 -0
  178. package/test/verify-migration-notice.mjs +74 -0
  179. package/test/verify-multi-wait.mjs +42 -0
  180. package/test/verify-opencode-display.mjs +47 -0
  181. package/test/verify-opencode-fieldnotes.mjs +121 -0
  182. package/test/verify-opencode-notice.mjs +77 -0
  183. package/test/verify-opencode-nudge.mjs +116 -0
  184. package/test/verify-opencode-orphans.mjs +160 -0
  185. package/test/verify-opencode-surface.mjs +107 -0
  186. package/test/verify-packaging.mjs +82 -0
  187. package/test/verify-parent-surface.mjs +118 -0
  188. package/test/verify-phase0.mjs +95 -0
  189. package/test/verify-registry.mjs +124 -0
  190. package/test/verify-rename-migration.mjs +111 -0
  191. package/test/verify-rendering.mjs +379 -0
  192. package/test/verify-session-boundary.mjs +146 -0
  193. package/test/verify-settings.mjs +260 -0
  194. package/test/verify-stale-wait.mjs +339 -0
  195. package/test/verify-status-widget.mjs +377 -0
  196. package/test/verify-status.mjs +172 -0
  197. package/test/verify-task-completion.mjs +156 -0
  198. package/test/verify-task-failures.mjs +201 -0
  199. package/test/verify-task-mislabel.mjs +143 -0
  200. package/test/verify-task-registry.mjs +194 -0
  201. package/test/verify-task-watchers.mjs +217 -0
  202. package/test/verify-tool-schemas.mjs +120 -0
  203. package/test/verify-unseen-completions.mjs +1211 -0
  204. package/test/verify-watchers.mjs +181 -0
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * OpenCode-side coverage for the two remaining T011 gaps:
4
+ * - done-nudge delivered from session.execution.* events (bridge.ts), and
5
+ * - sheep-context shepherd_done with an unknown task id (actions.ts).
6
+ */
7
+ import assert from 'node:assert/strict';
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+
12
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pi-shepherd-oc-nudge-'));
13
+ process.env.HOME = home;
14
+ const bin = path.join(home, 'bin');
15
+ fs.mkdirSync(bin, { recursive: true });
16
+ const deliveries = path.join(home, 'deliveries.log');
17
+ const fakeHerdr = path.join(bin, 'herdr');
18
+ fs.writeFileSync(
19
+ fakeHerdr,
20
+ `#!/bin/sh
21
+ case "$1 $2" in
22
+ "--version "*|"--version") echo herdr-test; exit 0 ;;
23
+ "agent list") echo '{"id":"cli:agent:list","result":{"agents":[]}}'; exit 0 ;;
24
+ "agent get") echo '{"id":"cli:agent:get","result":{"agent":{"agent_status":"idle","pane_id":"pane-test","tab_id":"tab-test","workspace_id":"ws-test"}}}'; exit 0 ;;
25
+ "agent prompt") printf '%s\\n' "$*" >> '${deliveries}'; echo '{"id":"cli:prompt","result":{}}'; exit 0 ;;
26
+ "pane send-text") printf '%s\\n' "$*" >> '${deliveries}'; echo '{"id":"cli:send","result":{}}'; exit 0 ;;
27
+ "pane send-keys") echo '{"id":"cli:keys","result":{}}'; exit 0 ;;
28
+ *) echo '{"id":"cli:ok","result":{}}'; exit 0 ;;
29
+ esac
30
+ `
31
+ );
32
+ fs.chmodSync(fakeHerdr, 0o755);
33
+ process.env.PATH = `${bin}${path.delimiter}${process.env.PATH ?? ''}`;
34
+ process.env.SHEPHERD_DONE_NUDGES = '1';
35
+
36
+ const { lifecycleRegistry } = await import('../src/runtimes/herdr/orchestration.ts');
37
+ const {
38
+ bindChildSession,
39
+ installOpencodeBridges,
40
+ markParentSession,
41
+ recordSheepSpawn,
42
+ } = await import('../src/opencode/bridge.ts');
43
+
44
+ // ── 1. Done-nudge from a forgotten sheep ─────────────────────────────────
45
+ const handle = lifecycleRegistry.registerAgent({ agent: 'scout', label: 'nudge', paneId: 'pane-test' });
46
+ const task = lifecycleRegistry.createTask(handle, 'forget to call shepherd_done');
47
+ lifecycleRegistry.setTaskRunning(task.id);
48
+ recordSheepSpawn({
49
+ agentId: handle.id,
50
+ backend: 'pane',
51
+ paneId: 'pane-test',
52
+ cwd: home,
53
+ parentSessionId: 'parent-session',
54
+ childCapability: 'oc',
55
+ brokerRootDir: path.join(home, 'broker'),
56
+ brokerSessionId: 'broker-session',
57
+ brokerId: 'broker',
58
+ parentBrokerId: 'parent-broker',
59
+ spawnedAt: 0,
60
+ });
61
+ bindChildSession(handle.id, 'sheep-session');
62
+ markParentSession('parent-session');
63
+
64
+ const queue = [];
65
+ let consumed = 0;
66
+ let streamDone = false;
67
+ const stream = {
68
+ async *[Symbol.asyncIterator]() {
69
+ while (!streamDone) {
70
+ while (queue.length) { consumed++; yield queue.shift(); }
71
+ await new Promise(resolve => setTimeout(resolve, 20));
72
+ }
73
+ },
74
+ };
75
+ const parentPrompts = [];
76
+ const ctx = {
77
+ session: {
78
+ list: async () => [],
79
+ prompt: async input => { parentPrompts.push(input); },
80
+ },
81
+ event: { subscribe: () => stream },
82
+ };
83
+ // Two identical run-completion events: first nudges, second escalates.
84
+ queue.push({ type: 'session.execution.succeeded', properties: { sessionID: 'sheep-session' } });
85
+ queue.push({ type: 'session.execution.succeeded', properties: { sessionID: 'sheep-session' } });
86
+ installOpencodeBridges(ctx);
87
+ await new Promise(resolve => setTimeout(resolve, 1000));
88
+
89
+ const first = fs.existsSync(deliveries) ? fs.readFileSync(deliveries, 'utf8') : '';
90
+ assert.match(first, /shepherd_done/, 'nudge tells the sheep to call shepherd_done');
91
+ assert.match(first, new RegExp(task.id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), 'nudge names the open task id');
92
+
93
+ const second = fs.readFileSync(deliveries, 'utf8');
94
+ assert.equal(second, first, 'a bounded nudge is never repeated');
95
+ assert.equal(consumed, 2, 'both execution events were observed');
96
+ assert.ok(
97
+ parentPrompts.some(p => /Shepherd completion stalled/.test(p.text) && p.text.includes(task.id)),
98
+ 'exhausted nudge budget escalates to the parent session'
99
+ );
100
+ console.log('PASS OpenCode done-nudge fires once, then escalates to the parent');
101
+
102
+ // ── 2. Sheep-context shepherd_done with an unknown task id ───────────────
103
+ const { sheepDone } = await import('../src/opencode/actions.ts');
104
+ const bogus = 'shepherd-task-0000-0000';
105
+ await assert.rejects(
106
+ () => sheepDone({ cwd: home, sessionId: 'sheep-session-2' }, { taskId: bogus, status: 'completed' }, 'sheep-session-2'),
107
+ error => {
108
+ assert.match(String(error), /Unknown task id/);
109
+ assert.ok(String(error).includes(bogus), 'error names the bad id');
110
+ return true;
111
+ }
112
+ );
113
+ console.log('PASS OpenCode sheep-context shepherd_done rejects an unknown task id by name');
114
+
115
+ streamDone = true;
116
+ console.log('All OpenCode nudge/error-path assertions passed.');
@@ -0,0 +1,160 @@
1
+ #!/usr/bin/env node
2
+ /** Reload resilience — orphan detection, one-time notice, and ownership-safe reap. */
3
+ import assert from 'node:assert/strict';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+
8
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pi-shepherd-orphans-'));
9
+ process.env.HOME = home;
10
+ process.env.OPENCODE_CONFIG_DIR = path.join(home, 'config', 'opencode');
11
+ const bin = path.join(home, 'bin');
12
+ fs.mkdirSync(bin, { recursive: true });
13
+ fs.mkdirSync(process.env.OPENCODE_CONFIG_DIR, { recursive: true });
14
+
15
+ const panesFile = path.join(home, 'panes.txt');
16
+ const terminalsFile = path.join(home, 'terminals.txt');
17
+ fs.writeFileSync(panesFile, 'p1\n');
18
+ fs.writeFileSync(terminalsFile, 't1\n');
19
+ fs.writeFileSync(
20
+ path.join(bin, 'herdr'),
21
+ `#!/bin/sh
22
+ if [ "$1" = "--version" ]; then echo herdr-test; exit 0; fi
23
+ if [ "$1 $2" = "pane list" ]; then
24
+ printf '{"id":"cli:pane:list","result":{"panes":['
25
+ first=1
26
+ while read -r id; do [ -z "$id" ] && continue; [ $first -eq 0 ] && printf ','; printf '{"pane_id":"%s"}' "$id"; first=0; done < '${panesFile}'
27
+ printf ']}}'; exit 0
28
+ fi
29
+ if [ "$1 $2" = "pane close" ]; then
30
+ grep -vx "$3" '${panesFile}' > '${panesFile}.tmp' || true
31
+ mv '${panesFile}.tmp' '${panesFile}'
32
+ echo '{"id":"cli:pane:close","result":{}}'; exit 0
33
+ fi
34
+ echo '{"id":"cli:ok","result":{}}'
35
+ `
36
+ );
37
+ fs.writeFileSync(
38
+ path.join(bin, 'hc'),
39
+ `#!/bin/sh
40
+ if [ "$1" = "--version" ]; then echo hc-test; exit 0; fi
41
+ if [ "$1" = "get" ]; then
42
+ grep -qx "$2" '${terminalsFile}' && echo '{"address":"addr","state":"live"}' || echo '{"kind":"not_found"}'
43
+ exit 0
44
+ fi
45
+ if [ "$1" = "kill" ] || [ "$1" = "rm" ]; then
46
+ grep -vx "$2" '${terminalsFile}' > '${terminalsFile}.tmp' || true
47
+ mv '${terminalsFile}.tmp' '${terminalsFile}'
48
+ fi
49
+ echo '{"id":"cli:ok","result":{}}'
50
+ `
51
+ );
52
+ fs.chmodSync(path.join(bin, 'herdr'), 0o755);
53
+ fs.chmodSync(path.join(bin, 'hc'), 0o755);
54
+ process.env.PATH = `${bin}${path.delimiter}${process.env.PATH ?? ''}`;
55
+
56
+ const dataDir = path.join(process.env.OPENCODE_CONFIG_DIR, 'pi-shepherd');
57
+ fs.mkdirSync(dataDir, { recursive: true });
58
+ const paneDir = path.join(home, 'launch-p1');
59
+ const terminalDir = path.join(home, 'launch-t1');
60
+ fs.mkdirSync(paneDir, { recursive: true });
61
+ fs.mkdirSync(terminalDir, { recursive: true });
62
+ const writeRegistries = () => {
63
+ fs.writeFileSync(
64
+ path.join(dataDir, 'created-panes.json'),
65
+ JSON.stringify([
66
+ {
67
+ paneId: 'p1',
68
+ name: 'scout',
69
+ cwd: home,
70
+ createdAt: 1,
71
+ dir: paneDir,
72
+ ownerSession: 'ses-owner',
73
+ },
74
+ ])
75
+ );
76
+ fs.writeFileSync(
77
+ path.join(dataDir, 'created-terminals.json'),
78
+ JSON.stringify([
79
+ {
80
+ terminalId: 't1',
81
+ name: 'worker',
82
+ cwd: home,
83
+ createdAt: 1,
84
+ dir: terminalDir,
85
+ ownerSession: 'ses-owner',
86
+ },
87
+ ])
88
+ );
89
+ };
90
+ writeRegistries();
91
+
92
+ const { installOpencodeHost } = await import('../src/opencode/host.ts');
93
+ installOpencodeHost();
94
+ const { findOrphans, noticeNewOrphans, reapOrphans } = await import('../src/opencode/orphans.ts');
95
+
96
+ const orphans = findOrphans();
97
+ assert.deepEqual(
98
+ orphans.map(o => o.backend).sort(),
99
+ ['hc', 'herdr'],
100
+ 'live owned transports with no in-memory SheepRecord are orphans'
101
+ );
102
+ console.log('PASS live owned transports are detected as orphans');
103
+
104
+ const prompts = [];
105
+ const ctx = { session: { prompt: async input => prompts.push(input) } };
106
+ await noticeNewOrphans(ctx);
107
+ assert.equal(prompts.length, 1, 'one notice to the owning session');
108
+ assert.equal(prompts[0].sessionID, 'ses-owner');
109
+ assert.equal(prompts[0].resume, false, 'notice is display-only, no assistant turn');
110
+ assert.match(prompts[0].text, /action "reap"/);
111
+ assert.match(prompts[0].text, /scout/);
112
+ assert.doesNotMatch(prompts[0].text, /p1/, 'native pane ids never leak into the notice');
113
+ await noticeNewOrphans(ctx);
114
+ assert.equal(prompts.length, 1, 'the same orphan set is not reported twice');
115
+ console.log('PASS one-time display-only orphan notice');
116
+
117
+ // A new orphan after reload is reported once too.
118
+ fs.writeFileSync(panesFile, 'p1\np2\n');
119
+ fs.writeFileSync(
120
+ path.join(dataDir, 'created-panes.json'),
121
+ JSON.stringify([
122
+ ...JSON.parse(fs.readFileSync(path.join(dataDir, 'created-panes.json'), 'utf8')),
123
+ { paneId: 'p2', name: 'reviewer', cwd: home, createdAt: 2, ownerSession: 'ses-owner' },
124
+ ])
125
+ );
126
+ await noticeNewOrphans(ctx);
127
+ assert.equal(prompts.length, 2, 'a newly orphaned sheep gets its own notice');
128
+ assert.match(prompts[1].text, /reviewer/);
129
+ console.log('PASS newly orphaned sheep are reported without repeating old ones');
130
+
131
+ // Reap closes only orphans owned by the caller and clears their registrations.
132
+ const result = reapOrphans('ses-owner');
133
+ assert.match(result, /reaped 3 orphaned sheep/);
134
+ assert.equal(fs.readFileSync(panesFile, 'utf8').trim(), '');
135
+ assert.equal(fs.readFileSync(terminalsFile, 'utf8').trim(), '');
136
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dataDir, 'created-panes.json'), 'utf8')), []);
137
+ assert.deepEqual(
138
+ JSON.parse(fs.readFileSync(path.join(dataDir, 'created-terminals.json'), 'utf8')),
139
+ []
140
+ );
141
+ assert.equal(fs.existsSync(paneDir), false, 'launch dir cleaned');
142
+ assert.equal(fs.existsSync(terminalDir), false);
143
+ assert.deepEqual(findOrphans(), []);
144
+ assert.match(reapOrphans('ses-owner'), /No orphaned sheep/);
145
+ console.log('PASS ownership-safe reap closes sheep, clears registries, and cleans launch dirs');
146
+
147
+ // A different owner's entry is never reaped by this session.
148
+ fs.writeFileSync(panesFile, 'p3\n');
149
+ fs.writeFileSync(
150
+ path.join(dataDir, 'created-panes.json'),
151
+ JSON.stringify([
152
+ { paneId: 'p3', name: 'planner', cwd: home, createdAt: 3, ownerSession: 'ses-other' },
153
+ ])
154
+ );
155
+ assert.deepEqual(findOrphans('ses-owner'), [], 'other sessions are filtered out');
156
+ assert.match(reapOrphans('ses-owner'), /No orphaned sheep/);
157
+ assert.equal(fs.readFileSync(panesFile, 'utf8').trim(), 'p3');
158
+ console.log('PASS reap never touches another session’s sheep');
159
+
160
+ console.log('\nAll orphan-recovery assertions passed.');
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * T016 — OpenCode harness, FR-001–FR-004 at the plugin surface.
4
+ *
5
+ * Loads the real plugin module (a module-load smoke test: a bad import can
6
+ * no longer sit unnoticed) and drives `setup` with a fake host to inspect
7
+ * the registered tool/command surface without a running OpenCode server.
8
+ */
9
+ import assert from 'node:assert/strict';
10
+
11
+ const plugin = (await import('../src/opencode/server.ts')).default;
12
+ assert.equal(plugin.id, 'shepherd', 'plugin definition loads with a stable id');
13
+ assert.equal(typeof plugin.setup, 'function', 'plugin exposes a setup effect');
14
+
15
+ const tools = new Map();
16
+ const commands = new Map();
17
+ const host = {
18
+ location: { directory: process.cwd() },
19
+ session: {
20
+ list: async () => [],
21
+ get: async () => ({}),
22
+ prompt: async () => {},
23
+ },
24
+ event: {
25
+ subscribe: () => ({
26
+ async *[Symbol.asyncIterator]() {
27
+ /* no events in this harness */
28
+ },
29
+ }),
30
+ },
31
+ tool: {
32
+ transform: fn =>
33
+ fn({
34
+ add: definition => tools.set(definition.name, definition),
35
+ }),
36
+ },
37
+ command: {
38
+ transform: fn =>
39
+ fn({
40
+ add: definition => commands.set(definition.name, definition),
41
+ }),
42
+ },
43
+ };
44
+ await plugin.setup(host);
45
+
46
+ const expectedTools = [
47
+ 'shepherd',
48
+ 'shepherd_spawn',
49
+ 'shepherd_status',
50
+ 'shepherd_read',
51
+ 'shepherd_close',
52
+ 'shepherd_delegate',
53
+ 'shepherd_watch',
54
+ 'shepherd_message',
55
+ 'shepherd_done',
56
+ ];
57
+ assert.deepEqual([...tools.keys()], expectedTools, 'FR-001: full parent + child tool family');
58
+ for (const [name, tool] of tools) {
59
+ assert.ok(tool.description?.length > 20, `${name} has a usable description`);
60
+ assert.equal(tool.input.additionalProperties, false, `${name} rejects unknown arguments`);
61
+ assert.equal(typeof tool.execute, 'function', `${name} has an executor`);
62
+ }
63
+ console.log('PASS FR-001: plugin registers the full Shepherd tool family');
64
+
65
+ assert.deepEqual(tools.get('shepherd').input.properties.action.enum, [
66
+ 'herd',
67
+ 'agents',
68
+ 'prune',
69
+ 'reap',
70
+ ]);
71
+ assert.equal(commands.size, 1, 'one human command');
72
+ assert.equal(commands.get('shepherd').name, 'shepherd');
73
+ const placement = tools.get('shepherd_spawn').input.properties.placement.description;
74
+ for (const value of ['pane_right', 'pane_down', 'tab', 'workspace']) {
75
+ assert.ok(placement.includes(value), `FR-002: ${value} placement is documented`);
76
+ }
77
+ const { OPENCODE_LAUNCH_OVERRIDES, OPENCODE_CHILD_COMMAND } = await import('../src/opencode/host.ts');
78
+ assert.equal(OPENCODE_LAUNCH_OVERRIDES.command, OPENCODE_CHILD_COMMAND);
79
+ assert.equal(OPENCODE_LAUNCH_OVERRIDES.command, 'opencode', 'FR-002: children boot the OpenCode CLI');
80
+ assert.equal(OPENCODE_LAUNCH_OVERRIDES.envPrefix, 'SHEPHERD_');
81
+ console.log('PASS FR-002: visible-pane launch overrides are exposed by the OpenCode host');
82
+
83
+ assert.deepEqual(tools.get('shepherd_done').input.properties.status.enum, [
84
+ 'completed',
85
+ 'blocked',
86
+ 'failed',
87
+ ]);
88
+ const { sheepDone } = await import('../src/opencode/actions.ts');
89
+ const { markParentSession } = await import('../src/opencode/bridge.ts');
90
+ markParentSession('parent-session');
91
+ await assert.rejects(
92
+ () => sheepDone({ cwd: process.cwd(), sessionId: 'parent-session' }, { status: 'completed' }, 'parent-session'),
93
+ /sheep-only tool/,
94
+ 'FR-003: a parent session cannot fabricate a child completion'
95
+ );
96
+ console.log('PASS FR-003: completion is child-only with an explicit terminal status');
97
+
98
+ const watchInput = tools.get('shepherd_watch').input.properties.id;
99
+ assert.ok(watchInput.anyOf?.some(entry => entry.type === 'array'), 'watch accepts a batch of task ids');
100
+ const bridgeSource = await import('node:fs').then(fs =>
101
+ fs.readFileSync(new URL('../src/opencode/bridge.ts', import.meta.url), 'utf8')
102
+ );
103
+ assert.match(bridgeSource, /parentsFor\(result\.taskId\)/, 'FR-004: settlement routes by task parent');
104
+ assert.match(bridgeSource, /is retried instead of silently dropped/, 'FR-004: parent notices are retried');
105
+ console.log('PASS FR-004: watch surface, parent-only notices, and bounded retry are wired');
106
+
107
+ console.log('\nAll OpenCode surface assertions passed.');
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * T014 — one package, two host entries.
4
+ *
5
+ * Verifies the manifest exposes the Pi extension entry and the OpenCode
6
+ * plugin entry, that a fresh tarball install contains both, and that a bare
7
+ * package import resolves to the OpenCode plugin (what `plugins` in
8
+ * opencode.json loads) without dragging in a host-specific tool path.
9
+ */
10
+ import assert from 'node:assert/strict';
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import { execFileSync } from 'node:child_process';
15
+
16
+ const repo = path.resolve(import.meta.dirname, '..');
17
+ const manifest = JSON.parse(fs.readFileSync(path.join(repo, 'package.json'), 'utf8'));
18
+
19
+ assert.deepEqual(manifest.pi?.extensions, ['./index.ts'], 'Pi extension entry is declared');
20
+ assert.ok(fs.existsSync(path.join(repo, 'index.ts')), 'Pi extension entry exists');
21
+ const opencodeEntry = manifest.exports?.['.'];
22
+ assert.ok(typeof opencodeEntry === 'string', 'package root exports the OpenCode entry');
23
+ assert.equal(opencodeEntry, './src/opencode/server.ts');
24
+ assert.ok(fs.existsSync(path.join(repo, opencodeEntry)), 'OpenCode plugin entry exists');
25
+ const pluginSource = fs.readFileSync(path.join(repo, opencodeEntry), 'utf8');
26
+ assert.match(pluginSource, /from "@opencode\/plugin"/);
27
+ assert.match(pluginSource, /Plugin\.define\(/);
28
+ assert.match(pluginSource, /id: "shepherd"/);
29
+ console.log('PASS manifest declares both host entries');
30
+
31
+ // Pack and install into an isolated consumer, the way each host's docs say.
32
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pi-shepherd-packaging-'));
33
+ const packResult = JSON.parse(
34
+ execFileSync('npm', ['pack', '--json', '--pack-destination', tmp], {
35
+ cwd: repo,
36
+ encoding: 'utf8',
37
+ stdio: ['ignore', 'pipe', 'pipe'],
38
+ })
39
+ );
40
+ const packed = Array.isArray(packResult) ? packResult[0] : Object.values(packResult)[0];
41
+ const tarball = path.join(tmp, packed.filename);
42
+ assert.ok(fs.existsSync(tarball), 'npm pack produced a tarball');
43
+ const names = new Set(packed.files.map(f => f.path));
44
+ assert.ok(names.has('index.ts'), 'tarball contains the Pi extension');
45
+ assert.ok(names.has('src/opencode/server.ts'), 'tarball contains the OpenCode plugin');
46
+ assert.ok(names.has('src/core/artifact-sessions.ts'), 'tarball contains the shared engine');
47
+ assert.ok(names.has('README.md'), 'tarball contains host docs');
48
+ console.log('PASS tarball contains both host entries and the shared engine');
49
+
50
+ const consumer = path.join(tmp, 'consumer');
51
+ fs.mkdirSync(consumer, { recursive: true });
52
+ fs.writeFileSync(
53
+ path.join(consumer, 'package.json'),
54
+ JSON.stringify({ name: 'shepherd-consumer', private: true, version: '1.0.0' })
55
+ );
56
+ // `npm run` exports npm_config_* values that a nested npm treats as a
57
+ // project-scoped script-approval directive; strip them for the fresh install.
58
+ const cleanEnv = Object.fromEntries(
59
+ Object.entries(process.env).filter(([key]) => !key.startsWith('npm_config_'))
60
+ );
61
+ execFileSync('npm', ['install', tarball, '--legacy-peer-deps', '--no-audit', '--no-fund'], {
62
+ cwd: consumer,
63
+ env: cleanEnv,
64
+ stdio: 'ignore',
65
+ });
66
+ const resolved = execFileSync(
67
+ process.execPath,
68
+ ['--input-type=module', '-e', 'console.log(import.meta.resolve("@luminascale/shepherd"))'],
69
+ { cwd: consumer, encoding: 'utf8' }
70
+ ).trim();
71
+ assert.match(resolved, /src[\\/]opencode[\\/]server\.ts$/, 'bare import resolves to the OpenCode plugin');
72
+ const installedManifest = JSON.parse(
73
+ fs.readFileSync(path.join(consumer, 'node_modules', '@luminascale', 'shepherd', 'package.json'), 'utf8')
74
+ );
75
+ assert.deepEqual(
76
+ installedManifest.pi.extensions,
77
+ ['./index.ts'],
78
+ 'installed manifest still declares the Pi entry'
79
+ );
80
+ console.log('PASS fresh install resolves both host entries independently');
81
+
82
+ console.log('\nAll packaging assertions passed.');
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Parent/worker registration boundary.
4
+ *
5
+ * Launched workers inherit the user extension set, but herdr.ts explicitly
6
+ * injects shepherd-done.ts as their worker-side Shepherd surface. The parent
7
+ * control plane must not also be registered in those sessions.
8
+ */
9
+ import assert from 'node:assert/strict';
10
+ import { spawnSync } from 'node:child_process';
11
+ import { fileURLToPath, pathToFileURL } from 'node:url';
12
+ import * as path from 'node:path';
13
+ import { parentMessageDeliveryOptions } from '../src/extension/shepherd.ts';
14
+
15
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
16
+ const indexUrl = pathToFileURL(path.join(root, 'index.ts')).href;
17
+ const probe = `
18
+ const calls = { tools: [], toolDetails: {}, commands: [], events: [] };
19
+ const pi = {
20
+ registerTool(tool) {
21
+ calls.tools.push(tool.name);
22
+ calls.toolDetails[tool.name] = {
23
+ description: tool.description,
24
+ promptGuidelines: tool.promptGuidelines,
25
+ };
26
+ },
27
+ registerCommand(name) { calls.commands.push(name); },
28
+ registerMessageRenderer() {},
29
+ on(event) { calls.events.push(event); },
30
+ };
31
+ const mod = await import(${JSON.stringify(indexUrl)});
32
+ mod.default(pi);
33
+ console.log(JSON.stringify(calls));
34
+ `;
35
+
36
+ function run(worker) {
37
+ const env = { ...process.env };
38
+ if (worker) env.PI_SHEPHERD_SESSION = '/tmp/pi-shepherd-worker-session.jsonl';
39
+ else delete env.PI_SHEPHERD_SESSION;
40
+ const result = spawnSync(
41
+ process.execPath,
42
+ [
43
+ '--experimental-strip-types',
44
+ '--disable-warning=ExperimentalWarning',
45
+ '--input-type=module',
46
+ '--eval',
47
+ probe,
48
+ ],
49
+ { cwd: root, env, encoding: 'utf8' }
50
+ );
51
+ assert.equal(result.status, 0, `${worker ? 'worker' : 'parent'} probe failed: ${result.stderr}`);
52
+ const line = result.stdout.trim().split('\n').at(-1);
53
+ return JSON.parse(line);
54
+ }
55
+
56
+ const parent = run(false);
57
+ const worker = run(true);
58
+
59
+ assert.equal(parent.tools.length, 9, 'parent registers the umbrella and eight lifecycle tools');
60
+ assert.ok(parent.tools.includes('shepherd'), 'parent registers the umbrella shepherd tool');
61
+ assert.ok(parent.tools.includes('shepherd_delegate'), 'parent registers tracked delegation');
62
+ assert.ok(parent.commands.includes('shepherd'), 'parent registers the /shepherd command');
63
+ const umbrella = parent.toolDetails.shepherd;
64
+ assert.ok(
65
+ umbrella.description.includes('shepherd_spawn'),
66
+ 'umbrella description names the lifecycle tools'
67
+ );
68
+ assert.ok(
69
+ umbrella.description.includes('shepherd_delegate'),
70
+ 'umbrella description names tracked delegation'
71
+ );
72
+ const guidance = umbrella.promptGuidelines.join(' ');
73
+ assert.ok(
74
+ guidance.includes('shepherd_watch'),
75
+ 'umbrella guidance explains the non-blocking lifecycle workflow'
76
+ );
77
+ assert.ok(guidance.includes('shepherd_watch'), 'umbrella guidance explains asynchronous watching');
78
+ assert.ok(guidance.includes('shepherd_delegate'), 'umbrella guidance explains tracked delegation');
79
+ assert.ok(guidance.includes('close each agent'), 'umbrella guidance explains close semantics');
80
+ assert.ok(guidance.includes('shepherd.md'), 'umbrella guidance explains fieldnotes');
81
+ const messageTool = parent.toolDetails.shepherd_message;
82
+ assert.ok(
83
+ messageTool.description.includes('exact opaque agent id returned by shepherd_spawn'),
84
+ 'message description requires the exact spawned id'
85
+ );
86
+ assert.ok(
87
+ messageTool.description.includes('agent definition name'),
88
+ 'message description rejects definition names'
89
+ );
90
+ assert.ok(
91
+ messageTool.description.includes('will be rejected'),
92
+ 'message description promises invalid-target rejection'
93
+ );
94
+ assert.ok(
95
+ messageTool.promptGuidelines.join(' ').includes('angle-bracket placeholder'),
96
+ 'message guidance rejects unresolved placeholders'
97
+ );
98
+ assert.equal(worker.tools.length, 0, 'worker does not register parent Shepherd tools');
99
+ assert.equal(worker.commands.length, 0, 'worker does not register parent Shepherd commands');
100
+ assert.deepEqual(
101
+ parentMessageDeliveryOptions({ kind: 'message' }),
102
+ { deliverAs: 'followUp', triggerTurn: false },
103
+ 'ordinary child messages remain passive'
104
+ );
105
+ assert.deepEqual(
106
+ parentMessageDeliveryOptions({ kind: 'message', expectsReply: true }),
107
+ { deliverAs: 'steer', triggerTurn: true },
108
+ 'child requests wake the parent to answer'
109
+ );
110
+ assert.deepEqual(
111
+ parentMessageDeliveryOptions({ kind: 'reply' }),
112
+ { deliverAs: 'steer', triggerTurn: true },
113
+ 'child replies wake the parent to resume waiting work'
114
+ );
115
+
116
+ console.log('PASS parent registers the Shepherd control plane');
117
+ console.log('PASS launched worker excludes parent Shepherd tools and commands');
118
+ console.log('All parent-surface assertions passed.');
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Phase 0 guardrails and test-fixture verification.
4
+ *
5
+ * This test deliberately exercises the existing prompt registry without
6
+ * introducing task runtime behavior. It documents the boundary that the task
7
+ * implementation must preserve: process/agent state can change independently
8
+ * of explicit lifecycle settlement.
9
+ */
10
+ import assert from 'node:assert/strict';
11
+ import { LifecycleRegistry } from '../src/core/orchestration.ts';
12
+ import { createManualClock, withFakeDateNow } from './helpers/fake-clock.mjs';
13
+ import {
14
+ createFakeChildIdentity,
15
+ createFakeParentIdentity,
16
+ flushMicrotasks,
17
+ withTempDirectory,
18
+ } from './helpers/test-utils.mjs';
19
+ import {
20
+ plannedChildOnlyTools,
21
+ plannedParentOnlyTools,
22
+ plannedTaskStates,
23
+ plannedToolContracts,
24
+ } from './helpers/feature-contracts.mjs';
25
+ import * as fs from 'node:fs';
26
+ import * as path from 'node:path';
27
+
28
+ const parent = createFakeParentIdentity();
29
+ const child = createFakeChildIdentity();
30
+ assert.equal(parent.role, 'parent');
31
+ assert.equal(child.role, 'child');
32
+ assert.equal(parent.sessionId, child.sessionId);
33
+ console.log('PASS reusable parent/child test identities share a session');
34
+
35
+ await withTempDirectory('pi-shepherd-phase0-', async directory => {
36
+ const marker = path.join(directory, 'fixture-marker.txt');
37
+ fs.writeFileSync(marker, 'isolated');
38
+ assert.equal(fs.readFileSync(marker, 'utf8'), 'isolated');
39
+ assert.ok(directory.includes('pi-shepherd-phase0-'));
40
+ });
41
+ console.log('PASS temporary test directories are isolated and cleaned up');
42
+
43
+ const clock = createManualClock(1_000);
44
+ assert.equal(clock.now(), 1_000);
45
+ assert.equal(clock.advance(500), 1_500);
46
+ assert.equal(clock.set(9_000), 9_000);
47
+ await withFakeDateNow(42_000, async controlled => {
48
+ assert.equal(Date.now(), 42_000);
49
+ controlled.advance(1_000);
50
+ assert.equal(Date.now(), 43_000);
51
+ await flushMicrotasks();
52
+ });
53
+ console.log('PASS deterministic clock helpers control synchronous and async test time');
54
+
55
+ assert.deepEqual(Object.keys(plannedToolContracts), [
56
+ 'shepherd_delegate',
57
+ 'shepherd_message',
58
+ 'shepherd_done',
59
+ 'shepherd_watch',
60
+ ]);
61
+ assert.deepEqual(plannedParentOnlyTools, ['shepherd_delegate', 'shepherd_watch']);
62
+ assert.deepEqual(plannedChildOnlyTools, ['shepherd_done']);
63
+ assert.ok(plannedTaskStates.includes('waiting'));
64
+ assert.ok(plannedTaskStates.includes('completed'));
65
+ assert.ok(plannedTaskStates.includes('timed_out'));
66
+ for (const contract of Object.values(plannedToolContracts)) {
67
+ assert.equal(contract.rootType, 'object');
68
+ assert.ok(contract.required.length > 0);
69
+ }
70
+ console.log('PASS future tool, surface, and task-state contract placeholders are centralized');
71
+
72
+ const registry = new LifecycleRegistry();
73
+ const agent = registry.registerAgent({ agent: 'scout', label: 'phase 0 guardrail' });
74
+ const prompt = registry.createPrompt(agent);
75
+
76
+ // This is the explicit-settlement guard for the future task registry. A child
77
+ // may become idle between turns, but an open delegated task must remain open
78
+ // until shepherd_done (or an explicit failure/cancellation/timeout) settles it.
79
+ registry.setAgentState(agent, 'idle');
80
+ assert.equal(registry.status(agent).state, 'idle');
81
+ assert.equal(registry.promptResult(prompt.id), undefined);
82
+ assert.equal(registry.getPrompt(prompt.id).settled, false);
83
+ console.log('PASS agent idle state does not itself settle an open lifecycle record');
84
+
85
+ registry.settlePrompt(prompt, {
86
+ promptId: prompt.id,
87
+ agentId: prompt.agentId,
88
+ status: 'done',
89
+ ok: true,
90
+ text: 'explicit settlement',
91
+ });
92
+ assert.equal(registry.promptResult(prompt.id)?.text, 'explicit settlement');
93
+ console.log('PASS lifecycle record settles only after an explicit settlement call');
94
+
95
+ console.log('All Phase 0 guardrail assertions passed.');