pi-herdsman 0.35.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/SKILL.md +25 -15
  2. package/dist/index.js +906 -407
  3. package/dist/index.js.map +4 -4
  4. package/dist/peer-bridge.js +188 -83
  5. package/dist/peer-bridge.js.map +4 -4
  6. package/docs/adr/0034-separate-definition-namespaces.md +30 -0
  7. package/docs/development/smoke-testing.md +4 -4
  8. package/docs/development/validation.md +10 -4
  9. package/docs/guides/agent-definitions.md +15 -5
  10. package/docs/guides/container-deployment.md +15 -1
  11. package/docs/guides/customizing-agents.md +15 -10
  12. package/docs/guides/handoffs.md +25 -17
  13. package/docs/guides/project-orchestration.md +1 -1
  14. package/docs/reference/agent-definition-schema.md +16 -5
  15. package/docs/reference/agent.md +14 -7
  16. package/docs/reference/commands.md +1 -1
  17. package/docs/reference/peer.md +23 -21
  18. package/docs/reference/staff.md +38 -23
  19. package/package.json +1 -1
  20. package/skills/agent-definitions/SKILL.md +16 -7
  21. /package/dist/{agent-definitions → agents}/generalist.md +0 -0
  22. /package/dist/{agent-definitions → agents}/implementer.md +0 -0
  23. /package/dist/{agent-definitions → agents}/researcher.md +0 -0
  24. /package/dist/{agent-definitions → agents}/reviewer.md +0 -0
  25. /package/dist/{agent-definitions → agents}/scout.md +0 -0
  26. /package/dist/{agent-definitions → roles}/chief.md +0 -0
  27. /package/dist/{agent-definitions → roles}/flexible-lead.md +0 -0
  28. /package/dist/{agent-definitions → roles}/managed-lead.md +0 -0
  29. /package/dist/{agent-definitions → roles}/manager.md +0 -0
  30. /package/dist/{agent-definitions → roles}/orchestrator-lead.md +0 -0
@@ -1,22 +1,42 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // bin/peer-bridge.ts
4
- import { createHash as createHash6, randomUUID as randomUUID6 } from "node:crypto";
4
+ import { createHash as createHash7, randomUUID as randomUUID6 } from "node:crypto";
5
5
  import {
6
6
  closeSync as closeSync4,
7
7
  fsyncSync as fsyncSync4,
8
8
  linkSync,
9
9
  mkdirSync as mkdirSync5,
10
10
  openSync as openSync4,
11
- readFileSync as readFileSync5,
11
+ readFileSync as readFileSync6,
12
12
  renameSync as renameSync5,
13
13
  rmSync as rmSync2,
14
14
  writeSync as writeSync2,
15
15
  writeFileSync as writeFileSync4
16
16
  } from "node:fs";
17
- import { isAbsolute as isAbsolute2, join as join5 } from "node:path";
17
+ import { basename as basename4, dirname as dirname4, isAbsolute as isAbsolute2, join as join5 } from "node:path";
18
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
18
19
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
19
20
 
21
+ // extension/compatibility.ts
22
+ import { createHash } from "node:crypto";
23
+ import { readFileSync } from "node:fs";
24
+ var SHA256 = /^[0-9a-f]{64}$/;
25
+ function runtimeBuild(version, path) {
26
+ return Object.freeze({
27
+ version,
28
+ sha256: createHash("sha256").update(readFileSync(path)).digest("hex")
29
+ });
30
+ }
31
+ function isRuntimeBuild(value) {
32
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
33
+ const record = value;
34
+ return Object.keys(record).length === 2 && typeof record.version === "string" && record.version.length > 0 && record.version.length <= 128 && typeof record.sha256 === "string" && SHA256.test(record.sha256);
35
+ }
36
+ function sameRuntimeBuild(left, right) {
37
+ return left.version === right.version && left.sha256 === right.sha256;
38
+ }
39
+
20
40
  // extension/storage.ts
21
41
  import { homedir, tmpdir } from "node:os";
22
42
  import {
@@ -28,13 +48,13 @@ import {
28
48
  mkdirSync,
29
49
  openSync,
30
50
  readdirSync,
31
- readFileSync,
51
+ readFileSync as readFileSync2,
32
52
  renameSync,
33
53
  lstatSync,
34
54
  unlinkSync,
35
55
  writeFileSync
36
56
  } from "node:fs";
37
- import { createHash, randomUUID } from "node:crypto";
57
+ import { createHash as createHash2, randomUUID } from "node:crypto";
38
58
  import { basename, dirname, join } from "node:path";
39
59
  import { fileURLToPath } from "node:url";
40
60
  var RESULT_PREFIX = "result:";
@@ -82,7 +102,7 @@ function verifySemanticEvidenceReservation(evidenceId, ref) {
82
102
  const stat = lstatSync(path);
83
103
  if (!stat.isFile() || stat.isSymbolicLink())
84
104
  throw new Error("invalid semantic evidence reservation");
85
- return readFileSync(path, "utf8");
105
+ return readFileSync2(path, "utf8");
86
106
  });
87
107
  const [byId, byRef] = contents;
88
108
  if (byId !== `${ref}
@@ -131,7 +151,7 @@ function resultPath(requestId) {
131
151
  validateResultId(requestId);
132
152
  return join(herdsmanDataRoot(), "results", requestId);
133
153
  }
134
- function persistPeerAttachment(name, text) {
154
+ function peerAttachmentPath(name, text) {
135
155
  if (typeof name !== "string" || !name || name.length > 255 || /[\\/\0]/u.test(name) || typeof text !== "string")
136
156
  throw new Error("invalid peer attachment");
137
157
  const bytes = Buffer.from(text, "utf8");
@@ -143,15 +163,19 @@ function persistPeerAttachment(name, text) {
143
163
  "peers-v2",
144
164
  "received-evidence"
145
165
  );
146
- mkdirSync(directory2, { recursive: true, mode: 448 });
147
- chmodSync(directory2, 448);
148
- const digest = createHash("sha256").update(bytes).digest("hex");
149
- const path = join(directory2, `${digest}-${name}`);
166
+ const digest = createHash2("sha256").update(bytes).digest("hex");
167
+ return join(directory2, `${digest}-${name}`);
168
+ }
169
+ function persistPeerAttachment(name, text) {
170
+ const path = peerAttachmentPath(name, text);
171
+ const bytes = Buffer.from(text, "utf8");
172
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
173
+ chmodSync(dirname(path), 448);
150
174
  try {
151
175
  writeFileSync(path, bytes, { flag: "wx", mode: 384, flush: true });
152
176
  } catch (error) {
153
177
  if (error.code !== "EEXIST") throw error;
154
- if (!readFileSync(path).equals(bytes))
178
+ if (!readFileSync2(path).equals(bytes))
155
179
  throw new Error("peer attachment content identity collision");
156
180
  }
157
181
  return path;
@@ -167,7 +191,7 @@ function persistPeerResultArtifact(canonicalRef, text) {
167
191
  writeFileSync(path, bytes, { flag: "wx", mode: 384, flush: true });
168
192
  } catch (error) {
169
193
  if (error.code !== "EEXIST") throw error;
170
- if (!readFileSync(path).equals(bytes))
194
+ if (!readFileSync2(path).equals(bytes))
171
195
  throw new Error("peer result identity collision");
172
196
  }
173
197
  return path;
@@ -184,20 +208,20 @@ import {
184
208
  readdirSync as readdirSync3,
185
209
  mkdirSync as mkdirSync3,
186
210
  openSync as openSync3,
187
- readFileSync as readFileSync3,
211
+ readFileSync as readFileSync4,
188
212
  readSync,
189
213
  statSync,
190
214
  renameSync as renameSync3,
191
215
  unlinkSync as unlinkSync3,
192
216
  writeFileSync as writeFileSync2
193
217
  } from "node:fs";
194
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
218
+ import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
195
219
  import { basename as basename3, dirname as dirname3, isAbsolute, join as join3, normalize } from "node:path";
196
220
  import { isDeepStrictEqual } from "node:util";
197
221
 
198
222
  // extension/lock.ts
199
223
  import * as fs from "node:fs";
200
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
224
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
201
225
  import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
202
226
  var ProcessLockOccupiedError = class extends Error {
203
227
  code = "PROCESS_LOCK_OCCUPIED";
@@ -532,14 +556,6 @@ function unlinkMetadata(path, entries) {
532
556
  }
533
557
  }
534
558
 
535
- // extension/compatibility.ts
536
- var SHA256 = /^[0-9a-f]{64}$/;
537
- function isRuntimeBuild(value) {
538
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
539
- const record = value;
540
- return Object.keys(record).length === 2 && typeof record.version === "string" && record.version.length > 0 && record.version.length <= 128 && typeof record.sha256 === "string" && SHA256.test(record.sha256);
541
- }
542
-
543
559
  // extension/supervision.ts
544
560
  var COORDINATION_MESSAGE_KINDS = [
545
561
  "chief_message",
@@ -629,7 +645,7 @@ function inboxFor(runtime2, toSessionId) {
629
645
  throw new Error("Invalid Chief message target");
630
646
  return join3(
631
647
  runtime2.inbox,
632
- createHash3("sha256").update(toSessionId).digest("hex")
648
+ createHash4("sha256").update(toSessionId).digest("hex")
633
649
  );
634
650
  }
635
651
  function chiefMessagePath(runtime2, toSessionId, id) {
@@ -642,7 +658,7 @@ function peerDeliveryReceiptPath(runtime2, sessionId, id) {
642
658
  return join3(
643
659
  runtime2.root,
644
660
  "peer-delivery-receipts",
645
- createHash3("sha256").update(sessionId).digest("hex"),
661
+ createHash4("sha256").update(sessionId).digest("hex"),
646
662
  `${id}.json`
647
663
  );
648
664
  }
@@ -669,12 +685,12 @@ function coordinationMessageDigest(record) {
669
685
  peerSource: record.peerSource,
670
686
  createdAt: record.createdAt
671
687
  };
672
- return createHash3("sha256").update(JSON.stringify(canonical(content))).digest("hex");
688
+ return createHash4("sha256").update(JSON.stringify(canonical(content))).digest("hex");
673
689
  }
674
690
  function hasPeerDeliveryReceipt(runtime2, sessionId, id, digest) {
675
691
  try {
676
692
  const receipt = JSON.parse(
677
- readFileSync3(peerDeliveryReceiptPath(runtime2, sessionId, id), "utf8")
693
+ readFileSync4(peerDeliveryReceiptPath(runtime2, sessionId, id), "utf8")
678
694
  );
679
695
  if (receipt.sessionId !== sessionId || receipt.id !== id || receipt.digest !== digest)
680
696
  throw new Error("Conflicting peer delivery receipt");
@@ -722,7 +738,7 @@ function writeOverflowBody(path, body) {
722
738
  const bytes = Buffer.byteLength(content, "utf8");
723
739
  if (bytes > COORDINATION_BODY_MAX_BYTES)
724
740
  throw new Error("Coordination message body is too large");
725
- const sha256 = createHash3("sha256").update(content).digest("hex");
741
+ const sha256 = createHash4("sha256").update(content).digest("hex");
726
742
  try {
727
743
  const stat = lstatSync3(path);
728
744
  if (!stat.isFile() || stat.size > COORDINATION_BODY_MAX_BYTES)
@@ -757,7 +773,7 @@ function writeOverflowBody(path, body) {
757
773
  } finally {
758
774
  closeSync3(fd);
759
775
  }
760
- if (existing.length !== bytes || createHash3("sha256").update(existing).digest("hex") !== sha256)
776
+ if (existing.length !== bytes || createHash4("sha256").update(existing).digest("hex") !== sha256)
761
777
  throw new Error("Coordination message ID already has a different body");
762
778
  } catch (error) {
763
779
  if (error.code !== "ENOENT") throw error;
@@ -784,7 +800,7 @@ function readOverflowBody(path, ref) {
784
800
  if (!count) throw new Error("Coordination message body is truncated");
785
801
  offset += count;
786
802
  }
787
- if (createHash3("sha256").update(bytes).digest("hex") !== ref.sha256)
803
+ if (createHash4("sha256").update(bytes).digest("hex") !== ref.sha256)
788
804
  throw new Error("Coordination message body integrity check failed");
789
805
  const parsed = JSON.parse(
790
806
  new TextDecoder("utf-8", { fatal: true }).decode(bytes)
@@ -906,7 +922,7 @@ function readStoredChiefMessage(path) {
906
922
  if (size > COORDINATION_MESSAGE_MAX_BYTES)
907
923
  throw new Error("Chief message record is too large");
908
924
  try {
909
- const parsed = JSON.parse(readFileSync3(path, "utf8"));
925
+ const parsed = JSON.parse(readFileSync4(path, "utf8"));
910
926
  assertMessage(parsed);
911
927
  return parsed;
912
928
  } catch (error) {
@@ -964,7 +980,7 @@ function socketPath() {
964
980
  }
965
981
  function supervisionRuntime(socket = socketPath()) {
966
982
  if (!socket) throw new Error("HERDR_SOCKET_PATH is required");
967
- const runtimeHash = createHash3("sha256").update(socket).digest("hex");
983
+ const runtimeHash = createHash4("sha256").update(socket).digest("hex");
968
984
  const root = join3(
969
985
  herdsmanDataRoot(),
970
986
  "runtime",
@@ -1023,7 +1039,7 @@ function peerLeadRecordPath(runtime2, piSessionId) {
1023
1039
  }
1024
1040
  function peerLeadRecordFilename(piSessionId) {
1025
1041
  if (!validSession(piSessionId)) throw new Error("Invalid peer session ID");
1026
- return `${createHash3("sha256").update(piSessionId).digest("hex")}.json`;
1042
+ return `${createHash4("sha256").update(piSessionId).digest("hex")}.json`;
1027
1043
  }
1028
1044
  function peerLeadLockPath(runtime2, piSessionId) {
1029
1045
  return `${peerLeadRecordPath(runtime2, piSessionId)}.lock`;
@@ -1072,7 +1088,7 @@ function readPeerLeadRecord(runtime2, piSessionId) {
1072
1088
  const path = peerLeadRecordPath(runtime2, piSessionId);
1073
1089
  let value;
1074
1090
  try {
1075
- const text = readFileSync3(path, "utf8");
1091
+ const text = readFileSync4(path, "utf8");
1076
1092
  if (Buffer.byteLength(text, "utf8") > PEER_LEAD_RECORD_MAX_BYTES)
1077
1093
  throw new Error("peer lead record too large");
1078
1094
  value = JSON.parse(text);
@@ -1099,7 +1115,7 @@ function listPeerLeadRecords(runtime2 = peerRuntime()) {
1099
1115
  try {
1100
1116
  const path = join3(runtime2.peers, entry);
1101
1117
  if (statSync(path).size > PEER_LEAD_RECORD_MAX_BYTES) return [];
1102
- const text = readFileSync3(path, "utf8");
1118
+ const text = readFileSync4(path, "utf8");
1103
1119
  const value = JSON.parse(text);
1104
1120
  if (!validPeerLeadRecord(value) || peerLeadRecordFilename(value.piSessionId) !== entry)
1105
1121
  return [];
@@ -1146,7 +1162,7 @@ function readProjectAssignmentFile(path, repoKey, branch, pending = false) {
1146
1162
  throw new Error("invalid file");
1147
1163
  if (file.size > PROJECT_ASSIGNMENT_FILE_MAX_BYTES)
1148
1164
  throw new Error("file is too large");
1149
- value = JSON.parse(readFileSync3(path, "utf8"));
1165
+ value = JSON.parse(readFileSync4(path, "utf8"));
1150
1166
  } catch (error) {
1151
1167
  if (error.code === "ENOENT") return void 0;
1152
1168
  const reason = error instanceof SyntaxError ? "invalid JSON" : error instanceof Error && error.message === "file is too large" ? error.message : `read failed${safeFilesystemCode(error)}`;
@@ -1163,7 +1179,7 @@ function readProjectAssignmentFile(path, repoKey, branch, pending = false) {
1163
1179
  }
1164
1180
  if (projectAssignmentBytes(value) > PROJECT_ASSIGNMENT_MAX_BYTES)
1165
1181
  throw projectAssignmentReadError(path, "assignment payload is too large");
1166
- if (repoKey !== void 0 && value.repoKey !== repoKey || basename3(dirname3(path)) !== createHash3("sha256").update(value.repoKey).digest("hex") || branch !== void 0 && value.branch !== branch || basename3(path) !== `${createHash3("sha256").update(value.branch).digest("hex")}${pending ? `.${value.id}` : ""}.json`)
1182
+ if (repoKey !== void 0 && value.repoKey !== repoKey || basename3(dirname3(path)) !== createHash4("sha256").update(value.repoKey).digest("hex") || branch !== void 0 && value.branch !== branch || basename3(path) !== `${createHash4("sha256").update(value.branch).digest("hex")}${pending ? `.${value.id}` : ""}.json`)
1167
1183
  throw projectAssignmentReadError(path, "assignment identity mismatch");
1168
1184
  return value;
1169
1185
  }
@@ -1257,7 +1273,7 @@ function scanGlobalProjectAssignments() {
1257
1273
  void 0,
1258
1274
  void 0
1259
1275
  );
1260
- if (!assignment || createHash3("sha256").update(assignment.repoKey).digest("hex") !== repository.name)
1276
+ if (!assignment || createHash4("sha256").update(assignment.repoKey).digest("hex") !== repository.name)
1261
1277
  throw projectAssignmentReadError(
1262
1278
  path,
1263
1279
  "assignment repository hash mismatch"
@@ -1282,7 +1298,7 @@ var LEAD_STATE_MAX_BYTES = COORDINATION_MESSAGE_MAX_BYTES * 2;
1282
1298
 
1283
1299
  // extension/peer-correspondence.ts
1284
1300
  import {
1285
- createHash as createHash5,
1301
+ createHash as createHash6,
1286
1302
  randomBytes,
1287
1303
  randomUUID as randomUUID5,
1288
1304
  timingSafeEqual
@@ -1290,7 +1306,7 @@ import {
1290
1306
  import {
1291
1307
  chmodSync as chmodSync4,
1292
1308
  mkdirSync as mkdirSync4,
1293
- readFileSync as readFileSync4,
1309
+ readFileSync as readFileSync5,
1294
1310
  readdirSync as readdirSync4,
1295
1311
  renameSync as renameSync4,
1296
1312
  unlinkSync as unlinkSync4,
@@ -1299,7 +1315,7 @@ import {
1299
1315
  import { join as join4 } from "node:path";
1300
1316
 
1301
1317
  // extension/peer-transport.ts
1302
- import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
1318
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
1303
1319
  var PEER_TRANSPORT_FRAME_LIMIT_BYTES = 2 * 1024 * 1024;
1304
1320
  var OUTBOUND_RECORD_LIMIT_BYTES = 12 * 1024 * 1024;
1305
1321
  function peerPayloadDigest(value) {
@@ -1313,7 +1329,7 @@ function peerPayloadDigest(value) {
1313
1329
  const object = item;
1314
1330
  return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonical(object[key])}`).join(",")}}`;
1315
1331
  };
1316
- return createHash4("sha256").update(canonical(value), "utf8").digest("hex");
1332
+ return createHash5("sha256").update(canonical(value), "utf8").digest("hex");
1317
1333
  }
1318
1334
 
1319
1335
  // extension/peer-correspondence.ts
@@ -1351,7 +1367,7 @@ function valid(value) {
1351
1367
  c.acceptanceId
1352
1368
  ].every((s) => typeof s === "string" && s.length > 0 && s.length <= 512) && (c.originDisplay === void 0 || validOriginDisplay(c.originDisplay)) && (c.finalized === void 0 || typeof c.finalized === "boolean") && Array.isArray(c.replies) && c.replies.every(
1353
1369
  (reply) => !!reply && ID.test(reply.id) && /^[0-9a-f]{64}$/u.test(reply.digest) && typeof reply.text === "string" && (reply.attachments === void 0 || Array.isArray(reply.attachments) && reply.attachments.every(
1354
- (attachment) => typeof attachment.name === "string" && typeof attachment.marker === "string" && typeof attachment.text === "string" && /^[0-9a-f]{64}$/u.test(attachment.sha256) && createHash5("sha256").update(attachment.text, "utf8").digest("hex") === attachment.sha256
1370
+ (attachment) => typeof attachment.name === "string" && typeof attachment.marker === "string" && typeof attachment.text === "string" && /^[0-9a-f]{64}$/u.test(attachment.sha256) && createHash6("sha256").update(attachment.text, "utf8").digest("hex") === attachment.sha256
1355
1371
  )) && (reply.resultBindings === void 0 || Array.isArray(reply.resultBindings) && reply.resultBindings.every(isResultBinding)) && Number.isFinite(reply.createdAt) && typeof reply.acknowledged === "boolean"
1356
1372
  );
1357
1373
  }
@@ -1420,6 +1436,40 @@ function storePeerCorrespondence(c) {
1420
1436
  }
1421
1437
  save({ ...c, role: c.role ?? "manager" });
1422
1438
  }
1439
+ function readPeerCorrespondence(id) {
1440
+ if (!ID.test(id)) throw new Error("invalid peer correspondence id");
1441
+ const path = join4(
1442
+ herdsmanDataRoot(),
1443
+ "runtime",
1444
+ "peer-correspondences",
1445
+ `${id}.json`
1446
+ );
1447
+ let current;
1448
+ try {
1449
+ current = JSON.parse(readFileSync5(path, "utf8"));
1450
+ } catch (error) {
1451
+ if (error.code === "ENOENT") return void 0;
1452
+ throw error;
1453
+ }
1454
+ if (!valid(current) || current.id !== id)
1455
+ throw new Error("invalid peer correspondence");
1456
+ return current;
1457
+ }
1458
+ function verifyPeerCorrespondence(c) {
1459
+ if (!valid(c)) throw new Error("invalid peer correspondence");
1460
+ const current = readPeerCorrespondence(c.id);
1461
+ if (!valid(current) || current.finalized || (current.role ?? "manager") !== (c.role ?? "manager") || [
1462
+ "capability",
1463
+ "originSession",
1464
+ "originGeneration",
1465
+ "recipientSession",
1466
+ "recipientGeneration",
1467
+ "acceptanceId"
1468
+ ].some(
1469
+ (key) => current[key] !== c[key]
1470
+ ))
1471
+ throw new Error("conflicting peer correspondence");
1472
+ }
1423
1473
  function updatePeerOriginGeneration(id, capability, originSession, oldGeneration, newGeneration) {
1424
1474
  if (!newGeneration) throw new Error("peer correspondence recovery rejected");
1425
1475
  return mutate(id, (c) => {
@@ -1451,7 +1501,7 @@ function listPeerCorrespondences() {
1451
1501
  return [];
1452
1502
  try {
1453
1503
  const c = JSON.parse(
1454
- readFileSync4(join4(directory(), name), "utf8")
1504
+ readFileSync5(join4(directory(), name), "utf8")
1455
1505
  );
1456
1506
  return valid(c) ? [c] : [];
1457
1507
  } catch {
@@ -1467,7 +1517,7 @@ function matchesCapability(actual, expected) {
1467
1517
  if (timingSafeEqual(actualBytes, expectedBytes)) return true;
1468
1518
  return timingSafeEqual(
1469
1519
  Buffer.from(
1470
- createHash5("sha256").update(expectedBytes).digest("hex"),
1520
+ createHash6("sha256").update(expectedBytes).digest("hex"),
1471
1521
  "hex"
1472
1522
  ),
1473
1523
  actualBytes
@@ -1522,7 +1572,7 @@ function finalizePeerCorrespondence(id, capability, originSession, originGenerat
1522
1572
  "cannot finalize peer correspondence with pending replies"
1523
1573
  );
1524
1574
  if (c.finalized) return;
1525
- c.capability = createHash5("sha256").update(Buffer.from(capability, "hex")).digest("hex");
1575
+ c.capability = createHash6("sha256").update(Buffer.from(capability, "hex")).digest("hex");
1526
1576
  c.replies = [];
1527
1577
  c.finalized = true;
1528
1578
  });
@@ -1575,6 +1625,22 @@ if (!isAbsolute2(agentDir)) {
1575
1625
  process.exit(1);
1576
1626
  }
1577
1627
  var runtime = peerRuntime();
1628
+ var bridgeDirectory = dirname4(fileURLToPath2(import.meta.url));
1629
+ var packageRoot = dirname4(bridgeDirectory);
1630
+ var compatible = (peer) => {
1631
+ try {
1632
+ const metadata = JSON.parse(
1633
+ readFileSync6(join5(packageRoot, "package.json"), "utf8")
1634
+ );
1635
+ const build = runtimeBuild(
1636
+ metadata.version,
1637
+ basename4(bridgeDirectory) === "bin" ? join5(packageRoot, "extension", "index.ts") : join5(packageRoot, "dist", "index.js")
1638
+ );
1639
+ return isRuntimeBuild(build) && isRuntimeBuild(peer.build) && sameRuntimeBuild(build, peer.build);
1640
+ } catch {
1641
+ return false;
1642
+ }
1643
+ };
1578
1644
  var recoveringStatus = false;
1579
1645
  var syncDirectory = (directory2) => {
1580
1646
  if (process.platform === "win32") return;
@@ -1623,10 +1689,10 @@ if (action === "probe") {
1623
1689
  assertPeerDataRoot(herdsmanDataRoot(), expectedDataRoot ?? "");
1624
1690
  if (!process.env.SSH_CONNECTION || typeof id !== "string" || typeof originSession !== "string" || typeof recipientSession !== "string" || typeof digest2 !== "string" || !/^[0-9a-f]{64}$/u.test(digest2))
1625
1691
  throw new Error("invalid peer acceptance status request");
1626
- const key2 = createHash6("sha256").update(`${originSession}\0${id}`).digest("hex");
1692
+ const key2 = createHash7("sha256").update(`${originSession}\0${id}`).digest("hex");
1627
1693
  const marker2 = join5(runtime.root, "peer-acceptances", `${key2}.json`);
1628
1694
  try {
1629
- const prior = JSON.parse(readFileSync5(marker2, "utf8"));
1695
+ const prior = JSON.parse(readFileSync6(marker2, "utf8"));
1630
1696
  const status = prior.digest !== digest2 || prior.recipientSession !== recipientSession ? "conflict" : prior.status === "accepted" ? "accepted" : prior.status === "pending" ? "pending" : "conflict";
1631
1697
  if (status === "pending" && prior.transfer) {
1632
1698
  envelope = prior.transfer;
@@ -1666,15 +1732,13 @@ if (action === "probe") {
1666
1732
  assertPeerDataRoot(herdsmanDataRoot(), envelope.expectedDataRoot ?? "");
1667
1733
  const liveRecipientGeneration = action === "recover-recipient" ? envelope.newRecipientGeneration : recipientGeneration;
1668
1734
  const runCorrespondenceOperation = (assignments) => {
1669
- const correspondence = listPeerCorrespondences().find(
1670
- (item) => item.id === id
1671
- );
1735
+ const correspondence = readPeerCorrespondence(id);
1672
1736
  const correspondenceRole2 = correspondence?.role ?? "manager";
1673
1737
  const live = listPeerLeadRecords(runtime).find(
1674
1738
  (peer) => peer.piSessionId === recipientSession && peer.claim.id === liveRecipientGeneration
1675
1739
  );
1676
1740
  const recipientIsLive = !!live && (correspondenceRole2 === "manager" ? live.role === "manager" : correspondenceRole2 === "lead" && !!assignments && isRemoteOrdinaryLead(live, assignments));
1677
- if (!recipientIsLive || !correspondence || correspondenceRole2 !== (correspondence?.role ?? "manager") || correspondence.originSession !== originSession || correspondence.recipientSession !== recipientSession || correspondence.capability !== capability)
1741
+ if (!recipientIsLive || action !== "poll" && !compatible(live) || !correspondence || correspondenceRole2 !== (correspondence?.role ?? "manager") || correspondence.originSession !== originSession || correspondence.recipientSession !== recipientSession || correspondence.capability !== capability)
1678
1742
  throw new Error(
1679
1743
  "exact correspondence recipient is not live or authorized"
1680
1744
  );
@@ -1731,7 +1795,7 @@ if (action === "probe") {
1731
1795
  JSON.stringify({
1732
1796
  dataRoot: herdsmanDataRoot(),
1733
1797
  replies,
1734
- hasReplies: (listPeerCorrespondences().find((item) => item.id === id)?.replies.length ?? 0) > 0
1798
+ hasReplies: (readPeerCorrespondence(id)?.replies.length ?? 0) > 0
1735
1799
  })
1736
1800
  );
1737
1801
  } else if (action === "ack") {
@@ -1761,7 +1825,7 @@ if (action === "probe") {
1761
1825
  console.log(JSON.stringify({ finalized: true, id }));
1762
1826
  }
1763
1827
  };
1764
- const role = listPeerCorrespondences().find((item) => item.id === id)?.role ?? "manager";
1828
+ const role = readPeerCorrespondence(id)?.role ?? "manager";
1765
1829
  if (role === "lead") {
1766
1830
  withProjectAssignmentAuthority(
1767
1831
  (assignments) => runCorrespondenceOperation(assignments)
@@ -1791,13 +1855,11 @@ if (action === "probe") {
1791
1855
  attachments: envelope.attachments
1792
1856
  });
1793
1857
  const markerDir = join5(runtime.root, "peer-acceptances");
1794
- mkdirSync5(markerDir, { recursive: true, mode: 448 });
1795
- syncDirectory(runtime.root);
1796
- const key = createHash6("sha256").update(`${record.fromSessionId}\0${record.id}`).digest("hex");
1858
+ const key = createHash7("sha256").update(`${record.fromSessionId}\0${record.id}`).digest("hex");
1797
1859
  const marker = join5(markerDir, `${key}.json`);
1798
1860
  let acceptedRace = false;
1799
1861
  try {
1800
- const prior = JSON.parse(readFileSync5(marker, "utf8"));
1862
+ const prior = JSON.parse(readFileSync6(marker, "utf8"));
1801
1863
  if (prior.digest !== digest || prior.recipientSession !== record.toSessionId)
1802
1864
  throw new Error("conflicting peer message identity");
1803
1865
  if (prior.status === "accepted") {
@@ -1820,10 +1882,12 @@ if (action === "probe") {
1820
1882
  const authorized = liveRecipient && (correspondenceRole === "manager" ? liveRecipient.role === "manager" : withProjectAssignmentAuthority(
1821
1883
  (assignments) => isRemoteOrdinaryLead(liveRecipient, assignments)
1822
1884
  ));
1823
- if (!authorized)
1885
+ if (!authorized || !compatible(liveRecipient))
1824
1886
  throw new Error(
1825
1887
  "exact correspondence recipient is not live or authorized"
1826
1888
  );
1889
+ mkdirSync5(markerDir, { recursive: true, mode: 448 });
1890
+ syncDirectory(runtime.root);
1827
1891
  const content = `${JSON.stringify({ connection, digest, status: "pending", recipientSession: record.toSessionId, transfer: envelope })}
1828
1892
  `;
1829
1893
  const temp = `${marker}.${randomUUID6()}.tmp`;
@@ -1858,7 +1922,7 @@ if (action === "probe") {
1858
1922
  }
1859
1923
  syncDirectory(markerDir);
1860
1924
  if (alreadyExists) {
1861
- const prior = JSON.parse(readFileSync5(marker, "utf8"));
1925
+ const prior = JSON.parse(readFileSync6(marker, "utf8"));
1862
1926
  if (prior.digest !== digest || prior.recipientSession !== record.toSessionId)
1863
1927
  throw new Error("conflicting peer message identity");
1864
1928
  if (prior.status === "accepted") acceptedRace = true;
@@ -1887,7 +1951,7 @@ if (action === "probe") {
1887
1951
  for (const attachment of envelope.attachments) {
1888
1952
  if (typeof attachment.name !== "string" || typeof attachment.marker !== "string" || typeof attachment.text !== "string" || typeof attachment.sha256 !== "string" || !/^[0-9a-f]{64}$/u.test(attachment.sha256))
1889
1953
  throw new Error("invalid peer attachment metadata");
1890
- const contentDigest = createHash6("sha256").update(attachment.text, "utf8").digest("hex");
1954
+ const contentDigest = createHash7("sha256").update(attachment.text, "utf8").digest("hex");
1891
1955
  if (contentDigest !== attachment.sha256)
1892
1956
  throw new Error("peer attachment integrity check failed");
1893
1957
  const markerIndex = receivedText.indexOf(attachment.marker);
@@ -1897,7 +1961,9 @@ if (action === "probe") {
1897
1961
  const binding = record.resultBindings?.find(
1898
1962
  (item) => item.ref === attachment.ref
1899
1963
  );
1900
- const path = binding ? persistPeerResultArtifact(binding.canonicalRef, attachment.text) : persistPeerAttachment(attachment.name, attachment.text);
1964
+ if (binding && !isCanonicalResultRef(binding.canonicalRef))
1965
+ throw new Error("invalid peer result artifact");
1966
+ const path = binding ? resultPath(binding.canonicalRef.slice("result:".length)) : peerAttachmentPath(attachment.name, attachment.text);
1901
1967
  receivedRefs.push(
1902
1968
  `${attachment.name}: ${binding ? `${binding.ref} (canonical ${binding.canonicalRef})` : path}`
1903
1969
  );
@@ -1937,7 +2003,7 @@ ${receivedRefs.join("\n")}`
1937
2003
  const liveRecipient = listPeerLeadRecords(runtime).find(
1938
2004
  (peer) => peer.piSessionId === record.toSessionId
1939
2005
  );
1940
- if (!liveRecipient)
2006
+ if (!liveRecipient || !compatible(liveRecipient))
1941
2007
  throw new Error(
1942
2008
  correspondenceRole === "manager" ? "exact destination Manager is not live" : "exact correspondence recipient is not live"
1943
2009
  );
@@ -1964,46 +2030,85 @@ ${receivedRefs.join("\n")}`
1964
2030
  }
1965
2031
  syncDirectory(markerDir);
1966
2032
  }
2033
+ for (const attachment of envelope.attachments) {
2034
+ const binding = record.resultBindings?.find(
2035
+ (item) => item.ref === attachment.ref
2036
+ );
2037
+ if (binding)
2038
+ persistPeerResultArtifact(
2039
+ binding.canonicalRef,
2040
+ attachment.text
2041
+ );
2042
+ else
2043
+ persistPeerAttachment(
2044
+ attachment.name,
2045
+ attachment.text
2046
+ );
2047
+ }
2048
+ } else {
2049
+ for (const attachment of envelope.attachments) {
2050
+ const binding = record.resultBindings?.find(
2051
+ (item) => item.ref === attachment.ref
2052
+ );
2053
+ const path = binding ? resultPath(binding.canonicalRef.slice("result:".length)) : peerAttachmentPath(
2054
+ attachment.name,
2055
+ attachment.text
2056
+ );
2057
+ if (!readFileSync6(path).equals(
2058
+ Buffer.from(attachment.text, "utf8")
2059
+ ))
2060
+ throw new Error("peer attachment content identity collision");
2061
+ }
2062
+ verifyPeerCorrespondence(envelope.correspondence);
1967
2063
  }
1968
2064
  const publish = () => {
1969
2065
  if (published && correspondenceRole === "manager") {
1970
- storePeerCorrespondence(envelope.correspondence);
1971
2066
  return;
1972
2067
  }
1973
2068
  const current = listPeerLeadRecords(runtime).find(
1974
2069
  (peer) => peer.piSessionId === record.toSessionId && peer.claim.id === envelope.recipientClaimId
1975
2070
  );
1976
2071
  const authorized = current && (correspondenceRole === "manager" ? current.role === "manager" : isRemoteOrdinaryLead(current, globalProjectAssignmentSnapshot()));
1977
- if (!authorized)
2072
+ if (!authorized || !published && !compatible(current))
1978
2073
  throw new Error(
1979
2074
  "exact correspondence recipient is not live or authorized"
1980
2075
  );
1981
- storePeerCorrespondence(envelope.correspondence);
1982
- if (!published && !hasPeerDeliveryReceipt(
1983
- runtime,
1984
- record.toSessionId,
1985
- record.id,
1986
- acceptedDigest
1987
- ))
1988
- writeCoordinationMessage(accepted, runtime);
2076
+ if (!published) {
2077
+ if (hasPeerDeliveryReceipt(
2078
+ runtime,
2079
+ record.toSessionId,
2080
+ record.id,
2081
+ acceptedDigest
2082
+ ))
2083
+ verifyPeerCorrespondence(envelope.correspondence);
2084
+ else {
2085
+ storePeerCorrespondence(envelope.correspondence);
2086
+ writeCoordinationMessage(accepted, runtime);
2087
+ }
2088
+ }
1989
2089
  };
1990
2090
  if (correspondenceRole === "lead") {
1991
2091
  withProjectAssignmentAuthority((assignments) => {
1992
2092
  const current = listPeerLeadRecords(runtime).find(
1993
2093
  (peer) => peer.piSessionId === record.toSessionId && peer.claim.id === envelope.recipientClaimId
1994
2094
  );
1995
- if (!current || !isRemoteOrdinaryLead(current, assignments))
2095
+ if (!current || !isRemoteOrdinaryLead(current, assignments) || !published && !compatible(current))
1996
2096
  throw new Error(
1997
2097
  "exact correspondence recipient is not live or authorized"
1998
2098
  );
1999
- storePeerCorrespondence(envelope.correspondence);
2000
- if (!published && !hasPeerDeliveryReceipt(
2001
- runtime,
2002
- record.toSessionId,
2003
- record.id,
2004
- acceptedDigest
2005
- ))
2006
- writeCoordinationMessage(accepted, runtime);
2099
+ if (!published) {
2100
+ if (hasPeerDeliveryReceipt(
2101
+ runtime,
2102
+ record.toSessionId,
2103
+ record.id,
2104
+ acceptedDigest
2105
+ ))
2106
+ verifyPeerCorrespondence(envelope.correspondence);
2107
+ else {
2108
+ storePeerCorrespondence(envelope.correspondence);
2109
+ writeCoordinationMessage(accepted, runtime);
2110
+ }
2111
+ }
2007
2112
  });
2008
2113
  } else publish();
2009
2114
  if (!published) afterDurablePeerAcceptanceStep("inbox-publication-durable");