linkedin-relay-mcp 2.1.0 → 3.0.0
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.
- package/dist/cli.js +162 -3
- package/dist/cli.js.map +1 -1
- package/dist/index.js +21 -2
- package/dist/index.js.map +1 -1
- package/dist/mcp-shim.js +21 -2
- package/dist/mcp-shim.js.map +1 -1
- package/package.json +1 -1
package/dist/mcp-shim.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp-shim.ts","../src/cache/db.ts","../src/cache/store.ts","../src/engine/restli.ts","../src/format.ts","../src/output.ts","../src/commands/cache.ts","../src/progress.ts","../src/engine/budget.ts","../src/engine/auth.ts","../src/engine/classify.ts","../src/engine/client.ts","../src/engine/contracts.ts","../src/engine/parse.ts","../src/engine/index.ts","../src/engine/session.ts","../src/commands/live.ts","../src/commands/local.ts","../src/commands/registry.ts","../src/entry.ts"],"sourcesContent":["#!/usr/bin/env bun\n// ─── MCP surface ──────────────────────────────────────────────────────────────\n//\n// Thin by contract: this file validates arguments, calls the same runners the\n// CLI calls, and returns the same envelope. No parsing, no transport, no\n// pacing, no cache logic lives here.\n//\n// Writes are not registered. Not disabled, not permission-gated — absent. The\n// registry marks each command's audience and risk, `mcpCommands()` filters on\n// both, and a test asserts no write survives that filter. An agent talking to\n// this server cannot post, comment, react, connect or message, whatever\n// arguments it composes.\n//\n// Tool descriptions do real work here. The agent reads them BEFORE it ever sees\n// a response, so each one states the specific misreading that would cause harm\n// — chiefly that an empty result and a failed fetch look identical unless you\n// check the counts.\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport { runCacheStatus, runLocal, runSourceRead } from './commands/cache.ts';\nimport {\n runFeed,\n runPost,\n runProfile,\n runReactions,\n runSearch,\n runWhoami,\n} from './commands/live.ts';\nimport { runBudget, runDoctor, runRisk } from './commands/local.ts';\nimport { mcpCommands } from './commands/registry.ts';\nimport { shouldRunAsEntry } from './entry.ts';\nimport type { Envelope } from './types.ts';\n\nconst READING_CONTRACT =\n 'ALWAYS read `meta` before reporting. `state:\"complete\"` with an empty `items` genuinely means ' +\n 'none. `state:\"partial\"` means references failed to resolve — the record is INCOMPLETE, not ' +\n 'small. `claimedCount > 0` with `returnedCount === 0` is a FAILED FETCH, never \"no results\". ' +\n 'A non-empty `unknownTypes` means LinkedIn changed shape and the parser is behind — say so. ' +\n 'If `meta.budget.remaining` is low, tell the user and stop.';\n\nconst NO_RETRY =\n 'Never retry on failure. RATE_LIMITED, REQUEST_DENIED, CHALLENGE_DETECTED and COOLDOWN_ACTIVE ' +\n 'all mean a cross-process cooldown has opened; every further call will refuse until it lifts. ' +\n 'Report it and stop.';\n\n/** Render an envelope as MCP content. Errors stay envelopes, not exceptions. */\nfunction reply(envelope: Envelope) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(envelope) }],\n isError: !envelope.ok,\n };\n}\n\nexport function buildServer(): McpServer {\n const server = new McpServer({ name: 'linkedin-relay', version: '0.1.0' });\n\n // Guard rather than trust: if a write ever reached this list, fail loudly at\n // startup instead of quietly exposing it.\n const exposed = mcpCommands();\n const write = exposed.find((c) => c.risk === 'write');\n if (write !== undefined) {\n throw new Error(`refusing to start: write command '${write.name}' reached the MCP surface`);\n }\n\n server.tool(\n 'risk',\n 'Circuit-breaker state and the ToS notice. Free, no network. CALL THIS FIRST in a research ' +\n 'session — it reports whether LinkedIn has thrown a throttle, block or challenge, so you ' +\n 'find out before spending calls rather than one wasted call at a time.',\n {},\n async () => reply(runRisk(Date.now())),\n );\n\n server.tool(\n 'budget',\n \"Remaining request budget per class, with each cap's provenance. Free, no network. The caps \" +\n 'are deliberately low because LinkedIn restricts accounts for READ velocity alone — they are ' +\n \"guesses, not measured safe limits, and they cannot see the user's own browser activity.\",\n {},\n async () => reply(runBudget(Date.now(), false, false)),\n );\n\n server.tool(\n 'doctor',\n 'Diagnose setup end to end: session, cooldown, budget, engine readiness. Free with offline. ' +\n 'Run this first when anything behaves oddly. Never reveals credential values.',\n { offline: z.boolean().optional().describe('skip live checks (default true)') },\n async ({ offline }) => reply(runDoctor(Date.now(), offline ?? true)),\n );\n\n server.tool(\n 'whoami',\n 'The authenticated LinkedIn member: name, headline, public id, urn. Cheap (1 call). Good ' +\n `first call to confirm the session works and which account it is. ${NO_RETRY}`,\n {},\n async () => reply(await runWhoami()),\n );\n\n server.tool(\n 'search',\n 'Search LinkedIn people, companies or jobs. CHEAP — this is the net. Rows already carry name, ' +\n 'headline, location and url, so RANK ON THOSE and deep-read only 2-3 finalists with ' +\n '`profile`. Calling profile on every result burns a day of budget in one request. ' +\n \"`meta.claimedCount` is LinkedIn's total for the query (often millions), NOT how many you \" +\n 'got, and `meta.state` is always \"unknown\" because this is one page of many. Out-of-network ' +\n 'people return as name \"LinkedIn Member\" with a /headless url — that is real LinkedIn ' +\n `behaviour for this account, not a failure. ${READING_CONTRACT} ${NO_RETRY}`,\n {\n kind: z.enum(['people', 'companies', 'jobs']),\n query: z.string().min(1).describe('search terms'),\n limit: z.number().int().min(1).max(25).optional().describe('default 10'),\n },\n async ({ kind, query, limit }) => reply(await runSearch(kind, query, limit ?? 10)),\n );\n\n server.tool(\n 'profile',\n 'Read one LinkedIn profile: headline, location, current title, company, school. MEDIUM cost — ' +\n 'use only on finalists surfaced by `search`. Accepts a public id, a urn, or a ' +\n \"linkedin.com/in/… URL. KNOWN LIMIT: LinkedIn's profile projections do not return a name, \" +\n 'so the result has a headline but no first/last name — use the identifier you passed in. ' +\n `Do NOT report the profile as empty on that basis. ${NO_RETRY}`,\n { id: z.string().min(1).describe('public id, urn, or profile URL') },\n async ({ id }) => reply(await runProfile(id)),\n );\n\n server.tool(\n 'feed',\n \"The user's own chronological LinkedIn feed: author, when, text, url. MEDIUM cost. Promoted \" +\n 'posts are dropped and counted in `meta.excludedCount`, so fewer items than `limit` usually ' +\n `means ads were filtered, not that the fetch failed. ${READING_CONTRACT} ${NO_RETRY}`,\n { limit: z.number().int().min(1).max(20).optional().describe('default 10') },\n async ({ limit }) => reply(await runFeed(limit ?? 10)),\n );\n\n server.tool(\n 'post',\n \"A LinkedIn post's comment thread. EXPENSIVE — read only finalists. Accepts a bare \" +\n 'urn:li:activity:…, a urn:li:ugcPost:…, or a linkedin.com/feed/update/… URL; no prior lookup ' +\n 'is needed. Feed and search rows already report how many comments a post has, so use that to ' +\n 'decide whether the thread is worth a call. `meta.state` is always \"unknown\" — this is the ' +\n 'first page and pagination is not followed, so NEVER report a comment count as complete. ' +\n `Nested replies are not supported and a comment with replies does not carry them. ${READING_CONTRACT} ${NO_RETRY}`,\n {\n urn: z.string().min(1).describe('activity/ugcPost urn, or a feed-update URL'),\n limit: z.number().int().min(1).max(100).optional().describe('default 20'),\n },\n async ({ urn, limit }) => reply(await runPost(urn, limit ?? 20)),\n );\n\n server.tool(\n 'reactions',\n 'Who reacted to a LinkedIn post, and with which reaction. MEDIUM cost. Often more informative ' +\n 'than the comments for mapping who is paying attention to a topic. Same input forms as ' +\n '`post`. `meta.state` is always \"unknown\" — first page only, so do not report a total. ' +\n `${READING_CONTRACT} ${NO_RETRY}`,\n {\n urn: z.string().min(1).describe('activity/ugcPost urn, or a feed-update URL'),\n limit: z.number().int().min(1).max(100).optional().describe('default 20'),\n },\n async ({ urn, limit }) => reply(await runReactions(urn, limit ?? 20)),\n );\n\n server.tool(\n 'local',\n 'Search the LOCAL cache. Free — no network call, no budget spent. PREFER THIS before any live ' +\n 'command: if the answer is already cached, there is no reason to spend a request on it. The ' +\n 'cache only fills when the user runs a live read with --retain, so an empty result here means ' +\n 'nothing has been retained yet — NOT that LinkedIn has nothing. Check `meta.cachedTotal`.',\n {\n query: z.string().optional().describe('substring match; omit to list everything'),\n source: z.string().optional().describe('comma-separated: connections,my-posts,third-party'),\n since: z.string().optional().describe('YYYY-MM-DD'),\n limit: z.number().int().min(1).max(100).optional().describe('default 25'),\n },\n async ({ query, source, since, limit }) => reply(runLocal(query, source, since, limit ?? 25)),\n );\n\n for (const source of ['connections', 'my-posts'] as const) {\n server.tool(\n source.replace('-', '_'),\n `The user's own ${source === 'connections' ? 'connections' : 'authored posts'}, read from the ` +\n 'LOCAL cache. Free — no network call, no budget spent. An empty result means the cache has ' +\n `not been filled, NOT that the user has none: tell them to run \\`lnrelay sync ${source}\\` ` +\n 'themselves (it is CLI-only). Check `meta.cachedTotal` to tell the two apart.',\n {\n query: z.string().optional().describe('substring match; omit to list everything'),\n limit: z.number().int().min(1).max(100).optional().describe('default 25'),\n },\n async ({ query, limit }) => reply(runSourceRead(source, query, limit ?? 25)),\n );\n }\n\n server.tool(\n 'cache_status',\n 'What is cached per source, with sync checkpoints and the retention policy. Free, no network. ' +\n 'Third-party records expire 30 days after capture — the body goes, an identity stub stays, so ' +\n 'a re-fetch is a visible choice rather than a silent budget charge.',\n {},\n async () => reply(runCacheStatus()),\n );\n\n return server;\n}\n\nconst entry = shouldRunAsEntry(process.argv[1], import.meta.url, import.meta.main, [\n 'linkedin-relay-mcp',\n 'lnrelay',\n]);\n\nif (entry.run) {\n const server = buildServer();\n await server.connect(new StdioServerTransport());\n}\n","// ─── The local store ──────────────────────────────────────────────────────────\n//\n// SQLite (`bun:sqlite`, WAL) behind the same narrow load/save/query interface\n// the family's JSON store exposes. The family similarity that matters is the\n// interface, not the file format.\n//\n// SQLite was chosen for one specific reason: it makes \"corrupt\" a detectable,\n// per-source, quarantinable state. In a single JSON blob, corruption is\n// all-or-nothing and tells you nothing about which records survived — and on\n// this platform an empty-looking cache is what triggers a full re-sync against\n// the most hostile host in the research. TTL expiry as a transactional delete\n// rather than a whole-file rewrite is the second reason.\n//\n// Retention is enforced on the READ path, not by a schedule. There is no cron\n// to forget and no purge command to remember: the only code that can observe\n// expired third-party data is the code that deletes it first.\n\nimport { Database } from 'bun:sqlite';\nimport { mkdirSync, renameSync } from 'node:fs';\nimport { cacheDir, cachePath } from './store.ts';\n\nconst DB_FILE = 'cache.db';\n\n/** Third-party rows expire; owner rows do not. */\nexport const THIRD_PARTY_TTL_MS = 30 * 86_400_000;\n\nexport type Source = 'connections' | 'my-posts' | 'third-party';\n\nexport interface Record_ {\n urn: string;\n source: Source;\n /** Shaped JSON. Null once expired — the identity stub survives, the body does not. */\n body: string | null;\n text: string;\n firstSeenAt: number;\n updatedAt: number;\n expiresAt: number | null;\n}\n\n/**\n * Strip diacritics and lowercase, for matching only.\n *\n * SQLite's LIKE is not accent-insensitive, so `local \"kovary\"` found nothing\n * while \"kőváry\" found the record — the user types what is on their keyboard,\n * not what LinkedIn stored. Found by a real search on a Hungarian name.\n *\n * The folded form is stored ALONGSIDE the original, never instead of it: the\n * display value keeps its accents.\n */\nexport function fold(value: string): string {\n return value\n .normalize('NFD')\n .replace(/\\p{Diacritic}/gu, '')\n .toLowerCase();\n}\n\nconst TABLES = [\n `CREATE TABLE IF NOT EXISTS records (\n urn TEXT NOT NULL,\n source TEXT NOT NULL,\n body TEXT,\n text TEXT NOT NULL DEFAULT '',\n textFold TEXT NOT NULL DEFAULT '',\n firstSeenAt INTEGER NOT NULL,\n updatedAt INTEGER NOT NULL,\n expiresAt INTEGER,\n PRIMARY KEY (urn, source)\n )`,\n `CREATE TABLE IF NOT EXISTS checkpoints (\n source TEXT PRIMARY KEY,\n lastSuccessfulAt INTEGER NOT NULL,\n newestCreatedAt INTEGER,\n headIds TEXT NOT NULL DEFAULT '[]',\n state TEXT NOT NULL DEFAULT 'ok'\n )`,\n];\n\n// Indexes are created AFTER migrations, because an index may reference a column\n// a migration is about to add. Creating them alongside the tables meant an\n// existing store — where CREATE TABLE IF NOT EXISTS is a no-op — tried to index\n// a column it did not have yet, and threw on open.\nconst INDEXES = [\n 'CREATE INDEX IF NOT EXISTS records_source ON records(source)',\n 'CREATE INDEX IF NOT EXISTS records_fold ON records(textFold)',\n 'CREATE INDEX IF NOT EXISTS records_expires ON records(expiresAt)',\n];\n\nexport class CacheCorrupt extends Error {\n constructor(\n message: string,\n readonly quarantinedTo: string,\n ) {\n super(message);\n this.name = 'CacheCorrupt';\n }\n}\n\n/**\n * Open the store. A database that fails its integrity check is QUARANTINED and\n * the error is thrown — never silently replaced with an empty one, because an\n * empty cache is operationally active here: it is precisely what makes `sync`\n * enumerate everything again.\n */\nexport function openDb(now = Date.now()): Database {\n mkdirSync(cacheDir(), { recursive: true });\n const path = cachePath(DB_FILE);\n\n let db: Database;\n try {\n db = new Database(path, { create: true });\n const check = db.query('PRAGMA integrity_check').get() as { integrity_check?: string } | null;\n if (check?.integrity_check !== undefined && check.integrity_check !== 'ok') {\n throw new Error(`integrity_check: ${check.integrity_check}`);\n }\n } catch (e) {\n throw quarantine(path, (e as Error).message, now);\n }\n\n db.run('PRAGMA journal_mode = WAL');\n for (const stmt of TABLES) db.run(stmt);\n migrate(db);\n for (const stmt of INDEXES) db.run(stmt);\n sweepExpired(db, now);\n return db;\n}\n\n/**\n * Additive migrations for stores created before a column existed. Kept\n * idempotent and additive so an older cache upgrades in place rather than\n * being discarded — discarding it would trigger a full re-sync, which is the\n * expensive failure on this platform.\n */\nfunction migrate(db: Database): void {\n const columns = db.query('PRAGMA table_info(records)').all() as { name: string }[];\n if (!columns.some((c) => c.name === 'textFold')) {\n db.run(\"ALTER TABLE records ADD COLUMN textFold TEXT NOT NULL DEFAULT ''\");\n }\n // Backfill any row that predates the column.\n const stale = db\n .query(\"SELECT urn, source, text FROM records WHERE textFold = '' AND text != ''\")\n .all() as {\n urn: string;\n source: string;\n text: string;\n }[];\n if (stale.length > 0) {\n const update = db.query('UPDATE records SET textFold = ? WHERE urn = ? AND source = ?');\n db.transaction(() => {\n for (const r of stale) update.run(fold(r.text), r.urn, r.source);\n })();\n }\n}\n\nfunction quarantine(path: string, reason: string, now: number): CacheCorrupt {\n const stamp = new Date(now).toISOString().replace(/[:.]/g, '-');\n const target = cachePath('quarantine', stamp, DB_FILE);\n try {\n mkdirSync(cachePath('quarantine', stamp), { recursive: true });\n renameSync(path, target);\n } catch {\n // Even if it cannot be moved, the caller must still refuse to proceed.\n }\n return new CacheCorrupt(\n `the local cache was unreadable and has been quarantined: ${reason}`,\n target,\n );\n}\n\n/**\n * Expire third-party bodies. The row survives as an identity stub so a re-fetch\n * is a VISIBLE choice — the budget can say \"14 of these 20 are re-fetches of\n * expired records\" instead of quietly charging for them again.\n */\nexport function sweepExpired(db: Database, now = Date.now()): number {\n const result = db.run(\n \"UPDATE records SET body = NULL, text = '', textFold = '' WHERE expiresAt IS NOT NULL AND expiresAt <= ? AND body IS NOT NULL\",\n [now],\n );\n return result.changes;\n}\n\nexport function upsert(\n db: Database,\n source: Source,\n rows: { urn: string; body: unknown; text: string }[],\n now = Date.now(),\n): { added: number; updated: number } {\n const expiresAt = source === 'third-party' ? now + THIRD_PARTY_TTL_MS : null;\n let added = 0;\n let updated = 0;\n\n const exists = db.query('SELECT 1 FROM records WHERE urn = ? AND source = ?');\n const write = db.query(\n `INSERT INTO records (urn, source, body, text, textFold, firstSeenAt, updatedAt, expiresAt)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(urn, source) DO UPDATE SET\n body = excluded.body, text = excluded.text, textFold = excluded.textFold,\n updatedAt = excluded.updatedAt, expiresAt = excluded.expiresAt`,\n );\n\n db.transaction(() => {\n for (const row of rows) {\n if (exists.get(row.urn, source) === null) added++;\n else updated++;\n write.run(\n row.urn,\n source,\n JSON.stringify(row.body),\n row.text,\n fold(row.text),\n now,\n now,\n expiresAt,\n );\n }\n })();\n\n return { added, updated };\n}\n\nexport function count(db: Database, source?: Source): number {\n const row =\n source === undefined\n ? (db.query('SELECT COUNT(*) AS n FROM records').get() as { n: number })\n : (db.query('SELECT COUNT(*) AS n FROM records WHERE source = ?').get(source) as {\n n: number;\n });\n return row.n;\n}\n\n/** Offline search. Substring match over the flattened text of each record. */\nexport function search(\n db: Database,\n query: string,\n opts: { sources?: Source[]; since?: number; limit?: number } = {},\n): Record_[] {\n const sources = opts.sources ?? ['connections', 'my-posts', 'third-party'];\n const placeholders = sources.map(() => '?').join(',');\n const params: (string | number)[] = [...sources];\n\n let sql = `SELECT * FROM records WHERE source IN (${placeholders}) AND body IS NOT NULL`;\n if (query !== '') {\n // Match on the folded column with a folded query, so \"kovary\" finds\n // \"Kőváry\" and vice versa.\n sql += ' AND textFold LIKE ?';\n params.push(`%${fold(query)}%`);\n }\n if (opts.since !== undefined) {\n sql += ' AND updatedAt >= ?';\n params.push(opts.since);\n }\n sql += ' ORDER BY updatedAt DESC LIMIT ?';\n params.push(opts.limit ?? 25);\n\n return db.query(sql).all(...params) as Record_[];\n}\n\nexport function urnsFor(db: Database, source: Source): Set<string> {\n const rows = db.query('SELECT urn FROM records WHERE source = ?').all(source) as {\n urn: string;\n }[];\n return new Set(rows.map((r) => r.urn));\n}\n\nexport function removeUrns(db: Database, source: Source, urns: string[]): number {\n if (urns.length === 0) return 0;\n const stmt = db.query('DELETE FROM records WHERE source = ? AND urn = ?');\n let removed = 0;\n db.transaction(() => {\n for (const urn of urns) removed += stmt.run(source, urn).changes;\n })();\n return removed;\n}\n\n// ─── Checkpoints ──────────────────────────────────────────────────────────────\n\nexport interface Checkpoint {\n source: string;\n lastSuccessfulAt: number;\n newestCreatedAt: number | null;\n headIds: string[];\n /** `snapshot-partial` where no ordering exists — never a fabricated watermark. */\n state: 'ok' | 'snapshot-partial';\n}\n\nexport function getCheckpoint(db: Database, source: Source): Checkpoint | undefined {\n const row = db.query('SELECT * FROM checkpoints WHERE source = ?').get(source) as\n | (Omit<Checkpoint, 'headIds'> & { headIds: string })\n | null;\n if (row === null) return undefined;\n return { ...row, headIds: JSON.parse(row.headIds) as string[] };\n}\n\nexport function setCheckpoint(db: Database, cp: Checkpoint): void {\n db.run(\n `INSERT INTO checkpoints (source, lastSuccessfulAt, newestCreatedAt, headIds, state)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(source) DO UPDATE SET\n lastSuccessfulAt = excluded.lastSuccessfulAt,\n newestCreatedAt = excluded.newestCreatedAt,\n headIds = excluded.headIds,\n state = excluded.state`,\n [cp.source, cp.lastSuccessfulAt, cp.newestCreatedAt, JSON.stringify(cp.headIds), cp.state],\n );\n}\n\nexport function purge(db: Database, scope: 'all' | 'third-party'): number {\n const result =\n scope === 'all'\n ? db.run('DELETE FROM records')\n : db.run(\"DELETE FROM records WHERE source = 'third-party'\");\n if (scope === 'all') db.run('DELETE FROM checkpoints');\n return result.changes;\n}\n","// ─── Local state store ────────────────────────────────────────────────────────\n//\n// Small, replaceable JSON state (the ledger, the cooldown, credentials\n// metadata) lives here. The research cache proper is SQLite and arrives in\n// Phase 4 — see docs/DESIGN.md §5.\n//\n// The rule that matters, and where we deliberately break with the family:\n//\n// never-throw is NOT never-fail.\n//\n// x-relay's store degrades a corrupt file to an empty object so a read never\n// crashes. That is right on X. Here it composes into a disaster: corrupt file →\n// empty cache → sync sees no prior state → full enumeration against the most\n// hostile platform in the research, triggered by a disk error. So a corrupt\n// file is quarantined and reported loudly. An empty result and a lost result\n// must be distinguishable on disk for exactly the same reason they must be\n// distinguishable in a parse.\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nexport function cacheDir(): string {\n return process.env.LNRELAY_CACHE_DIR ?? join(homedir(), '.lnrelay');\n}\n\nexport function cachePath(...parts: string[]): string {\n return join(cacheDir(), ...parts);\n}\n\nexport type LoadResult<T> =\n | { state: 'ok'; value: T }\n | { state: 'missing' }\n | { state: 'corrupt'; quarantinedTo: string; reason: string };\n\n/**\n * Read a JSON file. Never throws. A file that exists but cannot be parsed is\n * MOVED to `quarantine/` and reported as corrupt — never silently treated as\n * absent, because \"we lost your data\" and \"you have no data\" lead to opposite\n * and non-interchangeable actions.\n */\nexport function loadJson<T>(path: string): LoadResult<T> {\n if (!existsSync(path)) return { state: 'missing' };\n\n let raw: string;\n try {\n raw = readFileSync(path, 'utf-8');\n } catch (e) {\n return quarantine(path, `unreadable: ${(e as Error).message}`);\n }\n\n try {\n return { state: 'ok', value: JSON.parse(raw) as T };\n } catch (e) {\n return quarantine(path, `unparseable JSON: ${(e as Error).message}`);\n }\n}\n\nfunction quarantine(path: string, reason: string): LoadResult<never> {\n const stamp = new Date().toISOString().replace(/[:.]/g, '-');\n const target = cachePath('quarantine', stamp, path.split('/').pop() ?? 'file');\n try {\n mkdirSync(dirname(target), { recursive: true });\n renameSync(path, target);\n } catch {\n // If we cannot even move it, still report corrupt — the caller must refuse\n // to proceed either way.\n }\n return { state: 'corrupt', quarantinedTo: target, reason };\n}\n\n/**\n * Write JSON atomically: a temp file in the same directory, then rename. A\n * torn write leaves the previous good file intact rather than a truncated one.\n */\nexport function saveJson(path: string, value: unknown): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf-8', mode: 0o600 });\n renameSync(tmp, path);\n}\n","// ─── Rest.li 2.0 variables grammar ────────────────────────────────────────────\n//\n// LinkedIn's Voyager GraphQL endpoint does NOT take JSON variables. It takes\n// Rest.li 2.0's own tuple grammar:\n//\n// (key:value,key2:value2) object literal\n// List(a,b,c) array\n// a | b OR-group inside a single filter value\n//\n// nested to arbitrary depth. Example (verified, R3 §2):\n//\n// ?queryId=voyagerSearchDashClusters.<hash>&variables=(start:0,query:(keywords:foo,\n// queryParameters:List((key:resultType,value:List(PEOPLE)))))\n//\n// Every client in the 90-repo corpus string-templates this. That is why adding a\n// filter is a guessing game for them: an unescaped comma or paren in a user's\n// search term silently terminates a tuple early and changes what you asked for\n// without erroring. This module is the pure, tested alternative.\n\n/** A value expressible in the Rest.li variables grammar. */\nexport type RestliValue =\n | string\n | number\n | boolean\n | undefined\n | RestliValue[]\n | { [key: string]: RestliValue };\n\n/**\n * Characters that must be percent-encoded inside a scalar value. Two distinct\n * hazards, both silent:\n *\n * Grammar `( ) , : |` change the shape of the tuple. A keyword containing\n * a comma would split one value into two.\n * URL `& # + space %` corrupt the query string the tuple is spliced\n * into. Searching for \"tom & jerry\" would inject a second query\n * parameter, and LinkedIn would answer a question we never asked\n * — returning 200 with plausible results for the wrong query.\n *\n * `%` is listed first and handled first, so an already-percent-looking value is\n * escaped rather than double-decoded into something else.\n */\nconst ENCODED: Record<string, string> = {\n '%': '%25', // MUST be first — see below\n '(': '%28',\n ')': '%29',\n ',': '%2C',\n ':': '%3A',\n '|': '%7C',\n '&': '%26',\n '#': '%23',\n '+': '%2B',\n ' ': '%20',\n};\n\nconst RESERVED = /[%(),:|&#+ ]/g;\n\nfunction encodeScalar(value: string | number | boolean): string {\n if (typeof value !== 'string') return String(value);\n // A single pass over the string, replacing each reserved character with its\n // escape. Because it is one pass, the `%` introduced by an escape is never\n // itself re-escaped — which is what makes the `%` entry above safe.\n return value.replace(RESERVED, (c) => ENCODED[c] ?? c);\n}\n\nfunction encodeValue(value: RestliValue): string | undefined {\n if (value === undefined) return undefined;\n if (Array.isArray(value)) {\n const members = value.map(encodeValue).filter((m): m is string => m !== undefined);\n return `List(${members.join(',')})`;\n }\n if (typeof value === 'object') return encodeObject(value);\n return encodeScalar(value);\n}\n\nfunction encodeObject(obj: { [key: string]: RestliValue }): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(obj)) {\n const encoded = encodeValue(value);\n // An undefined value is omitted entirely — never emitted as the string\n // \"undefined\", which LinkedIn would treat as a real filter value.\n if (encoded !== undefined) parts.push(`${key}:${encoded}`);\n }\n return `(${parts.join(',')})`;\n}\n\n/** Encode a variables object into the Rest.li 2.0 grammar. */\nexport function encodeVariables(vars: { [key: string]: RestliValue }): string {\n return encodeObject(vars);\n}\n\n// ─── Composite URNs ───────────────────────────────────────────────────────────\n//\n// Voyager URNs are not always `urn:li:type:id`. Tuple forms appear inline:\n//\n// urn:li:fs_updateV2:(urn:li:activity:999,GROUP_FEED,EMPTY,DEFAULT,false)\n// urn:li:fsd_profilePositionGroup:(urn:li:fsd_profile:ABC,urn:li:fsd_company:(1,2))\n//\n// R3 §4 documents the reference implementation extracting the inner URN with\n// `split(\"(\")[1].split(\",\")[0]`. That is correct only until a member is itself a\n// tuple — and nested tuples do occur. A paren-aware split is barely more code\n// and does not have a silent failure mode.\n\nexport interface TupleUrn {\n /** The URN's own namespace, e.g. `fs_updateV2`. */\n namespace: string;\n /** Top-level members, with nested tuples left intact. */\n members: string[];\n}\n\n/**\n * Parse a composite (tuple-form) URN. Returns null when the URN is not\n * composite, or when its parentheses are unbalanced — an unbalanced URN is\n * malformed data, and guessing at its members would invent structure.\n */\nexport function parseTupleUrn(urn: string): TupleUrn | null {\n const open = urn.indexOf(':(');\n if (open === -1 || !urn.endsWith(')')) return null;\n\n const namespace = urn.slice(0, open).split(':').pop();\n if (namespace === undefined || namespace === '') return null;\n\n const body = urn.slice(open + 2, -1);\n const members: string[] = [];\n let depth = 0;\n let current = '';\n\n for (const char of body) {\n if (char === '(') depth++;\n else if (char === ')') depth--;\n\n if (depth < 0) return null; // closed one we never opened\n\n if (char === ',' && depth === 0) {\n members.push(current);\n current = '';\n } else {\n current += char;\n }\n }\n if (depth !== 0) return null; // opened one we never closed\n\n members.push(current);\n return { namespace, members };\n}\n\n/**\n * The identity a composite URN wraps — its first member. A non-composite URN is\n * returned unchanged, so this is safe to call on any URN.\n */\nexport function innerUrn(urn: string): string {\n const parsed = parseTupleUrn(urn);\n const first = parsed?.members[0];\n return first ?? urn;\n}\n\n// ─── Namespace collapse ───────────────────────────────────────────────────────\n//\n// R3 §4: LinkedIn is mid-migration from `fs_*` (legacy) to `fsd_*` (dash), and\n// three profile URN forms coexist in live responses — the reference client\n// literally string-replaces between them. This is the same legacy/hoisted split\n// that cost x-relay real data, and the fix is the same: collapse to one identity\n// so dedupe and cross-referencing are structural rather than best-effort.\n//\n// Only mappings we have direct evidence for are listed. An unknown namespace\n// passes through untouched — inventing a mapping would silently merge two\n// distinct entities, which is worse than leaving them separate.\nconst NAMESPACE_ALIASES: Record<string, string> = {\n fs_miniProfile: 'fsd_profile',\n fs_profile: 'fsd_profile',\n};\n\n/**\n * Canonicalise a URN: unwrap composite forms to their inner identity, then\n * collapse known legacy namespace aliases onto their dash equivalent.\n * Idempotent.\n */\nexport function canonicalUrn(urn: string): string {\n const inner = innerUrn(urn);\n const parts = inner.split(':');\n // urn:li:<namespace>:<id...>\n const namespace = parts[2];\n if (namespace === undefined) return inner;\n\n const alias = NAMESPACE_ALIASES[namespace];\n if (alias === undefined) return inner;\n\n parts[2] = alias;\n return parts.join(':');\n}\n","// ─── Presentation ─────────────────────────────────────────────────────────────\n//\n// Pure shaping of Voyager entities into flat, readable rows. No I/O.\n//\n// LinkedIn wraps essentially every piece of display text in a TextViewModel\n// (`{text, textDirection, attributesV2, $type}`), sometimes twice — a post's\n// commentary is `commentary.text.text`. Raw entities are therefore both huge\n// and unreadable, so commands shape by default and keep the raw node behind\n// `--raw` for when a shape has drifted and you need to see what actually came\n// back.\n//\n// Every shaper is defensive: an unrecognised entity still reports its `$type`\n// rather than returning nothing, because the parser deliberately lets unknown\n// types through and silently blanking them here would undo that.\n\nimport type { Entity } from './engine/parse.ts';\nimport { innerUrn } from './engine/restli.ts';\n\nexport interface Shaped {\n type?: string;\n urn?: string;\n name?: string;\n headline?: string;\n location?: string;\n url?: string;\n text?: string;\n author?: string;\n posted?: string;\n [key: string]: unknown;\n}\n\n/** Pull the string out of a TextViewModel, at either nesting depth. */\nfunction text(value: unknown): string | undefined {\n if (typeof value === 'string') return value.trim() || undefined;\n if (value === null || typeof value !== 'object') return undefined;\n\n const node = value as { text?: unknown };\n if (typeof node.text === 'string') return node.text.trim() || undefined;\n // commentary.text.text — the doubly-wrapped case.\n if (node.text !== null && typeof node.text === 'object') return text(node.text);\n return undefined;\n}\n\nfunction typeOf(node: Entity): string | undefined {\n const t = node.$type ?? (node as { _type?: unknown })._type;\n return typeof t === 'string' ? t : undefined;\n}\n\n/** Drop tracking query strings, which differ per request for identical results. */\nfunction cleanUrl(url: unknown): string | undefined {\n if (typeof url !== 'string' || url === '') return undefined;\n const cut = url.indexOf('?');\n return cut === -1 ? url : url.slice(0, cut);\n}\n\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const key of Object.keys(obj)) {\n if (obj[key] === undefined) delete obj[key];\n }\n return obj;\n}\n\nfunction shapeSearchRow(node: Entity): Shaped {\n const entityUrn = typeof node.entityUrn === 'string' ? node.entityUrn : undefined;\n return defined({\n type: typeOf(node),\n // The entity urn is composite — (profileUrn, SEARCH_SRP, DEFAULT) — and the\n // member identity is its first member.\n urn: entityUrn === undefined ? undefined : innerUrn(entityUrn),\n name: text(node.title),\n headline: text(node.primarySubtitle),\n location: text(node.secondarySubtitle),\n url: cleanUrl(node.navigationUrl),\n });\n}\n\n/**\n * Engagement counts are two references away from the post:\n *\n * UpdateV2 --*socialDetail--> SocialDetail --*totalSocialActivityCounts--> counts\n *\n * The parser drops both intermediate nodes as decorations, which is correct —\n * they are not content — so without the index a post has no like or comment\n * count at all. Engagement is the main ranking signal for research, so it is\n * worth the two hops.\n *\n * The same SocialDetail also carries the post's **ugcPost** URN, which is NOT\n * the activity URN in `updateMetadata` (verified live: activity …8686600193 vs\n * ugcPost …7814144000). Reactions and comments key off the ugcPost form, so\n * this is where that mapping comes from — it cannot be derived.\n */\n/**\n * A post's own urn, from whichever of the two live shapes it is.\n *\n * `com.linkedin.voyager.feed.render.UpdateV2` carries it in `updateMetadata`.\n * Its dash sibling `com.linkedin.voyager.dash.feed.Update` — what `myPosts`\n * returns — has no `updateMetadata` at all, and hides the activity urn in the\n * first member of a composite entityUrn tuple:\n *\n * urn:li:fsd_update:(urn:li:activity:662…,MEMBER_SHARES,DEBUG_REASON,…)\n *\n * Handling only the first shape made every post from `my-posts` arrive with no\n * urn, which left `delete` unable to identify the post it was about to destroy.\n */\nfunction postUrn(node: Entity): string | undefined {\n const meta = node.updateMetadata as { urn?: unknown } | undefined;\n if (typeof meta?.urn === 'string') return meta.urn;\n\n const entityUrn = node.entityUrn;\n if (typeof entityUrn !== 'string') return undefined;\n return /urn:li:(activity|ugcPost|share):\\d+/.exec(entityUrn)?.[0];\n}\n\nfunction shapePost(node: Entity, index?: Map<string, Entity>): Shaped {\n const actor = node.actor as { name?: unknown; subDescription?: unknown } | undefined;\n const urn = postUrn(node);\n\n const social = deref(node, '*socialDetail', index);\n const counts =\n social === undefined ? undefined : deref(social, '*totalSocialActivityCounts', index);\n\n return defined({\n type: typeOf(node),\n urn,\n threadUrn: typeof social?.urn === 'string' ? social.urn : undefined,\n author: text(actor?.name),\n // `text()` already trims; LinkedIn pads these with trailing spaces.\n posted: text(actor?.subDescription),\n text: text(node.commentary),\n likes: numberOf(counts?.numLikes),\n comments: numberOf(counts?.numComments),\n shares: numberOf(counts?.numShares ?? social?.totalShares),\n url: urn === undefined ? undefined : `https://www.linkedin.com/feed/update/${urn}/`,\n });\n}\n\nfunction numberOf(value: unknown): number | undefined {\n return typeof value === 'number' ? value : undefined;\n}\n\n/**\n * Resolve a `*`-prefixed URN reference on a node against the side-table.\n * LinkedIn returns location, current position and education as references, so\n * a profile without its index is mostly pointers.\n */\nfunction deref(\n node: Entity,\n key: string,\n index: Map<string, Entity> | undefined,\n): Entity | undefined {\n if (index === undefined) return undefined;\n const ref = node[key];\n if (typeof ref === 'string') return index.get(ref);\n if (ref === undefined) return undefined;\n if (ref !== null && typeof ref === 'object') {\n for (const [k, v] of Object.entries(ref as Record<string, unknown>)) {\n if (k.startsWith('*') && typeof v === 'string') return index.get(v);\n }\n }\n return undefined;\n}\n\n/**\n * Shape a full profile, resolving the references LinkedIn leaves dangling.\n *\n * Note the honest gap: none of the observed projections returns\n * firstName/lastName/publicIdentifier, so a looked-up profile has no name.\n * The caller supplied the identifier, so this is a real limit rather than a\n * silent one — see src/engine/contracts.ts.\n */\nexport function shapeProfile(node: Entity, index?: Map<string, Entity>): Shaped {\n const base = shapeMember(node);\n const geo = deref(node, 'geoLocation', index);\n const position =\n deref(node, 'profileTopPosition', index) ?? firstOfType(index, 'profile.Position');\n const education =\n deref(node, 'profileTopEducation', index) ?? firstOfType(index, 'profile.Education');\n\n return defined({\n ...base,\n location: text(geo?.defaultLocalizedName) ?? text(geo?.localizedName),\n title: text(position?.title),\n company: text(position?.companyName),\n school: text(education?.schoolName),\n });\n}\n\nfunction firstOfType(index: Map<string, Entity> | undefined, suffix: string): Entity | undefined {\n if (index === undefined) return undefined;\n for (const node of new Set(index.values())) {\n if (String(node.$type ?? '').endsWith(suffix)) return node;\n }\n return undefined;\n}\n\nfunction shapeMember(node: Entity): Shaped {\n const first = text(node.firstName);\n const last = text(node.lastName);\n const publicId = text(node.publicIdentifier) ?? text(node.publicId);\n const name = [first, last].filter(Boolean).join(' ');\n return defined({\n type: typeOf(node),\n urn: typeof node.entityUrn === 'string' ? node.entityUrn : undefined,\n publicId,\n name: name === '' ? undefined : name,\n headline: text(node.headline) ?? text(node.occupation),\n url: publicId === undefined ? undefined : `https://www.linkedin.com/in/${publicId}/`,\n });\n}\n\n/**\n * A comment. The author lives under `commenter` as a lockup (title/subtitle/\n * navigationUrl), and the comment's own like count is another two-hop\n * dereference through its socialDetail — same chain as a post.\n */\nfunction shapeComment(node: Entity, index?: Map<string, Entity>): Shaped {\n const commenter = node.commenter as Entity | undefined;\n const social = deref(node, '*socialDetail', index);\n const counts =\n social === undefined ? undefined : deref(social, '*totalSocialActivityCounts', index);\n\n return defined({\n type: typeOf(node),\n urn: typeof node.urn === 'string' ? node.urn : undefined,\n author: text(commenter?.title),\n headline: text(commenter?.subtitle),\n authorUrl: cleanUrl(commenter?.navigationUrl),\n text: text(node.comment) ?? text(node.commentary),\n likes: numberOf(counts?.numLikes),\n postedAt:\n typeof node.createdAt === 'number' ? new Date(node.createdAt).toISOString() : undefined,\n edited: node.edited === true ? true : undefined,\n url: cleanUrl(node.permalink),\n });\n}\n\n/** A reactor — who reacted, and with which reaction. */\nfunction shapeReaction(node: Entity, index?: Map<string, Entity>): Shaped {\n const lockup = node.reactorLockup as Entity | undefined;\n const actorUrn = typeof node.actorUrn === 'string' ? node.actorUrn : undefined;\n const profile = actorUrn === undefined ? undefined : index?.get(actorUrn);\n\n return defined({\n type: typeOf(node),\n urn: actorUrn,\n name: text(lockup?.title),\n headline: text(lockup?.subtitle) ?? text(profile?.headline),\n reaction: typeof node.reactionType === 'string' ? node.reactionType : undefined,\n url: cleanUrl(lockup?.navigationUrl),\n });\n}\n\n/** Shape one entity into a flat row, dispatching on its type. */\nexport function shapeEntity(node: Entity, index?: Map<string, Entity>): Shaped {\n try {\n const t = (typeOf(node) ?? '').toLowerCase();\n if (t.includes('entityresultviewmodel')) return shapeSearchRow(node);\n // Order matters: Comment and Reaction are checked before the broader\n // 'update' and 'profile' fragments, which would otherwise swallow them.\n if (t.endsWith('social.comment')) return shapeComment(node, index);\n if (t.endsWith('social.reaction')) return shapeReaction(node, index);\n if (t.includes('update')) return shapePost(node, index);\n if (t.includes('profile')) return shapeMember(node);\n\n // Unrecognised: report the type and make a best effort, so a new shape\n // shows up as thin data rather than as nothing.\n return defined({\n type: typeOf(node),\n urn: typeof node.entityUrn === 'string' ? node.entityUrn : undefined,\n name: text(node.title) ?? text(node.name),\n text: text(node.commentary) ?? text(node.text),\n });\n } catch {\n return defined({ type: typeOf(node) });\n }\n}\n\nexport function shapeAll(items: Entity[], index?: Map<string, Entity>): Shaped[] {\n return items.map((node) => shapeEntity(node, index));\n}\n\n// ─── Output modes ─────────────────────────────────────────────────────────────\n//\n// `--fields` and `--compact` were advertised in the command registry long\n// before they existed — a documented promise the tool did not keep. They exist\n// now, and tests/skill.test.ts asserts that every flag a usage string\n// advertises is actually parsed, so the same drift cannot recur silently.\n//\n// Both are for the same problem: a shaped row is still ~8 keys of JSON, and an\n// agent ranking 25 search results does not need all of them in its context.\n\n/**\n * Keep only the named keys, in the order named. A key no row carries is\n * omitted rather than emitted as `undefined` — a field the user misspelled\n * should not become a column of nulls that looks like missing data.\n */\nexport function project<T extends Record<string, unknown>>(\n rows: T[],\n spec: string,\n): Record<string, unknown>[] {\n const keys = spec\n .split(',')\n .map((k) => k.trim())\n .filter((k) => k !== '');\n if (keys.length === 0) return rows;\n\n return rows.map((row) => {\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n if (row[key] !== undefined) out[key] = row[key];\n }\n return out;\n });\n}\n\n/** Fields to lead with, in preference order — most identifying first. */\nconst LEAD = ['name', 'author', 'title'];\nconst DETAIL = ['headline', 'text', 'location', 'company', 'posted', 'reaction'];\n\n/**\n * One flat line per row. Reduces a page of search results from kilobytes of\n * JSON to something scannable, without losing what a ranking decision needs.\n */\nexport function compactRows(rows: Record<string, unknown>[]): string[] {\n return rows.map((row) => {\n const parts: string[] = [];\n\n for (const key of LEAD) {\n const v = row[key];\n if (typeof v === 'string' && v !== '') {\n parts.push(v);\n break;\n }\n }\n for (const key of DETAIL) {\n const v = row[key];\n if (typeof v === 'string' && v !== '') parts.push(v);\n }\n\n const counts = ['likes', 'comments']\n .map((k) => (typeof row[k] === 'number' ? `${row[k]} ${k}` : undefined))\n .filter((v): v is string => v !== undefined);\n parts.push(...counts);\n\n // A row with nothing human-readable still has to identify itself.\n if (parts.length === 0) {\n const urn = row.urn ?? row.type;\n if (typeof urn === 'string') parts.push(urn);\n }\n\n // One row, one line — a newline in a post body would break the format.\n return parts.join(' · ').replace(/\\s*\\n\\s*/g, ' ');\n });\n}\n","import type { Envelope, Err, Ok } from './types.ts';\n\nexport function ok<T>(command: string, data: T): Ok<T> {\n return { ok: true, command, data };\n}\n\nexport function err(\n command: string,\n code: string,\n message: string,\n hint?: string,\n status?: number,\n retryAfterMs?: number,\n): Err {\n const error: Err['error'] = { code, message };\n if (hint !== undefined) error.hint = hint;\n if (status !== undefined) error.status = status;\n if (retryAfterMs !== undefined) error.retryAfterMs = retryAfterMs;\n return { ok: false, command, error };\n}\n\nexport function toJson(envelope: unknown): string {\n return JSON.stringify(envelope, null, 2);\n}\n\n// ─── Error taxonomy ───────────────────────────────────────────────────────────\n\nexport const ERROR_CODES = [\n // Raised before any network call is made.\n 'INVALID_INPUT',\n 'UNKNOWN_COMMAND',\n 'CONFIRMATION_REQUIRED',\n 'BUDGET_EXHAUSTED',\n 'COOLDOWN_ACTIVE',\n 'CACHE_CORRUPT',\n 'NOT_IMPLEMENTED',\n // Raised from a response.\n 'AUTH_FAILED',\n 'RATE_LIMITED',\n 'REQUEST_DENIED', // HTTP 999 — LinkedIn's non-standard bot block\n 'CHALLENGE_DETECTED',\n 'SCHEMA_DRIFT',\n 'NOT_FOUND',\n 'FETCH_FAILED',\n 'FETCH_TIMEOUT',\n] as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n/**\n * Whether a failure may be retried automatically.\n *\n * Almost everything is `false`, and that is the point. On LinkedIn a 429 is the\n * warning shot on a documented escalation ladder — retrying into it is the\n * mechanism by which a throttle becomes a restriction. A `retryAfterMs` is\n * information to print for a human, never permission for the process to try\n * again. The single exception is a timeout where no response was received at\n * all, which carries no signal about our standing with LinkedIn.\n *\n * This is a deliberate break with x-relay, which retries 429 three times. That\n * is correct on a platform where the worst case is a temporary block.\n */\nexport function isRetryable(code: ErrorCode | string): boolean {\n return code === 'FETCH_TIMEOUT';\n}\n\n/** 0 success · 1 command error · 2 unknown command. */\nexport function exitCodeFor(envelope: Envelope): number {\n if (envelope.ok) return 0;\n return envelope.error.code === 'UNKNOWN_COMMAND' ? 2 : 1;\n}\n","// Cache-backed commands. These make no network call at all — after a research\n// session, repeat lookups are free, which is the whole point of keeping a local\n// store on a platform where every request is rationed.\n\nimport {\n CacheCorrupt,\n count,\n getCheckpoint,\n openDb,\n purge as purgeDb,\n type Source,\n search as searchDb,\n upsert,\n} from '../cache/db.ts';\nimport { compactRows, project, type Shaped } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\n\nconst SOURCES: Source[] = ['connections', 'my-posts', 'third-party'];\n\n/** Turn a CacheCorrupt into an envelope; rethrow anything else. */\nfunction corruptEnvelope(command: string, e: unknown): Envelope {\n if (e instanceof CacheCorrupt) {\n return err(\n command,\n 'CACHE_CORRUPT',\n e.message,\n `Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as an empty one — that would ` +\n 'trigger a full re-sync against LinkedIn. Inspect it, then re-run.',\n );\n }\n throw e;\n}\n\nexport interface LocalOpts {\n compact?: boolean;\n fields?: string;\n}\n\n/** The cache path honours the same output flags as the live path. */\nfunction render(rows: Record<string, unknown>[], opts: LocalOpts): unknown[] {\n if (opts.compact === true) return compactRows(rows);\n if (opts.fields !== undefined && opts.fields !== '') return project(rows, opts.fields);\n return rows;\n}\n\nexport function runLocal(\n query: string | undefined,\n sources: string | undefined,\n since: string | undefined,\n limit: number,\n opts: LocalOpts = {},\n): Envelope {\n const requested = sources?.split(',').map((s) => s.trim()) ?? SOURCES;\n const invalid = requested.filter((s) => !SOURCES.includes(s as Source));\n if (invalid.length > 0) {\n return err(\n 'local',\n 'INVALID_INPUT',\n `unknown source(s): ${invalid.join(', ')}`,\n `valid sources: ${SOURCES.join(', ')}`,\n );\n }\n\n let sinceMs: number | undefined;\n if (since !== undefined) {\n const parsed = Date.parse(since);\n if (Number.isNaN(parsed)) {\n return err('local', 'INVALID_INPUT', `could not parse --since '${since}'`, 'use YYYY-MM-DD');\n }\n sinceMs = parsed;\n }\n\n try {\n const db = openDb();\n const rows = searchDb(db, query ?? '', {\n sources: requested as Source[],\n ...(sinceMs === undefined ? {} : { since: sinceMs }),\n limit,\n });\n const total = count(db);\n\n const shaped = rows.map((r) => ({\n ...(JSON.parse(r.body ?? '{}') as Shaped),\n source: r.source,\n cachedAt: new Date(r.updatedAt).toISOString(),\n }));\n\n return ok('local', {\n items: render(shaped, opts),\n meta: {\n returnedCount: rows.length,\n cachedTotal: total,\n sources: requested,\n // An empty cache is not an empty LinkedIn — say which one this is.\n note:\n total === 0\n ? 'The local cache is empty. Run a read command with --retain, or sync a source, before searching offline.'\n : undefined,\n },\n });\n } catch (e) {\n return corruptEnvelope('local', e);\n }\n}\n\n/**\n * `connections` and `my-posts` are the same offline read as `local`, with the\n * source pinned. They exist as separate commands because that is how a user\n * thinks about their own data — `--sync` fills them, they read from cache.\n */\nexport function runSourceRead(\n command: 'connections' | 'my-posts',\n query: string | undefined,\n limit: number,\n opts: LocalOpts = {},\n): Envelope {\n const result = runLocal(query, command, undefined, limit, opts);\n if (!result.ok) return result;\n const data = result.data as Record<string, unknown>;\n const meta = data.meta as Record<string, unknown>;\n if ((meta.cachedTotal as number) === 0 || (meta.returnedCount as number) === 0) {\n meta.note = `Nothing cached for '${command}'. Run \\`lnrelay sync ${command}\\` first — this command reads the local cache and makes no network call.`;\n }\n return ok(command, data);\n}\n\nexport function runPurge(scope: string | undefined, confirmed: boolean): Envelope {\n const target = scope === 'all' ? 'all' : 'third-party';\n\n if (!confirmed) {\n try {\n const db = openDb();\n return err(\n 'purge',\n 'CONFIRMATION_REQUIRED',\n `would delete ${target === 'all' ? count(db) : count(db, 'third-party')} records (${target})`,\n 'Re-run with --confirm. This only touches local files; it never contacts LinkedIn.',\n );\n } catch (e) {\n return corruptEnvelope('purge', e);\n }\n }\n\n try {\n const db = openDb();\n const removed = purgeDb(db, target);\n return ok('purge', { scope: target, removed, remaining: count(db) });\n } catch (e) {\n return corruptEnvelope('purge', e);\n }\n}\n\nexport function runCacheStatus(): Envelope {\n try {\n const db = openDb();\n return ok('cache-status', {\n total: count(db),\n bySource: Object.fromEntries(SOURCES.map((s) => [s, count(db, s)])),\n checkpoints: Object.fromEntries(SOURCES.map((s) => [s, getCheckpoint(db, s) ?? null])),\n retention:\n 'Third-party records expire 30 days after capture; the body is deleted and an identity ' +\n 'stub remains so a re-fetch is a visible choice. Owner data never expires.',\n });\n } catch (e) {\n return corruptEnvelope('cache-status', e);\n }\n}\n\n/**\n * Retain shaped rows from a live read. Opt-in (`--retain`) rather than\n * automatic: caching every profile you glance at recreates a personal data\n * lake, which is exactly the shape the risk research warns against.\n */\nexport type RetainResult = { added: number; updated: number } | { skipped: string };\n\nexport function retain(source: Source, items: Shaped[]): RetainResult {\n const rows = items\n .filter((i) => typeof i.urn === 'string' && i.urn !== '')\n .map((i) => ({\n urn: i.urn as string,\n body: i,\n text: [i.name, i.headline, i.location, i.text, i.author, i.company, i.title]\n .filter((v) => typeof v === 'string')\n .join(' '),\n }));\n if (rows.length === 0) return { skipped: 'no items carried a urn to key on' };\n\n try {\n return upsert(openDb(), source, rows);\n } catch (e) {\n // Retention never fails the read the user actually asked for — but it says\n // WHY it did nothing. Returning a silent null here cost real debugging time\n // once already.\n return { skipped: (e as Error).message };\n }\n}\n","// Progress reporting for long-running / multi-step commands.\n//\n// The hard invariant: stdout carries ONLY the final JSON envelope. Progress is\n// human-facing chatter, so it goes to STDERR (never stdout) and is silenced by\n// --quiet. The write sink is injectable purely so tests can capture it without\n// spying on process.stderr.\n\nexport type ProgressReporter = (msg: string) => void;\n\n/**\n * Build a progress reporter. When `quiet` is true it drops every message;\n * otherwise it writes `msg + '\\n'` to stderr (or the injected `write` sink).\n */\nexport function progressReporter(\n quiet: boolean,\n write: (s: string) => void = (s) => {\n process.stderr.write(s);\n },\n): ProgressReporter {\n return (msg: string) => {\n if (!quiet) write(`${msg}\\n`);\n };\n}\n","// ─── Spend accounting and the circuit breaker ─────────────────────────────────\n//\n// Two structural safety mechanisms live here, both pure (a clock is always\n// injected, never read):\n//\n// 1. Permits. `client` cannot be called without a `Permit`, and `spend()` is\n// the only thing that can make one. \"Issue a network call without\n// accounting for it\" is therefore a compile error rather than a\n// code-review norm. Redirects, pagination continuations and contract\n// discovery all consume permits too — otherwise the traffic easiest to\n// forget is exactly the traffic that escapes accounting.\n//\n// 2. The cooldown. A FILE, not process state. A CLI is a swarm of\n// short-lived processes, so an in-memory breaker protects nothing: the\n// next invocation would start clean and hammer straight back into the\n// throttle that opened it.\n//\n// About the numbers below: the field research swept 364 posts looking for\n// corroborated rate ceilings and found essentially none — one secondhand vendor\n// figure. So every cap is labelled with where it actually came from, and\n// `lnrelay budget` prints that label. None of them is `measured`, because we\n// have measured nothing. They are starting knobs, not LinkedIn facts.\n\nimport type { CapProvenance } from '../types.ts';\n\nconst HOUR = 3_600_000;\nconst DAY = 86_400_000;\n\nexport type SpendClass = 'profile' | 'search' | 'page' | 'write' | 'global';\n\nexport interface Cap {\n perDay: number;\n provenance: CapProvenance;\n note: string;\n}\n\nexport const CAPS: Record<SpendClass, Cap> = {\n profile: {\n perDay: 30,\n provenance: 'vendor-lore',\n note: \"transplanted from jjuanrivvera/linkedin-cli's job-detail cap\",\n },\n search: { perDay: 25, provenance: 'guessed', note: 'no corroborated figure exists' },\n page: { perDay: 60, provenance: 'guessed', note: 'thread/feed pagination' },\n write: {\n perDay: 10,\n provenance: 'guessed',\n note: 'deliberately below the weakly-reported ~20/day connection lore',\n },\n global: { perDay: 250, provenance: 'guessed', note: 'all classes combined' },\n};\n\n/** Minimum gap between any two calls, before jitter. */\nexport const MIN_GAP_MS = 3_000;\n\n// ─── Permits ──────────────────────────────────────────────────────────────────\n\n/**\n * Proof that a call was accounted for. The brand is unexported, so `spend()` is\n * the only thing in the program that can produce one.\n */\nexport interface Permit {\n readonly __brand: unique symbol;\n class: SpendClass;\n issuedAt: number;\n}\n\nexport interface Ledger {\n /** Epoch-ms timestamps of each spend, keyed by class. */\n spends: Record<string, number[]>;\n}\n\nexport function emptyLedger(): Ledger {\n return { spends: {} };\n}\n\nexport interface BudgetError {\n code: 'BUDGET_EXHAUSTED';\n message: string;\n hint: string;\n}\n\nexport type SpendResult = { permit: Permit; ledger: Ledger } | { error: BudgetError };\n\nfunction within(times: number[] | undefined, now: number, window: number): number[] {\n if (times === undefined) return [];\n return times.filter((t) => now - t < window);\n}\n\nfunction allSpends(ledger: Ledger, now: number): number[] {\n return Object.values(ledger.spends).flatMap((times) => within(times, now, DAY));\n}\n\n/**\n * Account for one intended call. Returns a permit and the updated ledger, or a\n * refusal — and a refusal charges nothing, so a denied call never consumes\n * budget.\n */\nexport function spend(ledger: Ledger, cls: SpendClass, now: number): SpendResult {\n const recent = allSpends(ledger, now);\n\n const last = recent.length > 0 ? Math.max(...recent) : undefined;\n if (last !== undefined && now - last < MIN_GAP_MS) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `minimum gap of ${MIN_GAP_MS}ms between calls not met`,\n hint: 'requests are paced deliberately; wait and retry',\n },\n };\n }\n\n if (recent.length >= CAPS.global.perDay) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `global daily cap of ${CAPS.global.perDay} calls reached`,\n hint: 'resets on a rolling 24h window; see `lnrelay budget`',\n },\n };\n }\n\n const cap = CAPS[cls];\n const forClass = within(ledger.spends[cls], now, DAY);\n if (forClass.length >= cap.perDay) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `daily cap of ${cap.perDay} reached for '${cls}'`,\n hint: `cap provenance: ${cap.provenance} (${cap.note}). See \\`lnrelay budget\\`.`,\n },\n };\n }\n\n return {\n permit: { class: cls, issuedAt: now } as Permit,\n ledger: { spends: { ...ledger.spends, [cls]: [...forClass, now] } },\n };\n}\n\nexport interface BudgetSummary {\n class: SpendClass;\n spentInWindow: number;\n cap: number;\n remaining: number;\n capProvenance: CapProvenance;\n warning?: string;\n}\n\nexport function summarise(ledger: Ledger, cls: SpendClass, now: number): BudgetSummary {\n const cap = CAPS[cls];\n const spent =\n cls === 'global' ? allSpends(ledger, now).length : within(ledger.spends[cls], now, DAY).length;\n const remaining = Math.max(0, cap.perDay - spent);\n\n const summary: BudgetSummary = {\n class: cls,\n spentInWindow: spent,\n cap: cap.perDay,\n remaining,\n capProvenance: cap.provenance,\n };\n if (remaining / cap.perDay < 0.25) {\n summary.warning = `only ${remaining} of ${cap.perDay} '${cls}' calls left in this 24h window — consider stopping`;\n }\n return summary;\n}\n\n// ─── The circuit breaker ──────────────────────────────────────────────────────\n\nexport type CooldownReason = 'RATE_LIMITED' | 'REQUEST_DENIED' | 'CHALLENGE_DETECTED';\n\nexport interface Cooldown {\n reason: CooldownReason;\n since: number;\n /** Epoch-ms when it lifts, or null for indefinite. */\n until: number | null;\n clearRequires: 'time' | 'human';\n}\n\n/**\n * Open a cooldown. The durations escalate with how bad the signal is: a 429 is\n * a throttle, a 999 is a network-layer bot block that lifts only as traffic\n * normalises, and a challenge means LinkedIn wants to see a human — so only a\n * human can clear it, via `lnrelay budget --reset-cooldown --confirm`.\n */\nexport function openCooldown(reason: CooldownReason, now: number): Cooldown {\n if (reason === 'CHALLENGE_DETECTED') {\n return { reason, since: now, until: null, clearRequires: 'human' };\n }\n const duration = reason === 'REQUEST_DENIED' ? 6 * HOUR : HOUR;\n return { reason, since: now, until: now + duration, clearRequires: 'time' };\n}\n\nexport function activeCooldown(cooldown: Cooldown | null, now: number): boolean {\n if (cooldown === null) return false;\n if (cooldown.until === null) return true;\n return now < cooldown.until;\n}\n","// ─── Session and headers ──────────────────────────────────────────────────────\n//\n// Verified live on 2026-08-01: the auth surface is exactly two cookies. `li_at`\n// is the session; `JSESSIONID` exists pre-login too, so its presence alone\n// means nothing. The `csrf-token` header is JSESSIONID with quotes stripped —\n// a derivation, not a second secret.\n//\n// Everything the research listed as a \"cargo-cult candidate\" — x-li-track,\n// x-li-page-instance, x-li-deviceId, li_rm, bcookie, bscookie — was confirmed\n// unnecessary. We do not send them. An unexplained header is as likely to be a\n// fingerprint mismatch as a fix.\n//\n// The User-Agent is stored with the session rather than hardcoded, because a\n// stale UA measurably raises the challenge rate; hardcoding is exactly how the\n// reference client ended up shipping a Chrome 83 string into 2026.\n\nexport interface Session {\n liAt: string;\n jsessionId: string;\n userAgent: string;\n /** ISO date the cookies were minted, so `doctor` can flag staleness. */\n capturedAt: string;\n /** The owner this session is sealed to. A mismatch opens the circuit. */\n ownerUrn?: string;\n}\n\nexport function csrfToken(jsessionId: string): string {\n return jsessionId.replace(/\"/g, '');\n}\n\n/** The complete, minimal header set for an authenticated Voyager call. */\nexport function buildHeaders(session: Session): Record<string, string> {\n return {\n cookie: `li_at=${session.liAt}; JSESSIONID=${session.jsessionId}`,\n 'csrf-token': csrfToken(session.jsessionId),\n 'x-restli-protocol-version': '2.0.0',\n accept: 'application/vnd.linkedin.normalized+json+2.1',\n 'x-li-lang': 'en_US',\n 'user-agent': session.userAgent,\n };\n}\n\nexport interface SessionCheck {\n ok: boolean;\n detail: string;\n}\n\n/**\n * Validate a session's SHAPE without touching the network, and without ever\n * revealing a credential value — lengths only, so `doctor` output is safe to\n * paste into a bug report.\n */\nexport function checkSession(session: Partial<Session> | null): SessionCheck {\n if (session === null || session.liAt === undefined || session.liAt === '') {\n return { ok: false, detail: 'no li_at — run `lnrelay login`' };\n }\n if (session.jsessionId === undefined || session.jsessionId === '') {\n return { ok: false, detail: 'no JSESSIONID — run `lnrelay login`' };\n }\n if (session.userAgent === undefined || session.userAgent === '') {\n return { ok: false, detail: 'no user-agent recorded with the session' };\n }\n const age = sessionAgeDays(session.capturedAt);\n const staleness =\n age !== undefined && age > 90 ? `; UA is ${age} days old, consider re-login` : '';\n return {\n ok: true,\n detail: `li_at present (len ${session.liAt.length}); JSESSIONID present (len ${session.jsessionId.length})${staleness}`,\n };\n}\n\nexport function sessionAgeDays(\n capturedAt: string | undefined,\n now = Date.now(),\n): number | undefined {\n if (capturedAt === undefined) return undefined;\n const then = Date.parse(capturedAt);\n if (Number.isNaN(then)) return undefined;\n return Math.floor((now - then) / 86_400_000);\n}\n","// ─── Response classification ──────────────────────────────────────────────────\n//\n// Every response passes through here BEFORE any parsing. That ordering is the\n// point: a parser asked to read a challenge page or a 410 envelope will happily\n// return an empty array, and an empty array is indistinguishable from \"there\n// was nothing\". Classification is what keeps those two apart.\n//\n// Nothing classified here is ever retried automatically. On LinkedIn a 429 is\n// the warning shot on a documented escalation ladder, so a `retry-after` is\n// information to print for a human — never permission for the process to go\n// again. The `retry` field exists so that rule is asserted in tests.\n\nimport type { CooldownReason } from './budget.ts';\n\nexport interface RawResponse {\n status: number;\n body: string;\n headers?: Record<string, string>;\n}\n\nexport interface Classification {\n outcome: 'ok' | 'error';\n /** The unparsed body, kept for surfaces whose response is not JSON. */\n raw?: string;\n code?: string;\n message?: string;\n hint?: string;\n /** Which cooldown to open, if any. */\n cooldown?: CooldownReason;\n retryAfterMs?: number;\n retry: boolean;\n /** Parsed body, when it was JSON and we already did the work. */\n json?: unknown;\n}\n\nconst CHALLENGE_MARKERS = /checkpoint|challenge|captcha|security verification|unusual activity/i;\nconst LOGIN_REDIRECT = /\\/login|\\/uas\\/login|session_redirect/i;\n\nfunction fail(code: string, message: string, extra: Partial<Classification> = {}): Classification {\n return { outcome: 'error', code, message, retry: false, ...extra };\n}\n\nconst CHALLENGE_HINT =\n 'Open LinkedIn in a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`.';\n\n/** Redirects carry two very different meanings; confusing them costs a day. */\nfunction classifyRedirect(location: string): Classification {\n if (CHALLENGE_MARKERS.test(location)) {\n return fail('CHALLENGE_DETECTED', `redirected to a challenge: ${location}`, {\n cooldown: 'CHALLENGE_DETECTED',\n hint: CHALLENGE_HINT,\n });\n }\n if (LOGIN_REDIRECT.test(location)) {\n return fail('AUTH_FAILED', 'redirected to the login page', {\n hint: 'This signature means expired cookies, NOT bot detection. Re-run `lnrelay login`.',\n });\n }\n return fail('FETCH_FAILED', `unexpected redirect to ${location || '(none)'}`);\n}\n\n/**\n * A challenge served with status 200, if this body is one.\n *\n * Split out of classifyBody because it applies to EVERY path: a write must not\n * skip the challenge check just because its body is not a read contract.\n */\nfunction challengeIn(body: string): Classification | null {\n if (!CHALLENGE_MARKERS.test(body.slice(0, 4000))) return null;\n return fail('CHALLENGE_DETECTED', 'a challenge page was returned with status 200', {\n cooldown: 'CHALLENGE_DETECTED',\n hint: CHALLENGE_HINT,\n });\n}\n\n/** A 200 can still be a failure. Everything here inspects the body. */\nfunction classifyBody(body: string): Classification {\n const challenge = challengeIn(body);\n if (challenge !== null) return challenge;\n\n let json: unknown;\n try {\n json = JSON.parse(body);\n } catch {\n return fail('SCHEMA_DRIFT', 'response was 200 but not JSON', {\n hint: 'LinkedIn may have served HTML — inspect the raw body.',\n });\n }\n\n const envelope = json as { data?: Record<string, unknown>; included?: unknown[] };\n\n // An inner status can contradict the HTTP one.\n const innerStatus = (envelope.data as { status?: number } | undefined)?.status;\n if (typeof innerStatus === 'number' && innerStatus >= 400) {\n return fail('SCHEMA_DRIFT', `body carries an inner status ${innerStatus}`, {\n hint: 'The endpoint answered but reported a failure. Re-capture the operation.',\n });\n }\n\n // The 336-analogue: `data` names URNs that `included` does not contain at\n // all. The decoration failed wholesale — this is a failed fetch wearing the\n // costume of an empty result.\n if (referencesUrns(envelope.data) && (envelope.included?.length ?? 0) === 0) {\n return fail('SCHEMA_DRIFT', 'data references entities but included[] is empty', {\n hint: 'Decoration failed wholesale — this is a failed fetch, not an empty result.',\n });\n }\n\n return { outcome: 'ok', retry: false, json };\n}\n\nexport interface ClassifyOpts {\n /**\n * Whether the body is a contract to validate (a read) or a receipt (a write).\n *\n * A read's body must be a Voyager envelope, and a body that is not one means\n * something went wrong even under a 200. A WRITE's body is whatever the\n * surface feels like returning — LinkedIn's SDUI endpoints answer with a\n * React Server Components stream, which is not JSON and never will be.\n *\n * Defaults to true so reads keep their contract and nothing loosens by\n * omission.\n */\n expectJson?: boolean;\n}\n\nexport function classify(res: RawResponse, opts: ClassifyOpts = {}): Classification {\n const headers = res.headers ?? {};\n\n if (res.status >= 300 && res.status < 400) {\n return classifyRedirect(headers.location ?? '');\n }\n\n // ── Hard blocks ────────────────────────────────────────────────────────────\n if (res.status === 999) {\n return fail('REQUEST_DENIED', 'LinkedIn returned HTTP 999 (Request Denied)', {\n cooldown: 'REQUEST_DENIED',\n hint: 'A network-layer bot block that lifts only as traffic normalises. Stop making requests.',\n });\n }\n\n if (res.status === 429) {\n const retryAfter = Number(headers['retry-after']);\n const out = fail('RATE_LIMITED', 'LinkedIn throttled this request', {\n cooldown: 'RATE_LIMITED',\n hint: 'Not retried automatically — a throttle is the warning shot before a restriction.',\n });\n if (Number.isFinite(retryAfter)) out.retryAfterMs = retryAfter * 1000;\n return out;\n }\n\n if (res.status === 401 || res.status === 403) {\n return fail('AUTH_FAILED', `LinkedIn rejected the session (${res.status})`, {\n hint: 'Usually expired cookies. Re-run `lnrelay login`.',\n });\n }\n\n // ── Endpoint drift ─────────────────────────────────────────────────────────\n // 410 is the shape profileView returned on 2026-08-01: the endpoint existed,\n // answered, and told us it is gone.\n if (res.status === 410) {\n return fail('SCHEMA_DRIFT', 'endpoint returned 410 Gone — it no longer exists', {\n hint: 'Re-capture the operation with scripts/observe.ts and update src/engine/contracts.ts.',\n });\n }\n\n if (res.status === 400) {\n const hint = /queryid/i.test(res.body)\n ? 're-capture the queryId with scripts/observe.ts and update src/engine/contracts.ts'\n : 'check the encoded variables against a live capture';\n return fail('SCHEMA_DRIFT', `LinkedIn rejected the request shape (400)`, { hint });\n }\n\n if (res.status === 404) {\n return fail('NOT_FOUND', 'no such resource');\n }\n\n if (res.status < 200 || res.status >= 300) {\n return fail('FETCH_FAILED', `unexpected status ${res.status}`);\n }\n\n // Writes answer 201 Created and 204 No Content with an empty body. Reads\n // never do either, which is how this was missed until the first live share\n // came back 201 and was reported as a failure — after the post had been\n // created. That is the worst direction to be wrong in: a user told their\n // post failed re-runs the command and posts twice.\n //\n // An empty body is therefore a normal write outcome and must not reach\n // classifyBody, whose whole job is detecting a READ that returned nothing\n // when it claimed otherwise.\n if (res.body.trim() === '') return { outcome: 'ok', retry: false, json: null };\n\n // A challenge is served with status 200 and an HTML body on ANY path, so it\n // is checked before the read/write split — a write must not walk past it.\n const challenge = challengeIn(res.body);\n if (challenge !== null) return challenge;\n\n if (opts.expectJson === false) {\n // Parse opportunistically: some writes do answer JSON and the caller can\n // use it, but a body we cannot parse is not an error on this path. The raw\n // text is carried through either way — LinkedIn's SDUI surface answers with\n // an RSC stream that DESCRIBES its available actions, and that description\n // is the most useful thing in the response.\n try {\n return { outcome: 'ok', retry: false, json: JSON.parse(res.body) as unknown, raw: res.body };\n } catch {\n return { outcome: 'ok', retry: false, json: null, raw: res.body };\n }\n }\n\n return classifyBody(res.body);\n}\n\n/** Whether `data` names any URN we would expect `included[]` to resolve. */\nfunction referencesUrns(data: Record<string, unknown> | undefined): boolean {\n if (data === undefined) return false;\n let found = false;\n\n const walk = (node: unknown): void => {\n if (found || node === null || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n for (const [key, value] of Object.entries(node)) {\n // `*`-prefixed keys are Voyager's reference convention.\n if (key.startsWith('*') && Array.isArray(value) && value.length > 0) {\n found = true;\n return;\n }\n if (typeof value === 'string' && value.startsWith('urn:li:')) {\n found = true;\n return;\n }\n walk(value);\n }\n };\n\n walk(data);\n return found;\n}\n","// ─── The request driver ───────────────────────────────────────────────────────\n//\n// The only place in the program that issues a network request, and the only\n// place that spends budget. `fetch`, the clock and the sleeper are all injected\n// so this whole file is testable without touching the network.\n//\n// Order of operations is the safety design, and it is deliberate:\n//\n// 1. cooldown check — refuse before spending anything, in every process\n// 2. permit — no Permit, no call; unaccounted traffic is impossible\n// 3. jittered pace — never two calls back to back\n// 4. fetch\n// 5. classify — before parsing, always\n// 6. open a cooldown — on any throttle/block/challenge signal\n//\n// Nothing here retries. That is the point.\n\nimport { buildHeaders, type Session } from './auth.ts';\nimport type { Ledger, SpendClass } from './budget.ts';\nimport { activeCooldown, type Cooldown, MIN_GAP_MS, openCooldown, spend } from './budget.ts';\nimport { type Classification, classify } from './classify.ts';\n\nexport interface ClientDeps {\n fetch: typeof globalThis.fetch;\n /** Human-facing progress, on stderr. Optional so tests stay silent. */\n progress?: (message: string) => void;\n now: () => number;\n sleep: (ms: number) => Promise<void>;\n /** [0,1). Injected so jitter is deterministic in tests. */\n random: () => number;\n loadLedger: () => Ledger;\n saveLedger: (l: Ledger) => void;\n loadCooldown: () => Cooldown | null;\n saveCooldown: (c: Cooldown | null) => void;\n}\n\nexport interface RequestSpec {\n url: string;\n spendClass: SpendClass;\n operation: string;\n method?: string;\n /** Serialised as JSON when present. Reads carry none and must stay that way. */\n body?: unknown;\n}\n\nexport type ClientResult =\n | { ok: true; json: unknown; classification: Classification }\n | { ok: false; code: string; message: string; hint?: string; retryAfterMs?: number };\n\n/** Upper bound of the jittered gap. Lower bound is MIN_GAP_MS. */\nconst MAX_GAP_MS = 15_000;\n\nexport function createClient(session: Session, deps: ClientDeps) {\n async function request(spec: RequestSpec): Promise<ClientResult> {\n const now = deps.now();\n\n // 1. The breaker, first and in every process. A cooldown lives in a file\n // precisely so a fresh CLI invocation cannot walk straight back into the\n // throttle that opened it.\n const cooldown = deps.loadCooldown();\n if (activeCooldown(cooldown, now)) {\n const until =\n cooldown?.until === null\n ? 'indefinitely'\n : `until ${new Date(cooldown?.until ?? 0).toISOString()}`;\n return {\n ok: false,\n code: 'COOLDOWN_ACTIVE',\n message: `refusing to call LinkedIn: ${cooldown?.reason} cooldown is active ${until}`,\n hint:\n cooldown?.clearRequires === 'human'\n ? 'Log in through a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`.'\n : 'Wait for it to lift, or inspect `lnrelay risk`.',\n };\n }\n\n // 2. Account for the call BEFORE making it. A denied call spends nothing.\n const ledger = deps.loadLedger();\n const result = spend(ledger, spec.spendClass, now);\n if ('error' in result) {\n return {\n ok: false,\n code: result.error.code,\n message: result.error.message,\n hint: result.error.hint,\n };\n }\n deps.saveLedger(result.ledger);\n\n // 3. Pace. Reads are paced as conservatively as writes, because the field\n // evidence shows restrictions triggered by read velocity alone.\n // That wait is 3-15s and silence during it reads as a hang, so say so.\n const gap = MIN_GAP_MS + Math.floor(deps.random() * (MAX_GAP_MS - MIN_GAP_MS));\n deps.progress?.(`${spec.operation}: pacing ${Math.round(gap / 1000)}s before the request…`);\n await deps.sleep(gap);\n deps.progress?.(`${spec.operation}: requesting…`);\n\n // 4-5. Fetch, then classify before anyone parses anything.\n const raw = await fetchRaw(spec, session, deps);\n if (raw === null) {\n return { ok: false, code: 'FETCH_FAILED', message: 'the request could not be completed' };\n }\n // A read's body is a contract; a write's body is a receipt. Validating a\n // write response read-shaped is what made a successful reaction report\n // SCHEMA_DRIFT — and made the user retry a write that had already landed.\n //\n // Keyed on the METHOD, not on whether a body was sent: `delete` sends no\n // body and is still a write.\n const isRead = (spec.method ?? 'GET') === 'GET';\n const classification = classify(raw, { expectJson: isRead });\n\n // 6. A throttle, block or challenge opens the breaker for every process.\n if (classification.cooldown !== undefined) {\n deps.saveCooldown(openCooldown(classification.cooldown, deps.now()));\n }\n\n if (classification.outcome === 'error') {\n const out: ClientResult = {\n ok: false,\n code: classification.code ?? 'FETCH_FAILED',\n message: classification.message ?? 'request failed',\n };\n if (classification.hint !== undefined) out.hint = classification.hint;\n if (classification.retryAfterMs !== undefined) out.retryAfterMs = classification.retryAfterMs;\n return out;\n }\n\n return { ok: true, json: classification.json, classification };\n }\n\n return { request };\n}\n\nasync function fetchRaw(\n spec: RequestSpec,\n session: Session,\n deps: ClientDeps,\n): Promise<{ status: number; body: string; headers: Record<string, string> } | null> {\n // A body is added only when there is one, so the read path keeps sending\n // exactly the six headers that were verified against live traffic.\n const requestHeaders = buildHeaders(session);\n if (spec.body !== undefined) requestHeaders['content-type'] = 'application/json; charset=UTF-8';\n\n try {\n const res = await deps.fetch(spec.url, {\n method: spec.method ?? 'GET',\n headers: requestHeaders,\n ...(spec.body === undefined ? {} : { body: JSON.stringify(spec.body) }),\n // Manual, so a login or checkpoint redirect is classified rather than\n // silently followed into an HTML page that parses as \"no data\".\n redirect: 'manual',\n });\n const headers: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n headers[key.toLowerCase()] = value;\n });\n return { status: res.status, body: await res.text(), headers };\n } catch {\n return null;\n }\n}\n\nexport type Client = ReturnType<typeof createClient>;\n","// ─── Operation contracts ──────────────────────────────────────────────────────\n//\n// Every endpoint we call, as DATA — never inline in request logic. queryIds and\n// decorationIds are pinned to LinkedIn's deployed web-client build and can\n// rotate; keeping them here means a rotation is a data edit, not a code hunt.\n//\n// Each contract carries its provenance and the date it was captured, and\n// `shippableContracts()` admits only `verified` ones. That rule is mechanical\n// rather than a convention someone has to remember:\n//\n// verified returned 200 on this machine, on the date recorded\n// discovered seen in live traffic (scripts/observe.ts) but never exercised\n// inferred from documentation or another client — may be archaeology\n//\n// The cost of getting this wrong is documented: `identity/profiles/{id}/\n// profileView` was the reference client's core profile endpoint, was documented\n// as working in November 2024, and returns 410 Gone today. It is kept below,\n// marked dead, so nobody re-adds it from an old blog post.\n//\n// Refresh with: bun run scripts/observe.ts <path> (see docs/ENGINE-RESEARCH.md)\n\nimport type { OperationContract } from '../types.ts';\n\nconst VOYAGER = 'https://www.linkedin.com/voyager/api';\n\nexport const CONTRACTS: Record<string, OperationContract> = {\n me: {\n name: 'me',\n transport: 'voyager-restli',\n path: `${VOYAGER}/me`,\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n // Three `voyagerIdentityDashProfiles` queryIds were observed on one page —\n // they are different PROJECTIONS of one operation, and picking the wrong one\n // gets you a 200 containing nothing useful:\n //\n // b5c27c04… identity only — entityUrn + versionTag. Looks like success.\n // e9b08094… the real profile: headline, geo, top position, education. ← this\n // da93c92b… 400s with (profileUrn:…); its variables shape is unknown.\n //\n // None of them returns firstName/lastName/publicIdentifier — LinkedIn splits\n // names into a projection we have not identified. Documented rather than\n // faked; the caller already knows who they asked for.\n profile: {\n name: 'profile',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerIdentityDashProfiles.e9b0809465a07db1f02e70a82d455e10',\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n feed: {\n name: 'feed',\n transport: 'voyager-restli',\n path: `${VOYAGER}/feed/updatesV2`,\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n // The November-2024 queryId, still returning 200 in August 2026 — roughly 21\n // months unchanged. Notable because kill criterion #3 assumed queryIds might\n // rotate weekly; on this evidence they are build-pinned but long-lived.\n search: {\n name: 'search',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSearchDashClusters.b0928897b71bd00a5a7291755dcd64f0',\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n reactions: {\n name: 'reactions',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSocialDashReactions.41ebf31a9f4c4a84e35a49d5abc9010b',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // Comments. The variables carry a COMPOSITE socialDetailUrn assembled from the\n // post's own urn, repeated, plus a highlightedReply placeholder:\n //\n // urn:li:fsd_socialDetail:(<postUrn>,<postUrn>,urn:li:highlightedReply:-)\n //\n // Two things were established by probing rather than assumed. Our codec's\n // percent-encoding of that urn's colons and parens is REQUIRED — the literal\n // form returns 400. And an `urn:li:activity:` post urn works directly, so\n // `post` does not need a feed lookup to find the ugcPost form first.\n comments: {\n name: 'comments',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSocialDashComments.afec6d88d7810d45548797a8dac4fb87',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // The member's own posts. Verified 200; returns an empty collection on an\n // account with no posts, which is a true empty rather than a failure.\n // Needs the `fsd_profile` namespace, NOT the `fs_miniProfile` urn `whoami`\n // returns — the legacy form answers 200 with an empty result rather than an\n // error. That was invisible until the account had a post to return, and is\n // why engine.myPosts canonicalises the urn before sending it.\n //\n // KNOWN INCOMPLETE (2026-08-13): with the namespace fixed this returns the\n // owner's posts, but a post created minutes earlier did not appear here, nor\n // in `feed`, over ~1.5 hours. Whether that is an indexing lag or a coverage\n // limit of this projection is UNRESOLVED — do not treat this endpoint as an\n // authoritative \"all my posts\" until it is settled.\n myPosts: {\n name: 'myPosts',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerFeedDashProfileUpdates.20c70fe0314184158516a7ec004c0408',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // Discovered and returns 200, but the projection is useless: 39 KB containing\n // one `guideFetcher` wrapper and no name, tagline, description or headcount.\n // The same trap as the thin profile projection, so it stays unverified and\n // `company` does not ship. The richer path is probably\n // voyagerOrganizationDashViewWrapper with an organizationalPageUrn, which\n // first requires resolving that urn — unfinished work, not a dead end.\n company: {\n name: 'company',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerOrganizationDashCompanies.148b1aebfadd0a455f32806df656c3c1',\n provenance: 'discovered',\n capturedAt: '2026-08-02',\n },\n\n // A job CARDS list, not a job detail. Observed on /jobs/collections/recommended\n // and never exercised; `job` needs a detail endpoint we have not captured.\n jobCards: {\n name: 'jobCards',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerJobsDashJobCards.e5b6b761ede078dabe8ad857aa42c220',\n provenance: 'discovered',\n capturedAt: '2026-08-02',\n },\n};\n\n/**\n * Endpoints known to be DEAD. Listed so a future maintainer reading the\n * November-2024 reference client does not helpfully re-add one.\n */\nexport const RETIRED: Record<string, { path: string; diedBy: string; note: string }> = {\n profileView: {\n path: `${VOYAGER}/identity/profiles/{id}/profileView`,\n diedBy: '2026-08-01',\n note:\n 'Returns 410 Gone inside a well-formed Voyager envelope. Superseded by the `profile` ' +\n 'contract above. Every client that reads profiles through this is broken.',\n },\n};\n\n/** Only `verified` contracts may back a shipped command. */\nexport function shippableContracts(): Record<string, OperationContract> {\n return Object.fromEntries(\n Object.entries(CONTRACTS).filter(([, c]) => c.provenance === 'verified'),\n );\n}\n\nexport function contractFor(name: string): OperationContract | undefined {\n return shippableContracts()[name];\n}\n","// ─── Normalising Voyager's decoration model ───────────────────────────────────\n//\n// LinkedIn returns a graph with a side-table, not a nested document:\n//\n// { data: { \"*elements\": [\"urn:li:activity:100\", …] }, ← thin refs, ORDERED\n// included: [ { entityUrn: \"urn:li:activity:100\", $type: …, … }, … ] } ← unordered\n//\n// So: index `included[]` once into a Map, then walk `data`'s references against\n// it. The reference implementation instead does an O(n·m) substring scan across\n// the two, which is both slow and subtly wrong — we do not re-derive that.\n//\n// Three rules here are load-bearing, and each one exists because its absence\n// caused a real production bug in the sibling project:\n//\n// 1. FILTER BY EXCLUSION. Drop known noise; let everything else through. An\n// accept-list naming the types we know silently dropped every reply in\n// every thread on x-relay, and 34 of 77 posts per feed page — invisible\n// behind ok:true, a live cursor and a plausible count. On a live LinkedIn\n// feed, 39 of 44 included[] nodes are decorations rather than content, so\n// an accept-list here would look reasonable right up until a rename.\n//\n// 2. UNKNOWN IS NOT DROPPED, AND IT IS COUNTED. A $type we have never seen\n// arrives as data AND increments meta.unknownTypes, so drift shows up in\n// the very first response after a LinkedIn deploy rather than whenever\n// someone next thinks to count.\n//\n// 3. UNRESOLVABLE IS NOT ABSENT. A reference in `data` that `included[]`\n// does not contain is a FAILED decoration. It goes to meta.unresolved and\n// makes the result `partial` — never silently shorter.\n\nimport type { FetchState } from '../types.ts';\nimport { canonicalUrn } from './restli.ts';\n\nexport type Entity = Record<string, unknown> & { entityUrn?: string; $type?: unknown };\n\n/**\n * Type fragments that identify chrome rather than content. Matched as\n * case-insensitive substrings of `$type`, because LinkedIn versions its type\n * names (`UpdateV2` → `UpdateV3`) and a fragment survives that.\n *\n * This list is the ONLY thing that removes data. Adding to it is a deliberate\n * act; forgetting to add to it costs some noise in the output, which is the\n * cheap failure. Forgetting to add to an accept-list costs the entire result,\n * silently, which is the expensive one.\n */\nconst DROP_TYPE_FRAGMENTS = [\n 'promoted',\n 'sponsored',\n 'adunit',\n 'peopleyoumayknow',\n 'recommendedentity',\n 'discoveryentity',\n 'discoverymodule',\n 'promptcomponent',\n 'carouselcomponent',\n 'lego',\n // Search-result chrome, observed live alongside real results.\n 'feedbackcard',\n 'lazyloadedactions',\n 'bannercard',\n 'searchsuggestion',\n 'keywordssuggestion',\n 'queryclarification',\n 'knowledgecard',\n 'topicalquestion',\n];\n\n/** Types that are supporting decorations — real, but not the thing asked for. */\nconst DECORATION_FRAGMENTS = [\n 'socialdetail',\n 'socialactivitycounts',\n 'socialpermissions',\n 'saveaction',\n 'updateactions',\n 'hidepostaction',\n 'followinginfo',\n 'miniprofile',\n 'minicompany',\n 'videoplaymetadata',\n 'hidecommentaction',\n 'followingstate',\n 'followaction',\n 'connectaction',\n];\n\nfunction typeOf(node: Entity): string {\n const t = node.$type ?? (node as { _type?: unknown })._type;\n return typeof t === 'string' ? t : '';\n}\n\n/**\n * A promoted feed post carries the SAME `$type` as a real one — the ad marker\n * lives in the actor's subdescription (\"Promoted\", \"Promoted by <brand>\"), not\n * in the type. Found live: an ad reached the output while every type-level\n * filter passed, which is the same lesson as the accept-list in a new costume.\n * Type is not the only place a thing can identify itself.\n */\nfunction isPromotedPost(node: Entity): boolean {\n const actor = node.actor as { subDescription?: { text?: unknown } } | undefined;\n const sub = actor?.subDescription?.text;\n return typeof sub === 'string' && /^promoted\\b/i.test(sub.trim());\n}\n\nfunction isNoise(node: Entity): boolean {\n if (isPromotedPost(node)) return true;\n const t = typeOf(node).toLowerCase();\n if (t === '') return false;\n return DROP_TYPE_FRAGMENTS.some((f) => t.includes(f));\n}\n\nfunction isDecoration(node: Entity): boolean {\n const t = typeOf(node).toLowerCase();\n return DECORATION_FRAGMENTS.some((f) => t.includes(f));\n}\n\n/**\n * Whether we recognise this type as one we have actually seen. Used ONLY to\n * count unknowns for reporting — never to decide whether to keep something.\n */\nconst KNOWN_CONTENT = [\n 'updatev2',\n 'profile',\n 'jobposting',\n 'company',\n 'comment',\n 'reaction',\n 'entityresult',\n];\n\nfunction isKnown(node: Entity): boolean {\n const t = typeOf(node).toLowerCase();\n return KNOWN_CONTENT.some((f) => t.includes(f)) || isDecoration(node) || isNoise(node);\n}\n\n/** Build the `entityUrn → node` index in one pass, canonicalising namespaces. */\nexport function indexIncluded(included: unknown): Map<string, Entity> {\n const index = new Map<string, Entity>();\n if (!Array.isArray(included)) return index;\n\n for (const raw of included) {\n if (raw === null || typeof raw !== 'object') continue;\n const node = raw as Entity;\n const urn = node.entityUrn;\n if (typeof urn !== 'string') continue;\n\n // Store under BOTH the canonical and the literal form: references in `data`\n // may use either side of the fs_*/fsd_* migration.\n const canonical = canonicalUrn(urn);\n index.set(canonical, node);\n if (canonical !== urn) index.set(urn, node);\n }\n return index;\n}\n\nexport interface ResolveResult {\n resolved: Entity[];\n unresolved: string[];\n}\n\n/** Resolve an ordered list of URN references against the index. */\nexport function resolveRefs(refs: unknown, index: Map<string, Entity>): ResolveResult {\n const resolved: Entity[] = [];\n const unresolved: string[] = [];\n if (!Array.isArray(refs)) return { resolved, unresolved };\n\n for (const ref of refs) {\n if (typeof ref !== 'string') continue;\n const node = index.get(ref) ?? index.get(canonicalUrn(ref));\n if (node === undefined) unresolved.push(ref);\n else resolved.push(node);\n }\n return { resolved, unresolved };\n}\n\nexport interface ParseOpts {\n operation: string;\n /** What the platform claims exists, when it tells us. */\n claimedCount?: number;\n contractCapturedAt?: string;\n truncated?: boolean;\n}\n\nexport interface ParseMeta {\n state: FetchState;\n operation: string;\n contractCapturedAt: string;\n rawCandidateCount: number;\n parsedCount: number;\n excludedCount: number;\n unknownCount: number;\n returnedCount: number;\n claimedCount?: number;\n truncated: boolean;\n unresolved?: string[];\n unknownTypes?: { type: string; count: number }[];\n warnings: string[];\n}\n\nexport interface ParseResult {\n items: Entity[];\n meta: ParseMeta;\n}\n\n/**\n * Find the ordered reference list. Voyager marks references with a `*` prefix,\n * but arranges them in two quite different ways, and a parser that knows only\n * one returns an empty result for the other — with `ok:true`.\n *\n * Collection shape data[\"*elements\"] = [urn, urn, …]\n * feed, dashProfiles. One array, already in order.\n *\n * Cluster shape data.data.<op>.elements[].items[].item[\"*entityResult\"] = urn\n * search. One SINGLE string per item, nested three levels\n * down and spread across clusters.\n *\n * Both were captured live on 2026-08-01. Search parsed to zero items until this\n * handled the second shape — found only because the parser was run against a\n * real capture rather than its own fixtures.\n */\nfunction findRefs(data: unknown): unknown[] {\n if (data === null || typeof data !== 'object') return [];\n\n // Pass 1 — the shallowest `*`-prefixed ARRAY wins. Breadth-first, so a\n // top-level \"*elements\" is preferred over anything nested beneath it.\n const queue: unknown[] = [data];\n while (queue.length > 0) {\n const node = queue.shift();\n if (node === null || typeof node !== 'object') continue;\n if (Array.isArray(node)) {\n queue.push(...node);\n continue;\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.startsWith('*') && Array.isArray(value)) return value;\n }\n for (const value of Object.values(node)) {\n if (value !== null && typeof value === 'object') queue.push(value);\n }\n }\n\n // Pass 2 — no reference array anywhere, so collect `*`-prefixed STRINGS in\n // document order. Depth-first and in-order, because the order items appear\n // in the response IS the ranking LinkedIn assigned them.\n const refs: string[] = [];\n const walk = (node: unknown): void => {\n if (node === null || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.startsWith('*') && typeof value === 'string') refs.push(value);\n else walk(value);\n }\n };\n walk(data);\n return refs;\n}\n\n/**\n * A single-entity response (`/me`) carries no reference list at all — just one\n * decorated node in `included[]`. Returns undefined rather than throwing when\n * there is nothing, so callers decide what an absence means.\n */\nexport function parseSingle(payload: unknown): Entity | undefined {\n const envelope = (payload ?? {}) as { included?: unknown };\n const nodes = [...new Set(indexIncluded(envelope.included).values())];\n if (nodes.length === 0) return undefined;\n // Prefer a content node; fall back to the first, since a decoration is still\n // better than nothing when that is all the endpoint returns.\n return nodes.find((n) => !isNoise(n) && !isDecoration(n)) ?? nodes[0];\n}\n\nexport function parseCollection(payload: unknown, opts: ParseOpts): ParseResult {\n const envelope = (payload ?? {}) as { data?: unknown; included?: unknown };\n const index = indexIncluded(envelope.included);\n const refs = findRefs(envelope.data);\n const { resolved, unresolved } = resolveRefs(refs, index);\n\n const items: Entity[] = [];\n const unknownTypes = new Map<string, number>();\n let excludedCount = 0;\n let unknownCount = 0;\n\n for (const node of resolved) {\n // Per-item isolation: one malformed node never takes the page with it.\n try {\n if (isNoise(node) || isDecoration(node)) {\n excludedCount++;\n continue;\n }\n if (!isKnown(node)) {\n // Unknown → KEEP it (rule 2), and count it so the drift is visible.\n const t = typeOf(node);\n unknownTypes.set(t, (unknownTypes.get(t) ?? 0) + 1);\n unknownCount++;\n }\n items.push(node);\n } catch {\n excludedCount++;\n }\n }\n\n const warnings: string[] = [];\n if (unresolved.length > 0) {\n warnings.push(\n `${unresolved.length} referenced entities were not present in included[] — the decoration failed for those, so this record is incomplete rather than short.`,\n );\n }\n if (opts.claimedCount !== undefined && opts.claimedCount > 0 && items.length === 0) {\n warnings.push(\n `LinkedIn claims ${opts.claimedCount} items but returned none — treat this as a FAILED FETCH, not an empty result.`,\n );\n }\n\n const state: FetchState =\n unresolved.length > 0 ? 'partial' : opts.truncated === true ? 'unknown' : 'complete';\n\n const meta: ParseMeta = {\n state,\n operation: opts.operation,\n contractCapturedAt: opts.contractCapturedAt ?? 'unknown',\n // parsedCount counts what we kept; `items` includes the unknowns, which is\n // why unknownCount is reported separately rather than added again here.\n rawCandidateCount: resolved.length,\n parsedCount: items.length - unknownCount,\n excludedCount,\n unknownCount,\n returnedCount: items.length,\n truncated: opts.truncated ?? false,\n warnings,\n };\n if (opts.claimedCount !== undefined) meta.claimedCount = opts.claimedCount;\n if (unresolved.length > 0) meta.unresolved = unresolved;\n if (unknownTypes.size > 0) {\n meta.unknownTypes = [...unknownTypes.entries()].map(([type, count]) => ({ type, count }));\n }\n\n return { items, meta };\n}\n","// The Engine interface and its real construction. This is the seam: everything\n// above it is pure and testable, everything below it talks to LinkedIn.\n\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { progressReporter } from '../progress.ts';\nimport type { Session } from './auth.ts';\nimport { type Cooldown, emptyLedger, type Ledger } from './budget.ts';\nimport { type Client, type ClientDeps, createClient } from './client.ts';\nimport { contractFor } from './contracts.ts';\nimport {\n type Entity,\n indexIncluded,\n type ParseResult,\n parseCollection,\n parseSingle,\n} from './parse.ts';\nimport { canonicalUrn, encodeVariables } from './restli.ts';\n\nexport interface Engine {\n whoami(): Promise<EngineResult<Entity | undefined>>;\n profile(memberId: string): Promise<EngineResult<ProfileResult | undefined>>;\n feed(limit: number): Promise<EngineResult<Collection>>;\n search(kind: SearchKind, query: string, limit: number): Promise<EngineResult<Collection>>;\n post(postUrn: string, limit: number): Promise<EngineResult<Collection>>;\n myPosts(profileUrn: string, limit: number): Promise<EngineResult<Collection>>;\n connections(limit: number): Promise<EngineResult<Collection>>;\n reactions(postUrn: string, limit: number): Promise<EngineResult<Collection>>;\n}\n\nexport type SearchKind = 'people' | 'companies' | 'jobs';\n\n/**\n * A profile plus the side-table it references. LinkedIn returns location,\n * current position and education as URN references into `included[]`, so the\n * caller needs the index to make sense of the profile node.\n */\n/** A parsed collection plus the side-table its entities reference. */\nexport interface Collection {\n parsed: ParseResult;\n index: Map<string, Entity>;\n}\n\nexport interface ProfileResult {\n profile: Entity;\n index: Map<string, Entity>;\n}\n\nexport type EngineResult<T> =\n | { ok: true; value: T }\n | { ok: false; code: string; message: string; hint?: string; retryAfterMs?: number };\n\nconst RESULT_TYPE: Record<SearchKind, string> = {\n people: 'PEOPLE',\n companies: 'COMPANIES',\n jobs: 'JOBS',\n};\n\nfunction missingContract(name: string): EngineResult<never> {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: `no verified contract for '${name}'`,\n hint:\n 'Only endpoints that returned 200 on this machine may back a command. ' +\n 'Capture it with `bun run scripts/observe.ts`, verify it, then mark it verified in src/engine/contracts.ts.',\n };\n}\n\n/**\n * A live client on the real cache files. Exported because writes need a client\n * without needing an Engine — the write surface is not part of the read\n * contract, but it must share the same ledger, cooldown and pacing, and a\n * second construction of those would be a second breaker that agrees with the\n * first only by luck.\n */\nexport function createLiveClient(\n session: Session,\n deps?: Partial<ClientDeps>,\n quiet = false,\n): Client {\n return createClient(session, {\n fetch: globalThis.fetch,\n // stdout stays JSON-only; progress is human chatter and goes to stderr.\n progress: progressReporter(quiet),\n now: () => Date.now(),\n sleep: (ms) => new Promise((r) => setTimeout(r, ms)),\n random: () => Math.random(),\n loadLedger: () => {\n const r = loadJson<Ledger>(cachePath('budget.json'));\n return r.state === 'ok' ? r.value : emptyLedger();\n },\n saveLedger: (l) => saveJson(cachePath('budget.json'), l),\n loadCooldown: () => {\n const r = loadJson<Cooldown | null>(cachePath('cooldown.json'));\n return r.state === 'ok' ? r.value : null;\n },\n saveCooldown: (c) => saveJson(cachePath('cooldown.json'), c),\n ...deps,\n });\n}\n\nexport function createEngine(session: Session, deps?: Partial<ClientDeps>, quiet = false): Engine {\n const client: Client = createLiveClient(session, deps, quiet);\n\n return {\n async whoami() {\n const contract = contractFor('me');\n if (contract === undefined) return missingContract('me');\n\n const res = await client.request({\n url: contract.path,\n spendClass: 'profile',\n operation: 'me',\n });\n if (!res.ok) return res;\n return { ok: true, value: parseSingle(res.json) };\n },\n\n async profile(memberId) {\n const contract = contractFor('profile');\n if (contract === undefined) return missingContract('profile');\n\n const variables = encodeVariables({ memberIdentity: memberId });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'profile', operation: 'profile' });\n if (!res.ok) return res;\n\n const envelope = res.json as { included?: unknown };\n const index = indexIncluded(envelope.included);\n const profile = [...new Set(index.values())].find((n) =>\n String(n.$type ?? '').endsWith('profile.Profile'),\n );\n if (profile === undefined) return { ok: true, value: undefined };\n return { ok: true, value: { profile, index } };\n },\n\n async feed(limit) {\n const contract = contractFor('feed');\n if (contract === undefined) return missingContract('feed');\n\n const url = `${contract.path}?q=chronFeed&count=${limit}&start=0`;\n const res = await client.request({ url, spendClass: 'page', operation: 'feed' });\n if (!res.ok) return res;\n const envelope = res.json as { included?: unknown };\n return {\n ok: true,\n value: {\n parsed: parseCollection(res.json, {\n operation: 'feed',\n contractCapturedAt: contract.capturedAt,\n }),\n index: indexIncluded(envelope.included),\n },\n };\n },\n\n async myPosts(profileUrn, limit) {\n const contract = contractFor('myPosts');\n if (contract === undefined) return missingContract('myPosts');\n\n // `whoami` answers with an `fs_miniProfile` urn; this is a DASH endpoint\n // and wants `fsd_profile`. The legacy form returns 200 with an empty\n // result — no error, no warning — which is why this shipped as\n // \"verified\": the account had no posts when the contract was captured,\n // so empty was indistinguishable from working.\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n start: 0,\n profileUrn: canonicalUrn(profileUrn),\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'myPosts' });\n if (!res.ok) return res;\n\n const envelope = res.json as { included?: unknown };\n return {\n ok: true,\n value: {\n parsed: parseCollection(res.json, {\n operation: 'myPosts',\n contractCapturedAt: contract.capturedAt,\n truncated: true,\n }),\n index: indexIncluded(envelope.included),\n },\n };\n },\n\n /**\n * Connections are a FILTERED PEOPLE SEARCH, not a list endpoint — LinkedIn\n * exposes no change stream for them. That is why the cache stores them as a\n * snapshot and diffs, rather than pretending a watermark exists.\n */\n async connections(limit) {\n const contract = contractFor('search');\n if (contract === undefined) return missingContract('search');\n\n const variables = encodeVariables({\n start: 0,\n origin: 'FACETED_SEARCH',\n query: {\n flagshipSearchIntent: 'SEARCH_SRP',\n queryParameters: [\n { key: 'resultType', value: ['PEOPLE'] },\n { key: 'network', value: ['F'] },\n ],\n includeFiltersInResponse: false,\n },\n });\n const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'search', operation: 'connections' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'connections',\n contractCapturedAt: contract.capturedAt,\n claimedCount: totalResultCount(res.json),\n truncated: true,\n });\n parsed.items = parsed.items.slice(0, limit);\n parsed.meta.returnedCount = parsed.items.length;\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async post(postUrn, limit) {\n const contract = contractFor('comments');\n if (contract === undefined) return missingContract('comments');\n\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n numReplies: 1,\n socialDetailUrn: socialDetailUrn(postUrn),\n sortOrder: 'RELEVANCE',\n start: 0,\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'comments' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'comments',\n contractCapturedAt: contract.capturedAt,\n // A page of many; we follow no cursor yet, so never claim exhaustion.\n truncated: true,\n });\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async reactions(postUrn, limit) {\n const contract = contractFor('reactions');\n if (contract === undefined) return missingContract('reactions');\n\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n start: 0,\n threadUrn: postUrn,\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'reactions' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'reactions',\n contractCapturedAt: contract.capturedAt,\n truncated: true,\n });\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async search(kind, query, limit) {\n const contract = contractFor('search');\n if (contract === undefined) return missingContract('search');\n\n const variables = encodeVariables({\n start: 0,\n origin: 'GLOBAL_SEARCH_HEADER',\n query: {\n keywords: query,\n flagshipSearchIntent: 'SEARCH_SRP',\n queryParameters: [{ key: 'resultType', value: [RESULT_TYPE[kind]] }],\n includeFiltersInResponse: false,\n },\n });\n const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'search', operation: 'search' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'search',\n contractCapturedAt: contract.capturedAt,\n claimedCount: totalResultCount(res.json),\n truncated: true, // one page of many; we never claim exhaustion\n });\n parsed.items = parsed.items.slice(0, limit);\n parsed.meta.returnedCount = parsed.items.length;\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n };\n}\n\n/**\n * The composite urn the comments endpoint keys off: the post's own urn,\n * repeated, plus a highlightedReply placeholder. Assembled rather than fetched\n * — verified working with an `urn:li:activity:` urn, so `post` needs no prior\n * lookup to find the ugcPost form.\n */\nfunction socialDetailUrn(postUrn: string): string {\n return `urn:li:fsd_socialDetail:(${postUrn},${postUrn},urn:li:highlightedReply:-)`;\n}\n\n/** LinkedIn's own claimed total, used to detect a claimed-but-empty fetch. */\nfunction totalResultCount(json: unknown): number | undefined {\n const found = JSON.stringify(json ?? {}).match(/\"totalResultCount\":(\\d+)/);\n return found?.[1] === undefined ? undefined : Number(found[1]);\n}\n","// Session persistence and the CDP bootstrap.\n//\n// Credentials live in a 0600 file under the cache dir. The design calls for OS\n// credential storage; that is a Phase 6 hardening step and is recorded as such\n// rather than silently skipped — for now the file is owner-only and the path is\n// gitignored.\n\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport type { Session } from './auth.ts';\n\nconst SESSION_FILE = 'session.json';\n\nexport type SessionLoad =\n | { state: 'ok'; session: Session }\n | { state: 'missing' }\n | { state: 'corrupt'; quarantinedTo: string };\n\nexport function loadSession(): SessionLoad {\n const result = loadJson<Session>(cachePath(SESSION_FILE));\n if (result.state === 'ok') return { state: 'ok', session: result.value };\n if (result.state === 'missing') return { state: 'missing' };\n return { state: 'corrupt', quarantinedTo: result.quarantinedTo };\n}\n\nexport function saveSession(session: Session): void {\n saveJson(cachePath(SESSION_FILE), session);\n}\n\n// ─── CDP bootstrap ────────────────────────────────────────────────────────────\n\nconst CDP = 'http://127.0.0.1:9222';\n\nexport const LAUNCH_HINT =\n 'Start Chrome with remote debugging first, DETACHED so it survives:\\n' +\n ' nohup /Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome \\\\\\n' +\n ' --remote-debugging-port=9222 --user-data-dir=\"$HOME/.lnrelay/chrome\" \\\\\\n' +\n ' https://www.linkedin.com/feed/ >/dev/null 2>&1 & disown\\n' +\n 'Then log into LinkedIn in that window and visit /feed/ once.';\n\ninterface CdpCookie {\n name: string;\n value: string;\n domain: string;\n}\n\n/**\n * Mint a session from a logged-in Chrome over the DevTools protocol.\n *\n * Visiting `/feed/` matters: that navigation is specifically what sets\n * JSESSIONID. A jar with JSESSIONID but no li_at means the browser has been to\n * linkedin.com but nobody has logged in.\n */\nexport async function mintSessionFromBrowser(): Promise<\n { ok: true; session: Session } | { ok: false; message: string; hint?: string }\n> {\n let targets: { type: string; webSocketDebuggerUrl?: string }[];\n let userAgent: string;\n try {\n targets = (await (await fetch(`${CDP}/json/list`)).json()) as typeof targets;\n const version = (await (await fetch(`${CDP}/json/version`)).json()) as {\n 'User-Agent'?: string;\n };\n userAgent = (version['User-Agent'] ?? '').replace('HeadlessChrome', 'Chrome');\n } catch {\n return { ok: false, message: `no Chrome DevTools endpoint at ${CDP}`, hint: LAUNCH_HINT };\n }\n\n const page = targets.find((t) => t.type === 'page' && t.webSocketDebuggerUrl !== undefined);\n if (page?.webSocketDebuggerUrl === undefined) {\n return { ok: false, message: 'no debuggable Chrome page found', hint: LAUNCH_HINT };\n }\n if (userAgent === '') {\n return { ok: false, message: 'Chrome did not report a User-Agent' };\n }\n\n let cookies: CdpCookie[];\n try {\n cookies = await getAllCookies(page.webSocketDebuggerUrl);\n } catch (e) {\n return { ok: false, message: `CDP failed: ${(e as Error).message}`, hint: LAUNCH_HINT };\n }\n\n const linkedin = cookies.filter((c) => c.domain.includes('linkedin.com'));\n const liAt = linkedin.find((c) => c.name === 'li_at');\n const jsession = linkedin.find((c) => c.name === 'JSESSIONID');\n\n if (liAt === undefined) {\n return {\n ok: false,\n message: 'no li_at cookie — you are not logged in',\n hint: 'Log into linkedin.com in the debug Chrome window, then re-run. Note that JSESSIONID alone is set pre-login and does not mean a session exists.',\n };\n }\n if (jsession === undefined) {\n return {\n ok: false,\n message: 'no JSESSIONID cookie',\n hint: 'Visit https://www.linkedin.com/feed/ in the debug window — that navigation is what sets it.',\n };\n }\n\n return {\n ok: true,\n session: {\n liAt: liAt.value,\n jsessionId: jsession.value,\n userAgent,\n capturedAt: new Date().toISOString().slice(0, 10),\n },\n };\n}\n\nfunction getAllCookies(wsUrl: string): Promise<CdpCookie[]> {\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(wsUrl);\n const timer = setTimeout(() => {\n ws.close();\n reject(new Error('timed out talking to Chrome'));\n }, 10_000);\n\n ws.onopen = () => ws.send(JSON.stringify({ id: 1, method: 'Network.getAllCookies' }));\n ws.onmessage = (ev) => {\n const msg = JSON.parse(String(ev.data)) as { id?: number; result?: { cookies: CdpCookie[] } };\n if (msg.id === 1 && msg.result !== undefined) {\n clearTimeout(timer);\n ws.close();\n resolve(msg.result.cookies);\n }\n };\n ws.onerror = () => {\n clearTimeout(timer);\n reject(new Error('websocket error'));\n };\n });\n}\n","// Runners for the commands that talk to LinkedIn. Thin: they resolve a\n// session, call the engine, and shape the envelope. All the interesting\n// behaviour lives in engine/.\n\nimport {\n type Collection,\n createEngine,\n type EngineResult,\n type SearchKind,\n} from '../engine/index.ts';\n\nimport {\n LAUNCH_HINT,\n loadSession,\n mintSessionFromBrowser,\n saveSession,\n} from '../engine/session.ts';\nimport {\n compactRows,\n project,\n type Shaped,\n shapeAll,\n shapeEntity,\n shapeProfile,\n} from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { retain } from './cache.ts';\n\nfunction withSession(\n command: string,\n quiet = false,\n): { engine: ReturnType<typeof createEngine> } | Envelope {\n const loaded = loadSession();\n if (loaded.state === 'corrupt') {\n return err(\n command,\n 'CACHE_CORRUPT',\n 'the stored session was unreadable and has been quarantined',\n `Moved to ${loaded.quarantinedTo}. Re-run \\`lnrelay login\\`.`,\n );\n }\n if (loaded.state === 'missing') {\n return err(command, 'AUTH_FAILED', 'no session — run `lnrelay login` first', LAUNCH_HINT);\n }\n return { engine: createEngine(loaded.session, undefined, quiet) };\n}\n\n/** Turn an engine failure into an envelope without losing its hint. */\nfunction toEnvelope(\n command: string,\n result: Extract<EngineResult<never>, { ok: false }>,\n): Envelope {\n return err(command, result.code, result.message, result.hint, undefined, result.retryAfterMs);\n}\n\nexport async function runLogin(): Promise<Envelope> {\n const minted = await mintSessionFromBrowser();\n if (!minted.ok) return err('login', 'AUTH_FAILED', minted.message, minted.hint);\n\n saveSession(minted.session);\n // Never echo a credential — presence and length only.\n return ok('login', {\n stored: true,\n liAtLength: minted.session.liAt.length,\n userAgent: minted.session.userAgent,\n capturedAt: minted.session.capturedAt,\n notice:\n 'Session stored with owner-only permissions. This tool breaches LinkedIn User Agreement ' +\n '§8.2 and the account can be restricted or banned.',\n });\n}\n\nexport async function runWhoami(raw = false): Promise<Envelope> {\n const ctx = withSession('whoami');\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.whoami();\n if (!result.ok) return toEnvelope('whoami', result);\n if (result.value === undefined) {\n return err(\n 'whoami',\n 'SCHEMA_DRIFT',\n 'LinkedIn returned no member entity',\n 're-capture the `me` contract',\n );\n }\n return ok(\n 'whoami',\n raw ? { ...shapeEntity(result.value), raw: result.value } : shapeEntity(result.value),\n );\n}\n\nexport async function runProfile(memberId: string | undefined, raw = false): Promise<Envelope> {\n if (memberId === undefined || memberId === '') {\n return err(\n 'profile',\n 'INVALID_INPUT',\n 'a member id or urn is required',\n 'lnrelay profile <public-id|urn>',\n );\n }\n const ctx = withSession('profile');\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.profile(normaliseMemberId(memberId));\n if (!result.ok) return toEnvelope('profile', result);\n if (result.value === undefined) {\n return err('profile', 'NOT_FOUND', `no profile for '${memberId}'`);\n }\n const shaped = shapeProfile(result.value.profile, result.value.index);\n return ok('profile', raw ? { ...shaped, raw: result.value.profile } : shaped);\n}\n\nexport async function runFeed(limit: number, opts: OutputOpts = {}): Promise<Envelope> {\n const ctx = withSession('feed', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.feed(limit);\n if (!result.ok) return toEnvelope('feed', result);\n return ok('feed', collection(result.value, opts));\n}\n\nexport async function runSearch(\n kind: string | undefined,\n query: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n if (kind === undefined || !['people', 'companies', 'jobs'].includes(kind)) {\n return err(\n 'search',\n 'INVALID_INPUT',\n 'kind must be people, companies or jobs',\n 'lnrelay search people \"<query>\"',\n );\n }\n if (query === undefined || query === '') {\n return err('search', 'INVALID_INPUT', 'a query is required', 'lnrelay search people \"<query>\"');\n }\n const ctx = withSession('search', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.search(kind as SearchKind, query, limit);\n if (!result.ok) return toEnvelope('search', result);\n return ok('search', { query, kind, ...collection(result.value, opts) });\n}\n\nexport async function runPost(\n urn: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n const postUrn = normalisePostUrn(urn);\n if (postUrn === undefined) {\n return err(\n 'post',\n 'INVALID_INPUT',\n 'a post urn or feed URL is required',\n 'lnrelay post <activity-urn|https://www.linkedin.com/feed/update/...>',\n );\n }\n const ctx = withSession('post', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.post(postUrn, limit);\n if (!result.ok) return toEnvelope('post', result);\n return ok('post', { urn: postUrn, ...collection(result.value, opts) });\n}\n\nexport async function runReactions(\n urn: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n const postUrn = normalisePostUrn(urn);\n if (postUrn === undefined) {\n return err('reactions', 'INVALID_INPUT', 'a post urn or feed URL is required');\n }\n const ctx = withSession('reactions', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.reactions(postUrn, limit);\n if (!result.ok) return toEnvelope('reactions', result);\n return ok('reactions', { urn: postUrn, ...collection(result.value, opts) });\n}\n\n// ─── shaping ──────────────────────────────────────────────────────────────────\n\n/** Accept a bare urn or a feed permalink; both carry the post identity. */\nfunction normalisePostUrn(input: string | undefined): string | undefined {\n if (input === undefined || input === '') return undefined;\n const found = input.match(/urn:li:(?:activity|ugcPost|share):\\d+/);\n if (found !== null) return found[0];\n return /^\\d+$/.test(input) ? `urn:li:activity:${input}` : undefined;\n}\n\n/** A URL, a public id, or a bare urn all reduce to the member identity. */\nfunction normaliseMemberId(input: string): string {\n const fromUrl = input.match(/linkedin\\.com\\/in\\/([^/?#]+)/);\n if (fromUrl?.[1] !== undefined) return fromUrl[1];\n const fromUrn = input.match(/urn:li:fsd?_(?:mini)?[Pp]rofile:([^,)]+)/);\n if (fromUrn?.[1] !== undefined) return fromUrn[1];\n return input;\n}\n\n/** How the caller wants the rows rendered. */\nexport interface OutputOpts {\n raw?: boolean;\n retain?: boolean;\n compact?: boolean;\n fields?: string;\n quiet?: boolean;\n}\n\n/**\n * Collections are shaped by default — raw Voyager entities are enormous and\n * wrap every string in a TextViewModel. `--raw` keeps the original node\n * alongside, for when a shape has drifted and you need to see what arrived;\n * `--compact` and `--fields` go the other way, for when a page of results is\n * about to land in an agent's context and only the ranking signal matters.\n */\nfunction collection(result: Collection, opts: OutputOpts = {}): Record<string, unknown> {\n const { parsed, index } = result;\n const shaped = shapeAll(parsed.items, index);\n\n const meta: Record<string, unknown> = { ...parsed.meta };\n // Retention always stores the FULL shaped row, never the projected one — a\n // display choice must not silently narrow what gets cached.\n if (opts.retain === true) meta.retained = retain('third-party', shaped);\n\n if (opts.raw === true) {\n return {\n items: parsed.items.map((node, i) => ({ ...(shaped[i] as Shaped), raw: node })),\n meta,\n };\n }\n if (opts.compact === true) return { items: compactRows(shaped), meta };\n if (opts.fields !== undefined && opts.fields !== '') {\n return { items: project(shaped, opts.fields), meta };\n }\n return { items: shaped, meta };\n}\n","// The three commands that work today. All are local: they make no network call\n// and need no LinkedIn session, so they are useful before the Phase 0 gate has\n// even run.\n\nimport { existsSync } from 'node:fs';\nimport { version as nodeVersion } from 'node:process';\nimport { cacheDir, cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport {\n activeCooldown,\n CAPS,\n type Cooldown,\n emptyLedger,\n type Ledger,\n type SpendClass,\n summarise,\n} from '../engine/budget.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\n\nconst LEDGER_FILE = 'budget.json';\nconst COOLDOWN_FILE = 'cooldown.json';\n\ninterface StateLoad<T> {\n value: T | null;\n corrupt: { path: string; quarantinedTo: string; reason: string } | null;\n}\n\nfunction loadState<T>(file: string, fallback: T): StateLoad<T> {\n const path = cachePath(file);\n const result = loadJson<T>(path);\n if (result.state === 'ok') return { value: result.value, corrupt: null };\n if (result.state === 'missing') return { value: fallback, corrupt: null };\n return {\n value: null,\n corrupt: { path, quarantinedTo: result.quarantinedTo, reason: result.reason },\n };\n}\n\nexport function loadLedger(): StateLoad<Ledger> {\n return loadState<Ledger>(LEDGER_FILE, emptyLedger());\n}\n\nexport function loadCooldown(): StateLoad<Cooldown | null> {\n return loadState<Cooldown | null>(COOLDOWN_FILE, null);\n}\n\n// ─── risk ─────────────────────────────────────────────────────────────────────\n\n/**\n * The breaker's current state. Exposed over MCP deliberately, so an agent can\n * check standing BEFORE deciding to spend budget on research rather than\n * discovering the lockout one wasted call at a time.\n */\nexport function runRisk(now: number): Envelope {\n const { value: cooldown, corrupt } = loadCooldown();\n if (corrupt !== null) {\n return err(\n 'risk',\n 'CACHE_CORRUPT',\n `cooldown state was unreadable and has been quarantined: ${corrupt.reason}`,\n `moved to ${corrupt.quarantinedTo}. Inspect it, then re-run — a fresh cooldown file will be created.`,\n );\n }\n\n const blocked = activeCooldown(cooldown ?? null, now);\n return ok('risk', {\n state: blocked ? 'blocked' : 'ok',\n cooldown: cooldown ?? null,\n tosNotice:\n 'Voyager reads breach LinkedIn User Agreement §8.2. This tool is not ToS-compliant and ' +\n 'any account it touches can be restricted or permanently banned.',\n });\n}\n\n// ─── budget ───────────────────────────────────────────────────────────────────\n\nexport function runBudget(now: number, resetCooldown: boolean, confirmed: boolean): Envelope {\n if (resetCooldown && !confirmed) {\n return err(\n 'budget',\n 'CONFIRMATION_REQUIRED',\n 'clearing a cooldown requires --confirm',\n 'A cooldown means LinkedIn signalled a throttle, block or challenge. Log in through a real ' +\n 'browser and confirm you are unblocked before clearing it. Re-run with --confirm.',\n );\n }\n\n if (resetCooldown) {\n saveJson(cachePath(COOLDOWN_FILE), null);\n }\n\n const { value: ledger, corrupt } = loadLedger();\n if (corrupt !== null) {\n return err(\n 'budget',\n 'CACHE_CORRUPT',\n `the spend ledger was unreadable and has been quarantined: ${corrupt.reason}`,\n `moved to ${corrupt.quarantinedTo}. A corrupt ledger is NOT treated as an empty one — that ` +\n 'would silently restore a full budget. Inspect it, then re-run.',\n );\n }\n\n const classes: SpendClass[] = ['profile', 'search', 'page', 'write', 'global'];\n const { value: cooldown } = loadCooldown();\n\n return ok('budget', {\n classes: classes.map((c) => ({\n ...summarise(ledger ?? emptyLedger(), c, now),\n note: CAPS[c].note,\n })),\n cooldown: cooldown ?? null,\n caveat:\n 'Every cap is guessed or transplanted vendor lore — the field research found no corroborated ' +\n 'LinkedIn rate limits. These are starting knobs, not safe thresholds. They also cannot see ' +\n 'your manual browser activity.',\n });\n}\n\n// ─── doctor ───────────────────────────────────────────────────────────────────\n\nexport interface Check {\n name: string;\n ok: boolean;\n detail: string;\n}\n\n/**\n * Diagnose setup. Always returns ok:true at the envelope level — a diagnostic\n * that fails to report because something is broken is useless. Individual checks\n * carry their own pass/fail. Never prints a credential value.\n */\nexport function runDoctor(now: number, offline: boolean): Envelope {\n const checks: Check[] = [];\n\n checks.push({\n name: 'runtime',\n ok: true,\n detail: `node ${nodeVersion}; cache dir ${cacheDir()}${existsSync(cacheDir()) ? '' : ' (not created yet)'}`,\n });\n\n const { value: cooldown, corrupt: cooldownCorrupt } = loadCooldown();\n if (cooldownCorrupt !== null) {\n checks.push({\n name: 'cooldown',\n ok: false,\n detail: `state file was corrupt; quarantined to ${cooldownCorrupt.quarantinedTo}`,\n });\n } else {\n const blocked = activeCooldown(cooldown ?? null, now);\n checks.push({\n name: 'cooldown',\n ok: !blocked,\n detail: blocked\n ? `BLOCKED — ${cooldown?.reason}, clears by ${cooldown?.clearRequires}${\n cooldown?.until === null\n ? ' (indefinite)'\n : ` at ${new Date(cooldown?.until ?? 0).toISOString()}`\n }`\n : 'clear',\n });\n }\n\n const { value: ledger, corrupt: ledgerCorrupt } = loadLedger();\n if (ledgerCorrupt !== null) {\n checks.push({\n name: 'budget',\n ok: false,\n detail: `ledger was corrupt; quarantined to ${ledgerCorrupt.quarantinedTo}`,\n });\n } else {\n const g = summarise(ledger ?? emptyLedger(), 'global', now);\n checks.push({\n name: 'budget',\n ok: g.remaining > 0,\n detail: `${g.spentInWindow}/${g.cap} global calls used in the last 24h (cap provenance: ${g.capProvenance})`,\n });\n }\n\n // Credentials are checked for PRESENCE and LENGTH only — never printed.\n const cookiePath = cachePath('cookies.json');\n checks.push({\n name: 'session',\n ok: false,\n detail: existsSync(cookiePath)\n ? 'a cookie file exists, but the engine is not implemented yet (Phase 2)'\n : 'no session yet — the Phase 0 capture gate has not been run. See docs/PLAN.md.',\n });\n\n checks.push({\n name: 'engine',\n ok: false,\n detail:\n 'not implemented. Phase 0 (three human-paced requests from a residential IP) must pass ' +\n 'before engine code is written — see docs/PLAN.md.',\n });\n\n if (!offline) {\n checks.push({\n name: 'live',\n ok: false,\n detail: 'no live checks available yet; --offline is currently the only meaningful mode',\n });\n }\n\n return ok('doctor', {\n healthy: checks.every((c) => c.ok),\n phase: 'Phase 1 — local scaffolding. No network capability exists yet, by design.',\n checks,\n });\n}\n","// Single source of truth for command definitions. Drives CLI dispatch + help,\n// the MCP tool surface, and the SKILL.md parity test.\n//\n// `audience` is load-bearing, not documentation: the MCP shim registers only\n// commands marked `mcp`, so a write can never reach an agent by accident. The\n// research half of this tool is the product; writes are a thin, human-gated\n// layer that arrives last (docs/PLAN.md Phase 6).\n\nexport type Audience = 'cli' | 'mcp';\nexport type RiskClass = 'read' | 'local' | 'write';\n\nexport interface CommandDef {\n name: string;\n /** Funnel cost hint shown in help + skill. */\n cost: string;\n summary: string;\n usage: string;\n audience: Audience[];\n risk: RiskClass;\n /** false until the command is actually wired up. */\n implemented: boolean;\n}\n\nexport const COMMANDS: CommandDef[] = [\n // ─── local / meta — no network, available today ────────────────────────────\n {\n name: 'doctor',\n cost: 'free with --offline',\n summary: 'Diagnose setup: entry point, cache dir, cookies, cooldown, budget.',\n usage: 'lnrelay doctor [--offline]',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'budget',\n cost: 'free',\n summary: \"Spend ledger per class, with each cap's provenance. Reset a cooldown here.\",\n usage: 'lnrelay budget [--reset-cooldown --confirm]',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'risk',\n cost: 'free',\n summary: 'Circuit-breaker state. Check this BEFORE spending budget on research.',\n usage: 'lnrelay risk',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── session ───────────────────────────────────────────────────────────────\n {\n name: 'login',\n cost: 'free — local browser',\n summary: 'Mint a session from a logged-in Chrome via DevTools. Stores cookies owner-only.',\n usage:\n 'lnrelay login\\n' +\n ' Requires a Chrome started with remote debugging on port 9222 (see docs/PLAN.md).',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── reads — verified live 2026-08-01 ─────────────────────────────────────\n {\n name: 'whoami',\n cost: '1 call',\n summary: 'The authenticated member: name, headline, URN.',\n usage: 'lnrelay whoami',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'profile',\n cost: '1 call (+1 per section)',\n summary: 'A member profile. Expensive sections are opt-in.',\n usage:\n 'lnrelay profile <public-id|urn|url> [--raw]\\n' +\n \" Returns headline, location, current title, company and school. LinkedIn's profile\\n\" +\n ' projections do not return a name — use the identifier you passed in.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'search',\n cost: 'cheap — the net',\n summary: 'Search people, companies or jobs. Cast wide, then deep-read the finalists.',\n usage:\n 'lnrelay search people|companies|jobs \"<query>\" [--limit N]\\n' +\n ' [--compact | --fields a,b,c] [--retain] [--raw]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'post',\n cost: 'expensive — full read',\n summary: 'A post plus its comment thread, cursor-followed.',\n usage:\n 'lnrelay post <activity-urn|url> [--limit N] [--compact | --fields a,b] [--retain]\\n' +\n ' Check meta.returnedCount / claimedCount / state. claimedCount > 0 with\\n' +\n ' returnedCount 0 is a FAILED FETCH, not an empty thread.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'reactions',\n cost: 'medium',\n summary: 'Who reacted to a post, and with which reaction.',\n usage: 'lnrelay reactions <activity-urn|url> [--limit N] [--compact | --fields a,b]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'company',\n cost: 'medium',\n summary: 'A company page, optionally with a bounded sample of its updates.',\n usage: 'lnrelay company <universal-name|url> [--updates N]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: false,\n },\n {\n name: 'job',\n cost: '1 call',\n summary: 'A job posting detail.',\n usage: 'lnrelay job <job-id|url>',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: false,\n },\n {\n name: 'feed',\n cost: 'medium',\n summary: 'Your own chronological feed.',\n usage: 'lnrelay feed [--limit N] [--compact | --fields a,b,c] [--retain] [--raw]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n\n // ─── cache-backed — Phase 4 ────────────────────────────────────────────────\n {\n name: 'sync',\n cost: 'medium — 1-2 calls',\n summary: 'Pull your own posts or connections into the local cache for offline search.',\n usage: 'lnrelay sync my-posts|connections [--limit N] [--force]',\n audience: ['cli'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'connections',\n cost: 'free — local cache',\n summary: 'Your connections, from the local cache. Fill it with `sync connections`.',\n usage:\n 'lnrelay connections [-q \"<query>\"] [--limit N] [--compact | --fields a,b] # free; cache',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'my-posts',\n cost: 'free — local cache',\n summary: 'Your own authored posts, from the local cache. Fill it with `sync my-posts`.',\n usage:\n 'lnrelay my-posts [-q \"<query>\"] [--limit N] [--compact | --fields a,b] # free; cache',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'local',\n cost: 'free — local cache',\n summary: 'Offline search across everything synced. The default research path after a sync.',\n usage:\n 'lnrelay local \"<query>\" [--source connections,my-posts,third-party] [--since YYYY-MM-DD]\\n' +\n ' [--limit N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'cache-status',\n cost: 'free — local cache',\n summary: 'What is cached, per source, with sync checkpoints and the retention policy.',\n usage: 'lnrelay cache-status',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'purge',\n cost: 'free',\n summary: 'Delete cached data. Never contacts LinkedIn.',\n usage: 'lnrelay purge [--all] --confirm # default scope: third-party only',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── writes — Phase 6, official OAuth only, never MCP ──────────────────────\n {\n name: 'oauth',\n cost: 'free',\n summary:\n \"Obtain and inspect the write credential, over LinkedIn's own self-serve scope. \" +\n 'Never prints the token.',\n usage:\n 'lnrelay oauth login --client-id <id> [--client-secret <secret>]\\n' +\n ' lnrelay oauth status | logout\\n' +\n ' The secret is prompted for if omitted; LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET also work.\\n' +\n ' Needs an app you registered: see the hint printed when no token is stored.',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'share',\n cost: '1 call — write',\n summary:\n \"Post to your own feed. Prefers LinkedIn's official OAuth scope, falls back to the \" +\n 'private API when no token exists — the prompt always names which.',\n usage:\n 'lnrelay share \"<text>\" [--visibility public|connections] [--via oauth|voyager]\\n' +\n ' Stops and asks at an interactive terminal. No TTY = no write, and no network call.',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'comment',\n cost: '1 call — write',\n summary:\n 'Add a comment to a post. Harvests its binding tokens from the rendered page; no browser ' +\n 'needed, but it costs one heavy read.',\n usage:\n 'lnrelay comment <activity-urn> \"<text>\"\\n' +\n ' Fetches the post page (~2.8 MB) to harvest a binding key and trackingId, and proves\\n' +\n ' the key belongs to that post before asking. To change a comment, see `edit`.',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'delete',\n cost: '1 read + 1 write',\n summary:\n 'Delete one of your own posts or comments. Reads a post back and shows its text first — ' +\n 'this is the one action that cannot be undone.',\n usage:\n 'lnrelay delete <activity-urn> # a post; shows you its text before destroying it\\n' +\n ' lnrelay delete <comment-urn> # a comment; the server decides if you may',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'edit',\n cost: '1 read + 1 write',\n summary:\n 'Change the text of a comment you wrote. Its own verb, so a comment urn can never be ' +\n 'mistaken for something to comment ON.',\n usage: 'lnrelay edit <comment-urn> \"<text>\"',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'react',\n cost: '1 call — write',\n summary: \"React to a post or comment, over LinkedIn's SDUI surface. Reversible with --remove.\",\n usage:\n 'lnrelay react <activity-urn | comment-urn> [--type LIKE|PRAISE|EMPATHY|INTEREST|APPRECIATION|ENTERTAINMENT]\\n' +\n ' lnrelay react <urn> --remove # take the reaction back',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n];\n\nexport const commandNames = COMMANDS.map((c) => c.name);\n\nexport function findCommand(name: string): CommandDef | undefined {\n return COMMANDS.find((c) => c.name === name);\n}\n\n/** Commands the MCP shim may register. Writes are structurally excluded. */\nexport function mcpCommands(): CommandDef[] {\n return COMMANDS.filter((c) => c.audience.includes('mcp') && c.risk !== 'write');\n}\n\nexport function helpText(): string {\n const lines = ['lnrelay — deep research over LinkedIn from your own account', '', 'Commands:'];\n const width = Math.max(...commandNames.map((n) => n.length));\n for (const c of COMMANDS) {\n const flag = c.implemented ? ' ' : '·'; // · = designed, not yet wired\n lines.push(` ${flag} ${c.name.padEnd(width)} ${c.summary} [${c.cost}]`);\n }\n lines.push('', ' · = specified in docs/DESIGN.md, not yet implemented');\n lines.push('', 'Run `lnrelay <command> --help` for usage.');\n return lines.join('\\n');\n}\n","// ─── Main-module detection ────────────────────────────────────────────────\n// Deciding whether an entry file was invoked directly (should run) vs merely\n// imported (should stay silent). The naive `fileURLToPath(url) === argv[1]`\n// check breaks under the npm bin symlink (…/bin/lnrelay → …/dist/cli.js): argv1\n// is the symlink, the module url is the real file — unequal — so the CLI would\n// silently exit 0. Resolving both through realpath fixes that. Pure + testable.\nimport { realpathSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Decide whether the current module is the process entry point.\n * @param argv1 process.argv[1] — the invoked script path (may be a symlink).\n * @param moduleUrl import.meta.url of the entry module.\n * @param importMetaMain import.meta.main when the runtime provides it.\n */\nexport function isMainModule(\n argv1: string | undefined,\n moduleUrl: string,\n importMetaMain: boolean | undefined,\n): boolean {\n // The runtime told us explicitly — trust it (Bun always sets this).\n if (importMetaMain === true) return true;\n if (importMetaMain === false) return false;\n\n if (argv1 === undefined) return false;\n\n const modulePath = fileURLToPath(moduleUrl);\n try {\n return realpathSync(argv1) === realpathSync(modulePath);\n } catch {\n // realpath failed (path missing, permission, etc.) — fall back to a plain\n // string compare.\n return argv1 === modulePath;\n }\n}\n\n/**\n * Fail-loud heuristic: when isMainModule said \"not entry\" but argv1's basename\n * looks like one of our binaries, the user clearly invoked us and our detection\n * failed. Callers run anyway (after warning) rather than silently exiting.\n */\nexport function shouldForceEntry(argv1: string | undefined, binNames: string[]): boolean {\n if (argv1 === undefined) return false;\n return binNames.includes(basename(argv1));\n}\n\nexport interface EntryDecision {\n /** Whether the entry file should run its main routine. */\n run: boolean;\n /** A stderr warning to print first, or undefined when detection was clean. */\n warning: string | undefined;\n}\n\n/**\n * Consolidated entry decision. Runs when detected as main. Otherwise, ONLY when\n * the runtime gave no definitive answer (import.meta.main === undefined) and the\n * basename looks like one of our binaries, force-runs with a fail-loud warning —\n * an explicit import.meta.main === false is authoritative and never overridden.\n * binNames[0] is used as the label in the warning (the user-facing bin name).\n */\nexport function shouldRunAsEntry(\n argv1: string | undefined,\n moduleUrl: string,\n importMetaMain: boolean | undefined,\n binNames: string[],\n): EntryDecision {\n if (isMainModule(argv1, moduleUrl, importMetaMain)) {\n return { run: true, warning: undefined };\n }\n if (importMetaMain === undefined && shouldForceEntry(argv1, binNames)) {\n return {\n run: true,\n warning: `${binNames[0]}: entry detection failed — treating as main; report at github.com/gabros20/linkedin-relay/issues`,\n };\n }\n return { run: false, warning: undefined };\n}\n"],"mappings":";;;AAkBA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,SAAS;;;ACHlB,SAAS,gBAAgB;AACzB,SAAS,aAAAA,YAAW,cAAAC,mBAAkB;;;ACAtC,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAEvB,SAAS,WAAmB;AACjC,SAAO,QAAQ,IAAI,qBAAqB,KAAK,QAAQ,GAAG,UAAU;AACpE;AAEO,SAAS,aAAa,OAAyB;AACpD,SAAO,KAAK,SAAS,GAAG,GAAG,KAAK;AAClC;AAaO,SAAS,SAAY,MAA6B;AACvD,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO,EAAE,OAAO,UAAU;AAEjD,MAAI;AACJ,MAAI;AACF,UAAM,aAAa,MAAM,OAAO;AAAA,EAClC,SAAS,GAAG;AACV,WAAO,WAAW,MAAM,eAAgB,EAAY,OAAO,EAAE;AAAA,EAC/D;AAEA,MAAI;AACF,WAAO,EAAE,OAAO,MAAM,OAAO,KAAK,MAAM,GAAG,EAAO;AAAA,EACpD,SAAS,GAAG;AACV,WAAO,WAAW,MAAM,qBAAsB,EAAY,OAAO,EAAE;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CAAC;AAAA,IACD,YAAY,MAAM,eAAe,CAAC;AAAA,EACpC;AAEA,SAAO;AACT;AAEA,IAAM,QAAQ,iBAAiB,QAAQ,KAAK,CAAC,GAAG,YAAY,KAAK,YAAY,MAAM;AAAA,EACjF;AAAA,EACA;AACF,CAAC;AAED,IAAI,MAAM,KAAK;AACb,QAAM,SAAS,YAAY;AAC3B,QAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AACjD;","names":["mkdirSync","renameSync","mkdirSync","quarantine","renameSync","typeOf","count","postUrn","postUrn","existsSync","existsSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp-shim.ts","../src/cache/db.ts","../src/cache/store.ts","../src/engine/restli.ts","../src/format.ts","../src/output.ts","../src/commands/cache.ts","../src/progress.ts","../src/engine/budget.ts","../src/engine/auth.ts","../src/engine/classify.ts","../src/engine/client.ts","../src/engine/contracts.ts","../src/engine/parse.ts","../src/engine/index.ts","../src/engine/session.ts","../src/commands/live.ts","../src/commands/local.ts","../src/commands/registry.ts","../src/entry.ts"],"sourcesContent":["#!/usr/bin/env bun\n// ─── MCP surface ──────────────────────────────────────────────────────────────\n//\n// Thin by contract: this file validates arguments, calls the same runners the\n// CLI calls, and returns the same envelope. No parsing, no transport, no\n// pacing, no cache logic lives here.\n//\n// Writes are not registered. Not disabled, not permission-gated — absent. The\n// registry marks each command's audience and risk, `mcpCommands()` filters on\n// both, and a test asserts no write survives that filter. An agent talking to\n// this server cannot post, comment, react, connect or message, whatever\n// arguments it composes.\n//\n// Tool descriptions do real work here. The agent reads them BEFORE it ever sees\n// a response, so each one states the specific misreading that would cause harm\n// — chiefly that an empty result and a failed fetch look identical unless you\n// check the counts.\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport { runCacheStatus, runLocal, runSourceRead } from './commands/cache.ts';\nimport {\n runFeed,\n runPost,\n runProfile,\n runReactions,\n runSearch,\n runWhoami,\n} from './commands/live.ts';\nimport { runBudget, runDoctor, runRisk } from './commands/local.ts';\nimport { mcpCommands } from './commands/registry.ts';\nimport { shouldRunAsEntry } from './entry.ts';\nimport type { Envelope } from './types.ts';\n\nconst READING_CONTRACT =\n 'ALWAYS read `meta` before reporting. `state:\"complete\"` with an empty `items` genuinely means ' +\n 'none. `state:\"partial\"` means references failed to resolve — the record is INCOMPLETE, not ' +\n 'small. `claimedCount > 0` with `returnedCount === 0` is a FAILED FETCH, never \"no results\". ' +\n 'A non-empty `unknownTypes` means LinkedIn changed shape and the parser is behind — say so. ' +\n 'If `meta.budget.remaining` is low, tell the user and stop.';\n\nconst NO_RETRY =\n 'Never retry on failure. RATE_LIMITED, REQUEST_DENIED, CHALLENGE_DETECTED and COOLDOWN_ACTIVE ' +\n 'all mean a cross-process cooldown has opened; every further call will refuse until it lifts. ' +\n 'Report it and stop.';\n\n/** Render an envelope as MCP content. Errors stay envelopes, not exceptions. */\nfunction reply(envelope: Envelope) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(envelope) }],\n isError: !envelope.ok,\n };\n}\n\nexport function buildServer(): McpServer {\n const server = new McpServer({ name: 'linkedin-relay', version: '0.1.0' });\n\n // Guard rather than trust: if a write ever reached this list, fail loudly at\n // startup instead of quietly exposing it.\n const exposed = mcpCommands();\n const write = exposed.find((c) => c.risk === 'write');\n if (write !== undefined) {\n throw new Error(`refusing to start: write command '${write.name}' reached the MCP surface`);\n }\n\n server.tool(\n 'risk',\n 'Circuit-breaker state and the ToS notice. Free, no network. CALL THIS FIRST in a research ' +\n 'session — it reports whether LinkedIn has thrown a throttle, block or challenge, so you ' +\n 'find out before spending calls rather than one wasted call at a time.',\n {},\n async () => reply(runRisk(Date.now())),\n );\n\n server.tool(\n 'budget',\n \"Remaining request budget per class, with each cap's provenance. Free, no network. The caps \" +\n 'are deliberately low because LinkedIn restricts accounts for READ velocity alone — they are ' +\n \"guesses, not measured safe limits, and they cannot see the user's own browser activity.\",\n {},\n async () => reply(runBudget(Date.now(), false, false)),\n );\n\n server.tool(\n 'doctor',\n 'Diagnose setup end to end: session, cooldown, budget, engine readiness. Free with offline. ' +\n 'Run this first when anything behaves oddly. Never reveals credential values.',\n { offline: z.boolean().optional().describe('skip live checks (default true)') },\n async ({ offline }) => reply(runDoctor(Date.now(), offline ?? true)),\n );\n\n server.tool(\n 'whoami',\n 'The authenticated LinkedIn member: name, headline, public id, urn. Cheap (1 call). Good ' +\n `first call to confirm the session works and which account it is. ${NO_RETRY}`,\n {},\n async () => reply(await runWhoami()),\n );\n\n server.tool(\n 'search',\n 'Search LinkedIn people, companies or jobs. CHEAP — this is the net. Rows already carry name, ' +\n 'headline, location and url, so RANK ON THOSE and deep-read only 2-3 finalists with ' +\n '`profile`. Calling profile on every result burns a day of budget in one request. ' +\n \"`meta.claimedCount` is LinkedIn's total for the query (often millions), NOT how many you \" +\n 'got, and `meta.state` is always \"unknown\" because this is one page of many. Out-of-network ' +\n 'people return as name \"LinkedIn Member\" with a /headless url — that is real LinkedIn ' +\n `behaviour for this account, not a failure. ${READING_CONTRACT} ${NO_RETRY}`,\n {\n kind: z.enum(['people', 'companies', 'jobs']),\n query: z.string().min(1).describe('search terms'),\n limit: z.number().int().min(1).max(25).optional().describe('default 10'),\n },\n async ({ kind, query, limit }) => reply(await runSearch(kind, query, limit ?? 10)),\n );\n\n server.tool(\n 'profile',\n 'Read one LinkedIn profile: headline, location, current title, company, school. MEDIUM cost — ' +\n 'use only on finalists surfaced by `search`. Accepts a public id, a urn, or a ' +\n \"linkedin.com/in/… URL. KNOWN LIMIT: LinkedIn's profile projections do not return a name, \" +\n 'so the result has a headline but no first/last name — use the identifier you passed in. ' +\n `Do NOT report the profile as empty on that basis. ${NO_RETRY}`,\n { id: z.string().min(1).describe('public id, urn, or profile URL') },\n async ({ id }) => reply(await runProfile(id)),\n );\n\n server.tool(\n 'feed',\n \"The user's own chronological LinkedIn feed: author, when, text, url. MEDIUM cost. Promoted \" +\n 'posts are dropped and counted in `meta.excludedCount`, so fewer items than `limit` usually ' +\n `means ads were filtered, not that the fetch failed. ${READING_CONTRACT} ${NO_RETRY}`,\n { limit: z.number().int().min(1).max(20).optional().describe('default 10') },\n async ({ limit }) => reply(await runFeed(limit ?? 10)),\n );\n\n server.tool(\n 'post',\n \"A LinkedIn post's comment thread. EXPENSIVE — read only finalists. Accepts a bare \" +\n 'urn:li:activity:…, a urn:li:ugcPost:…, or a linkedin.com/feed/update/… URL; no prior lookup ' +\n 'is needed. Feed and search rows already report how many comments a post has, so use that to ' +\n 'decide whether the thread is worth a call. `meta.state` is always \"unknown\" — this is the ' +\n 'first page and pagination is not followed, so NEVER report a comment count as complete. ' +\n `Nested replies are not supported and a comment with replies does not carry them. ${READING_CONTRACT} ${NO_RETRY}`,\n {\n urn: z.string().min(1).describe('activity/ugcPost urn, or a feed-update URL'),\n limit: z.number().int().min(1).max(100).optional().describe('default 20'),\n },\n async ({ urn, limit }) => reply(await runPost(urn, limit ?? 20)),\n );\n\n server.tool(\n 'reactions',\n 'Who reacted to a LinkedIn post, and with which reaction. MEDIUM cost. Often more informative ' +\n 'than the comments for mapping who is paying attention to a topic. Same input forms as ' +\n '`post`. `meta.state` is always \"unknown\" — first page only, so do not report a total. ' +\n `${READING_CONTRACT} ${NO_RETRY}`,\n {\n urn: z.string().min(1).describe('activity/ugcPost urn, or a feed-update URL'),\n limit: z.number().int().min(1).max(100).optional().describe('default 20'),\n },\n async ({ urn, limit }) => reply(await runReactions(urn, limit ?? 20)),\n );\n\n server.tool(\n 'local',\n 'Search the LOCAL cache. Free — no network call, no budget spent. PREFER THIS before any live ' +\n 'command: if the answer is already cached, there is no reason to spend a request on it. The ' +\n 'cache only fills when the user runs a live read with --retain, so an empty result here means ' +\n 'nothing has been retained yet — NOT that LinkedIn has nothing. Check `meta.cachedTotal`.',\n {\n query: z.string().optional().describe('substring match; omit to list everything'),\n source: z.string().optional().describe('comma-separated: connections,my-posts,third-party'),\n since: z.string().optional().describe('YYYY-MM-DD'),\n limit: z.number().int().min(1).max(100).optional().describe('default 25'),\n },\n async ({ query, source, since, limit }) => reply(runLocal(query, source, since, limit ?? 25)),\n );\n\n for (const source of ['connections', 'my-posts'] as const) {\n server.tool(\n source.replace('-', '_'),\n `The user's own ${source === 'connections' ? 'connections' : 'authored posts'}, read from the ` +\n 'LOCAL cache. Free — no network call, no budget spent. An empty result means the cache has ' +\n `not been filled, NOT that the user has none: tell them to run \\`lnrelay sync ${source}\\` ` +\n 'themselves (it is CLI-only). Check `meta.cachedTotal` to tell the two apart.',\n {\n query: z.string().optional().describe('substring match; omit to list everything'),\n limit: z.number().int().min(1).max(100).optional().describe('default 25'),\n },\n async ({ query, limit }) => reply(runSourceRead(source, query, limit ?? 25)),\n );\n }\n\n server.tool(\n 'cache_status',\n 'What is cached per source, with sync checkpoints and the retention policy. Free, no network. ' +\n 'Third-party records expire 30 days after capture — the body goes, an identity stub stays, so ' +\n 'a re-fetch is a visible choice rather than a silent budget charge.',\n {},\n async () => reply(runCacheStatus()),\n );\n\n return server;\n}\n\nconst entry = shouldRunAsEntry(process.argv[1], import.meta.url, import.meta.main, [\n 'linkedin-relay-mcp',\n 'lnrelay',\n]);\n\nif (entry.run) {\n const server = buildServer();\n await server.connect(new StdioServerTransport());\n}\n","// ─── The local store ──────────────────────────────────────────────────────────\n//\n// SQLite (`bun:sqlite`, WAL) behind the same narrow load/save/query interface\n// the family's JSON store exposes. The family similarity that matters is the\n// interface, not the file format.\n//\n// SQLite was chosen for one specific reason: it makes \"corrupt\" a detectable,\n// per-source, quarantinable state. In a single JSON blob, corruption is\n// all-or-nothing and tells you nothing about which records survived — and on\n// this platform an empty-looking cache is what triggers a full re-sync against\n// the most hostile host in the research. TTL expiry as a transactional delete\n// rather than a whole-file rewrite is the second reason.\n//\n// Retention is enforced on the READ path, not by a schedule. There is no cron\n// to forget and no purge command to remember: the only code that can observe\n// expired third-party data is the code that deletes it first.\n\nimport { Database } from 'bun:sqlite';\nimport { mkdirSync, renameSync } from 'node:fs';\nimport { cacheDir, cachePath } from './store.ts';\n\nconst DB_FILE = 'cache.db';\n\n/** Third-party rows expire; owner rows do not. */\nexport const THIRD_PARTY_TTL_MS = 30 * 86_400_000;\n\nexport type Source = 'connections' | 'my-posts' | 'third-party';\n\nexport interface Record_ {\n urn: string;\n source: Source;\n /** Shaped JSON. Null once expired — the identity stub survives, the body does not. */\n body: string | null;\n text: string;\n firstSeenAt: number;\n updatedAt: number;\n expiresAt: number | null;\n}\n\n/**\n * Strip diacritics and lowercase, for matching only.\n *\n * SQLite's LIKE is not accent-insensitive, so `local \"kovary\"` found nothing\n * while \"kőváry\" found the record — the user types what is on their keyboard,\n * not what LinkedIn stored. Found by a real search on a Hungarian name.\n *\n * The folded form is stored ALONGSIDE the original, never instead of it: the\n * display value keeps its accents.\n */\nexport function fold(value: string): string {\n return value\n .normalize('NFD')\n .replace(/\\p{Diacritic}/gu, '')\n .toLowerCase();\n}\n\nconst TABLES = [\n `CREATE TABLE IF NOT EXISTS records (\n urn TEXT NOT NULL,\n source TEXT NOT NULL,\n body TEXT,\n text TEXT NOT NULL DEFAULT '',\n textFold TEXT NOT NULL DEFAULT '',\n firstSeenAt INTEGER NOT NULL,\n updatedAt INTEGER NOT NULL,\n expiresAt INTEGER,\n PRIMARY KEY (urn, source)\n )`,\n `CREATE TABLE IF NOT EXISTS checkpoints (\n source TEXT PRIMARY KEY,\n lastSuccessfulAt INTEGER NOT NULL,\n newestCreatedAt INTEGER,\n headIds TEXT NOT NULL DEFAULT '[]',\n state TEXT NOT NULL DEFAULT 'ok'\n )`,\n];\n\n// Indexes are created AFTER migrations, because an index may reference a column\n// a migration is about to add. Creating them alongside the tables meant an\n// existing store — where CREATE TABLE IF NOT EXISTS is a no-op — tried to index\n// a column it did not have yet, and threw on open.\nconst INDEXES = [\n 'CREATE INDEX IF NOT EXISTS records_source ON records(source)',\n 'CREATE INDEX IF NOT EXISTS records_fold ON records(textFold)',\n 'CREATE INDEX IF NOT EXISTS records_expires ON records(expiresAt)',\n];\n\nexport class CacheCorrupt extends Error {\n constructor(\n message: string,\n readonly quarantinedTo: string,\n ) {\n super(message);\n this.name = 'CacheCorrupt';\n }\n}\n\n/**\n * Open the store. A database that fails its integrity check is QUARANTINED and\n * the error is thrown — never silently replaced with an empty one, because an\n * empty cache is operationally active here: it is precisely what makes `sync`\n * enumerate everything again.\n */\nexport function openDb(now = Date.now()): Database {\n mkdirSync(cacheDir(), { recursive: true });\n const path = cachePath(DB_FILE);\n\n let db: Database;\n try {\n db = new Database(path, { create: true });\n const check = db.query('PRAGMA integrity_check').get() as { integrity_check?: string } | null;\n if (check?.integrity_check !== undefined && check.integrity_check !== 'ok') {\n throw new Error(`integrity_check: ${check.integrity_check}`);\n }\n } catch (e) {\n throw quarantine(path, (e as Error).message, now);\n }\n\n db.run('PRAGMA journal_mode = WAL');\n for (const stmt of TABLES) db.run(stmt);\n migrate(db);\n for (const stmt of INDEXES) db.run(stmt);\n sweepExpired(db, now);\n return db;\n}\n\n/**\n * Additive migrations for stores created before a column existed. Kept\n * idempotent and additive so an older cache upgrades in place rather than\n * being discarded — discarding it would trigger a full re-sync, which is the\n * expensive failure on this platform.\n */\nfunction migrate(db: Database): void {\n const columns = db.query('PRAGMA table_info(records)').all() as { name: string }[];\n if (!columns.some((c) => c.name === 'textFold')) {\n db.run(\"ALTER TABLE records ADD COLUMN textFold TEXT NOT NULL DEFAULT ''\");\n }\n // Backfill any row that predates the column.\n const stale = db\n .query(\"SELECT urn, source, text FROM records WHERE textFold = '' AND text != ''\")\n .all() as {\n urn: string;\n source: string;\n text: string;\n }[];\n if (stale.length > 0) {\n const update = db.query('UPDATE records SET textFold = ? WHERE urn = ? AND source = ?');\n db.transaction(() => {\n for (const r of stale) update.run(fold(r.text), r.urn, r.source);\n })();\n }\n}\n\nfunction quarantine(path: string, reason: string, now: number): CacheCorrupt {\n const stamp = new Date(now).toISOString().replace(/[:.]/g, '-');\n const target = cachePath('quarantine', stamp, DB_FILE);\n try {\n mkdirSync(cachePath('quarantine', stamp), { recursive: true });\n renameSync(path, target);\n } catch {\n // Even if it cannot be moved, the caller must still refuse to proceed.\n }\n return new CacheCorrupt(\n `the local cache was unreadable and has been quarantined: ${reason}`,\n target,\n );\n}\n\n/**\n * Expire third-party bodies. The row survives as an identity stub so a re-fetch\n * is a VISIBLE choice — the budget can say \"14 of these 20 are re-fetches of\n * expired records\" instead of quietly charging for them again.\n */\nexport function sweepExpired(db: Database, now = Date.now()): number {\n const result = db.run(\n \"UPDATE records SET body = NULL, text = '', textFold = '' WHERE expiresAt IS NOT NULL AND expiresAt <= ? AND body IS NOT NULL\",\n [now],\n );\n return result.changes;\n}\n\nexport function upsert(\n db: Database,\n source: Source,\n rows: { urn: string; body: unknown; text: string }[],\n now = Date.now(),\n): { added: number; updated: number } {\n const expiresAt = source === 'third-party' ? now + THIRD_PARTY_TTL_MS : null;\n let added = 0;\n let updated = 0;\n\n const exists = db.query('SELECT 1 FROM records WHERE urn = ? AND source = ?');\n const write = db.query(\n `INSERT INTO records (urn, source, body, text, textFold, firstSeenAt, updatedAt, expiresAt)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(urn, source) DO UPDATE SET\n body = excluded.body, text = excluded.text, textFold = excluded.textFold,\n updatedAt = excluded.updatedAt, expiresAt = excluded.expiresAt`,\n );\n\n db.transaction(() => {\n for (const row of rows) {\n if (exists.get(row.urn, source) === null) added++;\n else updated++;\n write.run(\n row.urn,\n source,\n JSON.stringify(row.body),\n row.text,\n fold(row.text),\n now,\n now,\n expiresAt,\n );\n }\n })();\n\n return { added, updated };\n}\n\nexport function count(db: Database, source?: Source): number {\n const row =\n source === undefined\n ? (db.query('SELECT COUNT(*) AS n FROM records').get() as { n: number })\n : (db.query('SELECT COUNT(*) AS n FROM records WHERE source = ?').get(source) as {\n n: number;\n });\n return row.n;\n}\n\n/** Offline search. Substring match over the flattened text of each record. */\nexport function search(\n db: Database,\n query: string,\n opts: { sources?: Source[]; since?: number; limit?: number } = {},\n): Record_[] {\n const sources = opts.sources ?? ['connections', 'my-posts', 'third-party'];\n const placeholders = sources.map(() => '?').join(',');\n const params: (string | number)[] = [...sources];\n\n let sql = `SELECT * FROM records WHERE source IN (${placeholders}) AND body IS NOT NULL`;\n if (query !== '') {\n // Match on the folded column with a folded query, so \"kovary\" finds\n // \"Kőváry\" and vice versa.\n sql += ' AND textFold LIKE ?';\n params.push(`%${fold(query)}%`);\n }\n if (opts.since !== undefined) {\n sql += ' AND updatedAt >= ?';\n params.push(opts.since);\n }\n sql += ' ORDER BY updatedAt DESC LIMIT ?';\n params.push(opts.limit ?? 25);\n\n return db.query(sql).all(...params) as Record_[];\n}\n\nexport function urnsFor(db: Database, source: Source): Set<string> {\n const rows = db.query('SELECT urn FROM records WHERE source = ?').all(source) as {\n urn: string;\n }[];\n return new Set(rows.map((r) => r.urn));\n}\n\nexport function removeUrns(db: Database, source: Source, urns: string[]): number {\n if (urns.length === 0) return 0;\n const stmt = db.query('DELETE FROM records WHERE source = ? AND urn = ?');\n let removed = 0;\n db.transaction(() => {\n for (const urn of urns) removed += stmt.run(source, urn).changes;\n })();\n return removed;\n}\n\n// ─── Checkpoints ──────────────────────────────────────────────────────────────\n\nexport interface Checkpoint {\n source: string;\n lastSuccessfulAt: number;\n newestCreatedAt: number | null;\n headIds: string[];\n /** `snapshot-partial` where no ordering exists — never a fabricated watermark. */\n state: 'ok' | 'snapshot-partial';\n}\n\nexport function getCheckpoint(db: Database, source: Source): Checkpoint | undefined {\n const row = db.query('SELECT * FROM checkpoints WHERE source = ?').get(source) as\n | (Omit<Checkpoint, 'headIds'> & { headIds: string })\n | null;\n if (row === null) return undefined;\n return { ...row, headIds: JSON.parse(row.headIds) as string[] };\n}\n\nexport function setCheckpoint(db: Database, cp: Checkpoint): void {\n db.run(\n `INSERT INTO checkpoints (source, lastSuccessfulAt, newestCreatedAt, headIds, state)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(source) DO UPDATE SET\n lastSuccessfulAt = excluded.lastSuccessfulAt,\n newestCreatedAt = excluded.newestCreatedAt,\n headIds = excluded.headIds,\n state = excluded.state`,\n [cp.source, cp.lastSuccessfulAt, cp.newestCreatedAt, JSON.stringify(cp.headIds), cp.state],\n );\n}\n\nexport function purge(db: Database, scope: 'all' | 'third-party'): number {\n const result =\n scope === 'all'\n ? db.run('DELETE FROM records')\n : db.run(\"DELETE FROM records WHERE source = 'third-party'\");\n if (scope === 'all') db.run('DELETE FROM checkpoints');\n return result.changes;\n}\n","// ─── Local state store ────────────────────────────────────────────────────────\n//\n// Small, replaceable JSON state (the ledger, the cooldown, credentials\n// metadata) lives here. The research cache proper is SQLite and arrives in\n// Phase 4 — see docs/DESIGN.md §5.\n//\n// The rule that matters, and where we deliberately break with the family:\n//\n// never-throw is NOT never-fail.\n//\n// x-relay's store degrades a corrupt file to an empty object so a read never\n// crashes. That is right on X. Here it composes into a disaster: corrupt file →\n// empty cache → sync sees no prior state → full enumeration against the most\n// hostile platform in the research, triggered by a disk error. So a corrupt\n// file is quarantined and reported loudly. An empty result and a lost result\n// must be distinguishable on disk for exactly the same reason they must be\n// distinguishable in a parse.\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nexport function cacheDir(): string {\n return process.env.LNRELAY_CACHE_DIR ?? join(homedir(), '.lnrelay');\n}\n\nexport function cachePath(...parts: string[]): string {\n return join(cacheDir(), ...parts);\n}\n\nexport type LoadResult<T> =\n | { state: 'ok'; value: T }\n | { state: 'missing' }\n | { state: 'corrupt'; quarantinedTo: string; reason: string };\n\n/**\n * Read a JSON file. Never throws. A file that exists but cannot be parsed is\n * MOVED to `quarantine/` and reported as corrupt — never silently treated as\n * absent, because \"we lost your data\" and \"you have no data\" lead to opposite\n * and non-interchangeable actions.\n */\nexport function loadJson<T>(path: string): LoadResult<T> {\n if (!existsSync(path)) return { state: 'missing' };\n\n let raw: string;\n try {\n raw = readFileSync(path, 'utf-8');\n } catch (e) {\n return quarantine(path, `unreadable: ${(e as Error).message}`);\n }\n\n try {\n return { state: 'ok', value: JSON.parse(raw) as T };\n } catch (e) {\n return quarantine(path, `unparseable JSON: ${(e as Error).message}`);\n }\n}\n\nfunction quarantine(path: string, reason: string): LoadResult<never> {\n const stamp = new Date().toISOString().replace(/[:.]/g, '-');\n const target = cachePath('quarantine', stamp, path.split('/').pop() ?? 'file');\n try {\n mkdirSync(dirname(target), { recursive: true });\n renameSync(path, target);\n } catch {\n // If we cannot even move it, still report corrupt — the caller must refuse\n // to proceed either way.\n }\n return { state: 'corrupt', quarantinedTo: target, reason };\n}\n\n/**\n * Write JSON atomically: a temp file in the same directory, then rename. A\n * torn write leaves the previous good file intact rather than a truncated one.\n */\nexport function saveJson(path: string, value: unknown): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf-8', mode: 0o600 });\n renameSync(tmp, path);\n}\n","// ─── Rest.li 2.0 variables grammar ────────────────────────────────────────────\n//\n// LinkedIn's Voyager GraphQL endpoint does NOT take JSON variables. It takes\n// Rest.li 2.0's own tuple grammar:\n//\n// (key:value,key2:value2) object literal\n// List(a,b,c) array\n// a | b OR-group inside a single filter value\n//\n// nested to arbitrary depth. Example (verified, R3 §2):\n//\n// ?queryId=voyagerSearchDashClusters.<hash>&variables=(start:0,query:(keywords:foo,\n// queryParameters:List((key:resultType,value:List(PEOPLE)))))\n//\n// Every client in the 90-repo corpus string-templates this. That is why adding a\n// filter is a guessing game for them: an unescaped comma or paren in a user's\n// search term silently terminates a tuple early and changes what you asked for\n// without erroring. This module is the pure, tested alternative.\n\n/** A value expressible in the Rest.li variables grammar. */\nexport type RestliValue =\n | string\n | number\n | boolean\n | undefined\n | RestliValue[]\n | { [key: string]: RestliValue };\n\n/**\n * Characters that must be percent-encoded inside a scalar value. Two distinct\n * hazards, both silent:\n *\n * Grammar `( ) , : |` change the shape of the tuple. A keyword containing\n * a comma would split one value into two.\n * URL `& # + space %` corrupt the query string the tuple is spliced\n * into. Searching for \"tom & jerry\" would inject a second query\n * parameter, and LinkedIn would answer a question we never asked\n * — returning 200 with plausible results for the wrong query.\n *\n * `%` is listed first and handled first, so an already-percent-looking value is\n * escaped rather than double-decoded into something else.\n */\nconst ENCODED: Record<string, string> = {\n '%': '%25', // MUST be first — see below\n '(': '%28',\n ')': '%29',\n ',': '%2C',\n ':': '%3A',\n '|': '%7C',\n '&': '%26',\n '#': '%23',\n '+': '%2B',\n ' ': '%20',\n};\n\nconst RESERVED = /[%(),:|&#+ ]/g;\n\nfunction encodeScalar(value: string | number | boolean): string {\n if (typeof value !== 'string') return String(value);\n // A single pass over the string, replacing each reserved character with its\n // escape. Because it is one pass, the `%` introduced by an escape is never\n // itself re-escaped — which is what makes the `%` entry above safe.\n return value.replace(RESERVED, (c) => ENCODED[c] ?? c);\n}\n\nfunction encodeValue(value: RestliValue): string | undefined {\n if (value === undefined) return undefined;\n if (Array.isArray(value)) {\n const members = value.map(encodeValue).filter((m): m is string => m !== undefined);\n return `List(${members.join(',')})`;\n }\n if (typeof value === 'object') return encodeObject(value);\n return encodeScalar(value);\n}\n\nfunction encodeObject(obj: { [key: string]: RestliValue }): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(obj)) {\n const encoded = encodeValue(value);\n // An undefined value is omitted entirely — never emitted as the string\n // \"undefined\", which LinkedIn would treat as a real filter value.\n if (encoded !== undefined) parts.push(`${key}:${encoded}`);\n }\n return `(${parts.join(',')})`;\n}\n\n/** Encode a variables object into the Rest.li 2.0 grammar. */\nexport function encodeVariables(vars: { [key: string]: RestliValue }): string {\n return encodeObject(vars);\n}\n\n// ─── Composite URNs ───────────────────────────────────────────────────────────\n//\n// Voyager URNs are not always `urn:li:type:id`. Tuple forms appear inline:\n//\n// urn:li:fs_updateV2:(urn:li:activity:999,GROUP_FEED,EMPTY,DEFAULT,false)\n// urn:li:fsd_profilePositionGroup:(urn:li:fsd_profile:ABC,urn:li:fsd_company:(1,2))\n//\n// R3 §4 documents the reference implementation extracting the inner URN with\n// `split(\"(\")[1].split(\",\")[0]`. That is correct only until a member is itself a\n// tuple — and nested tuples do occur. A paren-aware split is barely more code\n// and does not have a silent failure mode.\n\nexport interface TupleUrn {\n /** The URN's own namespace, e.g. `fs_updateV2`. */\n namespace: string;\n /** Top-level members, with nested tuples left intact. */\n members: string[];\n}\n\n/**\n * Parse a composite (tuple-form) URN. Returns null when the URN is not\n * composite, or when its parentheses are unbalanced — an unbalanced URN is\n * malformed data, and guessing at its members would invent structure.\n */\nexport function parseTupleUrn(urn: string): TupleUrn | null {\n const open = urn.indexOf(':(');\n if (open === -1 || !urn.endsWith(')')) return null;\n\n const namespace = urn.slice(0, open).split(':').pop();\n if (namespace === undefined || namespace === '') return null;\n\n const body = urn.slice(open + 2, -1);\n const members: string[] = [];\n let depth = 0;\n let current = '';\n\n for (const char of body) {\n if (char === '(') depth++;\n else if (char === ')') depth--;\n\n if (depth < 0) return null; // closed one we never opened\n\n if (char === ',' && depth === 0) {\n members.push(current);\n current = '';\n } else {\n current += char;\n }\n }\n if (depth !== 0) return null; // opened one we never closed\n\n members.push(current);\n return { namespace, members };\n}\n\n/**\n * The identity a composite URN wraps — its first member. A non-composite URN is\n * returned unchanged, so this is safe to call on any URN.\n */\nexport function innerUrn(urn: string): string {\n const parsed = parseTupleUrn(urn);\n const first = parsed?.members[0];\n return first ?? urn;\n}\n\n// ─── Namespace collapse ───────────────────────────────────────────────────────\n//\n// R3 §4: LinkedIn is mid-migration from `fs_*` (legacy) to `fsd_*` (dash), and\n// three profile URN forms coexist in live responses — the reference client\n// literally string-replaces between them. This is the same legacy/hoisted split\n// that cost x-relay real data, and the fix is the same: collapse to one identity\n// so dedupe and cross-referencing are structural rather than best-effort.\n//\n// Only mappings we have direct evidence for are listed. An unknown namespace\n// passes through untouched — inventing a mapping would silently merge two\n// distinct entities, which is worse than leaving them separate.\nconst NAMESPACE_ALIASES: Record<string, string> = {\n fs_miniProfile: 'fsd_profile',\n fs_profile: 'fsd_profile',\n};\n\n/**\n * Canonicalise a URN: unwrap composite forms to their inner identity, then\n * collapse known legacy namespace aliases onto their dash equivalent.\n * Idempotent.\n */\nexport function canonicalUrn(urn: string): string {\n const inner = innerUrn(urn);\n const parts = inner.split(':');\n // urn:li:<namespace>:<id...>\n const namespace = parts[2];\n if (namespace === undefined) return inner;\n\n const alias = NAMESPACE_ALIASES[namespace];\n if (alias === undefined) return inner;\n\n parts[2] = alias;\n return parts.join(':');\n}\n","// ─── Presentation ─────────────────────────────────────────────────────────────\n//\n// Pure shaping of Voyager entities into flat, readable rows. No I/O.\n//\n// LinkedIn wraps essentially every piece of display text in a TextViewModel\n// (`{text, textDirection, attributesV2, $type}`), sometimes twice — a post's\n// commentary is `commentary.text.text`. Raw entities are therefore both huge\n// and unreadable, so commands shape by default and keep the raw node behind\n// `--raw` for when a shape has drifted and you need to see what actually came\n// back.\n//\n// Every shaper is defensive: an unrecognised entity still reports its `$type`\n// rather than returning nothing, because the parser deliberately lets unknown\n// types through and silently blanking them here would undo that.\n\nimport type { Entity } from './engine/parse.ts';\nimport { innerUrn } from './engine/restli.ts';\n\nexport interface Shaped {\n type?: string;\n urn?: string;\n name?: string;\n headline?: string;\n location?: string;\n url?: string;\n text?: string;\n author?: string;\n posted?: string;\n [key: string]: unknown;\n}\n\n/** Pull the string out of a TextViewModel, at either nesting depth. */\nfunction text(value: unknown): string | undefined {\n if (typeof value === 'string') return value.trim() || undefined;\n if (value === null || typeof value !== 'object') return undefined;\n\n const node = value as { text?: unknown };\n if (typeof node.text === 'string') return node.text.trim() || undefined;\n // commentary.text.text — the doubly-wrapped case.\n if (node.text !== null && typeof node.text === 'object') return text(node.text);\n return undefined;\n}\n\nfunction typeOf(node: Entity): string | undefined {\n const t = node.$type ?? (node as { _type?: unknown })._type;\n return typeof t === 'string' ? t : undefined;\n}\n\n/** Drop tracking query strings, which differ per request for identical results. */\nfunction cleanUrl(url: unknown): string | undefined {\n if (typeof url !== 'string' || url === '') return undefined;\n const cut = url.indexOf('?');\n return cut === -1 ? url : url.slice(0, cut);\n}\n\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const key of Object.keys(obj)) {\n if (obj[key] === undefined) delete obj[key];\n }\n return obj;\n}\n\nfunction shapeSearchRow(node: Entity): Shaped {\n const entityUrn = typeof node.entityUrn === 'string' ? node.entityUrn : undefined;\n return defined({\n type: typeOf(node),\n // The entity urn is composite — (profileUrn, SEARCH_SRP, DEFAULT) — and the\n // member identity is its first member.\n urn: entityUrn === undefined ? undefined : innerUrn(entityUrn),\n name: text(node.title),\n headline: text(node.primarySubtitle),\n location: text(node.secondarySubtitle),\n url: cleanUrl(node.navigationUrl),\n });\n}\n\n/**\n * Engagement counts are two references away from the post:\n *\n * UpdateV2 --*socialDetail--> SocialDetail --*totalSocialActivityCounts--> counts\n *\n * The parser drops both intermediate nodes as decorations, which is correct —\n * they are not content — so without the index a post has no like or comment\n * count at all. Engagement is the main ranking signal for research, so it is\n * worth the two hops.\n *\n * The same SocialDetail also carries the post's **ugcPost** URN, which is NOT\n * the activity URN in `updateMetadata` (verified live: activity …8686600193 vs\n * ugcPost …7814144000). Reactions and comments key off the ugcPost form, so\n * this is where that mapping comes from — it cannot be derived.\n */\n/**\n * A post's own urn, from whichever of the two live shapes it is.\n *\n * `com.linkedin.voyager.feed.render.UpdateV2` carries it in `updateMetadata`.\n * Its dash sibling `com.linkedin.voyager.dash.feed.Update` — what `myPosts`\n * returns — has no `updateMetadata` at all, and hides the activity urn in the\n * first member of a composite entityUrn tuple:\n *\n * urn:li:fsd_update:(urn:li:activity:662…,MEMBER_SHARES,DEBUG_REASON,…)\n *\n * Handling only the first shape made every post from `my-posts` arrive with no\n * urn, which left `delete` unable to identify the post it was about to destroy.\n */\nfunction postUrn(node: Entity): string | undefined {\n const meta = node.updateMetadata as { urn?: unknown } | undefined;\n if (typeof meta?.urn === 'string') return meta.urn;\n\n const entityUrn = node.entityUrn;\n if (typeof entityUrn !== 'string') return undefined;\n return /urn:li:(activity|ugcPost|share):\\d+/.exec(entityUrn)?.[0];\n}\n\nfunction shapePost(node: Entity, index?: Map<string, Entity>): Shaped {\n const actor = node.actor as { name?: unknown; subDescription?: unknown } | undefined;\n const urn = postUrn(node);\n\n const social = deref(node, '*socialDetail', index);\n const counts =\n social === undefined ? undefined : deref(social, '*totalSocialActivityCounts', index);\n\n return defined({\n type: typeOf(node),\n urn,\n threadUrn: typeof social?.urn === 'string' ? social.urn : undefined,\n author: text(actor?.name),\n // `text()` already trims; LinkedIn pads these with trailing spaces.\n posted: text(actor?.subDescription),\n text: text(node.commentary),\n likes: numberOf(counts?.numLikes),\n comments: numberOf(counts?.numComments),\n shares: numberOf(counts?.numShares ?? social?.totalShares),\n url: urn === undefined ? undefined : `https://www.linkedin.com/feed/update/${urn}/`,\n });\n}\n\nfunction numberOf(value: unknown): number | undefined {\n return typeof value === 'number' ? value : undefined;\n}\n\n/**\n * Resolve a `*`-prefixed URN reference on a node against the side-table.\n * LinkedIn returns location, current position and education as references, so\n * a profile without its index is mostly pointers.\n */\nfunction deref(\n node: Entity,\n key: string,\n index: Map<string, Entity> | undefined,\n): Entity | undefined {\n if (index === undefined) return undefined;\n const ref = node[key];\n if (typeof ref === 'string') return index.get(ref);\n if (ref === undefined) return undefined;\n if (ref !== null && typeof ref === 'object') {\n for (const [k, v] of Object.entries(ref as Record<string, unknown>)) {\n if (k.startsWith('*') && typeof v === 'string') return index.get(v);\n }\n }\n return undefined;\n}\n\n/**\n * Shape a full profile, resolving the references LinkedIn leaves dangling.\n *\n * Note the honest gap: none of the observed projections returns\n * firstName/lastName/publicIdentifier, so a looked-up profile has no name.\n * The caller supplied the identifier, so this is a real limit rather than a\n * silent one — see src/engine/contracts.ts.\n */\nexport function shapeProfile(node: Entity, index?: Map<string, Entity>): Shaped {\n const base = shapeMember(node);\n const geo = deref(node, 'geoLocation', index);\n const position =\n deref(node, 'profileTopPosition', index) ?? firstOfType(index, 'profile.Position');\n const education =\n deref(node, 'profileTopEducation', index) ?? firstOfType(index, 'profile.Education');\n\n return defined({\n ...base,\n location: text(geo?.defaultLocalizedName) ?? text(geo?.localizedName),\n title: text(position?.title),\n company: text(position?.companyName),\n school: text(education?.schoolName),\n });\n}\n\nfunction firstOfType(index: Map<string, Entity> | undefined, suffix: string): Entity | undefined {\n if (index === undefined) return undefined;\n for (const node of new Set(index.values())) {\n if (String(node.$type ?? '').endsWith(suffix)) return node;\n }\n return undefined;\n}\n\nfunction shapeMember(node: Entity): Shaped {\n const first = text(node.firstName);\n const last = text(node.lastName);\n const publicId = text(node.publicIdentifier) ?? text(node.publicId);\n const name = [first, last].filter(Boolean).join(' ');\n return defined({\n type: typeOf(node),\n urn: typeof node.entityUrn === 'string' ? node.entityUrn : undefined,\n publicId,\n name: name === '' ? undefined : name,\n headline: text(node.headline) ?? text(node.occupation),\n url: publicId === undefined ? undefined : `https://www.linkedin.com/in/${publicId}/`,\n });\n}\n\n/**\n * A comment. The author lives under `commenter` as a lockup (title/subtitle/\n * navigationUrl), and the comment's own like count is another two-hop\n * dereference through its socialDetail — same chain as a post.\n */\nfunction shapeComment(node: Entity, index?: Map<string, Entity>): Shaped {\n const commenter = node.commenter as Entity | undefined;\n const social = deref(node, '*socialDetail', index);\n const counts =\n social === undefined ? undefined : deref(social, '*totalSocialActivityCounts', index);\n\n return defined({\n type: typeOf(node),\n urn: typeof node.urn === 'string' ? node.urn : undefined,\n author: text(commenter?.title),\n headline: text(commenter?.subtitle),\n authorUrl: cleanUrl(commenter?.navigationUrl),\n text: text(node.comment) ?? text(node.commentary),\n likes: numberOf(counts?.numLikes),\n postedAt:\n typeof node.createdAt === 'number' ? new Date(node.createdAt).toISOString() : undefined,\n edited: node.edited === true ? true : undefined,\n url: cleanUrl(node.permalink),\n });\n}\n\n/** A reactor — who reacted, and with which reaction. */\nfunction shapeReaction(node: Entity, index?: Map<string, Entity>): Shaped {\n const lockup = node.reactorLockup as Entity | undefined;\n const actorUrn = typeof node.actorUrn === 'string' ? node.actorUrn : undefined;\n const profile = actorUrn === undefined ? undefined : index?.get(actorUrn);\n\n return defined({\n type: typeOf(node),\n urn: actorUrn,\n name: text(lockup?.title),\n headline: text(lockup?.subtitle) ?? text(profile?.headline),\n reaction: typeof node.reactionType === 'string' ? node.reactionType : undefined,\n url: cleanUrl(lockup?.navigationUrl),\n });\n}\n\n/** Shape one entity into a flat row, dispatching on its type. */\nexport function shapeEntity(node: Entity, index?: Map<string, Entity>): Shaped {\n try {\n const t = (typeOf(node) ?? '').toLowerCase();\n if (t.includes('entityresultviewmodel')) return shapeSearchRow(node);\n // Order matters: Comment and Reaction are checked before the broader\n // 'update' and 'profile' fragments, which would otherwise swallow them.\n if (t.endsWith('social.comment')) return shapeComment(node, index);\n if (t.endsWith('social.reaction')) return shapeReaction(node, index);\n if (t.includes('update')) return shapePost(node, index);\n if (t.includes('profile')) return shapeMember(node);\n\n // Unrecognised: report the type and make a best effort, so a new shape\n // shows up as thin data rather than as nothing.\n return defined({\n type: typeOf(node),\n urn: typeof node.entityUrn === 'string' ? node.entityUrn : undefined,\n name: text(node.title) ?? text(node.name),\n text: text(node.commentary) ?? text(node.text),\n });\n } catch {\n return defined({ type: typeOf(node) });\n }\n}\n\nexport function shapeAll(items: Entity[], index?: Map<string, Entity>): Shaped[] {\n return items.map((node) => shapeEntity(node, index));\n}\n\n// ─── Output modes ─────────────────────────────────────────────────────────────\n//\n// `--fields` and `--compact` were advertised in the command registry long\n// before they existed — a documented promise the tool did not keep. They exist\n// now, and tests/skill.test.ts asserts that every flag a usage string\n// advertises is actually parsed, so the same drift cannot recur silently.\n//\n// Both are for the same problem: a shaped row is still ~8 keys of JSON, and an\n// agent ranking 25 search results does not need all of them in its context.\n\n/**\n * Keep only the named keys, in the order named. A key no row carries is\n * omitted rather than emitted as `undefined` — a field the user misspelled\n * should not become a column of nulls that looks like missing data.\n */\nexport function project<T extends Record<string, unknown>>(\n rows: T[],\n spec: string,\n): Record<string, unknown>[] {\n const keys = spec\n .split(',')\n .map((k) => k.trim())\n .filter((k) => k !== '');\n if (keys.length === 0) return rows;\n\n return rows.map((row) => {\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n if (row[key] !== undefined) out[key] = row[key];\n }\n return out;\n });\n}\n\n/** Fields to lead with, in preference order — most identifying first. */\nconst LEAD = ['name', 'author', 'title'];\nconst DETAIL = ['headline', 'text', 'location', 'company', 'posted', 'reaction'];\n\n/**\n * One flat line per row. Reduces a page of search results from kilobytes of\n * JSON to something scannable, without losing what a ranking decision needs.\n */\nexport function compactRows(rows: Record<string, unknown>[]): string[] {\n return rows.map((row) => {\n const parts: string[] = [];\n\n for (const key of LEAD) {\n const v = row[key];\n if (typeof v === 'string' && v !== '') {\n parts.push(v);\n break;\n }\n }\n for (const key of DETAIL) {\n const v = row[key];\n if (typeof v === 'string' && v !== '') parts.push(v);\n }\n\n const counts = ['likes', 'comments']\n .map((k) => (typeof row[k] === 'number' ? `${row[k]} ${k}` : undefined))\n .filter((v): v is string => v !== undefined);\n parts.push(...counts);\n\n // A row with nothing human-readable still has to identify itself.\n if (parts.length === 0) {\n const urn = row.urn ?? row.type;\n if (typeof urn === 'string') parts.push(urn);\n }\n\n // One row, one line — a newline in a post body would break the format.\n return parts.join(' · ').replace(/\\s*\\n\\s*/g, ' ');\n });\n}\n","import type { Envelope, Err, Ok } from './types.ts';\n\nexport function ok<T>(command: string, data: T): Ok<T> {\n return { ok: true, command, data };\n}\n\nexport function err(\n command: string,\n code: string,\n message: string,\n hint?: string,\n status?: number,\n retryAfterMs?: number,\n): Err {\n const error: Err['error'] = { code, message };\n if (hint !== undefined) error.hint = hint;\n if (status !== undefined) error.status = status;\n if (retryAfterMs !== undefined) error.retryAfterMs = retryAfterMs;\n return { ok: false, command, error };\n}\n\nexport function toJson(envelope: unknown): string {\n return JSON.stringify(envelope, null, 2);\n}\n\n// ─── Error taxonomy ───────────────────────────────────────────────────────────\n\nexport const ERROR_CODES = [\n // Raised before any network call is made.\n 'INVALID_INPUT',\n 'UNKNOWN_COMMAND',\n 'CONFIRMATION_REQUIRED',\n 'BUDGET_EXHAUSTED',\n 'COOLDOWN_ACTIVE',\n 'CACHE_CORRUPT',\n 'NOT_IMPLEMENTED',\n // Raised from a response.\n 'AUTH_FAILED',\n 'RATE_LIMITED',\n 'REQUEST_DENIED', // HTTP 999 — LinkedIn's non-standard bot block\n 'CHALLENGE_DETECTED',\n 'SCHEMA_DRIFT',\n 'NOT_FOUND',\n 'FETCH_FAILED',\n 'FETCH_TIMEOUT',\n] as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n/**\n * Whether a failure may be retried automatically.\n *\n * Almost everything is `false`, and that is the point. On LinkedIn a 429 is the\n * warning shot on a documented escalation ladder — retrying into it is the\n * mechanism by which a throttle becomes a restriction. A `retryAfterMs` is\n * information to print for a human, never permission for the process to try\n * again. The single exception is a timeout where no response was received at\n * all, which carries no signal about our standing with LinkedIn.\n *\n * This is a deliberate break with x-relay, which retries 429 three times. That\n * is correct on a platform where the worst case is a temporary block.\n */\nexport function isRetryable(code: ErrorCode | string): boolean {\n return code === 'FETCH_TIMEOUT';\n}\n\n/** 0 success · 1 command error · 2 unknown command. */\nexport function exitCodeFor(envelope: Envelope): number {\n if (envelope.ok) return 0;\n return envelope.error.code === 'UNKNOWN_COMMAND' ? 2 : 1;\n}\n","// Cache-backed commands. These make no network call at all — after a research\n// session, repeat lookups are free, which is the whole point of keeping a local\n// store on a platform where every request is rationed.\n\nimport {\n CacheCorrupt,\n count,\n getCheckpoint,\n openDb,\n purge as purgeDb,\n type Source,\n search as searchDb,\n upsert,\n} from '../cache/db.ts';\nimport { compactRows, project, type Shaped } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\n\nconst SOURCES: Source[] = ['connections', 'my-posts', 'third-party'];\n\n/** Turn a CacheCorrupt into an envelope; rethrow anything else. */\nfunction corruptEnvelope(command: string, e: unknown): Envelope {\n if (e instanceof CacheCorrupt) {\n return err(\n command,\n 'CACHE_CORRUPT',\n e.message,\n `Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as an empty one — that would ` +\n 'trigger a full re-sync against LinkedIn. Inspect it, then re-run.',\n );\n }\n throw e;\n}\n\nexport interface LocalOpts {\n compact?: boolean;\n fields?: string;\n}\n\n/** The cache path honours the same output flags as the live path. */\nfunction render(rows: Record<string, unknown>[], opts: LocalOpts): unknown[] {\n if (opts.compact === true) return compactRows(rows);\n if (opts.fields !== undefined && opts.fields !== '') return project(rows, opts.fields);\n return rows;\n}\n\nexport function runLocal(\n query: string | undefined,\n sources: string | undefined,\n since: string | undefined,\n limit: number,\n opts: LocalOpts = {},\n): Envelope {\n const requested = sources?.split(',').map((s) => s.trim()) ?? SOURCES;\n const invalid = requested.filter((s) => !SOURCES.includes(s as Source));\n if (invalid.length > 0) {\n return err(\n 'local',\n 'INVALID_INPUT',\n `unknown source(s): ${invalid.join(', ')}`,\n `valid sources: ${SOURCES.join(', ')}`,\n );\n }\n\n let sinceMs: number | undefined;\n if (since !== undefined) {\n const parsed = Date.parse(since);\n if (Number.isNaN(parsed)) {\n return err('local', 'INVALID_INPUT', `could not parse --since '${since}'`, 'use YYYY-MM-DD');\n }\n sinceMs = parsed;\n }\n\n try {\n const db = openDb();\n const rows = searchDb(db, query ?? '', {\n sources: requested as Source[],\n ...(sinceMs === undefined ? {} : { since: sinceMs }),\n limit,\n });\n const total = count(db);\n\n const shaped = rows.map((r) => ({\n ...(JSON.parse(r.body ?? '{}') as Shaped),\n source: r.source,\n cachedAt: new Date(r.updatedAt).toISOString(),\n }));\n\n return ok('local', {\n items: render(shaped, opts),\n meta: {\n returnedCount: rows.length,\n cachedTotal: total,\n sources: requested,\n // An empty cache is not an empty LinkedIn — say which one this is.\n note:\n total === 0\n ? 'The local cache is empty. Run a read command with --retain, or sync a source, before searching offline.'\n : undefined,\n },\n });\n } catch (e) {\n return corruptEnvelope('local', e);\n }\n}\n\n/**\n * `connections` and `my-posts` are the same offline read as `local`, with the\n * source pinned. They exist as separate commands because that is how a user\n * thinks about their own data — `--sync` fills them, they read from cache.\n */\nexport function runSourceRead(\n command: 'connections' | 'my-posts',\n query: string | undefined,\n limit: number,\n opts: LocalOpts = {},\n): Envelope {\n const result = runLocal(query, command, undefined, limit, opts);\n if (!result.ok) return result;\n const data = result.data as Record<string, unknown>;\n const meta = data.meta as Record<string, unknown>;\n if ((meta.cachedTotal as number) === 0 || (meta.returnedCount as number) === 0) {\n meta.note = `Nothing cached for '${command}'. Run \\`lnrelay sync ${command}\\` first — this command reads the local cache and makes no network call.`;\n }\n return ok(command, data);\n}\n\nexport function runPurge(scope: string | undefined, confirmed: boolean): Envelope {\n const target = scope === 'all' ? 'all' : 'third-party';\n\n if (!confirmed) {\n try {\n const db = openDb();\n return err(\n 'purge',\n 'CONFIRMATION_REQUIRED',\n `would delete ${target === 'all' ? count(db) : count(db, 'third-party')} records (${target})`,\n 'Re-run with --confirm. This only touches local files; it never contacts LinkedIn.',\n );\n } catch (e) {\n return corruptEnvelope('purge', e);\n }\n }\n\n try {\n const db = openDb();\n const removed = purgeDb(db, target);\n return ok('purge', { scope: target, removed, remaining: count(db) });\n } catch (e) {\n return corruptEnvelope('purge', e);\n }\n}\n\nexport function runCacheStatus(): Envelope {\n try {\n const db = openDb();\n return ok('cache-status', {\n total: count(db),\n bySource: Object.fromEntries(SOURCES.map((s) => [s, count(db, s)])),\n checkpoints: Object.fromEntries(SOURCES.map((s) => [s, getCheckpoint(db, s) ?? null])),\n retention:\n 'Third-party records expire 30 days after capture; the body is deleted and an identity ' +\n 'stub remains so a re-fetch is a visible choice. Owner data never expires.',\n });\n } catch (e) {\n return corruptEnvelope('cache-status', e);\n }\n}\n\n/**\n * Retain shaped rows from a live read. Opt-in (`--retain`) rather than\n * automatic: caching every profile you glance at recreates a personal data\n * lake, which is exactly the shape the risk research warns against.\n */\nexport type RetainResult = { added: number; updated: number } | { skipped: string };\n\nexport function retain(source: Source, items: Shaped[]): RetainResult {\n const rows = items\n .filter((i) => typeof i.urn === 'string' && i.urn !== '')\n .map((i) => ({\n urn: i.urn as string,\n body: i,\n text: [i.name, i.headline, i.location, i.text, i.author, i.company, i.title]\n .filter((v) => typeof v === 'string')\n .join(' '),\n }));\n if (rows.length === 0) return { skipped: 'no items carried a urn to key on' };\n\n try {\n return upsert(openDb(), source, rows);\n } catch (e) {\n // Retention never fails the read the user actually asked for — but it says\n // WHY it did nothing. Returning a silent null here cost real debugging time\n // once already.\n return { skipped: (e as Error).message };\n }\n}\n","// Progress reporting for long-running / multi-step commands.\n//\n// The hard invariant: stdout carries ONLY the final JSON envelope. Progress is\n// human-facing chatter, so it goes to STDERR (never stdout) and is silenced by\n// --quiet. The write sink is injectable purely so tests can capture it without\n// spying on process.stderr.\n\nexport type ProgressReporter = (msg: string) => void;\n\n/**\n * Build a progress reporter. When `quiet` is true it drops every message;\n * otherwise it writes `msg + '\\n'` to stderr (or the injected `write` sink).\n */\nexport function progressReporter(\n quiet: boolean,\n write: (s: string) => void = (s) => {\n process.stderr.write(s);\n },\n): ProgressReporter {\n return (msg: string) => {\n if (!quiet) write(`${msg}\\n`);\n };\n}\n","// ─── Spend accounting and the circuit breaker ─────────────────────────────────\n//\n// Two structural safety mechanisms live here, both pure (a clock is always\n// injected, never read):\n//\n// 1. Permits. `client` cannot be called without a `Permit`, and `spend()` is\n// the only thing that can make one. \"Issue a network call without\n// accounting for it\" is therefore a compile error rather than a\n// code-review norm. Redirects, pagination continuations and contract\n// discovery all consume permits too — otherwise the traffic easiest to\n// forget is exactly the traffic that escapes accounting.\n//\n// 2. The cooldown. A FILE, not process state. A CLI is a swarm of\n// short-lived processes, so an in-memory breaker protects nothing: the\n// next invocation would start clean and hammer straight back into the\n// throttle that opened it.\n//\n// About the numbers below: the field research swept 364 posts looking for\n// corroborated rate ceilings and found essentially none — one secondhand vendor\n// figure. So every cap is labelled with where it actually came from, and\n// `lnrelay budget` prints that label. None of them is `measured`, because we\n// have measured nothing. They are starting knobs, not LinkedIn facts.\n\nimport type { CapProvenance } from '../types.ts';\n\nconst HOUR = 3_600_000;\nconst DAY = 86_400_000;\n\nexport type SpendClass = 'profile' | 'search' | 'page' | 'write' | 'global';\n\nexport interface Cap {\n perDay: number;\n provenance: CapProvenance;\n note: string;\n}\n\nexport const CAPS: Record<SpendClass, Cap> = {\n profile: {\n perDay: 30,\n provenance: 'vendor-lore',\n note: \"transplanted from jjuanrivvera/linkedin-cli's job-detail cap\",\n },\n search: { perDay: 25, provenance: 'guessed', note: 'no corroborated figure exists' },\n page: { perDay: 60, provenance: 'guessed', note: 'thread/feed pagination' },\n write: {\n // Raised from 10 on 2026-08-14 by the owner's explicit decision, after 10\n // blocked ordinary development on a tool whose writes are the point — a\n // single test round of comment, reply and two deletes exceeded a whole day.\n //\n // Still a GUESS, and still below the weakly-reported ~20/day connection\n // lore. Nothing here has ever been measured against LinkedIn, and the\n // research's strongest finding stands: cadence triggers restrictions more\n // reliably than volume, and this cap does not pace anything — the client's\n // jittered 3-15s gap does. Treat a raised ceiling as more room to be\n // careful in, not permission to burst.\n perDay: 25,\n provenance: 'guessed',\n note: 'raised from 10 for development; still below the ~20/day connection lore per action type',\n },\n global: { perDay: 250, provenance: 'guessed', note: 'all classes combined' },\n};\n\n/** Minimum gap between any two calls, before jitter. */\nexport const MIN_GAP_MS = 3_000;\n\n// ─── Permits ──────────────────────────────────────────────────────────────────\n\n/**\n * Proof that a call was accounted for. The brand is unexported, so `spend()` is\n * the only thing in the program that can produce one.\n */\nexport interface Permit {\n readonly __brand: unique symbol;\n class: SpendClass;\n issuedAt: number;\n}\n\nexport interface Ledger {\n /** Epoch-ms timestamps of each spend, keyed by class. */\n spends: Record<string, number[]>;\n}\n\nexport function emptyLedger(): Ledger {\n return { spends: {} };\n}\n\nexport interface BudgetError {\n code: 'BUDGET_EXHAUSTED';\n message: string;\n hint: string;\n}\n\nexport type SpendResult = { permit: Permit; ledger: Ledger } | { error: BudgetError };\n\nfunction within(times: number[] | undefined, now: number, window: number): number[] {\n if (times === undefined) return [];\n return times.filter((t) => now - t < window);\n}\n\nfunction allSpends(ledger: Ledger, now: number): number[] {\n return Object.values(ledger.spends).flatMap((times) => within(times, now, DAY));\n}\n\n/**\n * Account for one intended call. Returns a permit and the updated ledger, or a\n * refusal — and a refusal charges nothing, so a denied call never consumes\n * budget.\n */\nexport function spend(ledger: Ledger, cls: SpendClass, now: number): SpendResult {\n const recent = allSpends(ledger, now);\n\n const last = recent.length > 0 ? Math.max(...recent) : undefined;\n if (last !== undefined && now - last < MIN_GAP_MS) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `minimum gap of ${MIN_GAP_MS}ms between calls not met`,\n hint: 'requests are paced deliberately; wait and retry',\n },\n };\n }\n\n if (recent.length >= CAPS.global.perDay) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `global daily cap of ${CAPS.global.perDay} calls reached`,\n hint: 'resets on a rolling 24h window; see `lnrelay budget`',\n },\n };\n }\n\n const cap = CAPS[cls];\n const forClass = within(ledger.spends[cls], now, DAY);\n if (forClass.length >= cap.perDay) {\n return {\n error: {\n code: 'BUDGET_EXHAUSTED',\n message: `daily cap of ${cap.perDay} reached for '${cls}'`,\n hint: `cap provenance: ${cap.provenance} (${cap.note}). See \\`lnrelay budget\\`.`,\n },\n };\n }\n\n return {\n permit: { class: cls, issuedAt: now } as Permit,\n ledger: { spends: { ...ledger.spends, [cls]: [...forClass, now] } },\n };\n}\n\nexport interface BudgetSummary {\n class: SpendClass;\n spentInWindow: number;\n cap: number;\n remaining: number;\n capProvenance: CapProvenance;\n warning?: string;\n}\n\nexport function summarise(ledger: Ledger, cls: SpendClass, now: number): BudgetSummary {\n const cap = CAPS[cls];\n const spent =\n cls === 'global' ? allSpends(ledger, now).length : within(ledger.spends[cls], now, DAY).length;\n const remaining = Math.max(0, cap.perDay - spent);\n\n const summary: BudgetSummary = {\n class: cls,\n spentInWindow: spent,\n cap: cap.perDay,\n remaining,\n capProvenance: cap.provenance,\n };\n if (remaining / cap.perDay < 0.25) {\n summary.warning = `only ${remaining} of ${cap.perDay} '${cls}' calls left in this 24h window — consider stopping`;\n }\n return summary;\n}\n\n// ─── The circuit breaker ──────────────────────────────────────────────────────\n\nexport type CooldownReason = 'RATE_LIMITED' | 'REQUEST_DENIED' | 'CHALLENGE_DETECTED';\n\nexport interface Cooldown {\n reason: CooldownReason;\n since: number;\n /** Epoch-ms when it lifts, or null for indefinite. */\n until: number | null;\n clearRequires: 'time' | 'human';\n}\n\n/**\n * Open a cooldown. The durations escalate with how bad the signal is: a 429 is\n * a throttle, a 999 is a network-layer bot block that lifts only as traffic\n * normalises, and a challenge means LinkedIn wants to see a human — so only a\n * human can clear it, via `lnrelay budget --reset-cooldown --confirm`.\n */\nexport function openCooldown(reason: CooldownReason, now: number): Cooldown {\n if (reason === 'CHALLENGE_DETECTED') {\n return { reason, since: now, until: null, clearRequires: 'human' };\n }\n const duration = reason === 'REQUEST_DENIED' ? 6 * HOUR : HOUR;\n return { reason, since: now, until: now + duration, clearRequires: 'time' };\n}\n\nexport function activeCooldown(cooldown: Cooldown | null, now: number): boolean {\n if (cooldown === null) return false;\n if (cooldown.until === null) return true;\n return now < cooldown.until;\n}\n","// ─── Session and headers ──────────────────────────────────────────────────────\n//\n// Verified live on 2026-08-01: the auth surface is exactly two cookies. `li_at`\n// is the session; `JSESSIONID` exists pre-login too, so its presence alone\n// means nothing. The `csrf-token` header is JSESSIONID with quotes stripped —\n// a derivation, not a second secret.\n//\n// Everything the research listed as a \"cargo-cult candidate\" — x-li-track,\n// x-li-page-instance, x-li-deviceId, li_rm, bcookie, bscookie — was confirmed\n// unnecessary. We do not send them. An unexplained header is as likely to be a\n// fingerprint mismatch as a fix.\n//\n// The User-Agent is stored with the session rather than hardcoded, because a\n// stale UA measurably raises the challenge rate; hardcoding is exactly how the\n// reference client ended up shipping a Chrome 83 string into 2026.\n\nexport interface Session {\n liAt: string;\n jsessionId: string;\n userAgent: string;\n /** ISO date the cookies were minted, so `doctor` can flag staleness. */\n capturedAt: string;\n /** The owner this session is sealed to. A mismatch opens the circuit. */\n ownerUrn?: string;\n}\n\nexport function csrfToken(jsessionId: string): string {\n return jsessionId.replace(/\"/g, '');\n}\n\n/** The complete, minimal header set for an authenticated Voyager call. */\nexport function buildHeaders(session: Session): Record<string, string> {\n return {\n cookie: `li_at=${session.liAt}; JSESSIONID=${session.jsessionId}`,\n 'csrf-token': csrfToken(session.jsessionId),\n 'x-restli-protocol-version': '2.0.0',\n accept: 'application/vnd.linkedin.normalized+json+2.1',\n 'x-li-lang': 'en_US',\n 'user-agent': session.userAgent,\n };\n}\n\nexport interface SessionCheck {\n ok: boolean;\n detail: string;\n}\n\n/**\n * Validate a session's SHAPE without touching the network, and without ever\n * revealing a credential value — lengths only, so `doctor` output is safe to\n * paste into a bug report.\n */\nexport function checkSession(session: Partial<Session> | null): SessionCheck {\n if (session === null || session.liAt === undefined || session.liAt === '') {\n return { ok: false, detail: 'no li_at — run `lnrelay login`' };\n }\n if (session.jsessionId === undefined || session.jsessionId === '') {\n return { ok: false, detail: 'no JSESSIONID — run `lnrelay login`' };\n }\n if (session.userAgent === undefined || session.userAgent === '') {\n return { ok: false, detail: 'no user-agent recorded with the session' };\n }\n const age = sessionAgeDays(session.capturedAt);\n const staleness =\n age !== undefined && age > 90 ? `; UA is ${age} days old, consider re-login` : '';\n return {\n ok: true,\n detail: `li_at present (len ${session.liAt.length}); JSESSIONID present (len ${session.jsessionId.length})${staleness}`,\n };\n}\n\nexport function sessionAgeDays(\n capturedAt: string | undefined,\n now = Date.now(),\n): number | undefined {\n if (capturedAt === undefined) return undefined;\n const then = Date.parse(capturedAt);\n if (Number.isNaN(then)) return undefined;\n return Math.floor((now - then) / 86_400_000);\n}\n","// ─── Response classification ──────────────────────────────────────────────────\n//\n// Every response passes through here BEFORE any parsing. That ordering is the\n// point: a parser asked to read a challenge page or a 410 envelope will happily\n// return an empty array, and an empty array is indistinguishable from \"there\n// was nothing\". Classification is what keeps those two apart.\n//\n// Nothing classified here is ever retried automatically. On LinkedIn a 429 is\n// the warning shot on a documented escalation ladder, so a `retry-after` is\n// information to print for a human — never permission for the process to go\n// again. The `retry` field exists so that rule is asserted in tests.\n\nimport type { CooldownReason } from './budget.ts';\n\nexport interface RawResponse {\n status: number;\n body: string;\n headers?: Record<string, string>;\n}\n\nexport interface Classification {\n outcome: 'ok' | 'error';\n /** The unparsed body, kept for surfaces whose response is not JSON. */\n raw?: string;\n code?: string;\n message?: string;\n hint?: string;\n /** Which cooldown to open, if any. */\n cooldown?: CooldownReason;\n retryAfterMs?: number;\n retry: boolean;\n /** Parsed body, when it was JSON and we already did the work. */\n json?: unknown;\n}\n\nconst CHALLENGE_MARKERS = /checkpoint|challenge|captcha|security verification|unusual activity/i;\nconst LOGIN_REDIRECT = /\\/login|\\/uas\\/login|session_redirect/i;\n\nfunction fail(code: string, message: string, extra: Partial<Classification> = {}): Classification {\n return { outcome: 'error', code, message, retry: false, ...extra };\n}\n\nconst CHALLENGE_HINT =\n 'Open LinkedIn in a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`.';\n\n/** Redirects carry two very different meanings; confusing them costs a day. */\nfunction classifyRedirect(location: string): Classification {\n if (CHALLENGE_MARKERS.test(location)) {\n return fail('CHALLENGE_DETECTED', `redirected to a challenge: ${location}`, {\n cooldown: 'CHALLENGE_DETECTED',\n hint: CHALLENGE_HINT,\n });\n }\n if (LOGIN_REDIRECT.test(location)) {\n return fail('AUTH_FAILED', 'redirected to the login page', {\n hint: 'This signature means expired cookies, NOT bot detection. Re-run `lnrelay login`.',\n });\n }\n return fail('FETCH_FAILED', `unexpected redirect to ${location || '(none)'}`);\n}\n\n/**\n * A challenge served with status 200, if this body is one.\n *\n * Split out of classifyBody because it applies to EVERY path: a write must not\n * skip the challenge check just because its body is not a read contract.\n */\nfunction challengeIn(body: string): Classification | null {\n if (!CHALLENGE_MARKERS.test(body.slice(0, 4000))) return null;\n return fail('CHALLENGE_DETECTED', 'a challenge page was returned with status 200', {\n cooldown: 'CHALLENGE_DETECTED',\n hint: CHALLENGE_HINT,\n });\n}\n\n/** A 200 can still be a failure. Everything here inspects the body. */\nfunction classifyBody(body: string): Classification {\n const challenge = challengeIn(body);\n if (challenge !== null) return challenge;\n\n let json: unknown;\n try {\n json = JSON.parse(body);\n } catch {\n return fail('SCHEMA_DRIFT', 'response was 200 but not JSON', {\n hint: 'LinkedIn may have served HTML — inspect the raw body.',\n });\n }\n\n const envelope = json as { data?: Record<string, unknown>; included?: unknown[] };\n\n // An inner status can contradict the HTTP one.\n const innerStatus = (envelope.data as { status?: number } | undefined)?.status;\n if (typeof innerStatus === 'number' && innerStatus >= 400) {\n return fail('SCHEMA_DRIFT', `body carries an inner status ${innerStatus}`, {\n hint: 'The endpoint answered but reported a failure. Re-capture the operation.',\n });\n }\n\n // The 336-analogue: `data` names URNs that `included` does not contain at\n // all. The decoration failed wholesale — this is a failed fetch wearing the\n // costume of an empty result.\n if (referencesUrns(envelope.data) && (envelope.included?.length ?? 0) === 0) {\n return fail('SCHEMA_DRIFT', 'data references entities but included[] is empty', {\n hint: 'Decoration failed wholesale — this is a failed fetch, not an empty result.',\n });\n }\n\n return { outcome: 'ok', retry: false, json };\n}\n\nexport interface ClassifyOpts {\n /**\n * Whether the body is a contract to validate (a read) or a receipt (a write).\n *\n * A read's body must be a Voyager envelope, and a body that is not one means\n * something went wrong even under a 200. A WRITE's body is whatever the\n * surface feels like returning — LinkedIn's SDUI endpoints answer with a\n * React Server Components stream, which is not JSON and never will be.\n *\n * Defaults to true so reads keep their contract and nothing loosens by\n * omission.\n */\n expectJson?: boolean;\n}\n\nexport function classify(res: RawResponse, opts: ClassifyOpts = {}): Classification {\n const headers = res.headers ?? {};\n\n if (res.status >= 300 && res.status < 400) {\n return classifyRedirect(headers.location ?? '');\n }\n\n // ── Hard blocks ────────────────────────────────────────────────────────────\n if (res.status === 999) {\n return fail('REQUEST_DENIED', 'LinkedIn returned HTTP 999 (Request Denied)', {\n cooldown: 'REQUEST_DENIED',\n hint: 'A network-layer bot block that lifts only as traffic normalises. Stop making requests.',\n });\n }\n\n if (res.status === 429) {\n const retryAfter = Number(headers['retry-after']);\n const out = fail('RATE_LIMITED', 'LinkedIn throttled this request', {\n cooldown: 'RATE_LIMITED',\n hint: 'Not retried automatically — a throttle is the warning shot before a restriction.',\n });\n if (Number.isFinite(retryAfter)) out.retryAfterMs = retryAfter * 1000;\n return out;\n }\n\n if (res.status === 401 || res.status === 403) {\n return fail('AUTH_FAILED', `LinkedIn rejected the session (${res.status})`, {\n hint: 'Usually expired cookies. Re-run `lnrelay login`.',\n });\n }\n\n // ── Endpoint drift ─────────────────────────────────────────────────────────\n // 410 is the shape profileView returned on 2026-08-01: the endpoint existed,\n // answered, and told us it is gone.\n if (res.status === 410) {\n return fail('SCHEMA_DRIFT', 'endpoint returned 410 Gone — it no longer exists', {\n hint: 'Re-capture the operation with scripts/observe.ts and update src/engine/contracts.ts.',\n });\n }\n\n if (res.status === 400) {\n const hint = /queryid/i.test(res.body)\n ? 're-capture the queryId with scripts/observe.ts and update src/engine/contracts.ts'\n : 'check the encoded variables against a live capture';\n return fail('SCHEMA_DRIFT', `LinkedIn rejected the request shape (400)`, { hint });\n }\n\n if (res.status === 404) {\n return fail('NOT_FOUND', 'no such resource');\n }\n\n if (res.status < 200 || res.status >= 300) {\n return fail('FETCH_FAILED', `unexpected status ${res.status}`);\n }\n\n // Writes answer 201 Created and 204 No Content with an empty body. Reads\n // never do either, which is how this was missed until the first live share\n // came back 201 and was reported as a failure — after the post had been\n // created. That is the worst direction to be wrong in: a user told their\n // post failed re-runs the command and posts twice.\n //\n // An empty body is therefore a normal write outcome and must not reach\n // classifyBody, whose whole job is detecting a READ that returned nothing\n // when it claimed otherwise.\n if (res.body.trim() === '') return { outcome: 'ok', retry: false, json: null };\n\n // A challenge is served with status 200 and an HTML body on ANY path, so it\n // is checked before the read/write split — a write must not walk past it.\n const challenge = challengeIn(res.body);\n if (challenge !== null) return challenge;\n\n if (opts.expectJson === false) {\n // Parse opportunistically: some writes do answer JSON and the caller can\n // use it, but a body we cannot parse is not an error on this path. The raw\n // text is carried through either way — LinkedIn's SDUI surface answers with\n // an RSC stream that DESCRIBES its available actions, and that description\n // is the most useful thing in the response.\n try {\n return { outcome: 'ok', retry: false, json: JSON.parse(res.body) as unknown, raw: res.body };\n } catch {\n return { outcome: 'ok', retry: false, json: null, raw: res.body };\n }\n }\n\n return classifyBody(res.body);\n}\n\n/** Whether `data` names any URN we would expect `included[]` to resolve. */\nfunction referencesUrns(data: Record<string, unknown> | undefined): boolean {\n if (data === undefined) return false;\n let found = false;\n\n const walk = (node: unknown): void => {\n if (found || node === null || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n for (const [key, value] of Object.entries(node)) {\n // `*`-prefixed keys are Voyager's reference convention.\n if (key.startsWith('*') && Array.isArray(value) && value.length > 0) {\n found = true;\n return;\n }\n if (typeof value === 'string' && value.startsWith('urn:li:')) {\n found = true;\n return;\n }\n walk(value);\n }\n };\n\n walk(data);\n return found;\n}\n","// ─── The request driver ───────────────────────────────────────────────────────\n//\n// The only place in the program that issues a network request, and the only\n// place that spends budget. `fetch`, the clock and the sleeper are all injected\n// so this whole file is testable without touching the network.\n//\n// Order of operations is the safety design, and it is deliberate:\n//\n// 1. cooldown check — refuse before spending anything, in every process\n// 2. permit — no Permit, no call; unaccounted traffic is impossible\n// 3. jittered pace — never two calls back to back\n// 4. fetch\n// 5. classify — before parsing, always\n// 6. open a cooldown — on any throttle/block/challenge signal\n//\n// Nothing here retries. That is the point.\n\nimport { buildHeaders, type Session } from './auth.ts';\nimport type { Ledger, SpendClass } from './budget.ts';\nimport { activeCooldown, type Cooldown, MIN_GAP_MS, openCooldown, spend } from './budget.ts';\nimport { type Classification, classify } from './classify.ts';\n\nexport interface ClientDeps {\n fetch: typeof globalThis.fetch;\n /** Human-facing progress, on stderr. Optional so tests stay silent. */\n progress?: (message: string) => void;\n now: () => number;\n sleep: (ms: number) => Promise<void>;\n /** [0,1). Injected so jitter is deterministic in tests. */\n random: () => number;\n loadLedger: () => Ledger;\n saveLedger: (l: Ledger) => void;\n loadCooldown: () => Cooldown | null;\n saveCooldown: (c: Cooldown | null) => void;\n}\n\nexport interface RequestSpec {\n url: string;\n spendClass: SpendClass;\n operation: string;\n method?: string;\n /** Serialised as JSON when present. Reads carry none and must stay that way. */\n body?: unknown;\n}\n\nexport type ClientResult =\n | { ok: true; json: unknown; classification: Classification }\n | { ok: false; code: string; message: string; hint?: string; retryAfterMs?: number };\n\n/** Upper bound of the jittered gap. Lower bound is MIN_GAP_MS. */\nconst MAX_GAP_MS = 15_000;\n\nexport function createClient(session: Session, deps: ClientDeps) {\n async function request(spec: RequestSpec): Promise<ClientResult> {\n const now = deps.now();\n\n // 1. The breaker, first and in every process. A cooldown lives in a file\n // precisely so a fresh CLI invocation cannot walk straight back into the\n // throttle that opened it.\n const cooldown = deps.loadCooldown();\n if (activeCooldown(cooldown, now)) {\n const until =\n cooldown?.until === null\n ? 'indefinitely'\n : `until ${new Date(cooldown?.until ?? 0).toISOString()}`;\n return {\n ok: false,\n code: 'COOLDOWN_ACTIVE',\n message: `refusing to call LinkedIn: ${cooldown?.reason} cooldown is active ${until}`,\n hint:\n cooldown?.clearRequires === 'human'\n ? 'Log in through a real browser, clear the challenge, then `lnrelay budget --reset-cooldown --confirm`.'\n : 'Wait for it to lift, or inspect `lnrelay risk`.',\n };\n }\n\n // 2. Account for the call BEFORE making it. A denied call spends nothing.\n const ledger = deps.loadLedger();\n const result = spend(ledger, spec.spendClass, now);\n if ('error' in result) {\n return {\n ok: false,\n code: result.error.code,\n message: result.error.message,\n hint: result.error.hint,\n };\n }\n deps.saveLedger(result.ledger);\n\n // 3. Pace. Reads are paced as conservatively as writes, because the field\n // evidence shows restrictions triggered by read velocity alone.\n // That wait is 3-15s and silence during it reads as a hang, so say so.\n const gap = MIN_GAP_MS + Math.floor(deps.random() * (MAX_GAP_MS - MIN_GAP_MS));\n deps.progress?.(`${spec.operation}: pacing ${Math.round(gap / 1000)}s before the request…`);\n await deps.sleep(gap);\n deps.progress?.(`${spec.operation}: requesting…`);\n\n // 4-5. Fetch, then classify before anyone parses anything.\n const raw = await fetchRaw(spec, session, deps);\n if (raw === null) {\n return { ok: false, code: 'FETCH_FAILED', message: 'the request could not be completed' };\n }\n // A read's body is a contract; a write's body is a receipt. Validating a\n // write response read-shaped is what made a successful reaction report\n // SCHEMA_DRIFT — and made the user retry a write that had already landed.\n //\n // Keyed on the METHOD, not on whether a body was sent: `delete` sends no\n // body and is still a write.\n const isRead = (spec.method ?? 'GET') === 'GET';\n const classification = classify(raw, { expectJson: isRead });\n\n // 6. A throttle, block or challenge opens the breaker for every process.\n if (classification.cooldown !== undefined) {\n deps.saveCooldown(openCooldown(classification.cooldown, deps.now()));\n }\n\n if (classification.outcome === 'error') {\n const out: ClientResult = {\n ok: false,\n code: classification.code ?? 'FETCH_FAILED',\n message: classification.message ?? 'request failed',\n };\n if (classification.hint !== undefined) out.hint = classification.hint;\n if (classification.retryAfterMs !== undefined) out.retryAfterMs = classification.retryAfterMs;\n return out;\n }\n\n return { ok: true, json: classification.json, classification };\n }\n\n return { request };\n}\n\nasync function fetchRaw(\n spec: RequestSpec,\n session: Session,\n deps: ClientDeps,\n): Promise<{ status: number; body: string; headers: Record<string, string> } | null> {\n // A body is added only when there is one, so the read path keeps sending\n // exactly the six headers that were verified against live traffic.\n const requestHeaders = buildHeaders(session);\n if (spec.body !== undefined) requestHeaders['content-type'] = 'application/json; charset=UTF-8';\n\n try {\n const res = await deps.fetch(spec.url, {\n method: spec.method ?? 'GET',\n headers: requestHeaders,\n ...(spec.body === undefined ? {} : { body: JSON.stringify(spec.body) }),\n // Manual, so a login or checkpoint redirect is classified rather than\n // silently followed into an HTML page that parses as \"no data\".\n redirect: 'manual',\n });\n const headers: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n headers[key.toLowerCase()] = value;\n });\n return { status: res.status, body: await res.text(), headers };\n } catch {\n return null;\n }\n}\n\nexport type Client = ReturnType<typeof createClient>;\n","// ─── Operation contracts ──────────────────────────────────────────────────────\n//\n// Every endpoint we call, as DATA — never inline in request logic. queryIds and\n// decorationIds are pinned to LinkedIn's deployed web-client build and can\n// rotate; keeping them here means a rotation is a data edit, not a code hunt.\n//\n// Each contract carries its provenance and the date it was captured, and\n// `shippableContracts()` admits only `verified` ones. That rule is mechanical\n// rather than a convention someone has to remember:\n//\n// verified returned 200 on this machine, on the date recorded\n// discovered seen in live traffic (scripts/observe.ts) but never exercised\n// inferred from documentation or another client — may be archaeology\n//\n// The cost of getting this wrong is documented: `identity/profiles/{id}/\n// profileView` was the reference client's core profile endpoint, was documented\n// as working in November 2024, and returns 410 Gone today. It is kept below,\n// marked dead, so nobody re-adds it from an old blog post.\n//\n// Refresh with: bun run scripts/observe.ts <path> (see docs/ENGINE-RESEARCH.md)\n\nimport type { OperationContract } from '../types.ts';\n\nconst VOYAGER = 'https://www.linkedin.com/voyager/api';\n\nexport const CONTRACTS: Record<string, OperationContract> = {\n me: {\n name: 'me',\n transport: 'voyager-restli',\n path: `${VOYAGER}/me`,\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n // Three `voyagerIdentityDashProfiles` queryIds were observed on one page —\n // they are different PROJECTIONS of one operation, and picking the wrong one\n // gets you a 200 containing nothing useful:\n //\n // b5c27c04… identity only — entityUrn + versionTag. Looks like success.\n // e9b08094… the real profile: headline, geo, top position, education. ← this\n // da93c92b… 400s with (profileUrn:…); its variables shape is unknown.\n //\n // None of them returns firstName/lastName/publicIdentifier — LinkedIn splits\n // names into a projection we have not identified. Documented rather than\n // faked; the caller already knows who they asked for.\n profile: {\n name: 'profile',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerIdentityDashProfiles.e9b0809465a07db1f02e70a82d455e10',\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n feed: {\n name: 'feed',\n transport: 'voyager-restli',\n path: `${VOYAGER}/feed/updatesV2`,\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n // The November-2024 queryId, still returning 200 in August 2026 — roughly 21\n // months unchanged. Notable because kill criterion #3 assumed queryIds might\n // rotate weekly; on this evidence they are build-pinned but long-lived.\n search: {\n name: 'search',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSearchDashClusters.b0928897b71bd00a5a7291755dcd64f0',\n provenance: 'verified',\n capturedAt: '2026-08-01',\n },\n\n reactions: {\n name: 'reactions',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSocialDashReactions.41ebf31a9f4c4a84e35a49d5abc9010b',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // Comments. The variables carry a COMPOSITE socialDetailUrn assembled from the\n // post's own urn, repeated, plus a highlightedReply placeholder:\n //\n // urn:li:fsd_socialDetail:(<postUrn>,<postUrn>,urn:li:highlightedReply:-)\n //\n // Two things were established by probing rather than assumed. Our codec's\n // percent-encoding of that urn's colons and parens is REQUIRED — the literal\n // form returns 400. And an `urn:li:activity:` post urn works directly, so\n // `post` does not need a feed lookup to find the ugcPost form first.\n comments: {\n name: 'comments',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerSocialDashComments.afec6d88d7810d45548797a8dac4fb87',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // The member's own posts. Verified 200; returns an empty collection on an\n // account with no posts, which is a true empty rather than a failure.\n // Needs the `fsd_profile` namespace, NOT the `fs_miniProfile` urn `whoami`\n // returns — the legacy form answers 200 with an empty result rather than an\n // error. That was invisible until the account had a post to return, and is\n // why engine.myPosts canonicalises the urn before sending it.\n //\n // KNOWN INCOMPLETE (2026-08-13): with the namespace fixed this returns the\n // owner's posts, but a post created minutes earlier did not appear here, nor\n // in `feed`, over ~1.5 hours. Whether that is an indexing lag or a coverage\n // limit of this projection is UNRESOLVED — do not treat this endpoint as an\n // authoritative \"all my posts\" until it is settled.\n myPosts: {\n name: 'myPosts',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerFeedDashProfileUpdates.20c70fe0314184158516a7ec004c0408',\n provenance: 'verified',\n capturedAt: '2026-08-02',\n },\n\n // Discovered and returns 200, but the projection is useless: 39 KB containing\n // one `guideFetcher` wrapper and no name, tagline, description or headcount.\n // The same trap as the thin profile projection, so it stays unverified and\n // `company` does not ship. The richer path is probably\n // voyagerOrganizationDashViewWrapper with an organizationalPageUrn, which\n // first requires resolving that urn — unfinished work, not a dead end.\n company: {\n name: 'company',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerOrganizationDashCompanies.148b1aebfadd0a455f32806df656c3c1',\n provenance: 'discovered',\n capturedAt: '2026-08-02',\n },\n\n // A job CARDS list, not a job detail. Observed on /jobs/collections/recommended\n // and never exercised; `job` needs a detail endpoint we have not captured.\n jobCards: {\n name: 'jobCards',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerJobsDashJobCards.e5b6b761ede078dabe8ad857aa42c220',\n provenance: 'discovered',\n capturedAt: '2026-08-02',\n },\n};\n\n/**\n * Endpoints known to be DEAD. Listed so a future maintainer reading the\n * November-2024 reference client does not helpfully re-add one.\n */\nexport const RETIRED: Record<string, { path: string; diedBy: string; note: string }> = {\n profileView: {\n path: `${VOYAGER}/identity/profiles/{id}/profileView`,\n diedBy: '2026-08-01',\n note:\n 'Returns 410 Gone inside a well-formed Voyager envelope. Superseded by the `profile` ' +\n 'contract above. Every client that reads profiles through this is broken.',\n },\n};\n\n/** Only `verified` contracts may back a shipped command. */\nexport function shippableContracts(): Record<string, OperationContract> {\n return Object.fromEntries(\n Object.entries(CONTRACTS).filter(([, c]) => c.provenance === 'verified'),\n );\n}\n\nexport function contractFor(name: string): OperationContract | undefined {\n return shippableContracts()[name];\n}\n","// ─── Normalising Voyager's decoration model ───────────────────────────────────\n//\n// LinkedIn returns a graph with a side-table, not a nested document:\n//\n// { data: { \"*elements\": [\"urn:li:activity:100\", …] }, ← thin refs, ORDERED\n// included: [ { entityUrn: \"urn:li:activity:100\", $type: …, … }, … ] } ← unordered\n//\n// So: index `included[]` once into a Map, then walk `data`'s references against\n// it. The reference implementation instead does an O(n·m) substring scan across\n// the two, which is both slow and subtly wrong — we do not re-derive that.\n//\n// Three rules here are load-bearing, and each one exists because its absence\n// caused a real production bug in the sibling project:\n//\n// 1. FILTER BY EXCLUSION. Drop known noise; let everything else through. An\n// accept-list naming the types we know silently dropped every reply in\n// every thread on x-relay, and 34 of 77 posts per feed page — invisible\n// behind ok:true, a live cursor and a plausible count. On a live LinkedIn\n// feed, 39 of 44 included[] nodes are decorations rather than content, so\n// an accept-list here would look reasonable right up until a rename.\n//\n// 2. UNKNOWN IS NOT DROPPED, AND IT IS COUNTED. A $type we have never seen\n// arrives as data AND increments meta.unknownTypes, so drift shows up in\n// the very first response after a LinkedIn deploy rather than whenever\n// someone next thinks to count.\n//\n// 3. UNRESOLVABLE IS NOT ABSENT. A reference in `data` that `included[]`\n// does not contain is a FAILED decoration. It goes to meta.unresolved and\n// makes the result `partial` — never silently shorter.\n\nimport type { FetchState } from '../types.ts';\nimport { canonicalUrn } from './restli.ts';\n\nexport type Entity = Record<string, unknown> & { entityUrn?: string; $type?: unknown };\n\n/**\n * Type fragments that identify chrome rather than content. Matched as\n * case-insensitive substrings of `$type`, because LinkedIn versions its type\n * names (`UpdateV2` → `UpdateV3`) and a fragment survives that.\n *\n * This list is the ONLY thing that removes data. Adding to it is a deliberate\n * act; forgetting to add to it costs some noise in the output, which is the\n * cheap failure. Forgetting to add to an accept-list costs the entire result,\n * silently, which is the expensive one.\n */\nconst DROP_TYPE_FRAGMENTS = [\n 'promoted',\n 'sponsored',\n 'adunit',\n 'peopleyoumayknow',\n 'recommendedentity',\n 'discoveryentity',\n 'discoverymodule',\n 'promptcomponent',\n 'carouselcomponent',\n 'lego',\n // Search-result chrome, observed live alongside real results.\n 'feedbackcard',\n 'lazyloadedactions',\n 'bannercard',\n 'searchsuggestion',\n 'keywordssuggestion',\n 'queryclarification',\n 'knowledgecard',\n 'topicalquestion',\n];\n\n/** Types that are supporting decorations — real, but not the thing asked for. */\nconst DECORATION_FRAGMENTS = [\n 'socialdetail',\n 'socialactivitycounts',\n 'socialpermissions',\n 'saveaction',\n 'updateactions',\n 'hidepostaction',\n 'followinginfo',\n 'miniprofile',\n 'minicompany',\n 'videoplaymetadata',\n 'hidecommentaction',\n 'followingstate',\n 'followaction',\n 'connectaction',\n];\n\nfunction typeOf(node: Entity): string {\n const t = node.$type ?? (node as { _type?: unknown })._type;\n return typeof t === 'string' ? t : '';\n}\n\n/**\n * A promoted feed post carries the SAME `$type` as a real one — the ad marker\n * lives in the actor's subdescription (\"Promoted\", \"Promoted by <brand>\"), not\n * in the type. Found live: an ad reached the output while every type-level\n * filter passed, which is the same lesson as the accept-list in a new costume.\n * Type is not the only place a thing can identify itself.\n */\nfunction isPromotedPost(node: Entity): boolean {\n const actor = node.actor as { subDescription?: { text?: unknown } } | undefined;\n const sub = actor?.subDescription?.text;\n return typeof sub === 'string' && /^promoted\\b/i.test(sub.trim());\n}\n\nfunction isNoise(node: Entity): boolean {\n if (isPromotedPost(node)) return true;\n const t = typeOf(node).toLowerCase();\n if (t === '') return false;\n return DROP_TYPE_FRAGMENTS.some((f) => t.includes(f));\n}\n\nfunction isDecoration(node: Entity): boolean {\n const t = typeOf(node).toLowerCase();\n return DECORATION_FRAGMENTS.some((f) => t.includes(f));\n}\n\n/**\n * Whether we recognise this type as one we have actually seen. Used ONLY to\n * count unknowns for reporting — never to decide whether to keep something.\n */\nconst KNOWN_CONTENT = [\n 'updatev2',\n 'profile',\n 'jobposting',\n 'company',\n 'comment',\n 'reaction',\n 'entityresult',\n];\n\nfunction isKnown(node: Entity): boolean {\n const t = typeOf(node).toLowerCase();\n return KNOWN_CONTENT.some((f) => t.includes(f)) || isDecoration(node) || isNoise(node);\n}\n\n/** Build the `entityUrn → node` index in one pass, canonicalising namespaces. */\nexport function indexIncluded(included: unknown): Map<string, Entity> {\n const index = new Map<string, Entity>();\n if (!Array.isArray(included)) return index;\n\n for (const raw of included) {\n if (raw === null || typeof raw !== 'object') continue;\n const node = raw as Entity;\n const urn = node.entityUrn;\n if (typeof urn !== 'string') continue;\n\n // Store under BOTH the canonical and the literal form: references in `data`\n // may use either side of the fs_*/fsd_* migration.\n const canonical = canonicalUrn(urn);\n index.set(canonical, node);\n if (canonical !== urn) index.set(urn, node);\n }\n return index;\n}\n\nexport interface ResolveResult {\n resolved: Entity[];\n unresolved: string[];\n}\n\n/** Resolve an ordered list of URN references against the index. */\nexport function resolveRefs(refs: unknown, index: Map<string, Entity>): ResolveResult {\n const resolved: Entity[] = [];\n const unresolved: string[] = [];\n if (!Array.isArray(refs)) return { resolved, unresolved };\n\n for (const ref of refs) {\n if (typeof ref !== 'string') continue;\n const node = index.get(ref) ?? index.get(canonicalUrn(ref));\n if (node === undefined) unresolved.push(ref);\n else resolved.push(node);\n }\n return { resolved, unresolved };\n}\n\nexport interface ParseOpts {\n operation: string;\n /** What the platform claims exists, when it tells us. */\n claimedCount?: number;\n contractCapturedAt?: string;\n truncated?: boolean;\n}\n\nexport interface ParseMeta {\n state: FetchState;\n operation: string;\n contractCapturedAt: string;\n rawCandidateCount: number;\n parsedCount: number;\n excludedCount: number;\n unknownCount: number;\n returnedCount: number;\n claimedCount?: number;\n truncated: boolean;\n unresolved?: string[];\n unknownTypes?: { type: string; count: number }[];\n warnings: string[];\n}\n\nexport interface ParseResult {\n items: Entity[];\n meta: ParseMeta;\n}\n\n/**\n * Find the ordered reference list. Voyager marks references with a `*` prefix,\n * but arranges them in two quite different ways, and a parser that knows only\n * one returns an empty result for the other — with `ok:true`.\n *\n * Collection shape data[\"*elements\"] = [urn, urn, …]\n * feed, dashProfiles. One array, already in order.\n *\n * Cluster shape data.data.<op>.elements[].items[].item[\"*entityResult\"] = urn\n * search. One SINGLE string per item, nested three levels\n * down and spread across clusters.\n *\n * Both were captured live on 2026-08-01. Search parsed to zero items until this\n * handled the second shape — found only because the parser was run against a\n * real capture rather than its own fixtures.\n */\nfunction findRefs(data: unknown): unknown[] {\n if (data === null || typeof data !== 'object') return [];\n\n // Pass 1 — the shallowest `*`-prefixed ARRAY wins. Breadth-first, so a\n // top-level \"*elements\" is preferred over anything nested beneath it.\n const queue: unknown[] = [data];\n while (queue.length > 0) {\n const node = queue.shift();\n if (node === null || typeof node !== 'object') continue;\n if (Array.isArray(node)) {\n queue.push(...node);\n continue;\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.startsWith('*') && Array.isArray(value)) return value;\n }\n for (const value of Object.values(node)) {\n if (value !== null && typeof value === 'object') queue.push(value);\n }\n }\n\n // Pass 2 — no reference array anywhere, so collect `*`-prefixed STRINGS in\n // document order. Depth-first and in-order, because the order items appear\n // in the response IS the ranking LinkedIn assigned them.\n const refs: string[] = [];\n const walk = (node: unknown): void => {\n if (node === null || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.startsWith('*') && typeof value === 'string') refs.push(value);\n else walk(value);\n }\n };\n walk(data);\n return refs;\n}\n\n/**\n * A single-entity response (`/me`) carries no reference list at all — just one\n * decorated node in `included[]`. Returns undefined rather than throwing when\n * there is nothing, so callers decide what an absence means.\n */\nexport function parseSingle(payload: unknown): Entity | undefined {\n const envelope = (payload ?? {}) as { included?: unknown };\n const nodes = [...new Set(indexIncluded(envelope.included).values())];\n if (nodes.length === 0) return undefined;\n // Prefer a content node; fall back to the first, since a decoration is still\n // better than nothing when that is all the endpoint returns.\n return nodes.find((n) => !isNoise(n) && !isDecoration(n)) ?? nodes[0];\n}\n\nexport function parseCollection(payload: unknown, opts: ParseOpts): ParseResult {\n const envelope = (payload ?? {}) as { data?: unknown; included?: unknown };\n const index = indexIncluded(envelope.included);\n const refs = findRefs(envelope.data);\n const { resolved, unresolved } = resolveRefs(refs, index);\n\n const items: Entity[] = [];\n const unknownTypes = new Map<string, number>();\n let excludedCount = 0;\n let unknownCount = 0;\n\n for (const node of resolved) {\n // Per-item isolation: one malformed node never takes the page with it.\n try {\n if (isNoise(node) || isDecoration(node)) {\n excludedCount++;\n continue;\n }\n if (!isKnown(node)) {\n // Unknown → KEEP it (rule 2), and count it so the drift is visible.\n const t = typeOf(node);\n unknownTypes.set(t, (unknownTypes.get(t) ?? 0) + 1);\n unknownCount++;\n }\n items.push(node);\n } catch {\n excludedCount++;\n }\n }\n\n const warnings: string[] = [];\n if (unresolved.length > 0) {\n warnings.push(\n `${unresolved.length} referenced entities were not present in included[] — the decoration failed for those, so this record is incomplete rather than short.`,\n );\n }\n if (opts.claimedCount !== undefined && opts.claimedCount > 0 && items.length === 0) {\n warnings.push(\n `LinkedIn claims ${opts.claimedCount} items but returned none — treat this as a FAILED FETCH, not an empty result.`,\n );\n }\n\n const state: FetchState =\n unresolved.length > 0 ? 'partial' : opts.truncated === true ? 'unknown' : 'complete';\n\n const meta: ParseMeta = {\n state,\n operation: opts.operation,\n contractCapturedAt: opts.contractCapturedAt ?? 'unknown',\n // parsedCount counts what we kept; `items` includes the unknowns, which is\n // why unknownCount is reported separately rather than added again here.\n rawCandidateCount: resolved.length,\n parsedCount: items.length - unknownCount,\n excludedCount,\n unknownCount,\n returnedCount: items.length,\n truncated: opts.truncated ?? false,\n warnings,\n };\n if (opts.claimedCount !== undefined) meta.claimedCount = opts.claimedCount;\n if (unresolved.length > 0) meta.unresolved = unresolved;\n if (unknownTypes.size > 0) {\n meta.unknownTypes = [...unknownTypes.entries()].map(([type, count]) => ({ type, count }));\n }\n\n return { items, meta };\n}\n","// The Engine interface and its real construction. This is the seam: everything\n// above it is pure and testable, everything below it talks to LinkedIn.\n\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { progressReporter } from '../progress.ts';\nimport type { Session } from './auth.ts';\nimport { type Cooldown, emptyLedger, type Ledger } from './budget.ts';\nimport { type Client, type ClientDeps, createClient } from './client.ts';\nimport { contractFor } from './contracts.ts';\nimport {\n type Entity,\n indexIncluded,\n type ParseResult,\n parseCollection,\n parseSingle,\n} from './parse.ts';\nimport { canonicalUrn, encodeVariables } from './restli.ts';\n\nexport interface Engine {\n whoami(): Promise<EngineResult<Entity | undefined>>;\n profile(memberId: string): Promise<EngineResult<ProfileResult | undefined>>;\n feed(limit: number): Promise<EngineResult<Collection>>;\n search(kind: SearchKind, query: string, limit: number): Promise<EngineResult<Collection>>;\n post(postUrn: string, limit: number): Promise<EngineResult<Collection>>;\n myPosts(profileUrn: string, limit: number): Promise<EngineResult<Collection>>;\n connections(limit: number): Promise<EngineResult<Collection>>;\n reactions(postUrn: string, limit: number): Promise<EngineResult<Collection>>;\n}\n\nexport type SearchKind = 'people' | 'companies' | 'jobs';\n\n/**\n * A profile plus the side-table it references. LinkedIn returns location,\n * current position and education as URN references into `included[]`, so the\n * caller needs the index to make sense of the profile node.\n */\n/** A parsed collection plus the side-table its entities reference. */\nexport interface Collection {\n parsed: ParseResult;\n index: Map<string, Entity>;\n}\n\nexport interface ProfileResult {\n profile: Entity;\n index: Map<string, Entity>;\n}\n\nexport type EngineResult<T> =\n | { ok: true; value: T }\n | { ok: false; code: string; message: string; hint?: string; retryAfterMs?: number };\n\nconst RESULT_TYPE: Record<SearchKind, string> = {\n people: 'PEOPLE',\n companies: 'COMPANIES',\n jobs: 'JOBS',\n};\n\nfunction missingContract(name: string): EngineResult<never> {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: `no verified contract for '${name}'`,\n hint:\n 'Only endpoints that returned 200 on this machine may back a command. ' +\n 'Capture it with `bun run scripts/observe.ts`, verify it, then mark it verified in src/engine/contracts.ts.',\n };\n}\n\n/**\n * A live client on the real cache files. Exported because writes need a client\n * without needing an Engine — the write surface is not part of the read\n * contract, but it must share the same ledger, cooldown and pacing, and a\n * second construction of those would be a second breaker that agrees with the\n * first only by luck.\n */\nexport function createLiveClient(\n session: Session,\n deps?: Partial<ClientDeps>,\n quiet = false,\n): Client {\n return createClient(session, {\n fetch: globalThis.fetch,\n // stdout stays JSON-only; progress is human chatter and goes to stderr.\n progress: progressReporter(quiet),\n now: () => Date.now(),\n sleep: (ms) => new Promise((r) => setTimeout(r, ms)),\n random: () => Math.random(),\n loadLedger: () => {\n const r = loadJson<Ledger>(cachePath('budget.json'));\n return r.state === 'ok' ? r.value : emptyLedger();\n },\n saveLedger: (l) => saveJson(cachePath('budget.json'), l),\n loadCooldown: () => {\n const r = loadJson<Cooldown | null>(cachePath('cooldown.json'));\n return r.state === 'ok' ? r.value : null;\n },\n saveCooldown: (c) => saveJson(cachePath('cooldown.json'), c),\n ...deps,\n });\n}\n\nexport function createEngine(session: Session, deps?: Partial<ClientDeps>, quiet = false): Engine {\n const client: Client = createLiveClient(session, deps, quiet);\n\n return {\n async whoami() {\n const contract = contractFor('me');\n if (contract === undefined) return missingContract('me');\n\n const res = await client.request({\n url: contract.path,\n spendClass: 'profile',\n operation: 'me',\n });\n if (!res.ok) return res;\n return { ok: true, value: parseSingle(res.json) };\n },\n\n async profile(memberId) {\n const contract = contractFor('profile');\n if (contract === undefined) return missingContract('profile');\n\n const variables = encodeVariables({ memberIdentity: memberId });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'profile', operation: 'profile' });\n if (!res.ok) return res;\n\n const envelope = res.json as { included?: unknown };\n const index = indexIncluded(envelope.included);\n const profile = [...new Set(index.values())].find((n) =>\n String(n.$type ?? '').endsWith('profile.Profile'),\n );\n if (profile === undefined) return { ok: true, value: undefined };\n return { ok: true, value: { profile, index } };\n },\n\n async feed(limit) {\n const contract = contractFor('feed');\n if (contract === undefined) return missingContract('feed');\n\n const url = `${contract.path}?q=chronFeed&count=${limit}&start=0`;\n const res = await client.request({ url, spendClass: 'page', operation: 'feed' });\n if (!res.ok) return res;\n const envelope = res.json as { included?: unknown };\n return {\n ok: true,\n value: {\n parsed: parseCollection(res.json, {\n operation: 'feed',\n contractCapturedAt: contract.capturedAt,\n }),\n index: indexIncluded(envelope.included),\n },\n };\n },\n\n async myPosts(profileUrn, limit) {\n const contract = contractFor('myPosts');\n if (contract === undefined) return missingContract('myPosts');\n\n // `whoami` answers with an `fs_miniProfile` urn; this is a DASH endpoint\n // and wants `fsd_profile`. The legacy form returns 200 with an empty\n // result — no error, no warning — which is why this shipped as\n // \"verified\": the account had no posts when the contract was captured,\n // so empty was indistinguishable from working.\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n start: 0,\n profileUrn: canonicalUrn(profileUrn),\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'myPosts' });\n if (!res.ok) return res;\n\n const envelope = res.json as { included?: unknown };\n return {\n ok: true,\n value: {\n parsed: parseCollection(res.json, {\n operation: 'myPosts',\n contractCapturedAt: contract.capturedAt,\n truncated: true,\n }),\n index: indexIncluded(envelope.included),\n },\n };\n },\n\n /**\n * Connections are a FILTERED PEOPLE SEARCH, not a list endpoint — LinkedIn\n * exposes no change stream for them. That is why the cache stores them as a\n * snapshot and diffs, rather than pretending a watermark exists.\n */\n async connections(limit) {\n const contract = contractFor('search');\n if (contract === undefined) return missingContract('search');\n\n const variables = encodeVariables({\n start: 0,\n origin: 'FACETED_SEARCH',\n query: {\n flagshipSearchIntent: 'SEARCH_SRP',\n queryParameters: [\n { key: 'resultType', value: ['PEOPLE'] },\n { key: 'network', value: ['F'] },\n ],\n includeFiltersInResponse: false,\n },\n });\n const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'search', operation: 'connections' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'connections',\n contractCapturedAt: contract.capturedAt,\n claimedCount: totalResultCount(res.json),\n truncated: true,\n });\n parsed.items = parsed.items.slice(0, limit);\n parsed.meta.returnedCount = parsed.items.length;\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async post(postUrn, limit) {\n const contract = contractFor('comments');\n if (contract === undefined) return missingContract('comments');\n\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n numReplies: 1,\n socialDetailUrn: socialDetailUrn(postUrn),\n sortOrder: 'RELEVANCE',\n start: 0,\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'comments' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'comments',\n contractCapturedAt: contract.capturedAt,\n // A page of many; we follow no cursor yet, so never claim exhaustion.\n truncated: true,\n });\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async reactions(postUrn, limit) {\n const contract = contractFor('reactions');\n if (contract === undefined) return missingContract('reactions');\n\n const variables = encodeVariables({\n count: Math.min(limit, 100),\n start: 0,\n threadUrn: postUrn,\n });\n const url = `${contract.path}?includeWebMetadata=true&variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'page', operation: 'reactions' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'reactions',\n contractCapturedAt: contract.capturedAt,\n truncated: true,\n });\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n\n async search(kind, query, limit) {\n const contract = contractFor('search');\n if (contract === undefined) return missingContract('search');\n\n const variables = encodeVariables({\n start: 0,\n origin: 'GLOBAL_SEARCH_HEADER',\n query: {\n keywords: query,\n flagshipSearchIntent: 'SEARCH_SRP',\n queryParameters: [{ key: 'resultType', value: [RESULT_TYPE[kind]] }],\n includeFiltersInResponse: false,\n },\n });\n const url = `${contract.path}?variables=${variables}&queryId=${contract.queryId}`;\n const res = await client.request({ url, spendClass: 'search', operation: 'search' });\n if (!res.ok) return res;\n\n const parsed = parseCollection(res.json, {\n operation: 'search',\n contractCapturedAt: contract.capturedAt,\n claimedCount: totalResultCount(res.json),\n truncated: true, // one page of many; we never claim exhaustion\n });\n parsed.items = parsed.items.slice(0, limit);\n parsed.meta.returnedCount = parsed.items.length;\n const envelope = res.json as { included?: unknown };\n return { ok: true, value: { parsed, index: indexIncluded(envelope.included) } };\n },\n };\n}\n\n/**\n * The composite urn the comments endpoint keys off: the post's own urn,\n * repeated, plus a highlightedReply placeholder. Assembled rather than fetched\n * — verified working with an `urn:li:activity:` urn, so `post` needs no prior\n * lookup to find the ugcPost form.\n */\nfunction socialDetailUrn(postUrn: string): string {\n return `urn:li:fsd_socialDetail:(${postUrn},${postUrn},urn:li:highlightedReply:-)`;\n}\n\n/** LinkedIn's own claimed total, used to detect a claimed-but-empty fetch. */\nfunction totalResultCount(json: unknown): number | undefined {\n const found = JSON.stringify(json ?? {}).match(/\"totalResultCount\":(\\d+)/);\n return found?.[1] === undefined ? undefined : Number(found[1]);\n}\n","// Session persistence and the CDP bootstrap.\n//\n// Credentials live in a 0600 file under the cache dir. The design calls for OS\n// credential storage; that is a Phase 6 hardening step and is recorded as such\n// rather than silently skipped — for now the file is owner-only and the path is\n// gitignored.\n\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport type { Session } from './auth.ts';\n\nconst SESSION_FILE = 'session.json';\n\nexport type SessionLoad =\n | { state: 'ok'; session: Session }\n | { state: 'missing' }\n | { state: 'corrupt'; quarantinedTo: string };\n\nexport function loadSession(): SessionLoad {\n const result = loadJson<Session>(cachePath(SESSION_FILE));\n if (result.state === 'ok') return { state: 'ok', session: result.value };\n if (result.state === 'missing') return { state: 'missing' };\n return { state: 'corrupt', quarantinedTo: result.quarantinedTo };\n}\n\nexport function saveSession(session: Session): void {\n saveJson(cachePath(SESSION_FILE), session);\n}\n\n// ─── CDP bootstrap ────────────────────────────────────────────────────────────\n\nconst CDP = 'http://127.0.0.1:9222';\n\nexport const LAUNCH_HINT =\n 'Start Chrome with remote debugging first, DETACHED so it survives:\\n' +\n ' nohup /Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome \\\\\\n' +\n ' --remote-debugging-port=9222 --user-data-dir=\"$HOME/.lnrelay/chrome\" \\\\\\n' +\n ' https://www.linkedin.com/feed/ >/dev/null 2>&1 & disown\\n' +\n 'Then log into LinkedIn in that window and visit /feed/ once.';\n\ninterface CdpCookie {\n name: string;\n value: string;\n domain: string;\n}\n\n/**\n * Mint a session from a logged-in Chrome over the DevTools protocol.\n *\n * Visiting `/feed/` matters: that navigation is specifically what sets\n * JSESSIONID. A jar with JSESSIONID but no li_at means the browser has been to\n * linkedin.com but nobody has logged in.\n */\nexport async function mintSessionFromBrowser(): Promise<\n { ok: true; session: Session } | { ok: false; message: string; hint?: string }\n> {\n let targets: { type: string; webSocketDebuggerUrl?: string }[];\n let userAgent: string;\n try {\n targets = (await (await fetch(`${CDP}/json/list`)).json()) as typeof targets;\n const version = (await (await fetch(`${CDP}/json/version`)).json()) as {\n 'User-Agent'?: string;\n };\n userAgent = (version['User-Agent'] ?? '').replace('HeadlessChrome', 'Chrome');\n } catch {\n return { ok: false, message: `no Chrome DevTools endpoint at ${CDP}`, hint: LAUNCH_HINT };\n }\n\n const page = targets.find((t) => t.type === 'page' && t.webSocketDebuggerUrl !== undefined);\n if (page?.webSocketDebuggerUrl === undefined) {\n return { ok: false, message: 'no debuggable Chrome page found', hint: LAUNCH_HINT };\n }\n if (userAgent === '') {\n return { ok: false, message: 'Chrome did not report a User-Agent' };\n }\n\n let cookies: CdpCookie[];\n try {\n cookies = await getAllCookies(page.webSocketDebuggerUrl);\n } catch (e) {\n return { ok: false, message: `CDP failed: ${(e as Error).message}`, hint: LAUNCH_HINT };\n }\n\n const linkedin = cookies.filter((c) => c.domain.includes('linkedin.com'));\n const liAt = linkedin.find((c) => c.name === 'li_at');\n const jsession = linkedin.find((c) => c.name === 'JSESSIONID');\n\n if (liAt === undefined) {\n return {\n ok: false,\n message: 'no li_at cookie — you are not logged in',\n hint: 'Log into linkedin.com in the debug Chrome window, then re-run. Note that JSESSIONID alone is set pre-login and does not mean a session exists.',\n };\n }\n if (jsession === undefined) {\n return {\n ok: false,\n message: 'no JSESSIONID cookie',\n hint: 'Visit https://www.linkedin.com/feed/ in the debug window — that navigation is what sets it.',\n };\n }\n\n return {\n ok: true,\n session: {\n liAt: liAt.value,\n jsessionId: jsession.value,\n userAgent,\n capturedAt: new Date().toISOString().slice(0, 10),\n },\n };\n}\n\nfunction getAllCookies(wsUrl: string): Promise<CdpCookie[]> {\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(wsUrl);\n const timer = setTimeout(() => {\n ws.close();\n reject(new Error('timed out talking to Chrome'));\n }, 10_000);\n\n ws.onopen = () => ws.send(JSON.stringify({ id: 1, method: 'Network.getAllCookies' }));\n ws.onmessage = (ev) => {\n const msg = JSON.parse(String(ev.data)) as { id?: number; result?: { cookies: CdpCookie[] } };\n if (msg.id === 1 && msg.result !== undefined) {\n clearTimeout(timer);\n ws.close();\n resolve(msg.result.cookies);\n }\n };\n ws.onerror = () => {\n clearTimeout(timer);\n reject(new Error('websocket error'));\n };\n });\n}\n","// Runners for the commands that talk to LinkedIn. Thin: they resolve a\n// session, call the engine, and shape the envelope. All the interesting\n// behaviour lives in engine/.\n\nimport {\n type Collection,\n createEngine,\n type EngineResult,\n type SearchKind,\n} from '../engine/index.ts';\n\nimport {\n LAUNCH_HINT,\n loadSession,\n mintSessionFromBrowser,\n saveSession,\n} from '../engine/session.ts';\nimport {\n compactRows,\n project,\n type Shaped,\n shapeAll,\n shapeEntity,\n shapeProfile,\n} from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { retain } from './cache.ts';\n\nfunction withSession(\n command: string,\n quiet = false,\n): { engine: ReturnType<typeof createEngine> } | Envelope {\n const loaded = loadSession();\n if (loaded.state === 'corrupt') {\n return err(\n command,\n 'CACHE_CORRUPT',\n 'the stored session was unreadable and has been quarantined',\n `Moved to ${loaded.quarantinedTo}. Re-run \\`lnrelay login\\`.`,\n );\n }\n if (loaded.state === 'missing') {\n return err(command, 'AUTH_FAILED', 'no session — run `lnrelay login` first', LAUNCH_HINT);\n }\n return { engine: createEngine(loaded.session, undefined, quiet) };\n}\n\n/** Turn an engine failure into an envelope without losing its hint. */\nfunction toEnvelope(\n command: string,\n result: Extract<EngineResult<never>, { ok: false }>,\n): Envelope {\n return err(command, result.code, result.message, result.hint, undefined, result.retryAfterMs);\n}\n\nexport async function runLogin(): Promise<Envelope> {\n const minted = await mintSessionFromBrowser();\n if (!minted.ok) return err('login', 'AUTH_FAILED', minted.message, minted.hint);\n\n saveSession(minted.session);\n // Never echo a credential — presence and length only.\n return ok('login', {\n stored: true,\n liAtLength: minted.session.liAt.length,\n userAgent: minted.session.userAgent,\n capturedAt: minted.session.capturedAt,\n notice:\n 'Session stored with owner-only permissions. This tool breaches LinkedIn User Agreement ' +\n '§8.2 and the account can be restricted or banned.',\n });\n}\n\nexport async function runWhoami(raw = false): Promise<Envelope> {\n const ctx = withSession('whoami');\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.whoami();\n if (!result.ok) return toEnvelope('whoami', result);\n if (result.value === undefined) {\n return err(\n 'whoami',\n 'SCHEMA_DRIFT',\n 'LinkedIn returned no member entity',\n 're-capture the `me` contract',\n );\n }\n return ok(\n 'whoami',\n raw ? { ...shapeEntity(result.value), raw: result.value } : shapeEntity(result.value),\n );\n}\n\nexport async function runProfile(memberId: string | undefined, raw = false): Promise<Envelope> {\n if (memberId === undefined || memberId === '') {\n return err(\n 'profile',\n 'INVALID_INPUT',\n 'a member id or urn is required',\n 'lnrelay profile <public-id|urn>',\n );\n }\n const ctx = withSession('profile');\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.profile(normaliseMemberId(memberId));\n if (!result.ok) return toEnvelope('profile', result);\n if (result.value === undefined) {\n return err('profile', 'NOT_FOUND', `no profile for '${memberId}'`);\n }\n const shaped = shapeProfile(result.value.profile, result.value.index);\n return ok('profile', raw ? { ...shaped, raw: result.value.profile } : shaped);\n}\n\nexport async function runFeed(limit: number, opts: OutputOpts = {}): Promise<Envelope> {\n const ctx = withSession('feed', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.feed(limit);\n if (!result.ok) return toEnvelope('feed', result);\n return ok('feed', collection(result.value, opts));\n}\n\nexport async function runSearch(\n kind: string | undefined,\n query: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n if (kind === undefined || !['people', 'companies', 'jobs'].includes(kind)) {\n return err(\n 'search',\n 'INVALID_INPUT',\n 'kind must be people, companies or jobs',\n 'lnrelay search people \"<query>\"',\n );\n }\n if (query === undefined || query === '') {\n return err('search', 'INVALID_INPUT', 'a query is required', 'lnrelay search people \"<query>\"');\n }\n const ctx = withSession('search', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.search(kind as SearchKind, query, limit);\n if (!result.ok) return toEnvelope('search', result);\n return ok('search', { query, kind, ...collection(result.value, opts) });\n}\n\nexport async function runPost(\n urn: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n const postUrn = normalisePostUrn(urn);\n if (postUrn === undefined) {\n return err(\n 'post',\n 'INVALID_INPUT',\n 'a post urn or feed URL is required',\n 'lnrelay post <activity-urn|https://www.linkedin.com/feed/update/...>',\n );\n }\n const ctx = withSession('post', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.post(postUrn, limit);\n if (!result.ok) return toEnvelope('post', result);\n return ok('post', { urn: postUrn, ...collection(result.value, opts) });\n}\n\nexport async function runReactions(\n urn: string | undefined,\n limit: number,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n const postUrn = normalisePostUrn(urn);\n if (postUrn === undefined) {\n return err('reactions', 'INVALID_INPUT', 'a post urn or feed URL is required');\n }\n const ctx = withSession('reactions', opts.quiet === true);\n if ('ok' in ctx) return ctx;\n\n const result = await ctx.engine.reactions(postUrn, limit);\n if (!result.ok) return toEnvelope('reactions', result);\n return ok('reactions', { urn: postUrn, ...collection(result.value, opts) });\n}\n\n// ─── shaping ──────────────────────────────────────────────────────────────────\n\n/** Accept a bare urn or a feed permalink; both carry the post identity. */\nfunction normalisePostUrn(input: string | undefined): string | undefined {\n if (input === undefined || input === '') return undefined;\n const found = input.match(/urn:li:(?:activity|ugcPost|share):\\d+/);\n if (found !== null) return found[0];\n return /^\\d+$/.test(input) ? `urn:li:activity:${input}` : undefined;\n}\n\n/** A URL, a public id, or a bare urn all reduce to the member identity. */\nfunction normaliseMemberId(input: string): string {\n const fromUrl = input.match(/linkedin\\.com\\/in\\/([^/?#]+)/);\n if (fromUrl?.[1] !== undefined) return fromUrl[1];\n const fromUrn = input.match(/urn:li:fsd?_(?:mini)?[Pp]rofile:([^,)]+)/);\n if (fromUrn?.[1] !== undefined) return fromUrn[1];\n return input;\n}\n\n/** How the caller wants the rows rendered. */\nexport interface OutputOpts {\n raw?: boolean;\n retain?: boolean;\n compact?: boolean;\n fields?: string;\n quiet?: boolean;\n}\n\n/**\n * Collections are shaped by default — raw Voyager entities are enormous and\n * wrap every string in a TextViewModel. `--raw` keeps the original node\n * alongside, for when a shape has drifted and you need to see what arrived;\n * `--compact` and `--fields` go the other way, for when a page of results is\n * about to land in an agent's context and only the ranking signal matters.\n */\nfunction collection(result: Collection, opts: OutputOpts = {}): Record<string, unknown> {\n const { parsed, index } = result;\n const shaped = shapeAll(parsed.items, index);\n\n const meta: Record<string, unknown> = { ...parsed.meta };\n // Retention always stores the FULL shaped row, never the projected one — a\n // display choice must not silently narrow what gets cached.\n if (opts.retain === true) meta.retained = retain('third-party', shaped);\n\n if (opts.raw === true) {\n return {\n items: parsed.items.map((node, i) => ({ ...(shaped[i] as Shaped), raw: node })),\n meta,\n };\n }\n if (opts.compact === true) return { items: compactRows(shaped), meta };\n if (opts.fields !== undefined && opts.fields !== '') {\n return { items: project(shaped, opts.fields), meta };\n }\n return { items: shaped, meta };\n}\n","// The three commands that work today. All are local: they make no network call\n// and need no LinkedIn session, so they are useful before the Phase 0 gate has\n// even run.\n\nimport { existsSync } from 'node:fs';\nimport { version as nodeVersion } from 'node:process';\nimport { cacheDir, cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport {\n activeCooldown,\n CAPS,\n type Cooldown,\n emptyLedger,\n type Ledger,\n type SpendClass,\n summarise,\n} from '../engine/budget.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\n\nconst LEDGER_FILE = 'budget.json';\nconst COOLDOWN_FILE = 'cooldown.json';\n\ninterface StateLoad<T> {\n value: T | null;\n corrupt: { path: string; quarantinedTo: string; reason: string } | null;\n}\n\nfunction loadState<T>(file: string, fallback: T): StateLoad<T> {\n const path = cachePath(file);\n const result = loadJson<T>(path);\n if (result.state === 'ok') return { value: result.value, corrupt: null };\n if (result.state === 'missing') return { value: fallback, corrupt: null };\n return {\n value: null,\n corrupt: { path, quarantinedTo: result.quarantinedTo, reason: result.reason },\n };\n}\n\nexport function loadLedger(): StateLoad<Ledger> {\n return loadState<Ledger>(LEDGER_FILE, emptyLedger());\n}\n\nexport function loadCooldown(): StateLoad<Cooldown | null> {\n return loadState<Cooldown | null>(COOLDOWN_FILE, null);\n}\n\n// ─── risk ─────────────────────────────────────────────────────────────────────\n\n/**\n * The breaker's current state. Exposed over MCP deliberately, so an agent can\n * check standing BEFORE deciding to spend budget on research rather than\n * discovering the lockout one wasted call at a time.\n */\nexport function runRisk(now: number): Envelope {\n const { value: cooldown, corrupt } = loadCooldown();\n if (corrupt !== null) {\n return err(\n 'risk',\n 'CACHE_CORRUPT',\n `cooldown state was unreadable and has been quarantined: ${corrupt.reason}`,\n `moved to ${corrupt.quarantinedTo}. Inspect it, then re-run — a fresh cooldown file will be created.`,\n );\n }\n\n const blocked = activeCooldown(cooldown ?? null, now);\n return ok('risk', {\n state: blocked ? 'blocked' : 'ok',\n cooldown: cooldown ?? null,\n tosNotice:\n 'Voyager reads breach LinkedIn User Agreement §8.2. This tool is not ToS-compliant and ' +\n 'any account it touches can be restricted or permanently banned.',\n });\n}\n\n// ─── budget ───────────────────────────────────────────────────────────────────\n\nexport function runBudget(now: number, resetCooldown: boolean, confirmed: boolean): Envelope {\n if (resetCooldown && !confirmed) {\n return err(\n 'budget',\n 'CONFIRMATION_REQUIRED',\n 'clearing a cooldown requires --confirm',\n 'A cooldown means LinkedIn signalled a throttle, block or challenge. Log in through a real ' +\n 'browser and confirm you are unblocked before clearing it. Re-run with --confirm.',\n );\n }\n\n if (resetCooldown) {\n saveJson(cachePath(COOLDOWN_FILE), null);\n }\n\n const { value: ledger, corrupt } = loadLedger();\n if (corrupt !== null) {\n return err(\n 'budget',\n 'CACHE_CORRUPT',\n `the spend ledger was unreadable and has been quarantined: ${corrupt.reason}`,\n `moved to ${corrupt.quarantinedTo}. A corrupt ledger is NOT treated as an empty one — that ` +\n 'would silently restore a full budget. Inspect it, then re-run.',\n );\n }\n\n const classes: SpendClass[] = ['profile', 'search', 'page', 'write', 'global'];\n const { value: cooldown } = loadCooldown();\n\n return ok('budget', {\n classes: classes.map((c) => ({\n ...summarise(ledger ?? emptyLedger(), c, now),\n note: CAPS[c].note,\n })),\n cooldown: cooldown ?? null,\n caveat:\n 'Every cap is guessed or transplanted vendor lore — the field research found no corroborated ' +\n 'LinkedIn rate limits. These are starting knobs, not safe thresholds. They also cannot see ' +\n 'your manual browser activity.',\n });\n}\n\n// ─── doctor ───────────────────────────────────────────────────────────────────\n\nexport interface Check {\n name: string;\n ok: boolean;\n detail: string;\n}\n\n/**\n * Diagnose setup. Always returns ok:true at the envelope level — a diagnostic\n * that fails to report because something is broken is useless. Individual checks\n * carry their own pass/fail. Never prints a credential value.\n */\nexport function runDoctor(now: number, offline: boolean): Envelope {\n const checks: Check[] = [];\n\n checks.push({\n name: 'runtime',\n ok: true,\n detail: `node ${nodeVersion}; cache dir ${cacheDir()}${existsSync(cacheDir()) ? '' : ' (not created yet)'}`,\n });\n\n const { value: cooldown, corrupt: cooldownCorrupt } = loadCooldown();\n if (cooldownCorrupt !== null) {\n checks.push({\n name: 'cooldown',\n ok: false,\n detail: `state file was corrupt; quarantined to ${cooldownCorrupt.quarantinedTo}`,\n });\n } else {\n const blocked = activeCooldown(cooldown ?? null, now);\n checks.push({\n name: 'cooldown',\n ok: !blocked,\n detail: blocked\n ? `BLOCKED — ${cooldown?.reason}, clears by ${cooldown?.clearRequires}${\n cooldown?.until === null\n ? ' (indefinite)'\n : ` at ${new Date(cooldown?.until ?? 0).toISOString()}`\n }`\n : 'clear',\n });\n }\n\n const { value: ledger, corrupt: ledgerCorrupt } = loadLedger();\n if (ledgerCorrupt !== null) {\n checks.push({\n name: 'budget',\n ok: false,\n detail: `ledger was corrupt; quarantined to ${ledgerCorrupt.quarantinedTo}`,\n });\n } else {\n const g = summarise(ledger ?? emptyLedger(), 'global', now);\n checks.push({\n name: 'budget',\n ok: g.remaining > 0,\n detail: `${g.spentInWindow}/${g.cap} global calls used in the last 24h (cap provenance: ${g.capProvenance})`,\n });\n }\n\n // Credentials are checked for PRESENCE and LENGTH only — never printed.\n const cookiePath = cachePath('cookies.json');\n checks.push({\n name: 'session',\n ok: false,\n detail: existsSync(cookiePath)\n ? 'a cookie file exists, but the engine is not implemented yet (Phase 2)'\n : 'no session yet — the Phase 0 capture gate has not been run. See docs/PLAN.md.',\n });\n\n checks.push({\n name: 'engine',\n ok: false,\n detail:\n 'not implemented. Phase 0 (three human-paced requests from a residential IP) must pass ' +\n 'before engine code is written — see docs/PLAN.md.',\n });\n\n if (!offline) {\n checks.push({\n name: 'live',\n ok: false,\n detail: 'no live checks available yet; --offline is currently the only meaningful mode',\n });\n }\n\n return ok('doctor', {\n healthy: checks.every((c) => c.ok),\n phase: 'Phase 1 — local scaffolding. No network capability exists yet, by design.',\n checks,\n });\n}\n","// Single source of truth for command definitions. Drives CLI dispatch + help,\n// the MCP tool surface, and the SKILL.md parity test.\n//\n// `audience` is load-bearing, not documentation: the MCP shim registers only\n// commands marked `mcp`, so a write can never reach an agent by accident. The\n// research half of this tool is the product; writes are a thin, human-gated\n// layer that arrives last (docs/PLAN.md Phase 6).\n\nexport type Audience = 'cli' | 'mcp';\nexport type RiskClass = 'read' | 'local' | 'write';\n\nexport interface CommandDef {\n name: string;\n /** Funnel cost hint shown in help + skill. */\n cost: string;\n summary: string;\n usage: string;\n audience: Audience[];\n risk: RiskClass;\n /** false until the command is actually wired up. */\n implemented: boolean;\n}\n\nexport const COMMANDS: CommandDef[] = [\n // ─── local / meta — no network, available today ────────────────────────────\n {\n name: 'doctor',\n cost: 'free with --offline',\n summary: 'Diagnose setup: entry point, cache dir, cookies, cooldown, budget.',\n usage: 'lnrelay doctor [--offline]',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'budget',\n cost: 'free',\n summary: \"Spend ledger per class, with each cap's provenance. Reset a cooldown here.\",\n usage: 'lnrelay budget [--reset-cooldown --confirm]',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'risk',\n cost: 'free',\n summary: 'Circuit-breaker state. Check this BEFORE spending budget on research.',\n usage: 'lnrelay risk',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── session ───────────────────────────────────────────────────────────────\n {\n name: 'login',\n cost: 'free — local browser',\n summary: 'Mint a session from a logged-in Chrome via DevTools. Stores cookies owner-only.',\n usage:\n 'lnrelay login\\n' +\n ' Requires a Chrome started with remote debugging on port 9222 (see docs/PLAN.md).',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── reads — verified live 2026-08-01 ─────────────────────────────────────\n {\n name: 'whoami',\n cost: '1 call',\n summary: 'The authenticated member: name, headline, URN.',\n usage: 'lnrelay whoami',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'profile',\n cost: '1 call (+1 per section)',\n summary: 'A member profile. Expensive sections are opt-in.',\n usage:\n 'lnrelay profile <public-id|urn|url> [--raw]\\n' +\n \" Returns headline, location, current title, company and school. LinkedIn's profile\\n\" +\n ' projections do not return a name — use the identifier you passed in.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'search',\n cost: 'cheap — the net',\n summary: 'Search people, companies or jobs. Cast wide, then deep-read the finalists.',\n usage:\n 'lnrelay search people|companies|jobs \"<query>\" [--limit N]\\n' +\n ' [--compact | --fields a,b,c] [--retain] [--raw]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'post',\n cost: 'expensive — full read',\n summary: 'A post plus its comment thread, cursor-followed.',\n usage:\n 'lnrelay post <activity-urn|url> [--limit N] [--compact | --fields a,b] [--retain]\\n' +\n ' Check meta.returnedCount / claimedCount / state. claimedCount > 0 with\\n' +\n ' returnedCount 0 is a FAILED FETCH, not an empty thread.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'reactions',\n cost: 'medium',\n summary: 'Who reacted to a post, and with which reaction.',\n usage: 'lnrelay reactions <activity-urn|url> [--limit N] [--compact | --fields a,b]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'company',\n cost: 'medium',\n summary: 'A company page, optionally with a bounded sample of its updates.',\n usage: 'lnrelay company <universal-name|url> [--updates N]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: false,\n },\n {\n name: 'job',\n cost: '1 call',\n summary: 'A job posting detail.',\n usage: 'lnrelay job <job-id|url>',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: false,\n },\n {\n name: 'feed',\n cost: 'medium',\n summary: 'Your own chronological feed.',\n usage: 'lnrelay feed [--limit N] [--compact | --fields a,b,c] [--retain] [--raw]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n\n // ─── cache-backed — Phase 4 ────────────────────────────────────────────────\n {\n name: 'sync',\n cost: 'medium — 1-2 calls',\n summary: 'Pull your own posts or connections into the local cache for offline search.',\n usage: 'lnrelay sync my-posts|connections [--limit N] [--force]',\n audience: ['cli'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'connections',\n cost: 'free — local cache',\n summary: 'Your connections, from the local cache. Fill it with `sync connections`.',\n usage:\n 'lnrelay connections [-q \"<query>\"] [--limit N] [--compact | --fields a,b] # free; cache',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'my-posts',\n cost: 'free — local cache',\n summary: 'Your own authored posts, from the local cache. Fill it with `sync my-posts`.',\n usage:\n 'lnrelay my-posts [-q \"<query>\"] [--limit N] [--compact | --fields a,b] # free; cache',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'local',\n cost: 'free — local cache',\n summary: 'Offline search across everything synced. The default research path after a sync.',\n usage:\n 'lnrelay local \"<query>\" [--source connections,my-posts,third-party] [--since YYYY-MM-DD]\\n' +\n ' [--limit N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'cache-status',\n cost: 'free — local cache',\n summary: 'What is cached, per source, with sync checkpoints and the retention policy.',\n usage: 'lnrelay cache-status',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'purge',\n cost: 'free',\n summary: 'Delete cached data. Never contacts LinkedIn.',\n usage: 'lnrelay purge [--all] --confirm # default scope: third-party only',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n\n // ─── writes — Phase 6, official OAuth only, never MCP ──────────────────────\n {\n name: 'oauth',\n cost: 'free',\n summary:\n \"Obtain and inspect the write credential, over LinkedIn's own self-serve scope. \" +\n 'Never prints the token.',\n usage:\n 'lnrelay oauth login --client-id <id> [--client-secret <secret>]\\n' +\n ' lnrelay oauth status | logout\\n' +\n ' The secret is prompted for if omitted; LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET also work.\\n' +\n ' Needs an app you registered: see the hint printed when no token is stored.',\n audience: ['cli'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'share',\n cost: '1 call — write',\n summary:\n \"Post to your own feed. Prefers LinkedIn's official OAuth scope, falls back to the \" +\n 'private API when no token exists — the prompt always names which.',\n usage:\n 'lnrelay share \"<text>\" [--visibility public|connections] [--via oauth|voyager]\\n' +\n ' Stops and asks at an interactive terminal. No TTY = no write, and no network call.',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'comment',\n cost: '1 call — write',\n summary:\n 'Add a comment to a post. Harvests its binding tokens from the rendered page; no browser ' +\n 'needed, but it costs one heavy read.',\n usage:\n 'lnrelay comment <activity-urn> \"<text>\"\\n' +\n ' Fetches the post page (~2.8 MB) to harvest a binding key and trackingId, and proves\\n' +\n ' the key belongs to that post before asking. To change a comment, see `edit`.',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'delete',\n cost: '1 read + 1 write',\n summary:\n 'Delete one of your own posts or comments. Reads a post back and shows its text first — ' +\n 'this is the one action that cannot be undone.',\n usage:\n 'lnrelay delete <activity-urn> # a post; shows you its text before destroying it\\n' +\n ' lnrelay delete <comment-urn> # a comment; the server decides if you may',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'reply',\n cost: '1 read + 1 write',\n summary:\n 'Reply to a comment. WITHDRAWN — the implementation posted a top-level comment instead of ' +\n 'a nested reply. Refuses until that is actually solved.',\n usage: 'lnrelay reply <comment-urn> \"<text>\"',\n audience: ['cli'],\n risk: 'write',\n implemented: false,\n },\n {\n name: 'edit',\n cost: '1 read + 1 write',\n summary:\n 'Change the text of a comment you wrote. Its own verb, so a comment urn can never be ' +\n 'mistaken for something to comment ON.',\n usage: 'lnrelay edit <comment-urn> \"<text>\"',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'react',\n cost: '1 call — write',\n summary: \"React to a post or comment, over LinkedIn's SDUI surface. Reversible with --remove.\",\n usage:\n 'lnrelay react <activity-urn | comment-urn> [--type LIKE|PRAISE|EMPATHY|INTEREST|APPRECIATION|ENTERTAINMENT]\\n' +\n ' lnrelay react <urn> --remove # take the reaction back',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n];\n\nexport const commandNames = COMMANDS.map((c) => c.name);\n\nexport function findCommand(name: string): CommandDef | undefined {\n return COMMANDS.find((c) => c.name === name);\n}\n\n/** Commands the MCP shim may register. Writes are structurally excluded. */\nexport function mcpCommands(): CommandDef[] {\n return COMMANDS.filter((c) => c.audience.includes('mcp') && c.risk !== 'write');\n}\n\nexport function helpText(): string {\n const lines = ['lnrelay — deep research over LinkedIn from your own account', '', 'Commands:'];\n const width = Math.max(...commandNames.map((n) => n.length));\n for (const c of COMMANDS) {\n const flag = c.implemented ? ' ' : '·'; // · = designed, not yet wired\n lines.push(` ${flag} ${c.name.padEnd(width)} ${c.summary} [${c.cost}]`);\n }\n lines.push('', ' · = specified in docs/DESIGN.md, not yet implemented');\n lines.push('', 'Run `lnrelay <command> --help` for usage.');\n return lines.join('\\n');\n}\n","// ─── Main-module detection ────────────────────────────────────────────────\n// Deciding whether an entry file was invoked directly (should run) vs merely\n// imported (should stay silent). The naive `fileURLToPath(url) === argv[1]`\n// check breaks under the npm bin symlink (…/bin/lnrelay → …/dist/cli.js): argv1\n// is the symlink, the module url is the real file — unequal — so the CLI would\n// silently exit 0. Resolving both through realpath fixes that. Pure + testable.\nimport { realpathSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Decide whether the current module is the process entry point.\n * @param argv1 process.argv[1] — the invoked script path (may be a symlink).\n * @param moduleUrl import.meta.url of the entry module.\n * @param importMetaMain import.meta.main when the runtime provides it.\n */\nexport function isMainModule(\n argv1: string | undefined,\n moduleUrl: string,\n importMetaMain: boolean | undefined,\n): boolean {\n // The runtime told us explicitly — trust it (Bun always sets this).\n if (importMetaMain === true) return true;\n if (importMetaMain === false) return false;\n\n if (argv1 === undefined) return false;\n\n const modulePath = fileURLToPath(moduleUrl);\n try {\n return realpathSync(argv1) === realpathSync(modulePath);\n } catch {\n // realpath failed (path missing, permission, etc.) — fall back to a plain\n // string compare.\n return argv1 === modulePath;\n }\n}\n\n/**\n * Fail-loud heuristic: when isMainModule said \"not entry\" but argv1's basename\n * looks like one of our binaries, the user clearly invoked us and our detection\n * failed. Callers run anyway (after warning) rather than silently exiting.\n */\nexport function shouldForceEntry(argv1: string | undefined, binNames: string[]): boolean {\n if (argv1 === undefined) return false;\n return binNames.includes(basename(argv1));\n}\n\nexport interface EntryDecision {\n /** Whether the entry file should run its main routine. */\n run: boolean;\n /** A stderr warning to print first, or undefined when detection was clean. */\n warning: string | undefined;\n}\n\n/**\n * Consolidated entry decision. Runs when detected as main. Otherwise, ONLY when\n * the runtime gave no definitive answer (import.meta.main === undefined) and the\n * basename looks like one of our binaries, force-runs with a fail-loud warning —\n * an explicit import.meta.main === false is authoritative and never overridden.\n * binNames[0] is used as the label in the warning (the user-facing bin name).\n */\nexport function shouldRunAsEntry(\n argv1: string | undefined,\n moduleUrl: string,\n importMetaMain: boolean | undefined,\n binNames: string[],\n): EntryDecision {\n if (isMainModule(argv1, moduleUrl, importMetaMain)) {\n return { run: true, warning: undefined };\n }\n if (importMetaMain === undefined && shouldForceEntry(argv1, binNames)) {\n return {\n run: true,\n warning: `${binNames[0]}: entry detection failed — treating as main; report at github.com/gabros20/linkedin-relay/issues`,\n };\n }\n return { run: false, warning: undefined };\n}\n"],"mappings":";;;AAkBA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,SAAS;;;ACHlB,SAAS,gBAAgB;AACzB,SAAS,aAAAA,YAAW,cAAAC,mBAAkB;;;ACAtC,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAEvB,S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