pi-agent-swarm 0.3.0 → 0.5.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.
@@ -0,0 +1,752 @@
1
+ import type { Dirent } from "node:fs";
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import {
5
+ atomicJson,
6
+ atomicText,
7
+ ensureStorageRoot,
8
+ hasRequiredHandoffSections,
9
+ isWithin,
10
+ MAX_REPLACEMENTS,
11
+ renderHandoffDocument,
12
+ SAFE_LINEAGE_ID,
13
+ validateHandoff,
14
+ WORKER_RECYCLING_DIRECTORY,
15
+ type WorkerHandoffContent,
16
+ withLineageLock,
17
+ } from "./context-recycling.js";
18
+
19
+ export const LEADER_LINEAGES_DIRECTORY = join(WORKER_RECYCLING_DIRECTORY, "leader-lineages");
20
+ export const DEFAULT_LEADER_SOFT_CONTEXT_PERCENT = 50;
21
+ export const DEFAULT_LEADER_SOFT_CONTEXT_TOKENS = 100_000;
22
+ export const DEFAULT_LEADER_HIGH_WATER_PERCENT = 75;
23
+ export const LEADER_SOFT_TOKEN_WINDOW_CAP = 0.6;
24
+ export const LEADER_OLD_TOOL_OUTPUT_PERCENT = 50;
25
+ export const LEADER_OLD_TOOL_OUTPUT_TOKENS = 40_000;
26
+ export const LEADER_TURN_SIGNAL_COUNT = 25;
27
+ export const LEADER_TURN_SIGNAL_TOKENS = 35_000;
28
+ export const LEADER_COOLDOWN_TURNS = 5;
29
+ export const LEADER_COOLDOWN_TOKENS = 20_000;
30
+ export const LEADER_RECENT_TURNS_TO_EXCLUDE = 6;
31
+
32
+ export interface LeaderRecyclingPolicy {
33
+ softContextPercent: number;
34
+ softContextTokens: number;
35
+ highWaterPercent: number;
36
+ maxReplacements: number;
37
+ }
38
+
39
+ export type LeaderRecyclingPolicyInput = Partial<LeaderRecyclingPolicy>;
40
+
41
+ export const DEFAULT_LEADER_RECYCLING_POLICY: Readonly<LeaderRecyclingPolicy> = Object.freeze({
42
+ softContextPercent: DEFAULT_LEADER_SOFT_CONTEXT_PERCENT,
43
+ softContextTokens: DEFAULT_LEADER_SOFT_CONTEXT_TOKENS,
44
+ highWaterPercent: DEFAULT_LEADER_HIGH_WATER_PERCENT,
45
+ maxReplacements: 3,
46
+ });
47
+
48
+ export interface LeaderContextUsage {
49
+ tokens: number | null;
50
+ contextWindow: number;
51
+ percent: number | null;
52
+ }
53
+
54
+ export interface LeaderSessionAnalysis {
55
+ status: "known" | "unknown";
56
+ completedTurns: number;
57
+ contextTokens: number | null;
58
+ contextWindow: number | null;
59
+ percent: number | null;
60
+ oldToolOutputTokens: number;
61
+ toolResultCountOver2KB: number;
62
+ compactionCount: number;
63
+ }
64
+
65
+ export interface LeaderRecyclingSnapshot extends LeaderSessionAnalysis {
66
+ replacementCount: number;
67
+ }
68
+
69
+ export interface LeaderRecyclingCooldown {
70
+ turnsSinceReplacement: number;
71
+ tokensSinceReplacement: number | null;
72
+ }
73
+
74
+ export interface LeaderRecyclingGate {
75
+ armed: boolean;
76
+ reason: string[];
77
+ priority: "normal" | "high";
78
+ }
79
+
80
+ export type LeaderLineageState =
81
+ | "active"
82
+ | "handoff_pending"
83
+ | "handoff_ready"
84
+ | "replacing"
85
+ | "paused"
86
+ | "completed"
87
+ | "failed";
88
+
89
+ export type LeaderHandoffContent = WorkerHandoffContent;
90
+
91
+ export type LeaderLineage = {
92
+ schemaVersion: 1;
93
+ lineageId: string;
94
+ projectRoot: string;
95
+ leaderSessionId: string;
96
+ successorSessionId?: string;
97
+ originalObjective: string;
98
+ policy: LeaderRecyclingPolicy;
99
+ currentGeneration: number;
100
+ replacementCount: number;
101
+ state: LeaderLineageState;
102
+ currentHandoffPath?: string;
103
+ nextAction?: string;
104
+ contextUsage?: LeaderSessionAnalysis;
105
+ /** Consecutive automatic replacement failures survive successor session creation. */
106
+ autoFailures?: number;
107
+ /** Persisted circuit state; manual handoffs do not clear it. */
108
+ autoCircuitOpen?: boolean;
109
+ updatedAt: string;
110
+ } & Record<string, unknown>;
111
+
112
+ export interface LeaderLineagePaths {
113
+ root: string;
114
+ lineageDirectory: string;
115
+ lineagePath: string;
116
+ handoffPath: string;
117
+ }
118
+
119
+ const LEADER_LINEAGE_STATES = new Set<LeaderLineageState>([
120
+ "active",
121
+ "handoff_pending",
122
+ "handoff_ready",
123
+ "replacing",
124
+ "paused",
125
+ "completed",
126
+ "failed",
127
+ ]);
128
+
129
+ const LEADER_LINEAGE_TRANSITIONS: Record<LeaderLineageState, readonly LeaderLineageState[]> = {
130
+ active: ["handoff_pending", "paused", "completed", "failed"],
131
+ handoff_pending: ["active", "handoff_ready", "paused", "failed"],
132
+ handoff_ready: ["replacing", "paused", "failed"],
133
+ replacing: ["active", "failed"],
134
+ paused: ["active", "completed", "failed"],
135
+ completed: [],
136
+ failed: ["active"],
137
+ };
138
+
139
+ export function normalizeLeaderRecyclingPolicy(input: unknown = {}): LeaderRecyclingPolicy {
140
+ const value = record(input, "leader recycling policy");
141
+ const allowed = ["softContextPercent", "softContextTokens", "highWaterPercent", "maxReplacements"];
142
+ const unknown = Object.keys(value).find((key) => !allowed.includes(key));
143
+ if (unknown) throw new Error(`Pi Agent Swarm leader recycling policy has unknown field ${unknown}`);
144
+ const softContextPercent = value.softContextPercent ?? DEFAULT_LEADER_SOFT_CONTEXT_PERCENT;
145
+ const softContextTokens = value.softContextTokens ?? DEFAULT_LEADER_SOFT_CONTEXT_TOKENS;
146
+ const highWaterPercent = value.highWaterPercent ?? DEFAULT_LEADER_HIGH_WATER_PERCENT;
147
+ const maxReplacements = value.maxReplacements ?? DEFAULT_LEADER_RECYCLING_POLICY.maxReplacements;
148
+ for (const [key, percentage] of [
149
+ ["softContextPercent", softContextPercent],
150
+ ["highWaterPercent", highWaterPercent],
151
+ ] as const) {
152
+ if (typeof percentage !== "number" || !Number.isFinite(percentage) || percentage <= 0 || percentage > 100) {
153
+ throw new Error(`Pi Agent Swarm leader recycling ${key} must be greater than 0 and at most 100`);
154
+ }
155
+ }
156
+ if (typeof softContextTokens !== "number" || !Number.isFinite(softContextTokens) || softContextTokens <= 0) {
157
+ throw new Error("Pi Agent Swarm leader recycling softContextTokens must be greater than 0");
158
+ }
159
+ if (
160
+ !Number.isInteger(maxReplacements) ||
161
+ (maxReplacements as number) < 0 ||
162
+ (maxReplacements as number) > MAX_REPLACEMENTS
163
+ ) {
164
+ throw new Error(`Pi Agent Swarm leader recycling replacements must be an integer from 0 to ${MAX_REPLACEMENTS}`);
165
+ }
166
+ return {
167
+ softContextPercent: softContextPercent as number,
168
+ softContextTokens,
169
+ highWaterPercent: highWaterPercent as number,
170
+ maxReplacements: maxReplacements as number,
171
+ };
172
+ }
173
+
174
+ /** Inspect only entry metadata until context pressure can plausibly arm the leader gate. */
175
+ export function shouldAnalyzeLeaderBranch(
176
+ branch: readonly unknown[],
177
+ usage: LeaderContextUsage | undefined,
178
+ policyInput: LeaderRecyclingPolicyInput = {},
179
+ ): boolean {
180
+ if (!finiteNonNegative(usage?.tokens) || !finitePositive(usage?.contextWindow)) return false;
181
+ const tokens = usage.tokens;
182
+ const window = usage.contextWindow;
183
+ const policy = normalizeLeaderRecyclingPolicy(policyInput);
184
+ const percent = (tokens / window) * 100;
185
+ if (
186
+ percent >= policy.softContextPercent ||
187
+ percent >= policy.highWaterPercent ||
188
+ tokens >= Math.min(policy.softContextTokens, window * LEADER_SOFT_TOKEN_WINDOW_CAP)
189
+ ) {
190
+ return true;
191
+ }
192
+ let completedTurns = 0;
193
+ for (const entry of branch) {
194
+ const value = asRecord(entry);
195
+ if (!value) continue;
196
+ if (value.type === "compaction") return true;
197
+ if (value.type !== "message") continue;
198
+ const message = asRecord(value.message);
199
+ if (
200
+ message?.role === "assistant" &&
201
+ (message.stopReason === "stop" || message.stopReason === "length" || message.stopReason === "toolUse")
202
+ ) {
203
+ completedTurns += 1;
204
+ }
205
+ }
206
+ return (
207
+ (completedTurns >= LEADER_TURN_SIGNAL_COUNT && tokens >= LEADER_TURN_SIGNAL_TOKENS) ||
208
+ tokens >= LEADER_OLD_TOOL_OUTPUT_TOKENS
209
+ );
210
+ }
211
+
212
+ /**
213
+ * Analyze serializable session entries without importing Pi runtime objects.
214
+ * A completed turn is an assistant `stop`, `length`, or `toolUse` response; aborted responses do not add a turn.
215
+ * Old-output evidence starts after the latest compaction so summarized output is not counted as live context.
216
+ */
217
+ export function analyzeSessionBranch(
218
+ branch: readonly unknown[],
219
+ usage: LeaderContextUsage | undefined,
220
+ ): LeaderSessionAnalysis {
221
+ const completedResponseIndices: number[] = [];
222
+ let compactionCount = 0;
223
+ let lastCompactionIndex = -1;
224
+
225
+ for (const [index, entry] of branch.entries()) {
226
+ const value = asRecord(entry);
227
+ if (!value) continue;
228
+ if (value.type === "compaction") {
229
+ compactionCount += 1;
230
+ lastCompactionIndex = index;
231
+ }
232
+ if (value.type !== "message") continue;
233
+ const message = asRecord(value.message);
234
+ if (
235
+ message?.role === "assistant" &&
236
+ (message.stopReason === "stop" || message.stopReason === "length" || message.stopReason === "toolUse")
237
+ ) {
238
+ completedResponseIndices.push(index);
239
+ }
240
+ }
241
+
242
+ const completedTurns = completedResponseIndices.length;
243
+ const recentResponseIndices = completedResponseIndices.filter((index) => index > lastCompactionIndex);
244
+ const lastOldEntryIndex =
245
+ recentResponseIndices.length > LEADER_RECENT_TURNS_TO_EXCLUDE
246
+ ? recentResponseIndices[recentResponseIndices.length - LEADER_RECENT_TURNS_TO_EXCLUDE - 1]
247
+ : lastCompactionIndex;
248
+ let oldToolOutputTokens = 0;
249
+ let toolResultCountOver2KB = 0;
250
+ for (const [index, entry] of branch.entries()) {
251
+ if (index <= lastCompactionIndex) continue;
252
+ const message = asRecord(asRecord(entry)?.message);
253
+ if (message?.role !== "toolResult") continue;
254
+ // Measure payload bytes directly; JSON.stringify duplicated every large tool result.
255
+ const bytes = toolResultContentBytes(message.content);
256
+ if (bytes > 2_048) toolResultCountOver2KB += 1;
257
+ if (index <= lastOldEntryIndex) {
258
+ oldToolOutputTokens += Math.ceil(bytes / 4);
259
+ }
260
+ }
261
+
262
+ const contextTokens = finiteNonNegative(usage?.tokens) ? usage.tokens : null;
263
+ const contextWindow = finitePositive(usage?.contextWindow) ? usage.contextWindow : null;
264
+ const known = contextTokens !== null && contextWindow !== null;
265
+ return {
266
+ status: known ? "known" : "unknown",
267
+ completedTurns,
268
+ contextTokens,
269
+ contextWindow,
270
+ percent: known ? (contextTokens / contextWindow) * 100 : null,
271
+ oldToolOutputTokens,
272
+ toolResultCountOver2KB,
273
+ compactionCount,
274
+ };
275
+ }
276
+
277
+ function toolResultContentBytes(content: unknown): number {
278
+ if (typeof content === "string") return Buffer.byteLength(content, "utf8");
279
+ if (!Array.isArray(content)) return 0;
280
+ let bytes = 0;
281
+ for (const item of content) {
282
+ if (typeof item === "string") {
283
+ bytes += Buffer.byteLength(item, "utf8");
284
+ continue;
285
+ }
286
+ const value = asRecord(item);
287
+ if (typeof value?.text === "string") bytes += Buffer.byteLength(value.text, "utf8");
288
+ if (typeof value?.data === "string") bytes += Buffer.byteLength(value.data, "utf8");
289
+ }
290
+ return bytes;
291
+ }
292
+
293
+ export function evaluateLeaderRecyclingGate(
294
+ snapshot: LeaderRecyclingSnapshot,
295
+ policyInput: LeaderRecyclingPolicyInput = {},
296
+ cooldown: LeaderRecyclingCooldown = {
297
+ turnsSinceReplacement: Number.POSITIVE_INFINITY,
298
+ tokensSinceReplacement: Number.POSITIVE_INFINITY,
299
+ },
300
+ ): LeaderRecyclingGate {
301
+ const policy = normalizeLeaderRecyclingPolicy(policyInput);
302
+ const known =
303
+ snapshot.status === "known" &&
304
+ snapshot.contextTokens !== null &&
305
+ snapshot.contextWindow !== null &&
306
+ snapshot.percent !== null
307
+ ? {
308
+ tokens: snapshot.contextTokens,
309
+ window: snapshot.contextWindow,
310
+ percent: snapshot.percent,
311
+ }
312
+ : undefined;
313
+ const signals: string[] = [];
314
+ if (known) {
315
+ if (known.percent >= policy.softContextPercent) signals.push("soft_context_percent");
316
+ const softTokenThreshold = Math.min(policy.softContextTokens, known.window * LEADER_SOFT_TOKEN_WINDOW_CAP);
317
+ if (known.tokens >= softTokenThreshold) signals.push("soft_context_tokens");
318
+ if (
319
+ known.tokens > 0 &&
320
+ snapshot.oldToolOutputTokens >= LEADER_OLD_TOOL_OUTPUT_TOKENS &&
321
+ (snapshot.oldToolOutputTokens / known.tokens) * 100 > LEADER_OLD_TOOL_OUTPUT_PERCENT
322
+ ) {
323
+ signals.push("old_tool_output");
324
+ }
325
+ if (snapshot.completedTurns >= LEADER_TURN_SIGNAL_COUNT && known.tokens >= LEADER_TURN_SIGNAL_TOKENS) {
326
+ signals.push("long_running_session");
327
+ }
328
+ }
329
+ if (snapshot.compactionCount >= 1) signals.push("compaction_detected");
330
+
331
+ const highWater = known !== undefined && known.percent >= policy.highWaterPercent;
332
+ const reason = [...signals];
333
+ if (highWater) reason.push("high_water_context");
334
+ if (known === undefined) reason.push("context_tokens_unknown");
335
+ if (snapshot.replacementCount >= policy.maxReplacements) reason.push("replacement_budget_exhausted");
336
+ const bypassCooldown = highWater || snapshot.compactionCount >= 1;
337
+ if (!bypassCooldown && !(cooldown.turnsSinceReplacement >= LEADER_COOLDOWN_TURNS)) reason.push("cooldown_turns");
338
+ if (
339
+ !bypassCooldown &&
340
+ (cooldown.tokensSinceReplacement === null || !(cooldown.tokensSinceReplacement >= LEADER_COOLDOWN_TOKENS))
341
+ ) {
342
+ reason.push("cooldown_tokens");
343
+ }
344
+
345
+ const hardSilence = reason.some((item) =>
346
+ ["context_tokens_unknown", "replacement_budget_exhausted", "cooldown_turns", "cooldown_tokens"].includes(item),
347
+ );
348
+ if (reason.length === 0) reason.push("below_handoff_thresholds");
349
+ return {
350
+ armed: signals.length > 0 && !hardSilence,
351
+ reason,
352
+ priority: highWater ? "high" : "normal",
353
+ };
354
+ }
355
+
356
+ /** Build evidence-only guidance. Exact percentages are deliberately omitted to avoid anchoring the leader's decision. */
357
+ export function buildLeaderHandoffAdvisory(evidence: {
358
+ snapshot: LeaderRecyclingSnapshot;
359
+ gate: LeaderRecyclingGate;
360
+ inFlightWorkerCount: number;
361
+ maxReplacements: number;
362
+ }): string {
363
+ const { snapshot, gate } = evidence;
364
+ const remaining = Math.max(0, evidence.maxReplacements - snapshot.replacementCount);
365
+ return [
366
+ "[Pi Agent Swarm leader context handoff advisory]",
367
+ `priority=${gate.priority}`,
368
+ "This is decision evidence, not an instruction to replace the session.",
369
+ `- Current context token range: ${tokenRange(snapshot.contextTokens)}.`,
370
+ `- Old tool-output estimate: ${snapshot.oldToolOutputTokens.toLocaleString("en-US")} tokens.`,
371
+ `- Tool results larger than 2KB: ${snapshot.toolResultCountOver2KB}.`,
372
+ `- Completed turns: ${snapshot.completedTurns}; compactions: ${snapshot.compactionCount}.`,
373
+ `- Signals: ${gate.reason.join(", ")}.`,
374
+ `- In-flight workers: ${evidence.inFlightWorkerCount}.`,
375
+ `- Remaining leader handoff budget: ${remaining}.`,
376
+ "Handoff criteria: substantial work remains, the current session is at a stable boundary, and a concise handoff would preserve decisions and verification better than continuing to accumulate context.",
377
+ "Do not interrupt a healthy turn, repeat completed work, or hand off merely because one signal is present.",
378
+ "If no handoff is needed, answer normally and do not mention this advisory.",
379
+ ].join("\n");
380
+ }
381
+
382
+ export function leaderLineagePaths(projectRoot: string, lineageId: string, generation: number): LeaderLineagePaths {
383
+ if (!SAFE_LINEAGE_ID.test(lineageId)) throw new Error("Pi Agent Swarm leader lineage id is invalid");
384
+ if (!Number.isInteger(generation) || generation < 1) {
385
+ throw new Error("Pi Agent Swarm leader lineage generation is invalid");
386
+ }
387
+ const root = resolve(projectRoot);
388
+ const storageRoot = resolve(root, WORKER_RECYCLING_DIRECTORY);
389
+ if (!isWithin(root, storageRoot)) throw new Error("Pi Agent Swarm leader lineage storage escapes the project root");
390
+ const lineageDirectory = join(storageRoot, "leader-lineages", lineageId);
391
+ return {
392
+ root: storageRoot,
393
+ lineageDirectory,
394
+ lineagePath: join(lineageDirectory, "lineage.json"),
395
+ handoffPath: join(lineageDirectory, "generations", `${String(generation).padStart(4, "0")}-handoff.md`),
396
+ };
397
+ }
398
+
399
+ export function canTransitionLeaderLineageState(from: LeaderLineageState, to: LeaderLineageState): boolean {
400
+ return LEADER_LINEAGE_TRANSITIONS[from].includes(to);
401
+ }
402
+
403
+ export async function initializeLeaderLineage(options: {
404
+ projectRoot: string;
405
+ lineageId: string;
406
+ leaderSessionId: string;
407
+ originalObjective: string;
408
+ policy: LeaderRecyclingPolicyInput;
409
+ }): Promise<LeaderLineage> {
410
+ const paths = leaderLineagePaths(options.projectRoot, options.lineageId, 1);
411
+ return withLineageLock(
412
+ options.projectRoot,
413
+ options.lineageId,
414
+ async () => {
415
+ const existing = await readLeaderLineageOptional(options.projectRoot, options.lineageId);
416
+ if (existing) return existing;
417
+ const lineage = validateLeaderLineage(
418
+ {
419
+ schemaVersion: 1,
420
+ lineageId: options.lineageId,
421
+ projectRoot: resolve(options.projectRoot),
422
+ leaderSessionId: options.leaderSessionId,
423
+ originalObjective: options.originalObjective,
424
+ policy: normalizeLeaderRecyclingPolicy(options.policy),
425
+ currentGeneration: 1,
426
+ replacementCount: 0,
427
+ state: "active",
428
+ autoFailures: 0,
429
+ autoCircuitOpen: false,
430
+ updatedAt: new Date().toISOString(),
431
+ },
432
+ options.projectRoot,
433
+ options.lineageId,
434
+ );
435
+ await ensureStorageRoot(paths);
436
+ await atomicJson(paths.lineagePath, lineage, "leader lineage");
437
+ return lineage;
438
+ },
439
+ paths,
440
+ );
441
+ }
442
+
443
+ /** Find a reusable current leader lineage without scanning the worker lineages namespace. */
444
+ export async function findLeaderLineage(
445
+ projectRoot: string,
446
+ leaderSessionId: string,
447
+ onWarning?: (message: string) => void,
448
+ ): Promise<LeaderLineage | undefined> {
449
+ const directory = resolve(projectRoot, LEADER_LINEAGES_DIRECTORY);
450
+ let entries: Dirent[];
451
+ try {
452
+ entries = await readdir(directory, { withFileTypes: true });
453
+ } catch (error) {
454
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
455
+ throw error;
456
+ }
457
+ const matches: LeaderLineage[] = [];
458
+ for (const entry of entries) {
459
+ if (!entry.isDirectory() || !SAFE_LINEAGE_ID.test(entry.name)) continue;
460
+ let lineage: LeaderLineage | undefined;
461
+ try {
462
+ lineage = await readLeaderLineage(projectRoot, entry.name);
463
+ } catch (error) {
464
+ onWarning?.(
465
+ `Ignored damaged leader lineage ${entry.name}: ${error instanceof Error ? error.message : String(error)}`,
466
+ );
467
+ continue;
468
+ }
469
+ if (
470
+ lineage.leaderSessionId === leaderSessionId &&
471
+ (lineage.state === "active" ||
472
+ lineage.state === "handoff_pending" ||
473
+ lineage.state === "handoff_ready" ||
474
+ lineage.state === "replacing" ||
475
+ lineage.state === "failed")
476
+ ) {
477
+ matches.push(lineage);
478
+ }
479
+ }
480
+ matches.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
481
+ return matches[0];
482
+ }
483
+
484
+ export async function readLeaderLineage(projectRoot: string, lineageId: string): Promise<LeaderLineage> {
485
+ const paths = leaderLineagePaths(projectRoot, lineageId, 1);
486
+ const value = JSON.parse(await readFile(paths.lineagePath, "utf8")) as unknown;
487
+ return validateLeaderLineage(value, projectRoot, lineageId);
488
+ }
489
+
490
+ /** Update non-lifecycle metadata while retaining the state machine as the only lifecycle mutation path. */
491
+ export async function updateLeaderLineage(
492
+ projectRoot: string,
493
+ lineageId: string,
494
+ patch: Record<string, unknown>,
495
+ expected: { generation?: number; state?: LeaderLineageState } = {},
496
+ ): Promise<LeaderLineage> {
497
+ for (const key of ["state", "currentGeneration", "replacementCount"]) {
498
+ if (key in patch) throw new Error(`Pi Agent Swarm leader metadata update must not change ${key}`);
499
+ }
500
+ const paths = leaderLineagePaths(projectRoot, lineageId, 1);
501
+ return withLineageLock(
502
+ projectRoot,
503
+ lineageId,
504
+ async () => {
505
+ const existing = await readLeaderLineage(projectRoot, lineageId);
506
+ assertExpectedLeaderLineage(existing, expected);
507
+ const updated = validateLeaderLineage(
508
+ {
509
+ ...existing,
510
+ ...patch,
511
+ lineageId,
512
+ projectRoot: resolve(projectRoot),
513
+ state: existing.state,
514
+ currentGeneration: existing.currentGeneration,
515
+ replacementCount: existing.replacementCount,
516
+ updatedAt: new Date().toISOString(),
517
+ },
518
+ projectRoot,
519
+ lineageId,
520
+ );
521
+ await atomicJson(paths.lineagePath, updated, "leader lineage");
522
+ return updated;
523
+ },
524
+ paths,
525
+ );
526
+ }
527
+
528
+ export async function transitionLeaderLineage(
529
+ projectRoot: string,
530
+ lineageId: string,
531
+ nextState: LeaderLineageState,
532
+ options: {
533
+ expectedGeneration?: number;
534
+ patch?: Record<string, unknown>;
535
+ } = {},
536
+ ): Promise<LeaderLineage> {
537
+ const paths = leaderLineagePaths(projectRoot, lineageId, 1);
538
+ return withLineageLock(
539
+ projectRoot,
540
+ lineageId,
541
+ async () => {
542
+ const existing = await readLeaderLineage(projectRoot, lineageId);
543
+ assertExpectedLeaderLineage(existing, { generation: options.expectedGeneration });
544
+ if (!canTransitionLeaderLineageState(existing.state, nextState)) {
545
+ throw new Error(`Pi Agent Swarm leader lineage transition ${existing.state} -> ${nextState} is invalid`);
546
+ }
547
+ if (nextState === "handoff_ready") {
548
+ throw new Error("Pi Agent Swarm leader handoff_ready must be published with its handoff artifact");
549
+ }
550
+ if (nextState === "replacing" && existing.replacementCount >= existing.policy.maxReplacements) {
551
+ throw new Error("Pi Agent Swarm leader lineage replacement budget is exhausted");
552
+ }
553
+ const advances = existing.state === "replacing" && nextState === "active";
554
+ const currentGeneration = existing.currentGeneration + (advances ? 1 : 0);
555
+ const replacementCount = existing.replacementCount + (advances ? 1 : 0);
556
+ const updated = validateLeaderLineage(
557
+ {
558
+ ...existing,
559
+ ...(options.patch ?? {}),
560
+ lineageId,
561
+ projectRoot: resolve(projectRoot),
562
+ currentGeneration,
563
+ replacementCount,
564
+ state: nextState,
565
+ updatedAt: new Date().toISOString(),
566
+ },
567
+ projectRoot,
568
+ lineageId,
569
+ );
570
+ await atomicJson(paths.lineagePath, updated, "leader lineage");
571
+ return updated;
572
+ },
573
+ paths,
574
+ );
575
+ }
576
+
577
+ export function validateLeaderHandoffContent(content: LeaderHandoffContent, projectRoot: string): void {
578
+ validateHandoff(content, "leader");
579
+ const root = resolve(projectRoot);
580
+ for (const artifact of content.artifacts) {
581
+ if (!isWithin(root, resolve(root, artifact))) {
582
+ throw new Error("Pi Agent Swarm leader handoff artifact is outside the project root");
583
+ }
584
+ }
585
+ }
586
+
587
+ export async function publishLeaderHandoff(options: {
588
+ projectRoot: string;
589
+ lineageId: string;
590
+ generation: number;
591
+ content: LeaderHandoffContent;
592
+ }): Promise<LeaderLineagePaths> {
593
+ validateLeaderHandoffContent(options.content, options.projectRoot);
594
+ const paths = leaderLineagePaths(options.projectRoot, options.lineageId, options.generation);
595
+ return withLineageLock(
596
+ options.projectRoot,
597
+ options.lineageId,
598
+ async () => {
599
+ const existing = await readLeaderLineage(options.projectRoot, options.lineageId);
600
+ if (existing.currentGeneration !== options.generation) {
601
+ throw new Error("Pi Agent Swarm leader lineage generation was superseded");
602
+ }
603
+ if (existing.state !== "handoff_pending") {
604
+ throw new Error("Pi Agent Swarm leader lineage is not waiting for a handoff");
605
+ }
606
+ await ensureStorageRoot(paths);
607
+ await atomicText(paths.handoffPath, renderLeaderHandoff(options.content));
608
+ const lineage = validateLeaderLineage(
609
+ {
610
+ ...existing,
611
+ originalObjective: options.content.originalObjective,
612
+ state: "handoff_ready",
613
+ currentHandoffPath: paths.handoffPath,
614
+ nextAction: options.content.nextAction,
615
+ remainingWork: options.content.remainingWork,
616
+ updatedAt: new Date().toISOString(),
617
+ },
618
+ options.projectRoot,
619
+ options.lineageId,
620
+ );
621
+ await atomicJson(paths.lineagePath, lineage, "leader lineage");
622
+ return paths;
623
+ },
624
+ paths,
625
+ );
626
+ }
627
+
628
+ export function renderLeaderHandoff(content: LeaderHandoffContent): string {
629
+ return renderHandoffDocument("Leader handoff", content, "leader");
630
+ }
631
+
632
+ export async function verifyLeaderHandoffReadable(
633
+ projectRoot: string,
634
+ lineageId: string,
635
+ generation: number,
636
+ handoffPath: string,
637
+ ): Promise<void> {
638
+ if (generation === 1) return;
639
+ const expected = leaderLineagePaths(projectRoot, lineageId, generation - 1).handoffPath;
640
+ if (resolve(handoffPath) !== expected) {
641
+ throw new Error("Pi Agent Swarm leader successor handoff path does not match its predecessor generation");
642
+ }
643
+ const markdown = await readFile(expected, "utf8");
644
+ if (!hasRequiredHandoffSections(markdown)) {
645
+ throw new Error("Pi Agent Swarm leader successor handoff is incomplete");
646
+ }
647
+ }
648
+
649
+ function validateLeaderLineage(value: unknown, projectRoot: string, lineageId: string): LeaderLineage {
650
+ const lineage = record(value, "leader lineage");
651
+ if (lineage.schemaVersion !== 1 || lineage.lineageId !== lineageId || lineage.projectRoot !== resolve(projectRoot)) {
652
+ throw new Error("Pi Agent Swarm leader lineage identity is invalid");
653
+ }
654
+ if (typeof lineage.leaderSessionId !== "string" || Buffer.byteLength(lineage.leaderSessionId, "utf8") > 256) {
655
+ throw new Error("Pi Agent Swarm leader lineage ownership is invalid");
656
+ }
657
+ if (typeof lineage.originalObjective !== "string") {
658
+ throw new Error("Pi Agent Swarm leader lineage objective is invalid");
659
+ }
660
+ if (!Number.isInteger(lineage.currentGeneration) || (lineage.currentGeneration as number) < 1) {
661
+ throw new Error("Pi Agent Swarm leader lineage generation is invalid");
662
+ }
663
+ if (!Number.isInteger(lineage.replacementCount) || (lineage.replacementCount as number) < 0) {
664
+ throw new Error("Pi Agent Swarm leader lineage replacement count is invalid");
665
+ }
666
+ if (typeof lineage.state !== "string" || !LEADER_LINEAGE_STATES.has(lineage.state as LeaderLineageState)) {
667
+ throw new Error("Pi Agent Swarm leader lineage state is invalid");
668
+ }
669
+ if (
670
+ lineage.autoFailures !== undefined &&
671
+ (!Number.isInteger(lineage.autoFailures) || (lineage.autoFailures as number) < 0)
672
+ ) {
673
+ throw new Error("Pi Agent Swarm leader lineage automatic failure count is invalid");
674
+ }
675
+ if (lineage.autoCircuitOpen !== undefined && typeof lineage.autoCircuitOpen !== "boolean") {
676
+ throw new Error("Pi Agent Swarm leader lineage automatic circuit state is invalid");
677
+ }
678
+ const policy = normalizeLeaderRecyclingPolicy(lineage.policy);
679
+ if (
680
+ lineage.replacementCount !== (lineage.currentGeneration as number) - 1 ||
681
+ (lineage.replacementCount as number) > policy.maxReplacements
682
+ ) {
683
+ throw new Error("Pi Agent Swarm leader lineage replacement budget is invalid");
684
+ }
685
+ if (lineage.currentHandoffPath !== undefined) {
686
+ if (typeof lineage.currentHandoffPath !== "string") {
687
+ throw new Error("Pi Agent Swarm leader lineage handoff path is invalid");
688
+ }
689
+ const handoffPath = resolve(lineage.currentHandoffPath);
690
+ const generations = join(leaderLineagePaths(projectRoot, lineageId, 1).lineageDirectory, "generations");
691
+ if (
692
+ !isWithin(generations, handoffPath) ||
693
+ !/^\d{4}-handoff\.md$/u.test(handoffPath.slice(generations.length + 1))
694
+ ) {
695
+ throw new Error("Pi Agent Swarm leader lineage handoff path is invalid");
696
+ }
697
+ }
698
+ for (const key of ["successorSessionId", "nextAction"] as const) {
699
+ if (lineage[key] !== undefined && typeof lineage[key] !== "string") {
700
+ throw new Error(`Pi Agent Swarm leader lineage ${key} is invalid`);
701
+ }
702
+ }
703
+ if (typeof lineage.updatedAt !== "string") throw new Error("Pi Agent Swarm leader lineage update time is invalid");
704
+ return { ...lineage, policy } as unknown as LeaderLineage;
705
+ }
706
+
707
+ function assertExpectedLeaderLineage(
708
+ lineage: LeaderLineage,
709
+ expected: { generation?: number; state?: LeaderLineageState },
710
+ ): void {
711
+ if (expected.generation !== undefined && lineage.currentGeneration !== expected.generation) {
712
+ throw new Error("Pi Agent Swarm leader lineage generation was superseded");
713
+ }
714
+ if (expected.state !== undefined && lineage.state !== expected.state) {
715
+ throw new Error("Pi Agent Swarm leader lineage state changed before its update");
716
+ }
717
+ }
718
+
719
+ async function readLeaderLineageOptional(projectRoot: string, lineageId: string): Promise<LeaderLineage | undefined> {
720
+ try {
721
+ return await readLeaderLineage(projectRoot, lineageId);
722
+ } catch (error) {
723
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
724
+ throw error;
725
+ }
726
+ }
727
+
728
+ function tokenRange(tokens: number | null): string {
729
+ if (tokens === null) return "unknown";
730
+ if (tokens < 35_000) return "below 35k";
731
+ if (tokens < 50_000) return "35k-50k";
732
+ if (tokens < 100_000) return "50k-100k";
733
+ return "100k+";
734
+ }
735
+
736
+ function finiteNonNegative(value: number | null | undefined): value is number {
737
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
738
+ }
739
+
740
+ function finitePositive(value: number | null | undefined): value is number {
741
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
742
+ }
743
+
744
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
745
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
746
+ }
747
+
748
+ function record(value: unknown, label: string): Record<string, unknown> {
749
+ const result = asRecord(value);
750
+ if (!result) throw new Error(`Pi Agent Swarm ${label} must be an object`);
751
+ return result;
752
+ }