@sema-agent/core
Version:
Stateless, task-oriented AI agent core
586 lines (585 loc) • 31.5 kB
JavaScript
import { ambiguousOriginRepresentation, computeEntryRev, serializeEntryFile } from "./frontmatter.js";
import { screenInboundEntries } from "./data-plane.js";
import { scanMemoryFileName, scanMemoryWrite } from "./scan.js";
import { MAX_MEMORY_BYTES } from "../memory.js";
import { reconcileMemoryEntries } from "./sync.js";
import { memoryDeletionRecords } from "./deletion-record.js";
import { MEMORY_ORIGIN_CAUSES } from "./types.js";
import { directoryPinOf, landingPathOf } from "./layout.js";
import { egressText } from "../untrusted-egress.js";
import { REDACTION_MARKS, userinfoHolds } from "@sema-agent/primitives";
import { isReplicableScope } from "./scope-contract.js";
import { applyPatchesWithin } from "./patch-scope-seat.js";
const DROP_THE_CURSOR = "drop the cursor to accept re-convergence from an empty baseline — entries changed on both sides are reported as conflicts, " +
"and entries deleted on one side since the last round come back from the other side unless that side's store records the deletion and reads it";
const REFUSAL_ROWS = {
scope: {
why: "a cursor is the baseline of one (scope, peer) partition",
outs: () => ["pass this partition's own cursor", "pass none before the partition's first completed round"],
},
peer: {
why: "a baseline taken elsewhere would misjudge every entry",
outs: (want) => [
"re-bind — run this layer over a transport that reaches the peer the cursor was taken against, or, " +
`only when this transport reaches that same peer under a new identity, set the cursor's peer to ${quoted(want)}`,
DROP_THE_CURSOR,
],
},
incarnation: {
why: "the peer holds another state than the one the baseline was taken against and refused the round before writing, so nothing " +
"was written on either side — run on that baseline, an entry the peer lacks would land here as a delete and an older copy as a rollback",
outs: (want) => [
"re-bind — run this layer against the state the baseline was taken against, or, only when the cursor carries no incarnation " +
`(it was written before cursors carried one) and this peer holds that same state, set the cursor's peerIncarnation to ${quoted(want)}; ` +
"a cursor that carries another incarnation is never re-bound to this one",
DROP_THE_CURSOR,
],
},
store: {
why: "its baseline describes another store's entries, so this round is refused, not run on that baseline or without one",
outs: () => [
"rebind — when this store holds the entries the baseline was taken over (the same store, moved to this root or bound before " +
"cursors carried a store), persist the cursor with its store set to this store's identity (memorySyncStoreOf) and sync again",
"clear — delete the cursor and sync from none, accepting that deletions without a baseline no longer cross and an entry deleted on either side since the last completed round " +
"comes back from the other side unless that side's store records the deletion and reads it (a recorded deletion blocks landing as a conflict and never deletes on the peer)",
],
},
"store-plane": {
why: "a sync baseline is bound to a File store's root, and this store has none",
outs: () => [
"sync the File store that holds this scope",
"leave this store out of the sync — a store with no directory is not a sync plane",
],
},
};
const MINTED_REFUSALS = new WeakSet();
function syncRefusal(on, head, want) {
const row = REFUSAL_ROWS[on === "store-plane" ? on : on.axis];
const [first, second] = row.outs(want);
const outs = Object.freeze([egressText("same-principal", first), egressText("same-principal", second)]);
const e = new Error(egressText("same-principal", `memory sync: ${head} — ${row.why}; two ways out: (1) ${outs[0]}; (2) ${outs[1]}`));
if (on === "store-plane") {
e.code = "config.memory_sync_store";
}
else {
e.code = "config.memory_sync_cursor_mismatch";
e.detail = Object.freeze({ axis: on.axis, found: on.found, want: carriesCredential(want) ? REDACTION_MARKS.bare : want });
}
e.outs = outs;
MINTED_REFUSALS.add(e);
return e;
}
export function readSyncRefusal(thrown) {
return typeof thrown === "object" && thrown !== null && MINTED_REFUSALS.has(thrown) ? thrown : undefined;
}
export function memorySyncStoreOf(backend) {
return syncStoreOf(backend).identity;
}
function syncStoreOf(backend) {
const pin = directoryPinOf(backend);
if (pin === undefined)
throw syncRefusal("store-plane", "the local store has no directory", "");
const root = landingPathOf(pin);
return { root, identity: `file:${root}` };
}
function cursorRefusal(axis, got, want) {
const found = got === undefined ? "absent" : "other";
const head = found === "absent" ? `cursor has no ${axis} binding` : `cursor is for ${axis} ${quoted(got)}`;
return syncRefusal({ axis, found }, `${head}; this round's ${axis} is ${quoted(want)}`, want);
}
function refuseForeignCursor(cursor, scope, peer, store) {
const axis = [["scope", cursor.scope, scope], ["peer", cursor.peer, peer], ["store", cursor.store, store]];
for (const [name, got, want] of axis) {
if (got !== want)
throw cursorRefusal(name, got, want);
}
}
function servesClaim(claim, baselineEmpty, incarnation) {
return claim !== undefined ? claim === incarnation : baselineEmpty;
}
function memorySyncPath(scope) {
return `/v2/memory/sync/${encodeURIComponent(scope)}`;
}
function baselineStub(id, rev, scope) {
return { id, rev, scope, slug: `sync-baseline-stub/${id}`, frontmatter: {}, body: "" };
}
const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const isNonEmptyString = (v) => typeof v === "string" && v.length > 0;
const namesSomething = (v) => typeof v === "string" && v.trim().length > 0;
function quoted(v) {
if (typeof v !== "string")
return JSON.stringify(typeof v);
return carriesCredential(v) ? REDACTION_MARKS.bare : JSON.stringify(v);
}
const isAsciiLetter = (c) => (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
const isSchemeChar = (c) => isAsciiLetter(c) || (c >= 48 && c <= 57) || c === 43 || c === 45 || c === 46;
const SPECIAL_SCHEMES = new Set(["ftp", "file", "http", "https", "ws", "wss"]);
export function carriesCredential(peer) {
if (egressText("same-principal", peer) !== peer)
return true;
for (let mark = peer.indexOf("://"); mark !== -1; mark = peer.indexOf("://", mark + 3)) {
let from = mark;
while (from > 0 && isSchemeChar(peer.charCodeAt(from - 1)))
from--;
while (from < mark && !isAsciiLetter(peer.charCodeAt(from)))
from++;
if (from === mark)
continue;
const rest = peer.slice(mark + 3);
const end = rest.search(SPECIAL_SCHEMES.has(peer.slice(from, mark).toLowerCase()) ? /[\s/\\?#]/ : /[\s/?#]/);
const authority = end === -1 ? rest : rest.slice(0, end);
const at = authority.lastIndexOf("@");
if (at !== -1 && userinfoHolds(authority.slice(0, at)))
return true;
}
try {
const url = new URL(peer);
return url.username !== "" || url.password !== "";
}
catch {
return false;
}
}
const isIncarnation = (v) => namesSomething(v) && !carriesCredential(v);
function parseMemorySyncResponse(raw, scope, peer, claim, baselineEmpty) {
const fail = (why) => {
throw new Error(egressText("same-principal", `memory sync: transport response is not a valid sync response (${why})`));
};
if (!isRecord(raw))
fail("body must be a JSON object { applied, conflicts, serverEntries, serverDeletes, cursor }");
const b = raw;
if (Object.prototype.hasOwnProperty.call(b, "refused")) {
if (b["refused"] !== "baseline_incarnation")
fail(`refused must be "baseline_incarnation" — the one refusal a peer answers a sync with`);
const incarnation = b["incarnation"];
if (!isIncarnation(incarnation))
fail("a refusal's incarnation must be a non-empty string that holds no credential");
if (servesClaim(claim, baselineEmpty, incarnation))
fail(`the peer refused a sync its incarnation ${quoted(incarnation)} serves`);
throw cursorRefusal("incarnation", claim, incarnation);
}
const applied = [];
if (!Array.isArray(b["applied"]))
fail("applied must be an array");
for (const a of b["applied"]) {
if (!isRecord(a) || (a["op"] !== "add" && a["op"] !== "update" && a["op"] !== "delete") || !isNonEmptyString(a["id"])) {
fail("each applied item must be { op: add|update|delete, id }");
}
const rec = a;
applied.push({ op: rec["op"], id: rec["id"], ...(isNonEmptyString(rec["slug"]) ? { slug: rec["slug"] } : {}) });
}
const conflicts = [];
if (!Array.isArray(b["conflicts"]))
fail("conflicts must be an array");
for (const c of b["conflicts"]) {
if (!isRecord(c) || !isNonEmptyString(c["id"]) || typeof c["reason"] !== "string")
fail("each conflict must be { id, reason }");
const rec = c;
conflicts.push({
id: rec["id"],
reason: rec["reason"],
...(isNonEmptyString(rec["baseRev"]) ? { baseRev: rec["baseRev"] } : {}),
...(isNonEmptyString(rec["currentRev"]) ? { currentRev: rec["currentRev"] } : {}),
});
}
const serverEntries = [];
if (!Array.isArray(b["serverEntries"]))
fail("serverEntries must be an array");
for (const raw2 of b["serverEntries"]) {
if (!isRecord(raw2))
fail("each server entry must be an object { id, slug, frontmatter, body, rev, scope }");
const e = raw2;
if (!isNonEmptyString(e["id"]) || !isNonEmptyString(e["slug"]) || typeof e["body"] !== "string" || !isNonEmptyString(e["rev"])) {
fail("each server entry must carry non-empty id/slug/rev and a string body");
}
if (e["scope"] !== scope)
fail(`server entry ${JSON.stringify(e["id"])} has scope ${JSON.stringify(e["scope"])} — must equal the synced scope`);
const fmRaw = e["frontmatter"] ?? {};
if (!isRecord(fmRaw))
fail("entry.frontmatter must be an object");
const fm = fmRaw;
for (const k of ["name", "description", "type"]) {
if (fm[k] !== undefined && typeof fm[k] !== "string")
fail(`entry.frontmatter.${k} must be a string when present`);
}
if (fm["deleted"] !== undefined && typeof fm["deleted"] !== "boolean")
fail("entry.frontmatter.deleted must be a boolean when present");
if (fm["extra"] !== undefined && !(Array.isArray(fm["extra"]) && fm["extra"].every((s) => typeof s === "string"))) {
fail("entry.frontmatter.extra must be an array of strings when present");
}
if (fm["trust"] !== undefined && fm["trust"] !== "untrusted")
fail('entry.frontmatter.trust must be "untrusted" when present');
const provWire = fm["provenance"];
if (provWire !== undefined &&
(!isRecord(provWire) ||
provWire["kind"] !== "repo_file" ||
!isNonEmptyString(provWire["path"]) ||
!isNonEmptyString(provWire["contentHash"]) ||
typeof provWire["ingestedAt"] !== "number" ||
!Number.isFinite(provWire["ingestedAt"]))) {
fail('entry.frontmatter.provenance must be { kind: "repo_file", path, contentHash, ingestedAt } when present');
}
const originWire = fm["origin"];
if (originWire !== undefined &&
(!isRecord(originWire) ||
originWire["taint"] !== "external" ||
typeof originWire["at"] !== "number" ||
!Number.isFinite(originWire["at"]) ||
(originWire["cause"] !== undefined && !(typeof originWire["cause"] === "string" && MEMORY_ORIGIN_CAUSES.includes(originWire["cause"]))))) {
fail('entry.frontmatter.origin must be { taint: "external", cause?, at } with a known cause when present');
}
const distilledWire = fm["distilled"];
if (distilledWire !== undefined &&
(!isRecord(distilledWire) ||
!isNonEmptyString(distilledWire["planId"]) ||
typeof distilledWire["at"] !== "number" ||
!Number.isFinite(distilledWire["at"]) ||
!isNonEmptyString(distilledWire["carrierRev"]) ||
!(Array.isArray(distilledWire["inputs"]) &&
distilledWire["inputs"].length > 0 &&
distilledWire["inputs"].every((row) => isRecord(row) && isNonEmptyString(row["id"]) && isNonEmptyString(row["rev"]) && (row["superseded"] === undefined || row["superseded"] === true))))) {
fail("entry.frontmatter.distilled must be { planId, at, carrierRev, inputs: [{ id, rev, superseded? }, …] } when present");
}
const extraRaw = fm["extra"];
if (Array.isArray(extraRaw) && extraRaw.every((s) => typeof s === "string")) {
const pickedOrigin = originWire !== undefined
? {
taint: "external",
...(originWire["cause"] !== undefined ? { cause: originWire["cause"] } : {}),
at: originWire["at"],
}
: undefined;
if (ambiguousOriginRepresentation({ ...(pickedOrigin !== undefined ? { origin: pickedOrigin } : {}), extra: fm["extra"] })) {
fail("entry.frontmatter carries conflicting or duplicated origin representations (ambiguous marker representation refused)");
}
}
serverEntries.push({
id: e["id"],
slug: e["slug"],
body: e["body"],
rev: e["rev"],
scope,
frontmatter: {
...(fm["name"] !== undefined ? { name: fm["name"] } : {}),
...(fm["description"] !== undefined ? { description: fm["description"] } : {}),
...(fm["type"] !== undefined ? { type: fm["type"] } : {}),
...(fm["deleted"] !== undefined ? { deleted: fm["deleted"] } : {}),
...(provWire !== undefined
? {
provenance: {
kind: "repo_file",
path: provWire["path"],
contentHash: provWire["contentHash"],
ingestedAt: provWire["ingestedAt"],
},
}
: {}),
...(fm["trust"] !== undefined ? { trust: "untrusted" } : {}),
...(originWire !== undefined
? {
origin: {
taint: "external",
...(originWire["cause"] !== undefined ? { cause: originWire["cause"] } : {}),
at: originWire["at"],
},
}
: {}),
...(distilledWire !== undefined
? {
distilled: {
planId: distilledWire["planId"],
at: distilledWire["at"],
carrierRev: distilledWire["carrierRev"],
inputs: distilledWire["inputs"].map((row) => ({
id: row["id"],
rev: row["rev"],
...(row["superseded"] === true ? { superseded: true } : {}),
})),
},
}
: {}),
...(fm["extra"] !== undefined ? { extra: [...fm["extra"]] } : {}),
},
});
}
const serverDeletes = [];
if (!Array.isArray(b["serverDeletes"]))
fail("serverDeletes must be an array");
for (const d of b["serverDeletes"]) {
if (!isRecord(d) || !isNonEmptyString(d["id"]) || !isNonEmptyString(d["baseRev"]))
fail("each server delete must be { id, baseRev }");
const rec = d;
serverDeletes.push({ id: rec["id"], baseRev: rec["baseRev"] });
}
const cur = b["cursor"];
if (!isRecord(cur))
fail("cursor must be an object { peer, incarnation, baseRevs, updatedAtMs }");
const curRec = cur;
if (curRec["peer"] !== peer)
fail(`cursor.peer ${quoted(curRec["peer"])} does not match the requested peer ${quoted(peer)}`);
const incarnation = curRec["incarnation"];
if (!isIncarnation(incarnation))
fail("cursor.incarnation must be a non-empty string that holds no credential — the incarnation of the state that answered");
if (!servesClaim(claim, baselineEmpty, incarnation)) {
fail(claim !== undefined
? `cursor.incarnation ${quoted(incarnation)} does not match the requested peerIncarnation ${quoted(claim)}`
: `the request carried a non-empty baseline and no peerIncarnation, which a peer answers only by refusing it — not with a result under ${quoted(incarnation)}`);
}
if (!isRecord(curRec["baseRevs"]))
fail("cursor.baseRevs must be an object mapping id → rev");
const baseRevs = {};
for (const [id, rev] of Object.entries(curRec["baseRevs"])) {
if (!isNonEmptyString(rev))
fail(`cursor.baseRevs[${JSON.stringify(id)}] must be a non-empty rev string`);
baseRevs[id] = rev;
}
const updatedAtMs = curRec["updatedAtMs"];
if (typeof updatedAtMs !== "number" || !Number.isFinite(updatedAtMs))
fail("cursor.updatedAtMs must be a finite number");
const pullTruncatedRaw = b["pullTruncated"];
if (pullTruncatedRaw !== undefined && typeof pullTruncatedRaw !== "boolean")
fail("pullTruncated must be a boolean when present");
return {
applied,
conflicts,
serverEntries,
serverDeletes,
cursor: { peer, incarnation: incarnation, baseRevs, updatedAtMs: updatedAtMs },
...(pullTruncatedRaw === true ? { pullTruncated: true } : {}),
};
}
export async function syncMemoryScope(opts) {
const { backend, scope, transport, cursor } = opts;
if (!namesSomething(scope))
throw new Error("memory sync: scope must be a non-empty string");
if (!isReplicableScope(scope)) {
const e = new Error(egressText("same-principal", `memory sync: scope ${quoted(scope)} is a userlocal: key — its layer never leaves the store it is written in, so no sync carries it; ` +
"nothing was read or sent. Leave this scope out of what you sync; memory meant to travel goes under a scope that does not start with userlocal:."));
e.code = "config.memory_scope_key";
throw e;
}
const peer = transport?.peer;
if (!namesSomething(peer))
throw new Error("memory sync: transport.peer must be a non-empty string — a transport is { peer, post }, peer = the identity of the peer it reaches");
if (carriesCredential(peer)) {
throw new Error(`memory sync: transport.peer ${quoted(peer)} carries a credential — the identity rides the wire, the cursor and refusal sentences verbatim, so it is never a credential: name the peer without userinfo or secret`);
}
const now = opts.now ?? Date.now;
const { root: storeRoot, identity: store } = syncStoreOf(backend);
if (cursor !== undefined)
refuseForeignCursor(cursor, scope, peer, store);
const claimed = cursor === undefined ? undefined : cursor.peerIncarnation;
if (claimed !== undefined && !isIncarnation(claimed)) {
throw new Error(`memory sync: cursor.peerIncarnation must be a non-empty string that holds no credential when present — it is the incarnation a peer answered a sync with, carried back verbatim`);
}
const claim = claimed;
for (const [name, v] of [["maxPushEntries", opts.maxPushEntries], ["maxPullEntries", opts.maxPullEntries], ["maxEntryBytes", opts.maxEntryBytes]]) {
if (v !== undefined && (!Number.isSafeInteger(v) || v < 1)) {
throw new Error(`memory sync: ${name} must be a positive integer (>= 1) when set, got ${String(v)}`);
}
}
const baseRevs = { ...(cursor?.baseRevs ?? {}) };
const headers = (await backend.listHeaders([scope])).filter((h) => h.scope === scope);
const fetched = (await backend.getByIds(headers.map((h) => h.id))).filter((e) => e.scope === scope);
const local = fetched.filter((e) => e.frontmatter.deleted !== true);
const stubs = Object.entries(baseRevs).map(([id, rev]) => baselineStub(id, rev, scope));
const plan = reconcileMemoryEntries(baseRevs, local, stubs);
if (plan.pull.length > 0 || plan.deleteLocal.length > 0 || plan.conflicts.length > 0 || plan.cleared.length > 0) {
throw new Error("memory sync: internal invariant violated — a baseline-stub peer produced pull/deleteLocal/conflict/cleared legs");
}
const pushGateConflicts = [];
const gatedPush = plan.push.filter((e) => {
const findings = [];
const nameFinding = scanMemoryFileName(`${e.slug}.md`);
if (nameFinding !== undefined)
findings.push(nameFinding);
findings.push(...scanMemoryWrite(serializeEntryFile(e), { maxBytes: opts.maxEntryBytes ?? MAX_MEMORY_BYTES }));
if (findings.length === 0)
return true;
pushGateConflicts.push({
side: "local",
id: e.id,
reason: `push_gate: ${findings.map((f) => `${f.code}: ${f.reason}`).join("; ")} — the entry was NOT pushed (it stays local; fix or remove it to stop this report)`,
});
return false;
});
let pushEntries = gatedPush;
let pushTruncated = false;
if (opts.maxPushEntries !== undefined) {
pushEntries = [...gatedPush].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
if (pushEntries.length > opts.maxPushEntries) {
pushEntries = pushEntries.slice(0, opts.maxPushEntries);
pushTruncated = true;
}
}
const request = {
peer,
...(claim !== undefined ? { peerIncarnation: claim } : {}),
baseRevs,
entries: pushEntries,
deletes: plan.deleteRemote.map((d) => d.id),
...(opts.maxPullEntries !== undefined ? { pull: { limit: opts.maxPullEntries } } : {}),
};
const resp = parseMemorySyncResponse(await transport.post(memorySyncPath(scope), request), scope, peer, claim, Object.keys(baseRevs).length === 0);
const conflicts = [...pushGateConflicts, ...resp.conflicts.map((c) => ({ side: "server", ...c }))];
const rejected = new Set();
const localIds = new Set(local.map((e) => e.id));
const serverEntryIds = new Set(resp.serverEntries.map((e) => e.id));
for (const e of resp.serverEntries) {
const computed = computeEntryRev(e);
if (computed !== e.rev) {
rejected.add(e.id);
conflicts.push({
side: "local",
id: e.id,
reason: `rev_mismatch: server claimed ${JSON.stringify(e.rev)} but the content hashes to ${JSON.stringify(computed)} (rev is core's computeEntryRev content-hash contract)`,
...(baseRevs[e.id] !== undefined ? { baseRev: baseRevs[e.id] } : {}),
});
continue;
}
if (baseRevs[e.id] === undefined && localIds.has(e.id)) {
rejected.add(e.id);
conflicts.push({
side: "local",
id: e.id,
reason: `untracked_local_exists: server offers ${JSON.stringify(e.id)} as a first-round add, but an entry with that id already exists locally (concurrent create the server had not observed) — not overwritten`,
});
}
}
const heldIds = new Set(fetched.map((e) => e.id));
const unbaselined = resp.serverEntries.filter((e) => !rejected.has(e.id) && baseRevs[e.id] === undefined && !heldIds.has(e.id));
const deletionBlocked = new Set();
if (unbaselined.length > 0) {
const judged = reconcileMemoryEntries({}, [], unbaselined, { local: await memoryDeletionRecords(backend, unbaselined.map((e) => e.id), scope) });
for (const c of judged.conflicts) {
deletionBlocked.add(c.id);
const record = c.deletion?.record;
conflicts.push({
side: "local",
id: c.id,
reason: record?.kind === "undecidable"
? `deletion_record_unreadable: the center offers ${JSON.stringify(c.id)}, which this store does not hold, and whether this store deleted it cannot be read (${record.why}) — not brought back`
: `deleted_here: this store deleted ${JSON.stringify(c.id)}${c.baseRev !== undefined ? ` at rev ${JSON.stringify(c.baseRev)}` : ""} and the center offers it at rev ${JSON.stringify(c.remote?.rev)} — not brought back (re-judged next round; nothing deleted on the center)`,
...(c.remote?.rev !== undefined ? { currentRev: c.remote.rev } : {}),
});
}
}
const landable = (id) => !rejected.has(id) && !deletionBlocked.has(id);
for (const f of screenInboundEntries(resp.serverEntries.filter((e) => landable(e.id)))) {
rejected.add(f.id);
conflicts.push({
side: "local",
id: f.id,
reason: `inbound_gate: ${f.findings.map((x) => `${x.code}: ${x.reason}`).join("; ")}`,
...(baseRevs[f.id] !== undefined ? { baseRev: baseRevs[f.id] } : {}),
});
}
const deletePatches = [];
for (const d of resp.serverDeletes) {
if (serverEntryIds.has(d.id)) {
rejected.add(d.id);
conflicts.push({
side: "local",
id: d.id,
reason: `server_delete_and_entry: ${JSON.stringify(d.id)} appears in both serverEntries and serverDeletes of one response — the server cannot both push and delete it in one round`,
baseRev: d.baseRev,
});
continue;
}
const base = baseRevs[d.id];
if (base === undefined) {
rejected.add(d.id);
conflicts.push({
side: "local",
id: d.id,
reason: `server_delete_not_in_baseline: server asked to delete ${JSON.stringify(d.id)} but it is absent from our input baseline (never synced here — a delete may not cross onto an id the server has never seen from us)`,
baseRev: d.baseRev,
});
continue;
}
if (base !== d.baseRev) {
rejected.add(d.id);
conflicts.push({
side: "local",
id: d.id,
reason: `server_delete_baserev_mismatch: server delete claims baseRev ${JSON.stringify(d.baseRev)} but our baseline holds ${JSON.stringify(base)} — refused (concurrent local change since the baseline)`,
baseRev: base,
currentRev: d.baseRev,
});
continue;
}
deletePatches.push({ op: "delete", id: d.id, baseRev: base });
}
const patches = [
...resp.serverEntries
.filter((e) => landable(e.id))
.map((e) => {
const base = baseRevs[e.id];
return base !== undefined
? { op: "update", id: e.id, entry: e, baseRev: base }
: { op: "add", id: e.id, entry: e, guard: "absent" };
}),
...deletePatches,
];
const report = patches.length > 0 ? await applyPatchesWithin(backend, patches, [scope], { anchoredRoot: storeRoot }) : { applied: [], conflicts: [] };
for (const c of report.conflicts) {
conflicts.push({
side: "local",
id: c.id,
reason: c.reason,
...(c.baseRev !== undefined ? { baseRev: c.baseRev } : {}),
...(c.currentRev !== undefined ? { currentRev: c.currentRev } : {}),
});
}
const cursorAdvanced = rejected.size === 0 && report.conflicts.length === 0;
let nextCursor = cursor;
const warnings = [];
if (cursorAdvanced) {
const pulledRevById = new Map(resp.serverEntries.filter((e) => landable(e.id)).map((e) => [e.id, e.rev]));
const pushedRevById = new Map(request.entries.map((e) => [e.id, e.rev]));
const serverAppliedIds = new Set(resp.applied.filter((a) => a.op !== "delete").map((a) => a.id));
const disputedIds = new Set(resp.conflicts.map((c) => c.id));
const pushAcked = (id, rev) => rev === pushedRevById.get(id) && (serverAppliedIds.has(id) || !disputedIds.has(id));
const nextBaseRevs = {};
for (const [id, rev] of Object.entries(resp.cursor.baseRevs)) {
if (rev === baseRevs[id] || pushAcked(id, rev) || rev === pulledRevById.get(id)) {
nextBaseRevs[id] = rev;
continue;
}
const retained = baseRevs[id];
const conflictedPush = rev === pushedRevById.get(id);
if (retained !== undefined) {
nextBaseRevs[id] = retained;
warnings.push(conflictedPush
? `cursor_prefill_rejected: server cursor advanced ${JSON.stringify(id)} to our pushed rev ${JSON.stringify(rev)} while reporting that push rejected/conflicted — kept the old baseline ${JSON.stringify(retained)} (the local version stays re-pushed / ladder-escalated next round instead of being silently overwritten)`
: `cursor_prefill_rejected: server cursor advanced ${JSON.stringify(id)} to ${JSON.stringify(rev)} without delivering it this round — kept the old baseline ${JSON.stringify(retained)} (the entry stays pullable next round)`);
}
else {
warnings.push(`cursor_prefill_rejected: server cursor introduced ${JSON.stringify(id)} at ${JSON.stringify(rev)} but never delivered it — dropped from the baseline (accepting it would spuriously delete-propagate an entry never seen here)`);
}
}
for (const op of report.applied) {
if (op.op === "delete") {
delete nextBaseRevs[op.id];
}
else {
const landedRev = pulledRevById.get(op.id);
if (landedRev !== undefined)
nextBaseRevs[op.id] = landedRev;
}
}
nextCursor = { scope, peer, peerIncarnation: resp.cursor.incarnation, store, baseRevs: nextBaseRevs, updatedAtMs: now() };
}
return {
ok: cursorAdvanced && conflicts.length === 0,
pushed: { entries: request.entries.map((e) => e.id), deletes: [...request.deletes] },
serverApplied: resp.applied,
localApplied: report.applied,
conflicts,
cursorAdvanced,
cursor: nextCursor,
...(pushTruncated ? { pushTruncated: true } : {}),
...(resp.pullTruncated === true ? { pullTruncated: true } : {}),
...(warnings.length > 0 ? { warnings } : {}),
};
}