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.
- package/README.md +44 -6
- package/dist/chunks/{menu-RH6GY6U4.ts → menu-NLK5I2DA.ts} +15 -2
- package/dist/chunks/menu-NLK5I2DA.ts.map +7 -0
- package/dist/index.ts +7755 -924
- package/dist/index.ts.map +4 -4
- package/package.json +4 -4
- package/src/auto-name.ts +137 -28
- package/src/budget.ts +268 -0
- package/src/context-recycling.ts +712 -0
- package/src/external-runtime.ts +374 -0
- package/src/fanout.ts +219 -0
- package/src/launch-envelope.ts +115 -0
- package/src/lead-mcp-bridge.ts +516 -0
- package/src/leader-handoff-bridge.ts +155 -0
- package/src/leader-recycling.ts +752 -0
- package/src/leader-runtime.ts +1098 -0
- package/src/leader-session-runtime.ts +71 -0
- package/src/ledger.ts +351 -0
- package/src/menu.ts +16 -2
- package/src/model-catalog.ts +213 -0
- package/src/org.ts +242 -0
- package/src/pi-agent-swarm.ts +55 -2
- package/src/profile-probe.ts +143 -0
- package/src/profiles.ts +621 -0
- package/src/protocol.ts +14 -3
- package/src/reload-handoff.ts +3 -0
- package/src/resource-lease.ts +250 -0
- package/src/reviewer.ts +191 -0
- package/src/settings.ts +335 -10
- package/src/swarm-controller.ts +2207 -89
- package/src/tools.ts +244 -7
- package/src/transport.ts +17 -0
- package/src/worktree.ts +86 -0
- package/dist/chunks/menu-RH6GY6U4.ts.map +0 -7
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join, resolve, sep } from "node:path";
|
|
4
|
+
import type { WorkerRole } from "./profiles.js";
|
|
5
|
+
|
|
6
|
+
export const WORKER_RECYCLING_DIRECTORY = join(".pi", "agent-swarm");
|
|
7
|
+
export const DEFAULT_MAX_CONTEXT_PERCENT = 50;
|
|
8
|
+
export const DEFAULT_MAX_REPLACEMENTS = 3;
|
|
9
|
+
export const MAX_REPLACEMENTS = 10;
|
|
10
|
+
|
|
11
|
+
export const SAFE_LINEAGE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
12
|
+
const TASK_PROFILES = new Set(["short", "long", "auto"]);
|
|
13
|
+
const LINEAGE_STATES = new Set([
|
|
14
|
+
"working",
|
|
15
|
+
"handoff_pending",
|
|
16
|
+
"handoff_ready",
|
|
17
|
+
"replacing",
|
|
18
|
+
"retired",
|
|
19
|
+
"completed",
|
|
20
|
+
"failed",
|
|
21
|
+
]);
|
|
22
|
+
export const SECRET_PATTERNS = [
|
|
23
|
+
/piagentswarm:v1:/iu,
|
|
24
|
+
/PI_SWARM_INVITE/iu,
|
|
25
|
+
/PI_SWARM_KICKOFF_CAPABILITY/iu,
|
|
26
|
+
/PI_SWARM_GROUP_SECRET/iu,
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
export type WorkerTaskProfile = "short" | "long" | "auto";
|
|
30
|
+
export type WorkerTaskStatus = "working" | "completed";
|
|
31
|
+
export type WorkerLineageState =
|
|
32
|
+
| "working"
|
|
33
|
+
| "handoff_pending"
|
|
34
|
+
| "handoff_ready"
|
|
35
|
+
| "replacing"
|
|
36
|
+
| "retired"
|
|
37
|
+
| "completed"
|
|
38
|
+
| "failed";
|
|
39
|
+
|
|
40
|
+
export interface ContextRecyclingPolicyInput {
|
|
41
|
+
taskProfile: WorkerTaskProfile;
|
|
42
|
+
maxContextPercent?: number;
|
|
43
|
+
maxReplacements?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface ContextRecyclingPolicy {
|
|
47
|
+
taskProfile: WorkerTaskProfile;
|
|
48
|
+
maxContextPercent: number;
|
|
49
|
+
maxReplacements: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ContextRecyclingLaunch {
|
|
53
|
+
lineageId: string;
|
|
54
|
+
generation: number;
|
|
55
|
+
replacementCount: number;
|
|
56
|
+
policy: ContextRecyclingPolicy;
|
|
57
|
+
/** Successors must prove this predecessor handoff is readable during session_start. */
|
|
58
|
+
handoffPath?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface WorkerLaunchSpecification {
|
|
62
|
+
cwd: string;
|
|
63
|
+
name?: string;
|
|
64
|
+
color?: string;
|
|
65
|
+
model?: string;
|
|
66
|
+
allowRequests: boolean;
|
|
67
|
+
role?: WorkerRole;
|
|
68
|
+
profile?: string;
|
|
69
|
+
readableDirs?: string[];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface WorkerContextMetric {
|
|
73
|
+
tokens: number | null;
|
|
74
|
+
contextWindow: number;
|
|
75
|
+
percent: number | null;
|
|
76
|
+
updatedAt: string;
|
|
77
|
+
}
|
|
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
|
+
|
|
103
|
+
export interface WorkerHandoffContent {
|
|
104
|
+
originalObjective: string;
|
|
105
|
+
currentState: string;
|
|
106
|
+
completedWork: string;
|
|
107
|
+
remainingWork: string;
|
|
108
|
+
modifiedFiles: string;
|
|
109
|
+
verification: string;
|
|
110
|
+
decisions: string;
|
|
111
|
+
blocker: string;
|
|
112
|
+
nextAction: string;
|
|
113
|
+
artifacts: string[];
|
|
114
|
+
/** Optional S3 structured header embedded ahead of the 10-section Markdown body. */
|
|
115
|
+
structuredHeader?: StructuredHandoffHeader;
|
|
116
|
+
}
|
|
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
|
+
|
|
139
|
+
export type WorkerLineage = {
|
|
140
|
+
schemaVersion: 1;
|
|
141
|
+
lineageId: string;
|
|
142
|
+
projectRoot: string;
|
|
143
|
+
leaderSessionId: string;
|
|
144
|
+
workerSessionId?: string;
|
|
145
|
+
successorSessionId?: string;
|
|
146
|
+
originalObjective: string;
|
|
147
|
+
taskProfile: WorkerTaskProfile;
|
|
148
|
+
policy: ContextRecyclingPolicy;
|
|
149
|
+
launch: WorkerLaunchSpecification;
|
|
150
|
+
currentGeneration: number;
|
|
151
|
+
replacementCount: number;
|
|
152
|
+
state: WorkerLineageState;
|
|
153
|
+
currentHandoffPath?: string;
|
|
154
|
+
nextAction?: string;
|
|
155
|
+
contextUsage?: WorkerContextMetric;
|
|
156
|
+
updatedAt: string;
|
|
157
|
+
} & Record<string, unknown>;
|
|
158
|
+
|
|
159
|
+
export interface WorkerLineagePaths {
|
|
160
|
+
root: string;
|
|
161
|
+
lineageDirectory: string;
|
|
162
|
+
lineagePath: string;
|
|
163
|
+
handoffPath: string;
|
|
164
|
+
artifactsDirectory: string;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function normalizeContextRecyclingPolicy(input: unknown): ContextRecyclingPolicy {
|
|
168
|
+
const value = record(input, "context recycling policy");
|
|
169
|
+
assertKeys(value, ["taskProfile", "maxContextPercent", "maxReplacements"], "context recycling policy");
|
|
170
|
+
if (typeof value.taskProfile !== "string" || !TASK_PROFILES.has(value.taskProfile)) {
|
|
171
|
+
throw new Error("Pi Agent Swarm context recycling task profile is invalid");
|
|
172
|
+
}
|
|
173
|
+
const maxContextPercent = value.maxContextPercent ?? DEFAULT_MAX_CONTEXT_PERCENT;
|
|
174
|
+
if (
|
|
175
|
+
typeof maxContextPercent !== "number" ||
|
|
176
|
+
!Number.isFinite(maxContextPercent) ||
|
|
177
|
+
maxContextPercent <= 0 ||
|
|
178
|
+
maxContextPercent > 100
|
|
179
|
+
) {
|
|
180
|
+
throw new Error("Pi Agent Swarm context recycling percent must be greater than 0 and at most 100");
|
|
181
|
+
}
|
|
182
|
+
const maxReplacements = value.maxReplacements ?? DEFAULT_MAX_REPLACEMENTS;
|
|
183
|
+
if (
|
|
184
|
+
!Number.isInteger(maxReplacements) ||
|
|
185
|
+
(maxReplacements as number) < 0 ||
|
|
186
|
+
(maxReplacements as number) > MAX_REPLACEMENTS
|
|
187
|
+
) {
|
|
188
|
+
throw new Error(`Pi Agent Swarm context recycling replacements must be an integer from 0 to ${MAX_REPLACEMENTS}`);
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
taskProfile: value.taskProfile as WorkerTaskProfile,
|
|
192
|
+
maxContextPercent,
|
|
193
|
+
maxReplacements: maxReplacements as number,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function contextHandoffDecision(
|
|
198
|
+
percent: number | null | undefined,
|
|
199
|
+
taskStatus: WorkerTaskStatus | undefined,
|
|
200
|
+
threshold = DEFAULT_MAX_CONTEXT_PERCENT,
|
|
201
|
+
): "continue" | "complete" | "handoff" {
|
|
202
|
+
if (percent === null || percent === undefined || percent < threshold) return "continue";
|
|
203
|
+
return taskStatus === "completed" ? "complete" : "handoff";
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function workerLineagePaths(projectRoot: string, lineageId: string, generation: number): WorkerLineagePaths {
|
|
207
|
+
if (!SAFE_LINEAGE_ID.test(lineageId)) throw new Error("Pi Agent Swarm lineage id is invalid");
|
|
208
|
+
if (!Number.isInteger(generation) || generation < 1) throw new Error("Pi Agent Swarm lineage generation is invalid");
|
|
209
|
+
const root = resolve(projectRoot);
|
|
210
|
+
const storageRoot = resolve(root, WORKER_RECYCLING_DIRECTORY);
|
|
211
|
+
if (storageRoot !== root && !storageRoot.startsWith(`${root}${sep}`)) {
|
|
212
|
+
throw new Error("Pi Agent Swarm lineage storage escapes the project root");
|
|
213
|
+
}
|
|
214
|
+
const lineageDirectory = join(storageRoot, "lineages", lineageId);
|
|
215
|
+
return {
|
|
216
|
+
root: storageRoot,
|
|
217
|
+
lineageDirectory,
|
|
218
|
+
lineagePath: join(lineageDirectory, "lineage.json"),
|
|
219
|
+
handoffPath: join(lineageDirectory, "generations", `${String(generation).padStart(4, "0")}-handoff.md`),
|
|
220
|
+
artifactsDirectory: join(storageRoot, "artifacts", lineageId, String(generation).padStart(4, "0")),
|
|
221
|
+
};
|
|
222
|
+
}
|
|
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
|
+
|
|
235
|
+
export async function verifyWorkerHandoffReadable(projectRoot: string, launch: ContextRecyclingLaunch): Promise<void> {
|
|
236
|
+
if (launch.generation === 1) return;
|
|
237
|
+
const expected = workerLineagePaths(projectRoot, launch.lineageId, launch.generation - 1).handoffPath;
|
|
238
|
+
if (!launch.handoffPath || resolve(launch.handoffPath) !== expected) {
|
|
239
|
+
throw new Error("Pi Agent Swarm successor handoff path does not match its predecessor generation");
|
|
240
|
+
}
|
|
241
|
+
const markdown = await readFile(expected, "utf8");
|
|
242
|
+
if (!hasRequiredHandoffSections(markdown)) {
|
|
243
|
+
throw new Error("Pi Agent Swarm successor handoff is incomplete");
|
|
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
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export async function initializeWorkerLineage(options: {
|
|
359
|
+
projectRoot: string;
|
|
360
|
+
launch: ContextRecyclingLaunch;
|
|
361
|
+
leaderSessionId: string;
|
|
362
|
+
workerSessionId: string;
|
|
363
|
+
specification: WorkerLaunchSpecification;
|
|
364
|
+
}): Promise<WorkerLineage> {
|
|
365
|
+
return withLineageLock(options.projectRoot, options.launch.lineageId, async () => {
|
|
366
|
+
const existing = await readWorkerLineageOptional(options.projectRoot, options.launch.lineageId);
|
|
367
|
+
if (existing && existing.currentGeneration > options.launch.generation) return existing;
|
|
368
|
+
const now = new Date().toISOString();
|
|
369
|
+
const lineage: WorkerLineage = {
|
|
370
|
+
...(existing ?? {}),
|
|
371
|
+
schemaVersion: 1,
|
|
372
|
+
lineageId: options.launch.lineageId,
|
|
373
|
+
projectRoot: resolve(options.projectRoot),
|
|
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,
|
|
377
|
+
workerSessionId: options.workerSessionId,
|
|
378
|
+
originalObjective: existing?.originalObjective ?? "",
|
|
379
|
+
taskProfile: options.launch.policy.taskProfile,
|
|
380
|
+
policy: options.launch.policy,
|
|
381
|
+
launch: options.specification,
|
|
382
|
+
currentGeneration: options.launch.generation,
|
|
383
|
+
replacementCount: options.launch.replacementCount,
|
|
384
|
+
state: existing?.currentGeneration === options.launch.generation ? existing.state : "working",
|
|
385
|
+
currentHandoffPath: options.launch.handoffPath ?? existing?.currentHandoffPath,
|
|
386
|
+
nextAction: existing?.nextAction,
|
|
387
|
+
updatedAt: now,
|
|
388
|
+
};
|
|
389
|
+
const paths = workerLineagePaths(options.projectRoot, options.launch.lineageId, options.launch.generation);
|
|
390
|
+
await ensureStorageRoot(paths);
|
|
391
|
+
await mkdir(paths.artifactsDirectory, { recursive: true, mode: 0o700 });
|
|
392
|
+
await atomicJson(paths.lineagePath, lineage);
|
|
393
|
+
return lineage;
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export async function readWorkerLineage(projectRoot: string, lineageId: string): Promise<WorkerLineage> {
|
|
398
|
+
const paths = workerLineagePaths(projectRoot, lineageId, 1);
|
|
399
|
+
const value = JSON.parse(await readFile(paths.lineagePath, "utf8")) as unknown;
|
|
400
|
+
return validateWorkerLineage(value, projectRoot, lineageId);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export async function updateWorkerLineage(
|
|
404
|
+
projectRoot: string,
|
|
405
|
+
lineageId: string,
|
|
406
|
+
patch: Record<string, unknown>,
|
|
407
|
+
expected: { generation?: number; state?: WorkerLineageState } = {},
|
|
408
|
+
): Promise<WorkerLineage> {
|
|
409
|
+
return withLineageLock(projectRoot, lineageId, async () => {
|
|
410
|
+
const existing = await readWorkerLineage(projectRoot, lineageId);
|
|
411
|
+
if (expected.generation !== undefined && existing.currentGeneration !== expected.generation) {
|
|
412
|
+
throw new Error("Pi Agent Swarm worker lineage generation was superseded");
|
|
413
|
+
}
|
|
414
|
+
if (expected.state !== undefined && existing.state !== expected.state) {
|
|
415
|
+
throw new Error("Pi Agent Swarm worker lineage state changed before its update");
|
|
416
|
+
}
|
|
417
|
+
const updated = validateWorkerLineage(
|
|
418
|
+
{ ...existing, ...patch, lineageId, projectRoot: resolve(projectRoot), updatedAt: new Date().toISOString() },
|
|
419
|
+
projectRoot,
|
|
420
|
+
lineageId,
|
|
421
|
+
);
|
|
422
|
+
await atomicJson(workerLineagePaths(projectRoot, lineageId, existing.currentGeneration).lineagePath, updated);
|
|
423
|
+
return updated;
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
export async function publishWorkerHandoff(options: {
|
|
428
|
+
projectRoot: string;
|
|
429
|
+
lineageId: string;
|
|
430
|
+
generation: number;
|
|
431
|
+
leaderSessionId: string;
|
|
432
|
+
policy: ContextRecyclingPolicy;
|
|
433
|
+
launch: WorkerLaunchSpecification;
|
|
434
|
+
content: WorkerHandoffContent;
|
|
435
|
+
nextAction: string;
|
|
436
|
+
}): Promise<{ handoffPath: string; leaderSessionId: string }> {
|
|
437
|
+
return withLineageLock(options.projectRoot, options.lineageId, async () => {
|
|
438
|
+
validateHandoff(options.content);
|
|
439
|
+
const root = resolve(options.projectRoot);
|
|
440
|
+
for (const artifact of options.content.artifacts) {
|
|
441
|
+
if (!isWithin(root, resolve(root, artifact))) {
|
|
442
|
+
throw new Error("Pi Agent Swarm handoff artifact is outside the project root");
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (options.content.structuredHeader) {
|
|
446
|
+
const validHeader = validateStructuredHandoffHeader(options.content.structuredHeader);
|
|
447
|
+
await verifyHandoffEvidence(root, validHeader.evidence, options.launch.readableDirs ?? []);
|
|
448
|
+
}
|
|
449
|
+
const paths = workerLineagePaths(options.projectRoot, options.lineageId, options.generation);
|
|
450
|
+
const existing = await readWorkerLineageOptional(options.projectRoot, options.lineageId);
|
|
451
|
+
if (
|
|
452
|
+
existing &&
|
|
453
|
+
(existing.currentGeneration > options.generation ||
|
|
454
|
+
existing.state === "replacing" ||
|
|
455
|
+
(existing.state === "working" && existing.currentHandoffPath !== paths.handoffPath))
|
|
456
|
+
) {
|
|
457
|
+
throw new Error("Pi Agent Swarm handoff was superseded by a newer generation");
|
|
458
|
+
}
|
|
459
|
+
await ensureStorageRoot(paths);
|
|
460
|
+
await mkdir(dirname(paths.handoffPath), { recursive: true, mode: 0o700 });
|
|
461
|
+
await mkdir(paths.artifactsDirectory, { recursive: true, mode: 0o700 });
|
|
462
|
+
await atomicText(paths.handoffPath, renderWorkerHandoff(options.content));
|
|
463
|
+
const lineage = validateWorkerLineage(
|
|
464
|
+
{
|
|
465
|
+
...(existing ?? {}),
|
|
466
|
+
schemaVersion: 1,
|
|
467
|
+
lineageId: options.lineageId,
|
|
468
|
+
projectRoot: root,
|
|
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,
|
|
472
|
+
originalObjective: options.content.originalObjective,
|
|
473
|
+
taskProfile: options.policy.taskProfile,
|
|
474
|
+
policy: options.policy,
|
|
475
|
+
launch: options.launch,
|
|
476
|
+
currentGeneration: options.generation,
|
|
477
|
+
replacementCount: existing?.replacementCount ?? Math.max(0, options.generation - 1),
|
|
478
|
+
state: "handoff_ready",
|
|
479
|
+
currentHandoffPath: paths.handoffPath,
|
|
480
|
+
nextAction: options.nextAction,
|
|
481
|
+
remainingWork: options.content.remainingWork,
|
|
482
|
+
updatedAt: new Date().toISOString(),
|
|
483
|
+
},
|
|
484
|
+
options.projectRoot,
|
|
485
|
+
options.lineageId,
|
|
486
|
+
);
|
|
487
|
+
await atomicJson(paths.lineagePath, lineage);
|
|
488
|
+
return { handoffPath: paths.handoffPath, leaderSessionId: lineage.leaderSessionId };
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
export function renderWorkerHandoff(content: WorkerHandoffContent): string {
|
|
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`);
|
|
520
|
+
for (const key of [
|
|
521
|
+
"originalObjective",
|
|
522
|
+
"currentState",
|
|
523
|
+
"completedWork",
|
|
524
|
+
"remainingWork",
|
|
525
|
+
"modifiedFiles",
|
|
526
|
+
"verification",
|
|
527
|
+
"decisions",
|
|
528
|
+
"blocker",
|
|
529
|
+
"nextAction",
|
|
530
|
+
]) {
|
|
531
|
+
if (typeof value[key] !== "string" || Buffer.byteLength(value[key], "utf8") > 8192) {
|
|
532
|
+
throw new Error(`Pi Agent Swarm ${owner} handoff ${key} is invalid`);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (
|
|
536
|
+
!Array.isArray(value.artifacts) ||
|
|
537
|
+
value.artifacts.length > 32 ||
|
|
538
|
+
value.artifacts.some((item) => typeof item !== "string")
|
|
539
|
+
) {
|
|
540
|
+
throw new Error(`Pi Agent Swarm ${owner} handoff artifacts are invalid`);
|
|
541
|
+
}
|
|
542
|
+
const serialized = JSON.stringify(value);
|
|
543
|
+
if (Buffer.byteLength(serialized, "utf8") > 40 * 1024)
|
|
544
|
+
throw new Error(`Pi Agent Swarm ${owner} handoff is too large`);
|
|
545
|
+
if (SECRET_PATTERNS.some((pattern) => pattern.test(serialized))) {
|
|
546
|
+
throw new Error(`Pi Agent Swarm ${owner} handoff must not contain secret material`);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
async function readWorkerLineageOptional(projectRoot: string, lineageId: string): Promise<WorkerLineage | undefined> {
|
|
551
|
+
try {
|
|
552
|
+
return await readWorkerLineage(projectRoot, lineageId);
|
|
553
|
+
} catch (error) {
|
|
554
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
555
|
+
throw error;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
export function isWithin(root: string, candidate: string): boolean {
|
|
560
|
+
return candidate === root || candidate.startsWith(`${root}${sep}`);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
export async function ensureStorageRoot(paths: { root: string }): Promise<void> {
|
|
564
|
+
await mkdir(paths.root, { recursive: true, mode: 0o700 });
|
|
565
|
+
try {
|
|
566
|
+
await writeFile(join(paths.root, ".gitignore"), "*\n", { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
567
|
+
} catch (error) {
|
|
568
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
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`;
|
|
580
|
+
await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 });
|
|
581
|
+
let handle: Awaited<ReturnType<typeof open>> | undefined;
|
|
582
|
+
for (let attempt = 0; attempt < 200 && !handle; attempt += 1) {
|
|
583
|
+
try {
|
|
584
|
+
handle = await open(lockPath, "wx", 0o600);
|
|
585
|
+
} catch (error) {
|
|
586
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
587
|
+
const lockStat = await stat(lockPath).catch(() => undefined);
|
|
588
|
+
if (lockStat && Date.now() - lockStat.mtimeMs > 30_000) await rm(lockPath, { force: true });
|
|
589
|
+
await new Promise((resolveDelay) => setTimeout(resolveDelay, 5));
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
if (!handle) throw new Error("Pi Agent Swarm lineage is busy with another update");
|
|
593
|
+
try {
|
|
594
|
+
return await callback();
|
|
595
|
+
} finally {
|
|
596
|
+
await handle.close();
|
|
597
|
+
await rm(lockPath, { force: true });
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function validateWorkerLineage(value: unknown, projectRoot: string, lineageId: string): WorkerLineage {
|
|
602
|
+
const lineage = record(value, "worker lineage");
|
|
603
|
+
if (lineage.schemaVersion !== 1 || lineage.lineageId !== lineageId || lineage.projectRoot !== resolve(projectRoot)) {
|
|
604
|
+
throw new Error("Pi Agent Swarm worker lineage identity is invalid");
|
|
605
|
+
}
|
|
606
|
+
if (typeof lineage.leaderSessionId !== "string" || typeof lineage.originalObjective !== "string") {
|
|
607
|
+
throw new Error("Pi Agent Swarm worker lineage ownership is invalid");
|
|
608
|
+
}
|
|
609
|
+
if (!Number.isInteger(lineage.currentGeneration) || (lineage.currentGeneration as number) < 1) {
|
|
610
|
+
throw new Error("Pi Agent Swarm worker lineage generation is invalid");
|
|
611
|
+
}
|
|
612
|
+
if (!Number.isInteger(lineage.replacementCount) || (lineage.replacementCount as number) < 0) {
|
|
613
|
+
throw new Error("Pi Agent Swarm worker lineage replacement count is invalid");
|
|
614
|
+
}
|
|
615
|
+
if (typeof lineage.state !== "string" || !LINEAGE_STATES.has(lineage.state)) {
|
|
616
|
+
throw new Error("Pi Agent Swarm worker lineage state is invalid");
|
|
617
|
+
}
|
|
618
|
+
const policy = normalizeContextRecyclingPolicy(lineage.policy);
|
|
619
|
+
if (
|
|
620
|
+
(lineage.replacementCount as number) !== (lineage.currentGeneration as number) - 1 ||
|
|
621
|
+
(lineage.replacementCount as number) > policy.maxReplacements
|
|
622
|
+
) {
|
|
623
|
+
throw new Error("Pi Agent Swarm worker lineage replacement budget is invalid");
|
|
624
|
+
}
|
|
625
|
+
const launch = record(lineage.launch, "worker lineage launch");
|
|
626
|
+
assertKeys(
|
|
627
|
+
launch,
|
|
628
|
+
["cwd", "name", "color", "model", "allowRequests", "role", "profile", "readableDirs"],
|
|
629
|
+
"worker lineage launch",
|
|
630
|
+
);
|
|
631
|
+
if (
|
|
632
|
+
typeof launch.cwd !== "string" ||
|
|
633
|
+
resolve(launch.cwd) !== resolve(projectRoot) ||
|
|
634
|
+
typeof launch.allowRequests !== "boolean"
|
|
635
|
+
) {
|
|
636
|
+
throw new Error("Pi Agent Swarm worker lineage launch is invalid");
|
|
637
|
+
}
|
|
638
|
+
for (const key of ["name", "color", "model", "profile"] as const) {
|
|
639
|
+
if (
|
|
640
|
+
launch[key] !== undefined &&
|
|
641
|
+
(typeof launch[key] !== "string" || Buffer.byteLength(launch[key], "utf8") > 4_096)
|
|
642
|
+
) {
|
|
643
|
+
throw new Error(`Pi Agent Swarm worker lineage launch ${key} is invalid`);
|
|
644
|
+
}
|
|
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
|
+
}
|
|
662
|
+
if (lineage.currentHandoffPath !== undefined) {
|
|
663
|
+
const handoffPath = resolve(String(lineage.currentHandoffPath));
|
|
664
|
+
const generations = join(workerLineagePaths(projectRoot, lineageId, 1).lineageDirectory, "generations");
|
|
665
|
+
if (
|
|
666
|
+
!isWithin(generations, handoffPath) ||
|
|
667
|
+
!/^\d{4}-handoff\.md$/u.test(handoffPath.slice(generations.length + 1))
|
|
668
|
+
) {
|
|
669
|
+
throw new Error("Pi Agent Swarm worker lineage handoff path is invalid");
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
for (const key of ["workerSessionId", "successorSessionId", "leaderSessionId"] as const) {
|
|
673
|
+
if (typeof lineage[key] !== "string" || Buffer.byteLength(lineage[key], "utf8") > 256) {
|
|
674
|
+
if (key !== "leaderSessionId" && lineage[key] === undefined) continue;
|
|
675
|
+
throw new Error(`Pi Agent Swarm worker lineage ${key} is invalid`);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
if (typeof lineage.updatedAt !== "string") throw new Error("Pi Agent Swarm worker lineage update time is invalid");
|
|
679
|
+
return { ...lineage, policy, launch } as unknown as WorkerLineage;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
export async function atomicJson(path: string, value: unknown, label = "worker lineage"): Promise<void> {
|
|
683
|
+
const serialized = JSON.stringify(value, null, 2);
|
|
684
|
+
if (SECRET_PATTERNS.some((pattern) => pattern.test(serialized))) {
|
|
685
|
+
throw new Error(`Pi Agent Swarm ${label} must not contain secret material`);
|
|
686
|
+
}
|
|
687
|
+
await atomicText(path, `${serialized}\n`);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
export async function atomicText(path: string, content: string): Promise<void> {
|
|
691
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
692
|
+
const temporary = `${path}.tmp-${process.pid}-${randomBytes(8).toString("hex")}`;
|
|
693
|
+
await writeFile(temporary, content, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
694
|
+
try {
|
|
695
|
+
await rename(temporary, path);
|
|
696
|
+
} catch (error) {
|
|
697
|
+
const { rm } = await import("node:fs/promises");
|
|
698
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
699
|
+
throw error;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
function record(value: unknown, label: string): Record<string, unknown> {
|
|
704
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
705
|
+
throw new Error(`Pi Agent Swarm ${label} must be an object`);
|
|
706
|
+
return value as Record<string, unknown>;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function assertKeys(value: Record<string, unknown>, allowed: string[], label: string): void {
|
|
710
|
+
const unknown = Object.keys(value).find((key) => !allowed.includes(key));
|
|
711
|
+
if (unknown) throw new Error(`Pi Agent Swarm ${label} has unknown field ${unknown}`);
|
|
712
|
+
}
|