pi-herdsman 0.36.2 → 0.36.3

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/dist/index.js CHANGED
@@ -113,425 +113,22 @@ var init_compatibility = __esm({
113
113
  }
114
114
  });
115
115
 
116
- // extension/storage.ts
117
- import { homedir, tmpdir } from "node:os";
118
- import {
119
- chmodSync,
120
- closeSync,
121
- constants,
122
- fstatSync,
123
- fsyncSync,
124
- mkdirSync,
125
- openSync,
126
- readdirSync,
127
- readFileSync as readFileSync2,
128
- renameSync,
129
- lstatSync,
130
- unlinkSync,
131
- writeFileSync
132
- } from "node:fs";
133
- import { createHash as createHash2, randomUUID } from "node:crypto";
134
- import { basename, dirname, join } from "node:path";
135
- import { fileURLToPath } from "node:url";
136
- function isIncidentalMetadata(entry) {
137
- return entry.isFile() && INCIDENTAL_METADATA.has(entry.name.toLowerCase());
138
- }
139
- function isRequiredEvidence(value2) {
140
- if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return false;
141
- const r = value2;
142
- if (typeof r.id !== "string" || !EVIDENCE_ID.test(r.id) || typeof r.name !== "string" || !r.name || r.name.length > 255)
143
- return false;
144
- if (Object.hasOwn(r, "result"))
145
- return Object.keys(r).length === 3 && isResultBinding(r.result);
146
- const keys = Object.keys(r).sort();
147
- const legacyKeys = ["id", "name", "path", "sha256", "sourceAssignmentId"];
148
- const semanticKeys = [...legacyKeys, "ref"].sort();
149
- return (keys.join("\0") === legacyKeys.join("\0") || keys.join("\0") === semanticKeys.join("\0")) && (!Object.hasOwn(r, "ref") || isCanonicalSemanticEvidenceRef(r.ref)) && typeof r.sourceAssignmentId === "string" && EVIDENCE_ID.test(r.sourceAssignmentId) && typeof r.path === "string" && r.path.length > 0 && typeof r.sha256 === "string" && /^[a-f0-9]{64}$/.test(r.sha256);
150
- }
151
- function isCanonicalSemanticEvidenceRef(value2) {
152
- if (typeof value2 !== "string") return false;
153
- const match = SEMANTIC_EVIDENCE_REF.exec(value2);
154
- return !!match && Number.isSafeInteger(Number(match[2]));
155
- }
156
- function semanticEvidenceRef(evidence) {
157
- if ("result" in evidence) return evidence.result.ref;
158
- if (!evidence.ref)
159
- throw new Error("required evidence has no semantic reference");
160
- return evidence.ref;
161
- }
162
- function upgradeRequiredEvidence(value2) {
163
- if (!isRequiredEvidence(value2)) throw new Error("invalid required evidence");
164
- if ("result" in value2 || value2.ref) return value2;
165
- const ref = reserveSemanticEvidenceRef(value2.id, value2.name);
166
- return { ...value2, ref };
167
- }
168
- function verifySemanticEvidenceReservation(evidenceId, ref) {
169
- if (!EVIDENCE_ID.test(evidenceId) || !isCanonicalSemanticEvidenceRef(ref))
170
- throw new Error("invalid semantic evidence reservation");
171
- const match = SEMANTIC_EVIDENCE_REF.exec(ref);
172
- const root2 = join(herdsmanDataRoot(), "evidence-ref-reservations");
173
- const paths = [
174
- join(root2, "by-id", evidenceId),
175
- join(root2, "refs", match[1], match[2])
176
- ];
177
- const contents = paths.map((path) => {
178
- const stat = lstatSync(path);
179
- if (!stat.isFile() || stat.isSymbolicLink())
180
- throw new Error("invalid semantic evidence reservation");
181
- return readFileSync2(path, "utf8");
182
- });
183
- const [byId, byRef] = contents;
184
- if (byId !== `${ref}
185
- ` || byRef !== `${evidenceId}
186
- `)
187
- throw new Error("invalid semantic evidence reservation");
188
- }
189
- function upgradeAndVerifyRequiredEvidence(value2) {
190
- const evidence = upgradeRequiredEvidence(value2);
191
- if (!("result" in evidence))
192
- verifySemanticEvidenceReservation(evidence.id, evidence.ref);
193
- return evidence;
194
- }
195
- function requiredEvidenceDirectory(assignmentId) {
196
- if (!EVIDENCE_ID.test(assignmentId))
197
- throw new Error("invalid evidence assignment id");
198
- return join(herdsmanDataRoot(), "evidence", assignmentId);
199
- }
200
- function assertEvidenceDirectory(assignmentId, create) {
201
- const directory2 = requiredEvidenceDirectory(assignmentId);
202
- const paths = [
203
- herdsmanDataRoot(),
204
- join(herdsmanDataRoot(), "evidence"),
205
- directory2
206
- ];
207
- for (const path of paths) {
208
- if (create) {
209
- try {
210
- mkdirSync(path, { mode: 448 });
211
- } catch (error2) {
212
- if (error2.code !== "EEXIST") throw error2;
213
- }
214
- }
215
- const stat = lstatSync(path);
216
- if (!stat.isDirectory() || stat.isSymbolicLink())
217
- throw new Error("required evidence directory is unsafe");
218
- }
219
- return directory2;
220
- }
221
- function safeEvidenceName(name) {
222
- const base = basename(name).replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 100);
223
- return base || "evidence.txt";
224
- }
225
- function persistRequiredEvidenceSnapshot(assignmentId, name, text) {
226
- const bytes = Buffer.from(text, "utf8");
227
- if (bytes.length > EVIDENCE_SNAPSHOT_MAX_BYTES || bytes.includes(0) || new TextDecoder("utf-8", { fatal: true }).decode(bytes) !== text)
228
- throw new Error(
229
- "Required evidence must be supported UTF-8 text no larger than 1 MiB"
230
- );
231
- const directory2 = assertEvidenceDirectory(assignmentId, true);
232
- chmodSync(directory2, 448);
233
- const id = randomUUID();
234
- const path = join(directory2, `${id}-${safeEvidenceName(name)}`);
235
- const temporary = `${path}.${randomUUID()}.tmp`;
236
- let fd;
237
- try {
238
- fd = openSync(temporary, "wx", 384);
239
- writeFileSync(fd, bytes);
240
- fsyncSync(fd);
241
- closeSync(fd);
242
- fd = void 0;
243
- assertEvidenceDirectory(assignmentId, false);
244
- renameSync(temporary, path);
245
- chmodSync(path, 384);
246
- if (process.platform !== "win32") {
247
- const dirFd = openSync(directory2, "r");
248
- try {
249
- fsyncSync(dirFd);
250
- } finally {
251
- closeSync(dirFd);
252
- }
253
- }
254
- return {
255
- id,
256
- ref: reserveSemanticEvidenceRef(id, name),
257
- name: safeEvidenceName(name),
258
- sourceAssignmentId: assignmentId,
259
- path,
260
- sha256: createHash2("sha256").update(bytes).digest("hex")
261
- };
262
- } finally {
263
- if (fd !== void 0) closeSync(fd);
264
- try {
265
- unlinkSync(temporary);
266
- } catch (error2) {
267
- if (error2.code !== "ENOENT") throw error2;
268
- }
269
- }
270
- }
271
- function reserveSemanticEvidenceRef(evidenceId, name) {
272
- if (!EVIDENCE_ID.test(evidenceId)) throw new Error("invalid evidence id");
273
- const root2 = join(herdsmanDataRoot(), "evidence-ref-reservations");
274
- const byId = join(root2, "by-id");
275
- mkdirSync(byId, { recursive: true, mode: 448 });
276
- chmodSync(byId, 448);
277
- const mapping = join(byId, evidenceId);
278
- try {
279
- const existing = readFileSync2(mapping, "utf8").trim();
280
- if (isCanonicalSemanticEvidenceRef(existing)) return existing;
281
- throw new Error("invalid semantic evidence reservation");
282
- } catch (error2) {
283
- if (error2.code !== "ENOENT") throw error2;
284
- }
285
- const label = safeEvidenceName(name).replace(/\.[^.]*$/, "").toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").slice(0, 32) || "evidence";
286
- const directory2 = join(root2, "refs", label);
287
- mkdirSync(directory2, { recursive: true, mode: 448 });
288
- chmodSync(directory2, 448);
289
- let index = 1;
290
- for (const entry of readdirSync(directory2)) {
291
- if (/^[1-9][0-9]*$/.test(entry)) index = Math.max(index, Number(entry) + 1);
292
- }
293
- for (; ; ) {
294
- if (!Number.isSafeInteger(index))
295
- throw new Error("Semantic evidence index exhausted");
296
- const ref = `evidence:${label}#${index}`;
297
- try {
298
- writeFileSync(join(directory2, String(index)), `${evidenceId}
299
- `, {
300
- encoding: "utf8",
301
- flag: "wx",
302
- mode: 384,
303
- flush: true
304
- });
305
- try {
306
- writeFileSync(mapping, `${ref}
307
- `, {
308
- encoding: "utf8",
309
- flag: "wx",
310
- mode: 384,
311
- flush: true
312
- });
313
- } catch (error2) {
314
- if (error2.code !== "EEXIST") throw error2;
315
- return reserveSemanticEvidenceRef(evidenceId, name);
316
- }
317
- return ref;
318
- } catch (error2) {
319
- if (error2.code === "EEXIST") {
320
- index++;
321
- continue;
322
- }
323
- throw error2;
324
- }
325
- }
326
- }
327
- function readRequiredEvidenceSnapshot(assignmentId, evidence) {
328
- if (!isRequiredEvidence(evidence) || "result" in evidence)
329
- throw new Error("invalid required evidence snapshot");
330
- if (evidence.sourceAssignmentId !== assignmentId)
331
- throw new Error("required evidence source assignment mismatch");
332
- const directory2 = requiredEvidenceDirectory(evidence.sourceAssignmentId);
333
- if (evidence.path !== join(directory2, `${evidence.id}-${safeEvidenceName(evidence.name)}`))
334
- throw new Error("required evidence path mismatch");
335
- assertEvidenceDirectory(evidence.sourceAssignmentId, false);
336
- const before = lstatSync(evidence.path);
337
- if (!before.isFile() || before.isSymbolicLink() || before.size > EVIDENCE_SNAPSHOT_MAX_BYTES)
338
- throw new Error(
339
- "required evidence snapshot is missing, unsafe, or oversized"
340
- );
341
- const fd = openSync(
342
- evidence.path,
343
- constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
344
- );
345
- try {
346
- const opened = fstatSync(fd);
347
- if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino)
348
- throw new Error("required evidence snapshot changed during read");
349
- const bytes = readFileSync2(fd);
350
- if (bytes.length > EVIDENCE_SNAPSHOT_MAX_BYTES || createHash2("sha256").update(bytes).digest("hex") !== evidence.sha256)
351
- throw new Error("required evidence snapshot integrity check failed");
352
- return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
353
- } finally {
354
- closeSync(fd);
355
- }
356
- }
357
- function parseSemanticResultRef(input) {
358
- const match = SEMANTIC_RESULT_REF.exec(input);
359
- if (!match) return void 0;
360
- const index = Number(match[2]);
361
- if (!Number.isSafeInteger(index)) return void 0;
362
- return { agent: match[1], index };
363
- }
364
- function isCanonicalResultRef(value2) {
365
- return typeof value2 === "string" && value2.startsWith(RESULT_PREFIX) && RESULT_ID.test(value2.slice(RESULT_PREFIX.length));
366
- }
367
- function isResultBinding(value2) {
368
- if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return false;
369
- const record = value2;
370
- return Object.keys(record).length === 2 && typeof record.ref === "string" && !!parseSemanticResultRef(record.ref) && isCanonicalResultRef(record.canonicalRef);
371
- }
372
- function herdsmanDataRoot() {
373
- return join(nodeOnlyAgentDir(), "pi-herdsman");
374
- }
375
- function nodeOnlyAgentDir() {
376
- let directory2 = process.env.PI_CODING_AGENT_DIR;
377
- if (!directory2) return join(homedir(), ".pi", "agent");
378
- if (process.platform === "win32" && directory2.startsWith("/") && !directory2.startsWith("//") && !directory2.includes("\\")) {
379
- const match = directory2.match(
380
- /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i
381
- );
382
- if (match)
383
- directory2 = `${match[1].toUpperCase()}:\\${(match[2] ?? "").replaceAll("/", "\\")}`;
384
- }
385
- if (directory2 === "~") return homedir();
386
- if (directory2.startsWith("~/") || process.platform === "win32" && directory2.startsWith("~\\"))
387
- return join(homedir(), directory2.slice(2));
388
- if (/^file:\/\//.test(directory2)) return fileURLToPath(directory2);
389
- return directory2;
390
- }
391
- function herdsmanConfigPath() {
392
- return join(herdsmanDataRoot(), "config.json");
393
- }
394
- function herdsmanTempRoot() {
395
- return join(tmpdir(), `pi-herdsman-${process.getuid?.() ?? "user"}`);
396
- }
397
- function validateResultId(requestId) {
398
- if (!RESULT_ID.test(requestId)) throw new Error("invalid result request id");
399
- }
400
- function resultPath(requestId) {
401
- validateResultId(requestId);
402
- return join(herdsmanDataRoot(), "results", requestId);
403
- }
404
- function peerAttachmentPath(name, text) {
405
- if (typeof name !== "string" || !name || name.length > 255 || /[\\/\0]/u.test(name) || typeof text !== "string")
406
- throw new Error("invalid peer attachment");
407
- const bytes = Buffer.from(text, "utf8");
408
- if (new TextDecoder("utf-8", { fatal: true }).decode(bytes) !== text)
409
- throw new Error("invalid peer attachment text");
410
- const directory2 = join(
411
- herdsmanDataRoot(),
412
- "runtime",
413
- "peers-v2",
414
- "received-evidence"
415
- );
416
- const digest = createHash2("sha256").update(bytes).digest("hex");
417
- return join(directory2, `${digest}-${name}`);
418
- }
419
- function persistPeerAttachment(name, text) {
420
- const path = peerAttachmentPath(name, text);
421
- const bytes = Buffer.from(text, "utf8");
422
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
423
- chmodSync(dirname(path), 448);
424
- try {
425
- writeFileSync(path, bytes, { flag: "wx", mode: 384, flush: true });
426
- } catch (error2) {
427
- if (error2.code !== "EEXIST") throw error2;
428
- if (!readFileSync2(path).equals(bytes))
429
- throw new Error("peer attachment content identity collision");
430
- }
431
- return path;
432
- }
433
- function persistPeerResultArtifact(canonicalRef, text) {
434
- if (!isCanonicalResultRef(canonicalRef) || typeof text !== "string")
435
- throw new Error("invalid peer result artifact");
436
- const path = resultPath(canonicalRef.slice(RESULT_PREFIX.length));
437
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
438
- chmodSync(dirname(path), 448);
439
- const bytes = Buffer.from(text, "utf8");
440
- try {
441
- writeFileSync(path, bytes, { flag: "wx", mode: 384, flush: true });
442
- } catch (error2) {
443
- if (error2.code !== "EEXIST") throw error2;
444
- if (!readFileSync2(path).equals(bytes))
445
- throw new Error("peer result identity collision");
446
- }
447
- return path;
448
- }
449
- function resultRef(requestId) {
450
- validateResultId(requestId);
451
- return `${RESULT_PREFIX}${requestId}`;
452
- }
453
- function reserveSemanticResultRef(agentLabel, minimumIndex = 1) {
454
- if (!parseSemanticResultRef(`result:${agentLabel}#${minimumIndex}`))
455
- throw new Error("Invalid semantic result identity");
456
- const directory2 = join(
457
- herdsmanDataRoot(),
458
- "result-ref-reservations",
459
- agentLabel
460
- );
461
- mkdirSync(directory2, { recursive: true, mode: 448 });
462
- chmodSync(directory2, 448);
463
- let index = minimumIndex;
464
- for (const name of readdirSync(directory2)) {
465
- if (!/^[1-9][0-9]*$/.test(name)) continue;
466
- const reserved = Number(name);
467
- if (Number.isSafeInteger(reserved)) index = Math.max(index, reserved + 1);
468
- }
469
- for (; ; ) {
470
- if (!Number.isSafeInteger(index))
471
- throw new Error("Semantic result index exhausted");
472
- try {
473
- writeFileSync(join(directory2, String(index)), "reserved\n", {
474
- encoding: "utf8",
475
- flag: "wx",
476
- mode: 384,
477
- flush: true
478
- });
479
- if (process.platform !== "win32") {
480
- const fd = openSync(directory2, "r");
481
- try {
482
- fsyncSync(fd);
483
- } finally {
484
- closeSync(fd);
485
- }
486
- }
487
- return { index, ref: `result:${agentLabel}#${index}` };
488
- } catch (error2) {
489
- if (error2.code === "EEXIST") {
490
- index++;
491
- continue;
492
- }
493
- throw error2;
494
- }
495
- }
496
- }
497
- function resolveResultRef(input) {
498
- if (!input.startsWith(RESULT_PREFIX)) return void 0;
499
- return resultPath(input.slice(RESULT_PREFIX.length));
500
- }
501
- var RESULT_PREFIX, RESULT_ID, SEMANTIC_RESULT_REF, SEMANTIC_EVIDENCE_REF, INCIDENTAL_METADATA, EVIDENCE_ID, EVIDENCE_SNAPSHOT_MAX_BYTES;
502
- var init_storage = __esm({
503
- "extension/storage.ts"() {
504
- RESULT_PREFIX = "result:";
505
- RESULT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
506
- SEMANTIC_RESULT_REF = /^result:([a-z][a-z0-9_-]{0,31})#([1-9][0-9]*)$/;
507
- SEMANTIC_EVIDENCE_REF = /^evidence:([a-z][a-z0-9_-]{0,31})#([1-9][0-9]*)$/;
508
- INCIDENTAL_METADATA = /* @__PURE__ */ new Set([
509
- ".ds_store",
510
- "desktop.ini",
511
- "thumbs.db",
512
- ".directory"
513
- ]);
514
- EVIDENCE_ID = RESULT_ID;
515
- EVIDENCE_SNAPSHOT_MAX_BYTES = 1024 * 1024;
516
- }
517
- });
518
-
519
116
  // extension/lock.ts
520
117
  import * as fs from "node:fs";
521
- import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
522
- import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
118
+ import { createHash as createHash2, randomUUID } from "node:crypto";
119
+ import { basename, dirname, join } from "node:path";
523
120
  function assignmentLockPath(mailbox) {
524
- return join2(
121
+ return join(
525
122
  herdsmanTempRoot(),
526
123
  "locks",
527
- `assignment-${createHash4("sha256").update(mailbox).digest("hex")}`
124
+ `assignment-${createHash2("sha256").update(mailbox).digest("hex")}`
528
125
  );
529
126
  }
530
127
  function sessionActivationLockPath(canonicalSessionPath2) {
531
- return join2(
128
+ return join(
532
129
  herdsmanTempRoot(),
533
130
  "locks",
534
- `session-${createHash4("sha256").update(canonicalSessionPath2).digest("hex")}`
131
+ `session-${createHash2("sha256").update(canonicalSessionPath2).digest("hex")}`
535
132
  );
536
133
  }
537
134
  function claimAssignmentLock(mailbox) {
@@ -562,7 +159,7 @@ function isProcessLockClaim(value2) {
562
159
  return true;
563
160
  }
564
161
  function readProcessLockOwner(path, owner) {
565
- const value2 = JSON.parse(fs.readFileSync(join2(path, owner), "utf8"));
162
+ const value2 = JSON.parse(fs.readFileSync(join(path, owner), "utf8"));
566
163
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2))
567
164
  throw new Error("invalid process lock claim");
568
165
  const record = value2;
@@ -639,9 +236,9 @@ function processExists(pid) {
639
236
  }
640
237
  }
641
238
  function publishClaim(parent, claimDir, owner, payload) {
642
- const temporary = join2(parent, `.${basename2(claimDir)}.${randomUUID2()}.tmp`);
239
+ const temporary = join(parent, `.${basename(claimDir)}.${randomUUID()}.tmp`);
643
240
  fs.mkdirSync(temporary, 448);
644
- const temporaryOwner = join2(temporary, owner);
241
+ const temporaryOwner = join(temporary, owner);
645
242
  let fd;
646
243
  try {
647
244
  fd = fs.openSync(temporaryOwner, "wx", 384);
@@ -690,15 +287,15 @@ function acquireProcessLock(path, options = {}) {
690
287
  const verifyMessage = `Unable to verify ${name}`;
691
288
  const occupiedMessage = options.occupiedMessage ?? `${name[0].toUpperCase()}${name.slice(1)} is in progress`;
692
289
  const recoverMessage = `Unable to recover ${name}`;
693
- const parent = dirname2(path);
290
+ const parent = dirname(path);
694
291
  fs.mkdirSync(parent, { recursive: true, mode: 448 });
695
292
  fs.chmodSync(parent, 448);
696
293
  const claimDir = path;
697
- const claim = { pid: process.pid, id: randomUUID2() };
294
+ const claim = { pid: process.pid, id: randomUUID() };
698
295
  const lockOwner = process.platform === "linux" ? { ...claim, linuxBirth: readLinuxBirth(process.pid) } : claim;
699
296
  const owner = `${claim.pid}-${claim.id}`;
700
297
  const payload = JSON.stringify(lockOwner);
701
- const ownerPath = join2(claimDir, owner);
298
+ const ownerPath = join(claimDir, owner);
702
299
  try {
703
300
  lockOwnerEntry(claimDir);
704
301
  } catch (error2) {
@@ -750,9 +347,9 @@ function acquireProcessLock(path, options = {}) {
750
347
  if (error3 instanceof ProcessLockOccupiedError) throw error3;
751
348
  throw new Error(verifyMessage, { cause: error3 });
752
349
  }
753
- const quarantine = join2(
350
+ const quarantine = join(
754
351
  parent,
755
- `.${basename2(claimDir)}.${randomUUID2()}.stale`
352
+ `.${basename(claimDir)}.${randomUUID()}.stale`
756
353
  );
757
354
  try {
758
355
  const { owner: currentOwner } = lockOwnerEntry(claimDir);
@@ -793,7 +390,7 @@ function acquireProcessLock(path, options = {}) {
793
390
  options.afterStaleOwnerRemoved?.();
794
391
  try {
795
392
  unlinkMetadata(quarantine, metadata);
796
- fs.unlinkSync(join2(quarantine, observedOwner));
393
+ fs.unlinkSync(join(quarantine, observedOwner));
797
394
  fs.rmdirSync(quarantine);
798
395
  } catch (cleanupError) {
799
396
  throw new Error(recoverMessage, { cause: cleanupError });
@@ -828,7 +425,7 @@ function releaseProcessLock(claimDir, ownerPath, claim, name) {
828
425
  }
829
426
  throw new Error(`Unable to verify ${name} ownership`, { cause: error2 });
830
427
  }
831
- if (owner !== basename2(ownerPath)) {
428
+ if (owner !== basename(ownerPath)) {
832
429
  try {
833
430
  if (ownerMissing(ownerPath)) return;
834
431
  } catch (error2) {
@@ -840,7 +437,7 @@ function releaseProcessLock(claimDir, ownerPath, claim, name) {
840
437
  }
841
438
  let current;
842
439
  try {
843
- current = readProcessLockOwner(claimDir, basename2(ownerPath));
440
+ current = readProcessLockOwner(claimDir, basename(ownerPath));
844
441
  } catch (error2) {
845
442
  if (error2.code === "ENOENT" && ownerMissing(ownerPath))
846
443
  return;
@@ -850,16 +447,16 @@ function releaseProcessLock(claimDir, ownerPath, claim, name) {
850
447
  throw new Error(
851
448
  `${name[0].toUpperCase()}${name.slice(1)} ownership changed`
852
449
  );
853
- const retired = join2(
854
- dirname2(claimDir),
855
- `.${basename2(claimDir)}.${randomUUID2()}.released`
450
+ const retired = join(
451
+ dirname(claimDir),
452
+ `.${basename(claimDir)}.${randomUUID()}.released`
856
453
  );
857
454
  fs.renameSync(claimDir, retired);
858
455
  let retiredOwner;
859
456
  let metadata;
860
457
  try {
861
458
  ({ owner: retiredOwner, metadata } = lockOwnerEntry(retired));
862
- if (retiredOwner !== basename2(ownerPath))
459
+ if (retiredOwner !== basename(ownerPath))
863
460
  throw new Error("Process lock owner changed");
864
461
  const relocated = readProcessLockOwner(retired, retiredOwner);
865
462
  if (relocated.pid !== claim.pid || relocated.id !== claim.id)
@@ -868,7 +465,7 @@ function releaseProcessLock(claimDir, ownerPath, claim, name) {
868
465
  throw new Error(`Unable to verify ${name} ownership`, { cause: error2 });
869
466
  }
870
467
  unlinkMetadata(retired, metadata);
871
- fs.unlinkSync(join2(retired, retiredOwner));
468
+ fs.unlinkSync(join(retired, retiredOwner));
872
469
  try {
873
470
  fs.rmdirSync(retired);
874
471
  } catch (error2) {
@@ -879,7 +476,7 @@ function releaseProcessLock(claimDir, ownerPath, claim, name) {
879
476
  function unlinkMetadata(path, entries) {
880
477
  for (const entry of entries) {
881
478
  try {
882
- fs.unlinkSync(join2(path, entry));
479
+ fs.unlinkSync(join(path, entry));
883
480
  } catch (error2) {
884
481
  if (error2.code !== "ENOENT") throw error2;
885
482
  }
@@ -896,6 +493,491 @@ var init_lock = __esm({
896
493
  }
897
494
  });
898
495
 
496
+ // extension/storage.ts
497
+ import { homedir, tmpdir } from "node:os";
498
+ import {
499
+ chmodSync as chmodSync2,
500
+ closeSync as closeSync2,
501
+ constants,
502
+ fstatSync,
503
+ fsyncSync as fsyncSync2,
504
+ mkdirSync as mkdirSync2,
505
+ openSync as openSync2,
506
+ readdirSync as readdirSync2,
507
+ readFileSync as readFileSync3,
508
+ renameSync as renameSync2,
509
+ lstatSync as lstatSync2,
510
+ unlinkSync as unlinkSync2,
511
+ writeFileSync
512
+ } from "node:fs";
513
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
514
+ import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
515
+ import { fileURLToPath } from "node:url";
516
+ function isIncidentalMetadata(entry) {
517
+ return entry.isFile() && INCIDENTAL_METADATA.has(entry.name.toLowerCase());
518
+ }
519
+ function isRequiredEvidence(value2) {
520
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return false;
521
+ const r = value2;
522
+ if (typeof r.id !== "string" || !EVIDENCE_ID.test(r.id) || typeof r.name !== "string" || !r.name || r.name.length > 255)
523
+ return false;
524
+ if (Object.hasOwn(r, "result"))
525
+ return Object.keys(r).length === 3 && isResultBinding(r.result);
526
+ const keys = Object.keys(r).sort();
527
+ const legacyKeys = ["id", "name", "path", "sha256", "sourceAssignmentId"];
528
+ const semanticKeys = [...legacyKeys, "ref"].sort();
529
+ return (keys.join("\0") === legacyKeys.join("\0") || keys.join("\0") === semanticKeys.join("\0")) && (!Object.hasOwn(r, "ref") || isCanonicalSemanticEvidenceRef(r.ref)) && typeof r.sourceAssignmentId === "string" && EVIDENCE_ID.test(r.sourceAssignmentId) && typeof r.path === "string" && r.path.length > 0 && typeof r.sha256 === "string" && /^[a-f0-9]{64}$/.test(r.sha256);
530
+ }
531
+ function isCanonicalSemanticEvidenceRef(value2) {
532
+ if (typeof value2 !== "string") return false;
533
+ const match = SEMANTIC_EVIDENCE_REF.exec(value2);
534
+ return !!match && Number.isSafeInteger(Number(match[2]));
535
+ }
536
+ function semanticEvidenceRef(evidence) {
537
+ if ("result" in evidence) return evidence.result.ref;
538
+ if (!evidence.ref)
539
+ throw new Error("required evidence has no semantic reference");
540
+ return evidence.ref;
541
+ }
542
+ function upgradeRequiredEvidence(value2) {
543
+ if (!isRequiredEvidence(value2)) throw new Error("invalid required evidence");
544
+ if ("result" in value2 || value2.ref) return value2;
545
+ const ref = reserveSemanticEvidenceRef(value2.id, value2.name);
546
+ return { ...value2, ref };
547
+ }
548
+ function verifySemanticEvidenceReservation(evidenceId, ref) {
549
+ if (!EVIDENCE_ID.test(evidenceId) || !isCanonicalSemanticEvidenceRef(ref))
550
+ throw new Error("invalid semantic evidence reservation");
551
+ const match = SEMANTIC_EVIDENCE_REF.exec(ref);
552
+ const root2 = join2(herdsmanDataRoot(), "evidence-ref-reservations");
553
+ const paths = [
554
+ join2(root2, "by-id", evidenceId),
555
+ join2(root2, "refs", match[1], match[2])
556
+ ];
557
+ const contents = paths.map((path) => {
558
+ const stat = lstatSync2(path);
559
+ if (!stat.isFile() || stat.isSymbolicLink())
560
+ throw new Error("invalid semantic evidence reservation");
561
+ return readFileSync3(path, "utf8");
562
+ });
563
+ const [byId, byRef] = contents;
564
+ if (byId !== `${ref}
565
+ ` || byRef !== `${evidenceId}
566
+ `)
567
+ throw new Error("invalid semantic evidence reservation");
568
+ }
569
+ function upgradeAndVerifyRequiredEvidence(value2) {
570
+ const evidence = upgradeRequiredEvidence(value2);
571
+ if (!("result" in evidence))
572
+ verifySemanticEvidenceReservation(evidence.id, evidence.ref);
573
+ return evidence;
574
+ }
575
+ function requiredEvidenceDirectory(assignmentId) {
576
+ if (!EVIDENCE_ID.test(assignmentId))
577
+ throw new Error("invalid evidence assignment id");
578
+ return join2(herdsmanDataRoot(), "evidence", assignmentId);
579
+ }
580
+ function assertEvidenceDirectory(assignmentId, create) {
581
+ const directory2 = requiredEvidenceDirectory(assignmentId);
582
+ const paths = [
583
+ herdsmanDataRoot(),
584
+ join2(herdsmanDataRoot(), "evidence"),
585
+ directory2
586
+ ];
587
+ for (const path of paths) {
588
+ if (create) {
589
+ try {
590
+ mkdirSync2(path, { mode: 448 });
591
+ } catch (error2) {
592
+ if (error2.code !== "EEXIST") throw error2;
593
+ }
594
+ }
595
+ const stat = lstatSync2(path);
596
+ if (!stat.isDirectory() || stat.isSymbolicLink())
597
+ throw new Error("required evidence directory is unsafe");
598
+ }
599
+ return directory2;
600
+ }
601
+ function safeEvidenceName(name) {
602
+ const base = basename2(name).replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 100);
603
+ return base || "evidence.txt";
604
+ }
605
+ function persistRequiredEvidenceSnapshot(assignmentId, name, text) {
606
+ const bytes = Buffer.from(text, "utf8");
607
+ if (bytes.length > EVIDENCE_SNAPSHOT_MAX_BYTES || bytes.includes(0) || new TextDecoder("utf-8", { fatal: true }).decode(bytes) !== text)
608
+ throw new Error(
609
+ "Required evidence must be supported UTF-8 text no larger than 1 MiB"
610
+ );
611
+ const directory2 = assertEvidenceDirectory(assignmentId, true);
612
+ chmodSync2(directory2, 448);
613
+ const id = randomUUID2();
614
+ const path = join2(directory2, `${id}-${safeEvidenceName(name)}`);
615
+ const temporary = `${path}.${randomUUID2()}.tmp`;
616
+ let fd;
617
+ try {
618
+ fd = openSync2(temporary, "wx", 384);
619
+ writeFileSync(fd, bytes);
620
+ fsyncSync2(fd);
621
+ closeSync2(fd);
622
+ fd = void 0;
623
+ assertEvidenceDirectory(assignmentId, false);
624
+ renameSync2(temporary, path);
625
+ chmodSync2(path, 384);
626
+ if (process.platform !== "win32") {
627
+ const dirFd = openSync2(directory2, "r");
628
+ try {
629
+ fsyncSync2(dirFd);
630
+ } finally {
631
+ closeSync2(dirFd);
632
+ }
633
+ }
634
+ return {
635
+ id,
636
+ ref: reserveSemanticEvidenceRef(id, name),
637
+ name: safeEvidenceName(name),
638
+ sourceAssignmentId: assignmentId,
639
+ path,
640
+ sha256: createHash3("sha256").update(bytes).digest("hex")
641
+ };
642
+ } finally {
643
+ if (fd !== void 0) closeSync2(fd);
644
+ try {
645
+ unlinkSync2(temporary);
646
+ } catch (error2) {
647
+ if (error2.code !== "ENOENT") throw error2;
648
+ }
649
+ }
650
+ }
651
+ function reserveSemanticEvidenceRef(evidenceId, name) {
652
+ if (!EVIDENCE_ID.test(evidenceId)) throw new Error("invalid evidence id");
653
+ const root2 = join2(herdsmanDataRoot(), "evidence-ref-reservations");
654
+ const byId = join2(root2, "by-id");
655
+ mkdirSync2(byId, { recursive: true, mode: 448 });
656
+ chmodSync2(byId, 448);
657
+ const mapping = join2(byId, evidenceId);
658
+ try {
659
+ const existing = readFileSync3(mapping, "utf8").trim();
660
+ if (isCanonicalSemanticEvidenceRef(existing)) return existing;
661
+ throw new Error("invalid semantic evidence reservation");
662
+ } catch (error2) {
663
+ if (error2.code !== "ENOENT") throw error2;
664
+ }
665
+ const label = safeEvidenceName(name).replace(/\.[^.]*$/, "").toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").slice(0, 32) || "evidence";
666
+ const directory2 = join2(root2, "refs", label);
667
+ mkdirSync2(directory2, { recursive: true, mode: 448 });
668
+ chmodSync2(directory2, 448);
669
+ let index = 1;
670
+ for (const entry of readdirSync2(directory2)) {
671
+ if (/^[1-9][0-9]*$/.test(entry)) index = Math.max(index, Number(entry) + 1);
672
+ }
673
+ for (; ; ) {
674
+ if (!Number.isSafeInteger(index))
675
+ throw new Error("Semantic evidence index exhausted");
676
+ const ref = `evidence:${label}#${index}`;
677
+ try {
678
+ writeFileSync(join2(directory2, String(index)), `${evidenceId}
679
+ `, {
680
+ encoding: "utf8",
681
+ flag: "wx",
682
+ mode: 384,
683
+ flush: true
684
+ });
685
+ try {
686
+ writeFileSync(mapping, `${ref}
687
+ `, {
688
+ encoding: "utf8",
689
+ flag: "wx",
690
+ mode: 384,
691
+ flush: true
692
+ });
693
+ } catch (error2) {
694
+ if (error2.code !== "EEXIST") throw error2;
695
+ return reserveSemanticEvidenceRef(evidenceId, name);
696
+ }
697
+ return ref;
698
+ } catch (error2) {
699
+ if (error2.code === "EEXIST") {
700
+ index++;
701
+ continue;
702
+ }
703
+ throw error2;
704
+ }
705
+ }
706
+ }
707
+ function readRequiredEvidenceSnapshot(assignmentId, evidence) {
708
+ if (!isRequiredEvidence(evidence) || "result" in evidence)
709
+ throw new Error("invalid required evidence snapshot");
710
+ if (evidence.sourceAssignmentId !== assignmentId)
711
+ throw new Error("required evidence source assignment mismatch");
712
+ const directory2 = requiredEvidenceDirectory(evidence.sourceAssignmentId);
713
+ if (evidence.path !== join2(directory2, `${evidence.id}-${safeEvidenceName(evidence.name)}`))
714
+ throw new Error("required evidence path mismatch");
715
+ assertEvidenceDirectory(evidence.sourceAssignmentId, false);
716
+ const before = lstatSync2(evidence.path);
717
+ if (!before.isFile() || before.isSymbolicLink() || before.size > EVIDENCE_SNAPSHOT_MAX_BYTES)
718
+ throw new Error(
719
+ "required evidence snapshot is missing, unsafe, or oversized"
720
+ );
721
+ const fd = openSync2(
722
+ evidence.path,
723
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
724
+ );
725
+ try {
726
+ const opened = fstatSync(fd);
727
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino)
728
+ throw new Error("required evidence snapshot changed during read");
729
+ const bytes = readFileSync3(fd);
730
+ if (bytes.length > EVIDENCE_SNAPSHOT_MAX_BYTES || createHash3("sha256").update(bytes).digest("hex") !== evidence.sha256)
731
+ throw new Error("required evidence snapshot integrity check failed");
732
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
733
+ } finally {
734
+ closeSync2(fd);
735
+ }
736
+ }
737
+ function parseSemanticResultRef(input) {
738
+ const match = SEMANTIC_RESULT_REF.exec(input);
739
+ if (!match) return void 0;
740
+ const index = Number(match[2]);
741
+ if (!Number.isSafeInteger(index)) return void 0;
742
+ return { agent: match[1], index };
743
+ }
744
+ function isCanonicalResultRef(value2) {
745
+ return typeof value2 === "string" && value2.startsWith(RESULT_PREFIX) && RESULT_ID.test(value2.slice(RESULT_PREFIX.length));
746
+ }
747
+ function isResultBinding(value2) {
748
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return false;
749
+ const record = value2;
750
+ return Object.keys(record).length === 2 && typeof record.ref === "string" && !!parseSemanticResultRef(record.ref) && isCanonicalResultRef(record.canonicalRef);
751
+ }
752
+ function herdsmanDataRoot() {
753
+ return join2(nodeOnlyAgentDir(), "pi-herdsman");
754
+ }
755
+ function nodeOnlyAgentDir() {
756
+ let directory2 = process.env.PI_CODING_AGENT_DIR;
757
+ if (!directory2) return join2(homedir(), ".pi", "agent");
758
+ if (process.platform === "win32" && directory2.startsWith("/") && !directory2.startsWith("//") && !directory2.includes("\\")) {
759
+ const match = directory2.match(
760
+ /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i
761
+ );
762
+ if (match)
763
+ directory2 = `${match[1].toUpperCase()}:\\${(match[2] ?? "").replaceAll("/", "\\")}`;
764
+ }
765
+ if (directory2 === "~") return homedir();
766
+ if (directory2.startsWith("~/") || process.platform === "win32" && directory2.startsWith("~\\"))
767
+ return join2(homedir(), directory2.slice(2));
768
+ if (/^file:\/\//.test(directory2)) return fileURLToPath(directory2);
769
+ return directory2;
770
+ }
771
+ function herdsmanConfigPath() {
772
+ return join2(herdsmanDataRoot(), "config.json");
773
+ }
774
+ function herdsmanTempRoot() {
775
+ return join2(tmpdir(), `pi-herdsman-${process.getuid?.() ?? "user"}`);
776
+ }
777
+ function validateResultId(requestId) {
778
+ if (!RESULT_ID.test(requestId)) throw new Error("invalid result request id");
779
+ }
780
+ function resultPath(requestId) {
781
+ validateResultId(requestId);
782
+ return join2(herdsmanDataRoot(), "results", requestId);
783
+ }
784
+ function peerAttachmentPath(name, text) {
785
+ if (typeof name !== "string" || !name || name.length > 255 || /[\\/\0]/u.test(name) || typeof text !== "string")
786
+ throw new Error("invalid peer attachment");
787
+ const bytes = Buffer.from(text, "utf8");
788
+ if (new TextDecoder("utf-8", { fatal: true }).decode(bytes) !== text)
789
+ throw new Error("invalid peer attachment text");
790
+ const directory2 = join2(
791
+ herdsmanDataRoot(),
792
+ "runtime",
793
+ "peers-v2",
794
+ "received-evidence"
795
+ );
796
+ const digest = createHash3("sha256").update(bytes).digest("hex");
797
+ return join2(directory2, `${digest}-${name}`);
798
+ }
799
+ function persistPeerAttachment(name, text) {
800
+ const path = peerAttachmentPath(name, text);
801
+ const bytes = Buffer.from(text, "utf8");
802
+ mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
803
+ chmodSync2(dirname2(path), 448);
804
+ try {
805
+ writeFileSync(path, bytes, { flag: "wx", mode: 384, flush: true });
806
+ } catch (error2) {
807
+ if (error2.code !== "EEXIST") throw error2;
808
+ if (!readFileSync3(path).equals(bytes))
809
+ throw new Error("peer attachment content identity collision");
810
+ }
811
+ return path;
812
+ }
813
+ function persistPeerResultArtifact(canonicalRef, text) {
814
+ if (!isCanonicalResultRef(canonicalRef) || typeof text !== "string")
815
+ throw new Error("invalid peer result artifact");
816
+ const path = resultPath(canonicalRef.slice(RESULT_PREFIX.length));
817
+ mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
818
+ chmodSync2(dirname2(path), 448);
819
+ const bytes = Buffer.from(text, "utf8");
820
+ try {
821
+ writeFileSync(path, bytes, { flag: "wx", mode: 384, flush: true });
822
+ } catch (error2) {
823
+ if (error2.code !== "EEXIST") throw error2;
824
+ if (!readFileSync3(path).equals(bytes))
825
+ throw new Error("peer result identity collision");
826
+ }
827
+ return path;
828
+ }
829
+ function resultRef(requestId) {
830
+ validateResultId(requestId);
831
+ return `${RESULT_PREFIX}${requestId}`;
832
+ }
833
+ function publishScopedResult(agentLabel, minimumIndex, canonicalRef, rootSessionId) {
834
+ if (!parseSemanticResultRef(`result:${agentLabel}#${minimumIndex}`) || !isCanonicalResultRef(canonicalRef) || typeof rootSessionId !== "string" || !rootSessionId.trim() || rootSessionId.length > 512)
835
+ throw new Error("Invalid scoped result identity");
836
+ const artifact = resolveResultRef(canonicalRef);
837
+ if (!artifact) throw new Error("Invalid scoped result artifact");
838
+ const stat = lstatSync2(artifact);
839
+ if (!stat.isFile() || stat.isSymbolicLink())
840
+ throw new Error("Invalid scoped result artifact");
841
+ const dataRoot = herdsmanDataRoot();
842
+ const reservationRoot = join2(dataRoot, "result-ref-reservations");
843
+ const directory2 = join2(reservationRoot, agentLabel);
844
+ mkdirSync2(directory2, { recursive: true, mode: 448 });
845
+ if (process.platform !== "win32") {
846
+ const dataParentFd = openSync2(dirname2(dataRoot), "r");
847
+ try {
848
+ fsyncSync2(dataParentFd);
849
+ } finally {
850
+ closeSync2(dataParentFd);
851
+ }
852
+ const dataRootFd = openSync2(dataRoot, "r");
853
+ try {
854
+ fsyncSync2(dataRootFd);
855
+ } finally {
856
+ closeSync2(dataRootFd);
857
+ }
858
+ const reservationRootFd = openSync2(reservationRoot, "r");
859
+ try {
860
+ fsyncSync2(reservationRootFd);
861
+ } finally {
862
+ closeSync2(reservationRootFd);
863
+ }
864
+ }
865
+ const lease = acquireProcessLock(
866
+ join2(dataRoot, "locks", "scoped-result-publication"),
867
+ { name: "scoped result publication" }
868
+ );
869
+ try {
870
+ let index = minimumIndex;
871
+ for (const name of readdirSync2(directory2)) {
872
+ if (!/^[1-9][0-9]*$/.test(name)) continue;
873
+ const reserved = Number(name);
874
+ if (Number.isSafeInteger(reserved)) index = Math.max(index, reserved + 1);
875
+ const path = join2(directory2, name);
876
+ let record;
877
+ try {
878
+ record = JSON.parse(readFileSync3(path, "utf8"));
879
+ } catch {
880
+ continue;
881
+ }
882
+ if (record && typeof record === "object" && !Array.isArray(record)) {
883
+ const metadata = record;
884
+ if (Object.keys(metadata).length === 3 && metadata.version === 1 && isCanonicalResultRef(metadata.canonicalRef) && typeof metadata.rootSessionId === "string" && metadata.rootSessionId.trim() && metadata.canonicalRef === canonicalRef) {
885
+ if (metadata.rootSessionId !== rootSessionId)
886
+ throw new Error("Conflicting scoped result ownership");
887
+ return {
888
+ ref: `result:${agentLabel}#${Number(name)}`,
889
+ index: Number(name)
890
+ };
891
+ }
892
+ }
893
+ }
894
+ for (; ; ) {
895
+ if (!Number.isSafeInteger(index))
896
+ throw new Error("Semantic result index exhausted");
897
+ const path = join2(directory2, String(index));
898
+ try {
899
+ writeFileSync(
900
+ path,
901
+ `${JSON.stringify({ version: 1, canonicalRef, rootSessionId })}
902
+ `,
903
+ { encoding: "utf8", flag: "wx", mode: 384, flush: true }
904
+ );
905
+ if (process.platform !== "win32") {
906
+ const fd = openSync2(directory2, "r");
907
+ try {
908
+ fsyncSync2(fd);
909
+ } finally {
910
+ closeSync2(fd);
911
+ }
912
+ }
913
+ return { ref: `result:${agentLabel}#${index}`, index };
914
+ } catch (error2) {
915
+ if (error2.code !== "EEXIST") throw error2;
916
+ index++;
917
+ }
918
+ }
919
+ } finally {
920
+ lease.release();
921
+ }
922
+ }
923
+ function resolveScopedResult(ref) {
924
+ const semantic = parseSemanticResultRef(ref);
925
+ if (!semantic) return void 0;
926
+ const path = join2(
927
+ herdsmanDataRoot(),
928
+ "result-ref-reservations",
929
+ semantic.agent,
930
+ String(semantic.index)
931
+ );
932
+ let stat;
933
+ try {
934
+ stat = lstatSync2(path);
935
+ } catch (error2) {
936
+ return error2.code === "ENOENT" ? void 0 : "invalid";
937
+ }
938
+ try {
939
+ if (!stat.isFile() || stat.isSymbolicLink()) return "invalid";
940
+ const contents = readFileSync3(path, "utf8");
941
+ if (contents === "reserved\n") return "reserved";
942
+ const value2 = JSON.parse(contents);
943
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2))
944
+ return "invalid";
945
+ const record = value2;
946
+ if (Object.keys(record).length !== 3 || record.version !== 1 || !isCanonicalResultRef(record.canonicalRef) || typeof record.rootSessionId !== "string" || !record.rootSessionId.trim() || record.rootSessionId.length > 512)
947
+ return "invalid";
948
+ const artifact = resolveResultRef(record.canonicalRef);
949
+ if (!artifact) return "invalid";
950
+ const artifactStat = lstatSync2(artifact);
951
+ if (!artifactStat.isFile() || artifactStat.isSymbolicLink())
952
+ return "invalid";
953
+ return record;
954
+ } catch {
955
+ return "invalid";
956
+ }
957
+ }
958
+ function resolveResultRef(input) {
959
+ if (!input.startsWith(RESULT_PREFIX)) return void 0;
960
+ return resultPath(input.slice(RESULT_PREFIX.length));
961
+ }
962
+ var RESULT_PREFIX, RESULT_ID, SEMANTIC_RESULT_REF, SEMANTIC_EVIDENCE_REF, INCIDENTAL_METADATA, EVIDENCE_ID, EVIDENCE_SNAPSHOT_MAX_BYTES;
963
+ var init_storage = __esm({
964
+ "extension/storage.ts"() {
965
+ init_lock();
966
+ RESULT_PREFIX = "result:";
967
+ RESULT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
968
+ SEMANTIC_RESULT_REF = /^result:([a-z][a-z0-9_-]{0,31})#([1-9][0-9]*)$/;
969
+ SEMANTIC_EVIDENCE_REF = /^evidence:([a-z][a-z0-9_-]{0,31})#([1-9][0-9]*)$/;
970
+ INCIDENTAL_METADATA = /* @__PURE__ */ new Set([
971
+ ".ds_store",
972
+ "desktop.ini",
973
+ "thumbs.db",
974
+ ".directory"
975
+ ]);
976
+ EVIDENCE_ID = RESULT_ID;
977
+ EVIDENCE_SNAPSHOT_MAX_BYTES = 1024 * 1024;
978
+ }
979
+ });
980
+
899
981
  // extension/mailbox.ts
900
982
  import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
901
983
  import {
@@ -1088,6 +1170,7 @@ function validate(value2, kind) {
1088
1170
  "agentLabel",
1089
1171
  "paneId",
1090
1172
  "piSessionId",
1173
+ "rootSessionId",
1091
1174
  "piSessionFile",
1092
1175
  "agentDefinition",
1093
1176
  "cwd",
@@ -1141,6 +1224,7 @@ function validate(value2, kind) {
1141
1224
  "workspaceId",
1142
1225
  "agentLabel",
1143
1226
  "paneId",
1227
+ "rootSessionId",
1144
1228
  "status",
1145
1229
  "text",
1146
1230
  "error",
@@ -1188,6 +1272,8 @@ function validate(value2, kind) {
1188
1272
  };
1189
1273
  if (kind === "state") {
1190
1274
  finite("updatedAt");
1275
+ if (v.rootSessionId !== void 0 && (typeof v.rootSessionId !== "string" || !v.rootSessionId.trim() || v.rootSessionId.length > 512))
1276
+ throw new Error("Invalid mailbox root session identity");
1191
1277
  if (v.lastActivityAt !== void 0 && (typeof v.lastActivityAt !== "number" || !Number.isInteger(v.lastActivityAt) || !Number.isFinite(v.lastActivityAt) || v.lastActivityAt < 0))
1192
1278
  throw new Error("Invalid mailbox timestamp: lastActivityAt");
1193
1279
  for (const field of ["activeRequestId", "completedRequestId"])
@@ -1304,6 +1390,8 @@ function validate(value2, kind) {
1304
1390
  throw new Error("Invalid ask result bindings");
1305
1391
  finite("createdAt");
1306
1392
  } else {
1393
+ if (v.rootSessionId !== void 0 && (typeof v.rootSessionId !== "string" || !v.rootSessionId.trim() || v.rootSessionId.length > 512))
1394
+ throw new Error("Invalid mailbox root session identity");
1307
1395
  if (v.status !== "completed" && v.status !== "failed")
1308
1396
  throw new Error("Invalid result status");
1309
1397
  finite("completedAt");
@@ -3069,13 +3157,27 @@ function sameDirectory(left, right) {
3069
3157
  return false;
3070
3158
  }
3071
3159
  }
3072
- async function localRepositoryScope(pi, ctx, workspaceId, signal) {
3073
- const listed = await runHerdr(
3074
- pi,
3075
- ctx,
3076
- ["worktree", "list", "--cwd", ctx.cwd],
3077
- { signal }
3160
+ function resolveAssignmentCheckout(assignment, worktrees, sessionCwd) {
3161
+ const recorded = assignment.checkoutPath;
3162
+ if (recorded && sessionCwd && !sameDirectory(recorded, sessionCwd))
3163
+ return { status: "conflict", reason: "checkout provenance disagrees" };
3164
+ const path = recorded ?? sessionCwd;
3165
+ if (!path)
3166
+ return { status: "unknown", reason: "checkout provenance unavailable" };
3167
+ const matches = worktrees.filter(
3168
+ (item) => item.is_linked_worktree === true && typeof item.path === "string" && sameDirectory(item.path, path)
3078
3169
  );
3170
+ if (matches.length !== 1)
3171
+ return {
3172
+ status: matches.length ? "conflict" : "unknown",
3173
+ reason: "assigned checkout placement is not uniquely verified"
3174
+ };
3175
+ return { status: "matched", worktree: matches[0], path };
3176
+ }
3177
+ async function localRepositoryScope(pi, ctx, workspaceId, signal, knownTopology) {
3178
+ const listed = knownTopology ?? await runHerdr(pi, ctx, ["worktree", "list", "--cwd", ctx.cwd], {
3179
+ signal
3180
+ });
3079
3181
  const workspace2 = (await runHerdr(pi, ctx, ["workspace", "get", workspaceId], { signal }))?.workspace;
3080
3182
  const source = listed?.source;
3081
3183
  if (workspace2?.workspace_id !== workspaceId || typeof source?.repo_key !== "string" || !isAbsolute2(source.repo_key) || typeof source?.repo_name !== "string" || !source.repo_name || !Array.isArray(listed?.worktrees))
@@ -3122,6 +3224,9 @@ async function worktreeGroupScope(pi, ctx, workspaceId, signal, timeout) {
3122
3224
  ["worktree", "list", "--workspace", workspaceId],
3123
3225
  { signal, timeout }
3124
3226
  );
3227
+ return worktreeGroupScopeFromTopology(workspaceId, listed);
3228
+ }
3229
+ function worktreeGroupScopeFromTopology(workspaceId, listed) {
3125
3230
  const source = listed?.source;
3126
3231
  const worktrees = listed?.worktrees;
3127
3232
  if (typeof source?.repo_key !== "string" || !source.repo_key || typeof source?.repo_name !== "string" || !source.repo_name || typeof source?.source_workspace_id !== "string" || !source.source_workspace_id || !Array.isArray(worktrees)) {
@@ -12082,9 +12187,8 @@ function projectTaskSummary(text) {
12082
12187
  }
12083
12188
  function projectWorkSnapshot(options) {
12084
12189
  return options.assignments.map((assignment) => {
12085
- const worktrees = options.worktrees.filter(
12086
- (item) => item.branch === assignment.branch
12087
- );
12190
+ const placement = options.placements?.get(assignment.id);
12191
+ const worktrees = placement ? placement.status === "matched" && placement.worktree ? [placement.worktree] : [] : options.worktrees.filter((item) => item.branch === assignment.branch);
12088
12192
  const exact = options.leads.filter((lead) => lead.lead === assignment.id);
12089
12193
  const uncertain = options.unverified?.filter((lead) => lead.lead === assignment.id) ?? [];
12090
12194
  let status;
@@ -12093,6 +12197,9 @@ function projectWorkSnapshot(options) {
12093
12197
  if (worktrees.length > 1 || exact.length > 1 || uncertain.length > 1 || exact.length > 0 && uncertain.length > 0) {
12094
12198
  status = "conflict";
12095
12199
  issue = "project runtime identity is ambiguous";
12200
+ } else if (placement && placement.status !== "matched") {
12201
+ status = placement.status;
12202
+ issue = placement.status === "conflict" ? "assigned checkout placement conflicts" : "assigned checkout placement is unavailable";
12096
12203
  } else if (uncertain.length === 1) {
12097
12204
  status = uncertain[0].status;
12098
12205
  issue = uncertain[0].issue;
@@ -12701,18 +12808,57 @@ function resolveMessageFiles(ctx, files, operation, acceptedEvidence = []) {
12701
12808
  `Result ref ${file2} is ambiguous in the accepted evidence scope`,
12702
12809
  operation
12703
12810
  );
12704
- if (acceptedResults.length === 1) return acceptedResults[0].result;
12705
12811
  if (!parseSemanticResultRef(file2))
12706
12812
  fail(
12707
12813
  "invalid_request",
12708
12814
  `Invalid result ref: ${file2}. Copy the exact result ref shown by the agent completion.`,
12709
12815
  operation
12710
12816
  );
12711
- const refs = canonicalRefsForSemanticResult(
12712
- ctx.sessionManager.getBranch(),
12817
+ const requesterSessionId = ctx.sessionManager.getSessionId();
12818
+ const branch = ctx.sessionManager.getBranch();
12819
+ const refs = verifiedBranchResultMappings(
12820
+ branch,
12713
12821
  file2,
12822
+ requesterSessionId,
12714
12823
  operation
12715
12824
  );
12825
+ const branchMappings = canonicalRefsForSemanticResult(
12826
+ branch,
12827
+ file2,
12828
+ operation
12829
+ );
12830
+ if (branchMappings.size > 1)
12831
+ fail(
12832
+ "target_ambiguous",
12833
+ `Result ref ${file2} resolves to conflicting canonical results`,
12834
+ operation
12835
+ );
12836
+ for (const accepted of acceptedResults)
12837
+ refs.add(accepted.result.canonicalRef);
12838
+ const published = resolveScopedResult(file2);
12839
+ if (published === "invalid")
12840
+ fail(
12841
+ "target_ambiguous",
12842
+ `Result ref ${file2} has an invalid publication`,
12843
+ operation
12844
+ );
12845
+ if (published && published !== "reserved") {
12846
+ const rootSessionId = process.env.PI_HERDSMAN_ROOT_SESSION_ID || requesterSessionId;
12847
+ if (published.rootSessionId === rootSessionId || acceptedResults.length)
12848
+ refs.add(published.canonicalRef);
12849
+ }
12850
+ if (refs.size && [...branchMappings].some((canonicalRef) => !refs.has(canonicalRef)))
12851
+ fail(
12852
+ "target_ambiguous",
12853
+ `Result ref ${file2} resolves to conflicting canonical results`,
12854
+ operation
12855
+ );
12856
+ if (acceptedResults.length > 1)
12857
+ fail(
12858
+ "target_ambiguous",
12859
+ `Result ref ${file2} is ambiguous in the accepted evidence scope`,
12860
+ operation
12861
+ );
12716
12862
  if (!refs.size)
12717
12863
  fail(
12718
12864
  "target_not_found",
@@ -13286,7 +13432,24 @@ function canonicalResultRef(details, operation) {
13286
13432
  function importedResultBinding2(entry) {
13287
13433
  if (!entry || typeof entry !== "object") return void 0;
13288
13434
  const record = entry;
13289
- return record.type === "custom" && record.customType === RESULT_REF_ENTRY && isResultBinding(record.data) ? record.data : void 0;
13435
+ const data = record.data;
13436
+ return record.type === "custom" && record.customType === RESULT_REF_ENTRY && !!data && isResultBinding({ ref: data.ref, canonicalRef: data.canonicalRef }) ? { ref: data.ref, canonicalRef: data.canonicalRef } : void 0;
13437
+ }
13438
+ function verifiedBranchResultMappings(entries, ref, requesterSessionId, operation) {
13439
+ const semantic = parseSemanticResultRef(ref);
13440
+ const refs = /* @__PURE__ */ new Set();
13441
+ if (!semantic || !validId(requesterSessionId)) return refs;
13442
+ for (const entry of entries) {
13443
+ const details = agentResultDetails(entry);
13444
+ if (details?.agentLabel === semantic.agent && details.resultIndex === semantic.index && details.ownerSessionId === requesterSessionId)
13445
+ refs.add(canonicalResultRef(details, operation));
13446
+ if (!entry || typeof entry !== "object") continue;
13447
+ const record = entry;
13448
+ const data = record.data;
13449
+ if (record.type === "custom" && record.customType === RESULT_REF_ENTRY && typeof data?.ref === "string" && typeof data.canonicalRef === "string" && isResultBinding({ ref: data.ref, canonicalRef: data.canonicalRef }) && data.ref === ref && data.requesterSessionId === requesterSessionId)
13450
+ refs.add(data.canonicalRef);
13451
+ }
13452
+ return refs;
13290
13453
  }
13291
13454
  function canonicalRefsForSemanticResult(entries, ref, operation) {
13292
13455
  const semantic = parseSemanticResultRef(ref);
@@ -13330,10 +13493,30 @@ function importResultBindings(pi, ctx, bindings, operation) {
13330
13493
  `Result ref ${binding.ref} conflicts with the current branch`,
13331
13494
  operation
13332
13495
  );
13333
- if (!existing.size) pending.set(binding.ref, binding.canonicalRef);
13496
+ const requesterSessionId2 = ctx.sessionManager.getSessionId();
13497
+ if (!validId(requesterSessionId2))
13498
+ fail(
13499
+ "internal_failure",
13500
+ "Requester session identity is invalid",
13501
+ operation
13502
+ );
13503
+ const authorized = verifiedBranchResultMappings(
13504
+ ctx.sessionManager.getBranch(),
13505
+ binding.ref,
13506
+ requesterSessionId2,
13507
+ operation
13508
+ );
13509
+ if (!authorized.size) pending.set(binding.ref, binding.canonicalRef);
13334
13510
  }
13511
+ const requesterSessionId = ctx.sessionManager.getSessionId();
13512
+ if (!validId(requesterSessionId))
13513
+ fail(
13514
+ "internal_failure",
13515
+ "Requester session identity is invalid",
13516
+ operation
13517
+ );
13335
13518
  for (const [ref, canonicalRef] of pending)
13336
- pi.appendEntry(RESULT_REF_ENTRY, { ref, canonicalRef });
13519
+ pi.appendEntry(RESULT_REF_ENTRY, { ref, canonicalRef, requesterSessionId });
13337
13520
  }
13338
13521
  function hasDeliveredAsk(entries, ask) {
13339
13522
  return entries.some((entry) => {
@@ -13955,7 +14138,7 @@ function validateAssignmentRequest(params) {
13955
14138
  fail("invalid_request", "continue requires session", params.action);
13956
14139
  }
13957
14140
  function runtimeIdentityMatches(runtime, state, agent) {
13958
- return runtime.runId === state.runId && runtime.ownerSessionId === state.ownerSessionId && runtime.workspaceId === agent.workspace_id && runtime.paneId === agent.pane_id && runtime.piSessionId === state.piSessionId && sameSessionPath(runtime.piSessionFile, state.piSessionFile) && sameCwd(runtime.cwd, agent.cwd);
14141
+ return runtime.runId === state.runId && runtime.ownerSessionId === state.ownerSessionId && runtime.workspaceId === agent.workspace_id && runtime.paneId === agent.pane_id && runtime.rootSessionId === state.rootSessionId && runtime.piSessionId === state.piSessionId && sameSessionPath(runtime.piSessionFile, state.piSessionFile) && sameCwd(runtime.cwd, agent.cwd);
13959
14142
  }
13960
14143
  function agentDefinitionForRuntime(agent, state, cached, allowTranscriptFallback) {
13961
14144
  if (state.agentDefinition !== void 0) return stateAgentDefinition(state);
@@ -14026,7 +14209,8 @@ function validateIdentity(runtime, state, agent, options = {}) {
14026
14209
  ["ownerSessionId", state.ownerSessionId, runtime.ownerSessionId],
14027
14210
  ["workspaceId", state.workspaceId, runtime.workspaceId],
14028
14211
  ["agentLabel", state.agentLabel, runtime.label],
14029
- ["paneId", state.paneId, runtime.paneId]
14212
+ ["paneId", state.paneId, runtime.paneId],
14213
+ ["rootSessionId", state.rootSessionId, runtime.rootSessionId]
14030
14214
  ].filter(([, expected, actual]) => expected !== actual);
14031
14215
  if (!sameCwd(state.cwd, runtime.cwd))
14032
14216
  differences.push(["cwd", state.cwd, runtime.cwd]);
@@ -14437,7 +14621,7 @@ function createAgentController(pi, options) {
14437
14621
  throw error2;
14438
14622
  }
14439
14623
  };
14440
- const sameIdentity = (left, right) => left.runId === right.runId && left.ownerSessionId === right.ownerSessionId && left.workspaceId === right.workspaceId && left.agentLabel === right.agentLabel && left.paneId === right.paneId && left.piSessionId === right.piSessionId && sameSessionPath3(left.piSessionFile, right.piSessionFile) && sameCwd(left.cwd, right.cwd);
14624
+ const sameIdentity = (left, right) => left.runId === right.runId && left.ownerSessionId === right.ownerSessionId && left.workspaceId === right.workspaceId && left.agentLabel === right.agentLabel && left.paneId === right.paneId && left.rootSessionId === right.rootSessionId && left.piSessionId === right.piSessionId && sameSessionPath3(left.piSessionFile, right.piSessionFile) && sameCwd(left.cwd, right.cwd);
14441
14625
  const persistedTranscriptReady2 = (state) => {
14442
14626
  if (!state.piSessionId || !state.piSessionFile) return false;
14443
14627
  try {
@@ -14462,6 +14646,7 @@ function createAgentController(pi, options) {
14462
14646
  agentLabel: runtime.label,
14463
14647
  paneId: runtime.paneId,
14464
14648
  piSessionId: runtime.piSessionId ?? "",
14649
+ rootSessionId: runtime.rootSessionId,
14465
14650
  piSessionFile: runtime.piSessionFile,
14466
14651
  cwd: runtime.cwd,
14467
14652
  updatedAt: 0
@@ -14794,6 +14979,7 @@ function createAgentController(pi, options) {
14794
14979
  cwd: agent.cwd,
14795
14980
  runId: state.runId,
14796
14981
  ownerSessionId: state.ownerSessionId,
14982
+ rootSessionId: state.rootSessionId,
14797
14983
  mailboxPath: agentMailboxPath(agent.workspace_id, agent.label),
14798
14984
  piSessionId: state.piSessionId,
14799
14985
  piSessionFile: state.piSessionFile,
@@ -14812,6 +14998,7 @@ function createAgentController(pi, options) {
14812
14998
  cwd: agent.cwd,
14813
14999
  runId: state.runId,
14814
15000
  ownerSessionId: state.ownerSessionId,
15001
+ rootSessionId: state.rootSessionId,
14815
15002
  mailboxPath: agentMailboxPath(agent.workspace_id, agent.label),
14816
15003
  piSessionId: state.piSessionId,
14817
15004
  piSessionFile: state.piSessionFile,
@@ -15005,6 +15192,7 @@ function createAgentController(pi, options) {
15005
15192
  workspaceId: runtime.workspaceId,
15006
15193
  agentLabel: runtime.label,
15007
15194
  paneId: runtime.paneId,
15195
+ rootSessionId: runtime.rootSessionId,
15008
15196
  piSessionId: runtime.piSessionId ?? "",
15009
15197
  piSessionFile: runtime.piSessionFile,
15010
15198
  cwd: runtime.cwd,
@@ -15086,6 +15274,7 @@ function createAgentController(pi, options) {
15086
15274
  workspaceId: runtime.workspaceId,
15087
15275
  agentLabel: runtime.label,
15088
15276
  paneId: runtime.paneId,
15277
+ rootSessionId: runtime.rootSessionId,
15089
15278
  piSessionId: runtime.piSessionId ?? "",
15090
15279
  piSessionFile: runtime.piSessionFile,
15091
15280
  cwd: runtime.cwd,
@@ -15128,6 +15317,7 @@ function createAgentController(pi, options) {
15128
15317
  workspaceId: runtime.workspaceId,
15129
15318
  agentLabel: runtime.label,
15130
15319
  paneId: runtime.paneId,
15320
+ rootSessionId: runtime.rootSessionId,
15131
15321
  piSessionId: runtime.piSessionId ?? "",
15132
15322
  piSessionFile: runtime.piSessionFile,
15133
15323
  cwd: runtime.cwd,
@@ -15154,33 +15344,7 @@ function createAgentController(pi, options) {
15154
15344
  }
15155
15345
  }
15156
15346
  };
15157
- const resolveFiles = (context, files, operation) => (files ?? []).map((file2) => {
15158
- if (!file2.startsWith("result:") || !file2.includes("#")) return file2;
15159
- if (!parseSemanticResultRef(file2))
15160
- fail(
15161
- "invalid_request",
15162
- `Invalid result ref: ${file2}. Copy the exact result ref shown by the agent completion.`,
15163
- operation
15164
- );
15165
- const refs = canonicalRefsForSemanticResult(
15166
- context.sessionManager.getBranch(),
15167
- file2,
15168
- operation
15169
- );
15170
- if (!refs.size)
15171
- fail(
15172
- "target_not_found",
15173
- `Result ref ${file2} is not available on the current branch`,
15174
- operation
15175
- );
15176
- if (refs.size !== 1)
15177
- fail(
15178
- "target_ambiguous",
15179
- `Result ref ${file2} resolves to conflicting canonical results`,
15180
- operation
15181
- );
15182
- return { ref: file2, canonicalRef: refs.values().next().value };
15183
- });
15347
+ const resolveFiles = (context, files, operation) => resolveMessageFiles(context, files, operation);
15184
15348
  const controlAction = async (context, params, signal) => {
15185
15349
  const resolved = await resolveRuntime(
15186
15350
  context,
@@ -15210,6 +15374,7 @@ function createAgentController(pi, options) {
15210
15374
  workspaceId: runtime.workspaceId,
15211
15375
  agentLabel: runtime.label,
15212
15376
  paneId: runtime.paneId,
15377
+ rootSessionId: runtime.rootSessionId,
15213
15378
  piSessionId: runtime.piSessionId,
15214
15379
  piSessionFile: runtime.piSessionFile,
15215
15380
  cwd: runtime.cwd,
@@ -15283,6 +15448,7 @@ function createAgentController(pi, options) {
15283
15448
  workspaceId: runtime.workspaceId,
15284
15449
  agentLabel: runtime.label,
15285
15450
  paneId: runtime.paneId,
15451
+ rootSessionId: runtime.rootSessionId,
15286
15452
  piSessionId: runtime.piSessionId,
15287
15453
  piSessionFile: runtime.piSessionFile,
15288
15454
  cwd: runtime.cwd,
@@ -16118,6 +16284,7 @@ function createAgentController(pi, options) {
16118
16284
  cwd: state.cwd,
16119
16285
  runId: state.runId,
16120
16286
  ownerSessionId: state.ownerSessionId,
16287
+ rootSessionId: state.rootSessionId,
16121
16288
  mailboxPath: path,
16122
16289
  piSessionId: state.piSessionId,
16123
16290
  piSessionFile: state.piSessionFile,
@@ -16247,9 +16414,12 @@ function createAgentController(pi, options) {
16247
16414
  max = Math.max(max, details.resultIndex);
16248
16415
  if (!entry || typeof entry !== "object") continue;
16249
16416
  const record = entry;
16250
- if (record.type !== "custom" || record.customType !== "pi-herdsman-result-ref" || !isResultBinding(record.data))
16417
+ const data = record.data;
16418
+ if (record.type !== "custom" || record.customType !== "pi-herdsman-result-ref" || !isResultBinding(
16419
+ data && { ref: data.ref, canonicalRef: data.canonicalRef }
16420
+ ))
16251
16421
  continue;
16252
- const semantic = parseSemanticResultRef(record.data.ref);
16422
+ const semantic = parseSemanticResultRef(data.ref);
16253
16423
  if (semantic?.agent === label) max = Math.max(max, semantic.index);
16254
16424
  }
16255
16425
  return max + 1;
@@ -16479,7 +16649,8 @@ function createAgentController(pi, options) {
16479
16649
  resultDeliveryInFlight.add(key);
16480
16650
  try {
16481
16651
  const expected = resultIdentity(runtime, result.requestId);
16482
- const identityMismatch = runtimes.get(runtime.label) !== runtime || result.runId !== runtime.runId || result.ownerSessionId !== runtime.ownerSessionId || result.workspaceId !== runtime.workspaceId || result.agentLabel !== runtime.label || result.paneId !== runtime.paneId || result.requestId !== (runtime.activeRequestId ?? runtime.completedRequestId);
16652
+ const persistedState = readAgentState(runtime.mailboxPath);
16653
+ const identityMismatch = runtimes.get(runtime.label) !== runtime || result.runId !== runtime.runId || result.ownerSessionId !== runtime.ownerSessionId || result.workspaceId !== runtime.workspaceId || result.agentLabel !== runtime.label || result.paneId !== runtime.paneId || result.rootSessionId !== runtime.rootSessionId || result.rootSessionId !== persistedState?.rootSessionId || result.requestId !== (runtime.activeRequestId ?? runtime.completedRequestId);
16483
16654
  if (identityMismatch) return;
16484
16655
  let entries = context.sessionManager.getEntries();
16485
16656
  const evidenceKey = JSON.stringify(Object.values(expected));
@@ -16509,9 +16680,13 @@ function createAgentController(pi, options) {
16509
16680
  );
16510
16681
  let semanticResult = completion.resultRef ? resultDeliverySemanticRefs.get(evidenceKey) : void 0;
16511
16682
  if (completion.resultRef && !semanticResult) {
16512
- semanticResult = reserveSemanticResultRef(
16683
+ if (!result.rootSessionId)
16684
+ throw new Error("Completed result has no verified ownership scope");
16685
+ semanticResult = publishScopedResult(
16513
16686
  result.agentLabel,
16514
- nextResultIndex(entries, result.agentLabel)
16687
+ nextResultIndex(entries, result.agentLabel),
16688
+ completion.resultRef,
16689
+ result.rootSessionId
16515
16690
  );
16516
16691
  resultDeliverySemanticRefs.set(evidenceKey, semanticResult);
16517
16692
  }
@@ -17288,6 +17463,9 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
17288
17463
  const delegationEnabled = agentDefinitionDelegationEnabled(effectiveDefinition);
17289
17464
  const runId = assignment.runId;
17290
17465
  const owner = assignment.ownerSessionId;
17466
+ const verifiedRootSessionId = scope.kind === "managed-agent" ? options.managedAgentRootSessionId?.(ctx) : ctx.sessionManager.getSessionId();
17467
+ if (!verifiedRootSessionId?.trim())
17468
+ throw new Error("Verified ownership root session is unavailable");
17291
17469
  const forwardingSession = scope.kind === "managed-agent" ? process.env.PI_SUBAGENT_PARENT_SESSION ?? owner : owner;
17292
17470
  const configuredPlacement = readConfig().spawnPlacement;
17293
17471
  const placement = await physicalPlacement(
@@ -17481,6 +17659,7 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
17481
17659
  `PI_HERDSMAN_MAILBOX=${mailbox}`,
17482
17660
  `PI_HERDSMAN_RUN_ID=${runId}`,
17483
17661
  `PI_HERDSMAN_OWNER_SESSION_ID=${owner}`,
17662
+ `PI_HERDSMAN_ROOT_SESSION_ID=${verifiedRootSessionId}`,
17484
17663
  `PI_HERDSMAN_OWNER_DISPLAY=${ownerDisplay}`,
17485
17664
  `PI_SUBAGENT_PARENT_SESSION=${forwardingSession}`,
17486
17665
  `PI_HERDSMAN_LABEL=${label}`,
@@ -17625,6 +17804,7 @@ ${result.stderr ?? ""}`.trim(),
17625
17804
  cwd: started.cwd,
17626
17805
  runId: state.runId,
17627
17806
  ownerSessionId: owner,
17807
+ rootSessionId: state.rootSessionId,
17628
17808
  mailboxPath: mailbox,
17629
17809
  piSessionId: state.piSessionId,
17630
17810
  piSessionFile: state.piSessionFile,
@@ -18021,16 +18201,25 @@ ${result.stderr ?? ""}`.trim(),
18021
18201
  execute: async (_id, params, _signal, _update, ctx) => {
18022
18202
  try {
18023
18203
  const scope = await options.projectEvidence?.(ctx);
18024
- if (!scope) throw new Error();
18025
- const { evidencePageContent: evidencePageContent2, readEvidencePage: readEvidencePage2 } = await Promise.resolve().then(() => (init_managed_agent_runtime(), managed_agent_runtime_exports));
18204
+ const {
18205
+ evidencePageContent: evidencePageContent2,
18206
+ readEvidencePage: readEvidencePage2,
18207
+ authorizedScopedResult: authorizedScopedResult2
18208
+ } = await Promise.resolve().then(() => (init_managed_agent_runtime(), managed_agent_runtime_exports));
18209
+ const accepted = scope?.assignment.requiredEvidence ?? [];
18210
+ const scoped = authorizedScopedResult2(
18211
+ params.ref,
18212
+ ctx.sessionManager.getSessionId(),
18213
+ accepted,
18214
+ ctx.sessionManager.getBranch(),
18215
+ ctx.sessionManager.getSessionId()
18216
+ );
18026
18217
  let page;
18027
- await scope.revalidate(() => {
18028
- page = readEvidencePage2(
18029
- scope.assignment.requiredEvidence,
18030
- params.ref,
18031
- params
18032
- );
18033
- });
18218
+ const read2 = () => {
18219
+ page = readEvidencePage2(accepted, params.ref, params, scoped);
18220
+ };
18221
+ if (scope) await scope.revalidate(read2);
18222
+ else read2();
18034
18223
  if (!page) throw new Error();
18035
18224
  return {
18036
18225
  content: [{ type: "text", text: evidencePageContent2(page) }],
@@ -19464,6 +19653,7 @@ __export(managed_agent_runtime_exports, {
19464
19653
  READ_EVIDENCE_MAX_BYTES: () => READ_EVIDENCE_MAX_BYTES,
19465
19654
  READ_EVIDENCE_MAX_LINES: () => READ_EVIDENCE_MAX_LINES,
19466
19655
  allowedAgentDefinitionsFromEnv: () => allowedAgentDefinitionsFromEnv,
19656
+ authorizedScopedResult: () => authorizedScopedResult,
19467
19657
  createManagedAgentAskOwnerHandler: () => createManagedAgentAskOwnerHandler,
19468
19658
  createManagedAgentEvidenceUpdater: () => createManagedAgentEvidenceUpdater,
19469
19659
  createManagedAgentExecutionState: () => createManagedAgentExecutionState,
@@ -19474,6 +19664,7 @@ __export(managed_agent_runtime_exports, {
19474
19664
  evidencePageContent: () => evidencePageContent,
19475
19665
  managedAgentEnvironmentError: () => managedAgentEnvironmentError,
19476
19666
  managedAgentEnvironmentIdentity: () => managedAgentEnvironmentIdentity,
19667
+ managedAgentIdentity: () => managedAgentIdentity,
19477
19668
  managedAgentRequiredEvidence: () => managedAgentRequiredEvidence,
19478
19669
  readEvidencePage: () => readEvidencePage,
19479
19670
  registerManagedAgentActivityHandlers: () => registerManagedAgentActivityHandlers,
@@ -19506,7 +19697,36 @@ function evidencePageContent(page) {
19506
19697
  return `${page.content}
19507
19698
  [More evidence: call read_evidence with offset=${page.nextOffset}, byteOffset=${page.nextByteOffset ?? 0}]`;
19508
19699
  }
19509
- function readEvidencePage(authorizedEvidence, ref, options = {}) {
19700
+ function authorizedScopedResult(ref, rootSessionId, accepted, branch, requesterSessionId) {
19701
+ if (!parseSemanticResultRef(ref)) return void 0;
19702
+ const branchMappings = verifiedBranchResultMappings(
19703
+ branch,
19704
+ ref,
19705
+ requesterSessionId,
19706
+ "read_evidence"
19707
+ );
19708
+ const acceptedMappings = /* @__PURE__ */ new Set();
19709
+ for (const item of accepted) {
19710
+ if (isRequiredEvidence(item) && "result" in item && item.result.ref === ref)
19711
+ acceptedMappings.add(item.result.canonicalRef);
19712
+ }
19713
+ const mappings = /* @__PURE__ */ new Set([...branchMappings, ...acceptedMappings]);
19714
+ const published = resolveScopedResult(ref);
19715
+ if (published === "invalid")
19716
+ throw new Error("Invalid scoped result publication");
19717
+ if (published && published !== "reserved") {
19718
+ mappings.add(published.canonicalRef);
19719
+ }
19720
+ if (mappings.size !== 1) return void 0;
19721
+ const canonicalRef = mappings.values().next().value;
19722
+ if (typeof canonicalRef !== "string") return void 0;
19723
+ const explicitlyAccepted = acceptedMappings.has(canonicalRef);
19724
+ const verifiedBranch = branchMappings.has(canonicalRef);
19725
+ const owned = !!rootSessionId && !!published && published !== "reserved" && published.rootSessionId === rootSessionId;
19726
+ if (!explicitlyAccepted && !owned && !verifiedBranch) return void 0;
19727
+ return { ref, canonicalRef };
19728
+ }
19729
+ function readEvidencePage(authorizedEvidence, ref, options = {}, authorizedResult) {
19510
19730
  const offset = options.offset ?? 1;
19511
19731
  const limit = options.limit ?? READ_EVIDENCE_MAX_LINES;
19512
19732
  const byteOffset = options.byteOffset ?? 0;
@@ -19516,15 +19736,18 @@ function readEvidencePage(authorizedEvidence, ref, options = {}) {
19516
19736
  const matches = authorizedEvidence.filter(
19517
19737
  (item) => isRequiredEvidence(item) && semanticEvidenceRef(item) === ref
19518
19738
  );
19519
- if (matches.length !== 1) throw new Error();
19739
+ if (matches.length > 1) throw new Error();
19520
19740
  const evidence = matches[0];
19521
- if (!("result" in evidence))
19741
+ if (!evidence && (!authorizedResult || authorizedResult.ref !== ref))
19742
+ throw new Error();
19743
+ if (evidence && !("result" in evidence))
19522
19744
  verifySemanticEvidenceReservation(evidence.id, evidence.ref);
19523
19745
  let content;
19524
- if ("result" in evidence) {
19525
- const path = resolveResultRef(evidence.result.canonicalRef);
19746
+ if (!evidence || "result" in evidence) {
19747
+ const binding = evidence && "result" in evidence ? evidence.result : authorizedResult;
19748
+ const path = resolveResultRef(binding.canonicalRef);
19526
19749
  if (!path) throw new Error();
19527
- validateMessageFiles([evidence.result], process.cwd(), "read_evidence");
19750
+ validateMessageFiles([binding], process.cwd(), "read_evidence");
19528
19751
  content = new TextDecoder3("utf-8", { fatal: true }).decode(
19529
19752
  readFileSync10(path)
19530
19753
  );
@@ -19748,6 +19971,7 @@ function managedAgentEnvironmentIdentity(ctx, build) {
19748
19971
  ownerSessionId: e.PI_HERDSMAN_OWNER_SESSION_ID,
19749
19972
  workspaceId: e.PI_HERDSMAN_WORKSPACE_ID,
19750
19973
  agentLabel: e.PI_HERDSMAN_LABEL,
19974
+ ...e.PI_HERDSMAN_ROOT_SESSION_ID?.trim() ? { rootSessionId: e.PI_HERDSMAN_ROOT_SESSION_ID.trim() } : {},
19751
19975
  paneId: e.HERDR_PANE_ID,
19752
19976
  piSessionId: ctx.sessionManager.getSessionId(),
19753
19977
  piSessionFile: ctx.sessionManager.getSessionFile(),
@@ -19757,7 +19981,7 @@ function managedAgentEnvironmentIdentity(ctx, build) {
19757
19981
  };
19758
19982
  }
19759
19983
  function sameManagedAgentIdentity(left, right) {
19760
- return left.runId === right.runId && left.ownerSessionId === right.ownerSessionId && left.workspaceId === right.workspaceId && left.agentLabel === right.agentLabel && left.paneId === right.paneId && left.piSessionId === right.piSessionId && sameSessionPath2(left.piSessionFile, right.piSessionFile) && sameCwd(left.cwd, right.cwd);
19984
+ return left.runId === right.runId && left.ownerSessionId === right.ownerSessionId && left.workspaceId === right.workspaceId && left.agentLabel === right.agentLabel && left.paneId === right.paneId && left.piSessionId === right.piSessionId && left.rootSessionId === right.rootSessionId && sameSessionPath2(left.piSessionFile, right.piSessionFile) && sameCwd(left.cwd, right.cwd);
19761
19985
  }
19762
19986
  function sameSessionPath2(left, right) {
19763
19987
  if (left === right) return true;
@@ -19778,7 +20002,10 @@ function sameManagedAgentDurableState(left, right) {
19778
20002
  const { updatedAt: _rightUpdatedAt, ...rightDurable } = right;
19779
20003
  return isDeepStrictEqual3(leftDurable, rightDurable);
19780
20004
  }
19781
- function runtimeIdentityState(runtime, build) {
20005
+ function runtimeIdentityState(runtime, build, validatedState) {
20006
+ const rootSessionId = validatedState.rootSessionId;
20007
+ if (!rootSessionId?.trim())
20008
+ throw new Error("Managed-agent state has no verified ownership scope");
19782
20009
  return {
19783
20010
  version: 5,
19784
20011
  build,
@@ -19788,6 +20015,7 @@ function runtimeIdentityState(runtime, build) {
19788
20015
  agentLabel: runtime.label,
19789
20016
  paneId: runtime.paneId,
19790
20017
  piSessionId: runtime.piSessionId ?? "",
20018
+ rootSessionId,
19791
20019
  piSessionFile: runtime.piSessionFile,
19792
20020
  cwd: runtime.cwd,
19793
20021
  updatedAt: 0
@@ -19804,7 +20032,7 @@ function validateManagedAgentIdentity(input) {
19804
20032
  ids: { label: env.PI_HERDSMAN_LABEL, paneId: env.HERDR_PANE_ID }
19805
20033
  }
19806
20034
  );
19807
- if (!state || !mailbox || state.workspaceId !== env.PI_HERDSMAN_WORKSPACE_ID || state.agentLabel !== env.PI_HERDSMAN_LABEL || state.paneId !== env.HERDR_PANE_ID || state.ownerSessionId !== env.PI_HERDSMAN_OWNER_SESSION_ID || state.piSessionId !== input.sessionId || !input.sameSessionPath(state.piSessionFile, input.sessionFile) || resolve5(state.cwd) !== resolve5(input.cwd) || state.runId !== env.PI_HERDSMAN_RUN_ID)
20035
+ if (!state || !mailbox || state.workspaceId !== env.PI_HERDSMAN_WORKSPACE_ID || state.agentLabel !== env.PI_HERDSMAN_LABEL || state.paneId !== env.HERDR_PANE_ID || state.ownerSessionId !== env.PI_HERDSMAN_OWNER_SESSION_ID || state.rootSessionId !== void 0 && (!env.PI_HERDSMAN_ROOT_SESSION_ID?.trim() || state.rootSessionId !== env.PI_HERDSMAN_ROOT_SESSION_ID.trim()) || state.piSessionId !== input.sessionId || !input.sameSessionPath(state.piSessionFile, input.sessionFile) || resolve5(state.cwd) !== resolve5(input.cwd) || state.runId !== env.PI_HERDSMAN_RUN_ID)
19808
20036
  fail(
19809
20037
  "target_not_found",
19810
20038
  "Delegation controller identity is not a valid managed agent",
@@ -20991,6 +21219,7 @@ function registerManagedAgentSettlementHandlers(pi, execution, options) {
20991
21219
  workspaceId: state.workspaceId,
20992
21220
  agentLabel: state.agentLabel,
20993
21221
  paneId: state.paneId,
21222
+ rootSessionId: state.rootSessionId,
20994
21223
  status: completed ? "completed" : "failed",
20995
21224
  ...completed ? {
20996
21225
  text: responseText,
@@ -21162,6 +21391,7 @@ function registerManagedAgentRuntime(pi, options) {
21162
21391
  let startupDefinitionRoster;
21163
21392
  const controller = delegationEnabled ? createAgentController(pi, {
21164
21393
  ...options.controllerOptions,
21394
+ managedAgentRootSessionId: (ctx) => managedAgentControllerIdentity(ctx).rootSessionId,
21165
21395
  scope: {
21166
21396
  kind: "managed-agent",
21167
21397
  allowedAgentDefinitions: new Set(allowedAgentDefinitions)
@@ -22182,7 +22412,7 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
22182
22412
  // package.json
22183
22413
  var package_default = {
22184
22414
  name: "pi-herdsman",
22185
- version: "0.36.2",
22415
+ version: "0.36.3",
22186
22416
  type: "module",
22187
22417
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
22188
22418
  license: "Apache-2.0",
@@ -22307,7 +22537,7 @@ init_storage();
22307
22537
  import { Type as Type3 } from "typebox";
22308
22538
 
22309
22539
  // extension/coordinator-target.ts
22310
- import { createHash as createHash3 } from "node:crypto";
22540
+ import { createHash as createHash4 } from "node:crypto";
22311
22541
  import { SessionManager } from "@earendil-works/pi-coding-agent";
22312
22542
  var COORDINATOR_TARGET_PATTERN = "^(?:lead|manager):[0-9a-hjkmnp-tv-zA-HJKMNP-TV-Z]{10}$";
22313
22543
  var TARGET_ENTRY = "pi-herdsman-coordinator-target-v1";
@@ -22328,7 +22558,7 @@ function assertSessionId(sessionId) {
22328
22558
  function coordinatorTarget(role2, sessionId) {
22329
22559
  if (!isCoordinatorRole(role2)) throw new Error("Invalid coordinator role");
22330
22560
  assertSessionId(sessionId);
22331
- const digest = createHash3("sha256").update("pi-herdsman:coordinator-target:v1\0").update(role2).update("\0").update(sessionId).digest();
22561
+ const digest = createHash4("sha256").update("pi-herdsman:coordinator-target:v1\0").update(role2).update("\0").update(sessionId).digest();
22332
22562
  let bits = BigInt(`0x${digest.subarray(0, 7).toString("hex")}`) >> 6n;
22333
22563
  let suffix = "";
22334
22564
  for (let i = 0; i < 10; i++) {
@@ -22747,12 +22977,28 @@ function createLeadProjectRuntime(host) {
22747
22977
  );
22748
22978
  if (!current || current.id !== assignment.id || current.repoKey !== manager.repoKey)
22749
22979
  throw new Error("Project assignment changed during removal");
22750
- const matches = topology.worktrees.filter(
22751
- (worktree2) => worktree2?.branch === branch
22980
+ let sessionCwd;
22981
+ if (assignment.piSessionFile) {
22982
+ try {
22983
+ const session = host.SessionManager.open(assignment.piSessionFile);
22984
+ if (session.getSessionId() !== assignment.id) throw new Error();
22985
+ sessionCwd = session.getCwd();
22986
+ } catch {
22987
+ throw new Error(
22988
+ "Persisted project session provenance is unavailable; worktree preserved"
22989
+ );
22990
+ }
22991
+ }
22992
+ const placement = resolveAssignmentCheckout(
22993
+ assignment,
22994
+ topology.worktrees,
22995
+ sessionCwd
22752
22996
  );
22753
- if (matches.length !== 1)
22754
- throw new Error("Branch does not identify exactly one Herdr worktree");
22755
- const worktree = matches[0];
22997
+ if (placement.status !== "matched")
22998
+ throw new Error(
22999
+ `Assigned checkout is not verified (${placement.reason}); worktree preserved`
23000
+ );
23001
+ const worktree = placement.worktree;
22756
23002
  if (typeof worktree.path !== "string" || !worktree.path || !isAbsolute7(worktree.path) || worktree.is_linked_worktree !== true)
22757
23003
  throw new Error("Herdr worktree checkout path is unavailable");
22758
23004
  const checkoutPath = resolve6(worktree.path);
@@ -22800,9 +23046,7 @@ function createLeadProjectRuntime(host) {
22800
23046
  if (gitRoot.code !== 0 || gitRoot.killed || gitRoot.stderr?.trim() || gitCommonDir.code !== 0 || gitCommonDir.killed || gitCommonDir.stderr?.trim() || gitInventory.code !== 0 || gitInventory.killed || gitInventory.stderr?.trim() || !sameDirectory(String(gitRoot.stdout ?? "").trim(), checkoutPath) || !sameDirectory(
22801
23047
  String(gitCommonDir.stdout ?? "").trim(),
22802
23048
  manager.repoKey
22803
- ) || !gitWorktrees || gitWorktrees.filter(
22804
- (entry) => sameDirectory(entry.path, checkoutPath) && entry.branch === branch
22805
- ).length !== 1)
23049
+ ) || !gitWorktrees || gitWorktrees.filter((entry) => sameDirectory(entry.path, checkoutPath)).length !== 1)
22806
23050
  throw new Error();
22807
23051
  } catch {
22808
23052
  throw new Error(
@@ -22845,6 +23089,7 @@ function createLeadProjectRuntime(host) {
22845
23089
  assignment,
22846
23090
  worktree,
22847
23091
  checkoutPath,
23092
+ checkedOutBranch: typeof worktree.branch === "string" ? worktree.branch : void 0,
22848
23093
  sourceCheckoutPath: topology.source.source_checkout_path,
22849
23094
  liveLead: leads[0]
22850
23095
  };
@@ -22900,7 +23145,8 @@ function createLeadProjectRuntime(host) {
22900
23145
  "branch",
22901
23146
  "repoKey",
22902
23147
  "assignmentId",
22903
- "checkoutPath"
23148
+ "checkoutPath",
23149
+ "checkedOutBranch"
22904
23150
  ].includes(key)
22905
23151
  ) || !valid2("branch", 256) || !valid2("repoKey", 4096) || !valid2("assignmentId", 256) || !valid2("checkoutPath", 4096))
22906
23152
  return;
@@ -22911,7 +23157,8 @@ function createLeadProjectRuntime(host) {
22911
23157
  branch: value2.branch,
22912
23158
  repoKey: value2.repoKey,
22913
23159
  assignmentId: value2.assignmentId,
22914
- checkoutPath: value2.checkoutPath
23160
+ checkoutPath: value2.checkoutPath,
23161
+ ...typeof value2.checkedOutBranch === "string" ? { checkedOutBranch: value2.checkedOutBranch } : {}
22915
23162
  };
22916
23163
  };
22917
23164
  const pendingRemovals = (ctx) => {
@@ -22953,7 +23200,7 @@ function createLeadProjectRuntime(host) {
22953
23200
  const operationSignal = signal ?? ctx.signal;
22954
23201
  operationSignal?.throwIfAborted();
22955
23202
  const candidate = await inspectRemovalTarget(branch, ctx, operationSignal);
22956
- if (options.expected && (options.expected.repoKey !== candidate.manager.repoKey || options.expected.assignmentId !== candidate.assignment.id || options.expected.checkoutPath !== candidate.checkoutPath || options.expected.sessionId !== ctx.sessionManager.getSessionId()))
23203
+ if (options.expected && (options.expected.repoKey !== candidate.manager.repoKey || options.expected.assignmentId !== candidate.assignment.id || options.expected.checkoutPath !== candidate.checkoutPath || !options.expected.checkedOutBranch || options.expected.checkedOutBranch !== candidate.checkedOutBranch || options.expected.sessionId !== ctx.sessionManager.getSessionId()))
22957
23204
  throw new Error("Pending removal target changed; worktree preserved");
22958
23205
  await assertNoUnrelatedPiExecution(candidate, ctx, operationSignal);
22959
23206
  const preauthorized = isWorktreeRemovalPreapproved(
@@ -23007,6 +23254,7 @@ function createLeadProjectRuntime(host) {
23007
23254
  "Remove worktree",
23008
23255
  "",
23009
23256
  `Branch: ${branch}`,
23257
+ ...candidate.checkedOutBranch && candidate.checkedOutBranch !== branch ? [`Checked-out branch: ${candidate.checkedOutBranch}`] : [],
23010
23258
  `Checkout: ${candidate.checkoutPath}`,
23011
23259
  "",
23012
23260
  "Removes this checkout and Herdr workspace.",
@@ -23094,14 +23342,14 @@ function createLeadProjectRuntime(host) {
23094
23342
  "open",
23095
23343
  "--workspace",
23096
23344
  current.manager.workspaceId,
23097
- "--branch",
23098
- branch,
23345
+ "--path",
23346
+ current.checkoutPath,
23099
23347
  "--no-focus"
23100
23348
  ],
23101
23349
  { signal: operationSignal }
23102
23350
  );
23103
23351
  workspaceId = opened?.workspace?.workspace_id;
23104
- if (!workspaceId || workspaceId === current.manager.workspaceId || opened?.worktree?.branch !== branch || !sameDirectory(
23352
+ if (!workspaceId || workspaceId === current.manager.workspaceId || !sameDirectory(
23105
23353
  opened?.worktree?.path ?? "",
23106
23354
  current.checkoutPath
23107
23355
  ))
@@ -23848,6 +24096,24 @@ Subsequent explicitly requested removals here can proceed without a per-removal
23848
24096
  ]);
23849
24097
  if (sourceHead !== expectedHead)
23850
24098
  throw new Error("Accepted source SHA is stale; worktree preserved");
24099
+ const sourceBranch = await output(candidate.checkoutPath, [
24100
+ "symbolic-ref",
24101
+ "--short",
24102
+ "HEAD"
24103
+ ]).catch(() => "");
24104
+ if (!sourceBranch || sourceBranch !== candidate.checkedOutBranch)
24105
+ throw new Error(
24106
+ "Assigned checkout must be on its verified named branch; worktree preserved"
24107
+ );
24108
+ if (await output(candidate.checkoutPath, [
24109
+ "show-ref",
24110
+ "--verify",
24111
+ "--hash",
24112
+ `refs/heads/${sourceBranch}`
24113
+ ]) !== expectedHead)
24114
+ throw new Error(
24115
+ "Accepted source branch ref is stale; worktree preserved"
24116
+ );
23851
24117
  const targetPath = candidate.sourceCheckoutPath;
23852
24118
  const targetBranch = await output(targetPath, [
23853
24119
  "symbolic-ref",
@@ -23953,7 +24219,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
23953
24219
  ctx,
23954
24220
  operationSignal
23955
24221
  );
23956
- if (current.assignment.id !== candidate.assignment.id || current.checkoutPath !== candidate.checkoutPath || current.sourceCheckoutPath !== targetPath)
24222
+ if (current.assignment.id !== candidate.assignment.id || current.checkoutPath !== candidate.checkoutPath || current.checkedOutBranch !== sourceBranch || current.sourceCheckoutPath !== targetPath)
23957
24223
  throw new Error(
23958
24224
  "Merge target changed; no integration performed"
23959
24225
  );
@@ -24012,6 +24278,11 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24012
24278
  "rev-parse",
24013
24279
  "HEAD"
24014
24280
  ]);
24281
+ const currentSourceBranch = await output(current.checkoutPath, [
24282
+ "symbolic-ref",
24283
+ "--short",
24284
+ "HEAD"
24285
+ ]).catch(() => "");
24015
24286
  const currentTargetBranch = await output(targetPath, [
24016
24287
  "symbolic-ref",
24017
24288
  "--short",
@@ -24021,9 +24292,14 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24021
24292
  "rev-parse",
24022
24293
  "HEAD"
24023
24294
  ]);
24024
- if (currentSource !== expectedHead)
24295
+ if (currentSource !== expectedHead || currentSourceBranch !== sourceBranch || await output(current.checkoutPath, [
24296
+ "show-ref",
24297
+ "--verify",
24298
+ "--hash",
24299
+ `refs/heads/${sourceBranch}`
24300
+ ]) !== expectedHead)
24025
24301
  throw new Error(
24026
- "Accepted source SHA changed before integration"
24302
+ "Accepted source branch or SHA changed before integration"
24027
24303
  );
24028
24304
  if (currentTargetBranch !== targetBranch)
24029
24305
  throw new Error(
@@ -24188,6 +24464,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24188
24464
  branch,
24189
24465
  target_branch: integration.targetBranch,
24190
24466
  source_head: expectedHead,
24467
+ source_branch: sourceBranch,
24191
24468
  target_head: integration.targetHead,
24192
24469
  status: "cleanup_pending",
24193
24470
  integrated: true,
@@ -24220,6 +24497,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24220
24497
  branch,
24221
24498
  target_branch: integration.targetBranch,
24222
24499
  source_head: expectedHead,
24500
+ source_branch: sourceBranch,
24223
24501
  target_head: integration.targetHead,
24224
24502
  status: complete ? "complete" : "cleanup_pending",
24225
24503
  integrated: true,
@@ -24242,6 +24520,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24242
24520
  branch,
24243
24521
  target_branch: integration.targetBranch,
24244
24522
  source_head: expectedHead,
24523
+ source_branch: sourceBranch,
24245
24524
  target_head: integration.targetHead,
24246
24525
  status: "cleanup_pending",
24247
24526
  integrated: true,
@@ -24309,13 +24588,29 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24309
24588
  );
24310
24589
  const presentationTask = operation.action === "resume" ? projectTaskSummary(currentAssignment.text) : void 0;
24311
24590
  const id = operation.action === "resume" ? currentAssignment.id : operation.id;
24312
- const branchWorktrees = topology.worktrees.filter(
24313
- (worktree) => worktree?.branch === branch
24314
- );
24315
- if (operation.action === "resume" && branchWorktrees.length === 0)
24591
+ let savedSessionCwd;
24592
+ if (operation.action === "resume" && currentAssignment.piSessionFile) {
24593
+ try {
24594
+ const saved = host.SessionManager.open(
24595
+ currentAssignment.piSessionFile
24596
+ );
24597
+ if (saved.getSessionId() === currentAssignment.id)
24598
+ savedSessionCwd = saved.getCwd();
24599
+ } catch {
24600
+ }
24601
+ }
24602
+ const placement = operation.action === "resume" ? resolveAssignmentCheckout(
24603
+ currentAssignment,
24604
+ topology.worktrees,
24605
+ savedSessionCwd
24606
+ ) : void 0;
24607
+ if (placement && placement.status !== "matched")
24316
24608
  throw new Error(
24317
- "Worktree availability could not be verified; the existing assignment was preserved. Retry when repository access is available."
24609
+ `Assigned checkout could not be verified: ${placement.reason}; existing work was preserved.`
24318
24610
  );
24611
+ const branchWorktrees = operation.action === "resume" ? [placement.worktree] : topology.worktrees.filter(
24612
+ (worktree) => worktree?.branch === branch
24613
+ );
24319
24614
  if (branchWorktrees.length > 1)
24320
24615
  throw new Error(`Multiple Herdr worktrees match branch ${branch}`);
24321
24616
  const live = operation.action === "resume" ? await liveAgent(ctx, currentAssignment.id) : [];
@@ -24470,7 +24765,12 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24470
24765
  let paneId;
24471
24766
  let tabId;
24472
24767
  let cwd;
24473
- const matchingWorktrees = topology.worktrees.filter(
24768
+ const assignedPlacement = operation.action === "resume" ? resolveAssignmentCheckout(
24769
+ assignment,
24770
+ topology.worktrees,
24771
+ savedSessionCwd
24772
+ ) : void 0;
24773
+ const matchingWorktrees = operation.action === "resume" ? assignedPlacement?.status === "matched" ? [assignedPlacement.worktree] : [] : topology.worktrees.filter(
24474
24774
  (worktree) => worktree?.branch === assignment.branch
24475
24775
  );
24476
24776
  if (matchingWorktrees.length > 1)
@@ -24493,8 +24793,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24493
24793
  "open",
24494
24794
  "--cwd",
24495
24795
  localScope.checkoutPath,
24496
- "--branch",
24497
- assignment.branch,
24796
+ ...assignedPlacement?.status === "matched" ? ["--path", assignedPlacement.path] : ["--branch", assignment.branch],
24498
24797
  "--no-focus"
24499
24798
  ],
24500
24799
  { signal }
@@ -24503,9 +24802,9 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24503
24802
  paneId = opened?.root_pane?.pane_id;
24504
24803
  tabId = opened?.tab?.tab_id ?? opened?.root_pane?.tab_id;
24505
24804
  cwd = opened?.worktree?.path;
24506
- if (opened?.worktree?.branch && opened.worktree.branch !== assignment.branch)
24805
+ if (assignedPlacement?.status === "matched" && (!opened?.worktree?.path || !sameDirectory(opened.worktree.path, assignedPlacement.path)))
24507
24806
  throw new Error(
24508
- "Herdr opened a worktree on a different branch than the persisted assignment"
24807
+ "Herdr opened a different checkout than the persisted assignment"
24509
24808
  );
24510
24809
  }
24511
24810
  } else {
@@ -24576,6 +24875,25 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24576
24875
  throw new Error(
24577
24876
  `Work already exists on ${assignment.branch}; resume it with resume_work.`
24578
24877
  );
24878
+ const competingClaim = host.listProjectAssignments(runtime, manager.repoKey).find((existing2) => {
24879
+ if (existing2.id === assignment.id) return false;
24880
+ let claimedPath = existing2.checkoutPath;
24881
+ if (!claimedPath && existing2.piSessionFile) {
24882
+ try {
24883
+ const saved = host.SessionManager.open(
24884
+ existing2.piSessionFile
24885
+ );
24886
+ if (saved.getSessionId() === existing2.id)
24887
+ claimedPath = saved.getCwd();
24888
+ } catch {
24889
+ }
24890
+ }
24891
+ return !!claimedPath && sameDirectory(claimedPath, assignment.checkoutPath);
24892
+ });
24893
+ if (competingClaim)
24894
+ throw new Error(
24895
+ `Checkout is already claimed by managed assignment ${competingClaim.branch}; resume that work instead.`
24896
+ );
24579
24897
  writeProjectAssignment2(runtime, assignment);
24580
24898
  },
24581
24899
  signal
@@ -24950,6 +25268,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24950
25268
  repoKey: target.manager.repoKey,
24951
25269
  assignmentId: target.assignment.id,
24952
25270
  checkoutPath: target.checkoutPath,
25271
+ checkedOutBranch: target.checkedOutBranch,
24953
25272
  sessionId: ctx.sessionManager.getSessionId()
24954
25273
  };
24955
25274
  const verifiedAgain = await inspectRemovalTarget(
@@ -24960,10 +25279,10 @@ Subsequent explicitly requested removals here can proceed without a per-removal
24960
25279
  if (host.activeRole() !== "manager" || pending.sessionId !== ctx.sessionManager.getSessionId() || !host.sameManagerDescriptor(
24961
25280
  await host.currentManager(ctx),
24962
25281
  target.manager
24963
- ) || verifiedAgain.assignment.id !== pending.assignmentId || verifiedAgain.checkoutPath !== pending.checkoutPath || verifiedAgain.manager.repoKey !== pending.repoKey)
25282
+ ) || verifiedAgain.assignment.id !== pending.assignmentId || verifiedAgain.checkoutPath !== pending.checkoutPath || verifiedAgain.checkedOutBranch !== pending.checkedOutBranch || verifiedAgain.manager.repoKey !== pending.repoKey)
24964
25283
  throw new Error("Manager authority changed while preparing approval");
24965
25284
  const existing = pendingRemovals(ctx).get(params.branch);
24966
- const request = existing?.repoKey === pending.repoKey && existing.assignmentId === pending.assignmentId && existing.checkoutPath === pending.checkoutPath ? existing : pending;
25285
+ const request = existing?.repoKey === pending.repoKey && existing.assignmentId === pending.assignmentId && existing.checkoutPath === pending.checkoutPath && existing.checkedOutBranch === pending.checkedOutBranch ? existing : pending;
24967
25286
  if (request === pending)
24968
25287
  host.pi.appendEntry(REMOVAL_ENTRY, {
24969
25288
  version: 1,
@@ -30270,6 +30589,7 @@ function registerLeadRuntime(pi, options) {
30270
30589
  });
30271
30590
  const inboxServices = {
30272
30591
  ...options.inboxHost,
30592
+ SessionManager: options.projectHost.SessionManager,
30273
30593
  projectAssignmentInstruction,
30274
30594
  leadRuntime: options.leadRuntime,
30275
30595
  leadInstanceId: () => options.leadRuntime.instanceId,
@@ -30756,16 +31076,43 @@ function registerLeadRuntime(pi, options) {
30756
31076
  throw new Error(
30757
31077
  "Project assignment conflicts with permanent session identity"
30758
31078
  );
31079
+ let expectedCheckout = assignment.checkoutPath;
31080
+ if (!expectedCheckout) {
31081
+ if (!assignment.piSessionFile)
31082
+ throw new Error("Managed Lead checkout provenance is unavailable");
31083
+ const saved = projectHost.SessionManager.open(
31084
+ assignment.piSessionFile
31085
+ );
31086
+ if (saved.getSessionId() !== identity.sessionId)
31087
+ throw new Error(
31088
+ "Managed Lead session provenance does not match assignment"
31089
+ );
31090
+ expectedCheckout = saved.getCwd();
31091
+ if (!expectedCheckout || !isAbsolute8(expectedCheckout))
31092
+ throw new Error("Managed Lead checkout provenance is unavailable");
31093
+ const common = await pi.exec(
31094
+ "git",
31095
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
31096
+ { cwd: expectedCheckout, signal: ctx.signal, timeout: 1e4 }
31097
+ );
31098
+ if (common.code !== 0 || common.killed || common.stderr?.trim() || !sameDirectory(String(common.stdout ?? "").trim(), identity.repoKey))
31099
+ throw new Error(
31100
+ "Managed Lead session checkout repository does not match assignment"
31101
+ );
31102
+ }
31103
+ if (!sameDirectory(expectedCheckout, ctx.cwd))
31104
+ throw new Error("Managed Lead is outside its assigned checkout");
30759
31105
  publish("assigned");
30760
31106
  roleTransitions.reconcileRoleTools();
30761
31107
  return assignment;
30762
31108
  }
30763
- const pendingRetirement = !replacement && listPendingRetirements(
31109
+ const pendingRecord = !replacement && listPendingRetirements(
30764
31110
  roleHost.supervisionRuntime(),
30765
31111
  identity.repoKey
30766
- ).some(
31112
+ ).find(
30767
31113
  (retired) => retired.id === identity.sessionId && retired.branch === identity.branch
30768
31114
  );
31115
+ const pendingRetirement = !!pendingRecord;
30769
31116
  let retirementVerified = false;
30770
31117
  if (pendingRetirement) {
30771
31118
  const workspaceId = (validScope ? scope.primaryWorkspaceId : void 0) ?? process.env.HERDR_WORKSPACE_ID;
@@ -30778,9 +31125,21 @@ function registerLeadRuntime(pi, options) {
30778
31125
  );
30779
31126
  if (sessionKind !== identity || ctx.sessionManager.getSessionId() !== identity.sessionId)
30780
31127
  throw new Error("Session changed while verifying retirement");
30781
- if (topology?.source?.repo_key === identity.repoKey && typeof topology.source.source_checkout_path === "string" && Array.isArray(topology.worktrees) && !topology.worktrees.some(
30782
- (worktree) => worktree.branch === identity.branch
30783
- )) {
31128
+ let checkoutPath = pendingRecord?.checkoutPath;
31129
+ if (!checkoutPath && pendingRecord?.piSessionFile) {
31130
+ try {
31131
+ const saved = roleHost.SessionManager.open(
31132
+ pendingRecord.piSessionFile
31133
+ );
31134
+ if (saved.getSessionId() === identity.sessionId)
31135
+ checkoutPath = saved.getCwd();
31136
+ } catch {
31137
+ }
31138
+ }
31139
+ const checkoutAbsent = typeof checkoutPath === "string" && topology?.source?.repo_key === identity.repoKey && Array.isArray(topology.worktrees) && !topology.worktrees.some(
31140
+ (worktree) => worktree.is_linked_worktree === true && typeof worktree.path === "string" && sameDirectory(worktree.path, checkoutPath)
31141
+ );
31142
+ if (checkoutAbsent && gitPathStatus(checkoutPath) === "absent") {
30784
31143
  const inventory = await pi.exec(
30785
31144
  "git",
30786
31145
  ["worktree", "list", "--porcelain", "-z"],
@@ -30793,7 +31152,9 @@ function registerLeadRuntime(pi, options) {
30793
31152
  const worktrees = inventory.code === 0 && !inventory.killed && !inventory.stderr?.trim() ? parseGitWorktreeInventory(inventory.stdout) : void 0;
30794
31153
  if (sessionKind !== identity || ctx.sessionManager.getSessionId() !== identity.sessionId)
30795
31154
  throw new Error("Session changed while verifying retirement");
30796
- if (worktrees && !worktrees.some((worktree) => worktree.branch === identity.branch)) {
31155
+ if (worktrees && !worktrees.some(
31156
+ (worktree) => sameDirectory(worktree.path, checkoutPath)
31157
+ )) {
30797
31158
  publish("retired");
30798
31159
  retirementVerified = true;
30799
31160
  }
@@ -31231,8 +31592,8 @@ function createLeadIdentityRuntime(host) {
31231
31592
  (agent) => host.isPiAgent(agent) && host.matchesExpectedSession(agent.agent_session, expected) && typeof agent.pane_id === "string" && typeof agent.tab_id === "string" && typeof agent.workspace_id === "string"
31232
31593
  );
31233
31594
  };
31234
- const remoteChiefAgent = async (ctx, descriptor) => verifiedHerdrAgent(descriptor, {
31235
- listAgents: async () => (await host.listAgents(ctx)).agents,
31595
+ const remoteChiefAgent = async (ctx, descriptor, knownAgents) => verifiedHerdrAgent(descriptor, {
31596
+ listAgents: async () => knownAgents ?? (await host.listAgents(ctx)).agents,
31236
31597
  getAgent: async (paneId) => (await host.getAgent(ctx, paneId))?.agent,
31237
31598
  expectedSession: host.expectedSession,
31238
31599
  isPiAgent: host.isPiAgent,
@@ -31257,7 +31618,7 @@ function createLeadIdentityRuntime(host) {
31257
31618
  return { liveAgent, remoteChiefAgent, liveLead };
31258
31619
  }
31259
31620
  function createLeadSupervisionRuntime(host) {
31260
- const loadSupervisionSnapshot = async (ctx, suppliedInventory, suppliedAgents, includeAll = false, classifyBuilds = false) => {
31621
+ const loadSupervisionSnapshot = async (ctx, suppliedInventory, suppliedAgents, includeAll = false, classifyBuilds = false, knownTopology) => {
31261
31622
  if (host.activeRole() === "chief" && !includeAll) {
31262
31623
  const incompatible = [];
31263
31624
  const reports = await directReports(
@@ -31278,27 +31639,32 @@ function createLeadSupervisionRuntime(host) {
31278
31639
  if (host.activeRole() === "manager" && !includeAll) {
31279
31640
  const manager = await host.currentManager(ctx);
31280
31641
  if (!manager) throw new Error("Manager lease is no longer active");
31281
- const group = await host.worktreeGroupScope(
31642
+ const topology = await host.runHerdr(
31282
31643
  host.pi,
31283
31644
  ctx,
31645
+ ["worktree", "list", "--workspace", manager.workspaceId],
31646
+ { signal: ctx.signal }
31647
+ );
31648
+ const group = worktreeGroupScopeFromTopology(
31284
31649
  manager.workspaceId,
31285
- ctx.signal
31650
+ topology
31286
31651
  );
31287
31652
  if (group.repoKey !== manager.repoKey)
31288
31653
  throw new Error("Manager workspace is not the assigned project");
31289
31654
  const incompatible = [];
31290
31655
  const unverified = [];
31291
- const [leads, topology] = await Promise.all([
31292
- directReports(ctx, suppliedInventory, suppliedAgents, incompatible, {
31293
- unverified
31294
- }),
31295
- host.runHerdr(
31296
- host.pi,
31297
- ctx,
31298
- ["worktree", "list", "--workspace", group.primaryWorkspaceId],
31299
- { signal: ctx.signal }
31300
- )
31301
- ]);
31656
+ const inventory2 = suppliedInventory ?? await host.herdrSessionSnapshot(host.pi, ctx, ctx.signal);
31657
+ const leads = await directReports(
31658
+ ctx,
31659
+ inventory2,
31660
+ suppliedAgents,
31661
+ incompatible,
31662
+ {
31663
+ unverified,
31664
+ group,
31665
+ topology
31666
+ }
31667
+ );
31302
31668
  if (topology?.source?.repo_key !== group.repoKey || topology?.source?.source_workspace_id !== group.primaryWorkspaceId || !Array.isArray(topology?.worktrees))
31303
31669
  throw new Error("Herdr worktree topology is not authoritative");
31304
31670
  if (typeof topology.source.source_checkout_path === "string")
@@ -31306,12 +31672,54 @@ function createLeadSupervisionRuntime(host) {
31306
31672
  ctx,
31307
31673
  group.repoKey,
31308
31674
  manager.workspaceId,
31309
- topology.source.source_checkout_path
31675
+ topology.source.source_checkout_path,
31676
+ false,
31677
+ void 0,
31678
+ false,
31679
+ void 0,
31680
+ group
31310
31681
  );
31311
31682
  const assignments = host.listProjectAssignments(
31312
31683
  host.supervisionRuntime(),
31313
31684
  group.repoKey
31314
31685
  );
31686
+ const placements = /* @__PURE__ */ new Map();
31687
+ for (const assignment of assignments) {
31688
+ let sessionCwd;
31689
+ if (assignment.piSessionFile) {
31690
+ try {
31691
+ const saved = host.SessionManager.open(assignment.piSessionFile);
31692
+ if (saved.getSessionId() === assignment.id)
31693
+ sessionCwd = saved.getCwd();
31694
+ } catch {
31695
+ }
31696
+ }
31697
+ const placement = resolveAssignmentCheckout(
31698
+ assignment,
31699
+ topology.worktrees,
31700
+ sessionCwd
31701
+ );
31702
+ placements.set(assignment.id, placement);
31703
+ }
31704
+ const conflictingAssignments = /* @__PURE__ */ new Set();
31705
+ for (let i = 0; i < assignments.length; i++) {
31706
+ const assignment = assignments[i];
31707
+ const placement = placements.get(assignment.id);
31708
+ if (placement?.status !== "matched") continue;
31709
+ for (let j = i + 1; j < assignments.length; j++) {
31710
+ const other = assignments[j];
31711
+ const otherPlacement = placements.get(other.id);
31712
+ if (otherPlacement?.status === "matched" && sameDirectory(placement.path, otherPlacement.path)) {
31713
+ conflictingAssignments.add(assignment.id);
31714
+ conflictingAssignments.add(other.id);
31715
+ }
31716
+ }
31717
+ }
31718
+ for (const id of conflictingAssignments)
31719
+ placements.set(id, {
31720
+ status: "conflict",
31721
+ reason: "multiple assignments claim the same checkout"
31722
+ });
31315
31723
  const openWorkspaces = topology.worktrees.flatMap(
31316
31724
  (worktree) => typeof worktree?.open_workspace_id === "string" && worktree.open_workspace_id ? [
31317
31725
  {
@@ -31327,6 +31735,7 @@ function createLeadSupervisionRuntime(host) {
31327
31735
  work: host.projectWorkSnapshot({
31328
31736
  assignments,
31329
31737
  worktrees: topology.worktrees,
31738
+ placements,
31330
31739
  leads: [
31331
31740
  ...leads,
31332
31741
  ...incompatible.filter((report) => report.role === "lead").map((report) => ({
@@ -31406,7 +31815,8 @@ function createLeadSupervisionRuntime(host) {
31406
31815
  [...new Set(agents.map((agent) => agent.workspaceId))],
31407
31816
  workspaceCwds,
31408
31817
  ctx.signal,
31409
- inventory.workspaces
31818
+ inventory.workspaces,
31819
+ knownTopology
31410
31820
  );
31411
31821
  const diagnostics = live.some(
31412
31822
  (agent) => (agent?.agent === "pi" || agent?.agent_session?.agent === "pi") && !host.isPiAgent(agent)
@@ -31444,18 +31854,20 @@ function createLeadSupervisionRuntime(host) {
31444
31854
  const manager = await host.currentManager(ctx);
31445
31855
  if (!manager || !host.state.managerLease || !host.sameManagerDescriptor(manager, host.state.managerLease.descriptor))
31446
31856
  throw new Error("Manager lease is no longer active");
31447
- const scope = await host.worktreeGroupScope(
31857
+ const scope = options?.group ?? await host.worktreeGroupScope(
31448
31858
  host.pi,
31449
31859
  ctx,
31450
31860
  manager.workspaceId,
31451
31861
  ctx.signal
31452
31862
  );
31863
+ const inventory = suppliedInventory ?? await host.herdrSessionSnapshot(host.pi, ctx, ctx.signal);
31453
31864
  const snapshot2 = await loadSupervisionSnapshot(
31454
31865
  ctx,
31455
- suppliedInventory,
31866
+ inventory,
31456
31867
  suppliedAgents,
31457
31868
  true,
31458
- true
31869
+ true,
31870
+ options?.topology
31459
31871
  );
31460
31872
  for (const report of snapshot2.incompatible ?? [])
31461
31873
  if (report.role === "lead" && scope.workspaceIds.includes(report.workspaceId))
@@ -31470,13 +31882,14 @@ function createLeadSupervisionRuntime(host) {
31470
31882
  const repoManagers = host.listManagerDescriptors(host.supervisionRuntime()).filter((candidate) => candidate.repoKey === manager.repoKey);
31471
31883
  const ordinarySupervisionAvailable = repoManagers.length === 1 && host.sameManagerDescriptor(repoManagers[0], manager);
31472
31884
  const candidates = options?.exactSession ? snapshot2.leads.filter((lead) => lead.lead === options.exactSession) : snapshot2.leads;
31473
- const leads = await Promise.all(
31885
+ const initial = await Promise.all(
31474
31886
  candidates.map(async (lead) => {
31475
31887
  const unverified = (status2, issue) => {
31476
31888
  if (sessions.has(lead.lead))
31477
31889
  options?.unverified?.push({ lead: lead.lead, status: status2, issue });
31478
31890
  return void 0;
31479
31891
  };
31892
+ let verificationStage = "identity";
31480
31893
  try {
31481
31894
  const descriptor = {
31482
31895
  piSessionId: lead.lead,
@@ -31485,38 +31898,73 @@ function createLeadSupervisionRuntime(host) {
31485
31898
  tabId: lead.tabId,
31486
31899
  workspaceId: lead.workspaceId
31487
31900
  };
31488
- const agent = await host.remoteChiefAgent(ctx, descriptor);
31901
+ const agent = await host.remoteChiefAgent(
31902
+ ctx,
31903
+ descriptor,
31904
+ inventory.agents
31905
+ );
31489
31906
  if (typeof agent?.cwd !== "string" || !agent.cwd)
31490
31907
  return unverified(
31491
31908
  "unknown",
31492
31909
  "Assigned Lead identity could not be verified"
31493
31910
  );
31911
+ verificationStage = "repository";
31494
31912
  const repository = await localRepositoryScope(
31495
31913
  host.pi,
31496
31914
  { ...ctx, cwd: agent.cwd },
31497
31915
  lead.workspaceId,
31498
- ctx.signal
31916
+ ctx.signal,
31917
+ options?.topology
31499
31918
  );
31500
31919
  if (repository.repoKey !== manager.repoKey)
31501
31920
  return unverified(
31502
31921
  "conflict",
31503
31922
  "Assigned Lead repository does not match the project"
31504
31923
  );
31505
- const current = await host.remoteChiefAgent(ctx, descriptor);
31506
- if (!current || current.cwd !== agent.cwd)
31507
- return unverified(
31508
- "unknown",
31509
- "Assigned Lead identity changed during verification"
31510
- );
31511
- return lead;
31924
+ return { lead, cwd: agent.cwd };
31512
31925
  } catch (error2) {
31513
31926
  if (ctx.signal?.aborted) throw ctx.signal.reason;
31514
31927
  if (error2 instanceof Error && error2.name === "AbortError")
31515
31928
  throw error2;
31516
31929
  return unverified(
31517
31930
  "unknown",
31518
- "Assigned Lead verification unavailable"
31931
+ verificationStage === "identity" ? "Assigned Lead identity verification unavailable" : "Assigned Lead repository verification unavailable"
31932
+ );
31933
+ }
31934
+ })
31935
+ );
31936
+ const pending2 = initial.filter((item) => item !== void 0);
31937
+ const finalAgents = pending2.length ? (await host.herdrSessionSnapshot(host.pi, ctx, ctx.signal)).agents : [];
31938
+ const leads = await Promise.all(
31939
+ pending2.map(async ({ lead, cwd }) => {
31940
+ try {
31941
+ const current = await host.remoteChiefAgent(
31942
+ ctx,
31943
+ {
31944
+ piSessionId: lead.lead,
31945
+ piSessionFile: lead.piSessionFile,
31946
+ paneId: lead.paneId,
31947
+ tabId: lead.tabId,
31948
+ workspaceId: lead.workspaceId
31949
+ },
31950
+ finalAgents
31519
31951
  );
31952
+ return current?.cwd === cwd ? lead : (sessions.has(lead.lead) && options?.unverified?.push({
31953
+ lead: lead.lead,
31954
+ status: "unknown",
31955
+ issue: "Assigned Lead identity changed during verification"
31956
+ }), void 0);
31957
+ } catch (error2) {
31958
+ if (ctx.signal?.aborted) throw ctx.signal.reason;
31959
+ if (error2 instanceof Error && error2.name === "AbortError")
31960
+ throw error2;
31961
+ if (sessions.has(lead.lead))
31962
+ options?.unverified?.push({
31963
+ lead: lead.lead,
31964
+ status: "unknown",
31965
+ issue: "Assigned Lead final identity unavailable"
31966
+ });
31967
+ return void 0;
31520
31968
  }
31521
31969
  })
31522
31970
  );
@@ -33204,11 +33652,6 @@ function createLeadInboxRuntime(host) {
33204
33652
  managerDiagnostic("project_assignment_topology_complete");
33205
33653
  if (topology?.source?.source_workspace_id !== scope.primaryWorkspaceId || topology?.source?.repo_key !== scope.repoKey || !Array.isArray(topology?.worktrees))
33206
33654
  return projectAssignmentAuthorized(false, "worktree_topology_mismatch");
33207
- const worktrees = topology.worktrees.filter(
33208
- (worktree) => worktree.branch === assignment2.branch
33209
- );
33210
- if (worktrees.length !== 1)
33211
- return projectAssignmentAuthorized(false, "branch_placement_mismatch");
33212
33655
  managerDiagnostic("project_assignment_live_lead_start");
33213
33656
  const live = await liveLead(
33214
33657
  ctx,
@@ -33218,7 +33661,61 @@ function createLeadInboxRuntime(host) {
33218
33661
  managerDiagnostic("project_assignment_live_lead_complete");
33219
33662
  if (live.length !== 1)
33220
33663
  return projectAssignmentAuthorized(false, "live_lead_mismatch");
33221
- if (!scope.workspaceIds.includes(live[0].workspace_id) || worktrees[0].open_workspace_id !== live[0].workspace_id)
33664
+ let savedSessionCwd;
33665
+ if (!assignment2.checkoutPath) {
33666
+ if (!assignment2.piSessionFile)
33667
+ return projectAssignmentAuthorized(
33668
+ false,
33669
+ "session_provenance_unavailable"
33670
+ );
33671
+ try {
33672
+ const saved = host.SessionManager.open(assignment2.piSessionFile);
33673
+ if (saved.getSessionId() !== assignment2.id)
33674
+ return projectAssignmentAuthorized(
33675
+ false,
33676
+ "session_provenance_mismatch"
33677
+ );
33678
+ savedSessionCwd = saved.getCwd();
33679
+ if (!savedSessionCwd || !isAbsolute8(savedSessionCwd))
33680
+ return projectAssignmentAuthorized(
33681
+ false,
33682
+ "session_provenance_unavailable"
33683
+ );
33684
+ const common = await pi.exec(
33685
+ "git",
33686
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
33687
+ {
33688
+ cwd: savedSessionCwd,
33689
+ signal: ctx.signal,
33690
+ timeout: 1e4
33691
+ }
33692
+ );
33693
+ if (common.code !== 0 || common.killed || common.stderr?.trim() || !sameDirectory(
33694
+ String(common.stdout ?? "").trim(),
33695
+ assignment2.repoKey
33696
+ ))
33697
+ return projectAssignmentAuthorized(
33698
+ false,
33699
+ "session_provenance_mismatch"
33700
+ );
33701
+ } catch {
33702
+ return projectAssignmentAuthorized(
33703
+ false,
33704
+ "session_provenance_unavailable"
33705
+ );
33706
+ }
33707
+ }
33708
+ const placement = resolveAssignmentCheckout(
33709
+ assignment2,
33710
+ topology.worktrees,
33711
+ savedSessionCwd
33712
+ );
33713
+ if (placement.status !== "matched")
33714
+ return projectAssignmentAuthorized(
33715
+ false,
33716
+ "checkout_placement_mismatch"
33717
+ );
33718
+ if (typeof live[0].cwd !== "string" || !sameDirectory(live[0].cwd, placement.path) || !scope.workspaceIds.includes(live[0].workspace_id) || placement.worktree.open_workspace_id !== live[0].workspace_id)
33222
33719
  return projectAssignmentAuthorized(
33223
33720
  false,
33224
33721
  "workspace_placement_mismatch"
@@ -34484,14 +34981,10 @@ function createLeadRoleTransitions(state, host) {
34484
34981
  }
34485
34982
  return true;
34486
34983
  };
34487
- const gitWorktreeInventory = async (ctx, repoKey, primaryWorkspaceId, sourceCheckoutPath) => {
34984
+ const gitWorktreeInventory = async (ctx, repoKey, primaryWorkspaceId, sourceCheckoutPath, knownScope) => {
34488
34985
  if (!isAbsolute8(sourceCheckoutPath)) return void 0;
34489
34986
  try {
34490
- const scope = await host.worktreeGroupScope(
34491
- ctx,
34492
- primaryWorkspaceId,
34493
- ctx.signal
34494
- );
34987
+ const scope = knownScope ?? await host.worktreeGroupScope(ctx, primaryWorkspaceId, ctx.signal);
34495
34988
  if (scope.repoKey !== repoKey) return void 0;
34496
34989
  const rootResult = await host.pi.exec(
34497
34990
  "git",
@@ -34517,7 +35010,7 @@ function createLeadRoleTransitions(state, host) {
34517
35010
  return void 0;
34518
35011
  }
34519
35012
  };
34520
- const reconcileProjectAssignments = async (ctx, repoKey, primaryWorkspaceId, sourceCheckoutPath, projectWorkLocked = false, onlyBranch, retryLockContention = false, expectedAssignmentId) => {
35013
+ const reconcileProjectAssignments = async (ctx, repoKey, primaryWorkspaceId, sourceCheckoutPath, projectWorkLocked = false, onlyBranch, retryLockContention = false, expectedAssignmentId, knownScope) => {
34521
35014
  const manager = await currentManager(ctx);
34522
35015
  if (!manager || manager.repoKey !== repoKey || manager.workspaceId !== primaryWorkspaceId)
34523
35016
  return;
@@ -34529,7 +35022,8 @@ function createLeadRoleTransitions(state, host) {
34529
35022
  ctx,
34530
35023
  repoKey,
34531
35024
  primaryWorkspaceId,
34532
- sourceCheckoutPath
35025
+ sourceCheckoutPath,
35026
+ knownScope
34533
35027
  );
34534
35028
  if (!initialInventory) return;
34535
35029
  const knownSessionCheckoutPath = (assignment) => {
@@ -34574,13 +35068,6 @@ function createLeadRoleTransitions(state, host) {
34574
35068
  }
34575
35069
  if (checkoutMaySurvive(observed, initialInventory, observedProvenance.path))
34576
35070
  continue;
34577
- const initialMatches = initialInventory.filter(
34578
- (worktree) => worktree.branch === observed.branch
34579
- );
34580
- if (initialMatches.length > 1 || initialMatches.some(
34581
- (worktree) => worktree.locked || !worktree.prunable || gitPathStatus(worktree.path) !== "absent"
34582
- ))
34583
- continue;
34584
35071
  const retireIfAbsent = async () => {
34585
35072
  const latestManager = await currentManager(ctx);
34586
35073
  if (!latestManager || !host.sameManagerDescriptor(latestManager, manager))
@@ -34606,13 +35093,6 @@ function createLeadRoleTransitions(state, host) {
34606
35093
  const currentProvenance = checkoutProvenance(current);
34607
35094
  if (currentProvenance.conflicting || checkoutMaySurvive(current, inventory, currentProvenance.path))
34608
35095
  return;
34609
- const matches = inventory.filter(
34610
- (worktree) => worktree.branch === observed.branch
34611
- );
34612
- if (matches.length > 1 || matches.some(
34613
- (worktree) => worktree.locked || !worktree.prunable || gitPathStatus(worktree.path) !== "absent"
34614
- ))
34615
- return;
34616
35096
  removeProjectAssignmentState(current, ctx);
34617
35097
  };
34618
35098
  const deadline = retryLockContention ? Date.now() + 3e4 : 0;
@@ -35895,7 +36375,7 @@ function expectedSession2(id, path) {
35895
36375
  function isPiAgent(agent) {
35896
36376
  return sessionIdentity(agent?.agent_session) !== void 0;
35897
36377
  }
35898
- async function workspacePresentationProvenance(pi, ctx, workspaceIds, workspaceCwds, signal, snapshotWorkspaces) {
36378
+ async function workspacePresentationProvenance(pi, ctx, workspaceIds, workspaceCwds, signal, snapshotWorkspaces, knownTopology) {
35899
36379
  const workspaces = /* @__PURE__ */ new Map();
35900
36380
  if (snapshotWorkspaces) {
35901
36381
  for (const workspace2 of snapshotWorkspaces)
@@ -35933,6 +36413,10 @@ async function workspacePresentationProvenance(pi, ctx, workspaceIds, workspaceC
35933
36413
  const topologyByRepo = /* @__PURE__ */ new Map();
35934
36414
  for (const [key, source] of sources) {
35935
36415
  if (signal?.aborted) break;
36416
+ if (knownTopology?.source?.repo_key === source.repoKey && knownTopology?.source?.repo_root === source.repoRoot && Array.isArray(knownTopology.worktrees)) {
36417
+ topologyByRepo.set(key, knownTopology);
36418
+ continue;
36419
+ }
35936
36420
  try {
35937
36421
  const topology = await runHerdr(
35938
36422
  pi,
@@ -37539,10 +38023,19 @@ ${summary}`,
37539
38023
  try {
37540
38024
  const accepted = managedAgentRequiredEvidence(ctx);
37541
38025
  if (!accepted) throw new Error();
38026
+ const state = managedAgentIdentity(ctx);
38027
+ const scoped = authorizedScopedResult(
38028
+ params.ref,
38029
+ state.rootSessionId ?? "",
38030
+ accepted.effectiveEvidence,
38031
+ ctx.sessionManager.getBranch(),
38032
+ ctx.sessionManager.getSessionId()
38033
+ );
37542
38034
  const page = readEvidencePage(
37543
38035
  accepted.effectiveEvidence,
37544
38036
  params.ref,
37545
- params
38037
+ params,
38038
+ scoped
37546
38039
  );
37547
38040
  return {
37548
38041
  content: [{ type: "text", text: evidencePageContent(page) }],