@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,329 @@
1
+ /**
2
+ * Persistent pi-shepherd settings.
3
+ *
4
+ * The user file stores personal values. The project file is anchored at the
5
+ * current cwd and, when it carries `projectScope: true`, is a self-contained
6
+ * source for project-overridable values. `confirmProjectAgents` and `backend`
7
+ * are deliberately user-owned: a repository must not be able to change its
8
+ * trust gate or force a runtime for everyone; built-in defaults run
9
+ * project-local agents without a prompt and `auto` runs where called from.
10
+ * `backend` is app-side only — no `shepherd_*` tool schema, prompt snippet,
11
+ * or result mentions it, and the model never decides the runtime.
12
+ */
13
+
14
+ import * as fs from 'node:fs';
15
+ import * as path from 'node:path';
16
+ import { hostCapabilities } from './host.ts';
17
+ import type { AgentScope } from './discovery.ts';
18
+
19
+ /** Fields that a project config may own.
20
+ * `confirmProjectAgents` and `backend` stay user-owned: a repository must
21
+ * not force a trust gate or a runtime for everyone. */
22
+ const PROJECT_FIELDS = [
23
+ 'agentScope',
24
+ 'includeBundledAgents',
25
+ 'keepOpen',
26
+ 'stayOpen',
27
+ 'fieldnotes',
28
+ 'emojiSheep',
29
+ 'timeout',
30
+ 'staleWaitThreshold',
31
+ ] as const;
32
+ type ProjectField = (typeof PROJECT_FIELDS)[number];
33
+
34
+ /** Fields stored in the trusted user config.
35
+ * `confirmProjectAgents` and `backend` are user-owned (see above). */
36
+ const USER_FIELDS = [...PROJECT_FIELDS, 'confirmProjectAgents', 'backend'] as const;
37
+ type UserField = (typeof USER_FIELDS)[number];
38
+
39
+ /** Execution backend pin. App-side only; the model never decides.
40
+ * `auto` runs where called from (see `detectCaller`), `herdr`/`hc` pin to
41
+ * one runtime and fail cleanly when it is unreachable (no fallback). */
42
+ export type BackendSetting = 'auto' | 'herdr' | 'hc';
43
+
44
+ /** Concrete runtime selected by `resolveBackend`. Never `auto`. */
45
+ export type ResolvedBackend = 'herdr' | 'hc';
46
+
47
+ export interface ShepherdSettings {
48
+ /** True when the current cwd's project file is the active source. */
49
+ projectScope: boolean;
50
+ /** Which agent definition directories to search. */
51
+ agentScope: AgentScope;
52
+ /** Include pi-shepherd's bundled agent definitions. */
53
+ includeBundledAgents: boolean;
54
+ /** User-owned security gate for project-local agent definitions (default off). */
55
+ confirmProjectAgents: boolean;
56
+ /** User-owned backend pin (default auto). Project files cannot force it. */
57
+ backend: BackendSetting;
58
+ /** Keep the Herdr tab open after completion. */
59
+ keepOpen: boolean;
60
+ /** Keep the child pi process alive after completion. */
61
+ stayOpen: boolean;
62
+ /** Create durable fieldnotes for delegated prompts. */
63
+ fieldnotes: boolean;
64
+ /** Show the animated sheep marker beside active agents. */
65
+ emojiSheep: boolean;
66
+ /** Default delegated-run timeout in minutes. */
67
+ timeout: number;
68
+ /** Minutes before one stale-wait reminder; values below one disable it. */
69
+ staleWaitThreshold: number;
70
+ }
71
+
72
+ export const DEFAULT_SETTINGS: ShepherdSettings = {
73
+ projectScope: false,
74
+ agentScope: 'both',
75
+ includeBundledAgents: true,
76
+ confirmProjectAgents: false,
77
+ backend: 'auto',
78
+ keepOpen: true,
79
+ stayOpen: true,
80
+ fieldnotes: true,
81
+ emojiSheep: true,
82
+ timeout: 60,
83
+ staleWaitThreshold: 30,
84
+ };
85
+
86
+ export function userConfigFile(): string {
87
+ const host = hostCapabilities();
88
+ return path.join(host.getAgentDir(), host.dataDirName, 'config.json');
89
+ }
90
+
91
+ export function projectConfigFile(projectRoot: string): string {
92
+ return path.resolve(projectRoot, '.shepherd', 'config.json');
93
+ }
94
+
95
+ function validAgentScope(value: unknown): AgentScope {
96
+ return value === 'user' || value === 'project' || value === 'both'
97
+ ? value
98
+ : DEFAULT_SETTINGS.agentScope;
99
+ }
100
+
101
+ /** Timeout is persisted in minutes; old millisecond values are migrated. */
102
+ function validTimeout(value: unknown): number {
103
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
104
+ return DEFAULT_SETTINGS.timeout;
105
+ return value >= 1000 ? Math.max(1, Math.round(value / 60_000)) : value;
106
+ }
107
+
108
+ /** Zero and negative stale thresholds intentionally disable reminders. */
109
+ function validStaleWaitThreshold(value: unknown): number {
110
+ return typeof value === 'number' && Number.isFinite(value)
111
+ ? value
112
+ : DEFAULT_SETTINGS.staleWaitThreshold;
113
+ }
114
+
115
+ function validField(field: UserField, raw: Record<string, unknown>): unknown {
116
+ const value = raw[field];
117
+ if (value === undefined) return undefined;
118
+ switch (field) {
119
+ case 'agentScope':
120
+ return validAgentScope(value);
121
+ case 'backend':
122
+ return value === 'auto' || value === 'herdr' || value === 'hc' ? value : undefined;
123
+ case 'timeout':
124
+ return validTimeout(value);
125
+ case 'staleWaitThreshold':
126
+ return validStaleWaitThreshold(value);
127
+ case 'includeBundledAgents':
128
+ case 'confirmProjectAgents':
129
+ case 'keepOpen':
130
+ case 'stayOpen':
131
+ case 'fieldnotes':
132
+ case 'emojiSheep':
133
+ return typeof value === 'boolean' ? value : undefined;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Parse one config layer, retaining only validated fields that were present.
139
+ * `confirmProjectAgents` and `backend` in a project file are intentionally
140
+ * excluded from project-owned values (user-owned precedence).
141
+ */
142
+ function validateLayer(raw: unknown, projectLayer: boolean): Partial<ShepherdSettings> | undefined {
143
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined;
144
+ const record = raw as Record<string, unknown>;
145
+ const partial: Partial<ShepherdSettings> = {};
146
+ for (const field of USER_FIELDS) {
147
+ if (projectLayer && (field === 'confirmProjectAgents' || field === 'backend')) continue;
148
+ const value = validField(field, record);
149
+ if (value !== undefined) (partial as Record<string, unknown>)[field] = value;
150
+ }
151
+ if (projectLayer) {
152
+ if (typeof record.projectScope === 'boolean') {
153
+ partial.projectScope = record.projectScope;
154
+ } else if (record.settingsScope === 'project') {
155
+ // Read-only compatibility with the intermediate project-file format.
156
+ partial.projectScope = true;
157
+ }
158
+ }
159
+ return partial;
160
+ }
161
+
162
+ interface LayerCacheEntry {
163
+ mtimeMs: number;
164
+ partial: Partial<ShepherdSettings>;
165
+ }
166
+
167
+ const layerCache = new Map<string, LayerCacheEntry>();
168
+
169
+ function readPartialLayer(
170
+ file: string,
171
+ projectLayer: boolean
172
+ ): Partial<ShepherdSettings> | undefined {
173
+ let mtimeMs: number;
174
+ let text: string;
175
+ try {
176
+ mtimeMs = fs.statSync(file).mtimeMs;
177
+ text = fs.readFileSync(file, 'utf8');
178
+ } catch {
179
+ return undefined;
180
+ }
181
+ const cached = layerCache.get(file);
182
+ if (cached && cached.mtimeMs === mtimeMs) return cached.partial;
183
+ let raw: unknown;
184
+ try {
185
+ raw = JSON.parse(text);
186
+ } catch {
187
+ return undefined;
188
+ }
189
+ const partial = validateLayer(raw, projectLayer);
190
+ if (partial) layerCache.set(file, { mtimeMs, partial });
191
+ return partial;
192
+ }
193
+
194
+ /**
195
+ * Migrate the old user-level settings filename once. The new config wins when
196
+ * both files exist, and the legacy file is intentionally left untouched then.
197
+ */
198
+ function migrateLegacySettingsFile(newFile: string): void {
199
+ const legacyFile = path.join(path.dirname(newFile), 'settings.json');
200
+ let legacyReal: string;
201
+ try {
202
+ legacyReal = fs.realpathSync(legacyFile);
203
+ } catch {
204
+ return;
205
+ }
206
+ let existingReal: string | undefined;
207
+ try {
208
+ existingReal = fs.realpathSync(newFile);
209
+ } catch {
210
+ // The new file does not exist and may be replaced by the legacy file.
211
+ }
212
+ if (existingReal) {
213
+ if (existingReal !== legacyReal) layerCache.delete(newFile);
214
+ return;
215
+ }
216
+ try {
217
+ fs.renameSync(legacyFile, newFile);
218
+ layerCache.delete(newFile);
219
+ } catch {
220
+ // Best effort: the legacy file remains available for the next attempt.
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Resolve settings for one workspace. An active project file starts from built-in
226
+ * defaults; only the user-owned confirmation gate and backend pin come from
227
+ * the user layer (a project file can never force a runtime for everyone).
228
+ */
229
+ export function loadSettings(cwd?: string): ShepherdSettings {
230
+ const userFile = userConfigFile();
231
+ migrateLegacySettingsFile(userFile);
232
+ const user = {
233
+ ...DEFAULT_SETTINGS,
234
+ ...readPartialLayer(userFile, false),
235
+ projectScope: false,
236
+ } as ShepherdSettings;
237
+ if (typeof cwd !== 'string' || cwd.length === 0) return user;
238
+
239
+ const project = readPartialLayer(projectConfigFile(cwd), true);
240
+ if (!project?.projectScope) return user;
241
+ return {
242
+ ...DEFAULT_SETTINGS,
243
+ ...project,
244
+ projectScope: true,
245
+ confirmProjectAgents: user.confirmProjectAgents,
246
+ backend: user.backend,
247
+ };
248
+ }
249
+
250
+ /**
251
+ * Return parked project values for menu activation. Missing fields use built-in
252
+ * defaults, never the current user's private values.
253
+ */
254
+ export function loadProjectFileValues(projectRoot: string): Pick<ShepherdSettings, ProjectField> {
255
+ const project = readPartialLayer(projectConfigFile(projectRoot), true);
256
+ const values = {} as Record<ProjectField, unknown>;
257
+ for (const field of PROJECT_FIELDS) {
258
+ const value = project?.[field];
259
+ values[field] = value !== undefined ? value : DEFAULT_SETTINGS[field];
260
+ }
261
+ return values as Pick<ShepherdSettings, ProjectField>;
262
+ }
263
+
264
+ /**
265
+ * Persist one layer. User files contain every user field; project files contain
266
+ * every project-owned field and the boolean activation flag.
267
+ */
268
+ export function saveSettings(
269
+ next: ShepherdSettings,
270
+ scope: 'user' | 'project' = 'user',
271
+ projectRoot?: string
272
+ ): { file: string; created: boolean } {
273
+ let file: string;
274
+ if (scope === 'project') {
275
+ if (!projectRoot) throw new Error('projectRoot is required to save the project config layer');
276
+ file = projectConfigFile(projectRoot);
277
+ } else {
278
+ file = userConfigFile();
279
+ }
280
+ const existed = fs.existsSync(file);
281
+ const output: Record<string, unknown> = {};
282
+ if (scope === 'project') {
283
+ for (const field of PROJECT_FIELDS) output[field] = next[field];
284
+ output.projectScope = next.projectScope;
285
+ } else {
286
+ for (const field of USER_FIELDS) output[field] = next[field];
287
+ }
288
+ fs.mkdirSync(path.dirname(file), { recursive: true });
289
+ fs.writeFileSync(file, JSON.stringify(output, null, 2));
290
+ const partial = validateLayer(output, scope === 'project') ?? {};
291
+ layerCache.set(file, { mtimeMs: fs.statSync(file).mtimeMs, partial });
292
+ return { file, created: !existed };
293
+ }
294
+
295
+ /**
296
+ * Deactivate one workspace without deleting its parked settings. Any valid
297
+ * object other than an already-false flag is normalized to the boolean form;
298
+ * this includes keyless and legacy-string project files.
299
+ */
300
+ export function deactivateProjectScope(projectRoot: string): { file: string; changed: boolean } {
301
+ const file = projectConfigFile(projectRoot);
302
+ let raw: unknown;
303
+ try {
304
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'));
305
+ } catch {
306
+ return { file, changed: false };
307
+ }
308
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
309
+ return { file, changed: false };
310
+ const record = { ...(raw as Record<string, unknown>) };
311
+ if (record.projectScope === false) return { file, changed: false };
312
+ record.projectScope = false;
313
+ delete record.settingsScope;
314
+ fs.writeFileSync(file, JSON.stringify(record, null, 2));
315
+ const partial = validateLayer(record, true) ?? {};
316
+ layerCache.set(file, { mtimeMs: fs.statSync(file).mtimeMs, partial });
317
+ return { file, changed: true };
318
+ }
319
+
320
+ // Fieldnotes are session-scoped so a running parent session has one stable mode.
321
+ let sessionFieldnotesEnabled: boolean | undefined;
322
+
323
+ export function initializeSessionSettings(cwd?: string): void {
324
+ sessionFieldnotesEnabled = loadSettings(cwd).fieldnotes;
325
+ }
326
+
327
+ export function fieldnotesEnabled(): boolean {
328
+ return sessionFieldnotesEnabled ?? loadSettings().fieldnotes;
329
+ }
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Phase 1 — Agent discovery.
3
+ *
4
+ * Pure filesystem + frontmatter parsing. No LLM calls, no pi session APIs.
5
+ *
6
+ * Reads agent definitions from the standard VS Code custom-agent syntax
7
+ * (YAML frontmatter + Markdown body) across user, project and bundled
8
+ * locations, in a fixed precedence order. On a name collision the EARLIER
9
+ * location in that order wins (first-write-with-guard).
10
+ */
11
+
12
+ import * as fs from 'node:fs';
13
+ import * as os from 'node:os';
14
+ import * as path from 'node:path';
15
+ import * as url from 'node:url';
16
+ import { hostCapabilities } from './host.ts';
17
+
18
+ export type AgentScope = 'user' | 'project' | 'both';
19
+
20
+ /** Thinking levels accepted by Pi's model/session configuration. */
21
+ export type AgentThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
22
+
23
+ const THINKING_LEVELS: readonly AgentThinkingLevel[] = [
24
+ 'off',
25
+ 'minimal',
26
+ 'low',
27
+ 'medium',
28
+ 'high',
29
+ 'xhigh',
30
+ 'max',
31
+ ];
32
+
33
+ /** The part of pi's current model needed to inherit its provider-qualified name. */
34
+ export type DelegatorModel = { provider: string; id: string };
35
+
36
+ export interface AgentConfig {
37
+ name: string;
38
+ description: string;
39
+ tools?: string[];
40
+ model?: string;
41
+ /** Requested Pi thinking level; absent means inherit the delegator's level. */
42
+ thinking?: AgentThinkingLevel;
43
+ /** Omit pi's built-in default system prompt when delegating this agent. */
44
+ omitSystemPrompt?: boolean;
45
+ /** Omit Pi's built-in documentation guidance from the delegated prompt. */
46
+ omitPiDocumentation: boolean;
47
+ /** Omit Pi's automatic AGENTS.md/CLAUDE.md context-file loading. */
48
+ omitContextFiles: boolean;
49
+ systemPrompt: string;
50
+ source: 'user' | 'project' | 'bundled';
51
+ filePath: string;
52
+ /** Whether the agent is intended to be directly invoked by a user. */
53
+ userInvocable: boolean;
54
+ }
55
+
56
+ export interface AgentDiscoveryResult {
57
+ agents: AgentConfig[];
58
+ projectDirs: string[];
59
+ }
60
+
61
+ type Source = 'user' | 'project' | 'bundled';
62
+
63
+ /** A candidate directory plus which source bucket it belongs to. */
64
+ interface Location {
65
+ dir: string;
66
+ source: Source;
67
+ }
68
+
69
+ function isDirectory(p: string): boolean {
70
+ try {
71
+ return fs.statSync(p).isDirectory();
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Walk up from `cwd` to the filesystem root, returning the nearest ancestor
79
+ * (including cwd itself) whose `<ancestor>/<subdir>/agents` is a directory.
80
+ */
81
+ function findNearestProjectAgentsDir(cwd: string, subdir: string): string | null {
82
+ let current = cwd;
83
+ while (true) {
84
+ const candidate = path.join(current, subdir, 'agents');
85
+ if (isDirectory(candidate)) return candidate;
86
+
87
+ const parent = path.dirname(current);
88
+ if (parent === current) return null;
89
+ current = parent;
90
+ }
91
+ }
92
+
93
+ /** Normalize a model frontmatter value. Missing, null, empty, and whitespace-only
94
+ * values mean the agent inherits the delegator's model. */
95
+ export function normalizeModel(model: unknown): string | undefined {
96
+ if (typeof model !== 'string') return undefined;
97
+ const normalized = model.trim();
98
+ if (!normalized) return undefined;
99
+ if (normalized.toLowerCase() === 'none') {
100
+ throw new Error(
101
+ 'Invalid model value "none"; agents must select a model or inherit the parent model.'
102
+ );
103
+ }
104
+ return normalized;
105
+ }
106
+
107
+ /** Normalize an agent thinking value. Missing, null, empty, and `default` values
108
+ * inherit the delegator's current level. Explicit Pi levels are retained. */
109
+ export function normalizeThinking(value: unknown): AgentThinkingLevel | undefined {
110
+ if (value === undefined || value === null) return undefined;
111
+ if (typeof value !== 'string') {
112
+ throw new Error(
113
+ 'Invalid thinking value; expected default, off, minimal, low, medium, high, xhigh, or max.'
114
+ );
115
+ }
116
+ const normalized = value.trim().toLowerCase();
117
+ if (!normalized || normalized === 'default') return undefined;
118
+ if ((THINKING_LEVELS as readonly string[]).includes(normalized)) {
119
+ return normalized as AgentThinkingLevel;
120
+ }
121
+ throw new Error(
122
+ `Invalid thinking level "${value}"; expected default, off, minimal, low, medium, high, xhigh, or max.`
123
+ );
124
+ }
125
+
126
+ /** Resolve the requested child thinking level. Explicit agent values win;
127
+ * otherwise the parent level is passed through for Pi to clamp to the child
128
+ * model's supported levels. */
129
+ export function resolveDelegatedThinking(
130
+ agentThinking: unknown,
131
+ parentThinking: unknown
132
+ ): AgentThinkingLevel | undefined {
133
+ return normalizeThinking(agentThinking) ?? normalizeThinking(parentThinking);
134
+ }
135
+
136
+ /** Resolve the model passed to a child pi process. An explicit agent model
137
+ * wins; otherwise inherit the parent's provider/id when both are available. */
138
+ export function resolveDelegatedModel(
139
+ agentModel: unknown,
140
+ parentModel: DelegatorModel | undefined
141
+ ): string | undefined {
142
+ const explicit = normalizeModel(agentModel);
143
+ // The orchestration API uses "default" as a sentinel when no model was
144
+ // selected. It means inherit the parent model; it is not a Pi model id.
145
+ if (explicit && explicit.toLowerCase() !== 'default') return explicit;
146
+ if (!parentModel || typeof parentModel !== 'object') return undefined;
147
+ const model = parentModel as { provider?: unknown; id?: unknown };
148
+ const provider = normalizeModel(model.provider);
149
+ const id = normalizeModel(model.id);
150
+ return provider && id ? `${provider}/${id}` : undefined;
151
+ }
152
+
153
+ function normalizeTools(tools: unknown): string[] | undefined {
154
+ if (tools === undefined || tools === null) return undefined;
155
+
156
+ let items: unknown[];
157
+ if (Array.isArray(tools)) {
158
+ items = tools;
159
+ } else if (typeof tools === 'string') {
160
+ items = tools.split(',');
161
+ } else {
162
+ return undefined;
163
+ }
164
+
165
+ const cleaned = items
166
+ .map(t => (typeof t === 'string' ? t.trim() : String(t).trim()))
167
+ .filter(t => t.length > 0);
168
+
169
+ return cleaned.length > 0 ? cleaned : undefined;
170
+ }
171
+
172
+ /**
173
+ * Read every `.md` / `.agent.md` file in a directory, returning parsed
174
+ * AgentConfigs. Files missing a name or description are skipped. Within a
175
+ * directory, if two files share a name the EARLIER one read wins.
176
+ */
177
+ function loadAgentsFromDir(dir: string, source: Source): AgentConfig[] {
178
+ if (!isDirectory(dir)) return [];
179
+
180
+ const agents: AgentConfig[] = [];
181
+ const seen = new Set<string>();
182
+
183
+ let entries: fs.Dirent[];
184
+ try {
185
+ entries = fs.readdirSync(dir, { withFileTypes: true });
186
+ } catch {
187
+ return agents;
188
+ }
189
+
190
+ for (const entry of entries) {
191
+ const name = entry.name;
192
+ if (!name.endsWith('.md') && !name.endsWith('.agent.md')) continue;
193
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;
194
+
195
+ const filePath = path.join(dir, name);
196
+ let content: string;
197
+ try {
198
+ content = fs.readFileSync(filePath, 'utf-8');
199
+ } catch {
200
+ continue;
201
+ }
202
+
203
+ const { frontmatter, body } = hostCapabilities().parseFrontmatter<Record<string, unknown>>(
204
+ content
205
+ );
206
+
207
+ const agentName = frontmatter.name;
208
+ const description = frontmatter.description;
209
+ if (typeof agentName !== 'string' || agentName.length === 0) continue;
210
+ if (typeof description !== 'string' || description.length === 0) continue;
211
+ if (seen.has(agentName)) continue; // earlier valid file in this dir wins
212
+
213
+ try {
214
+ agents.push({
215
+ name: agentName,
216
+ description,
217
+ tools: normalizeTools(frontmatter.tools),
218
+ model: normalizeModel(frontmatter.model),
219
+ thinking: normalizeThinking(frontmatter.thinking),
220
+ systemPrompt: body,
221
+ source,
222
+ filePath,
223
+ // Only a YAML boolean is accepted; absent or malformed values default true.
224
+ userInvocable:
225
+ typeof frontmatter['user-invocable'] === 'boolean' ? frontmatter['user-invocable'] : true,
226
+ // Only the YAML boolean is accepted; malformed values are ignored.
227
+ omitSystemPrompt:
228
+ typeof frontmatter['omit-system-prompt'] === 'boolean'
229
+ ? frontmatter['omit-system-prompt']
230
+ : undefined,
231
+ // Only the YAML boolean is accepted; malformed values are ignored.
232
+ omitPiDocumentation:
233
+ typeof frontmatter['omit-pi-documentation'] === 'boolean'
234
+ ? frontmatter['omit-pi-documentation']
235
+ : false,
236
+ // Only the YAML boolean is accepted; quoted strings default to false.
237
+ omitContextFiles:
238
+ typeof frontmatter['omit-context-files'] === 'boolean'
239
+ ? frontmatter['omit-context-files']
240
+ : false,
241
+ });
242
+ seen.add(agentName);
243
+ } catch {
244
+ // A malformed definition must not prevent discovery of other agents.
245
+ continue;
246
+ }
247
+ }
248
+
249
+ return agents;
250
+ }
251
+
252
+ /**
253
+ * Build the ordered list of locations to scan for a given scope.
254
+ * Precedence (1 highest, 6 lowest):
255
+ * 1 user: getAgentDir()/agents (~/.pi/agent/agents)
256
+ * 2 user: os.homedir()/.agents/agents
257
+ * 3 project: nearest ancestor with <anc>/ .pi/agents
258
+ * 4 project: nearest ancestor with <anc>/ .agents/agents
259
+ * 5 bundled: <pkg>/.pi/agents
260
+ * 6 bundled: <pkg>/.agents/agents
261
+ */
262
+ function buildLocations(
263
+ cwd: string,
264
+ scope: AgentScope,
265
+ projectDirs: string[],
266
+ includeBundled: boolean
267
+ ): Location[] {
268
+ const locations: Location[] = [];
269
+
270
+ // Bundled base set (lowest precedence): pi-shepherd's own agent dirs.
271
+ // discovery.ts lives in src/core, so walk back to the package root before
272
+ // resolving the bundled agent directories. Using the module directory
273
+ // directly would incorrectly look under src/core/.agents.
274
+ const pkgDir = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '../..');
275
+ const bundledPi = path.join(pkgDir, '.pi', 'agents');
276
+ const bundledAgents = path.join(pkgDir, '.agents', 'agents');
277
+
278
+ if (scope === 'user' || scope === 'both') {
279
+ locations.push({ dir: path.join(hostCapabilities().getAgentDir(), 'agents'), source: 'user' });
280
+ locations.push({ dir: path.join(os.homedir(), '.agents', 'agents'), source: 'user' });
281
+ }
282
+
283
+ if (scope === 'project' || scope === 'both') {
284
+ const piDir = findNearestProjectAgentsDir(cwd, hostCapabilities().projectConfigDirName);
285
+ if (piDir) {
286
+ locations.push({ dir: piDir, source: 'project' });
287
+ projectDirs.push(piDir);
288
+ }
289
+ const agentsDir = findNearestProjectAgentsDir(cwd, '.agents');
290
+ if (agentsDir) {
291
+ locations.push({ dir: agentsDir, source: 'project' });
292
+ projectDirs.push(agentsDir);
293
+ }
294
+ }
295
+
296
+ if (includeBundled) {
297
+ locations.push({ dir: bundledPi, source: 'bundled' });
298
+ locations.push({ dir: bundledAgents, source: 'bundled' });
299
+ }
300
+
301
+ return locations;
302
+ }
303
+
304
+ export interface DiscoveryOptions {
305
+ /** When false, skip bundled agent locations (scout, planner, worker, reviewer). */
306
+ includeBundled?: boolean;
307
+ }
308
+
309
+ export function discoverAgents(
310
+ cwd: string,
311
+ scope: AgentScope,
312
+ options: DiscoveryOptions = {}
313
+ ): AgentDiscoveryResult {
314
+ const projectDirs: string[] = [];
315
+ const locations = buildLocations(cwd, scope, projectDirs, options.includeBundled !== false);
316
+
317
+ // First-write-with-guard: the first location (highest precedence) that
318
+ // declares a given name wins; later duplicate names are dropped.
319
+ const agentMap = new Map<string, AgentConfig>();
320
+ for (const loc of locations) {
321
+ for (const agent of loadAgentsFromDir(loc.dir, loc.source)) {
322
+ if (!agentMap.has(agent.name)) {
323
+ agentMap.set(agent.name, agent);
324
+ }
325
+ }
326
+ }
327
+
328
+ return { agents: Array.from(agentMap.values()), projectDirs };
329
+ }
330
+
331
+ export function formatAgentList(
332
+ agents: AgentConfig[],
333
+ maxItems: number
334
+ ): { text: string; remaining: number } {
335
+ if (agents.length === 0) return { text: 'none', remaining: 0 };
336
+ const listed = agents.slice(0, maxItems);
337
+ const remaining = agents.length - listed.length;
338
+ return {
339
+ text: listed.map(a => `${a.name} (${a.source}): ${a.description}`).join('; '),
340
+ remaining,
341
+ };
342
+ }
@@ -0,0 +1 @@
1
+ export * from '../runtimes/herdr/herdr.ts';