@remnic/core 9.45.1 → 9.45.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -440,4 +440,4 @@ export {
440
440
  summarizeReconcilePlan,
441
441
  planReconciliation
442
442
  };
443
- //# sourceMappingURL=chunk-K442KOID.js.map
443
+ //# sourceMappingURL=chunk-HZFHQ4AQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/reconcile/plan.ts"],"sourcesContent":["import { normalizeNamespaceIdentity } from \"../namespaces/identity.js\";\nimport { OFFLINE_SYNC_MAX_MTIME_MS } from \"../offline-sync.js\";\nimport { validateArchiveRelativePath } from \"../transfer/fs-utils.js\";\nimport type { OfflineSyncFileState } from \"../offline-sync.js\";\nimport {\n CONVERGE_CONFLICT_POLICIES,\n DEFAULT_CONVERGE_CONFLICT_POLICY,\n} from \"../converge-config.js\";\nimport type { ConvergeConflictPolicy } from \"../types.js\";\nexport type ReconcileConflictPolicy = ConvergeConflictPolicy;\n\n/**\n * Bootstrap reconciliation planner for two peer daemons whose corpora have\n * already diverged (issue #2150).\n *\n * The offline-sync protocol assumes a satellite that shares a common base with\n * one daemon: every path it does not know about is a pull, and a conflict is\n * rare. Two long-lived daemons are the opposite case — each side holds months\n * of history the other never saw, both sides are authoritative, and there is\n * NO common base on the first run. That is a different decision problem, so it\n * gets its own planner rather than another mode flag inside `applyOfflineSync*`.\n *\n * This module is deliberately pure: it takes two file censuses and returns what\n * to do. No I/O, no transport, no clock. Everything that makes reconciliation\n * risky — which side wins, what counts as converged, what is reported — is\n * decided here where it can be exhaustively tested, and the transport layer is\n * left to carry out an already-settled plan.\n */\n\n/** Which way a path must move for the two corpora to agree. */\nexport type ReconcileAction = \"pull\" | \"push\" | \"identical\" | \"conflict\" | \"suppress\";\n\n/**\n * What the planner decided for a conflicting path.\n * `supersede-link` records that both revisions need durable preservation when\n * timestamps cannot safely select a winner. Apply must stop until transport\n * can assign distinct durable identities to both revisions.\n */\nexport type ReconcileResolution = \"local-wins\" | \"peer-wins\" | \"supersede-link\" | \"unresolved\";\n\nexport interface ReconcileSemanticFileState {\n path: string;\n sha256: string;\n}\n\nexport interface ReconcileSemanticAgreement {\n local: ReconcileSemanticFileState;\n peer: ReconcileSemanticFileState;\n}\n\nexport type ReconcileSemanticChange = \"unchanged\" | \"local_changed\" | \"peer_changed\" | \"both_modified\";\n\nexport interface ReconcilePlanEntry {\n path: string;\n namespace: string;\n action: ReconcileAction;\n /** Stable machine-readable cause, safe to assert on and to aggregate. */\n reason: ReconcileReason;\n localSha256?: string;\n peerSha256?: string;\n /** Present only when a prior converged run left a cursor covering this path. */\n baseSha256?: string;\n /** Set only when `action` is `conflict`. */\n resolution?: ReconcileResolution;\n /**\n * Which side holds the retracted revision. Set only when `action` is\n * `suppress`: with different digests on each side and only one retracted,\n * the entry would otherwise be identical either way and transport could\n * delete the live copy instead of the retracted one.\n */\n suppressSide?: \"local\" | \"peer\" | \"both\";\n /**\n * Real per-side identities for a cross-path semantic agreement. Synthetic\n * rows omit the top-level side digests because `path` cannot name both files.\n */\n semanticAgreement?: ReconcileSemanticAgreement;\n /** Each side's current digest compared with its own prior semantic digest. */\n semanticChange?: ReconcileSemanticChange;\n}\n\nexport type ReconcileReason =\n | \"peer_only\"\n | \"local_only\"\n /** Cursor showed only that side moved since agreement; both still hold the path. */\n | \"peer_changed\"\n | \"local_changed\"\n | \"same_content\"\n | \"semantic_duplicate\"\n | \"both_modified\"\n | \"peer_deleted\"\n | \"local_deleted\"\n /** Peer deleted it while this side edited it — the offline-sync delete/modify pair. */\n | \"local_modified_peer_deleted\"\n | \"local_deleted_peer_modified\"\n | \"tombstoned\";\n\nexport interface ReconcileNamespaceReport {\n namespace: string;\n pull: number;\n push: number;\n identical: number;\n conflict: number;\n /** Local retractions the peer must be told about before the pair agrees. */\n suppress: number;\n /**\n * Conflicts still needing an operator: those the policy declined to settle,\n * plus supersede links whose direction could not be determined.\n */\n unresolved: number;\n}\n\nexport interface ReconcilePlan {\n entries: ReconcilePlanEntry[];\n byNamespace: ReconcileNamespaceReport[];\n /**\n * True when the two corpora already agree — every shared path matches and\n * neither side holds a path the other lacks.\n *\n * This is the idempotency contract from #2150: running reconciliation against\n * an already-converged peer must be a no-op, and a caller can skip the whole\n * transfer phase on this flag alone.\n */\n converged: boolean;\n}\n\n/** Minimal shape the planner needs; `OfflineSyncFileState` satisfies it. */\nexport type ReconcileFileState = Pick<OfflineSyncFileState, \"path\" | \"sha256\"> &\n Partial<Pick<OfflineSyncFileState, \"mtimeMs\" | \"bytes\">>;\n\nexport interface ReconcileNamespaceInput {\n namespace: string;\n local: Iterable<ReconcileFileState>;\n peer: Iterable<ReconcileFileState>;\n /**\n * File states agreed at the end of the last converged run with THIS peer.\n * Absent on a bootstrap merge, which is why a path missing from one side is\n * read as \"never seen\" rather than \"deleted\".\n */\n base?: Iterable<ReconcileFileState>;\n /**\n * Revision timestamps for paths deleted locally since the base cursor.\n * A deletion is a revision and must carry a comparable time for\n * `newest-wins`; absence alone has no timestamp.\n */\n localDeletionMtimeMs?: ReadonlyMap<string, number>;\n /** Revision timestamps for paths deleted by the peer since the base cursor. */\n peerDeletionMtimeMs?: ReadonlyMap<string, number>;\n /**\n * Digests of FILES this side has retracted, in the same form as\n * `ReconcileFileState.sha256` — a hash of the serialized file.\n *\n * Deliberately NOT `TombstoneEntry.contentHash`, which hashes the canonical\n * raw fact text and therefore never equals a file digest (§13: one content\n * form, everywhere). Mapping retracted fact hashes onto the file digests that\n * carry them is the caller's job, because only the caller can read its own\n * corpus; handing this the wrong form would silently plan `pull` and\n * resurrect every retracted fact, so the parameter name states the form.\n */\n tombstonedFileSha256?: Iterable<string>;\n /**\n * Digests the PEER has retracted, same form.\n *\n * Without this a bootstrap merge cannot tell \"the peer never had it\" from\n * \"the peer deliberately retracted it\": the peer census simply omits both,\n * so a file we still hold is planned `push` and the peer's retraction is\n * undone. Reconciliation is symmetric, so retraction has to be too.\n *\n * SCOPE: these sets decide what happens to files that still EXIST on one\n * side. Sharing the retraction records themselves is not modelled here -\n * tombstones are corpus files (`state/tombstones.jsonl`), so they reconcile\n * as ordinary paths through this same plan. A digest both censuses have\n * already dropped therefore produces no entry, by design: there is no file\n * left to act on, and synthesizing a path-less entry would hand transport\n * something it cannot apply.\n */\n peerTombstonedFileSha256?: Iterable<string>;\n}\n\nexport interface ReconcileOptions {\n conflictPolicy?: ConvergeConflictPolicy;\n}\n\n/**\n * A census the planner refuses to reason about.\n *\n * Dropping a malformed or contradictory record would let the planner return\n * `converged: true` for a corpus it could not actually read, and transport is\n * invited to skip everything on that flag — so bad input fails loudly instead\n * (§1/§39).\n */\nexport class ReconcilePlanInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ReconcilePlanInputError\";\n }\n}\n\n/** Matches `assertSha256` in offline-sync so both surfaces reject the same values (§40). */\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/i;\n\n/**\n * Validate a census record's identity fields.\n *\n * The digest matters as much as the path: two records that both omit `sha256`\n * compare `undefined === undefined` and plan as `identical`, converging a\n * corpus the planner never actually read.\n */\nfunction assertCensusRecord(\n file: ReconcileFileState | undefined,\n side: string,\n namespace: string,\n): ReconcileFileState {\n const path = file?.path;\n if (typeof path !== \"string\" || path.length === 0) {\n throw new ReconcilePlanInputError(\n `reconcile: ${side} census for namespace ${namespace} contains a record with no path`,\n );\n }\n // Same boundary offline-sync applies to this field: a peer census is\n // untrusted input, and an absolute or traversal path would otherwise become\n // a transfer instruction pointing outside the corpus root.\n try {\n validateArchiveRelativePath(path, `reconcile: ${side} census for namespace ${namespace}`);\n } catch (err) {\n throw new ReconcilePlanInputError(err instanceof Error ? err.message : String(err));\n }\n assertPortablePathSegments(path, side, namespace);\n return {\n ...file,\n path,\n sha256: assertDigest(file?.sha256, `${side} census for namespace ${namespace} entry ${path}`),\n ...(file?.mtimeMs === undefined\n ? {}\n : { mtimeMs: assertMtimeMs(file.mtimeMs, `${side} census for namespace ${namespace} entry ${path}`) }),\n };\n}\n\n/**\n * `newest-wins` decides which corpus keeps its history from this number, so a\n * NaN, an Infinity or a value past the Date range must not pick the winner.\n *\n * Fractional values ARE valid: `fs.stat()` reports sub-millisecond mtimes on\n * common filesystems and offline-sync forwards them unrounded, so this matches\n * its `assertOfflineSyncMtimeMs` — non-negative finite within Date range — and\n * deliberately does not require an integer.\n */\nfunction assertMtimeMs(value: unknown, context: string): number {\n if (\n typeof value !== \"number\"\n || !Number.isFinite(value)\n || value < 0\n || value > OFFLINE_SYNC_MAX_MTIME_MS\n ) {\n throw new ReconcilePlanInputError(\n `reconcile: ${context} has an out-of-range mtimeMs; expected a finite value between 0 and ${OFFLINE_SYNC_MAX_MTIME_MS}`,\n );\n }\n return value;\n}\n\n/**\n * Digests are canonicalized to lowercase, exactly as offline-sync's\n * `assertSha256` does. Keeping the caller's spelling would make two forms of\n * one digest compare unequal, so identical files would plan `both_modified`\n * and tombstone lookups would silently miss.\n */\nfunction assertDigest(value: unknown, context: string): string {\n if (typeof value !== \"string\" || !SHA256_PATTERN.test(value)) {\n throw new ReconcilePlanInputError(\n `reconcile: ${context} must carry a 64-character sha256 hex digest`,\n );\n }\n return value.toLowerCase();\n}\n\nfunction isPlainObject(value: unknown): boolean {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nfunction assertNamespace(namespace: unknown): string {\n if (typeof namespace !== \"string\" || namespace.length === 0) {\n throw new ReconcilePlanInputError(\"reconcile: every namespace input needs a non-empty namespace\");\n }\n // `team` and ` team ` are one namespace to the rest of core, so accepting\n // both here would slip two inputs past the duplicate check and let them plan\n // contradictory actions for the same path. Rejected rather than silently\n // rewritten, so the namespace on every entry is the caller's own string.\n if (LONE_SURROGATE.test(namespace)) {\n // `namespaceIdentityToken()` encodes through TextEncoder, so a lone\n // surrogate and a literal U+FFFD collapse to ONE storage identity while\n // comparing as two here - slipping both past the duplicate-namespace guard.\n throw new ReconcilePlanInputError(\n \"reconcile: namespace contains an unpaired surrogate; it would collide with another namespace on disk\",\n );\n }\n if (normalizeNamespaceIdentity(namespace) !== namespace) {\n throw new ReconcilePlanInputError(\n `reconcile: namespace ${JSON.stringify(namespace)} is not canonical; pass ${JSON.stringify(normalizeNamespaceIdentity(namespace))}`,\n );\n }\n return namespace;\n}\n\nfunction assertIterable(value: unknown, side: string, namespace: string): Iterable<ReconcileFileState> {\n if (value === null || typeof value !== \"object\" || typeof (value as Iterable<ReconcileFileState>)[Symbol.iterator] !== \"function\") {\n throw new ReconcilePlanInputError(`reconcile: ${side} census for namespace ${namespace} must be iterable`);\n }\n return value as Iterable<ReconcileFileState>;\n}\n\n/**\n * Two paths that a participant's filesystem resolves to ONE file must not draw\n * separate push/pull work, or application order decides which revision\n * survives. Remnic is explicitly multi-platform, so all three aliasing rules\n * are folded together and a collision is rejected rather than raced:\n * case (macOS, Windows), Unicode normalization (macOS stores decomposed and\n * compares canonically), and Win32 trailing dots/spaces, which the Windows API\n * strips before touching disk.\n */\n// eslint-disable-next-line no-control-regex -- control characters are exactly what this rejects\nconst WIN32_INVALID_CHARS = /[<>:\"|?*\\u0000-\\u001f]/;\n// Windows treats the superscripts as their digits in COM/LPT device names.\nconst LONE_SURROGATE = /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\nconst WIN32_RESERVED_NAMES = /^(con|prn|aux|nul|(com|lpt)[1-9\\u00b9\\u00b2\\u00b3])$/i;\n\nfunction assertPortablePathSegments(path: string, side: string, namespace: string): void {\n for (const segment of path.split(\"/\")) {\n if (segment.length === 0) continue;\n if (segment.endsWith(\".\") || segment.endsWith(\" \")) {\n throw new ReconcilePlanInputError(\n `reconcile: ${side} census for namespace ${namespace} path ${path} has a segment ending in a dot or space; ` +\n \"Windows strips those and would alias it onto another file\",\n );\n }\n // `:` opens an alternate data stream, the rest cannot be created at all,\n // and a reserved device name resolves to hardware. A plan containing any of\n // them cannot be applied on a Windows participant.\n if (LONE_SURROGATE.test(segment)) {\n // Node encodes an unpaired surrogate as U+FFFD, so this path and a\n // literal U+FFFD path are one file on disk while comparing as distinct.\n throw new ReconcilePlanInputError(\n `reconcile: ${side} census for namespace ${namespace} path ${path} contains an unpaired surrogate`,\n );\n }\n if (WIN32_INVALID_CHARS.test(segment)) {\n throw new ReconcilePlanInputError(\n `reconcile: ${side} census for namespace ${namespace} path ${path} contains a character Windows cannot store`,\n );\n }\n if (WIN32_RESERVED_NAMES.test(segment.split(\".\")[0] ?? \"\")) {\n throw new ReconcilePlanInputError(\n `reconcile: ${side} census for namespace ${namespace} path ${path} uses a reserved Windows device name`,\n );\n }\n }\n}\n\nfunction assertNoPathAlias(\n seen: Map<string, string>,\n path: string,\n namespace: string,\n): void {\n // NFC first: macOS stores decomposed names and compares canonically, so\n // `é` (U+00E9) and `é` (e + U+0301) are ONE file there. Then a FULL caseless\n // fold - upper-then-lower, which collapses forms a bare toLowerCase() keeps\n // apart, such as final sigma `ς` against `σ`. Lowercasing alone would leave\n // those distinct and the planner would emit both a push and a pull.\n // `ß` upper-folds to `ss` while `ẞ` folds to `ß`, so one more pass equalizes\n // the pair that a single upper-then-lower still leaves apart.\n const folded = path.normalize(\"NFC\").toUpperCase().toLowerCase().replace(/\\u00df/g, \"ss\");\n const existing = seen.get(folded);\n if (existing !== undefined && existing !== path) {\n throw new ReconcilePlanInputError(\n `reconcile: namespace ${namespace} has aliasing paths (${existing}, ${path}); ` +\n \"they resolve to one file on a case-insensitive or Unicode-normalizing peer\",\n );\n }\n seen.set(folded, path);\n}\n\n/**\n * Duplicate paths are accepted only when they agree. Two digests for one path\n * make the plan depend on which record arrived last, which would break the\n * byte-stable ordering the convergence report relies on.\n */\nfunction rejectConflictingDuplicate(\n existing: { sha256: string; mtimeMs?: number } | undefined,\n incoming: { sha256: string; mtimeMs?: number },\n path: string,\n side: string,\n namespace: string,\n): boolean {\n if (!existing) return false;\n if (existing.sha256 !== incoming.sha256) {\n throw new ReconcilePlanInputError(\n `reconcile: ${side} census for namespace ${namespace} lists ${path} twice with different digests`,\n );\n }\n // Same bytes but a different mtime is still ambiguous: `newest-wins` reads\n // that timestamp, so accepting the first arrival would let input order decide\n // the winner.\n if (existing.mtimeMs !== incoming.mtimeMs) {\n throw new ReconcilePlanInputError(\n `reconcile: ${side} census for namespace ${namespace} lists ${path} twice with different mtimeMs`,\n );\n }\n return true;\n}\n\nfunction indexByPath(\n files: Iterable<ReconcileFileState>,\n side: string,\n namespace: string,\n): Map<string, ReconcileFileState> {\n const index = new Map<string, ReconcileFileState>();\n for (const raw of files) {\n const file = assertCensusRecord(raw, side, namespace);\n if (rejectConflictingDuplicate(index.get(file.path), file, file.path, side, namespace)) continue;\n index.set(file.path, file);\n }\n return index;\n}\n\n/**\n * A bare string satisfies `Iterable<string>`, and `new Set(\"abc…\")` would split\n * it into 64 one-character members — every membership test then misses and each\n * retracted file is planned as `pull` and resurrected. Reject the scalar and\n * canonicalize every member.\n */\nfunction parseTombstonedDigests(\n value: Iterable<string> | undefined,\n namespace: string,\n field = \"tombstonedFileSha256\",\n): Set<string> {\n if (value === undefined) return new Set();\n if (typeof value === \"string\") {\n throw new ReconcilePlanInputError(\n `reconcile: ${field} for namespace ${namespace} must be a collection of digests, not a single string`,\n );\n }\n if (value === null || typeof value !== \"object\" || typeof value[Symbol.iterator] !== \"function\") {\n // Otherwise the for...of below throws a raw TypeError and a caller handling\n // ReconcilePlanInputError cannot tell a bad request from a planner bug.\n throw new ReconcilePlanInputError(\n `reconcile: ${field} for namespace ${namespace} must be an iterable collection of digests`,\n );\n }\n const digests = new Set<string>();\n for (const entry of value) {\n digests.add(assertDigest(entry, `${field} for namespace ${namespace}`));\n }\n return digests;\n}\n\n/**\n * Validate a census while keeping ONLY path -> digest.\n *\n * The base cursor is read for digests alone, so indexing full records and\n * compacting afterwards would hold a corpus-sized record map and its copy at\n * once - the peak this avoids.\n */\nfunction indexDigestsByPath(\n files: Iterable<ReconcileFileState>,\n side: string,\n namespace: string,\n): Map<string, string> {\n const index = new Map<string, string>();\n for (const raw of files) {\n const file = assertCensusRecord(raw, side, namespace);\n const existing = index.get(file.path);\n // One map, not a parallel `seen`: the base's own mtimeMs is never a\n // decision input (only the local and peer timestamps order a conflict), so\n // a duplicate that agrees on the digest is unambiguous here regardless of\n // its timestamp, and the digest alone is enough to detect a real clash.\n if (existing !== undefined) {\n if (existing !== file.sha256) {\n throw new ReconcilePlanInputError(\n `reconcile: ${side} census for namespace ${namespace} lists ${file.path} twice with different digests`,\n );\n }\n continue;\n }\n index.set(file.path, file.sha256);\n }\n return index;\n}\n\nfunction assertConflictPolicy(value: ConvergeConflictPolicy | undefined): ConvergeConflictPolicy {\n if (value === undefined) return DEFAULT_CONVERGE_CONFLICT_POLICY;\n if (!CONVERGE_CONFLICT_POLICIES.includes(value)) {\n throw new ReconcilePlanInputError(\n `reconcile: unknown conflictPolicy ${JSON.stringify(value)}; expected one of ${CONVERGE_CONFLICT_POLICIES.join(\", \")}`,\n );\n }\n return value;\n}\n\n/**\n * Total ordering for plan entries (§12): namespace, then path. Both are unique\n * per entry, so equal keys are impossible and the comparator never has to\n * return 0 for distinct rows — the output is byte-identical across runs, which\n * is what makes a convergence report diffable.\n */\nfunction compareEntries(a: ReconcilePlanEntry, b: ReconcilePlanEntry): number {\n if (a.namespace !== b.namespace) return a.namespace < b.namespace ? -1 : 1;\n if (a.path !== b.path) return a.path < b.path ? -1 : 1;\n return 0;\n}\n\n\nfunction resolveConflict(\n policy: ConvergeConflictPolicy,\n localMtimeMs: number | undefined,\n peerMtimeMs: number | undefined,\n missingTimestampResolution: ReconcileResolution,\n): ReconcileResolution {\n if (policy !== \"newest-wins\") return \"unresolved\";\n if (localMtimeMs === undefined || peerMtimeMs === undefined || localMtimeMs === peerMtimeMs) {\n return missingTimestampResolution;\n }\n return localMtimeMs > peerMtimeMs ? \"local-wins\" : \"peer-wins\";\n}\n\nfunction parseDeletionMtimes(\n value: ReadonlyMap<string, number> | undefined,\n side: string,\n namespace: string,\n): ReadonlyMap<string, number> {\n if (value === undefined) return new Map();\n if (!(value instanceof Map)) {\n throw new ReconcilePlanInputError(\n `reconcile: ${side} deletion mtimes for namespace ${namespace} must be a Map`,\n );\n }\n const parsed = new Map<string, number>();\n for (const [path, mtimeMs] of value) {\n try {\n validateArchiveRelativePath(path, `reconcile: ${side} deletion mtimes for namespace ${namespace}`);\n } catch (err) {\n throw new ReconcilePlanInputError(err instanceof Error ? err.message : String(err));\n }\n assertPortablePathSegments(path, side, namespace);\n parsed.set(path, assertMtimeMs(mtimeMs, `${side} deletion for namespace ${namespace} entry ${path}`));\n }\n return parsed;\n}\n\n/**\n * Plan one namespace. Exposed for callers that stream namespaces one at a time.\n *\n * Residency is one peer index + a set of local paths + the entry list. The\n * local census is consumed as a stream and never materialized, so a 100k-file\n * corpus does not hold two full censuses at once — but this is NOT constant\n * memory, and a caller holding its own census arrays adds to that.\n */\nexport function planNamespaceReconciliation(\n input: ReconcileNamespaceInput,\n options: ReconcileOptions = {},\n): ReconcilePlanEntry[] {\n if (!isPlainObject(input)) {\n throw new ReconcilePlanInputError(\"reconcile: namespace input must be a plain object\");\n }\n if (!isPlainObject(options)) {\n // A Date, Map or RegExp passes a bare typeof check, exposes no\n // `conflictPolicy`, and would silently take the default policy - hiding a\n // malformed request behind `manual`.\n throw new ReconcilePlanInputError(\"reconcile: options must be a plain object\");\n }\n const namespace = assertNamespace(input.namespace);\n const policy = assertConflictPolicy(options.conflictPolicy);\n const localCensus = assertIterable(input.local, \"local\", namespace);\n const caseFold = new Map<string, string>();\n // Index the peer census only, then stream the local one against it, removing\n // each match as it is consumed. Peak residency is one index plus the entry\n // list rather than two full censuses (round 2, codex P2).\n const peer = indexByPath(assertIterable(input.peer, \"peer\", namespace), \"peer\", namespace);\n // Only `base.sha256` is ever read, so the base is compacted to path -> digest\n // instead of a second full record index (round 7, codex P2).\n // Only an ABSENT base means bootstrap. A null/invalid cursor silently read as\n // \"no prior agreement\" would turn a peer-side deletion into a push and\n // resurrect it.\n const base = input.base === undefined\n ? null\n : indexDigestsByPath(assertIterable(input.base, \"base\", namespace), \"base\", namespace);\n const tombstoned = parseTombstonedDigests(input.tombstonedFileSha256, namespace);\n const peerTombstoned = parseTombstonedDigests(\n input.peerTombstonedFileSha256,\n namespace,\n \"peerTombstonedFileSha256\",\n );\n const localDeletionMtimeMs = parseDeletionMtimes(input.localDeletionMtimeMs, \"local\", namespace);\n const peerDeletionMtimeMs = parseDeletionMtimes(input.peerDeletionMtimeMs, \"peer\", namespace);\n const entries: ReconcilePlanEntry[] = [];\n\n // Path -> digest only, never the file objects: enough to make the stream\n // idempotent and to catch contradictory duplicates without materializing the\n // second census.\n // Base paths participate in the collision check: a base `Facts/A.md` against\n // a local `facts/a.md` is the same delete/change ambiguity on a\n // case-insensitive participant.\n if (base) for (const basePath of base.keys()) assertNoPathAlias(caseFold, basePath, namespace);\n // Path -> decision-relevant fields only, never the whole record: enough to\n // make the stream idempotent and to catch contradictory duplicates without\n // materializing the second census.\n const seenLocal = new Map<string, { sha256: string; mtimeMs?: number }>();\n for (const rawLocal of localCensus) {\n const localFile = assertCensusRecord(rawLocal, \"local\", namespace);\n const path = localFile.path;\n assertNoPathAlias(caseFold, path, namespace);\n const seen = seenLocal.get(path);\n if (seen !== undefined) {\n // Same rule the indexed censuses get: mtimeMs is decision-relevant under\n // `newest-wins`, so a duplicate that disagrees on it is ambiguous too.\n if (rejectConflictingDuplicate(seen, localFile, path, \"local\", namespace)) continue;\n }\n seenLocal.set(path, { sha256: localFile.sha256, mtimeMs: localFile.mtimeMs });\n const peerFile = peer.get(path);\n // Consumed: whatever remains in the index afterwards is peer-only.\n peer.delete(path);\n const baseSha256 = base?.get(path);\n // Retraction outranks every other decision for this path, on EITHER side.\n // Checked before hash comparison and conflict resolution: a retracted peer\n // revision reaching the conflict ladder can win under `newest-wins`, and a\n // retracted LOCAL revision would otherwise be pushed - which is also how a\n // suppression undoes itself on the next run, since the local copy survives\n // the peer-side delete (round 4).\n // Either side's retraction removes the copy that carries the digest, so a\n // peer retraction of something we still hold suppresses OUR copy rather\n // than pushing it back.\n const localRetracted = tombstoned.has(localFile.sha256) || peerTombstoned.has(localFile.sha256);\n const peerRetracted =\n peerFile !== undefined && (tombstoned.has(peerFile.sha256) || peerTombstoned.has(peerFile.sha256));\n if (localRetracted || peerRetracted) {\n entries.push({\n path,\n namespace,\n action: \"suppress\",\n reason: \"tombstoned\",\n localSha256: localFile.sha256,\n ...(peerFile ? { peerSha256: peerFile.sha256 } : {}),\n ...(baseSha256 === undefined ? {} : { baseSha256 }),\n suppressSide: localRetracted && peerRetracted ? \"both\" : localRetracted ? \"local\" : \"peer\",\n });\n continue;\n }\n if (!peerFile) {\n // Base PRESENCE is what proves a deletion, not equality with whatever the\n // surviving side now holds. If we also edited since the base, this is\n // delete-versus-modify: still a conflict, and pushing it would resurrect\n // a deliberate deletion. Without a base the peer simply never saw the\n // path, and a bootstrap merge must push — both sides hold unique data.\n if (baseSha256 !== undefined) {\n entries.push({\n path,\n namespace,\n action: \"conflict\",\n reason: baseSha256 === localFile.sha256 ? \"peer_deleted\" : \"local_modified_peer_deleted\",\n localSha256: localFile.sha256,\n baseSha256,\n resolution: baseSha256 === localFile.sha256\n ? \"unresolved\"\n : resolveConflict(\n policy,\n localFile.mtimeMs,\n peerDeletionMtimeMs.get(path),\n \"unresolved\",\n ),\n });\n continue;\n }\n entries.push({\n path,\n namespace,\n action: \"push\",\n reason: \"local_only\",\n localSha256: localFile.sha256,\n });\n continue;\n }\n if (peerFile.sha256 === localFile.sha256) {\n entries.push({\n path,\n namespace,\n action: \"identical\",\n reason: \"same_content\",\n localSha256: localFile.sha256,\n peerSha256: peerFile.sha256,\n ...(baseSha256 === undefined ? {} : { baseSha256 }),\n });\n continue;\n }\n // A base that matches one side turns a \"conflict\" into an ordinary\n // one-sided change: that side is the only one that moved since agreement.\n if (baseSha256 !== undefined && baseSha256 === localFile.sha256) {\n entries.push({\n path,\n namespace,\n action: \"pull\",\n reason: \"peer_changed\",\n localSha256: localFile.sha256,\n peerSha256: peerFile.sha256,\n baseSha256,\n });\n continue;\n }\n if (baseSha256 !== undefined && baseSha256 === peerFile.sha256) {\n entries.push({\n path,\n namespace,\n action: \"push\",\n reason: \"local_changed\",\n localSha256: localFile.sha256,\n peerSha256: peerFile.sha256,\n baseSha256,\n });\n continue;\n }\n const resolution = resolveConflict(\n policy,\n localFile.mtimeMs,\n peerFile.mtimeMs,\n \"supersede-link\",\n );\n entries.push({\n path,\n namespace,\n action: \"conflict\",\n reason: \"both_modified\",\n localSha256: localFile.sha256,\n peerSha256: peerFile.sha256,\n ...(baseSha256 === undefined ? {} : { baseSha256 }),\n resolution,\n });\n }\n\n for (const [path, peerFile] of peer) {\n assertNoPathAlias(caseFold, path, namespace);\n const baseSha256 = base?.get(path);\n if (tombstoned.has(peerFile.sha256) || peerTombstoned.has(peerFile.sha256)) {\n // Retracted here on purpose, and the peer still serves it. Pulling it\n // back would undo the retraction; calling it `identical` would be worse,\n // because a converged plan lets transport skip everything and the peer\n // keeps serving the retracted fact forever. It is work: propagate the\n // tombstone.\n entries.push({\n path,\n namespace,\n action: \"suppress\",\n reason: \"tombstoned\",\n peerSha256: peerFile.sha256,\n ...(baseSha256 === undefined ? {} : { baseSha256 }),\n suppressSide: \"peer\",\n });\n continue;\n }\n if (baseSha256 !== undefined) {\n entries.push({\n path,\n namespace,\n action: \"conflict\",\n reason: baseSha256 === peerFile.sha256 ? \"local_deleted\" : \"local_deleted_peer_modified\",\n peerSha256: peerFile.sha256,\n baseSha256,\n resolution: baseSha256 === peerFile.sha256\n ? \"unresolved\"\n : resolveConflict(\n policy,\n localDeletionMtimeMs.get(path),\n peerFile.mtimeMs,\n \"unresolved\",\n ),\n });\n continue;\n }\n entries.push({\n path,\n namespace,\n action: \"pull\",\n reason: \"peer_only\",\n peerSha256: peerFile.sha256,\n });\n }\n\n return entries.sort(compareEntries);\n}\n\n/** Aggregate entries into the per-namespace convergence report (#2150). */\nexport function summarizeReconcilePlan(entries: readonly ReconcilePlanEntry[]): ReconcileNamespaceReport[] {\n const byNamespace = new Map<string, ReconcileNamespaceReport>();\n for (const entry of entries) {\n let report = byNamespace.get(entry.namespace);\n if (!report) {\n report = { namespace: entry.namespace, pull: 0, push: 0, identical: 0, conflict: 0, suppress: 0, unresolved: 0 };\n byNamespace.set(entry.namespace, report);\n }\n report[entry.action] += 1;\n const needsOperator =\n entry.resolution === \"unresolved\"\n || entry.resolution === \"supersede-link\";\n if (entry.action === \"conflict\" && needsOperator) report.unresolved += 1;\n }\n return [...byNamespace.values()].sort((a, b) => (a.namespace === b.namespace ? 0 : a.namespace < b.namespace ? -1 : 1));\n}\n\n/**\n * Plan a full reconciliation across namespaces.\n *\n * `converged` is an affirmative claim that nothing needs to move, so it is\n * derived from the entries rather than tracked alongside them: any action other\n * than `identical` disproves it.\n */\nexport function planReconciliation(\n namespaces: readonly ReconcileNamespaceInput[],\n options: ReconcileOptions = {},\n): ReconcilePlan {\n if (!Array.isArray(namespaces)) {\n throw new ReconcilePlanInputError(\"reconcile: planReconciliation expects an array of namespace inputs\");\n }\n // Validated here too: with an empty array the per-namespace path never runs,\n // and a malformed options envelope would return `converged` instead of\n // raising - the same call failing or succeeding based on list length.\n if (!isPlainObject(options)) {\n throw new ReconcilePlanInputError(\"reconcile: options must be a plain object\");\n }\n assertConflictPolicy(options.conflictPolicy);\n const entries: ReconcilePlanEntry[] = [];\n // Two inputs for one namespace are planned independently, so the same\n // (namespace, path) can draw contradictory actions - and because those\n // entries also sort equal, batch order would decide which revision survives.\n const seenNamespaces = new Set<string>();\n for (const namespace of namespaces) {\n const name = assertNamespace(namespace?.namespace);\n if (seenNamespaces.has(name)) {\n throw new ReconcilePlanInputError(\n `reconcile: namespace ${name} appears twice; merge its censuses before planning`,\n );\n }\n seenNamespaces.add(name);\n entries.push(...planNamespaceReconciliation(namespace, options));\n }\n entries.sort(compareEntries);\n return {\n entries,\n byNamespace: summar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AwB,IAAI;AAAA,MAC9B;AAAA,IACF;AACA,mBAAe,IAAI,IAAI;AACvB,YAAQ,KAAK,GAAG,4BAA4B,WAAW,OAAO,CAAC;AAAA,EACjE;AACA,UAAQ,KAAK,cAAc;AAC3B,SAAO;AAAA,IACL;AAAA,IACA,aAAa,uBAAuB,OAAO;AAAA,IAC3C,WAAW,QAAQ,MAAM,CAAC,UAAU,MAAM,WAAW,WAAW;AAAA,EAClE;AACF;","names":[]}
package/dist/index.d.ts CHANGED
@@ -4244,8 +4244,8 @@ declare const RelayMissionEventSchema: z.ZodObject<{
4244
4244
  }[] | undefined;
4245
4245
  }>;
4246
4246
  }, "strict", z.ZodTypeAny, {
4247
- schemaVersion: "1";
4248
4247
  recordedAt: string;
4248
+ schemaVersion: "1";
4249
4249
  payload: {
4250
4250
  kind: "mission_started";
4251
4251
  title: string;
@@ -4423,8 +4423,8 @@ declare const RelayMissionEventSchema: z.ZodObject<{
4423
4423
  authenticatedPrincipal?: string | undefined;
4424
4424
  idempotencyKey?: string | undefined;
4425
4425
  }, {
4426
- schemaVersion: "1";
4427
4426
  recordedAt: string;
4427
+ schemaVersion: "1";
4428
4428
  payload: {
4429
4429
  kind: "mission_started";
4430
4430
  title: string;
@@ -1,3 +1,11 @@
1
+ import { ReconcileSemanticAgreement, ReconcilePlanEntry } from './plan.js';
2
+ import '../offline-sync.js';
3
+ import '../types-rEwubvim.js';
4
+ import '../message-parts/index.js';
5
+ import '../bounded-jsonl-state.js';
6
+ import '../operator-doctor-types.js';
7
+ import '../types-continuity.js';
8
+
1
9
  interface ConvergeCursorFileState {
2
10
  path: string;
3
11
  sha256: string;
@@ -10,12 +18,14 @@ interface ConvergeCursorState {
10
18
  namespace: string;
11
19
  lastConvergedAt?: string;
12
20
  baseFiles: ConvergeCursorFileState[];
21
+ semanticAgreements?: ReconcileSemanticAgreement[];
13
22
  completedPaths?: string[];
14
23
  }
15
24
  declare function hashPeerNamespace(peerUrl: string, namespace: string): string;
16
25
  declare function defaultConvergeCursorPath(memoryDir: string, peerUrl: string, namespace: string): string;
26
+ declare function deriveConvergeCursorBase(entries: readonly ReconcilePlanEntry[], namespace: string, priorSemanticAgreements?: readonly ReconcileSemanticAgreement[]): Pick<ConvergeCursorState, "baseFiles" | "semanticAgreements">;
17
27
  declare function normalizeConvergeCursor(input: unknown): ConvergeCursorState;
18
28
  declare function readConvergeCursor(cursorPath: string): Promise<ConvergeCursorState | null>;
19
29
  declare function writeConvergeCursor(cursorPath: string, cursor: ConvergeCursorState): Promise<void>;
20
30
 
21
- export { type ConvergeCursorFileState, type ConvergeCursorState, defaultConvergeCursorPath, hashPeerNamespace, normalizeConvergeCursor, readConvergeCursor, writeConvergeCursor };
31
+ export { type ConvergeCursorFileState, type ConvergeCursorState, defaultConvergeCursorPath, deriveConvergeCursorBase, hashPeerNamespace, normalizeConvergeCursor, readConvergeCursor, writeConvergeCursor };
@@ -20,6 +20,48 @@ function defaultConvergeCursorPath(memoryDir, peerUrl, namespace) {
20
20
  const key = hashPeerNamespace(peerUrl, namespace);
21
21
  return path.join(path.resolve(memoryDir), ".remnic", "state", "converge-cursors", `${key}.json`);
22
22
  }
23
+ function normalizeSemanticFileState(input) {
24
+ if (!input || typeof input !== "object" || Array.isArray(input)) return void 0;
25
+ const file = input;
26
+ if (typeof file.path !== "string" || typeof file.sha256 !== "string") return void 0;
27
+ return { path: file.path, sha256: file.sha256 };
28
+ }
29
+ function digestAfterReconcile(entry) {
30
+ if (entry.action === "push") return entry.localSha256;
31
+ if (entry.action === "pull") return entry.peerSha256;
32
+ if (entry.action === "conflict") {
33
+ if (entry.resolution === "local-wins") return entry.localSha256;
34
+ if (entry.resolution === "peer-wins") return entry.peerSha256;
35
+ return void 0;
36
+ }
37
+ if (entry.action !== "identical") return void 0;
38
+ if (entry.localSha256 && entry.peerSha256 && entry.localSha256 !== entry.peerSha256) return void 0;
39
+ return entry.localSha256 ?? entry.peerSha256;
40
+ }
41
+ function semanticAgreementKey(agreement) {
42
+ return `${agreement.local.path}\0${agreement.peer.path}`;
43
+ }
44
+ function deriveConvergeCursorBase(entries, namespace, priorSemanticAgreements = []) {
45
+ const baseFiles = [];
46
+ const semanticAgreementsByPathPair = new Map(
47
+ priorSemanticAgreements.map((agreement) => [semanticAgreementKey(agreement), agreement])
48
+ );
49
+ for (const entry of entries) {
50
+ if (entry.namespace !== namespace) continue;
51
+ if (entry.semanticAgreement) {
52
+ semanticAgreementsByPathPair.set(semanticAgreementKey(entry.semanticAgreement), entry.semanticAgreement);
53
+ continue;
54
+ }
55
+ const sha256 = digestAfterReconcile(entry);
56
+ if (sha256) baseFiles.push({ path: entry.path, sha256 });
57
+ }
58
+ baseFiles.sort((left, right) => left.path.localeCompare(right.path));
59
+ const semanticAgreements = [...semanticAgreementsByPathPair.values()];
60
+ semanticAgreements.sort(
61
+ (left, right) => left.local.path.localeCompare(right.local.path) || left.peer.path.localeCompare(right.peer.path)
62
+ );
63
+ return { baseFiles, semanticAgreements };
64
+ }
23
65
  function normalizeConvergeCursor(input) {
24
66
  if (!input || typeof input !== "object" || Array.isArray(input)) {
25
67
  throw new Error("converge cursor must be an object");
@@ -50,6 +92,16 @@ function normalizeConvergeCursor(input) {
50
92
  }
51
93
  }
52
94
  }
95
+ const semanticAgreements = [];
96
+ if (Array.isArray(obj.semanticAgreements)) {
97
+ for (const item of obj.semanticAgreements) {
98
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
99
+ const agreement = item;
100
+ const local = normalizeSemanticFileState(agreement.local);
101
+ const peer = normalizeSemanticFileState(agreement.peer);
102
+ if (local && peer) semanticAgreements.push({ local, peer });
103
+ }
104
+ }
53
105
  const completedPaths = [];
54
106
  if (Array.isArray(obj.completedPaths)) {
55
107
  for (const item of obj.completedPaths) {
@@ -64,6 +116,7 @@ function normalizeConvergeCursor(input) {
64
116
  namespace: obj.namespace.trim(),
65
117
  lastConvergedAt: typeof obj.lastConvergedAt === "string" ? obj.lastConvergedAt : void 0,
66
118
  baseFiles,
119
+ semanticAgreements,
67
120
  completedPaths
68
121
  };
69
122
  }
@@ -96,6 +149,7 @@ async function writeConvergeCursor(cursorPath, cursor) {
96
149
  }
97
150
  export {
98
151
  defaultConvergeCursorPath,
152
+ deriveConvergeCursorBase,
99
153
  hashPeerNamespace,
100
154
  normalizeConvergeCursor,
101
155
  readConvergeCursor,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/reconcile/cursor.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nexport interface ConvergeCursorFileState {\n path: string;\n sha256: string;\n mtimeMs?: number;\n bytes?: number;\n}\n\nexport interface ConvergeCursorState {\n version: 1;\n peerUrl: string;\n namespace: string;\n lastConvergedAt?: string;\n baseFiles: ConvergeCursorFileState[];\n completedPaths?: string[];\n}\n\nexport function hashPeerNamespace(peerUrl: string, namespace: string): string {\n let normalizedUrl: string;\n try {\n const url = new URL(peerUrl);\n const credentials =\n url.username || url.password\n ? `${url.username}${url.password ? `:${url.password}` : \"\"}@`\n : \"\";\n normalizedUrl =\n `${url.protocol.toLowerCase()}//${credentials}${url.hostname.toLowerCase()}` +\n `${url.port ? `:${url.port}` : \"\"}${url.pathname.replace(/\\/+$/, \"\")}${url.search}${url.hash}`;\n } catch {\n normalizedUrl = peerUrl.trim().replace(/\\/+$/, \"\").toLowerCase();\n }\n const normalizedNs = namespace.trim().toLowerCase();\n return createHash(\"sha256\")\n .update(`${normalizedUrl}\\0${normalizedNs}`)\n .digest(\"hex\")\n .slice(0, 16);\n}\n\nexport function defaultConvergeCursorPath(\n memoryDir: string,\n peerUrl: string,\n namespace: string,\n): string {\n const key = hashPeerNamespace(peerUrl, namespace);\n return path.join(path.resolve(memoryDir), \".remnic\", \"state\", \"converge-cursors\", `${key}.json`);\n}\n\nexport function normalizeConvergeCursor(input: unknown): ConvergeCursorState {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(\"converge cursor must be an object\");\n }\n const obj = input as Record<string, unknown>;\n if (obj.version !== 1) {\n throw new Error(\"converge cursor version must be 1\");\n }\n if (typeof obj.peerUrl !== \"string\" || !obj.peerUrl.trim()) {\n throw new Error(\"converge cursor missing peerUrl\");\n }\n if (typeof obj.namespace !== \"string\" || !obj.namespace.trim()) {\n throw new Error(\"converge cursor missing namespace\");\n }\n const baseFiles: ConvergeCursorFileState[] = [];\n if (Array.isArray(obj.baseFiles)) {\n for (const item of obj.baseFiles) {\n if (item && typeof item === \"object\") {\n const fileItem = item as Record<string, unknown>;\n if (typeof fileItem.path === \"string\" && typeof fileItem.sha256 === \"string\") {\n baseFiles.push({\n path: fileItem.path,\n sha256: fileItem.sha256,\n mtimeMs: typeof fileItem.mtimeMs === \"number\" ? fileItem.mtimeMs : undefined,\n bytes: typeof fileItem.bytes === \"number\" ? fileItem.bytes : undefined,\n });\n }\n }\n }\n }\n const completedPaths: string[] = [];\n if (Array.isArray(obj.completedPaths)) {\n for (const item of obj.completedPaths) {\n if (typeof item === \"string\") {\n completedPaths.push(item);\n }\n }\n }\n return {\n version: 1,\n peerUrl: obj.peerUrl.trim(),\n namespace: obj.namespace.trim(),\n lastConvergedAt: typeof obj.lastConvergedAt === \"string\" ? obj.lastConvergedAt : undefined,\n baseFiles,\n completedPaths,\n };\n}\n\nexport async function readConvergeCursor(\n cursorPath: string,\n): Promise<ConvergeCursorState | null> {\n try {\n const raw = await fs.readFile(path.resolve(cursorPath), \"utf-8\");\n const parsed = JSON.parse(raw);\n return normalizeConvergeCursor(parsed);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n return null;\n }\n}\n\nexport async function writeConvergeCursor(\n cursorPath: string,\n cursor: ConvergeCursorState,\n): Promise<void> {\n const normalized = normalizeConvergeCursor(cursor);\n const target = path.resolve(cursorPath);\n await fs.mkdir(path.dirname(target), { recursive: true });\n const tmp = path.join(\n path.dirname(target),\n `.converge-cursor.${process.pid}.${randomUUID()}.tmp`,\n );\n await fs.writeFile(tmp, JSON.stringify(normalized, null, 2) + \"\\n\", \"utf-8\");\n try {\n await fs.rename(tmp, target);\n } catch (error) {\n await fs.unlink(tmp).catch(() => {});\n throw error;\n }\n}\n"],"mappings":";;;AAAA,SAAS,YAAY,kBAAkB;AACvC,YAAY,QAAQ;AACpB,YAAY,UAAU;AAkBf,SAAS,kBAAkB,SAAiB,WAA2B;AAC5E,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,OAAO;AAC3B,UAAM,cACJ,IAAI,YAAY,IAAI,WAChB,GAAG,IAAI,QAAQ,GAAG,IAAI,WAAW,IAAI,IAAI,QAAQ,KAAK,EAAE,MACxD;AACN,oBACE,GAAG,IAAI,SAAS,YAAY,CAAC,KAAK,WAAW,GAAG,IAAI,SAAS,YAAY,CAAC,GACvE,IAAI,OAAO,IAAI,IAAI,IAAI,KAAK,EAAE,GAAG,IAAI,SAAS,QAAQ,QAAQ,EAAE,CAAC,GAAG,IAAI,MAAM,GAAG,IAAI,IAAI;AAAA,EAChG,QAAQ;AACN,oBAAgB,QAAQ,KAAK,EAAE,QAAQ,QAAQ,EAAE,EAAE,YAAY;AAAA,EACjE;AACA,QAAM,eAAe,UAAU,KAAK,EAAE,YAAY;AAClD,SAAO,WAAW,QAAQ,EACvB,OAAO,GAAG,aAAa,KAAK,YAAY,EAAE,EAC1C,OAAO,KAAK,EACZ,MAAM,GAAG,EAAE;AAChB;AAEO,SAAS,0BACd,WACA,SACA,WACQ;AACR,QAAM,MAAM,kBAAkB,SAAS,SAAS;AAChD,SAAY,UAAU,aAAQ,SAAS,GAAG,WAAW,SAAS,oBAAoB,GAAG,GAAG,OAAO;AACjG;AAEO,SAAS,wBAAwB,OAAqC;AAC3E,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;AAC/D,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AACA,QAAM,MAAM;AACZ,MAAI,IAAI,YAAY,GAAG;AACrB,UAA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GAAG;AAC7B,WAAO,wBAAwB,MAAM;AAAA,EACvC,SAAS,OAAO;AACd,QAAK,MAAgC,SAAS,SAAU,QAAO;AAC/D,WAAO;AAAA,EACT;AACF;AAEA,eAAsB,oBACpB,YACA,QACe;AACf,QAAM,aAAa,wBAAwB,MAAM;AACjD,QAAM,SAAc,aAAQ,UAAU;AACtC,QAAS,SAAW,aAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AACxD,QAAM,MAAW;AAAA,IACV,aAAQ,MAAM;AAAA,IACnB,oBAAoB,QAAQ,GAAG,IAAI,WAAW,CAAC;AAAA,EACjD;AACA,QAAS,aAAU,KAAK,KAAK,UAAU,YAAY,MAAM,CAAC,IAAI,MAAM,OAAO;AAC3E,MAAI;AACF,UAAS,UAAO,KAAK,MAAM;AAAA,EAC7B,SAAS,OAAO;AACd,UAAS,UAAO,GAAG,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AACnC,UAAM;AAAA,EACR;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/reconcile/cursor.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport type { ReconcilePlanEntry, ReconcileSemanticAgreement } from \"./plan.js\";\n\nexport interface ConvergeCursorFileState {\n path: string;\n sha256: string;\n mtimeMs?: number;\n bytes?: number;\n}\n\nexport interface ConvergeCursorState {\n version: 1;\n peerUrl: string;\n namespace: string;\n lastConvergedAt?: string;\n baseFiles: ConvergeCursorFileState[];\n semanticAgreements?: ReconcileSemanticAgreement[];\n completedPaths?: string[];\n}\n\nexport function hashPeerNamespace(peerUrl: string, namespace: string): string {\n let normalizedUrl: string;\n try {\n const url = new URL(peerUrl);\n const credentials =\n url.username || url.password\n ? `${url.username}${url.password ? `:${url.password}` : \"\"}@`\n : \"\";\n normalizedUrl =\n `${url.protocol.toLowerCase()}//${credentials}${url.hostname.toLowerCase()}` +\n `${url.port ? `:${url.port}` : \"\"}${url.pathname.replace(/\\/+$/, \"\")}${url.search}${url.hash}`;\n } catch {\n normalizedUrl = peerUrl.trim().replace(/\\/+$/, \"\").toLowerCase();\n }\n const normalizedNs = namespace.trim().toLowerCase();\n return createHash(\"sha256\")\n .update(`${normalizedUrl}\\0${normalizedNs}`)\n .digest(\"hex\")\n .slice(0, 16);\n}\n\nexport function defaultConvergeCursorPath(\n memoryDir: string,\n peerUrl: string,\n namespace: string,\n): string {\n const key = hashPeerNamespace(peerUrl, namespace);\n return path.join(path.resolve(memoryDir), \".remnic\", \"state\", \"converge-cursors\", `${key}.json`);\n}\n\nfunction normalizeSemanticFileState(input: unknown): { path: string; sha256: string } | undefined {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) return undefined;\n const file = input as Record<string, unknown>;\n if (typeof file.path !== \"string\" || typeof file.sha256 !== \"string\") return undefined;\n return { path: file.path, sha256: file.sha256 };\n}\n\nfunction digestAfterReconcile(entry: ReconcilePlanEntry): string | undefined {\n if (entry.action === \"push\") return entry.localSha256;\n if (entry.action === \"pull\") return entry.peerSha256;\n if (entry.action === \"conflict\") {\n if (entry.resolution === \"local-wins\") return entry.localSha256;\n if (entry.resolution === \"peer-wins\") return entry.peerSha256;\n return undefined;\n }\n if (entry.action !== \"identical\") return undefined;\n if (entry.localSha256 && entry.peerSha256 && entry.localSha256 !== entry.peerSha256) return undefined;\n return entry.localSha256 ?? entry.peerSha256;\n}\n\nfunction semanticAgreementKey(agreement: ReconcileSemanticAgreement): string {\n return `${agreement.local.path}\\0${agreement.peer.path}`;\n}\n\nexport function deriveConvergeCursorBase(\n entries: readonly ReconcilePlanEntry[],\n namespace: string,\n priorSemanticAgreements: readonly ReconcileSemanticAgreement[] = [],\n): Pick<ConvergeCursorState, \"baseFiles\" | \"semanticAgreements\"> {\n const baseFiles: ConvergeCursorFileState[] = [];\n const semanticAgreementsByPathPair = new Map(\n priorSemanticAgreements.map((agreement) => [semanticAgreementKey(agreement), agreement])\n );\n for (const entry of entries) {\n if (entry.namespace !== namespace) continue;\n if (entry.semanticAgreement) {\n semanticAgreementsByPathPair.set(semanticAgreementKey(entry.semanticAgreement), entry.semanticAgreement);\n continue;\n }\n const sha256 = digestAfterReconcile(entry);\n if (sha256) baseFiles.push({ path: entry.path, sha256 });\n }\n baseFiles.sort((left, right) => left.path.localeCompare(right.path));\n const semanticAgreements = [...semanticAgreementsByPathPair.values()];\n semanticAgreements.sort((left, right) =>\n left.local.path.localeCompare(right.local.path) || left.peer.path.localeCompare(right.peer.path)\n );\n return { baseFiles, semanticAgreements };\n}\n\nexport function normalizeConvergeCursor(input: unknown): ConvergeCursorState {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(\"converge cursor must be an object\");\n }\n const obj = input as Record<string, unknown>;\n if (obj.version !== 1) {\n throw new Error(\"converge cursor version must be 1\");\n }\n if (typeof obj.peerUrl !== \"string\" || !obj.peerUrl.trim()) {\n throw new Error(\"converge cursor missing peerUrl\");\n }\n if (typeof obj.namespace !== \"string\" || !obj.namespace.trim()) {\n throw new Error(\"converge cursor missing namespace\");\n }\n const baseFiles: ConvergeCursorFileState[] = [];\n if (Array.isArray(obj.baseFiles)) {\n for (const item of obj.baseFiles) {\n if (item && typeof item === \"object\") {\n const fileItem = item as Record<string, unknown>;\n if (typeof fileItem.path === \"string\" && typeof fileItem.sha256 === \"string\") {\n baseFiles.push({\n path: fileItem.path,\n sha256: fileItem.sha256,\n mtimeMs: typeof fileItem.mtimeMs === \"number\" ? fileItem.mtimeMs : undefined,\n bytes: typeof fileItem.bytes === \"number\" ? fileItem.bytes : undefined,\n });\n }\n }\n }\n }\n const semanticAgreements: ReconcileSemanticAgreement[] = [];\n if (Array.isArray(obj.semanticAgreements)) {\n for (const item of obj.semanticAgreements) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n const agreement = item as Record<string, unknown>;\n const local = normalizeSemanticFileState(agreement.local);\n const peer = normalizeSemanticFileState(agreement.peer);\n if (local && peer) semanticAgreements.push({ local, peer });\n }\n }\n const completedPaths: string[] = [];\n if (Array.isArray(obj.completedPaths)) {\n for (const item of obj.completedPaths) {\n if (typeof item === \"string\") {\n completedPaths.push(item);\n }\n }\n }\n return {\n version: 1,\n peerUrl: obj.peerUrl.trim(),\n namespace: obj.namespace.trim(),\n lastConvergedAt: typeof obj.lastConvergedAt === \"string\" ? obj.lastConvergedAt : undefined,\n baseFiles,\n semanticAgreements,\n completedPaths,\n };\n}\n\nexport async function readConvergeCursor(\n cursorPath: string,\n): Promise<ConvergeCursorState | null> {\n try {\n const raw = await fs.readFile(path.resolve(cursorPath), \"utf-8\");\n const parsed = JSON.parse(raw);\n return normalizeConvergeCursor(parsed);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n return null;\n }\n}\n\nexport async function writeConvergeCursor(\n cursorPath: string,\n cursor: ConvergeCursorState,\n): Promise<void> {\n const normalized = normalizeConvergeCursor(cursor);\n const target = path.resolve(cursorPath);\n await fs.mkdir(path.dirname(target), { recursive: true });\n const tmp = path.join(\n path.dirname(target),\n `.converge-cursor.${process.pid}.${randomUUID()}.tmp`,\n );\n await fs.writeFile(tmp, JSON.stringify(normalized, null, 2) + \"\\n\", \"utf-8\");\n try {\n await fs.rename(tmp, target);\n } catch (error) {\n await fs.unlink(tmp).catch(() => {});\n throw error;\n }\n}\n"],"mappings":";;;AAAA,SAAS,YAAY,kBAAkB;AACvC,YAAY,QAAQ;AACpB,YAAY,UAAU;AAoBf,SAAS,kBAAkB,SAAiB,WAA2B;AAC5E,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,OAAO;AAC3B,UAAM,cACJ,IAAI,YAAY,IAAI,WAChB,GAAG,IAAI,QAAQ,GAAG,IAAI,WAAW,IAAI,IAAI,QAAQ,KAAK,EAAE,MACxD;AACN,oBACE,GAAG,IAAI,SAAS,YAAY,CAAC,KAAK,WAAW,GAAG,IAAI,SAAS,YAAY,CAAC,GACvE,IAAI,OAAO,IAAI,IAAI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EA,eAAsB,mBACpB,YACqC;AACrC,MAAI;AACF,UAAM,MAAM,MAAS,YAAc,aAAQ,UAAU,GAAG,OAAO;AAC/D,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,WAAO,wBAAwB,MAAM;AAAA,EACvC,SAAS,OAAO;AACd,QAAK,MAAgC,SAAS,SAAU,QAAO;AAC/D,WAAO;AAAA,EACT;AACF;AAEA,eAAsB,oBACpB,YACA,QACe;AACf,QAAM,aAAa,wBAAwB,MAAM;AACjD,QAAM,SAAc,aAAQ,UAAU;AACtC,QAAS,SAAW,aAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AACxD,QAAM,MAAW;AAAA,IACV,aAAQ,MAAM;AAAA,IACnB,oBAAoB,QAAQ,GAAG,IAAI,WAAW,CAAC;AAAA,EACjD;AACA,QAAS,aAAU,KAAK,KAAK,UAAU,YAAY,MAAM,CAAC,IAAI,MAAM,OAAO;AAC3E,MAAI;AACF,UAAS,UAAO,KAAK,MAAM;AAAA,EAC7B,SAAS,OAAO;AACd,UAAS,UAAO,GAAG,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AACnC,UAAM;AAAA,EACR;AACF;","names":[]}
@@ -1,5 +1,5 @@
1
1
  import { x as MemoryStatus } from '../types-rEwubvim.js';
2
- import { ReconcileFileState, ReconcilePlan } from './plan.js';
2
+ import { ReconcileFileState, ReconcilePlan, ReconcileSemanticAgreement } from './plan.js';
3
3
  import '../message-parts/index.js';
4
4
  import '../bounded-jsonl-state.js';
5
5
  import '../operator-doctor-types.js';
@@ -28,6 +28,6 @@ interface BuildReconcileManifestOptions {
28
28
  cachedFiles?: Iterable<ReconcileManifestFile>;
29
29
  }
30
30
  declare function buildReconcileManifest(options: BuildReconcileManifestOptions): Promise<ReconcileManifest>;
31
- declare function collapseActiveFactDuplicates(plan: ReconcilePlan, localManifests: ReadonlyMap<string, ReconcileManifest>, peerManifests: ReadonlyMap<string, ReconcileManifest>): ReconcilePlan;
31
+ declare function collapseActiveFactDuplicates(plan: ReconcilePlan, localManifests: ReadonlyMap<string, ReconcileManifest>, peerManifests: ReadonlyMap<string, ReconcileManifest>, priorSemanticAgreements?: ReadonlyMap<string, readonly ReconcileSemanticAgreement[]>): ReconcilePlan;
32
32
 
33
33
  export { type BuildReconcileManifestOptions, RECONCILE_MANIFEST_FORMAT, RECONCILE_MANIFEST_SCHEMA_VERSION, type ReconcileManifest, type ReconcileManifestFile, type ReconcileMemoryIdentity, buildReconcileManifest, collapseActiveFactDuplicates };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  summarizeReconcilePlan
3
- } from "../chunk-K442KOID.js";
3
+ } from "../chunk-HZFHQ4AQ.js";
4
4
  import "../chunk-HBVPYRDW.js";
5
5
  import "../chunk-EGGE52UU.js";
6
6
  import {
@@ -131,7 +131,19 @@ function comparePlanEntries(left, right) {
131
131
  if (left.namespace !== right.namespace) return left.namespace < right.namespace ? -1 : 1;
132
132
  return left.path < right.path ? -1 : left.path > right.path ? 1 : 0;
133
133
  }
134
- function collapseActiveFactDuplicates(plan, localManifests, peerManifests) {
134
+ function semanticAgreementKey(agreement) {
135
+ return `${agreement.local.path}\0${agreement.peer.path}`;
136
+ }
137
+ function classifySemanticChange(current, prior) {
138
+ if (!prior) return "unchanged";
139
+ const localChanged = current.local.sha256 !== prior.local.sha256;
140
+ const peerChanged = current.peer.sha256 !== prior.peer.sha256;
141
+ if (localChanged && peerChanged) return "both_modified";
142
+ if (localChanged) return "local_changed";
143
+ if (peerChanged) return "peer_changed";
144
+ return "unchanged";
145
+ }
146
+ function collapseActiveFactDuplicates(plan, localManifests, peerManifests, priorSemanticAgreements) {
135
147
  const entriesByNamespace = /* @__PURE__ */ new Map();
136
148
  for (const entry of plan.entries) {
137
149
  const entries2 = entriesByNamespace.get(entry.namespace) ?? [];
@@ -147,6 +159,12 @@ function collapseActiveFactDuplicates(plan, localManifests, peerManifests) {
147
159
  const peerByPath = activeFactByPath(peerManifest);
148
160
  const localFilesByPath = new Map((localManifest?.files ?? []).map((file) => [file.path, file]));
149
161
  const peerFilesByPath = new Map((peerManifest?.files ?? []).map((file) => [file.path, file]));
162
+ const priorSemanticByPathPair = new Map(
163
+ (priorSemanticAgreements?.get(namespace) ?? []).map((agreement) => [
164
+ semanticAgreementKey(agreement),
165
+ agreement
166
+ ])
167
+ );
150
168
  const localByHash = /* @__PURE__ */ new Map();
151
169
  const peerByHash = /* @__PURE__ */ new Map();
152
170
  for (const file of localByPath.values()) {
@@ -184,6 +202,18 @@ function collapseActiveFactDuplicates(plan, localManifests, peerManifests) {
184
202
  ...localCandidates.map((file) => file.path),
185
203
  ...peerCandidates.map((file) => file.path)
186
204
  ]);
205
+ const authoritativeSamePathEntries = new Set(entries2.filter(
206
+ (entry) => duplicatePaths.has(entry.path) && localFilesByPath.has(entry.path) && peerFilesByPath.has(entry.path) && entry.action !== "identical"
207
+ ));
208
+ if (authoritativeSamePathEntries.size > 0) {
209
+ for (const entry of entries2) {
210
+ if (duplicatePaths.has(entry.path) && !authoritativeSamePathEntries.has(entry) && (entry.action === "pull" || entry.action === "push" || entry.action === "identical")) {
211
+ removed.add(entry);
212
+ changed = true;
213
+ }
214
+ }
215
+ continue;
216
+ }
187
217
  const unsafeEntry = entries2.some(
188
218
  (entry) => duplicatePaths.has(entry.path) && (entry.action === "suppress" || entry.action === "conflict")
189
219
  );
@@ -193,13 +223,20 @@ function collapseActiveFactDuplicates(plan, localManifests, peerManifests) {
193
223
  removed.add(entry);
194
224
  }
195
225
  }
226
+ const semanticAgreement = {
227
+ local: { path: localPath, sha256: localFile.sha256 },
228
+ peer: { path: peerPath, sha256: peerFile.sha256 }
229
+ };
196
230
  replacements.push({
197
231
  path: localPath < peerPath ? localPath : peerPath,
198
232
  namespace,
199
233
  action: "identical",
200
234
  reason: "semantic_duplicate",
201
- localSha256: localFile.sha256,
202
- peerSha256: peerFile.sha256
235
+ semanticAgreement,
236
+ semanticChange: classifySemanticChange(
237
+ semanticAgreement,
238
+ priorSemanticByPathPair.get(semanticAgreementKey(semanticAgreement))
239
+ )
203
240
  });
204
241
  changed = true;
205
242
  continue;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/reconcile/manifest.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { inferMemoryStatus } from \"../memory-lifecycle-ledger-utils.js\";\nimport { ContentHashIndex, type ContentHashPathEntry } from \"../storage/content-hash-index.js\";\nimport type { MemoryFrontmatter, MemoryStatus } from \"../types.js\";\nimport { RECALL_FALLBACK_DIRS } from \"../utils/category-dir.js\";\nimport {\n type ReconcileFileState,\n type ReconcilePlan,\n type ReconcilePlanEntry,\n summarizeReconcilePlan,\n} from \"./plan.js\";\n\nexport const RECONCILE_MANIFEST_FORMAT = \"remnic-reconcile-manifest\";\nexport const RECONCILE_MANIFEST_SCHEMA_VERSION = 1;\n\nexport interface ReconcileMemoryIdentity {\n id: string;\n category: string;\n contentHash: string;\n status: MemoryStatus;\n}\n\nexport interface ReconcileManifestFile extends ReconcileFileState {\n memory?: ReconcileMemoryIdentity;\n}\n\ntype ActiveFactManifestFile = ReconcileManifestFile & { memory: ReconcileMemoryIdentity };\n\nexport interface ReconcileManifest {\n format: typeof RECONCILE_MANIFEST_FORMAT;\n schemaVersion: typeof RECONCILE_MANIFEST_SCHEMA_VERSION;\n files: ReconcileManifestFile[];\n}\n\nexport interface BuildReconcileManifestOptions {\n files: Iterable<ReconcileFileState>;\n readFile: (file: ReconcileFileState) => Promise<Buffer | string | null>;\n cachedFiles?: Iterable<ReconcileManifestFile>;\n}\n\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/i;\nconst MEMORY_DIRS = new Set(RECALL_FALLBACK_DIRS);\n\nfunction isMemoryPath(filePath: string): boolean {\n if (!filePath.endsWith(\".md\")) return false;\n const segments = filePath.split(\"/\");\n let index = 0;\n if (segments[index] === \"cold\" || segments[index] === \"archive\") index += 1;\n return MEMORY_DIRS.has(segments[index] ?? \"\");\n}\n\nfunction parseScalar(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n if (trimmed.startsWith('\"') && trimmed.endsWith('\"')) {\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n return typeof parsed === \"string\" ? parsed : trimmed;\n } catch {\n return trimmed.slice(1, -1).replace(/\\\\\"/g, '\"');\n }\n }\n if (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\")) {\n return trimmed.slice(1, -1).replace(/''/g, \"'\");\n }\n return trimmed;\n}\n\nfunction parsedMemoryIdentity(filePath: string, raw: Buffer | string): ReconcileMemoryIdentity | undefined {\n if (!isMemoryPath(filePath)) return undefined;\n const match = (Buffer.isBuffer(raw) ? raw.toString(\"utf8\") : raw).match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!match) return undefined;\n const fields = new Map<string, string>();\n for (const line of match[1].split(\"\\n\")) {\n const separator = line.indexOf(\":\");\n if (separator > 0) fields.set(line.slice(0, separator).trim(), line.slice(separator + 1).trim());\n }\n const id = parseScalar(fields.get(\"id\"));\n if (!id) return undefined;\n const category = parseScalar(fields.get(\"category\")) ?? \"fact\";\n const storedHash = parseScalar(fields.get(\"contentHash\"));\n const contentHash =\n storedHash && SHA256_PATTERN.test(storedHash)\n ? storedHash.toLowerCase()\n : ContentHashIndex.computeHash(match[2].trim());\n const status = inferMemoryStatus(\n {\n status: parseScalar(fields.get(\"status\")) as MemoryStatus | undefined,\n archivedAt: parseScalar(fields.get(\"archivedAt\")),\n } as MemoryFrontmatter,\n filePath\n );\n return { id, category, contentHash, status };\n}\n\nexport async function buildReconcileManifest(options: BuildReconcileManifestOptions): Promise<ReconcileManifest> {\n const cachedByPath = new Map<string, ReconcileManifestFile>();\n for (const cached of options.cachedFiles ?? []) {\n cachedByPath.set(cached.path, cached);\n }\n\n const files: ReconcileManifestFile[] = [];\n for (const file of options.files) {\n const cached = cachedByPath.get(file.path);\n if (cached?.sha256.toLowerCase() === file.sha256.toLowerCase()) {\n files.push({ ...file, ...(cached.memory ? { memory: cached.memory } : {}) });\n continue;\n }\n\n let raw: Buffer | string | null = null;\n if (isMemoryPath(file.path)) {\n try {\n raw = await options.readFile(file);\n } catch {\n raw = null;\n }\n }\n if (raw !== null && createHash(\"sha256\").update(raw).digest(\"hex\") !== file.sha256.toLowerCase()) {\n raw = null;\n }\n const memory = raw === null ? undefined : parsedMemoryIdentity(file.path, raw);\n files.push({ ...file, ...(memory ? { memory } : {}) });\n }\n files.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));\n return {\n format: RECONCILE_MANIFEST_FORMAT,\n schemaVersion: RECONCILE_MANIFEST_SCHEMA_VERSION,\n files,\n };\n}\n\nfunction activeFactByPath(manifest: ReconcileManifest | undefined): Map<string, ActiveFactManifestFile> {\n const result = new Map<string, ActiveFactManifestFile>();\n for (const file of manifest?.files ?? []) {\n if (file.memory?.category === \"fact\" && file.memory.status === \"active\") {\n result.set(file.path, file as ActiveFactManifestFile);\n }\n }\n return result;\n}\n\nfunction contentHashRows(files: Iterable<ActiveFactManifestFile>): ContentHashPathEntry[] {\n const rows: ContentHashPathEntry[] = [];\n for (const file of files) {\n rows.push({ path: file.path, contentHash: file.memory.contentHash });\n }\n return rows;\n}\n\nfunction comparePlanEntries(left: ReconcilePlanEntry, right: ReconcilePlanEntry): number {\n if (left.namespace !== right.namespace) return left.namespace < right.namespace ? -1 : 1;\n return left.path < right.path ? -1 : left.path > right.path ? 1 : 0;\n}\n\nexport function collapseActiveFactDuplicates(\n plan: ReconcilePlan,\n localManifests: ReadonlyMap<string, ReconcileManifest>,\n peerManifests: ReadonlyMap<string, ReconcileManifest>\n): ReconcilePlan {\n const entriesByNamespace = new Map<string, ReconcilePlanEntry[]>();\n for (const entry of plan.entries) {\n const entries = entriesByNamespace.get(entry.namespace) ?? [];\n entries.push({ ...entry });\n entriesByNamespace.set(entry.namespace, entries);\n }\n\n let changed = false;\n for (const namespace of new Set([...localManifests.keys(), ...peerManifests.keys()])) {\n const entries = entriesByNamespace.get(namespace) ?? [];\n const localManifest = localManifests.get(namespace);\n const peerManifest = peerManifests.get(namespace);\n const localByPath = activeFactByPath(localManifest);\n const peerByPath = activeFactByPath(peerManifest);\n const localFilesByPath = new Map((localManifest?.files ?? []).map((file) => [file.path, file]));\n const peerFilesByPath = new Map((peerManifest?.files ?? []).map((file) => [file.path, file]));\n const localByHash = new Map<string, ActiveFactManifestFile[]>();\n const peerByHash = new Map<string, ActiveFactManifestFile[]>();\n\n for (const file of localByPath.values()) {\n const hash = file.memory.contentHash;\n const bucket = localByHash.get(hash) ?? [];\n bucket.push(file);\n localByHash.set(hash, bucket);\n }\n for (const file of peerByPath.values()) {\n const hash = file.memory.contentHash;\n const bucket = peerByHash.get(hash) ?? [];\n bucket.push(file);\n peerByHash.set(hash, bucket);\n }\n\n const removed = new Set<ReconcilePlanEntry>();\n const replacements: ReconcilePlanEntry[] = [];\n for (const hash of new Set([...localByHash.keys(), ...peerByHash.keys()])) {\n const localCandidates = (localByHash.get(hash) ?? []).filter((file) => {\n const opposite = peerFilesByPath.get(file.path);\n const activeOpposite = peerByPath.get(file.path);\n return opposite === undefined || activeOpposite?.memory.contentHash === hash;\n });\n const peerCandidates = (peerByHash.get(hash) ?? []).filter((file) => {\n const opposite = localFilesByPath.get(file.path);\n const activeOpposite = localByPath.get(file.path);\n return opposite === undefined || activeOpposite?.memory.contentHash === hash;\n });\n const localPath = ContentHashIndex.resolvePathByHash(hash, contentHashRows(localCandidates));\n const peerPath = ContentHashIndex.resolvePathByHash(hash, contentHashRows(peerCandidates));\n\n if (localPath && peerPath && localPath !== peerPath) {\n const localFile = localByPath.get(localPath);\n const peerFile = peerByPath.get(peerPath);\n if (!localFile || !peerFile) continue;\n const duplicatePaths = new Set([\n ...localCandidates.map((file) => file.path),\n ...peerCandidates.map((file) => file.path),\n ]);\n const unsafeEntry = entries.some(\n (entry) => duplicatePaths.has(entry.path) && (entry.action === \"suppress\" || entry.action === \"conflict\")\n );\n if (unsafeEntry) continue;\n for (const entry of entries) {\n if (\n duplicatePaths.has(entry.path) &&\n (entry.action === \"pull\" || entry.action === \"push\" || entry.action === \"identical\")\n ) {\n removed.add(entry);\n }\n }\n replacements.push({\n path: localPath < peerPath ? localPath : peerPath,\n namespace,\n action: \"identical\",\n reason: \"semantic_duplicate\",\n localSha256: localFile.sha256,\n peerSha256: peerFile.sha256,\n });\n changed = true;\n continue;\n }\n\n const sameSideEntries = entries.filter((entry) => {\n if (localPath && entry.reason === \"local_only\") {\n return localCandidates.some((file) => file.path === entry.path);\n }\n if (peerPath && entry.reason === \"peer_only\") {\n return peerCandidates.some((file) => file.path === entry.path);\n }\n return false;\n });\n const canonicalPath = localPath ?? peerPath;\n const hasSharedCanonical = localPath !== undefined && localPath === peerPath;\n if (!canonicalPath || sameSideEntries.length === 0 || (!hasSharedCanonical && sameSideEntries.length < 2)) {\n continue;\n }\n for (const entry of sameSideEntries) {\n if (entry.path !== canonicalPath) {\n removed.add(entry);\n changed = true;\n }\n }\n }\n\n if (removed.size > 0 || replacements.length > 0) {\n entriesByNamespace.set(\n namespace,\n [...entries.filter((entry) => !removed.has(entry)), ...replacements].sort(comparePlanEntries)\n );\n }\n }\n\n if (!changed) return plan;\n const entries = [...entriesByNamespace.values()].flat().sort(comparePlanEntries);\n return {\n entries,\n byNamespace: summarizeReconcilePlan(entries),\n converged: entries.every((entry) => entry.action === \"identical\"),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAYpB,IAAM,4BAA4B;AAClC,IAAM,oCAAoC;AA2BjD,IAAM,iBAAiB;AACvB,IAAM,cAAc,IAAI,IAAI,oBAAoB;AAEhD,SAAS,aAAa,UAA2B;AAC/C,MAAI,CAAC,SAAS,SAAS,KAAK,EAAG,QAAO;AACtC,QAAM,WAAW,SAAS,MAAM,GAAG;AACnC,MAAI,QAAQ;AACZ,MAAI,SAAS,KAAK,MAAM,UAAU,SAAS,KAAK,MAAM,UAAW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AAI,YAAY,MAAM,WAAW,aAAa;AAC5C,iBAAO,eAAe,KAAK,CAAC,SAAS,KAAK,SAAS,MAAM,IAAI;AAAA,QAC/D;AACA,eAAO;AAAA,MACT,CAAC;AACD,YAAM,gBAAgB,aAAa;AACnC,YAAM,qBAAqB,cAAc,UAAa,cAAc;AACpE,UAAI,CAAC,iBAAiB,gBAAgB,WAAW,KAAM,CAAC,sBAAsB,gBAAgB,SAAS,GAAI;AACzG;AAAA,MACF;AACA,iBAAW,SAAS,iBAAiB;AACnC,YAAI,MAAM,SAAS,eAAe;AAChC,kBAAQ,IAAI,KAAK;AACjB,oBAAU;AAAA,QACZ;AAAA,MACF;AAAA,IACF;AAEA,QAAI,QAAQ,OAAO,KAAK,aAAa,SAAS,GAAG;AAC/C,yBAAmB;AAAA,QACjB;AAAA,QACA,CAAC,GAAGA,SAAQ,OAAO,CAAC,UAAU,CAAC,QAAQ,IAAI,KAAK,CAAC,GAAG,GAAG,YAAY,EAAE,KAAK,kBAAkB;AAAA,MAC9F;AAAA,IACF;AAAA,EACF;AAEA,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,UAAU,CAAC,GAAG,mBAAmB,OAAO,CAAC,EAAE,KAAK,EAAE,KAAK,kBAAkB;AAC/E,SAAO;AAAA,IACL;AAAA,IACA,aAAa,uBAAuB,OAAO;AAAA,IAC3C,WAAW,QAAQ,MAAM,CAAC,UAAU,MAAM,WAAW,WAAW;AAAA,EAClE;AACF;","names":["entries"]}
1
+ {"version":3,"sources":["../../src/reconcile/manifest.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { inferMemoryStatus } from \"../memory-lifecycle-ledger-utils.js\";\nimport { ContentHashIndex, type ContentHashPathEntry } from \"../storage/content-hash-index.js\";\nimport type { MemoryFrontmatter, MemoryStatus } from \"../types.js\";\nimport { RECALL_FALLBACK_DIRS } from \"../utils/category-dir.js\";\nimport {\n type ReconcileFileState,\n type ReconcilePlan,\n type ReconcilePlanEntry,\n type ReconcileSemanticAgreement,\n type ReconcileSemanticChange,\n summarizeReconcilePlan,\n} from \"./plan.js\";\n\nexport const RECONCILE_MANIFEST_FORMAT = \"remnic-reconcile-manifest\";\nexport const RECONCILE_MANIFEST_SCHEMA_VERSION = 1;\n\nexport interface ReconcileMemoryIdentity {\n id: string;\n category: string;\n contentHash: string;\n status: MemoryStatus;\n}\n\nexport interface ReconcileManifestFile extends ReconcileFileState {\n memory?: ReconcileMemoryIdentity;\n}\n\ntype ActiveFactManifestFile = ReconcileManifestFile & { memory: ReconcileMemoryIdentity };\n\nexport interface ReconcileManifest {\n format: typeof RECONCILE_MANIFEST_FORMAT;\n schemaVersion: typeof RECONCILE_MANIFEST_SCHEMA_VERSION;\n files: ReconcileManifestFile[];\n}\n\nexport interface BuildReconcileManifestOptions {\n files: Iterable<ReconcileFileState>;\n readFile: (file: ReconcileFileState) => Promise<Buffer | string | null>;\n cachedFiles?: Iterable<ReconcileManifestFile>;\n}\n\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/i;\nconst MEMORY_DIRS = new Set(RECALL_FALLBACK_DIRS);\n\nfunction isMemoryPath(filePath: string): boolean {\n if (!filePath.endsWith(\".md\")) return false;\n const segments = filePath.split(\"/\");\n let index = 0;\n if (segments[index] === \"cold\" || segments[index] === \"archive\") index += 1;\n return MEMORY_DIRS.has(segments[index] ?? \"\");\n}\n\nfunction parseScalar(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n if (trimmed.startsWith('\"') && trimmed.endsWith('\"')) {\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n return typeof parsed === \"string\" ? parsed : trimmed;\n } catch {\n return trimmed.slice(1, -1).replace(/\\\\\"/g, '\"');\n }\n }\n if (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\")) {\n return trimmed.slice(1, -1).replace(/''/g, \"'\");\n }\n return trimmed;\n}\n\nfunction parsedMemoryIdentity(filePath: string, raw: Buffer | string): ReconcileMemoryIdentity | undefined {\n if (!isMemoryPath(filePath)) return undefined;\n const match = (Buffer.isBuffer(raw) ? raw.toString(\"utf8\") : raw).match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!match) return undefined;\n const fields = new Map<string, string>();\n for (const line of match[1].split(\"\\n\")) {\n const separator = line.indexOf(\":\");\n if (separator > 0) fields.set(line.slice(0, separator).trim(), line.slice(separator + 1).trim());\n }\n const id = parseScalar(fields.get(\"id\"));\n if (!id) return undefined;\n const category = parseScalar(fields.get(\"category\")) ?? \"fact\";\n const storedHash = parseScalar(fields.get(\"contentHash\"));\n const contentHash =\n storedHash && SHA256_PATTERN.test(storedHash)\n ? storedHash.toLowerCase()\n : ContentHashIndex.computeHash(match[2].trim());\n const status = inferMemoryStatus(\n {\n status: parseScalar(fields.get(\"status\")) as MemoryStatus | undefined,\n archivedAt: parseScalar(fields.get(\"archivedAt\")),\n } as MemoryFrontmatter,\n filePath\n );\n return { id, category, contentHash, status };\n}\n\nexport async function buildReconcileManifest(options: BuildReconcileManifestOptions): Promise<ReconcileManifest> {\n const cachedByPath = new Map<string, ReconcileManifestFile>();\n for (const cached of options.cachedFiles ?? []) {\n cachedByPath.set(cached.path, cached);\n }\n\n const files: ReconcileManifestFile[] = [];\n for (const file of options.files) {\n const cached = cachedByPath.get(file.path);\n if (cached?.sha256.toLowerCase() === file.sha256.toLowerCase()) {\n files.push({ ...file, ...(cached.memory ? { memory: cached.memory } : {}) });\n continue;\n }\n\n let raw: Buffer | string | null = null;\n if (isMemoryPath(file.path)) {\n try {\n raw = await options.readFile(file);\n } catch {\n raw = null;\n }\n }\n if (raw !== null && createHash(\"sha256\").update(raw).digest(\"hex\") !== file.sha256.toLowerCase()) {\n raw = null;\n }\n const memory = raw === null ? undefined : parsedMemoryIdentity(file.path, raw);\n files.push({ ...file, ...(memory ? { memory } : {}) });\n }\n files.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));\n return {\n format: RECONCILE_MANIFEST_FORMAT,\n schemaVersion: RECONCILE_MANIFEST_SCHEMA_VERSION,\n files,\n };\n}\n\nfunction activeFactByPath(manifest: ReconcileManifest | undefined): Map<string, ActiveFactManifestFile> {\n const result = new Map<string, ActiveFactManifestFile>();\n for (const file of manifest?.files ?? []) {\n if (file.memory?.category === \"fact\" && file.memory.status === \"active\") {\n result.set(file.path, file as ActiveFactManifestFile);\n }\n }\n return result;\n}\n\nfunction contentHashRows(files: Iterable<ActiveFactManifestFile>): ContentHashPathEntry[] {\n const rows: ContentHashPathEntry[] = [];\n for (const file of files) {\n rows.push({ path: file.path, contentHash: file.memory.contentHash });\n }\n return rows;\n}\n\nfunction comparePlanEntries(left: ReconcilePlanEntry, right: ReconcilePlanEntry): number {\n if (left.namespace !== right.namespace) return left.namespace < right.namespace ? -1 : 1;\n return left.path < right.path ? -1 : left.path > right.path ? 1 : 0;\n}\n\nfunction semanticAgreementKey(agreement: ReconcileSemanticAgreement): string {\n return `${agreement.local.path}\\0${agreement.peer.path}`;\n}\n\nfunction classifySemanticChange(\n current: ReconcileSemanticAgreement,\n prior: ReconcileSemanticAgreement | undefined\n): ReconcileSemanticChange {\n if (!prior) return \"unchanged\";\n const localChanged = current.local.sha256 !== prior.local.sha256;\n const peerChanged = current.peer.sha256 !== prior.peer.sha256;\n if (localChanged && peerChanged) return \"both_modified\";\n if (localChanged) return \"local_changed\";\n if (peerChanged) return \"peer_changed\";\n return \"unchanged\";\n}\n\nexport function collapseActiveFactDuplicates(\n plan: ReconcilePlan,\n localManifests: ReadonlyMap<string, ReconcileManifest>,\n peerManifests: ReadonlyMap<string, ReconcileManifest>,\n priorSemanticAgreements?: ReadonlyMap<string, readonly ReconcileSemanticAgreement[]>,\n): ReconcilePlan {\n const entriesByNamespace = new Map<string, ReconcilePlanEntry[]>();\n for (const entry of plan.entries) {\n const entries = entriesByNamespace.get(entry.namespace) ?? [];\n entries.push({ ...entry });\n entriesByNamespace.set(entry.namespace, entries);\n }\n\n let changed = false;\n for (const namespace of new Set([...localManifests.keys(), ...peerManifests.keys()])) {\n const entries = entriesByNamespace.get(namespace) ?? [];\n const localManifest = localManifests.get(namespace);\n const peerManifest = peerManifests.get(namespace);\n const localByPath = activeFactByPath(localManifest);\n const peerByPath = activeFactByPath(peerManifest);\n const localFilesByPath = new Map((localManifest?.files ?? []).map((file) => [file.path, file]));\n const peerFilesByPath = new Map((peerManifest?.files ?? []).map((file) => [file.path, file]));\n const priorSemanticByPathPair = new Map(\n (priorSemanticAgreements?.get(namespace) ?? []).map((agreement) => [\n semanticAgreementKey(agreement),\n agreement,\n ])\n );\n const localByHash = new Map<string, ActiveFactManifestFile[]>();\n const peerByHash = new Map<string, ActiveFactManifestFile[]>();\n\n for (const file of localByPath.values()) {\n const hash = file.memory.contentHash;\n const bucket = localByHash.get(hash) ?? [];\n bucket.push(file);\n localByHash.set(hash, bucket);\n }\n for (const file of peerByPath.values()) {\n const hash = file.memory.contentHash;\n const bucket = peerByHash.get(hash) ?? [];\n bucket.push(file);\n peerByHash.set(hash, bucket);\n }\n\n const removed = new Set<ReconcilePlanEntry>();\n const replacements: ReconcilePlanEntry[] = [];\n for (const hash of new Set([...localByHash.keys(), ...peerByHash.keys()])) {\n const localCandidates = (localByHash.get(hash) ?? []).filter((file) => {\n const opposite = peerFilesByPath.get(file.path);\n const activeOpposite = peerByPath.get(file.path);\n return opposite === undefined || activeOpposite?.memory.contentHash === hash;\n });\n const peerCandidates = (peerByHash.get(hash) ?? []).filter((file) => {\n const opposite = localFilesByPath.get(file.path);\n const activeOpposite = localByPath.get(file.path);\n return opposite === undefined || activeOpposite?.memory.contentHash === hash;\n });\n const localPath = ContentHashIndex.resolvePathByHash(hash, contentHashRows(localCandidates));\n const peerPath = ContentHashIndex.resolvePathByHash(hash, contentHashRows(peerCandidates));\n\n if (localPath && peerPath && localPath !== peerPath) {\n const localFile = localByPath.get(localPath);\n const peerFile = peerByPath.get(peerPath);\n if (!localFile || !peerFile) continue;\n const duplicatePaths = new Set([\n ...localCandidates.map((file) => file.path),\n ...peerCandidates.map((file) => file.path),\n ]);\n const authoritativeSamePathEntries = new Set(entries.filter(\n (entry) =>\n duplicatePaths.has(entry.path)\n && localFilesByPath.has(entry.path)\n && peerFilesByPath.has(entry.path)\n && entry.action !== \"identical\"\n ));\n if (authoritativeSamePathEntries.size > 0) {\n for (const entry of entries) {\n if (\n duplicatePaths.has(entry.path)\n && !authoritativeSamePathEntries.has(entry)\n && (entry.action === \"pull\" || entry.action === \"push\" || entry.action === \"identical\")\n ) {\n removed.add(entry);\n changed = true;\n }\n }\n continue;\n }\n const unsafeEntry = entries.some(\n (entry) => duplicatePaths.has(entry.path) && (entry.action === \"suppress\" || entry.action === \"conflict\")\n );\n if (unsafeEntry) continue;\n for (const entry of entries) {\n if (\n duplicatePaths.has(entry.path) &&\n (entry.action === \"pull\" || entry.action === \"push\" || entry.action === \"identical\")\n ) {\n removed.add(entry);\n }\n }\n const semanticAgreement: ReconcileSemanticAgreement = {\n local: { path: localPath, sha256: localFile.sha256 },\n peer: { path: peerPath, sha256: peerFile.sha256 },\n };\n replacements.push({\n path: localPath < peerPath ? localPath : peerPath,\n namespace,\n action: \"identical\",\n reason: \"semantic_duplicate\",\n semanticAgreement,\n semanticChange: classifySemanticChange(\n semanticAgreement,\n priorSemanticByPathPair.get(semanticAgreementKey(semanticAgreement))\n ),\n });\n changed = true;\n continue;\n }\n\n const sameSideEntries = entries.filter((entry) => {\n if (localPath && entry.reason === \"local_only\") {\n return localCandidates.some((file) => file.path === entry.path);\n }\n if (peerPath && entry.reason === \"peer_only\") {\n return peerCandidates.some((file) => file.path === entry.path);\n }\n return false;\n });\n const canonicalPath = localPath ?? peerPath;\n const hasSharedCanonical = localPath !== undefined && localPath === peerPath;\n if (!canonicalPath || sameSideEntries.length === 0 || (!hasSharedCanonical && sameSideEntries.length < 2)) {\n continue;\n }\n for (const entry of sameSideEntries) {\n if (entry.path !== canonicalPath) {\n removed.add(entry);\n changed = true;\n }\n }\n }\n\n if (removed.size > 0 || replacements.length > 0) {\n entriesByNamespace.set(\n namespace,\n [...entries.filter((entry) => !removed.has(entry)), ...replacements].sort(comparePlanEntries)\n );\n }\n }\n\n if (!changed) return plan;\n const entries = [...entriesByNamespace.values()].flat().sort(comparePlanEntries);\n return {\n entries,\n byNamespace: summarizeReconcilePlan(entries),\n converged: entries.every((entry) => entry.action === \"identical\"),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAcpB,IAAM,4BAA4B;AAClC,IAAM,oCAAoC;AA2BjD,IAAM,iBAAiB;AACvB,IAAM,cAAc,IAAI,IAAI,oBAAoB;AAEhD,SAAS,aAAa,UAA2B;AAC/C,MAAI,CAAC,SAAS,SAAS,KAAK,EAAG,QAAO;AACtC,QAAM,WAAW,SAAS,MAAM,GAAG;AACnC,MAAI,QAAQ;AACZ,MAAI,SAAS,KAAK,MAAM,UAAU,SAAS,KAAK,MAAM,UAAW,UAAS;AAC1E,SAAO,YAAY,IAAI,SAAS,KAAK,KAAK,EAAE;AAC9C;AAEA,SAAS,YAAY,OAA+C;AAClE,MAAI,UAAU,OAAW,QAAO;AAChC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,MAAI,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,GAAG;AACpD,QAAI;AACF,YAAM,SAAS,KAAK,MAAM,OAAO;AACjC,aAAO,OAAO,WAAW,WAAW,SAAS;AAAA,IAC/C,QAAQ;AACN,aAAO,QAAQ,MAAM,GAAG,EAAE,EAAE,QAAQ,QAAQ,GAAG;AAAA,IACjD;AAAA,EACF;AACA,MAAI,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,GAAG;AACpD,WAAO,QAAQ,MAAM,GAAG,EAAE,EAAE,QAAQ,OAAO,GAAG;AAAA,EAChD;AACA,SAAO;AACT;AAEA,SAAS,qBAAqB,UAAkB,KAA2D;AAC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B,QAAM,UAAU,CAAC,GAAG,mBAAmB,OAAO,CAAC,EAAE,KAAK,EAAE,KAAK,kBAAkB;AAC/E,SAAO;AAAA,IACL;AAAA,IACA,aAAa,uBAAuB,OAAO;AAAA,IAC3C,WAAW,QAAQ,MAAM,CAAC,UAAU,MAAM,WAAW,WAAW;AAAA,EAClE;AACF;","names":["entries"]}
@@ -5,6 +5,7 @@ import '../bounded-jsonl-state.js';
5
5
  import '../operator-doctor-types.js';
6
6
  import '../types-continuity.js';
7
7
 
8
+ type ReconcileConflictPolicy = ConvergeConflictPolicy;
8
9
  /**
9
10
  * Bootstrap reconciliation planner for two peer daemons whose corpora have
10
11
  * already diverged (issue #2150).
@@ -31,6 +32,15 @@ type ReconcileAction = "pull" | "push" | "identical" | "conflict" | "suppress";
31
32
  * can assign distinct durable identities to both revisions.
32
33
  */
33
34
  type ReconcileResolution = "local-wins" | "peer-wins" | "supersede-link" | "unresolved";
35
+ interface ReconcileSemanticFileState {
36
+ path: string;
37
+ sha256: string;
38
+ }
39
+ interface ReconcileSemanticAgreement {
40
+ local: ReconcileSemanticFileState;
41
+ peer: ReconcileSemanticFileState;
42
+ }
43
+ type ReconcileSemanticChange = "unchanged" | "local_changed" | "peer_changed" | "both_modified";
34
44
  interface ReconcilePlanEntry {
35
45
  path: string;
36
46
  namespace: string;
@@ -50,6 +60,13 @@ interface ReconcilePlanEntry {
50
60
  * delete the live copy instead of the retracted one.
51
61
  */
52
62
  suppressSide?: "local" | "peer" | "both";
63
+ /**
64
+ * Real per-side identities for a cross-path semantic agreement. Synthetic
65
+ * rows omit the top-level side digests because `path` cannot name both files.
66
+ */
67
+ semanticAgreement?: ReconcileSemanticAgreement;
68
+ /** Each side's current digest compared with its own prior semantic digest. */
69
+ semanticChange?: ReconcileSemanticChange;
53
70
  }
54
71
  type ReconcileReason = "peer_only" | "local_only"
55
72
  /** Cursor showed only that side moved since agreement; both still hold the path. */
@@ -167,4 +184,4 @@ declare function summarizeReconcilePlan(entries: readonly ReconcilePlanEntry[]):
167
184
  */
168
185
  declare function planReconciliation(namespaces: readonly ReconcileNamespaceInput[], options?: ReconcileOptions): ReconcilePlan;
169
186
 
170
- export { type ReconcileAction, type ReconcileFileState, type ReconcileNamespaceInput, type ReconcileNamespaceReport, type ReconcileOptions, type ReconcilePlan, type ReconcilePlanEntry, ReconcilePlanInputError, type ReconcileReason, type ReconcileResolution, planNamespaceReconciliation, planReconciliation, summarizeReconcilePlan };
187
+ export { type ReconcileAction, type ReconcileConflictPolicy, type ReconcileFileState, type ReconcileNamespaceInput, type ReconcileNamespaceReport, type ReconcileOptions, type ReconcilePlan, type ReconcilePlanEntry, ReconcilePlanInputError, type ReconcileReason, type ReconcileResolution, type ReconcileSemanticAgreement, type ReconcileSemanticChange, type ReconcileSemanticFileState, planNamespaceReconciliation, planReconciliation, summarizeReconcilePlan };
@@ -3,7 +3,7 @@ import {
3
3
  planNamespaceReconciliation,
4
4
  planReconciliation,
5
5
  summarizeReconcilePlan
6
- } from "../chunk-K442KOID.js";
6
+ } from "../chunk-HZFHQ4AQ.js";
7
7
  import "../chunk-HBVPYRDW.js";
8
8
  import "../chunk-EGGE52UU.js";
9
9
  import "../chunk-7XC2HX75.js";