|
| 1 | +/** |
| 2 | + * Tier 5 end-to-end — exercises the full sync loop across two simulated |
| 3 | + * `LUMEN_DIR` instances connected by an in-memory mock relay. Touches every |
| 4 | + * sub-tier: |
| 5 | + * |
| 6 | + * 5a — sync_journal write-path triggers (upsertConcept, recordFeedback, |
| 7 | + * updateCompiledTruth, retireConcept all append journal rows) |
| 8 | + * 5b — encrypt/decrypt envelope round-trip |
| 9 | + * 5c — relay client push/pull + cursor pagination |
| 10 | + * 5d — exercised indirectly via the mock relay's ?since semantics |
| 11 | + * 5e — apply pass translating pulled rows into local store mutations |
| 12 | + * |
| 13 | + * Verifies that mutations on device A become observable on device B after |
| 14 | + * a single push → pull → apply cycle, with no plaintext touching the relay. |
| 15 | + */ |
| 16 | + |
| 17 | +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; |
| 18 | +import { mkdtempSync, rmSync } from 'node:fs'; |
| 19 | +import { join } from 'node:path'; |
| 20 | +import { tmpdir } from 'node:os'; |
| 21 | +import { resetDataDir } from '../src/utils/paths.js'; |
| 22 | +import { getDb, resetDb } from '../src/store/database.js'; |
| 23 | +import { |
| 24 | + setMasterKey, |
| 25 | + deleteMasterKey, |
| 26 | + setKeyringBackend, |
| 27 | + setEnabled, |
| 28 | + setRelayConfig, |
| 29 | + runPush, |
| 30 | + runPull, |
| 31 | + runApply, |
| 32 | + resetCircuitBreakerForTests, |
| 33 | + generateMasterKey, |
| 34 | + deriveUserHash, |
| 35 | + fingerprintMasterKey, |
| 36 | + decryptEnvelope, |
| 37 | + type FetchLike, |
| 38 | + type PushBatch, |
| 39 | + type PullEntry, |
| 40 | + type EncryptionEnvelope, |
| 41 | +} from '../src/sync/index.js'; |
| 42 | +import { |
| 43 | + upsertConcept, |
| 44 | + getConcept, |
| 45 | + updateCompiledTruth, |
| 46 | + retireConcept, |
| 47 | +} from '../src/store/concepts.js'; |
| 48 | +import { recordFeedback } from '../src/store/feedback.js'; |
| 49 | + |
| 50 | +let dirA: string; |
| 51 | +let dirB: string; |
| 52 | +let masterKey: Buffer; |
| 53 | + |
| 54 | +/** Yield long enough that consecutive ISO timestamps differ — otherwise |
| 55 | + * same-ms writes tie on `updated_at` and the LWW path returns `tie`. */ |
| 56 | +function tick(): Promise<void> { |
| 57 | + return new Promise((resolve) => setTimeout(resolve, 5)); |
| 58 | +} |
| 59 | + |
| 60 | +beforeEach(() => { |
| 61 | + dirA = mkdtempSync(join(tmpdir(), 'lumen-e2e-A-')); |
| 62 | + dirB = mkdtempSync(join(tmpdir(), 'lumen-e2e-B-')); |
| 63 | + masterKey = generateMasterKey(); |
| 64 | + process.env.LUMEN_RELAY_NO_BACKOFF = '1'; |
| 65 | +}); |
| 66 | + |
| 67 | +afterEach(() => { |
| 68 | + deleteMasterKey(); |
| 69 | + setKeyringBackend(null); |
| 70 | + resetDb(); |
| 71 | + resetDataDir(); |
| 72 | + delete process.env.LUMEN_DIR; |
| 73 | + delete process.env.LUMEN_RELAY_NO_BACKOFF; |
| 74 | + rmSync(dirA, { recursive: true, force: true }); |
| 75 | + rmSync(dirB, { recursive: true, force: true }); |
| 76 | +}); |
| 77 | + |
| 78 | +/** |
| 79 | + * Switch the test process between the two simulated devices. Each switch |
| 80 | + * tears down the prepared-statement cache and the singleton DB handle so |
| 81 | + * the next `getDb()` opens against the new LUMEN_DIR. The master key is |
| 82 | + * shared (simulating a successful Tier 6 key-share onboarding). |
| 83 | + */ |
| 84 | +function useDevice(dir: string): void { |
| 85 | + resetDb(); |
| 86 | + resetDataDir(); |
| 87 | + process.env.LUMEN_DIR = dir; |
| 88 | + setKeyringBackend('memory'); |
| 89 | + setMasterKey(masterKey); |
| 90 | + getDb(); |
| 91 | + setRelayConfig({ |
| 92 | + user_hash: deriveUserHash(masterKey), |
| 93 | + relay_url: 'https://relay.test', |
| 94 | + encryption_key_fingerprint: fingerprintMasterKey(masterKey), |
| 95 | + }); |
| 96 | + setEnabled(true); |
| 97 | + resetCircuitBreakerForTests(); |
| 98 | +} |
| 99 | + |
| 100 | +/** In-memory relay shared across both devices. Closes over `entries`. */ |
| 101 | +function makeMockRelay(): { fetch: FetchLike; entries: PullEntry[] } { |
| 102 | + const entries: PullEntry[] = []; |
| 103 | + const fetchImpl: FetchLike = async (url, init) => { |
| 104 | + const method = init?.method ?? 'GET'; |
| 105 | + if (method === 'POST') { |
| 106 | + const batch = JSON.parse(String(init?.body)) as PushBatch; |
| 107 | + for (const e of batch.entries) { |
| 108 | + entries.push({ |
| 109 | + sync_id: e.sync_id, |
| 110 | + envelope: e.envelope, |
| 111 | + scope_routing_tag: e.scope_routing_tag, |
| 112 | + received_at: new Date().toISOString(), |
| 113 | + }); |
| 114 | + } |
| 115 | + return new Response(JSON.stringify({ accepted: batch.entries.length, rejected: [] }), { |
| 116 | + status: 200, |
| 117 | + }); |
| 118 | + } |
| 119 | + /** GET — honour the `since` query so cursor pagination behaves like Tier 5d. */ |
| 120 | + const u = new URL(url); |
| 121 | + const since = u.searchParams.get('since') ?? ''; |
| 122 | + const filtered = since ? entries.filter((e) => e.sync_id > since) : [...entries]; |
| 123 | + return new Response(JSON.stringify({ entries: filtered, next_cursor: null }), { |
| 124 | + status: 200, |
| 125 | + }); |
| 126 | + }; |
| 127 | + return { fetch: fetchImpl, entries }; |
| 128 | +} |
| 129 | + |
| 130 | +describe('Tier 5 end-to-end (A → relay → B)', () => { |
| 131 | + it('round-trips concept_create + feedback + truth_update from A to B', async () => { |
| 132 | + const relay = makeMockRelay(); |
| 133 | + |
| 134 | + /** ─── Device A: mutate locally, push to relay ─── */ |
| 135 | + useDevice(dirA); |
| 136 | + const now = new Date().toISOString(); |
| 137 | + upsertConcept({ |
| 138 | + slug: 'attention', |
| 139 | + name: 'Attention', |
| 140 | + summary: 'self-attention mechanism', |
| 141 | + compiled_truth: null, |
| 142 | + article: null, |
| 143 | + created_at: now, |
| 144 | + updated_at: now, |
| 145 | + mention_count: 1, |
| 146 | + scope_kind: 'personal', |
| 147 | + scope_key: 'me', |
| 148 | + }); |
| 149 | + await tick(); |
| 150 | + recordFeedback({ slug: 'attention', delta: 1, reason: 'cited in 3 papers' }); |
| 151 | + await tick(); |
| 152 | + updateCompiledTruth('attention', 'Self-attention scales O(n^2) in sequence length.'); |
| 153 | + |
| 154 | + const pushResult = await runPush({ fetchImpl: relay.fetch }); |
| 155 | + expect(pushResult.errors).toEqual([]); |
| 156 | + expect(pushResult.pushed).toBe(3); |
| 157 | + expect(relay.entries).toHaveLength(3); |
| 158 | + |
| 159 | + /** All envelopes on the wire must be opaque to anyone without Kx. */ |
| 160 | + for (const e of relay.entries) { |
| 161 | + expect(e.envelope.v).toBe(1); |
| 162 | + expect(e.envelope.c.length).toBeGreaterThan(0); |
| 163 | + /** Plaintext is JSON; reject the trivial "looks like JSON" leak check. */ |
| 164 | + const raw = Buffer.from(e.envelope.c, 'base64').toString('utf-8'); |
| 165 | + expect(raw.startsWith('{')).toBe(false); |
| 166 | + } |
| 167 | + |
| 168 | + /** Spot-check: round-trip one envelope with the master key reproduces the original op. */ |
| 169 | + const decoded = JSON.parse(decryptEnvelope(relay.entries[0].envelope, masterKey)) as { |
| 170 | + op: string; |
| 171 | + entity_id: string; |
| 172 | + }; |
| 173 | + expect(decoded.op).toBe('concept_create'); |
| 174 | + expect(decoded.entity_id).toBe('attention'); |
| 175 | + |
| 176 | + /** ─── Device B: pull, apply, verify state matches ─── */ |
| 177 | + useDevice(dirB); |
| 178 | + expect(getConcept('attention')).toBeNull(); |
| 179 | + |
| 180 | + const pullResult = await runPull({ fetchImpl: relay.fetch }); |
| 181 | + expect(pullResult.errors).toEqual([]); |
| 182 | + expect(pullResult.pulled).toBe(3); |
| 183 | + |
| 184 | + const applyResult = runApply(); |
| 185 | + expect(applyResult.applied).toBe(3); |
| 186 | + expect(applyResult.apply_failed).toBe(0); |
| 187 | + |
| 188 | + const conceptOnB = getConcept('attention'); |
| 189 | + expect(conceptOnB).not.toBeNull(); |
| 190 | + expect(conceptOnB?.name).toBe('Attention'); |
| 191 | + expect(conceptOnB?.compiled_truth).toBe('Self-attention scales O(n^2) in sequence length.'); |
| 192 | + expect(conceptOnB?.score).toBe(1); |
| 193 | + }); |
| 194 | + |
| 195 | + it('round-trips a retire from A to B (retired_at observable on B)', async () => { |
| 196 | + const relay = makeMockRelay(); |
| 197 | + |
| 198 | + useDevice(dirA); |
| 199 | + const now = new Date().toISOString(); |
| 200 | + upsertConcept({ |
| 201 | + slug: 'deprecated-pattern', |
| 202 | + name: 'Deprecated Pattern', |
| 203 | + summary: null, |
| 204 | + compiled_truth: null, |
| 205 | + article: null, |
| 206 | + created_at: now, |
| 207 | + updated_at: now, |
| 208 | + mention_count: 1, |
| 209 | + scope_kind: 'personal', |
| 210 | + scope_key: 'me', |
| 211 | + }); |
| 212 | + retireConcept('deprecated-pattern', 'superseded by new pattern'); |
| 213 | + |
| 214 | + const pushResult = await runPush({ fetchImpl: relay.fetch }); |
| 215 | + expect(pushResult.pushed).toBe(2); |
| 216 | + |
| 217 | + useDevice(dirB); |
| 218 | + await runPull({ fetchImpl: relay.fetch }); |
| 219 | + const applyResult = runApply(); |
| 220 | + expect(applyResult.applied).toBe(2); |
| 221 | + |
| 222 | + const conceptOnB = getConcept('deprecated-pattern'); |
| 223 | + expect(conceptOnB).not.toBeNull(); |
| 224 | + expect(conceptOnB?.retired_at).not.toBeNull(); |
| 225 | + expect(conceptOnB?.retire_reason).toBe('superseded by new pattern'); |
| 226 | + }); |
| 227 | + |
| 228 | + it('relay sees only opaque ciphertext — wrong key cannot decrypt', async () => { |
| 229 | + const relay = makeMockRelay(); |
| 230 | + useDevice(dirA); |
| 231 | + const now = new Date().toISOString(); |
| 232 | + upsertConcept({ |
| 233 | + slug: 'private', |
| 234 | + name: 'Private', |
| 235 | + summary: 'sensitive content', |
| 236 | + compiled_truth: null, |
| 237 | + article: null, |
| 238 | + created_at: now, |
| 239 | + updated_at: now, |
| 240 | + mention_count: 1, |
| 241 | + scope_kind: 'personal', |
| 242 | + scope_key: 'me', |
| 243 | + }); |
| 244 | + await runPush({ fetchImpl: relay.fetch }); |
| 245 | + expect(relay.entries.length).toBeGreaterThan(0); |
| 246 | + |
| 247 | + const wrongKey = generateMasterKey(); |
| 248 | + expect(() => decryptEnvelope(relay.entries[0].envelope, wrongKey)).toThrow(); |
| 249 | + }); |
| 250 | + |
| 251 | + it('pull is idempotent — re-running a sync cycle does not duplicate state on B', async () => { |
| 252 | + const relay = makeMockRelay(); |
| 253 | + |
| 254 | + useDevice(dirA); |
| 255 | + const now = new Date().toISOString(); |
| 256 | + upsertConcept({ |
| 257 | + slug: 'dedup-test', |
| 258 | + name: 'Dedup', |
| 259 | + summary: null, |
| 260 | + compiled_truth: null, |
| 261 | + article: null, |
| 262 | + created_at: now, |
| 263 | + updated_at: now, |
| 264 | + mention_count: 1, |
| 265 | + scope_kind: 'personal', |
| 266 | + scope_key: 'me', |
| 267 | + }); |
| 268 | + recordFeedback({ slug: 'dedup-test', delta: 1, reason: 'first' }); |
| 269 | + await runPush({ fetchImpl: relay.fetch }); |
| 270 | + |
| 271 | + useDevice(dirB); |
| 272 | + await runPull({ fetchImpl: relay.fetch }); |
| 273 | + runApply(); |
| 274 | + expect(getConcept('dedup-test')?.score).toBe(1); |
| 275 | + |
| 276 | + /** Re-pull (no new entries on the relay). insertPulled is idempotent |
| 277 | + * on sync_id, applyPending is idempotent on applied_at IS NOT NULL. */ |
| 278 | + const secondPull = await runPull({ fetchImpl: relay.fetch }); |
| 279 | + expect(secondPull.pulled).toBe(0); |
| 280 | + const secondApply = runApply(); |
| 281 | + expect(secondApply.applied).toBe(0); |
| 282 | + expect(getConcept('dedup-test')?.score).toBe(1); |
| 283 | + }); |
| 284 | +}); |
0 commit comments