◯ KuberanOffline Sync & Local AI

Offline is a normal operating mode, not an emergency mode.

Kuberan commits business activity on the device where it happens, gives the user an immediate answer, then synchronizes immutable events through the Java store server. The store keeps trading through an internet outage, a server restart, or a temporary Wi‑Fi failure.

The synchronization model

Use an event outbox on every client, an inbox/idempotency table on the server, server-assigned ordering, and per-device pull cursors. This is simpler than distributed database replication and gives each business event an audit trail.

1. Flutter client + SQLiteOne local database transaction writes the sale/receipt/count and its outbox event together. The UI succeeds only after commit.
→
2. Java/Spring Boot APIAuthenticates the device, validates the contract, checks event ID, applies the command, records server sequence, returns an acknowledgement.
→
3. Store SQLiteAuthoritative store ledger, idempotency inbox, change log, device cursors, business projections and audit records.
Never synchronize by copying SQLite files, sharing the database file, or comparing whole tables. Sync explicit versioned business events through HTTPS on the store LAN. The server database remains private to the Java process.

Interactive outage simulation

● Network online

Register 07 • local outbox

No queued events.

Store server • event log

server ready\nlast_sequence = 184229\ninbox_duplicates_rejected = 0

Push, acknowledge, then pull

Client push loop

  1. Select up to 100 unsent outbox events in creation order.
  2. POST the batch with device ID, event IDs, schema versions and payload hashes.
  3. Server validates and applies each bounded command.
  4. Mark only explicitly acknowledged IDs as sent; retain rejects with a plain-language reason.
  5. Retry timeout/5xx with exponential backoff and jitter. Never create a new event ID for a retry.

Client pull loop

  1. Send the last applied server sequence cursor.
  2. Receive the next ordered page of changes permitted for that device.
  3. Apply the whole page in one local SQLite transaction.
  4. Advance the cursor in the same transaction.
  5. Repeat until current; use a compact snapshot for first pairing or a device far behind.
POST /api/v1/sync/push { deviceId, clientInstanceId, events:[{eventId, aggregateType, aggregateId, eventType, schemaVersion, occurredAt, baseVersion, payload, payloadSha256}] } → {accepted:[{eventId, serverSequence}], duplicates:[eventId], rejected:[{eventId, code, userMessage}]} GET /api/v1/sync/pull?after=184229&limit=500 → {changes:[{serverSequence, entityType, entityId, changeType, version, payload}], nextCursor, hasMore}

Prevent most conflicts with clear ownership

The easiest conflict to solve is the one the product design prevents. Kuberan assigns an authority for each kind of data and treats shared edits differently from immutable transactions.

DataWrite authorityOffline ruleConflict rule
Completed sales, tenders, returns, till eventsOriginating registerAllowed; append-only after completionSame event ID is a retry. Corrections are new reversing events.
Products, tax, prices, promotionsStore server / back officeClient uses last signed effective snapshotServer version wins; scheduled effective times prevent mid-sale changes.
Inventory movementsOriginating workflowAllowed with unique movement IDNever overwrite quantity. Append movements; investigate variance.
Draft PO, schedule, customer noteCurrent editor with lease/versionDrafts allowedOptimistic version check; show both versions and require merge.
Customer points / store creditStore server ledgerEarn can queue; spend subject to offline limitLedger with reservation/limit; never last-write-wins balance.
Device configuration / permissionsStore serverCached signed policyMost restrictive policy wins; expired privileged sessions lock.

States, retries and repair

Pending

Committed locally but not yet sent. Visible as “saved on this device.”

In flight

Batch sent; no final assumption until explicit event IDs are acknowledged.

Acknowledged

Server sequence stored locally. Payload follows retention and audit policy.

Needs attention

Permanent validation/permission reject. User gets a repair task, never silent loss.

Poison events do not block the queue. Move a permanently rejected event to a repair queue, preserve its payload and error, continue independent events, and mark dependent events with the causal ID.

Offline payment policy is separate from offline POS

Always available locally

Cash, approved store credit within a cached limit, gift card within a risk-controlled offline policy, and completed sales recording. Drawer and receipt workflows do not need the store server.

Processor-controlled

Debit/credit may still work if the terminal has its own connection. True internet loss requires the chosen processor’s approved store-and-forward capability and merchant risk policy. Kuberan must not simulate approval.

Default safe behaviour: if the terminal cannot obtain an approval and no processor-approved offline policy is active, offer cash or another valid tender and record no card approval.

Operations and data protection

Health signals for non-technical owners

  • “All caught up,” “working offline,” or “needs help”—not queue jargon.
  • Oldest unsent event age, count, storage remaining and last good backup.
  • One-click support bundle with logs, versions and redacted IDs.
  • Alert if a register is over five minutes behind while the LAN is healthy.

SQLite operating rules

  • WAL mode, foreign keys enabled, bounded transactions and busy timeout.
  • One Java process owns server writes; clients never access the file.
  • Regular integrity checks, encrypted backup, restore verification and disk-space alarms.
  • Archive immutable history by retention policy without breaking audit obligations.

Local AI and agents on the store box

Run the AI service beside—not inside—the transactional core. It reads approved projections and document copies through a permissioned Java tool layer. Java domain services remain the only path that can create business records.

Local model runtimeOCR, embeddings, small language model and forecasting models sized to the box hardware.
↔
Agent gatewayRole permission, approved tools, data minimization, source citations, time/step limits and a complete trace log.
↔
Java business toolsRead report, draft PO, propose match, create task. Protected posting tools require explicit human approval.

Recommended local agents

Document intake agentReads vendor invoice, receipt, packing slip or bank PDF; extracts fields and lines; links candidates; flags uncertainty and duplicates.Low • draft only
Reconciliation agentSuggests matches among bank lines, tender settlements, deposits, bills, invoices and receipts; explains evidence.Low • approve to post
Replenishment agentForecasts demand using sales, on-hand, open orders, promotions, lead time, case pack and waste; prepares PO drafts.Medium • buyer approves
Manager briefing agentAnswers “what needs attention?” and links each claim to a report, transaction or exception.Low • read only
Shrink & anomaly agentRanks unusual voids, refunds, overrides, waste, inventory movements and cash differences for investigation.Medium • never accuses
Schedule helperDrafts from availability, skills, rules, forecast workload and budget; shows uncovered constraints.Medium • manager publishes
Store support agentUses installed manuals, device status and logs to guide printer, scanner, backup and sync troubleshooting.Low • diagnostic
Autonomous posting/payment agentSilently changes price/tax, posts journals, files HST, pays vendors, authorizes refunds or approves cards.Prohibited in V1

Local AI deployment tiers

TierStore-box hardwareLocal capabilityFallback
BaseModern 8-core CPU, 32 GB RAM, 1 TB mirrored/encrypted SSDOCR, embeddings, classic forecasts, anomaly scoring and a small quantized model for short Q&A.Optional cloud for complex language tasks with consent and redaction.
AI+64 GB RAM plus supported GPU/NPUFaster document vision, larger local model, richer reporting and more frequent forecasts.Local-first; cloud optional.
No-AIBase server without model runtimeRules, deterministic imports, manual review and every transactional feature.Business operation remains complete.
Model updates are signed and reversible. A new model runs shadow tests against stored evaluation cases. Version, prompt, sources, tool calls and approval are kept with every consequential suggestion.

AI permission and safety contract

Every answer carries

  • Model and workflow version.
  • Source record IDs and timestamps.
  • Confidence or uncertainty where measurable.
  • Whether data is current or the device is offline.
  • A plain-language explanation of what approval will do.

Every agent is constrained by

  • Named role and store scope.
  • Allow-listed, typed Java tools.
  • Read-only by default; draft tools second; posting tools separately gated.
  • Maximum steps, duration, records and currency impact.
  • Vendor documents treated as untrusted data to resist prompt injection.

Recommended Version 1 build order

  1. Build client outbox, server inbox, ordered pull log, snapshots and sync monitor first.
  2. Prove sale, return, till and inventory idempotency with forced disconnect/retry tests.
  3. Add document intake with OCR/extraction and human review; then vendor invoice matching.
  4. Add bank CSV/OFX import and rule-based matching before a language-model agent.
  5. Add local search/manager briefing after permissions and audit logs are complete.
  6. Add PO forecasting and anomaly agents only after clean historical data exists.
Review notes · 2 critical protocol gaps

Technical Product Manager · Critical
Target: Offline payments. Define every payment state, stable attempt IDs, inquiry-before-retry, callback idempotency and sale/tender recovery.

Technical Product Manager · Critical
Target: Retries and repair. Define ordering, dependencies, batch semantics, poison events, retention, compaction, snapshot cutover and restore reconciliation.

Business Owner · Medium
Target: AI tiers. Add cost/data/health/disable controls and guarantee core operation without AI.

Read full attributed notes →
Powered by AI Agent Worker