/** * Sync shipper (Wave 3d, ADR-003) — one-way, append-only, idempotent log * shipping: local memory_events -> cloud POST /sync/events. * * The log IS the queue: unsynced rows are `synced_at IS NULL`; a batch is * acked by the cloud's `{ acked_seq }` and marked in one UPDATE. Crash-safe * by construction — replaying a batch is always safe (cloud dedups on * content_hash and (device_id, seq)). * * Scope filter (ADR-009): only events whose atom is team/org-scoped ship. * `private` atoms (renamed from `personal`, U7-local astramem-local#110, * DEC-048) never leave the machine. erase_request events for atoms * whose row is already hard-deleted ship when their payload carries a * team/org scope (3f writes the scope into the erase payload for exactly * this reason). * * Offline: unlimited — failures leave rows unsynced; retry with exponential * backoff capped at BACKOFF_CAP_MS. */ import type { DB } from '../storage/db.js'; import type { MemoryScope } from '../contracts/index.js'; export declare const SYNC_PROTOCOL: "astramem-sync@1"; export interface WireSyncEvent { seq: number; event_type: string; atom_id: string; payload_json: Record | null; content_hash: string | null; created_at: number; /** * Globally-unique event identity (ADR-011, migration 010). Additive field * — no astramem-sync@1 version bump (ADR-001's additive-field evolution * rule): older push clients that omit it are still valid envelopes; this * daemon always populates it (migration 010 backfills every pre-existing * row, and MemoryEventRepo.append() always assigns one going forward). * It is the pull-side dedup key (FEAT-407 AC-2) and the ADR-011 conflict * tie-break key (created_at, event_id). */ event_id: string; } export interface SyncEnvelope { protocol: typeof SYNC_PROTOCOL; device_id: string; workspace_id: string; cursor: number; events: WireSyncEvent[]; } export interface ShipperOpts { db: DB; /** Cloud base URL, e.g. https://memory.example.com — POSTs to /sync/events. */ url: string; workspaceId: string; deviceId: string; /** Bearer for the cloud (device token). */ token: string; batchSize?: number; intervalMs?: number; /** Injectable fetch for tests. */ fetchImpl?: typeof fetch; } export interface ShipperHandle { /** Stop the loop. Resolves after any in-flight ship completes. */ stop(): Promise; } export interface ShipperGateInput { /** `cfg.sync.enabled` — merged from sync.json pairing state at boot * (resolve-runtime.ts). Pairing-owned; `astramem-local pair` flips this to * true on a successful redeem. */ enabled: boolean; /** `cfg.sync.experimental` — config.yaml, hand-edit only. `pair` never * touches this field. */ experimental: boolean; dataDir: string; /** True under ASTRA_MEMORY_ISOLATED=1 (see resolve-runtime.ts). */ isolated: boolean; } /** * Hard gate on top of `enabled` (astramem-local sync-experimental-gate * slice). Originally added because sync-to-astramem-cloud was broken (8868 * events failing HTTP 400); that was root-caused to a YARP stale-pooled- * connection bug in the shared gateway (`common` repo, commit `edf266a`, * bounds `PooledConnectionLifetime`), fixed and deployed to prod 2026-07-14, * and re-verified live 2026-07-15 — sync is no longer known-broken. The gate * now stands as a deliberate staged-rollout safety net, not a "sync is * broken" guard: relaxing/removing it is a product decision, not a bugfix. * Before this gate, `astramem-local pair ` alone set `sync.json`'s * `enabled: true` and that was sufficient to start shipping — anyone who * paired hit the (then-broken) path. Both `enabled` (sync.json, * pairing-owned) AND `experimental` (config.yaml, hand-edit only) must be * true, on top of the pre-existing dataDir/isolated guards `cli/serve.ts` * already enforced. Pure/exported so the gate is unit-testable without * spawning a daemon. */ export declare function shouldStartShipper(input: ShipperGateInput): boolean; /** * Read a failed response's body (bounded to ~500 chars) for inclusion in the * thrown error message. A bare "HTTP 403" told us nothing about *why* — the * cloud's error JSON (e.g. `{"error":"sync_disabled"}`) is what actually * explains the failure, and swallowing it cost hours of debugging on a real * incident (astramem-local#81). Never throws itself — a body read failure * must not mask the original HTTP error. */ export declare function readErrorBody(res: Response): Promise; /** * Stable per-install device id, persisted as a plain file in the config dir * (an identifier, not a secret — the device TOKEN lives in the keystore). */ export declare function getOrCreateDeviceId(configDir: string): string; interface UnsyncedRow { seq: number; event_id: string; event_type: string; atom_id: string; payload_json: string | null; content_hash: string | null; created_at: number; /** * The atom's CURRENT scope (memories.scope), not the scope frozen into * this row's payload_json at write time. null only when the LEFT JOIN * found no memories row (the erase_request-for-a-ghost-atom case) — never * null for a `create`/`promote_scope` row, since those always require a * live memories row to satisfy this query's own WHERE clause below. * {@link buildEnvelope} uses this to correct a stale `create` payload * scope on the wire — see that function's doc comment for why. */ current_scope: MemoryScope | null; } /** * Unsynced, ship-eligible events in seq order (ADR-009 scope filter). * LEFT JOIN: an erase_request may outlive its memories row — it ships when * its payload records a team/org scope. * * `archive`/`restore` (FEAT-404) are excluded unconditionally, regardless of * scope: archival is a per-device retention/storage-hygiene decision (one * device's local SQLite-growth mitigation), not a semantic memory change, * so it must never leave the machine. The sync wire schema * (contracts/schemas/sync-envelope.v1.schema.json) also never lists these * two types in its event_type enum — shipping one would fail schema * validation on the wire, on top of being the wrong policy. * * `unsupersede` (FEAT-442 reversal primitive) is excluded the same way, but * for a different reason: it's local-only by SCOPE DECISION, not by nature * (the supersede event it reverses DOES ship). Multi-device propagation of a * reversal is a real follow-up — a second device would keep believing the * merge until it independently re-derives or is told — but designing that * cross-device semantics is out of scope for the reversal primitive itself * (FEAT-442 design review: "scoped narrowly ... so it doesn't have to solve * reversal for every supersede path in the system"). Excluding it here keeps * today's behavior safe (no wire-schema change, no risk of shipping a type * the cloud doesn't recognize) at the cost of that follow-up gap. * * `purge`/`unpurge` (FEAT-467, ADR-013 Decision 4 gate) are excluded for the * same scope-decision reason as `unsupersede`: cross-device propagation of a * disable-flow purge/restore is a real follow-up, not solved by this * primitive, and the wire schema doesn't list either type yet. * * `e.rejected_at IS NULL` (sync-promote-wedge fix, migration 036): a row the * cloud has permanently rejected (DEC-048 invariant 1 — see * SyncIngestService.IsPrivateScopedViolation) must never be reselected. Only * `shipOnce` ever sets `rejected_at`, from the cloud's `rejected_seqs` * response field — see that function's doc comment. */ export declare function listUnsynced(db: DB, batchSize: number): UnsyncedRow[]; /** Last acked seq = highest synced event seq (0 when nothing has shipped). */ export declare function lastAckedSeq(db: DB): number; /** * Timestamp (ms epoch) of the most recently-shipped event, or null if * nothing has ever shipped from this device. Read-only observability helper * (FEAT-427 GET /sync/status) — does not affect shipping behavior. */ export declare function lastShipAt(db: DB): number | null; /** * Count of currently ship-eligible, not-yet-synced events (same ADR-009 * scope-filter WHERE clause as {@link listUnsynced}, without the batch * LIMIT). Read-only observability helper (FEAT-427 GET /sync/status) — does * not affect shipping behavior. */ export declare function countUnsynced(db: DB): number; /** Count of events currently marked terminally rejected by the cloud. */ export declare function countRejected(db: DB): number; /** * How many of THESE seqs are actually marked rejected — i.e. what a targeted * `sync unreject --seq N` would really clear. Distinct from {@link countRejected} * so the dry-run preview reports the blast radius of the command the operator * typed, not the total across the whole log. */ export declare function countRejectedIn(db: DB, seqs: number[]): number; /** * Clear the terminal-reject marker so these events are shipped again — the * escape hatch for the one-way door `rejected_at` otherwise creates. * * WHY THIS MUST EXIST: `rejected_at` is set from the cloud's verdict, and the * cloud can be WRONG. If a cloud bug (or a bad deploy, or a guard regression) * rejects events it should have accepted, the shipper marks them terminal and * `listUnsynced` excludes them forever — the memories are then stranded on the * device with no code path that can ever reach them again. Retrying a *correct* * reject is merely wasteful; being unable to retry an *incorrect* one is * permanent data loss. So the door opens both ways, by hand, on purpose. * * Deliberately manual (an operator runs `astramem-local sync unreject`): an * automatic retry would recreate the very wedge this migration was written to * kill. Returns the number of rows cleared. */ export declare function clearRejected(db: DB, seqs?: number[]): number; /** * Strip characters that PostgreSQL's jsonb parser rejects from every string * in a payload, recursively (2026-07-15 sync-wedge incident): * * - U+0000 (NUL): JSON.stringify emits it as the escape `\u0000`, which is * VALID JSON — but Postgres text/jsonb storage cannot hold an embedded * NUL and its parser throws `22P05: unsupported Unicode escape sequence`. * - Lone UTF-16 surrogates (U+D800–U+DFFF unpaired): serialized as * `\udXXX` escapes that Postgres likewise rejects (22P05-adjacent). * * Why sanitize HERE (ship time) and not only cloud-side: the cloud's audit * interceptor casts the serialized payload `::jsonb` inside the SAME * transaction as the batch accept — one NUL-bearing memory rolled back the * whole batch, acked_seq never advanced, and the shipper resent the * identical bytes forever (local push_seq 44235 wedge, correlationId * f0ba853a-…). Ship-time sanitization self-heals every already-queued * poison event on the next round with no cloud deploy; the cloud gets its * own defense-in-depth fix separately. NUL/lone-surrogate bytes carry no * meaning in memory text — dropping/replacing them is strictly less lossy * than the current behavior (the event can never sync at all). */ export declare function sanitizeJsonbHostile(value: T): T; export declare function buildEnvelope(deviceId: string, workspaceId: string, cursor: number, rows: UnsyncedRow[]): SyncEnvelope; export interface ShipOnceResult { shipped: number; acked: number; /** * Count of events this round the cloud named in `rejected_seqs` — marked * `rejected_at` (terminal, never resent) rather than `synced_at` * (sync-promote-wedge fix). 0 on a cloud that doesn't send the field yet * (additive, astramem-sync@1 is not version-bumped for it). */ rejected: number; /** true when there was nothing eligible to ship. */ idle: boolean; } /** * One shipping round: read a batch, POST it, mark acked rows synced. * Throws on transport/HTTP failure — the caller owns retry/backoff. */ export declare function shipOnce(opts: ShipperOpts): Promise; /** Pure backoff schedule: base * 2^failures, capped. Exported for tests. */ export declare function backoffDelay(baseMs: number, consecutiveFailures: number): number; /** * Describe a ship failure in terms a human can ACT on. * * The catch block used to log `(err as Error).message` and nothing else. For a * failed `fetch`, Node/undici sets that message to the literal string * **"fetch failed"** and puts the ACTUAL reason on `err.cause` — an * `ECONNRESET`, `ECONNREFUSED`, `UND_ERR_CONNECT_TIMEOUT`, a TLS error, etc. * Logging only `.message` therefore threw the diagnosis away and left: * * { "err": { "error_message": "fetch failed", "error_kind": "Unknown" } } * * ...which is what the operator's daemon emitted 37 times. It says the request * failed. It does not say why, and there was no other way to find out. * * Concretely: DNS resolved (api.astramemory.com -> ca-yarp-prod, 57.167.72.99), * TCP/443 connected, TLS handshook, the cert was valid — every layer we could * check by hand was healthy, and the log still only said "fetch failed". The * one fact that would have identified the layer was on `.cause`, discarded. * * Walks the whole `cause` chain (undici nests them) and surfaces `code`/`errno`, * which is the field that actually names the failing layer. */ export declare function describeShipError(err: unknown): { err: string; err_cause?: string; err_code?: string; }; /** * Last-ship-ATTEMPT state (FEAT-434) — distinct from `lastShipAt`/ * `countUnsynced` above, which only ever reflect SUCCESS (or ADR-009 * eligibility). This is what lets `GET /sync/status` (FEAT-427) show * "failing/backing off" instead of only ever success/idle. * * Persisted (not in-memory) for the same reason `sync_pull_state` (migration * 010) is persisted rather than kept in the puller's closure: a daemon * restart should not silently erase the fact that the last attempt failed — * `startShipper`'s own in-memory `failures` counter resets to 0 on restart, * but this row does not. */ export interface ShipAttemptState { last_attempt_at: number | null; last_result: 'ok' | 'error' | null; /** Sanitized (no token) + length-capped. See {@link recordShipFailure}. */ last_error: string | null; consecutive_failures: number; /** Epoch ms of the next scheduled retry, or null when not currently backing off. */ next_retry_at: number | null; } /** * Strip the device sync token (if present) and cap length before an error * message is persisted/exposed. Defense-in-depth: `shipOnce` failures today * come from HTTP status text or fetch/transport errors, neither of which * includes the bearer token (it's sent as a header, never interpolated into * a thrown message) — but a future error path doing so must not leak it via * this state row or the FEAT-427 `/sync/status` route that reads it. */ export declare function sanitizeShipError(message: string, token?: string): string; /** Record a successful ship attempt — clears error/backoff state. */ export declare function recordShipSuccess(db: DB, at: number): void; /** Record a failed ship attempt — captures the (sanitized) error + backoff schedule. */ export declare function recordShipFailure(db: DB, at: number, error: unknown, consecutiveFailures: number, nextRetryAt: number, token?: string): void; /** * Current persisted ship-attempt state, or all-null/zero defaults if the * shipper has never run a round on this DB. Read-only observability helper * (FEAT-434 GET /sync/status) — does not affect shipping behavior. */ export declare function getShipAttemptState(db: DB): ShipAttemptState; /** * Start the periodic shipper loop. Ships immediately, then every intervalMs; * on failure the next attempt is delayed by exponential backoff. */ export declare function startShipper(opts: ShipperOpts): ShipperHandle; export {};