opencode-swarm 7.164.11 → 7.164.12
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/.opencode/skills/engineering-conventions/SKILL.md +1 -1
- package/dist/background/pending-delegations.d.ts +7 -2
- package/dist/background/pr-subscriptions.d.ts +3 -3
- package/dist/cli/{coder-settlement-0rfk8y11.js → coder-settlement-yh1q5fr3.js} +15 -16
- package/dist/cli/{config-doctor-j17b7qq2.js → config-doctor-bd4yzmh7.js} +3 -3
- package/dist/cli/{core-evhjjrtt.js → core-y0s1vmyc.js} +2 -2
- package/dist/cli/{curation-policy-vj6z5hvr.js → curation-policy-gs1qakn7.js} +5 -6
- package/dist/cli/{curator-vqd5yeck.js → curator-brqack0j.js} +48 -46
- package/dist/cli/{curator-drift-ez81vg2t.js → curator-drift-1sg9yk2m.js} +14 -12
- package/dist/cli/curator-llm-factory-dtsjc3zf.js +70 -0
- package/dist/cli/{dispatch-dqybvj8v.js → dispatch-c7xjt7js.js} +3 -3
- package/dist/cli/{evidence-summary-service-937x7rbg.js → evidence-summary-service-nqbcvp30.js} +24 -23
- package/dist/cli/{gate-evidence-q1cehr4k.js → gate-evidence-9stdtpej.js} +9 -10
- package/dist/cli/guardrail-explain-3ff1z3fm.js +71 -0
- package/dist/cli/{guardrail-log-3g93f3g2.js → guardrail-log-sf39x00b.js} +10 -10
- package/dist/cli/{guardrail-reset-qe2r5qzq.js → guardrail-reset-9wr6a60s.js} +48 -46
- package/dist/cli/hive-promoter-bqtj8261.js +85 -0
- package/dist/cli/{index-kv2tdkk5.js → index-03enxdaq.js} +1 -1
- package/dist/cli/{index-ggrp3v00.js → index-0byep4pe.js} +15 -17
- package/dist/cli/{index-2bgr671r.js → index-2bhz5k91.js} +20 -2
- package/dist/cli/{index-mmjamc9b.js → index-3fnym6ac.js} +5 -5
- package/dist/cli/{index-d9entpn3.js → index-40twgsyh.js} +4 -4
- package/dist/cli/{index-ggtmsm84.js → index-4mjmnysc.js} +1 -1
- package/dist/cli/{index-e90em0x4.js → index-4vb56w2k.js} +12 -17
- package/dist/cli/{index-r656jh9j.js → index-5wc5pbzc.js} +3700 -2609
- package/dist/cli/{index-w3gtqey0.js → index-6chhqq2n.js} +4 -4
- package/dist/cli/{index-qbw3yw2d.js → index-888pq4xx.js} +11 -11
- package/dist/cli/{index-3146wmgv.js → index-8d90gzaz.js} +1 -1
- package/dist/cli/{index-5jx22kwc.js → index-8vw2pjgr.js} +544 -15
- package/dist/cli/{index-b2nj04q6.js → index-9ss2m4rs.js} +1 -434
- package/dist/cli/{index-x43debgx.js → index-ad9064j9.js} +15 -17
- package/dist/cli/{index-5kcvrpkt.js → index-b25t91a3.js} +1 -1
- package/dist/cli/index-c45662wc.js +361 -0
- package/dist/cli/{index-aqppaaqx.js → index-cgewrpw5.js} +3 -2
- package/dist/cli/{index-zfs3zqeq.js → index-d3mpxsmy.js} +771 -21
- package/dist/cli/{index-y1yqmkv7.js → index-d7j3n5ra.js} +52 -50
- package/dist/cli/{index-4vb6qa73.js → index-ebce775n.js} +36 -2
- package/dist/cli/{index-dsg9dw3b.js → index-eed0gkv6.js} +2 -2
- package/dist/cli/index-es64amqt.js +675 -0
- package/dist/cli/{index-9gxbjkts.js → index-ewv8qa8q.js} +22 -19
- package/dist/cli/{index-1ww7wj8d.js → index-hb7bh4r2.js} +15 -15
- package/dist/cli/{index-kc2tgcm7.js → index-hg09xemc.js} +4 -4
- package/dist/cli/{index-w95vxjde.js → index-hvz4ad2t.js} +39 -8
- package/dist/cli/{index-77z98j76.js → index-k0s8n6m5.js} +314 -130
- package/dist/cli/{index-7m32fjb4.js → index-kxv193aq.js} +9 -9
- package/dist/cli/{index-hp22pzn5.js → index-m8xrbdmn.js} +2 -2
- package/dist/cli/{index-4gqxppcx.js → index-mee9maf5.js} +2 -2
- package/dist/cli/{index-r3mvsbtq.js → index-p612v1mv.js} +7 -1
- package/dist/cli/{index-r5q5gd2a.js → index-qgajv9rd.js} +2 -2
- package/dist/cli/{index-zjg4chy2.js → index-qqq04n70.js} +2 -2
- package/dist/cli/{index-ww6zm5hr.js → index-r2p0pgst.js} +3 -3
- package/dist/cli/{index-47kh2103.js → index-r69gzes2.js} +14 -14
- package/dist/cli/{index-vdn32nws.js → index-sphahrmq.js} +3 -3
- package/dist/cli/{index-rhqdsc1x.js → index-vw66q1rw.js} +9 -9
- package/dist/cli/{index-kch6yenm.js → index-wasdrhev.js} +7 -7
- package/dist/cli/{index-c5v1w13g.js → index-wknpkfm8.js} +807 -629
- package/dist/cli/{index-pp2nya9v.js → index-x39hjdf1.js} +2 -4
- package/dist/cli/{index-n8688d12.js → index-xxfk62zd.js} +2 -2
- package/dist/cli/index-yvqg6kn5.js +429 -0
- package/dist/cli/{index-nqsj0g5y.js → index-ztm0q26v.js} +8 -8
- package/dist/cli/index.js +50 -48
- package/dist/cli/{knowledge-escalator-j04g450p.js → knowledge-escalator-01vva51d.js} +17 -18
- package/dist/cli/{knowledge-events-53z45rs0.js → knowledge-events-dpfwh1hs.js} +15 -16
- package/dist/cli/{knowledge-link-a6kfg3qm.js → knowledge-link-2rvp966j.js} +4 -5
- package/dist/cli/{knowledge-store-whm0gagt.js → knowledge-store-aw58ae7b.js} +6 -7
- package/dist/cli/{knowledge-validator-h8m7065g.js → knowledge-validator-yhd31ryf.js} +8 -9
- package/dist/cli/{pending-delegations-6hkpe5ze.js → pending-delegations-fjetcz8e.js} +17 -8
- package/dist/cli/{pr-subscriptions-11zca1mh.js → pr-subscriptions-cwwtfs8w.js} +17 -8
- package/dist/cli/{pr-workflow-gate-6g29rkg7.js → pr-workflow-gate-5xwtg1k2.js} +50 -48
- package/dist/cli/{runner-5abw3t35.js → runner-mb51twxt.js} +6 -7
- package/dist/cli/{scan-cursor-mkfx410t.js → scan-cursor-j11qwf0v.js} +9 -10
- package/dist/cli/{schema-jbbam3ev.js → schema-0xp3bde3.js} +1 -1
- package/dist/cli/{scope-persistence-q1ct4k42.js → scope-persistence-brrk806y.js} +19 -12
- package/dist/cli/{skill-generator-cv8fg96x.js → skill-generator-j8qzmet9.js} +20 -21
- package/dist/cli/snapshot-coordination-init-h0xmtftq.js +84 -0
- package/dist/cli/{telemetry-mbqqamsj.js → telemetry-m84ap0pp.js} +1 -1
- package/dist/cli/{workspace-snapshot-eh18vgkn.js → workspace-snapshot-6z9rk7xw.js} +3 -3
- package/dist/cli/{worktree-collision-ownership-xgnn8dsq.js → worktree-collision-ownership-j9zykj18.js} +21 -12
- package/dist/cli/{worktree-isolation-k2dgfmeg.js → worktree-isolation-jd39xz6h.js} +48 -46
- package/dist/commands/close.d.ts +13 -6
- package/dist/commands/reset-session.d.ts +4 -0
- package/dist/db/coordination-store.d.ts +85 -0
- package/dist/db/durability.d.ts +22 -5
- package/dist/db/index.d.ts +1 -0
- package/dist/db/project-db.d.ts +12 -0
- package/dist/index.js +810 -705
- package/dist/memory/schema.d.ts +3 -3
- package/dist/pr-review/authorization.d.ts +5 -4
- package/dist/pr-review/persistence.d.ts +10 -1
- package/dist/scope/scope-binding.d.ts +10 -0
- package/dist/scope/scope-persistence.d.ts +10 -0
- package/dist/services/handoff-service.d.ts +2 -0
- package/dist/services/status-service.d.ts +4 -0
- package/dist/session/snapshot-coordination-init.d.ts +49 -0
- package/dist/session/snapshot-reader.d.ts +2 -0
- package/dist/session/snapshot-store.d.ts +42 -0
- package/dist/session/snapshot-writer.d.ts +4 -1
- package/dist/state.d.ts +6 -3
- package/dist/turbo/epic/state.d.ts +4 -20
- package/dist/utils/bun-compat.d.ts +10 -0
- package/dist/utils/external-tool-runner.d.ts +2 -0
- package/package.json +3 -2
- package/dist/cli/curator-llm-factory-sxcpmcqq.js +0 -68
- package/dist/cli/guardrail-explain-xv9aw1bf.js +0 -69
- package/dist/cli/hive-promoter-09yc9mp5.js +0 -83
- package/dist/cli/index-xnb3tk7x.js +0 -24
- package/dist/cli/{ast-diff-ekd9v10f.js → ast-diff-b0esr2kf.js} +3 -3
|
@@ -1,13 +1,31 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import {
|
|
3
3
|
validateSwarmPath
|
|
4
|
-
} from "./index-
|
|
4
|
+
} from "./index-qqq04n70.js";
|
|
5
5
|
import {
|
|
6
6
|
bunWrite
|
|
7
|
-
} from "./index-
|
|
7
|
+
} from "./index-p612v1mv.js";
|
|
8
|
+
import {
|
|
9
|
+
MAX_COORDINATION_STATE_LIST_ROWS,
|
|
10
|
+
acquireCoordinationLease,
|
|
11
|
+
countCoordinationStates,
|
|
12
|
+
deleteCoordinationState,
|
|
13
|
+
deleteCoordinationStateWithinTransaction,
|
|
14
|
+
getCoordinationLease,
|
|
15
|
+
getCoordinationState,
|
|
16
|
+
importCoordinationOnce,
|
|
17
|
+
listCoordinationStates,
|
|
18
|
+
releaseCoordinationLease,
|
|
19
|
+
transitionCoordinationState,
|
|
20
|
+
withCoordinationTransaction
|
|
21
|
+
} from "./index-c45662wc.js";
|
|
22
|
+
import {
|
|
23
|
+
getProjectDb,
|
|
24
|
+
projectDbExists
|
|
25
|
+
} from "./index-es64amqt.js";
|
|
8
26
|
import {
|
|
9
27
|
observeDelegationLedgerPressure
|
|
10
|
-
} from "./index-
|
|
28
|
+
} from "./index-eed0gkv6.js";
|
|
11
29
|
import {
|
|
12
30
|
canonicalRootKeyFresh,
|
|
13
31
|
sameProjectRoot
|
|
@@ -15,7 +33,7 @@ import {
|
|
|
15
33
|
import {
|
|
16
34
|
EvidenceLockTimeoutError,
|
|
17
35
|
withEvidenceLock
|
|
18
|
-
} from "./index-
|
|
36
|
+
} from "./index-2bhz5k91.js";
|
|
19
37
|
import {
|
|
20
38
|
exports_external,
|
|
21
39
|
init_zod
|
|
@@ -1073,6 +1091,9 @@ var MAX_BACKGROUND_OBSERVED_FILES = 5000;
|
|
|
1073
1091
|
var MAX_BACKGROUND_ADVISORY_CHARS = 4000;
|
|
1074
1092
|
var LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER = "legacy coder settlement transfer is pending";
|
|
1075
1093
|
var MAX_BACKGROUND_DELEGATION_GENERATION = 1e6;
|
|
1094
|
+
var DELEGATION_COORDINATION_NAMESPACE = "background.pending-delegation";
|
|
1095
|
+
var RESERVATION_COORDINATION_NAMESPACE = "background.coder-reservation";
|
|
1096
|
+
var RESERVATION_LEASE_NAMESPACE = "background.coder-reservation.lease";
|
|
1076
1097
|
var MAX_RECOVERY_FALLBACK_BYTES = 1024 * 1024;
|
|
1077
1098
|
var MAX_TRACKED_LENIENT_LEDGER_SIGNALS = 32;
|
|
1078
1099
|
var LENIENT_LEDGER_SIGNAL_SOURCE = "lenient-read";
|
|
@@ -1081,6 +1102,8 @@ var DELEGATION_COMPACTION_HIGH_WATER_BYTES = 1024 * 1024;
|
|
|
1081
1102
|
var MAX_CHECKPOINT_BYTES = 2 * 1024 * 1024;
|
|
1082
1103
|
var CHECKPOINT_SELECTION_RESERVE_BYTES = 64 * 1024;
|
|
1083
1104
|
var MAX_CHECKPOINT_RECORDS = 2048;
|
|
1105
|
+
var MAX_COORDINATION_DELEGATION_ROWS = MAX_CHECKPOINT_RECORDS * 2;
|
|
1106
|
+
var MAX_COORDINATION_TERMINAL_ROWS = MAX_CHECKPOINT_RECORDS;
|
|
1084
1107
|
var TOMBSTONE_MIN_AGE_MS = 72 * 60 * 60 * 1000;
|
|
1085
1108
|
var STORE_LOCK_AGENT = "background";
|
|
1086
1109
|
var STORE_LOCK_TASK = "background-delegations";
|
|
@@ -1174,7 +1197,7 @@ var WorktreeDescriptorSchema = exports_external.object({
|
|
|
1174
1197
|
}).strict();
|
|
1175
1198
|
var TerminalResultSchema = exports_external.object({
|
|
1176
1199
|
eventId: exports_external.string().min(1).max(256),
|
|
1177
|
-
status: exports_external.enum(["completed", "error", "cancelled"]),
|
|
1200
|
+
status: exports_external.enum(["completed", "error", "cancelled", "rejected"]),
|
|
1178
1201
|
recordedAt: exports_external.number().int().nonnegative(),
|
|
1179
1202
|
result: ResultSchema
|
|
1180
1203
|
}).strict();
|
|
@@ -1343,6 +1366,7 @@ var RecordSchema = exports_external.object({
|
|
|
1343
1366
|
"pending",
|
|
1344
1367
|
"running",
|
|
1345
1368
|
"ingestion_error",
|
|
1369
|
+
"rejected",
|
|
1346
1370
|
"completed",
|
|
1347
1371
|
"error",
|
|
1348
1372
|
"cancelled",
|
|
@@ -1406,6 +1430,173 @@ function checkpointPath(directory) {
|
|
|
1406
1430
|
function manifestPath(directory) {
|
|
1407
1431
|
return validateSwarmPath(directory, BACKGROUND_DELEGATIONS_MANIFEST_FILE);
|
|
1408
1432
|
}
|
|
1433
|
+
function importedShadowPath(filePath) {
|
|
1434
|
+
return `${filePath}.imported`;
|
|
1435
|
+
}
|
|
1436
|
+
function projectionMarkerPath(filePath) {
|
|
1437
|
+
return `${filePath}.sqlite-projection`;
|
|
1438
|
+
}
|
|
1439
|
+
function coordinationReservationLeaseKey(reservation) {
|
|
1440
|
+
return {
|
|
1441
|
+
namespace: RESERVATION_LEASE_NAMESPACE,
|
|
1442
|
+
entityKey: reservation.reservationId,
|
|
1443
|
+
generation: reservation.generation ?? 1,
|
|
1444
|
+
ownerToken: reservation.reservationId
|
|
1445
|
+
};
|
|
1446
|
+
}
|
|
1447
|
+
function releaseReservationLeaseIfPresent(directory, reservation) {
|
|
1448
|
+
const leaseKey = coordinationReservationLeaseKey(reservation);
|
|
1449
|
+
const existing = getCoordinationLease(directory, leaseKey.namespace, leaseKey.entityKey);
|
|
1450
|
+
if (!existing)
|
|
1451
|
+
return;
|
|
1452
|
+
if (existing.generation !== leaseKey.generation || existing.ownerToken !== leaseKey.ownerToken || !releaseCoordinationLease(directory, leaseKey.namespace, leaseKey.entityKey, leaseKey.generation, leaseKey.ownerToken)) {
|
|
1453
|
+
throw new Error(`reservation lease authority mismatch for ${reservation.reservationId}`);
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
function coordinationRowsToDelegations(directory) {
|
|
1457
|
+
if (!projectDbExists(directory))
|
|
1458
|
+
return null;
|
|
1459
|
+
try {
|
|
1460
|
+
const rows = listCoordinationStates(directory, DELEGATION_COORDINATION_NAMESPACE, MAX_COORDINATION_STATE_LIST_ROWS);
|
|
1461
|
+
if (rows.length >= MAX_COORDINATION_STATE_LIST_ROWS) {
|
|
1462
|
+
throw new Error(`delegation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);
|
|
1463
|
+
}
|
|
1464
|
+
return rows.map((row) => {
|
|
1465
|
+
const parsed = RecordSchema.safeParse(JSON.parse(row.payload));
|
|
1466
|
+
if (!parsed.success || parsed.data.correlationId !== row.entityKey || Math.max(parsed.data.generation ?? 1, 1) !== row.generation || parsed.data.status !== row.status) {
|
|
1467
|
+
throw new Error(`delegation coordination row failed schema or authority binding validation for ${row.entityKey}`);
|
|
1468
|
+
}
|
|
1469
|
+
return parsed.data;
|
|
1470
|
+
}).sort((left, right) => left.createdAt === right.createdAt ? left.correlationId.localeCompare(right.correlationId) : left.createdAt - right.createdAt);
|
|
1471
|
+
} catch (error) {
|
|
1472
|
+
recordLedgerUncertainty(directory, error instanceof Error ? error.message : String(error), "coordination-read");
|
|
1473
|
+
return null;
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
function archiveShadowFileBestEffort(filePath) {
|
|
1477
|
+
if (!fs2.existsSync(filePath))
|
|
1478
|
+
return;
|
|
1479
|
+
const importedPath = importedShadowPath(filePath);
|
|
1480
|
+
try {
|
|
1481
|
+
if (fs2.existsSync(importedPath))
|
|
1482
|
+
return;
|
|
1483
|
+
fs2.renameSync(filePath, importedPath);
|
|
1484
|
+
} catch (error) {
|
|
1485
|
+
warn(`[background] shadow archive failed for ${path2.basename(filePath)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
function writeDelegationShadowProjection(directory, records) {
|
|
1489
|
+
ensureSwarmDir(directory);
|
|
1490
|
+
const payload = records.map((record) => JSON.stringify(record)).join(`
|
|
1491
|
+
`) + (records.length > 0 ? `
|
|
1492
|
+
` : "");
|
|
1493
|
+
fs2.writeFileSync(storePath(directory), payload, "utf-8");
|
|
1494
|
+
fs2.writeFileSync(projectionMarkerPath(storePath(directory)), "", "utf-8");
|
|
1495
|
+
}
|
|
1496
|
+
function loadLegacyDelegationsStrict(directory) {
|
|
1497
|
+
const load = loadFoldedState(directory, { strict: true });
|
|
1498
|
+
if (load.status === "uncertain") {
|
|
1499
|
+
recordLedgerUncertainty(directory, load.reason, "legacy-import", load.repairHint);
|
|
1500
|
+
return null;
|
|
1501
|
+
}
|
|
1502
|
+
return [...load.records.values()];
|
|
1503
|
+
}
|
|
1504
|
+
function delegationShadowMatches(directory, records) {
|
|
1505
|
+
const load = loadFoldedState(directory, { strict: false });
|
|
1506
|
+
if (load.status === "uncertain")
|
|
1507
|
+
return false;
|
|
1508
|
+
return isDeepStrictEqual([...load.records.values()].sort((left, right) => left.correlationId.localeCompare(right.correlationId)), [...records].sort((left, right) => left.correlationId.localeCompare(right.correlationId)));
|
|
1509
|
+
}
|
|
1510
|
+
function delegationShadowDigest(directory, records) {
|
|
1511
|
+
const hash = createHash3("sha256");
|
|
1512
|
+
hash.update(JSON.stringify(records));
|
|
1513
|
+
for (const filePath of [
|
|
1514
|
+
storePath(directory),
|
|
1515
|
+
checkpointPath(directory),
|
|
1516
|
+
manifestPath(directory)
|
|
1517
|
+
]) {
|
|
1518
|
+
if (!fs2.existsSync(filePath))
|
|
1519
|
+
continue;
|
|
1520
|
+
hash.update(path2.basename(filePath));
|
|
1521
|
+
hash.update(fs2.readFileSync(filePath));
|
|
1522
|
+
}
|
|
1523
|
+
return hash.digest("hex");
|
|
1524
|
+
}
|
|
1525
|
+
function ensureDelegationCoordinationImported(directory, createIfNeeded) {
|
|
1526
|
+
const dbExists = projectDbExists(directory);
|
|
1527
|
+
if (!createIfNeeded && !dbExists)
|
|
1528
|
+
return "absent";
|
|
1529
|
+
const existing = dbExists ? coordinationRowsToDelegations(directory) : null;
|
|
1530
|
+
if (dbExists && existing === null)
|
|
1531
|
+
return "uncertain";
|
|
1532
|
+
if (existing && existing.length > 0) {
|
|
1533
|
+
if (createIfNeeded)
|
|
1534
|
+
return "ready";
|
|
1535
|
+
const markerPresent = fs2.existsSync(projectionMarkerPath(storePath(directory)));
|
|
1536
|
+
const shadowMatches = markerPresent && delegationShadowMatches(directory, existing);
|
|
1537
|
+
if (!shadowMatches) {
|
|
1538
|
+
for (const filePath of [
|
|
1539
|
+
storePath(directory),
|
|
1540
|
+
checkpointPath(directory),
|
|
1541
|
+
manifestPath(directory)
|
|
1542
|
+
]) {
|
|
1543
|
+
archiveShadowFileBestEffort(filePath);
|
|
1544
|
+
}
|
|
1545
|
+
writeDelegationShadowProjection(directory, existing);
|
|
1546
|
+
}
|
|
1547
|
+
return "ready";
|
|
1548
|
+
}
|
|
1549
|
+
const legacyRecords = loadLegacyDelegationsStrict(directory);
|
|
1550
|
+
if (legacyRecords === null)
|
|
1551
|
+
return "uncertain";
|
|
1552
|
+
if (legacyRecords.length === 0 && !fs2.existsSync(storePath(directory)) && !fs2.existsSync(checkpointPath(directory)) && !fs2.existsSync(manifestPath(directory))) {
|
|
1553
|
+
if (!createIfNeeded)
|
|
1554
|
+
return "absent";
|
|
1555
|
+
withCoordinationTransaction(directory, () => {
|
|
1556
|
+
return;
|
|
1557
|
+
});
|
|
1558
|
+
return "ready";
|
|
1559
|
+
}
|
|
1560
|
+
const outcome = importCoordinationOnce(directory, {
|
|
1561
|
+
source: BACKGROUND_DELEGATIONS_FILE,
|
|
1562
|
+
sourceDigest: delegationShadowDigest(directory, legacyRecords),
|
|
1563
|
+
rowCount: legacyRecords.length,
|
|
1564
|
+
emptyNamespace: DELEGATION_COORDINATION_NAMESPACE
|
|
1565
|
+
}, () => {
|
|
1566
|
+
for (const record of legacyRecords) {
|
|
1567
|
+
const result = transitionCoordinationState(directory, {
|
|
1568
|
+
namespace: DELEGATION_COORDINATION_NAMESPACE,
|
|
1569
|
+
entityKey: record.correlationId,
|
|
1570
|
+
expectedRevision: null,
|
|
1571
|
+
generation: Math.max(record.generation ?? 1, 1),
|
|
1572
|
+
status: record.status,
|
|
1573
|
+
payload: JSON.stringify(record)
|
|
1574
|
+
});
|
|
1575
|
+
if (result.outcome !== "applied") {
|
|
1576
|
+
throw new Error(`delegation import failed for ${record.correlationId}: ${result.outcome}`);
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
});
|
|
1580
|
+
if (outcome === "imported") {
|
|
1581
|
+
archiveShadowFileBestEffort(storePath(directory));
|
|
1582
|
+
archiveShadowFileBestEffort(checkpointPath(directory));
|
|
1583
|
+
archiveShadowFileBestEffort(manifestPath(directory));
|
|
1584
|
+
writeDelegationShadowProjection(directory, legacyRecords);
|
|
1585
|
+
}
|
|
1586
|
+
return "ready";
|
|
1587
|
+
}
|
|
1588
|
+
function pruneCoordinationDelegationRows(directory) {
|
|
1589
|
+
const rows = listCoordinationStates(directory, DELEGATION_COORDINATION_NAMESPACE, MAX_COORDINATION_STATE_LIST_ROWS);
|
|
1590
|
+
const terminals = rows.filter((row) => !isCheckpointLiveRecord(JSON.parse(row.payload))).sort((left, right) => left.updatedAt.localeCompare(right.updatedAt));
|
|
1591
|
+
const excessTerminals = Math.max(0, terminals.length - MAX_COORDINATION_TERMINAL_ROWS);
|
|
1592
|
+
for (const row of terminals.slice(0, excessTerminals)) {
|
|
1593
|
+
deleteCoordinationState(directory, DELEGATION_COORDINATION_NAMESPACE, row.entityKey, row.revision);
|
|
1594
|
+
}
|
|
1595
|
+
const remaining = listCoordinationStates(directory, DELEGATION_COORDINATION_NAMESPACE, MAX_COORDINATION_STATE_LIST_ROWS);
|
|
1596
|
+
if (remaining.length >= MAX_COORDINATION_DELEGATION_ROWS) {
|
|
1597
|
+
throw new Error(`delegation coordination state reached its ${MAX_COORDINATION_DELEGATION_ROWS}-row safety bound`);
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1409
1600
|
var SHA256_HEX = /^[0-9a-f]{64}$/;
|
|
1410
1601
|
var CheckpointSchema = exports_external.object({
|
|
1411
1602
|
schemaVersion: exports_external.literal(1),
|
|
@@ -1814,6 +2005,15 @@ function loadLegacyLedger(directory, strict) {
|
|
|
1814
2005
|
};
|
|
1815
2006
|
}
|
|
1816
2007
|
function loadRecordsForWrite(directory) {
|
|
2008
|
+
const importState = ensureDelegationCoordinationImported(directory, true);
|
|
2009
|
+
if (importState === "uncertain")
|
|
2010
|
+
return null;
|
|
2011
|
+
if (importState === "ready") {
|
|
2012
|
+
const coordination = coordinationRowsToDelegations(directory);
|
|
2013
|
+
if (coordination !== null)
|
|
2014
|
+
return coordination;
|
|
2015
|
+
return null;
|
|
2016
|
+
}
|
|
1817
2017
|
const load = loadFoldedState(directory, { strict: false });
|
|
1818
2018
|
if (load.status === "uncertain") {
|
|
1819
2019
|
recordLedgerUncertainty(directory, load.reason, "mutation", load.repairHint);
|
|
@@ -1988,7 +2188,7 @@ function terminalEventStatusOf(record) {
|
|
|
1988
2188
|
if (record.terminalResult) {
|
|
1989
2189
|
return record.terminalResult.status;
|
|
1990
2190
|
}
|
|
1991
|
-
if (record.status === "completed" || record.status === "error" || record.status === "cancelled" || record.status === "stale") {
|
|
2191
|
+
if (record.status === "completed" || record.status === "error" || record.status === "cancelled" || record.status === "rejected" || record.status === "stale") {
|
|
1992
2192
|
return record.status;
|
|
1993
2193
|
}
|
|
1994
2194
|
return null;
|
|
@@ -2027,7 +2227,9 @@ function mergeCheckpointAudit(previous, previousCheckpoint, folded, healthLateTe
|
|
|
2027
2227
|
if (terminalStatus) {
|
|
2028
2228
|
const prevStatus = prevRecord ? terminalEventStatusOf(prevRecord) : null;
|
|
2029
2229
|
if (prevStatus !== terminalStatus) {
|
|
2030
|
-
|
|
2230
|
+
if (terminalStatus !== "rejected") {
|
|
2231
|
+
audit.terminalsByStatus[terminalStatus] += 1;
|
|
2232
|
+
}
|
|
2031
2233
|
}
|
|
2032
2234
|
maxTerminal = Math.max(maxTerminal, record.terminalResult?.recordedAt ?? record.completedAt ?? 0);
|
|
2033
2235
|
}
|
|
@@ -2046,6 +2248,47 @@ function mergeCheckpointAudit(previous, previousCheckpoint, folded, healthLateTe
|
|
|
2046
2248
|
function capCounter(previous, delta) {
|
|
2047
2249
|
return Number.isSafeInteger(previous + delta) ? previous + delta : Number.MAX_SAFE_INTEGER;
|
|
2048
2250
|
}
|
|
2251
|
+
function synchronizeCoordinationAfterCompaction(directory, retained) {
|
|
2252
|
+
if (!projectDbExists(directory))
|
|
2253
|
+
return;
|
|
2254
|
+
const retainedById = new Map(retained.map((record) => [record.correlationId, record]));
|
|
2255
|
+
withCoordinationTransaction(directory, () => {
|
|
2256
|
+
const rows = listCoordinationStates(directory, DELEGATION_COORDINATION_NAMESPACE, MAX_COORDINATION_STATE_LIST_ROWS);
|
|
2257
|
+
if (rows.length >= MAX_COORDINATION_STATE_LIST_ROWS) {
|
|
2258
|
+
throw new Error(`delegation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);
|
|
2259
|
+
}
|
|
2260
|
+
for (const row of rows) {
|
|
2261
|
+
const record = retainedById.get(row.entityKey);
|
|
2262
|
+
if (!record) {
|
|
2263
|
+
if (!deleteCoordinationStateWithinTransaction(directory, DELEGATION_COORDINATION_NAMESPACE, row.entityKey, row.revision)) {
|
|
2264
|
+
throw new Error(`coordination compaction delete lost a concurrent update for ${row.entityKey}`);
|
|
2265
|
+
}
|
|
2266
|
+
continue;
|
|
2267
|
+
}
|
|
2268
|
+
const current = RecordSchema.safeParse(JSON.parse(row.payload));
|
|
2269
|
+
if (!current.success) {
|
|
2270
|
+
throw new Error(`delegation coordination row failed schema validation for ${row.entityKey}`);
|
|
2271
|
+
}
|
|
2272
|
+
if (isDeepStrictEqual(current.data, record))
|
|
2273
|
+
continue;
|
|
2274
|
+
const result = getProjectDb(directory).run(`UPDATE coordination_state
|
|
2275
|
+
SET revision = ?, generation = ?, status = ?, payload = ?, updated_at = ?
|
|
2276
|
+
WHERE namespace = ? AND entity_key = ? AND revision = ?`, [
|
|
2277
|
+
row.revision + 1,
|
|
2278
|
+
Math.max(record.generation ?? 1, 1),
|
|
2279
|
+
record.status,
|
|
2280
|
+
JSON.stringify(record),
|
|
2281
|
+
new Date().toISOString(),
|
|
2282
|
+
DELEGATION_COORDINATION_NAMESPACE,
|
|
2283
|
+
row.entityKey,
|
|
2284
|
+
row.revision
|
|
2285
|
+
]);
|
|
2286
|
+
if (result.changes !== 1) {
|
|
2287
|
+
throw new Error(`coordination compaction update lost a concurrent update for ${row.entityKey}`);
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
});
|
|
2291
|
+
}
|
|
2049
2292
|
async function compactBackgroundDelegations(directory, options = {}) {
|
|
2050
2293
|
try {
|
|
2051
2294
|
let outcome = {
|
|
@@ -2063,7 +2306,24 @@ async function compactBackgroundDelegations(directory, options = {}) {
|
|
|
2063
2306
|
}
|
|
2064
2307
|
}
|
|
2065
2308
|
function compactDelegationsLocked(directory, options) {
|
|
2066
|
-
const
|
|
2309
|
+
const hasAuthority = projectDbExists(directory);
|
|
2310
|
+
const authoritative = hasAuthority ? coordinationRowsToDelegations(directory) : null;
|
|
2311
|
+
const manifestRead = hasAuthority ? readDelegationManifest(directory) : null;
|
|
2312
|
+
const checkpointRead = hasAuthority ? readDelegationCheckpoint(directory) : null;
|
|
2313
|
+
const manifest = manifestRead?.kind === "ok" && sameProjectRoot(manifestRead.manifest.rootPath, directory) ? manifestRead.manifest : null;
|
|
2314
|
+
const existingCheckpoint = checkpointRead?.kind === "ok" && sameProjectRoot(checkpointRead.checkpoint.rootPath, directory) ? checkpointRead.checkpoint : null;
|
|
2315
|
+
if (hasAuthority && authoritative === null) {
|
|
2316
|
+
const reason = "SQLite delegation coordination authority is unreadable; refusing legacy compaction fallback";
|
|
2317
|
+
recordLedgerUncertainty(directory, reason, "compaction");
|
|
2318
|
+
return { status: "uncertain", reason };
|
|
2319
|
+
}
|
|
2320
|
+
const load = hasAuthority ? {
|
|
2321
|
+
status: "ok",
|
|
2322
|
+
mode: "legacy",
|
|
2323
|
+
records: new Map((authoritative ?? []).map((record) => [record.correlationId, record])),
|
|
2324
|
+
manifest,
|
|
2325
|
+
checkpoint: existingCheckpoint
|
|
2326
|
+
} : loadFoldedState(directory, { strict: false });
|
|
2067
2327
|
if (load.status === "uncertain") {
|
|
2068
2328
|
recordLedgerUncertainty(directory, load.reason, "compaction", load.repairHint);
|
|
2069
2329
|
return { status: "uncertain", reason: load.reason };
|
|
@@ -2218,6 +2478,13 @@ function compactDelegationsLocked(directory, options) {
|
|
|
2218
2478
|
}
|
|
2219
2479
|
const tailContent = currentSize > cutLedgerBytes ? readLedgerRegion(directory, cutLedgerBytes, currentSize - cutLedgerBytes) : Buffer.alloc(0);
|
|
2220
2480
|
writeDurableFileSync(storePath(directory), tailContent);
|
|
2481
|
+
try {
|
|
2482
|
+
synchronizeCoordinationAfterCompaction(directory, [...live, ...keptClosed]);
|
|
2483
|
+
} catch (error) {
|
|
2484
|
+
const reason = `coordination authority could not be synchronized after compaction: ${error instanceof Error ? error.message : String(error)}`;
|
|
2485
|
+
recordLedgerUncertainty(directory, reason, "compaction");
|
|
2486
|
+
return { status: "uncertain", reason };
|
|
2487
|
+
}
|
|
2221
2488
|
try {
|
|
2222
2489
|
const pressurePct = Math.min(100, Math.round(tailContent.length / MAX_RECOVERY_LEDGER_BYTES * 1000) / 10);
|
|
2223
2490
|
writeDelegationHealthArtifact(directory, {
|
|
@@ -2275,6 +2542,15 @@ function ensureSwarmDir(directory) {
|
|
|
2275
2542
|
fs2.mkdirSync(path2.resolve(directory, ".swarm"), { recursive: true });
|
|
2276
2543
|
}
|
|
2277
2544
|
function readDelegations(directory) {
|
|
2545
|
+
const importState = ensureDelegationCoordinationImported(directory, false);
|
|
2546
|
+
if (importState === "uncertain")
|
|
2547
|
+
return [];
|
|
2548
|
+
if (importState === "ready") {
|
|
2549
|
+
const coordination = coordinationRowsToDelegations(directory);
|
|
2550
|
+
if (coordination !== null)
|
|
2551
|
+
return coordination;
|
|
2552
|
+
return [];
|
|
2553
|
+
}
|
|
2278
2554
|
const load = loadFoldedState(directory, { strict: false });
|
|
2279
2555
|
if (load.status === "uncertain") {
|
|
2280
2556
|
warn(`[background] readDelegations: authoritative state uncertain (${load.reason}); returning empty`);
|
|
@@ -2283,6 +2559,29 @@ function readDelegations(directory) {
|
|
|
2283
2559
|
return [...load.records.values()];
|
|
2284
2560
|
}
|
|
2285
2561
|
function scanDelegationsForRecovery(directory) {
|
|
2562
|
+
const importState = ensureDelegationCoordinationImported(directory, false);
|
|
2563
|
+
if (importState === "uncertain") {
|
|
2564
|
+
return {
|
|
2565
|
+
status: "uncertain",
|
|
2566
|
+
reason: "background delegation coordination state is uncertain",
|
|
2567
|
+
source: "unknown"
|
|
2568
|
+
};
|
|
2569
|
+
}
|
|
2570
|
+
if (importState === "ready") {
|
|
2571
|
+
const coordination = coordinationRowsToDelegations(directory);
|
|
2572
|
+
if (coordination !== null) {
|
|
2573
|
+
return {
|
|
2574
|
+
status: "ok",
|
|
2575
|
+
owners: coordination,
|
|
2576
|
+
source: "checkpoint+tail"
|
|
2577
|
+
};
|
|
2578
|
+
}
|
|
2579
|
+
return {
|
|
2580
|
+
status: "uncertain",
|
|
2581
|
+
reason: "background delegation coordination state is unreadable or over-bound",
|
|
2582
|
+
source: "unknown"
|
|
2583
|
+
};
|
|
2584
|
+
}
|
|
2286
2585
|
const load = loadFoldedState(directory, { strict: true });
|
|
2287
2586
|
if (load.status === "uncertain") {
|
|
2288
2587
|
const manifestKind = readDelegationManifest(directory).kind;
|
|
@@ -2306,6 +2605,39 @@ function findByCorrelationId(directory, correlationId) {
|
|
|
2306
2605
|
return null;
|
|
2307
2606
|
}
|
|
2308
2607
|
function appendRecord(directory, record) {
|
|
2608
|
+
const importState = ensureDelegationCoordinationImported(directory, true);
|
|
2609
|
+
if (importState === "uncertain") {
|
|
2610
|
+
throw new Error("delegation coordination authority is uncertain");
|
|
2611
|
+
}
|
|
2612
|
+
if (importState === "ready") {
|
|
2613
|
+
pruneCoordinationDelegationRows(directory);
|
|
2614
|
+
const current = getCoordinationState(directory, DELEGATION_COORDINATION_NAMESPACE, record.correlationId);
|
|
2615
|
+
const eventPayload = JSON.stringify(record);
|
|
2616
|
+
const eventDigest = createHash3("sha256").update(eventPayload).digest("hex");
|
|
2617
|
+
const result = transitionCoordinationState(directory, {
|
|
2618
|
+
namespace: DELEGATION_COORDINATION_NAMESPACE,
|
|
2619
|
+
entityKey: record.correlationId,
|
|
2620
|
+
expectedRevision: current?.revision ?? null,
|
|
2621
|
+
generation: Math.max(record.generation ?? 1, 1),
|
|
2622
|
+
status: record.status,
|
|
2623
|
+
payload: eventPayload,
|
|
2624
|
+
event: {
|
|
2625
|
+
streamId: record.correlationId,
|
|
2626
|
+
idempotencyKey: `${record.status}:${eventDigest}`,
|
|
2627
|
+
eventType: record.status,
|
|
2628
|
+
payload: eventPayload
|
|
2629
|
+
}
|
|
2630
|
+
});
|
|
2631
|
+
if (result.outcome !== "applied" && result.outcome !== "duplicate") {
|
|
2632
|
+
throw new Error(`coordination append rejected for ${record.correlationId}: ${result.outcome}`);
|
|
2633
|
+
}
|
|
2634
|
+
if (!fs2.existsSync(projectionMarkerPath(storePath(directory)))) {
|
|
2635
|
+
const records = coordinationRowsToDelegations(directory);
|
|
2636
|
+
if (records)
|
|
2637
|
+
writeDelegationShadowProjection(directory, records);
|
|
2638
|
+
}
|
|
2639
|
+
return;
|
|
2640
|
+
}
|
|
2309
2641
|
ensureSwarmDir(directory);
|
|
2310
2642
|
fs2.appendFileSync(storePath(directory), `${JSON.stringify(record)}
|
|
2311
2643
|
`, "utf-8");
|
|
@@ -2451,7 +2783,7 @@ async function appendDelegationTransition(directory, correlationId, transition)
|
|
|
2451
2783
|
...current,
|
|
2452
2784
|
schemaVersion: transition.result?.prReviewResultReceipt ? 4 : current.schemaVersion === 1 ? 2 : current.schemaVersion,
|
|
2453
2785
|
status: transition.status,
|
|
2454
|
-
updatedAt: now,
|
|
2786
|
+
updatedAt: transition.updatedAt ?? now,
|
|
2455
2787
|
...transition.completedAt !== undefined ? { completedAt: transition.completedAt } : transition.status === "completed" || transition.status === "error" ? { completedAt: now } : {},
|
|
2456
2788
|
...transition.result ? { result: transition.result } : {}
|
|
2457
2789
|
};
|
|
@@ -2927,7 +3259,9 @@ var _internals = {
|
|
|
2927
3259
|
resetLegacyCoderSettlementReconcilers: () => {
|
|
2928
3260
|
legacyCoderSettlementReconcilers.clear();
|
|
2929
3261
|
legacyCoderSettlementReconcilerOrder.length = 0;
|
|
2930
|
-
}
|
|
3262
|
+
},
|
|
3263
|
+
reservationCoordinationRowLimit: MAX_COORDINATION_STATE_LIST_ROWS,
|
|
3264
|
+
writeBackgroundCoderReservations
|
|
2931
3265
|
};
|
|
2932
3266
|
async function markLegacyCoderSettlementTransferPending(directory, correlationId, transfer) {
|
|
2933
3267
|
return updateLegacyCoderSettlementTransfer(directory, correlationId, transfer);
|
|
@@ -3626,11 +3960,45 @@ var MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES = 2 * 1024 * 1024;
|
|
|
3626
3960
|
function reservationStorePath(directory) {
|
|
3627
3961
|
return validateSwarmPath(directory, BACKGROUND_CODER_RESERVATIONS_FILE);
|
|
3628
3962
|
}
|
|
3629
|
-
function
|
|
3630
|
-
const
|
|
3631
|
-
|
|
3963
|
+
function reservationShadowDigest(directory, reservations) {
|
|
3964
|
+
const hash = createHash3("sha256");
|
|
3965
|
+
hash.update(JSON.stringify(reservations));
|
|
3966
|
+
const filePath = reservationStorePath(directory);
|
|
3967
|
+
if (fs2.existsSync(filePath)) {
|
|
3968
|
+
hash.update(fs2.readFileSync(filePath));
|
|
3969
|
+
}
|
|
3970
|
+
return hash.digest("hex");
|
|
3632
3971
|
}
|
|
3633
|
-
function
|
|
3972
|
+
function writeReservationShadowProjection(directory, reservations) {
|
|
3973
|
+
const parsed = BackgroundCoderReservationStoreSchema.parse({
|
|
3974
|
+
schemaVersion: 1,
|
|
3975
|
+
reservations
|
|
3976
|
+
});
|
|
3977
|
+
fs2.writeFileSync(reservationStorePath(directory), `${JSON.stringify(parsed)}
|
|
3978
|
+
`, "utf-8");
|
|
3979
|
+
fs2.writeFileSync(projectionMarkerPath(reservationStorePath(directory)), "", "utf-8");
|
|
3980
|
+
}
|
|
3981
|
+
function coordinationRowsToReservations(directory) {
|
|
3982
|
+
if (!projectDbExists(directory))
|
|
3983
|
+
return null;
|
|
3984
|
+
try {
|
|
3985
|
+
const rows = listCoordinationStates(directory, RESERVATION_COORDINATION_NAMESPACE, MAX_COORDINATION_STATE_LIST_ROWS);
|
|
3986
|
+
if (rows.length >= MAX_COORDINATION_STATE_LIST_ROWS) {
|
|
3987
|
+
throw new Error(`reservation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);
|
|
3988
|
+
}
|
|
3989
|
+
return rows.map((row) => {
|
|
3990
|
+
const parsed = BackgroundCoderReservationSchema.safeParse(JSON.parse(row.payload));
|
|
3991
|
+
if (!parsed.success || parsed.data.reservationId !== row.entityKey || (parsed.data.generation ?? 1) !== row.generation || parsed.data.state !== row.status) {
|
|
3992
|
+
throw new Error(`reservation coordination row failed schema or authority binding validation for ${row.entityKey}`);
|
|
3993
|
+
}
|
|
3994
|
+
return parsed.data;
|
|
3995
|
+
}).sort((left, right) => left.createdAt === right.createdAt ? left.reservationId.localeCompare(right.reservationId) : left.createdAt - right.createdAt);
|
|
3996
|
+
} catch (error) {
|
|
3997
|
+
recordLedgerUncertainty(directory, error instanceof Error ? error.message : String(error), "reservation-coordination-read");
|
|
3998
|
+
return null;
|
|
3999
|
+
}
|
|
4000
|
+
}
|
|
4001
|
+
function scanLegacyBackgroundCoderReservationsForAdmission(directory) {
|
|
3634
4002
|
let absolutePath;
|
|
3635
4003
|
let raw;
|
|
3636
4004
|
try {
|
|
@@ -3676,6 +4044,96 @@ function scanBackgroundCoderReservationsForAdmission(directory) {
|
|
|
3676
4044
|
}
|
|
3677
4045
|
return { status: "ok", reservations: parsed.data.reservations };
|
|
3678
4046
|
}
|
|
4047
|
+
function ensureReservationCoordinationImported(directory, createIfNeeded) {
|
|
4048
|
+
const dbExists = projectDbExists(directory);
|
|
4049
|
+
if (!createIfNeeded && !dbExists)
|
|
4050
|
+
return "absent";
|
|
4051
|
+
const existing = dbExists ? coordinationRowsToReservations(directory) : null;
|
|
4052
|
+
if (dbExists && existing === null)
|
|
4053
|
+
return "uncertain";
|
|
4054
|
+
if (existing && existing.length > 0) {
|
|
4055
|
+
const legacy2 = scanLegacyBackgroundCoderReservationsForAdmission(directory);
|
|
4056
|
+
if (!fs2.existsSync(projectionMarkerPath(reservationStorePath(directory))) || legacy2.status !== "ok" || !isDeepStrictEqual(legacy2.reservations.sort((left, right) => left.reservationId.localeCompare(right.reservationId)), [...existing].sort((left, right) => left.reservationId.localeCompare(right.reservationId)))) {
|
|
4057
|
+
archiveShadowFileBestEffort(reservationStorePath(directory));
|
|
4058
|
+
}
|
|
4059
|
+
writeReservationShadowProjection(directory, existing);
|
|
4060
|
+
return "ready";
|
|
4061
|
+
}
|
|
4062
|
+
const legacy = scanLegacyBackgroundCoderReservationsForAdmission(directory);
|
|
4063
|
+
if (legacy.status === "uncertain") {
|
|
4064
|
+
recordLedgerUncertainty(directory, legacy.reason, "reservation-legacy-import");
|
|
4065
|
+
return "uncertain";
|
|
4066
|
+
}
|
|
4067
|
+
if (legacy.reservations.length === 0 && !fs2.existsSync(reservationStorePath(directory))) {
|
|
4068
|
+
if (!createIfNeeded)
|
|
4069
|
+
return "absent";
|
|
4070
|
+
withCoordinationTransaction(directory, () => {
|
|
4071
|
+
return;
|
|
4072
|
+
});
|
|
4073
|
+
return "ready";
|
|
4074
|
+
}
|
|
4075
|
+
const outcome = importCoordinationOnce(directory, {
|
|
4076
|
+
source: BACKGROUND_CODER_RESERVATIONS_FILE,
|
|
4077
|
+
sourceDigest: reservationShadowDigest(directory, legacy.reservations),
|
|
4078
|
+
rowCount: legacy.reservations.length,
|
|
4079
|
+
emptyNamespace: RESERVATION_COORDINATION_NAMESPACE
|
|
4080
|
+
}, () => {
|
|
4081
|
+
for (const reservation of legacy.reservations) {
|
|
4082
|
+
const result = transitionCoordinationState(directory, {
|
|
4083
|
+
namespace: RESERVATION_COORDINATION_NAMESPACE,
|
|
4084
|
+
entityKey: reservation.reservationId,
|
|
4085
|
+
expectedRevision: null,
|
|
4086
|
+
generation: reservation.generation ?? 1,
|
|
4087
|
+
status: reservation.state,
|
|
4088
|
+
payload: JSON.stringify(reservation)
|
|
4089
|
+
});
|
|
4090
|
+
if (result.outcome !== "applied") {
|
|
4091
|
+
throw new Error(`reservation import failed for ${reservation.reservationId}: ${result.outcome}`);
|
|
4092
|
+
}
|
|
4093
|
+
if (reservation.leaseExpiresAt !== undefined) {
|
|
4094
|
+
const lease = acquireCoordinationLease(directory, {
|
|
4095
|
+
...coordinationReservationLeaseKey(reservation),
|
|
4096
|
+
leaseExpiresAt: new Date(reservation.leaseExpiresAt).toISOString(),
|
|
4097
|
+
payload: JSON.stringify({
|
|
4098
|
+
parentSessionId: reservation.parentSessionId,
|
|
4099
|
+
correlationId: reservation.correlationId
|
|
4100
|
+
})
|
|
4101
|
+
});
|
|
4102
|
+
if (lease.outcome === "held" || lease.outcome === "stale_generation") {
|
|
4103
|
+
throw new Error(`reservation lease import failed for ${reservation.reservationId}: ${lease.outcome}`);
|
|
4104
|
+
}
|
|
4105
|
+
}
|
|
4106
|
+
}
|
|
4107
|
+
});
|
|
4108
|
+
if (outcome === "imported") {
|
|
4109
|
+
archiveShadowFileBestEffort(reservationStorePath(directory));
|
|
4110
|
+
writeReservationShadowProjection(directory, legacy.reservations);
|
|
4111
|
+
}
|
|
4112
|
+
return "ready";
|
|
4113
|
+
}
|
|
4114
|
+
function buildBackgroundCoderReservationId(input) {
|
|
4115
|
+
const ownerIdentity = input.planTaskId === null ? ["call", input.parentSessionId, input.callID] : ["task", input.parentSessionId, input.planTaskId];
|
|
4116
|
+
return `bgcr1:${createHash3("sha256").update(JSON.stringify(ownerIdentity)).digest("hex")}`;
|
|
4117
|
+
}
|
|
4118
|
+
function scanBackgroundCoderReservationsForAdmission(directory) {
|
|
4119
|
+
const importState = ensureReservationCoordinationImported(directory, false);
|
|
4120
|
+
if (importState === "uncertain") {
|
|
4121
|
+
return {
|
|
4122
|
+
status: "uncertain",
|
|
4123
|
+
reason: "background coder reservation coordination state is uncertain"
|
|
4124
|
+
};
|
|
4125
|
+
}
|
|
4126
|
+
if (importState === "ready") {
|
|
4127
|
+
const reservations = coordinationRowsToReservations(directory);
|
|
4128
|
+
if (reservations !== null)
|
|
4129
|
+
return { status: "ok", reservations };
|
|
4130
|
+
return {
|
|
4131
|
+
status: "uncertain",
|
|
4132
|
+
reason: "background coder reservation coordination state is unreadable or over-bound"
|
|
4133
|
+
};
|
|
4134
|
+
}
|
|
4135
|
+
return scanLegacyBackgroundCoderReservationsForAdmission(directory);
|
|
4136
|
+
}
|
|
3679
4137
|
async function writeBackgroundCoderReservations(directory, reservations) {
|
|
3680
4138
|
const parsed = BackgroundCoderReservationStoreSchema.safeParse({
|
|
3681
4139
|
schemaVersion: 1,
|
|
@@ -3683,6 +4141,77 @@ async function writeBackgroundCoderReservations(directory, reservations) {
|
|
|
3683
4141
|
});
|
|
3684
4142
|
if (!parsed.success)
|
|
3685
4143
|
return false;
|
|
4144
|
+
const importState = ensureReservationCoordinationImported(directory, true);
|
|
4145
|
+
if (importState === "uncertain")
|
|
4146
|
+
return false;
|
|
4147
|
+
if (importState === "ready") {
|
|
4148
|
+
try {
|
|
4149
|
+
withCoordinationTransaction(directory, () => {
|
|
4150
|
+
const safetyBound = _internals.reservationCoordinationRowLimit;
|
|
4151
|
+
const authoritativeCount = countCoordinationStates(directory, RESERVATION_COORDINATION_NAMESPACE);
|
|
4152
|
+
if (authoritativeCount > safetyBound) {
|
|
4153
|
+
throw new Error(`reservation coordination write exceeded its ${safetyBound}-row safety bound`);
|
|
4154
|
+
}
|
|
4155
|
+
const currentRows = listCoordinationStates(directory, RESERVATION_COORDINATION_NAMESPACE, safetyBound);
|
|
4156
|
+
if (currentRows.length !== authoritativeCount) {
|
|
4157
|
+
throw new Error("reservation coordination state changed during bounded reconciliation");
|
|
4158
|
+
}
|
|
4159
|
+
const current = new Map(currentRows.map((row) => [row.entityKey, row]));
|
|
4160
|
+
const nextIds = new Set(parsed.data.reservations.map((entry) => entry.reservationId));
|
|
4161
|
+
for (const [reservationId, row] of current) {
|
|
4162
|
+
if (nextIds.has(reservationId))
|
|
4163
|
+
continue;
|
|
4164
|
+
const currentReservation = BackgroundCoderReservationSchema.parse(JSON.parse(row.payload));
|
|
4165
|
+
const deleted = deleteCoordinationState(directory, RESERVATION_COORDINATION_NAMESPACE, reservationId, row.revision);
|
|
4166
|
+
if (!deleted) {
|
|
4167
|
+
throw new Error(`reservation delete conflict for ${reservationId}`);
|
|
4168
|
+
}
|
|
4169
|
+
releaseReservationLeaseIfPresent(directory, currentReservation);
|
|
4170
|
+
}
|
|
4171
|
+
for (const reservation of parsed.data.reservations) {
|
|
4172
|
+
const row = current.get(reservation.reservationId);
|
|
4173
|
+
const result = transitionCoordinationState(directory, {
|
|
4174
|
+
namespace: RESERVATION_COORDINATION_NAMESPACE,
|
|
4175
|
+
entityKey: reservation.reservationId,
|
|
4176
|
+
expectedRevision: row?.revision ?? null,
|
|
4177
|
+
generation: reservation.generation ?? 1,
|
|
4178
|
+
status: reservation.state,
|
|
4179
|
+
payload: JSON.stringify(reservation),
|
|
4180
|
+
event: {
|
|
4181
|
+
streamId: reservation.reservationId,
|
|
4182
|
+
idempotencyKey: createHash3("sha256").update(JSON.stringify(reservation)).digest("hex"),
|
|
4183
|
+
eventType: reservation.state,
|
|
4184
|
+
payload: JSON.stringify(reservation)
|
|
4185
|
+
}
|
|
4186
|
+
});
|
|
4187
|
+
if (result.outcome !== "applied" && result.outcome !== "duplicate") {
|
|
4188
|
+
throw new Error(`reservation write failed for ${reservation.reservationId}: ${result.outcome}`);
|
|
4189
|
+
}
|
|
4190
|
+
const leaseKey = coordinationReservationLeaseKey(reservation);
|
|
4191
|
+
if (reservation.leaseExpiresAt !== undefined) {
|
|
4192
|
+
const lease = acquireCoordinationLease(directory, {
|
|
4193
|
+
...leaseKey,
|
|
4194
|
+
leaseExpiresAt: new Date(reservation.leaseExpiresAt).toISOString(),
|
|
4195
|
+
payload: JSON.stringify({
|
|
4196
|
+
parentSessionId: reservation.parentSessionId,
|
|
4197
|
+
correlationId: reservation.correlationId
|
|
4198
|
+
})
|
|
4199
|
+
});
|
|
4200
|
+
if (lease.outcome === "held" || lease.outcome === "stale_generation") {
|
|
4201
|
+
throw new Error(`reservation lease write failed for ${reservation.reservationId}: ${lease.outcome}`);
|
|
4202
|
+
}
|
|
4203
|
+
} else {
|
|
4204
|
+
releaseReservationLeaseIfPresent(directory, reservation);
|
|
4205
|
+
}
|
|
4206
|
+
}
|
|
4207
|
+
});
|
|
4208
|
+
writeReservationShadowProjection(directory, parsed.data.reservations);
|
|
4209
|
+
return true;
|
|
4210
|
+
} catch (error) {
|
|
4211
|
+
warn(`[background] reservation coordination write failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
4212
|
+
return false;
|
|
4213
|
+
}
|
|
4214
|
+
}
|
|
3686
4215
|
try {
|
|
3687
4216
|
await bunWrite(reservationStorePath(directory), `${JSON.stringify(parsed.data)}
|
|
3688
4217
|
`);
|
|
@@ -3988,7 +4517,7 @@ async function reconcileLegacyCoderSettlements(directory, maxRecords, onReconcil
|
|
|
3988
4517
|
const candidates = readDelegations(directory).filter((record) => record.normalizedAgent === "coder" && Boolean(record.legacyCoderSettlementTransfer) && Boolean(record.terminalResult)).slice(0, maxRecords);
|
|
3989
4518
|
if (candidates.length === 0)
|
|
3990
4519
|
return 0;
|
|
3991
|
-
const { transferCoderSettlementToBackground } = await import("./coder-settlement-
|
|
4520
|
+
const { transferCoderSettlementToBackground } = await import("./coder-settlement-yh1q5fr3.js");
|
|
3992
4521
|
let transferred = 0;
|
|
3993
4522
|
for (const record of candidates) {
|
|
3994
4523
|
try {
|