pi-agent-swarm 0.4.0 → 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.
@@ -1,13 +1,14 @@
1
- import { randomBytes } from "node:crypto";
1
+ import { createHash, randomBytes } from "node:crypto";
2
2
  import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3
3
  import { dirname, join, resolve, sep } from "node:path";
4
+ import type { WorkerRole } from "./profiles.js";
4
5
 
5
6
  export const WORKER_RECYCLING_DIRECTORY = join(".pi", "agent-swarm");
6
7
  export const DEFAULT_MAX_CONTEXT_PERCENT = 50;
7
8
  export const DEFAULT_MAX_REPLACEMENTS = 3;
8
9
  export const MAX_REPLACEMENTS = 10;
9
10
 
10
- const SAFE_LINEAGE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
11
+ export const SAFE_LINEAGE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
11
12
  const TASK_PROFILES = new Set(["short", "long", "auto"]);
12
13
  const LINEAGE_STATES = new Set([
13
14
  "working",
@@ -18,7 +19,7 @@ const LINEAGE_STATES = new Set([
18
19
  "completed",
19
20
  "failed",
20
21
  ]);
21
- const SECRET_PATTERNS = [
22
+ export const SECRET_PATTERNS = [
22
23
  /piagentswarm:v1:/iu,
23
24
  /PI_SWARM_INVITE/iu,
24
25
  /PI_SWARM_KICKOFF_CAPABILITY/iu,
@@ -63,6 +64,9 @@ export interface WorkerLaunchSpecification {
63
64
  color?: string;
64
65
  model?: string;
65
66
  allowRequests: boolean;
67
+ role?: WorkerRole;
68
+ profile?: string;
69
+ readableDirs?: string[];
66
70
  }
67
71
 
68
72
  export interface WorkerContextMetric {
@@ -72,6 +76,30 @@ export interface WorkerContextMetric {
72
76
  updatedAt: string;
73
77
  }
74
78
 
79
+ export interface HandoffEvidenceRef {
80
+ type: "file" | "artifact" | "log" | "diff" | "command";
81
+ ref: string;
82
+ /** Optional `sha256:<hex>` integrity digest verified against the file on disk. */
83
+ hash?: string;
84
+ }
85
+
86
+ /**
87
+ * S3 machine-verifiable handoff header (optional; missing header falls back cleanly to
88
+ * the legacy 10-section Markdown validation).
89
+ * Minimal required fields (`task_id`, `status`, `nextAction`, `evidence`) prevent models
90
+ * from fabricating filler content.
91
+ */
92
+ export interface StructuredHandoffHeader {
93
+ task_id: string;
94
+ status: "working" | "completed" | "blocked" | "handoff";
95
+ nextAction: string;
96
+ evidence: HandoffEvidenceRef[];
97
+ generation?: number;
98
+ facts?: Record<string, unknown>;
99
+ uncertainties?: string[];
100
+ requested_next_action?: string;
101
+ }
102
+
75
103
  export interface WorkerHandoffContent {
76
104
  originalObjective: string;
77
105
  currentState: string;
@@ -83,8 +111,31 @@ export interface WorkerHandoffContent {
83
111
  blocker: string;
84
112
  nextAction: string;
85
113
  artifacts: string[];
114
+ /** Optional S3 structured header embedded ahead of the 10-section Markdown body. */
115
+ structuredHeader?: StructuredHandoffHeader;
86
116
  }
87
117
 
118
+ const HANDOFF_HEADER_OPEN = "<!-- pi-swarm-handoff-header:v1\n";
119
+ const HANDOFF_HEADER_CLOSE = "\n-->";
120
+ const SHA256_PREFIX = "sha256:";
121
+ const VALID_EVIDENCE_TYPES = new Set(["file", "artifact", "log", "diff", "command"]);
122
+ const VALID_HEADER_STATUSES = new Set(["working", "completed", "blocked", "handoff"]);
123
+
124
+ const HANDOFF_SECTIONS = [
125
+ ["Original objective and constraints", "originalObjective"],
126
+ ["Current state", "currentState"],
127
+ ["Completed work", "completedWork"],
128
+ ["Remaining work", "remainingWork"],
129
+ ["Modified files and Git state", "modifiedFiles"],
130
+ ["Verification performed and its results", "verification"],
131
+ ["Key decisions and their rationale", "decisions"],
132
+ ["Current problem or blocker", "blocker"],
133
+ ["Exact next action", "nextAction"],
134
+ ["Required project files and artifact paths", "artifacts"],
135
+ ] as const satisfies readonly (readonly [string, keyof WorkerHandoffContent])[];
136
+
137
+ export const HANDOFF_SECTION_TITLES: readonly string[] = HANDOFF_SECTIONS.map(([title]) => title);
138
+
88
139
  export type WorkerLineage = {
89
140
  schemaVersion: 1;
90
141
  lineageId: string;
@@ -170,6 +221,17 @@ export function workerLineagePaths(projectRoot: string, lineageId: string, gener
170
221
  };
171
222
  }
172
223
 
224
+ /** Whether a recorded handoff path belongs to the lineage's current generation document. */
225
+ export function isCurrentGenerationHandoffPath(
226
+ projectRoot: string,
227
+ lineageId: string,
228
+ generation: number,
229
+ handoffPath: string | undefined,
230
+ ): boolean {
231
+ if (!handoffPath) return false;
232
+ return resolve(handoffPath) === workerLineagePaths(projectRoot, lineageId, generation).handoffPath;
233
+ }
234
+
173
235
  export async function verifyWorkerHandoffReadable(projectRoot: string, launch: ContextRecyclingLaunch): Promise<void> {
174
236
  if (launch.generation === 1) return;
175
237
  const expected = workerLineagePaths(projectRoot, launch.lineageId, launch.generation - 1).handoffPath;
@@ -177,21 +239,120 @@ export async function verifyWorkerHandoffReadable(projectRoot: string, launch: C
177
239
  throw new Error("Pi Agent Swarm successor handoff path does not match its predecessor generation");
178
240
  }
179
241
  const markdown = await readFile(expected, "utf8");
180
- const requiredSections = [
181
- "Original objective and constraints",
182
- "Current state",
183
- "Completed work",
184
- "Remaining work",
185
- "Modified files and Git state",
186
- "Verification performed and its results",
187
- "Key decisions and their rationale",
188
- "Current problem or blocker",
189
- "Exact next action",
190
- "Required project files and artifact paths",
191
- ];
192
- if (requiredSections.some((section) => !markdown.includes(`## ${section}`))) {
242
+ if (!hasRequiredHandoffSections(markdown)) {
193
243
  throw new Error("Pi Agent Swarm successor handoff is incomplete");
194
244
  }
245
+ const header = parseStructuredHandoffHeader(markdown);
246
+ if (header) {
247
+ await verifyHandoffEvidence(projectRoot, header.evidence);
248
+ }
249
+ }
250
+
251
+ export async function computeFileSha256(filePath: string): Promise<string> {
252
+ const buf = await readFile(filePath);
253
+ return `${SHA256_PREFIX}${createHash("sha256").update(buf).digest("hex")}`;
254
+ }
255
+
256
+ export function validateStructuredHandoffHeader(raw: unknown): StructuredHandoffHeader {
257
+ const obj = record(raw, "handoff structured header");
258
+ if (typeof obj.task_id !== "string" || obj.task_id.trim().length === 0) {
259
+ throw new Error("Pi Agent Swarm handoff header requires a non-empty task_id");
260
+ }
261
+ if (typeof obj.status !== "string" || !VALID_HEADER_STATUSES.has(obj.status)) {
262
+ throw new Error(`Pi Agent Swarm handoff header status is invalid: "${String(obj.status)}"`);
263
+ }
264
+ if (typeof obj.nextAction !== "string" || obj.nextAction.trim().length === 0) {
265
+ throw new Error("Pi Agent Swarm handoff header requires a non-empty nextAction");
266
+ }
267
+ if (!Array.isArray(obj.evidence)) {
268
+ throw new Error("Pi Agent Swarm handoff header evidence must be an array");
269
+ }
270
+ const evidence: HandoffEvidenceRef[] = obj.evidence.map((entry) => {
271
+ const item = record(entry, "handoff evidence");
272
+ if (typeof item.type !== "string" || !VALID_EVIDENCE_TYPES.has(item.type)) {
273
+ throw new Error(`Pi Agent Swarm handoff evidence type is invalid: "${String(item.type)}"`);
274
+ }
275
+ if (typeof item.ref !== "string" || item.ref.trim().length === 0 || item.ref.includes("\0")) {
276
+ throw new Error("Pi Agent Swarm handoff evidence ref must be a non-empty string without NUL bytes");
277
+ }
278
+ if (item.hash !== undefined) {
279
+ if (typeof item.hash !== "string" || !/^sha256:[a-f0-9]{64}$/iu.test(item.hash)) {
280
+ throw new Error(`Pi Agent Swarm handoff evidence hash is invalid: "${String(item.hash)}"`);
281
+ }
282
+ }
283
+ return {
284
+ type: item.type as HandoffEvidenceRef["type"],
285
+ ref: item.ref.trim(),
286
+ ...(typeof item.hash === "string" ? { hash: item.hash.toLowerCase() } : {}),
287
+ };
288
+ });
289
+ return {
290
+ task_id: obj.task_id.trim(),
291
+ status: obj.status as StructuredHandoffHeader["status"],
292
+ nextAction: obj.nextAction.trim(),
293
+ evidence,
294
+ ...(typeof obj.generation === "number" && Number.isInteger(obj.generation) && obj.generation >= 1
295
+ ? { generation: obj.generation }
296
+ : {}),
297
+ ...(obj.facts && typeof obj.facts === "object" && !Array.isArray(obj.facts)
298
+ ? { facts: obj.facts as Record<string, unknown> }
299
+ : {}),
300
+ ...(Array.isArray(obj.uncertainties) && obj.uncertainties.every((u) => typeof u === "string")
301
+ ? { uncertainties: obj.uncertainties as string[] }
302
+ : {}),
303
+ ...(typeof obj.requested_next_action === "string" ? { requested_next_action: obj.requested_next_action } : {}),
304
+ };
305
+ }
306
+
307
+ export function parseStructuredHandoffHeader(markdown: string): StructuredHandoffHeader | undefined {
308
+ if (!markdown.startsWith(HANDOFF_HEADER_OPEN)) return undefined;
309
+ const closeIdx = markdown.indexOf(HANDOFF_HEADER_CLOSE, HANDOFF_HEADER_OPEN.length);
310
+ if (closeIdx < 0) {
311
+ throw new Error("Pi Agent Swarm handoff structured header is malformed (missing closing marker)");
312
+ }
313
+ const rawJson = markdown.slice(HANDOFF_HEADER_OPEN.length, closeIdx).trim();
314
+ let parsed: unknown;
315
+ try {
316
+ parsed = JSON.parse(rawJson);
317
+ } catch (error) {
318
+ throw new Error(
319
+ `Pi Agent Swarm handoff structured header JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
320
+ );
321
+ }
322
+ return validateStructuredHandoffHeader(parsed);
323
+ }
324
+
325
+ export async function verifyHandoffEvidence(
326
+ projectRoot: string,
327
+ evidence: readonly HandoffEvidenceRef[],
328
+ extraAllowedDirs: readonly string[] = [],
329
+ ): Promise<void> {
330
+ const root = resolve(projectRoot);
331
+ const allowedRoots = [root, ...extraAllowedDirs.map((d) => resolve(d))];
332
+ for (const item of evidence) {
333
+ if (item.type === "command") continue;
334
+ const candidate = resolve(root, item.ref);
335
+ if (!allowedRoots.some((allowed) => isWithin(allowed, candidate))) {
336
+ throw new Error(`Pi Agent Swarm handoff evidence ref "${item.ref}" escapes allowed project roots`);
337
+ }
338
+ let info: Awaited<ReturnType<typeof stat>>;
339
+ try {
340
+ info = await stat(candidate);
341
+ } catch {
342
+ throw new Error(`Pi Agent Swarm handoff evidence ref does not exist on disk: "${item.ref}"`);
343
+ }
344
+ if (!info.isFile()) {
345
+ throw new Error(`Pi Agent Swarm handoff evidence ref is not a regular file: "${item.ref}"`);
346
+ }
347
+ if (item.hash) {
348
+ const actual = await computeFileSha256(candidate);
349
+ if (actual !== item.hash.toLowerCase()) {
350
+ throw new Error(
351
+ `Pi Agent Swarm handoff evidence hash mismatch for "${item.ref}": expected ${item.hash}, got ${actual}`,
352
+ );
353
+ }
354
+ }
355
+ }
195
356
  }
196
357
 
197
358
  export async function initializeWorkerLineage(options: {
@@ -210,7 +371,9 @@ export async function initializeWorkerLineage(options: {
210
371
  schemaVersion: 1,
211
372
  lineageId: options.launch.lineageId,
212
373
  projectRoot: resolve(options.projectRoot),
213
- leaderSessionId: options.leaderSessionId,
374
+ // A committed successor may have rebound this lineage already; reloads of the worker still
375
+ // carry the previous parent session id, so the on-disk leader always wins.
376
+ leaderSessionId: existing?.leaderSessionId ?? options.leaderSessionId,
214
377
  workerSessionId: options.workerSessionId,
215
378
  originalObjective: existing?.originalObjective ?? "",
216
379
  taskProfile: options.launch.policy.taskProfile,
@@ -270,7 +433,7 @@ export async function publishWorkerHandoff(options: {
270
433
  launch: WorkerLaunchSpecification;
271
434
  content: WorkerHandoffContent;
272
435
  nextAction: string;
273
- }): Promise<WorkerLineagePaths> {
436
+ }): Promise<{ handoffPath: string; leaderSessionId: string }> {
274
437
  return withLineageLock(options.projectRoot, options.lineageId, async () => {
275
438
  validateHandoff(options.content);
276
439
  const root = resolve(options.projectRoot);
@@ -279,6 +442,10 @@ export async function publishWorkerHandoff(options: {
279
442
  throw new Error("Pi Agent Swarm handoff artifact is outside the project root");
280
443
  }
281
444
  }
445
+ if (options.content.structuredHeader) {
446
+ const validHeader = validateStructuredHandoffHeader(options.content.structuredHeader);
447
+ await verifyHandoffEvidence(root, validHeader.evidence, options.launch.readableDirs ?? []);
448
+ }
282
449
  const paths = workerLineagePaths(options.projectRoot, options.lineageId, options.generation);
283
450
  const existing = await readWorkerLineageOptional(options.projectRoot, options.lineageId);
284
451
  if (
@@ -299,7 +466,9 @@ export async function publishWorkerHandoff(options: {
299
466
  schemaVersion: 1,
300
467
  lineageId: options.lineageId,
301
468
  projectRoot: root,
302
- leaderSessionId: options.leaderSessionId,
469
+ // The lineage file is the authority for the current leader: a concurrent rebind must win
470
+ // over the id this worker still holds in memory.
471
+ leaderSessionId: existing?.leaderSessionId ?? options.leaderSessionId,
303
472
  originalObjective: options.content.originalObjective,
304
473
  taskProfile: options.policy.taskProfile,
305
474
  policy: options.policy,
@@ -316,29 +485,38 @@ export async function publishWorkerHandoff(options: {
316
485
  options.lineageId,
317
486
  );
318
487
  await atomicJson(paths.lineagePath, lineage);
319
- return paths;
488
+ return { handoffPath: paths.handoffPath, leaderSessionId: lineage.leaderSessionId };
320
489
  });
321
490
  }
322
491
 
323
492
  export function renderWorkerHandoff(content: WorkerHandoffContent): string {
324
- validateHandoff(content);
325
- const sections: [string, string][] = [
326
- ["Original objective and constraints", content.originalObjective],
327
- ["Current state", content.currentState],
328
- ["Completed work", content.completedWork],
329
- ["Remaining work", content.remainingWork],
330
- ["Modified files and Git state", content.modifiedFiles],
331
- ["Verification performed and its results", content.verification],
332
- ["Key decisions and their rationale", content.decisions],
333
- ["Current problem or blocker", content.blocker],
334
- ["Exact next action", content.nextAction],
335
- ["Required project files and artifact paths", content.artifacts.length > 0 ? content.artifacts.join("\n") : "None"],
336
- ];
337
- return `# Worker handoff\n\n${sections.map(([title, body]) => `## ${title}\n\n${body.trim() || "None"}`).join("\n\n")}\n`;
338
- }
339
-
340
- function validateHandoff(content: WorkerHandoffContent): void {
341
- const value = record(content, "worker handoff");
493
+ return renderHandoffDocument("Worker handoff", content, "worker");
494
+ }
495
+
496
+ /** Shared renderer keeps worker and leader handoff contracts byte-for-byte aligned apart from the title. */
497
+ export function renderHandoffDocument(
498
+ title: string,
499
+ content: WorkerHandoffContent,
500
+ owner: "worker" | "leader",
501
+ ): string {
502
+ validateHandoff(content, owner);
503
+ const headerBlock = content.structuredHeader
504
+ ? `${HANDOFF_HEADER_OPEN}${JSON.stringify(validateStructuredHandoffHeader(content.structuredHeader), null, 2)}${HANDOFF_HEADER_CLOSE}\n\n`
505
+ : "";
506
+ const sections = HANDOFF_SECTIONS.map(([section, key]) => {
507
+ const value = content[key];
508
+ const body = Array.isArray(value) ? value.join("\n") : value;
509
+ return `## ${section}\n\n${body.trim() || "None"}`;
510
+ });
511
+ return `${headerBlock}# ${title}\n\n${sections.join("\n\n")}\n`;
512
+ }
513
+
514
+ export function hasRequiredHandoffSections(markdown: string): boolean {
515
+ return HANDOFF_SECTION_TITLES.every((section) => markdown.includes(`## ${section}`));
516
+ }
517
+
518
+ export function validateHandoff(content: WorkerHandoffContent, owner: "worker" | "leader" = "worker"): void {
519
+ const value = record(content, `${owner} handoff`);
342
520
  for (const key of [
343
521
  "originalObjective",
344
522
  "currentState",
@@ -351,7 +529,7 @@ function validateHandoff(content: WorkerHandoffContent): void {
351
529
  "nextAction",
352
530
  ]) {
353
531
  if (typeof value[key] !== "string" || Buffer.byteLength(value[key], "utf8") > 8192) {
354
- throw new Error(`Pi Agent Swarm worker handoff ${key} is invalid`);
532
+ throw new Error(`Pi Agent Swarm ${owner} handoff ${key} is invalid`);
355
533
  }
356
534
  }
357
535
  if (
@@ -359,12 +537,13 @@ function validateHandoff(content: WorkerHandoffContent): void {
359
537
  value.artifacts.length > 32 ||
360
538
  value.artifacts.some((item) => typeof item !== "string")
361
539
  ) {
362
- throw new Error("Pi Agent Swarm worker handoff artifacts are invalid");
540
+ throw new Error(`Pi Agent Swarm ${owner} handoff artifacts are invalid`);
363
541
  }
364
542
  const serialized = JSON.stringify(value);
365
- if (Buffer.byteLength(serialized, "utf8") > 40 * 1024) throw new Error("Pi Agent Swarm worker handoff is too large");
543
+ if (Buffer.byteLength(serialized, "utf8") > 40 * 1024)
544
+ throw new Error(`Pi Agent Swarm ${owner} handoff is too large`);
366
545
  if (SECRET_PATTERNS.some((pattern) => pattern.test(serialized))) {
367
- throw new Error("Pi Agent Swarm worker handoff must not contain secret material");
546
+ throw new Error(`Pi Agent Swarm ${owner} handoff must not contain secret material`);
368
547
  }
369
548
  }
370
549
 
@@ -377,11 +556,11 @@ async function readWorkerLineageOptional(projectRoot: string, lineageId: string)
377
556
  }
378
557
  }
379
558
 
380
- function isWithin(root: string, candidate: string): boolean {
559
+ export function isWithin(root: string, candidate: string): boolean {
381
560
  return candidate === root || candidate.startsWith(`${root}${sep}`);
382
561
  }
383
562
 
384
- async function ensureStorageRoot(paths: WorkerLineagePaths): Promise<void> {
563
+ export async function ensureStorageRoot(paths: { root: string }): Promise<void> {
385
564
  await mkdir(paths.root, { recursive: true, mode: 0o700 });
386
565
  try {
387
566
  await writeFile(join(paths.root, ".gitignore"), "*\n", { encoding: "utf8", mode: 0o600, flag: "wx" });
@@ -390,8 +569,14 @@ async function ensureStorageRoot(paths: WorkerLineagePaths): Promise<void> {
390
569
  }
391
570
  }
392
571
 
393
- async function withLineageLock<T>(projectRoot: string, lineageId: string, callback: () => Promise<T>): Promise<T> {
394
- const lockPath = `${workerLineagePaths(projectRoot, lineageId, 1).lineagePath}.lock`;
572
+ export async function withLineageLock<T>(
573
+ projectRoot: string,
574
+ lineageId: string,
575
+ callback: () => Promise<T>,
576
+ paths: Pick<WorkerLineagePaths, "lineagePath"> = workerLineagePaths(projectRoot, lineageId, 1),
577
+ ): Promise<T> {
578
+ // The caller supplies leader paths explicitly; the worker default preserves the existing isolated lock location.
579
+ const lockPath = `${paths.lineagePath}.lock`;
395
580
  await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 });
396
581
  let handle: Awaited<ReturnType<typeof open>> | undefined;
397
582
  for (let attempt = 0; attempt < 200 && !handle; attempt += 1) {
@@ -404,7 +589,7 @@ async function withLineageLock<T>(projectRoot: string, lineageId: string, callba
404
589
  await new Promise((resolveDelay) => setTimeout(resolveDelay, 5));
405
590
  }
406
591
  }
407
- if (!handle) throw new Error("Pi Agent Swarm worker lineage is busy with another update");
592
+ if (!handle) throw new Error("Pi Agent Swarm lineage is busy with another update");
408
593
  try {
409
594
  return await callback();
410
595
  } finally {
@@ -438,7 +623,11 @@ function validateWorkerLineage(value: unknown, projectRoot: string, lineageId: s
438
623
  throw new Error("Pi Agent Swarm worker lineage replacement budget is invalid");
439
624
  }
440
625
  const launch = record(lineage.launch, "worker lineage launch");
441
- assertKeys(launch, ["cwd", "name", "color", "model", "allowRequests"], "worker lineage launch");
626
+ assertKeys(
627
+ launch,
628
+ ["cwd", "name", "color", "model", "allowRequests", "role", "profile", "readableDirs"],
629
+ "worker lineage launch",
630
+ );
442
631
  if (
443
632
  typeof launch.cwd !== "string" ||
444
633
  resolve(launch.cwd) !== resolve(projectRoot) ||
@@ -446,7 +635,7 @@ function validateWorkerLineage(value: unknown, projectRoot: string, lineageId: s
446
635
  ) {
447
636
  throw new Error("Pi Agent Swarm worker lineage launch is invalid");
448
637
  }
449
- for (const key of ["name", "color", "model"] as const) {
638
+ for (const key of ["name", "color", "model", "profile"] as const) {
450
639
  if (
451
640
  launch[key] !== undefined &&
452
641
  (typeof launch[key] !== "string" || Buffer.byteLength(launch[key], "utf8") > 4_096)
@@ -454,6 +643,22 @@ function validateWorkerLineage(value: unknown, projectRoot: string, lineageId: s
454
643
  throw new Error(`Pi Agent Swarm worker lineage launch ${key} is invalid`);
455
644
  }
456
645
  }
646
+ if (
647
+ launch.role !== undefined &&
648
+ launch.role !== "implementer" &&
649
+ launch.role !== "researcher" &&
650
+ launch.role !== "reviewer"
651
+ ) {
652
+ throw new Error("Pi Agent Swarm worker lineage launch role is invalid");
653
+ }
654
+ if (
655
+ launch.readableDirs !== undefined &&
656
+ (!Array.isArray(launch.readableDirs) ||
657
+ launch.readableDirs.length > 32 ||
658
+ launch.readableDirs.some((item) => typeof item !== "string" || item.length === 0 || item.includes("\0")))
659
+ ) {
660
+ throw new Error("Pi Agent Swarm worker lineage launch readableDirs is invalid");
661
+ }
457
662
  if (lineage.currentHandoffPath !== undefined) {
458
663
  const handoffPath = resolve(String(lineage.currentHandoffPath));
459
664
  const generations = join(workerLineagePaths(projectRoot, lineageId, 1).lineageDirectory, "generations");
@@ -474,15 +679,15 @@ function validateWorkerLineage(value: unknown, projectRoot: string, lineageId: s
474
679
  return { ...lineage, policy, launch } as unknown as WorkerLineage;
475
680
  }
476
681
 
477
- async function atomicJson(path: string, value: unknown): Promise<void> {
682
+ export async function atomicJson(path: string, value: unknown, label = "worker lineage"): Promise<void> {
478
683
  const serialized = JSON.stringify(value, null, 2);
479
684
  if (SECRET_PATTERNS.some((pattern) => pattern.test(serialized))) {
480
- throw new Error("Pi Agent Swarm worker lineage must not contain secret material");
685
+ throw new Error(`Pi Agent Swarm ${label} must not contain secret material`);
481
686
  }
482
687
  await atomicText(path, `${serialized}\n`);
483
688
  }
484
689
 
485
- async function atomicText(path: string, content: string): Promise<void> {
690
+ export async function atomicText(path: string, content: string): Promise<void> {
486
691
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
487
692
  const temporary = `${path}.tmp-${process.pid}-${randomBytes(8).toString("hex")}`;
488
693
  await writeFile(temporary, content, { encoding: "utf8", mode: 0o600, flag: "wx" });