@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,835 @@
1
+ /**
2
+ * Filesystem persistence for Shepherd fieldnotes sessions.
3
+ *
4
+ * This module deliberately has no pi/Herdr dependencies. All mutations use
5
+ * small exclusive lock files and same-directory rename operations so it is
6
+ * safe for separate Shepherd processes to update one session.
7
+ */
8
+ import * as fs from 'node:fs';
9
+ import * as path from 'node:path';
10
+ import * as crypto from 'node:crypto';
11
+
12
+ export type SessionMode = 'single' | 'parallel' | 'chain';
13
+ export type ArtifactStatus =
14
+ 'pending' | 'running' | 'completed' | 'failed' | 'timed-out' | 'cancelled';
15
+
16
+ export interface ParentPiSessionBinding {
17
+ /** Opaque identity supplied by the parent pi runtime. */
18
+ identity: string;
19
+ /** Canonical project root to which this parent is bound. */
20
+ projectRoot: string;
21
+ boundAt: string;
22
+ /** Optional diagnostic only; never used as the binding key. */
23
+ sessionFile?: string;
24
+ }
25
+
26
+ export interface ShepherdSession {
27
+ /** Versioned durable binding format. Legacy sessions omit this field. */
28
+ artifactSessionVersion?: 2;
29
+ /** Canonical parent binding. Legacy sessions omit this field. */
30
+ parentPiSession?: ParentPiSessionBinding;
31
+ /** Compatibility aliases retained for callers of the initial draft. */
32
+ parentPiSessionId?: string;
33
+ parentSessionFile?: string;
34
+ sessionName: string;
35
+ slug: string;
36
+ ordinal: number;
37
+ directoryName: string;
38
+ projectRoot: string;
39
+ sessionPath: string;
40
+ sessionRelativePath: string;
41
+ mocPath: string;
42
+ sessionMetadataPath: string;
43
+ resumed: boolean;
44
+ startedAt: string;
45
+ updatedAt: string;
46
+ status: string;
47
+ modes: SessionMode[];
48
+ }
49
+
50
+ export interface ArtifactReservation {
51
+ id: string;
52
+ agent: string;
53
+ agentSlug: string;
54
+ ordinal: number;
55
+ fileName: string;
56
+ filePath: string;
57
+ relativePath: string;
58
+ mode: SessionMode;
59
+ task?: string;
60
+ status: ArtifactStatus;
61
+ reservedAt: string;
62
+ startedAt?: string;
63
+ completedAt?: string;
64
+ }
65
+
66
+ export interface PlannedArtifact {
67
+ agent: string;
68
+ mode: SessionMode;
69
+ task?: string;
70
+ }
71
+
72
+ interface SessionRecord extends ShepherdSession {
73
+ artifacts: ArtifactReservation[];
74
+ }
75
+
76
+ /** A validated, parent-bound persistent fieldnotes session. */
77
+ export type ArtifactSession = ShepherdSession & {
78
+ artifactSessionVersion: 2;
79
+ parentPiSession: ParentPiSessionBinding;
80
+ };
81
+
82
+ const MAX_SLUG_LENGTH = 64;
83
+ const MAX_AGENT_SLUG_LENGTH = 48;
84
+ const ROOT_DIR = '.shepherd';
85
+ const SESSIONS_DIR = 'sessions';
86
+ const LOCK_RETRY_MS = 10;
87
+ const LOCK_TIMEOUT_MS = 30_000;
88
+
89
+ function now(): string {
90
+ return new Date().toISOString();
91
+ }
92
+ function sleep(ms: number): void {
93
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
94
+ }
95
+
96
+ function lock(lockPath: string): () => void {
97
+ const started = Date.now();
98
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
99
+ while (true) {
100
+ try {
101
+ const fd = fs.openSync(lockPath, 'wx');
102
+ fs.writeSync(fd, `${process.pid}\n`);
103
+ fs.closeSync(fd);
104
+ return () => {
105
+ try {
106
+ fs.unlinkSync(lockPath);
107
+ } catch (error) {
108
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
109
+ }
110
+ };
111
+ } catch (error) {
112
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
113
+ if (Date.now() - started > LOCK_TIMEOUT_MS)
114
+ throw new Error(`Timed out acquiring filesystem lock: ${lockPath}`);
115
+ sleep(LOCK_RETRY_MS);
116
+ }
117
+ }
118
+ }
119
+
120
+ function atomicWrite(filePath: string, content: string): void {
121
+ const temporary = `${filePath}.tmp-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
122
+ const fd = fs.openSync(temporary, 'wx', 0o644);
123
+ try {
124
+ fs.writeFileSync(fd, content, 'utf8');
125
+ fs.fsyncSync(fd);
126
+ fs.closeSync(fd);
127
+ fs.renameSync(temporary, filePath);
128
+ } catch (error) {
129
+ try {
130
+ fs.closeSync(fd);
131
+ } catch {
132
+ /* already closed */
133
+ }
134
+ try {
135
+ fs.unlinkSync(temporary);
136
+ } catch {
137
+ /* best effort */
138
+ }
139
+ throw error;
140
+ }
141
+ }
142
+
143
+ function ensureDescendant(root: string, candidate: string): void {
144
+ const relative = path.relative(root, candidate);
145
+ if (relative === '' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
146
+ throw new Error(`Path escapes session root: ${candidate}`);
147
+ }
148
+ }
149
+
150
+ function validateParentIdentity(identity: unknown): string {
151
+ if (typeof identity !== 'string' || !identity)
152
+ throw new TypeError('A stable parent pi session identity is required');
153
+ if (/[\u0000-\u001f\u007f]/.test(identity))
154
+ throw new Error('Parent pi session identity contains control characters');
155
+ return identity;
156
+ }
157
+
158
+ /** Validate and normalize a human-facing session name into a safe slug. */
159
+ export function slugifySessionName(name: string): string {
160
+ if (typeof name !== 'string') throw new TypeError('Session name must be a string');
161
+ if (
162
+ name.includes('\0') ||
163
+ /[\u0001-\u001f\u007f]/.test(name) ||
164
+ name.includes('/') ||
165
+ name.includes('\\') ||
166
+ path.isAbsolute(name)
167
+ ) {
168
+ throw new Error(
169
+ 'Session name must not contain control characters, path separators, or be an absolute path'
170
+ );
171
+ }
172
+ const trimmed = name.trim();
173
+ if (trimmed === '.' || trimmed === '..' || trimmed.split(/[\\/]/).some(part => part === '..')) {
174
+ throw new Error('Session name must not contain traversal components');
175
+ }
176
+ const slug = trimmed
177
+ .toLocaleLowerCase()
178
+ .normalize('NFKD')
179
+ .replace(/[\u0300-\u036f]/g, '')
180
+ .replace(/[^a-z0-9]+/g, '-')
181
+ .replace(/^-+|-+$/g, '')
182
+ .slice(0, MAX_SLUG_LENGTH)
183
+ .replace(/-+$/g, '');
184
+ if (!slug) throw new Error('Session name must contain at least one usable character');
185
+ return slug;
186
+ }
187
+
188
+ /** Convert an agent label to a filename component (agent labels are sanitized, not rejected). */
189
+ export function slugifyAgentName(agent: string): string {
190
+ const value = String(agent)
191
+ .normalize('NFKD')
192
+ .replace(/[\u0300-\u036f]/g, '')
193
+ .toLocaleLowerCase()
194
+ .replace(/[^a-z0-9]+/g, '-')
195
+ .replace(/^-+|-+$/g, '')
196
+ .slice(0, MAX_AGENT_SLUG_LENGTH)
197
+ .replace(/-+$/g, '');
198
+ return value || 'agent';
199
+ }
200
+
201
+ export function deriveSessionName(task?: string): string {
202
+ if (!task || !task.trim()) return 'delegation';
203
+ const words = task.trim().split(/\s+/).slice(0, 8).join('-');
204
+ try {
205
+ return slugifySessionName(words);
206
+ } catch {
207
+ return 'delegation';
208
+ }
209
+ }
210
+
211
+ function sessionRoot(projectRoot: string): string {
212
+ return path.resolve(projectRoot, ROOT_DIR, SESSIONS_DIR);
213
+ }
214
+ function isSessionDirectory(name: string): boolean {
215
+ return /^\d{4,}-.+/.test(name);
216
+ }
217
+ function readRecord(dir: string): SessionRecord | undefined {
218
+ try {
219
+ const value = JSON.parse(
220
+ fs.readFileSync(path.join(dir, 'session.json'), 'utf8')
221
+ ) as SessionRecord;
222
+ if (
223
+ !value ||
224
+ typeof value.sessionName !== 'string' ||
225
+ typeof value.projectRoot !== 'string' ||
226
+ !Number.isInteger(value.ordinal) ||
227
+ !Array.isArray(value.artifacts)
228
+ )
229
+ return undefined;
230
+ if (value.directoryName !== path.basename(dir)) return undefined;
231
+ const sessionPath = path.resolve(dir);
232
+ const projectRoot = path.resolve(value.projectRoot);
233
+ // The metadata may contain paths from another machine or an attacker. The
234
+ // directory being read must be the canonical sessions child of its recorded
235
+ // project; all other paths are derived below rather than trusted.
236
+ if (path.dirname(sessionPath) !== sessionRoot(projectRoot)) return undefined;
237
+ if (value.artifactSessionVersion === 2) {
238
+ const identity = value.parentPiSession?.identity ?? value.parentPiSessionId;
239
+ if (typeof identity !== 'string' || !identity || /[\u0000-\u001f\u007f]/.test(identity))
240
+ return undefined;
241
+ if (value.parentPiSession && path.resolve(value.parentPiSession.projectRoot) !== projectRoot)
242
+ return undefined;
243
+ }
244
+ const artifacts = value.artifacts.map(artifact => {
245
+ if (
246
+ !artifact ||
247
+ typeof artifact.agent !== 'string' ||
248
+ typeof artifact.fileName !== 'string' ||
249
+ !Number.isInteger(artifact.ordinal)
250
+ )
251
+ throw new Error('Invalid artifact metadata');
252
+ // Never trust paths read from session.json. They are derived from the
253
+ // session directory and the filename, then checked lexically below.
254
+ if (
255
+ artifact.fileName === 'shepherd.md' ||
256
+ path.basename(artifact.fileName) !== artifact.fileName ||
257
+ artifact.fileName.includes('\0')
258
+ )
259
+ throw new Error('Invalid artifact filename');
260
+ const filePath = path.join(sessionPath, artifact.fileName);
261
+ ensureDescendant(sessionPath, filePath);
262
+ return {
263
+ ...artifact,
264
+ filePath,
265
+ relativePath: path.relative(projectRoot, filePath),
266
+ };
267
+ });
268
+ return {
269
+ ...value,
270
+ projectRoot,
271
+ sessionPath,
272
+ sessionRelativePath: path.relative(projectRoot, sessionPath),
273
+ mocPath: path.join(sessionPath, 'shepherd.md'),
274
+ sessionMetadataPath: path.join(sessionPath, 'session.json'),
275
+ artifacts,
276
+ };
277
+ } catch {
278
+ return undefined;
279
+ }
280
+ }
281
+ function toSession(record: SessionRecord, resumed: boolean): ShepherdSession {
282
+ return { ...record, resumed };
283
+ }
284
+ function writeRecord(sessionPath: string, record: SessionRecord): void {
285
+ atomicWrite(path.join(sessionPath, 'session.json'), `${JSON.stringify(record, null, 2)}\n`);
286
+ }
287
+
288
+ function directorySlug(name: string): string | undefined {
289
+ const match = /^\d{4,}-(.+)$/.exec(name);
290
+ return match?.[1];
291
+ }
292
+ function collisionSlug(root: string, slug: string, sessionName: string): string {
293
+ const existingSlugs = new Set<string>();
294
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
295
+ if (!entry.isDirectory() || !isSessionDirectory(entry.name)) continue;
296
+ const existingSlug = directorySlug(entry.name);
297
+ if (existingSlug) existingSlugs.add(existingSlug);
298
+ const record = readRecord(path.join(root, entry.name));
299
+ if (record?.sessionName === sessionName) continue;
300
+ if (
301
+ record &&
302
+ (() => {
303
+ try {
304
+ return slugifySessionName(record.sessionName) === slug;
305
+ } catch {
306
+ return false;
307
+ }
308
+ })()
309
+ )
310
+ existingSlugs.add(slug);
311
+ }
312
+ if (!existingSlugs.has(slug)) return slug;
313
+ const suffix = hash(sessionName);
314
+ const baseLength = Math.max(1, MAX_SLUG_LENGTH - suffix.length - 1);
315
+ const base = slug.slice(0, baseLength).replace(/-+$/g, '') || 'session';
316
+ let candidate = `${base}-${suffix}`;
317
+ let serial = 2;
318
+ while (existingSlugs.has(candidate)) {
319
+ const serialSuffix = `-${serial++}`;
320
+ const length = Math.max(1, MAX_SLUG_LENGTH - serialSuffix.length);
321
+ candidate = `${candidate.slice(0, length).replace(/-+$/g, '')}${serialSuffix}`;
322
+ }
323
+ return candidate;
324
+ }
325
+ function displayName(name: string): string {
326
+ return name.replace(/[-_]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase());
327
+ }
328
+ function renderMoc(record: SessionRecord): string {
329
+ const modes = record.modes.length
330
+ ? record.modes.join(', ')
331
+ : record.artifacts
332
+ .map(a => a.mode)
333
+ .filter((m, i, all) => all.indexOf(m) === i)
334
+ .join(', ');
335
+ const binding =
336
+ record.artifactSessionVersion === 2 &&
337
+ (record.parentPiSession?.identity ?? record.parentPiSessionId)
338
+ ? `parent-bound (identity ${hash(record.parentPiSession?.identity ?? record.parentPiSessionId!)})`
339
+ : 'legacy/unbound';
340
+ const artifacts = record.artifacts.length
341
+ ? record.artifacts
342
+ .map(
343
+ (a, i) =>
344
+ `${i + 1}. [${displayName(a.agent)} ${String(a.ordinal).padStart(2, '0')}](./${a.fileName}) — ${a.status}`
345
+ )
346
+ .join('\n')
347
+ : '_No notes reserved yet._';
348
+ const flow = record.artifacts.length
349
+ ? record.artifacts.map(a => `[${a.fileName.replace(/\.md$/, '')}](./${a.fileName})`).join(' → ')
350
+ : '_No flow yet._';
351
+ return `# Session ${String(record.ordinal).padStart(4, '0')} — ${displayName(record.sessionName)}\n\n- **Status:** ${record.status}\n- **Session name:** \`${record.sessionName}\`\n- **Fieldnotes session version:** ${record.artifactSessionVersion ?? 'legacy'}\n- **Parent binding:** ${binding}\n- **Started:** ${record.startedAt}\n- **Updated:** ${record.updatedAt}\n- **Project:** .\n- **Mode(s):** ${modes || 'pending'}\n\n## Notes\n\n${artifacts}\n\n## Flow\n\n${flow}\n`;
352
+ }
353
+ function writeMoc(record: SessionRecord): void {
354
+ atomicWrite(path.join(record.sessionPath, 'shepherd.md'), renderMoc(record));
355
+ }
356
+ function updateRecordAndMoc(record: SessionRecord): void {
357
+ record.updatedAt = now();
358
+ writeRecord(record.sessionPath, record);
359
+ writeMoc(record);
360
+ }
361
+
362
+ function allocationOrdinal(root: string): number {
363
+ const alloc = path.join(root, '.alloc');
364
+ fs.mkdirSync(alloc, { recursive: true });
365
+ let candidate = 1;
366
+ try {
367
+ for (const name of fs.readdirSync(root)) {
368
+ const match = /^(\d{4,})-/.exec(name);
369
+ if (match) candidate = Math.max(candidate, Number(match[1]) + 1);
370
+ }
371
+ } catch {
372
+ /* root was created above */
373
+ }
374
+ while (true) {
375
+ const token = path.join(alloc, String(candidate).padStart(4, '0'));
376
+ try {
377
+ fs.mkdirSync(token);
378
+ return candidate;
379
+ } catch (error) {
380
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
381
+ candidate++;
382
+ }
383
+ }
384
+ }
385
+
386
+ export interface CreateSessionOptions {
387
+ projectRoot: string;
388
+ sessionName?: string;
389
+ fallbackTask?: string;
390
+ mode?: SessionMode;
391
+ /** Explicit names resume; generated fallback names create a fresh session by default. */
392
+ resumeExisting?: boolean;
393
+ }
394
+
395
+ /** Create a numbered session or resume one matched by exact session.json name. */
396
+ export function createOrResumeSession(options: CreateSessionOptions): ShepherdSession {
397
+ const projectRoot = path.resolve(options.projectRoot);
398
+ const root = sessionRoot(projectRoot);
399
+ fs.mkdirSync(root, { recursive: true });
400
+ const explicitName = Boolean(options.sessionName?.trim());
401
+ const requested = options.sessionName?.trim() || deriveSessionName(options.fallbackTask);
402
+ const resumeExisting = options.resumeExisting ?? explicitName;
403
+ // Explicit names are validated even if a malformed name could be normalized safely.
404
+ const slug = slugifySessionName(requested);
405
+ const release = lock(path.join(root, '.sessions.lock'));
406
+ try {
407
+ if (resumeExisting) {
408
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
409
+ if (!entry.isDirectory() || !isSessionDirectory(entry.name)) continue;
410
+ const record = readRecord(path.join(root, entry.name));
411
+ if (!record || record.projectRoot !== projectRoot || record.sessionName !== requested)
412
+ continue;
413
+ const sessionRelease = lock(path.join(path.join(root, entry.name), '.session.lock'));
414
+ try {
415
+ record.resumed = true;
416
+ if (options.mode && !record.modes.includes(options.mode)) record.modes.push(options.mode);
417
+ record.status = ['completed', 'failed', 'timed-out', 'cancelled'].includes(record.status)
418
+ ? 'running'
419
+ : record.status;
420
+ updateRecordAndMoc(record);
421
+ return toSession(record, true);
422
+ } finally {
423
+ sessionRelease();
424
+ }
425
+ }
426
+ }
427
+ const ordinal = allocationOrdinal(root);
428
+ const actualSlug = collisionSlug(root, slug, requested);
429
+ const directoryName = `${String(ordinal).padStart(4, '0')}-${actualSlug}`;
430
+ const sessionPath = path.join(root, directoryName);
431
+ ensureDescendant(root, sessionPath);
432
+ fs.mkdirSync(sessionPath); // ordinal reservation means this should be unique
433
+ const startedAt = now();
434
+ const record: SessionRecord = {
435
+ sessionName: requested,
436
+ slug: actualSlug,
437
+ ordinal,
438
+ directoryName,
439
+ projectRoot,
440
+ sessionPath,
441
+ sessionRelativePath: path.relative(projectRoot, sessionPath),
442
+ mocPath: path.join(sessionPath, 'shepherd.md'),
443
+ sessionMetadataPath: path.join(sessionPath, 'session.json'),
444
+ resumed: false,
445
+ startedAt,
446
+ updatedAt: startedAt,
447
+ status: 'running',
448
+ modes: options.mode ? [options.mode] : [],
449
+ artifacts: [],
450
+ };
451
+ writeRecord(sessionPath, record);
452
+ writeMoc(record);
453
+ return toSession(record, false);
454
+ } finally {
455
+ release();
456
+ }
457
+ }
458
+
459
+ function loadSession(session: ShepherdSession): SessionRecord {
460
+ const sessionPath = path.resolve(session.sessionPath);
461
+ const record = readRecord(sessionPath);
462
+ if (!record) throw new Error(`Invalid session metadata: ${session.sessionMetadataPath}`);
463
+ if (record.sessionPath !== sessionPath)
464
+ throw new Error('Session path does not match durable metadata');
465
+ if (record.artifactSessionVersion === 2 && !record.parentPiSession && !record.parentPiSessionId) {
466
+ throw new Error('Parent-bound session is missing its binding metadata');
467
+ }
468
+ return record;
469
+ }
470
+
471
+ /**
472
+ * Mirror the canonical on-disk record back into the held session object.
473
+ * Every mutator below re-parses session.json, so the artifacts array held by
474
+ * callers (payloads serialize from the object) holds a per-parse copy that is
475
+ * stale by the time the first mutation lands; merging the record back keeps
476
+ * the held session in sync with the durable state without swapping
477
+ * references (agent records keep their original object).
478
+ */
479
+ function syncHeldSession(session: ShepherdSession, record: SessionRecord): void {
480
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
481
+ for (const key of Object.keys(record) as Array<keyof SessionRecord>)
482
+ (session as any)[key] = (record as any)[key];
483
+ }
484
+ function hash(value: string): string {
485
+ return crypto.createHash('sha256').update(value).digest('hex').slice(0, 8);
486
+ }
487
+ function safeArtifactMetadata(metadata: Record<string, unknown>): Record<string, unknown> {
488
+ // Lifecycle metadata is useful provenance, but never allow it to replace the
489
+ // allocator-owned identity or filesystem fields loaded from session.json.
490
+ const forbidden = new Set([
491
+ 'id',
492
+ 'artifactSessionVersion',
493
+ 'session',
494
+ 'sessionName',
495
+ 'parentPiSession',
496
+ 'agent',
497
+ 'agentSlug',
498
+ 'ordinal',
499
+ 'fileName',
500
+ 'filePath',
501
+ 'relativePath',
502
+ 'mode',
503
+ 'status',
504
+ 'reservedAt',
505
+ 'startedAt',
506
+ 'completedAt',
507
+ ]);
508
+ return Object.fromEntries(Object.entries(metadata).filter(([key]) => !forbidden.has(key)));
509
+ }
510
+ function artifactBase(agent: string, existing: ArtifactReservation[]): string {
511
+ // Reuse the established slug for repeated invocations of the same agent;
512
+ // ordinals, rather than slugs, distinguish those artifacts.
513
+ const prior = existing.find(item => item.agent === agent);
514
+ if (prior) return prior.agentSlug;
515
+ const base = slugifyAgentName(agent);
516
+ // Different labels may normalize to the same filename component. Keep the
517
+ // original label in the metadata, and disambiguate the filename safely.
518
+ if (!existing.some(item => item.agentSlug === base)) return base;
519
+ return `${base}-${hash(agent)}`;
520
+ }
521
+ function artifactFrontmatter(
522
+ a: ArtifactReservation,
523
+ session: SessionRecord,
524
+ extra: Record<string, unknown> = {}
525
+ ): string {
526
+ const parentIdentity = session.parentPiSession?.identity ?? session.parentPiSessionId;
527
+ const fields: Record<string, unknown> = {
528
+ ...extra,
529
+ artifactSessionVersion: session.artifactSessionVersion ?? 1,
530
+ session: session.directoryName,
531
+ sessionName: session.sessionName,
532
+ ...(parentIdentity ? { parentPiSession: hash(parentIdentity) } : {}),
533
+ agent: a.agent,
534
+ ordinal: a.ordinal,
535
+ mode: a.mode,
536
+ status: a.status,
537
+ reservedAt: a.reservedAt,
538
+ ...(a.startedAt ? { started: a.startedAt } : {}),
539
+ ...(a.completedAt ? { completed: a.completedAt } : {}),
540
+ };
541
+ const lines = Object.entries(fields).map(([key, value]) => {
542
+ if (typeof value !== 'string') return `${key}: ${JSON.stringify(value)}`;
543
+ const safe = /^[A-Za-z0-9._-]+$/.test(value) ? value : JSON.stringify(value);
544
+ return `${key}: ${safe}`;
545
+ });
546
+ return `---\n${lines.join('\n')}\n---\n\n# ${displayName(a.agent)} ${String(a.ordinal).padStart(2, '0')}\n\n<!-- Agent's note or agent-maintained report follows. -->\n`;
547
+ }
548
+ function initializeArtifact(a: ArtifactReservation, session: SessionRecord): void {
549
+ atomicWrite(a.filePath, artifactFrontmatter(a, session) + '\n');
550
+ }
551
+
552
+ /** Reserve all artifacts in input order, before any corresponding child starts. */
553
+ export function reserveArtifacts(
554
+ session: ShepherdSession,
555
+ planned: PlannedArtifact[]
556
+ ): ArtifactReservation[] {
557
+ if (!Array.isArray(planned)) throw new TypeError('planned artifacts must be an array');
558
+ const release = lock(path.join(session.sessionPath, '.session.lock'));
559
+ try {
560
+ const record = loadSession(session);
561
+ const result: ArtifactReservation[] = [];
562
+ for (const item of planned) {
563
+ if (!item || typeof item.agent !== 'string' || !item.agent.trim())
564
+ throw new Error('Artifact agent name is required');
565
+ const ordinal = record.artifacts.filter(a => a.agent === item.agent).length + 1;
566
+ let base = artifactBase(item.agent, record.artifacts);
567
+ let fileName = `${base}-${String(ordinal).padStart(2, '0')}.md`;
568
+ let suffix = 2;
569
+ while (
570
+ record.artifacts.some(a => a.fileName === fileName) ||
571
+ fs.existsSync(path.join(record.sessionPath, fileName))
572
+ )
573
+ fileName = `${base}-${suffix++}-${String(ordinal).padStart(2, '0')}.md`;
574
+ const reservedAt = now();
575
+ const artifact: ArtifactReservation = {
576
+ id: `${record.directoryName}/${fileName}`,
577
+ agent: item.agent,
578
+ agentSlug: base,
579
+ ordinal,
580
+ fileName,
581
+ filePath: path.join(record.sessionPath, fileName),
582
+ relativePath: path.relative(record.projectRoot, path.join(record.sessionPath, fileName)),
583
+ mode: item.mode,
584
+ task: item.task,
585
+ status: 'pending',
586
+ reservedAt,
587
+ };
588
+ ensureDescendant(record.sessionPath, artifact.filePath);
589
+ initializeArtifact(artifact, record);
590
+ record.artifacts.push(artifact);
591
+ result.push(artifact);
592
+ }
593
+ if (planned.some(p => p.mode && !record.modes.includes(p.mode)))
594
+ record.modes = [
595
+ ...record.modes,
596
+ ...planned
597
+ .map(p => p.mode)
598
+ .filter((m, i, all) => !record.modes.includes(m) && all.indexOf(m) === i),
599
+ ];
600
+ updateRecordAndMoc(record);
601
+ return result;
602
+ } finally {
603
+ release();
604
+ }
605
+ }
606
+
607
+ export function markArtifactStarted(
608
+ session: ShepherdSession,
609
+ artifact: ArtifactReservation,
610
+ metadata: Record<string, unknown> = {}
611
+ ): void {
612
+ updateArtifact(session, artifact, 'running', metadata);
613
+ }
614
+
615
+ export function markArtifactStatus(
616
+ session: ShepherdSession,
617
+ artifact: ArtifactReservation,
618
+ status: ArtifactStatus,
619
+ metadata: Record<string, unknown> = {}
620
+ ): void {
621
+ updateArtifact(session, artifact, status, metadata);
622
+ }
623
+
624
+ function updateArtifact(
625
+ session: ShepherdSession,
626
+ artifact: ArtifactReservation,
627
+ status: ArtifactStatus,
628
+ metadata: Record<string, unknown>
629
+ ): void {
630
+ const release = lock(path.join(session.sessionPath, '.session.lock'));
631
+ try {
632
+ const record = loadSession(session);
633
+ const stored = record.artifacts.find(
634
+ a => a.id === artifact.id || a.filePath === artifact.filePath
635
+ );
636
+ if (!stored) throw new Error(`Artifact is not part of session: ${artifact.filePath}`);
637
+ stored.status = status;
638
+ if (status === 'running' && !stored.startedAt) stored.startedAt = now();
639
+ if (['completed', 'failed', 'timed-out', 'cancelled'].includes(status))
640
+ stored.completedAt = now();
641
+ Object.assign(stored, safeArtifactMetadata(metadata));
642
+ // Mirror the canonical on-disk state back into the in-memory reservation
643
+ // so callers that hold the handle (e.g. shepherd_wait payloads) report
644
+ // the current status instead of the stale value from reservation time.
645
+ Object.assign(artifact, stored);
646
+ const existing = fs.existsSync(stored.filePath) ? fs.readFileSync(stored.filePath, 'utf8') : '';
647
+ const body = existing
648
+ .replace(/^---[\s\S]*?---\s*/, '')
649
+ .replace(/\n<!-- Shepherd orchestration -->[\s\S]*$/, '');
650
+ atomicWrite(
651
+ stored.filePath,
652
+ artifactFrontmatter(stored, record, metadata) + body.trimStart() + '\n'
653
+ );
654
+ updateRecordAndMoc(record);
655
+ syncHeldSession(session, record);
656
+ } finally {
657
+ release();
658
+ }
659
+ }
660
+
661
+ /** Finalize an artifact without discarding content an agent may have written. */
662
+ export function finalizeArtifact(
663
+ session: ShepherdSession,
664
+ artifact: ArtifactReservation,
665
+ result: {
666
+ status: ArtifactStatus;
667
+ output?: string;
668
+ error?: string;
669
+ metadata?: Record<string, unknown>;
670
+ }
671
+ ): void {
672
+ if (!['completed', 'failed', 'timed-out', 'cancelled'].includes(result.status))
673
+ throw new Error('Final artifact status must be terminal');
674
+ const release = lock(path.join(session.sessionPath, '.session.lock'));
675
+ try {
676
+ const record = loadSession(session);
677
+ const stored = record.artifacts.find(
678
+ a => a.id === artifact.id || a.filePath === artifact.filePath
679
+ );
680
+ if (!stored) throw new Error(`Artifact is not part of session: ${artifact.filePath}`);
681
+ stored.status = result.status;
682
+ stored.completedAt = now();
683
+ if (result.metadata) Object.assign(stored, safeArtifactMetadata(result.metadata));
684
+ // Same mirror invariant as updateArtifact: the handle serialized into
685
+ // wait payloads must agree with session.json.
686
+ Object.assign(artifact, stored);
687
+ const existing = fs.existsSync(stored.filePath)
688
+ ? fs.readFileSync(stored.filePath, 'utf8')
689
+ : artifactFrontmatter(stored, record);
690
+ const body = existing
691
+ .replace(/^---[\s\S]*?---\s*/, '')
692
+ .replace(/\n<!-- Shepherd orchestration -->[\s\S]*$/, '')
693
+ .trimEnd();
694
+ const output = result.output ? `\n\n### Final output\n\n${result.output}` : '';
695
+ const error = result.error ? `\n\n### Error\n\n${result.error}` : '';
696
+ const section = `\n\n<!-- Shepherd orchestration -->\n## Shepherd orchestration\n\n- **Final status:** ${result.status}\n- **Completed:** ${stored.completedAt}\n${result.metadata && Object.keys(result.metadata).length ? `- **Metadata:** \`${JSON.stringify(result.metadata)}\`\n` : ''}${output}${error}\n`;
697
+ atomicWrite(
698
+ stored.filePath,
699
+ artifactFrontmatter(stored, record, result.metadata ?? {}) + body + section
700
+ );
701
+ updateRecordAndMoc(record);
702
+ syncHeldSession(session, record);
703
+ } finally {
704
+ release();
705
+ }
706
+ }
707
+
708
+ /** Update session status/modes and atomically regenerate its fieldnotes index. */
709
+ export function updateSessionMoc(
710
+ session: ShepherdSession,
711
+ update: { mode?: SessionMode; status?: string } = {}
712
+ ): ShepherdSession {
713
+ const release = lock(path.join(session.sessionPath, '.session.lock'));
714
+ try {
715
+ // Start from fresh on-disk state (a concurrent process may have added
716
+ // artifacts) so this update does not clobber them.
717
+ const record = loadSession(session);
718
+ if (update.mode && !record.modes.includes(update.mode)) record.modes.push(update.mode);
719
+ if (update.status) record.status = update.status;
720
+ updateRecordAndMoc(record);
721
+ // Merge the durable record back into the held session instead of
722
+ // returning a fresh copy: callers keep their reference and payloads
723
+ // serialized from it reflect the on-disk state.
724
+ syncHeldSession(session, record);
725
+ return session;
726
+ } finally {
727
+ release();
728
+ }
729
+ }
730
+
731
+ export interface ParentArtifactSessionOptions {
732
+ /** Stable identity supplied by the parent pi SessionManager. */
733
+ parentPiSessionId?: string;
734
+ /** Preferred spelling for callers that expose the pi identity as identity. */
735
+ parentPiSessionIdentity?: string;
736
+ /** Optional human-readable label; it never participates in lookup. */
737
+ sessionName?: string;
738
+ /** Canonical project root for this parent binding. */
739
+ projectRoot: string;
740
+ /** Optional parent JSONL path, for provenance/debugging only. */
741
+ parentSessionFile?: string;
742
+ }
743
+
744
+ /**
745
+ * Resolve the one durable fieldnotes session owned by a parent pi session and
746
+ * project root. This deliberately does not use createOrResumeSession's
747
+ * human-facing name matching: legacy unbound sessions and sessions belonging
748
+ * to another parent are never silently claimed.
749
+ */
750
+ export function resolveOrCreateParentArtifactSession(
751
+ options: ParentArtifactSessionOptions
752
+ ): ArtifactSession {
753
+ const parentPiSessionId = validateParentIdentity(
754
+ options.parentPiSessionIdentity ?? options.parentPiSessionId
755
+ );
756
+ const projectRoot = path.resolve(options.projectRoot);
757
+ if (!projectRoot || projectRoot === path.parse(projectRoot).root) {
758
+ // The filesystem root is technically valid, but is almost certainly an
759
+ // accidental binding and would make project isolation hard to reason about.
760
+ // Keep the check explicit while allowing normal temporary/project roots.
761
+ if (!fs.existsSync(projectRoot)) throw new Error('Project root does not exist');
762
+ }
763
+ const root = sessionRoot(projectRoot);
764
+ fs.mkdirSync(root, { recursive: true });
765
+ const release = lock(path.join(root, '.sessions.lock'));
766
+ try {
767
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
768
+ if (!entry.isDirectory() || !isSessionDirectory(entry.name)) continue;
769
+ const record = readRecord(path.join(root, entry.name));
770
+ if (!record || record.artifactSessionVersion !== 2) continue;
771
+ const storedIdentity = record.parentPiSession?.identity ?? record.parentPiSessionId;
772
+ if (record.projectRoot !== projectRoot || storedIdentity !== parentPiSessionId) continue;
773
+ const sessionRelease = lock(path.join(record.sessionPath, '.session.lock'));
774
+ try {
775
+ record.parentSessionFile = options.parentSessionFile ?? record.parentSessionFile;
776
+ if (record.parentPiSession) record.parentPiSession.sessionFile = record.parentSessionFile;
777
+ record.resumed = true;
778
+ if (['completed', 'failed', 'timed-out', 'cancelled'].includes(record.status))
779
+ record.status = 'running';
780
+ updateRecordAndMoc(record);
781
+ return toSession(record, true) as ArtifactSession;
782
+ } finally {
783
+ sessionRelease();
784
+ }
785
+ }
786
+
787
+ const ordinal = allocationOrdinal(root);
788
+ const sessionName = options.sessionName?.trim() || `orchestrator-${hash(parentPiSessionId)}`;
789
+ const slug = collisionSlug(root, slugifySessionName(sessionName), sessionName);
790
+ const directoryName = `${String(ordinal).padStart(4, '0')}-${slug}`;
791
+ const sessionPath = path.join(root, directoryName);
792
+ ensureDescendant(root, sessionPath);
793
+ fs.mkdirSync(sessionPath);
794
+ const startedAt = now();
795
+ const boundAt = startedAt;
796
+ const parentPiSession: ParentPiSessionBinding = {
797
+ identity: parentPiSessionId,
798
+ projectRoot,
799
+ boundAt,
800
+ ...(options.parentSessionFile ? { sessionFile: options.parentSessionFile } : {}),
801
+ };
802
+ const record: SessionRecord = {
803
+ artifactSessionVersion: 2,
804
+ parentPiSession,
805
+ parentPiSessionId,
806
+ ...(options.parentSessionFile ? { parentSessionFile: options.parentSessionFile } : {}),
807
+ sessionName,
808
+ slug,
809
+ ordinal,
810
+ directoryName,
811
+ projectRoot,
812
+ sessionPath,
813
+ sessionRelativePath: path.relative(projectRoot, sessionPath),
814
+ mocPath: path.join(sessionPath, 'shepherd.md'),
815
+ sessionMetadataPath: path.join(sessionPath, 'session.json'),
816
+ resumed: false,
817
+ startedAt,
818
+ updatedAt: startedAt,
819
+ status: 'running',
820
+ modes: [],
821
+ artifacts: [],
822
+ };
823
+ writeRecord(sessionPath, record);
824
+ writeMoc(record);
825
+ return toSession(record, false) as ArtifactSession;
826
+ } finally {
827
+ release();
828
+ }
829
+ }
830
+
831
+ export function readSessionMetadata(sessionPath: string): ShepherdSession | undefined {
832
+ const resolved = path.resolve(sessionPath);
833
+ const record = readRecord(resolved);
834
+ return record ? toSession(record, true) : undefined;
835
+ }