trylode 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1344 @@
1
+ #!/usr/bin/env node
2
+ // Lode Integration Check: verified, source-linked facts about how one product works with another
3
+ // (Xero, QuickBooks Online, HubSpot, Shopify, Stripe, Supabase, Vercel, Netlify, n8n, Lovable, Replit,
4
+ // Linear, GitHub, LangChain), read from Lode's
5
+ // public JSON API at https://trylode.io/api/. No key, no account, no dependencies (Node 18+).
6
+ //
7
+ // node lode.mjs check <app> [platform] facts for one app, on one platform or on every platform Lode covers
8
+ // node lode.mjs list <platform> [--category <c>] [--all] apps Lode covers on a platform
9
+ // node lode.mjs platforms platforms Lode covers
10
+ // node lode.mjs find <platform> [--category <c>] [--needs a,b] [--region XX] [--stack a,b] [--framework f]
11
+ // options ranked by fit to the stated needs (never by payment)
12
+ // node lode.mjs chose <app|none> <platform> [--considered "A,B"] [--reason <code>] [--needs a,b] [--region XX] [--share]
13
+ // node lode.mjs outcome <app> <platform> <integrated|failed|abandoned|not-tried> [--failure-reason <code>] [--switched-to <app>] [--share]
14
+ // node lode.mjs request <app> <platform> [--needs a,b] [--region XX] tell Lode about an integration it lacks
15
+ // node lode.mjs overlap <platform> --apps "A,B,C" [--region XX] [--share]
16
+ // which of the apps write the same objects into the platform
17
+ // node lode.mjs recheck [--share] what changed in Lode since each integration in lode-integrations.json was chosen
18
+ // node lode.mjs drop <app> <platform> [--reason <code>] [--switched-to <app>] [--share]
19
+ // mark an integration in lode-integrations.json as dropped (or swapped)
20
+ // node lode.mjs adr <platform> --considered "A,B" --chose B [--reason <code>] [--status <s>] [--constraint a,b] [--workaround a,b] [--share]
21
+ // node lode.mjs adr --update <file> [--status <s>] [--constraint a,b] [--workaround a,b] [--share]
22
+ // write or update a decision record in docs/adr/ in the current folder
23
+ // node lode.mjs stack [--framework f] [--share] what Lode documents about the apps and platforms this project's manifests name
24
+ // node lode.mjs triage <app> <platform> --symptom <code> [--status 429] [--object o] [--outcome fixed|switched|gave-up] [--switched-to <app>] [--share]
25
+ // why an integration fails: Lode's sourced facts for that kind of failure
26
+ // node lode.mjs init [--client claude|cursor|all] [--yes] [--remove]
27
+ // add Lode to this project so every teammate and sub-agent has it (shows the files first)
28
+ //
29
+ // What Lode receives: the app, platform and options in each request (for find and request: the needs,
30
+ // region, stack names and fixed codes you pass). chose and outcome send nothing unless --share is
31
+ // added after the user agrees; then they send the chosen app, the apps considered, fixed codes, needs
32
+ // and region. overlap only reads Lode's
33
+ // public records (one request per app), so Lode sees which records were read, as for check; with
34
+ // --share it also sends the platform, the app list and the region, and only then. chose also reads the
35
+ // chosen app's public record and saves it in lode-integrations.json in the current folder; that file
36
+ // stays on your machine. recheck reads the public record of each integration in it. Only with --share
37
+ // do recheck and drop send, per platform, the file's random project code and, for each integration,
38
+ // its Lode id, kept, dropped or swapped, the fixed reason code and how many days since it was chosen.
39
+ // adr writes docs/adr/NNN-<platform>-<app>.md from Lode's public records and saves nothing else; only with
40
+ // --share does it send the project code, platform, the Lode ids considered and chosen (only a count of other options),
41
+ // the fixed reason, status, constraint and workaround codes, and the days since the decision. stack reads
42
+ // only package.json, requirements.txt, pyproject.toml, Gemfile, go.mod, the variable NAMES in .env.example
43
+ // (never values), vercel.json, netlify.toml and supabase/config.toml, then Lode's public files; only with
44
+ // --share does it send the app and platform codes it found and the framework. triage sends the app, the platform,
45
+ // one fixed symptom code and the HTTP status if given (Lode keeps only its class); never error text, logs or code;
46
+ // the outcome only with --share. init writes only Lode's server address into .mcp.json and/or .cursor/mcp.json and
47
+ // copies this skill into .claude/skills/, after showing the files and only with --yes; it sends nothing to Lode.
48
+ // Nothing else from your project, prompt or machine is sent; no free text. https://trylode.io/privacy/
49
+ import { createHash, randomUUID } from 'node:crypto';
50
+ import { readFileSync, writeFileSync as fsWriteFileSync, existsSync, readdirSync, mkdirSync, lstatSync, realpathSync } from 'node:fs';
51
+ import { join, resolve as resolvePath, relative as relativePath, isAbsolute as isAbsolutePath } from 'node:path';
52
+ import { pathToFileURL } from 'node:url';
53
+
54
+ const BASE = (process.env.LODE_BASE || 'https://trylode.io').replace(/\/$/, '');
55
+ const UA = process.env.LODE_UA || 'lode-skill/0.1 (+https://trylode.io/agents/)';
56
+
57
+ export const NAMES = { xero: 'Xero', 'quickbooks-online': 'QuickBooks Online', hubspot: 'HubSpot', shopify: 'Shopify', stripe: 'Stripe', supabase: 'Supabase', vercel: 'Vercel', netlify: 'Netlify', n8n: 'n8n', lovable: 'Lovable', replit: 'Replit', linear: 'Linear', github: 'GitHub', langchain: 'LangChain', cursor: 'Cursor', cloudflare: 'Cloudflare' };
58
+ export const PLATFORMS = {
59
+ xero: ['xero'],
60
+ 'quickbooks-online': ['quickbooks-online', 'quickbooks', 'qbo', 'quickbooks online', 'intuit quickbooks'],
61
+ hubspot: ['hubspot'],
62
+ shopify: ['shopify'],
63
+ stripe: ['stripe'],
64
+ supabase: ['supabase'],
65
+ vercel: ['vercel'],
66
+ netlify: ['netlify'],
67
+ n8n: ['n8n'],
68
+ lovable: ['lovable', 'lovable dev', 'lovable.dev'],
69
+ replit: ['replit'],
70
+ linear: ['linear', 'linear app', 'linear.app'],
71
+ github: ['github', 'github.com', 'github marketplace'],
72
+ langchain: ['langchain', 'lang chain', 'langgraph'],
73
+ cursor: ['cursor', 'cursor marketplace', 'cursor.com'],
74
+ cloudflare: ['cloudflare', 'cloudflare workers', 'cloudflare pages'],
75
+ };
76
+
77
+ const norm = (s = '') => String(s).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/&/g, ' and ').replace(/[^a-z0-9]+/g, ' ').trim();
78
+ const slugish = (s = '') => norm(s).replace(/ /g, '-');
79
+
80
+ export function platformSlug(input) {
81
+ const n = norm(input);
82
+ for (const [slug, names] of Object.entries(PLATFORMS)) if (names.some((x) => norm(x) === n)) return slug;
83
+ return null;
84
+ }
85
+
86
+ // Rank entries ({id, name, aliases?, domains?}) against what the user typed. Exact id or name first,
87
+ // then a name that starts with it, then a whole-word match. Never guesses past that.
88
+ export function matchApp(query, entries) {
89
+ const q = norm(query), qs = slugish(query);
90
+ if (!q) return [];
91
+ const score = (e) => {
92
+ const names = [e.name, ...(e.aliases || [])].filter(Boolean).map(norm);
93
+ const id = String(e.id || '').split('--')[0];
94
+ if (id === qs || names.includes(q)) return 3;
95
+ if ((e.domains || []).some((d) => norm(d.split('.')[0]) === q)) return 3;
96
+ if (names.some((n) => n.startsWith(q + ' ')) || id.startsWith(qs + '-')) return 2;
97
+ if (names.some((n) => ` ${n} `.includes(` ${q} `))) return 1;
98
+ return 0;
99
+ };
100
+ const scored = entries.map((e) => [score(e), e]).filter(([s]) => s > 0).sort((a, b) => b[0] - a[0]);
101
+ if (!scored.length) return [];
102
+ const best = scored[0][0];
103
+ return scored.filter(([s]) => s === best).map(([, e]) => e);
104
+ }
105
+
106
+ async function post(path, body) {
107
+ const res = await fetch(`${BASE}${path}`, { method: 'POST', headers: { 'user-agent': UA, 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(body) });
108
+ const json = await res.json().catch(() => ({}));
109
+ if (!res.ok && res.status !== 400) throw new Error(`Lode answered HTTP ${res.status} for ${path}`);
110
+ return json;
111
+ }
112
+
113
+ export const CHOICE_REASONS = ['sync-coverage', 'price', 'region', 'setup-effort', 'limitations', 'plan-requirement', 'already-uses', 'vendor-preference', 'other'];
114
+ export const OUTCOMES = ['integrated', 'failed', 'abandoned', 'not-tried'];
115
+ export const FAILURE_REASONS = ['auth', 'api-error', 'docs', 'missing-feature', 'plan-required', 'pricing', 'region', 'sdk', 'limits', 'other'];
116
+ const list = (v) => (typeof v === 'string' ? v.split(',').map((x) => x.trim()).filter(Boolean) : undefined);
117
+
118
+ // Pick the platform's category that a loose word means ("auth" -> "authentication").
119
+ export function categoryFor(word, items) {
120
+ if (!word) return undefined;
121
+ const c = slugish(word);
122
+ const cats = [...new Set(items.flatMap((i) => i.categories || []))];
123
+ return cats.find((x) => x === c) || cats.find((x) => x.startsWith(c)) || cats.find((x) => x.includes(c));
124
+ }
125
+
126
+ export function formatFind(body, ecoName) {
127
+ const r = body.results || [];
128
+ const p = body.profile || {};
129
+ const out = [`## ${ecoName}: ${r.length} option(s) for ${[p.category, p.needs?.length ? `needs ${p.needs.join(', ')}` : '', p.region ? `in ${p.region}` : ''].filter(Boolean).join(', ') || 'your search'}`];
130
+ for (const [i, x] of r.entries()) out.push(`${i + 1}. ${x.app}: ${(x.reasons || []).join('; ') || 'no stated fit'} | ${x.url} | verified ${x.last_verified || 'unknown'}${x.in_stack ? ' | already in your stack' : ''}`);
131
+ if (body.excluded_count) out.push(`${body.excluded_count} other app(s) in scope did not meet the needs or region given.`);
132
+ for (const n of body.input_notes || []) out.push(`Note: ${n}`);
133
+ out.push('Ranked by fit to the needs given; equal scores are genuine ties. Lode never sells placement. Get facts for one option with: node lode.mjs check "<app>" <platform>');
134
+ return out.join('\n');
135
+ }
136
+
137
+ async function get(path) {
138
+ const res = await fetch(`${BASE}${path}`, { headers: { 'user-agent': UA, accept: 'application/json' } });
139
+ if (res.status === 404) return null;
140
+ if (!res.ok) throw new Error(`Lode answered HTTP ${res.status} for ${path}`);
141
+ return res.json();
142
+ }
143
+
144
+ const DIR = { 'app-to-ecosystem': 'app → platform', 'ecosystem-to-app': 'platform → app', 'two-way': 'both ways', supported: 'supported; direction not documented', 'not-supported': 'documented as not supported' };
145
+ const money = (prices = {}) => Object.entries(prices).map(([c, v]) => `${c} ${v}`).join(' / ');
146
+ // A plan whose every price is 0 (and has no usage rate) is free: say so in words, never "USD 0" (Paul, 26-11-2026, LOD-152)
147
+ const isFreePlan = (pl) => !pl.rate && Object.keys(pl.prices || {}).length > 0 && Object.values(pl.prices).every((v) => v === 0);
148
+ const freePlan = (name = '') => (/free/i.test(name) ? (/plan/i.test(name) ? name : `${name} plan`) : `${name}: free`);
149
+ const planText = (pl) => (isFreePlan(pl) ? freePlan(pl.name) : `${pl.name}${pl.billing ? ` (${pl.billing})` : ''}: ${money(pl.prices) || pl.rate || 'no published amount'}`);
150
+
151
+ // One record as compact markdown. Facts are Lode's own sentences; every line keeps its sources.
152
+ export function formatRecord(r) {
153
+ const live = r.lode?.publish_state === 'live';
154
+ const name = r.app?.name || r.id;
155
+ const eco = NAMES[r.ecosystem] || r.ecosystem;
156
+ const src = Object.fromEntries((r.sources || []).map((s) => [s.id, s]));
157
+ const cite = (ids = []) => ids.map((id) => src[id]?.url).filter(Boolean);
158
+ const out = [];
159
+ out.push(`## ${name} + ${eco}`);
160
+ out.push(`Lode page: ${r.url} | last verified ${r.verification?.last_verified || 'unknown'}${live ? '' : ' | HELD: Lode has not published this record yet; treat its facts as unconfirmed'}`);
161
+ const c = r.connection || {};
162
+ out.push(`Built by: ${c.built_by || 'not documented'}${c.method ? ` (${c.method})` : ''}${c.certified_by_ecosystem?.value ? '; certified by the platform' : ''}`);
163
+ if (c.setup_docs_url) out.push(`Setup guide: ${c.setup_docs_url}`);
164
+ if (c.marketplace_listing_url) out.push(`Marketplace listing: ${c.marketplace_listing_url}`);
165
+ if (r.sync?.length) {
166
+ out.push('', 'What syncs:');
167
+ for (const s of r.sync) {
168
+ const trig = (s.flows || []).filter((f) => f.trigger && f.trigger !== 'unknown').map((f) => `${f.from === 'app' ? 'from app' : 'from platform'}: ${f.trigger}${f.interval ? ` every ${f.interval}` : ''}`).join('; ');
169
+ out.push(`- ${s.object}: ${DIR[s.direction] || s.direction}${trig ? ` (${trig})` : ''}${s.notes ? `. ${s.notes}` : ''} [${cite(s.src).join(' ')}]`);
170
+ }
171
+ }
172
+ const p = r.pricing || {};
173
+ if (p.model || p.plans?.length) {
174
+ out.push('', `Pricing (${p.model || 'model not stated'}):`);
175
+ for (const pl of p.plans || []) out.push(`- ${planText(pl)}${pl.per ? `, ${pl.per}` : ''} [${cite(pl.src).join(' ')}]`);
176
+ }
177
+ const req = r.requirements || {};
178
+ out.push('', `Platform plan needed: ${req.ecosystem_plan_min && req.ecosystem_plan_min !== 'unknown' ? req.ecosystem_plan_min : 'not documented'}`);
179
+ const reg = r.regions || {};
180
+ out.push(`Regions: ${reg.basis === 'no-restriction-stated' ? 'no restriction stated' : (reg.supported || []).join(', ') || 'not documented'}`);
181
+ if (r.limitations?.length) {
182
+ out.push('', 'Known limitations:');
183
+ for (const l of r.limitations) out.push(`- ${l.summary} [${cite(l.src).join(' ')}]`);
184
+ }
185
+ if (r.verification?.open_flags?.length) out.push('', `Open questions on this record: ${r.verification.open_flags.length}`);
186
+ out.push('', `Cite as: ${r.cite_as || `Lode (trylode.io), ${name} + ${eco}`}`);
187
+ out.push('Anything not listed here is not documented by Lode. That does not mean it is unsupported.');
188
+ return out.join('\n');
189
+ }
190
+
191
+ export function formatList(eco, items, { category, all } = {}) {
192
+ const c = category ? slugish(category) : null;
193
+ const rows = items.filter((i) => !c || (i.categories || []).some((x) => x === c || x.startsWith(c) || x.includes(c)))
194
+ .sort((a, b) => String(a.app).localeCompare(String(b.app)));
195
+ const shown = all ? rows : rows.slice(0, 40);
196
+ const out = [`## Apps Lode covers on ${eco.name}${category ? ` (category: ${category})` : ''}: ${rows.length}`, `Platform page: ${eco.url}`];
197
+ for (const i of shown) out.push(`- ${i.app} [${(i.categories || []).join(', ')}]: ${i.summary || ''} (details: node lode.mjs check "${i.app}" ${eco.slug})`);
198
+ if (rows.length > shown.length) out.push(`...and ${rows.length - shown.length} more (add --all, or --category to narrow).`);
199
+ if (!rows.length && category) out.push(`No apps in that category. Categories on ${eco.name}: ${[...new Set(items.flatMap((i) => i.categories || []))].sort().join(', ')}`);
200
+ out.push('Order is alphabetical by Lode, not a ranking. Lode never sells placement.');
201
+ return out.join('\n');
202
+ }
203
+
204
+ async function check(app, platform) {
205
+ if (platform) {
206
+ const eco = platformSlug(platform);
207
+ if (!eco) return `Lode does not cover "${platform}" yet. Platforms covered: ${Object.keys(PLATFORMS).join(', ')}.`;
208
+ const index = await get(`/api/ecosystems/${eco}.json`);
209
+ const entries = (index?.integrations || []).map((i) => ({ ...i, name: i.app }));
210
+ const hits = matchApp(app, entries);
211
+ if (!hits.length) return `Lode has no record of "${app}" on ${index?.name || eco}. That means not documented by Lode, not that no integration exists. List what Lode covers: node lode.mjs list ${eco}. If the user needs it, tell Lode (with their agreement): node lode.mjs request "${app}" ${eco}`;
212
+ if (hits.length > 1) return `"${app}" matches more than one app on ${index.name}: ${hits.map((h) => h.app).join('; ')}. Run check again with the exact name.`;
213
+ const slug = hits[0].id.split('--')[0];
214
+ const rec = await get(`/api/integrations/${eco}/${slug}.json`);
215
+ return rec ? formatRecord(rec) : `Lode lists ${hits[0].app} on ${index.name} but its record could not be read (${hits[0].api}).`;
216
+ }
217
+ const vendors = (await get('/api/vendors/index.json'))?.vendors || [];
218
+ const hits = matchApp(app, vendors);
219
+ if (!hits.length) return `Lode has no vendor called "${app}". That means not documented by Lode, not that no integration exists.`;
220
+ if (hits.length > 1) return `"${app}" matches more than one vendor: ${hits.map((h) => h.name).join('; ')}. Run check again with the exact name.`;
221
+ const v = hits[0];
222
+ const detail = await get(`/api/vendors/${v.id}.json`);
223
+ const list = detail?.integrations || v.integrations.map((id) => ({ integration_id: id, ecosystem: id.split('--')[1] }));
224
+ const out = [`## ${v.name}: Lode covers ${list.length} integration(s)`];
225
+ for (const i of list) out.push(`- ${NAMES[i.ecosystem] || i.ecosystem}: ${i.page || ''} (details: node lode.mjs check "${v.name}" ${i.ecosystem})`);
226
+ out.push('Run check with a platform for the facts: what syncs and which way, price, plan needed, regions, limitations, sources.');
227
+ return out.join('\n');
228
+ }
229
+
230
+ async function platformIndex(p) {
231
+ const eco = platformSlug(p);
232
+ if (!eco) throw new Error(`Lode does not cover "${p}" yet. Platforms covered: ${Object.keys(PLATFORMS).join(', ')}`);
233
+ return { eco, index: await get(`/api/ecosystems/${eco}.json`) };
234
+ }
235
+ function idFor(app, index) {
236
+ if (String(app).toLowerCase() === 'none') return 'none';
237
+ const hits = matchApp(app, (index.integrations || []).map((i) => ({ ...i, name: i.app })));
238
+ if (hits.length !== 1) throw new Error(hits.length ? `"${app}" matches more than one app: ${hits.map((h) => h.app).join('; ')}` : `Lode has no record of "${app}" on ${index.name}`);
239
+ return hits[0].id;
240
+ }
241
+
242
+ // LOD-93: kept identical in logic to stackOverlap in Lode's src/lib/overlap.mjs (tests check both agree).
243
+ export const OVERLAP_NOTE = 'Facts from Lode\'s published records only. An object not listed for an app means Lode has not documented it, not that the app does not sync it. Two apps writing the same object, or both syncing it two-way, is worth checking in each app\'s settings and docs; this is a list of documented facts, not a recommendation.';
244
+ export function stackOverlap(platform, records, { not_found = [], ambiguous = [], region } = {}) {
245
+ const byId = new Map();
246
+ for (const r of records) if (r && r.ecosystem === platform && !byId.has(r.id)) byId.set(r.id, r);
247
+ const all = [...byId.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
248
+ const live = all.filter((r) => r.lode?.publish_state === 'live');
249
+ const held = all.filter((r) => r.lode?.publish_state !== 'live').map((r) => ({ id: r.id, app: r.app?.name ?? r.id, url: r.url }));
250
+ const objects = {};
251
+ for (const r of live) {
252
+ const src = Object.fromEntries((r.sources ?? []).map((s) => [s.id, s.url]));
253
+ for (const s of r.sync ?? []) {
254
+ const o = (objects[s.object] ??= { writers: [], undirected: [] });
255
+ const sources = [...new Set((s.src ?? []).map((id) => src[id]).filter(Boolean))];
256
+ const app = r.app?.name ?? r.id;
257
+ if (s.direction === 'app-to-ecosystem' || s.direction === 'two-way') {
258
+ const flows = (s.flows ?? []).filter((f) => f.trigger && f.trigger !== 'unknown').map((f) => ({ from: f.from, trigger: f.trigger, ...(f.interval ? { interval: f.interval } : {}) }));
259
+ o.writers.push({ id: r.id, app, direction: s.direction, ...(flows.length ? { flows } : {}), sources });
260
+ } else if (s.direction === 'supported') o.undirected.push({ id: r.id, app, sources });
261
+ }
262
+ }
263
+ const writes = [], two_way_pairs = [], documented_no_direction = [];
264
+ for (const object of Object.keys(objects).sort()) {
265
+ const { writers, undirected } = objects[object];
266
+ if (!writers.length) continue;
267
+ writes.push({ object, apps: writers });
268
+ const two = writers.filter((w) => w.direction === 'two-way').map((w) => w.id);
269
+ for (let i = 0; i < two.length; i++) for (let j = i + 1; j < two.length; j++) two_way_pairs.push({ object, apps: [two[i], two[j]] });
270
+ for (const u of undirected) if (writers.some((w) => w.id !== u.id)) documented_no_direction.push({ object, ...u });
271
+ }
272
+ const listed = (r) => { const rs = r.regions?.supported ?? []; return rs.includes('GLOBAL') || rs.includes(region); };
273
+ return {
274
+ platform, ...(region ? { region } : {}),
275
+ checked: live.map((r) => ({ id: r.id, app: r.app?.name ?? r.id, url: r.url, last_verified: r.verification?.last_verified, ...(region && !listed(r) ? { region_not_listed: true } : {}) })),
276
+ held, not_found: [...not_found], ...(ambiguous.length ? { ambiguous: [...ambiguous] } : {}),
277
+ writes, shared_objects: writes.filter((w) => w.apps.length > 1).map((w) => w.object), two_way_pairs, documented_no_direction,
278
+ note: OVERLAP_NOTE,
279
+ };
280
+ }
281
+
282
+ const FLOW = (f) => `from ${f.from === 'app' ? 'app' : 'platform'}: ${f.trigger}${f.interval ? ` every ${f.interval}` : ''}`;
283
+ export function formatOverlap(o, ecoName) {
284
+ const app = Object.fromEntries([...o.checked, ...o.held].map((c) => [c.id, c.app]));
285
+ const line = (w) => `${w.app} (${DIR[w.direction] || w.direction}${w.flows?.length ? `; ${w.flows.map(FLOW).join('; ')}` : ''}) [${w.sources.join(' ')}]`;
286
+ const out = [`## Stack overlap on ${ecoName}: ${o.checked.length} app(s) checked`];
287
+ for (const c of o.checked) out.push(`- ${c.app}: ${c.url} | verified ${c.last_verified || 'unknown'}${c.region_not_listed ? ` | Lode's record does not list ${o.region} among its regions` : ''}`);
288
+ const shared = o.writes.filter((w) => w.apps.length > 1), single = o.writes.filter((w) => w.apps.length === 1);
289
+ out.push('', shared.length ? `Objects more than one of these apps writes into ${ecoName}:` : `No object is documented as written into ${ecoName} by more than one of these apps.`);
290
+ for (const w of shared) {
291
+ out.push(`- ${w.object}: ${w.apps.map(line).join('; ')}`);
292
+ for (const p of o.two_way_pairs.filter((x) => x.object === w.object)) out.push(` Both two-way (possible loop): ${app[p.apps[0]]} and ${app[p.apps[1]]}`);
293
+ }
294
+ const nd = o.documented_no_direction;
295
+ if (nd.length) {
296
+ out.push('', 'Also documented on objects another app writes, with no direction recorded:');
297
+ for (const d of nd) out.push(`- ${d.object}: ${d.app} [${d.sources.join(' ')}]`);
298
+ }
299
+ if (single.length) {
300
+ out.push('', `Written into ${ecoName} by one app:`);
301
+ for (const w of single) out.push(`- ${w.object}: ${line(w.apps[0])}`);
302
+ }
303
+ if (o.held.length) out.push('', `Held (not yet published by Lode; facts not used): ${o.held.map((h) => h.app).join(', ')}`);
304
+ for (const a of o.ambiguous || []) out.push(`"${a.input}" matches more than one app: ${a.matches.join('; ')}. Run again with the exact name.`);
305
+ if (o.not_found.length) out.push('', `Not in Lode on ${ecoName}: ${o.not_found.join(', ')} (not documented by Lode, not that no integration exists).`);
306
+ out.push('', o.note);
307
+ return out.join('\n');
308
+ }
309
+
310
+ const REGION = (r) => { const x = String(r).trim().toUpperCase(); return x === 'GB' ? 'UK' : x; };
311
+ async function overlap(platform, apps, { region, share } = {}) {
312
+ const { eco, index } = await platformIndex(platform);
313
+ const entries = (index?.integrations || []).map((i) => ({ ...i, name: i.app }));
314
+ const found = [], not_found = [], ambiguous = [];
315
+ for (const a of apps.slice(0, 20)) {
316
+ const hits = matchApp(a, entries);
317
+ if (hits.length === 1) { if (!found.some((f) => f.id === hits[0].id)) found.push(hits[0]); } else if (hits.length) ambiguous.push({ input: a, matches: hits.map((h) => h.id).sort() }); else not_found.push(a);
318
+ }
319
+ const records = (await Promise.all(found.map((h) => get(`/api/integrations/${eco}/${h.id.split('--')[0]}.json`)))).filter(Boolean);
320
+ const reg = typeof region === 'string' ? REGION(region) : undefined;
321
+ let text = formatOverlap(stackOverlap(eco, records, { not_found, ambiguous, region: reg }), index.name);
322
+ if (share) {
323
+ const r = await post('/v1/feedback/stack', { platform: eco, apps: [...found.map((h) => h.id), ...not_found, ...ambiguous.map((x) => x.input)], ...(reg ? { region: reg } : {}) });
324
+ text += r.recorded ? '\n\nShared with Lode: the platform and this app list.' : `\n\nLode did not record the stack${r.message ? `: ${r.message}` : ''}.`;
325
+ }
326
+ return text;
327
+ }
328
+
329
+ // D51 (LOD-90): integration retention. `chose` keeps a local list of chosen integrations in
330
+ // lode-integrations.json in the current folder; `recheck` says what changed in Lode since each was
331
+ // chosen; `drop` marks one dropped or swapped. The file holds no secrets. Nothing in it is sent unless
332
+ // the user passes --share, and then only the project code, Lode ids, states, reason codes and days.
333
+ export const LOCAL_FILE = 'lode-integrations.json';
334
+ export const RETENTION_REASONS = ['missing-feature', 'price', 'sync-errors', 'setup-effort', 'replaced', 'no-longer-needed', 'other'];
335
+ const localPath = () => join(process.cwd(), LOCAL_FILE);
336
+ // Every file the skill writes in a project goes through here: it refuses a target that is a link, or that sits under
337
+ // a link, so a project can't redirect a write to a file elsewhere (independent security review, 30-11-2026).
338
+ // Checked from the project folder down (the folders above it are the user's own business), plus the target itself.
339
+ export function viaLink(target, cwd = process.cwd()) {
340
+ let root; try { root = realpathSync(cwd); } catch { root = resolvePath(cwd); }
341
+ const abs = resolvePath(root, target);
342
+ const parts = [abs];
343
+ const rel = relativePath(root, abs);
344
+ if (rel && !rel.startsWith('..') && !isAbsolutePath(rel)) { let p = root; for (const part of rel.split(/[\\/]/).slice(0, -1)) { p = join(p, part); parts.push(p); } }
345
+ return parts.some((p) => { try { return lstatSync(p).isSymbolicLink(); } catch { return false; } });
346
+ }
347
+ function writeFileSync(target, data) {
348
+ if (viaLink(target)) throw new Error(`${target} is a link or sits under one, so the Lode skill won't write there`);
349
+ return fsWriteFileSync(target, data);
350
+ }
351
+ // A random code made once per file, never derived from paths, names or the machine
352
+ export const newProject = () => randomUUID().replace(/-/g, '').slice(0, 16);
353
+
354
+ // JSON with object keys sorted, so the same facts always hash the same way
355
+ const stable = (v) => JSON.stringify(v, (k, x) => (x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.keys(x).sort().map((key) => [key, x[key]])) : x));
356
+ // The facts a buyer acts on: who built it, what syncs which way and how, prices, platform plan, regions,
357
+ // limitations. Sources, dates and wording of notes are left out, so a re-check alone does not count as a change.
358
+ export function factsOf(r) {
359
+ const c = r.connection || {};
360
+ const key = (s) => `${s.object}|${s.direction}`;
361
+ return {
362
+ connection: { built_by: c.built_by ?? null, method: c.method ?? null },
363
+ sync: (r.sync || []).map((s) => ({ object: s.object, direction: s.direction, flows: (s.flows || []).map((f) => ({ from: f.from, trigger: f.trigger ?? null, interval: f.interval ?? null })) })).sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0)),
364
+ pricing: { model: r.pricing?.model ?? null, plans: (r.pricing?.plans || []).map((p) => ({ name: p.name, billing: p.billing ?? null, prices: p.prices ?? null, rate: p.rate ?? null })) },
365
+ plan_min: r.requirements?.ecosystem_plan_min ?? null,
366
+ regions: [...(r.regions?.supported || [])].sort(),
367
+ limitations: (r.limitations || []).map((l) => l.summary).sort(),
368
+ };
369
+ }
370
+ export const factsHash = (r) => createHash('sha256').update(stable(factsOf(r))).digest('hex').slice(0, 12);
371
+ export function priceLine(r) {
372
+ const p = r.pricing || {};
373
+ const plans = (p.plans || []).map(planText);
374
+ const line = plans.length ? plans.join('; ') : p.model ? `pricing model: ${p.model}` : 'not documented';
375
+ return line.length > 300 ? `${line.slice(0, 297)}...` : line;
376
+ }
377
+
378
+ export function readLocal(path = localPath()) {
379
+ if (!existsSync(path)) return null;
380
+ let f;
381
+ try { f = JSON.parse(readFileSync(path, 'utf8')); } catch (e) { throw new Error(`${LOCAL_FILE} could not be read (${e.message}); fix or remove it`); }
382
+ if (!f || typeof f !== 'object' || !Array.isArray(f.integrations)) throw new Error(`${LOCAL_FILE} is not in the expected format; fix or remove it`);
383
+ return f;
384
+ }
385
+ const writeLocal = (f, path = localPath()) => writeFileSync(path, JSON.stringify(f, null, 2) + '\n');
386
+ const freshFile = () => ({ version: 1, project: newProject(), share: false, integrations: [] });
387
+ const DAY = 86400000;
388
+ export const daysBetween = (from, to = new Date()) => { const a = Date.parse(from); return Number.isFinite(a) ? Math.max(0, Math.floor((new Date(to).getTime() - a) / DAY)) : undefined; };
389
+
390
+ // Save a chosen integration locally. A record chosen again while kept keeps its first date; one dropped
391
+ // earlier and chosen again starts over as kept.
392
+ export function rememberChoice(f, rec, platform, now = new Date()) {
393
+ const entry = { id: rec.id, platform, chosen_at: now.toISOString(), last_verified: rec.verification?.last_verified ?? null, facts_hash: factsHash(rec), state: 'kept', url: rec.url, price: priceLine(rec) };
394
+ const i = f.integrations.findIndex((x) => x.id === rec.id);
395
+ if (i >= 0 && f.integrations[i].state === 'kept') return f.integrations[i];
396
+ if (i >= 0) f.integrations[i] = entry; else f.integrations.push(entry);
397
+ return entry;
398
+ }
399
+
400
+ async function saveChoice(eco, id) {
401
+ try {
402
+ const rec = await get(`/api/integrations/${eco}/${id.split('--')[0]}.json`);
403
+ if (!rec) return '';
404
+ const f = readLocal() || freshFile();
405
+ rememberChoice(f, rec, eco);
406
+ writeLocal(f);
407
+ return `\nSaved to ${LOCAL_FILE} in this folder; the file stays on this machine. Later, run: node lode.mjs recheck`;
408
+ } catch (e) { return `\nNot saved to ${LOCAL_FILE}: ${e.message}.`; }
409
+ }
410
+
411
+ // One line per integration: what changed in Lode since it was chosen. `rec` is the public record now (null if gone).
412
+ export function formatRecheckItem(it, rec, now = new Date()) {
413
+ const eco = NAMES[it.platform] || it.platform;
414
+ const name = rec?.app?.name || it.id.split('--')[0];
415
+ const since = String(it.chosen_at || '').slice(0, 10) || 'unknown date';
416
+ const out = [`- ${name} on ${eco}: ${it.state}${it.state === 'swapped' && it.switched_to ? ` for ${it.switched_to}` : ''}, chosen ${since} (${daysBetween(it.chosen_at, now) ?? '?'} days ago) | ${rec?.url || it.url || ''}`];
417
+ if (it.state !== 'kept') { out.push(` Not rechecked: marked ${it.state}${it.reason ? ` (${it.reason})` : ''}${it.dropped_at ? ` on ${String(it.dropped_at).slice(0, 10)}` : ''}.`); return out.join('\n'); }
418
+ if (!rec) { out.push(' No longer in Lode: the record has been removed. Check the integration with the vendor directly.'); return out.join('\n'); }
419
+ if (rec.lode?.publish_state !== 'live') out.push(' Now HELD by Lode: it has not confirmed this record\'s facts; treat them as unconfirmed.');
420
+ const lv = rec.verification?.last_verified;
421
+ out.push(` Last verified: ${it.last_verified || 'unknown'} when chosen; ${lv || 'unknown'} now${lv && lv !== it.last_verified ? ' (re-checked since)' : ''}`);
422
+ const changed = it.facts_hash && factsHash(rec) !== it.facts_hash;
423
+ out.push(changed ? ` Facts CHANGED since chosen (sync, price, plan, regions or limitations). Read the record: node lode.mjs check "${name}" ${it.platform}` : it.facts_hash ? ' Facts unchanged since chosen.' : ' Facts at the time of choosing were not saved, so changes cannot be compared.');
424
+ const p = priceLine(rec);
425
+ if (it.price && p !== it.price) out.push(` Price then: ${it.price}`, ` Price now: ${p}`);
426
+ return out.join('\n');
427
+ }
428
+
429
+ // What --share sends for one platform: the project code and, per integration, its id, state, reason and days
430
+ export function retentionPayload(f, platform, now = new Date()) {
431
+ return {
432
+ project: f.project, platform,
433
+ items: f.integrations.filter((x) => x.platform === platform).map((x) => ({
434
+ id: x.id, state: x.state, ...(x.state !== 'kept' && x.reason ? { reason: x.reason } : {}), ...(x.state === 'swapped' && x.switched_to ? { switched_to: x.switched_to } : {}),
435
+ // days since chosen; for an integration dropped or swapped, how long it was kept
436
+ ...(daysBetween(x.chosen_at, x.state !== 'kept' && x.dropped_at ? x.dropped_at : now) !== undefined ? { days: daysBetween(x.chosen_at, x.state !== 'kept' && x.dropped_at ? x.dropped_at : now) } : {}),
437
+ })),
438
+ };
439
+ }
440
+
441
+ async function shareRetention(f, platforms) {
442
+ const out = [];
443
+ for (const platform of platforms) {
444
+ const body = retentionPayload(f, platform);
445
+ for (let i = 0; i < body.items.length; i += 20) {
446
+ const r = await post('/v1/feedback/retention', { ...body, items: body.items.slice(i, i + 20) });
447
+ out.push(r.recorded ? `Shared with Lode for ${NAMES[platform] || platform}: the project code, and for each integration whether it is kept, dropped or swapped and how many days since it was chosen.` : `Lode did not record this for ${platform}${r.message ? `: ${r.message}` : ''}.`);
448
+ }
449
+ }
450
+ return out.join('\n');
451
+ }
452
+
453
+ async function recheck({ share } = {}) {
454
+ const f = readLocal();
455
+ if (!f || !f.integrations.length) return `No integrations recorded in ${LOCAL_FILE} in this folder. It is made when a choice is recorded: node lode.mjs chose <app> <platform>`;
456
+ const now = new Date();
457
+ const lines = [`## Recheck of ${f.integrations.length} integration(s) in ${LOCAL_FILE}`];
458
+ for (const it of f.integrations) {
459
+ const rec = it.state === 'kept' ? await get(`/api/integrations/${it.platform}/${it.id.split('--')[0]}.json`) : null;
460
+ lines.push(formatRecheckItem(it, rec, now));
461
+ }
462
+ lines.push('', 'Changes are what Lode\'s published record says now against what it said when chosen. Anything not listed is not documented by Lode.');
463
+ const adrs = syncAdrs(f, { now });
464
+ if (adrs.length) lines.push('', `Decision records updated: ${adrs.join('; ')}.`);
465
+ if (share) lines.push('', await shareRetention(f, [...new Set(f.integrations.map((x) => x.platform))]));
466
+ return lines.join('\n');
467
+ }
468
+
469
+ async function drop(app, platform, { reason, switched, share } = {}) {
470
+ const { eco, index } = await platformIndex(platform);
471
+ const id = idFor(app, index);
472
+ if (id === 'none') return 'Name the app to drop.';
473
+ const f = readLocal();
474
+ const it = f?.integrations.find((x) => x.id === id);
475
+ if (!it) return `${id} is not in ${LOCAL_FILE} in this folder. Record it first with: node lode.mjs chose "${app}" ${eco}`;
476
+ let to, unresolved;
477
+ if (typeof switched === 'string') { try { to = idFor(switched, index); } catch { unresolved = switched; } }
478
+ if (to && to !== 'none' && to !== id) { it.state = 'swapped'; it.switched_to = to; } else { it.state = 'dropped'; delete it.switched_to; }
479
+ // A reason outside the fixed list becomes "other"; a replacement Lode doesn't cover counts as "replaced"
480
+ const code = typeof reason === 'string' ? (RETENTION_REASONS.includes(reason) ? reason : 'other') : unresolved ? 'replaced' : undefined;
481
+ if (code) it.reason = code; else delete it.reason;
482
+ it.dropped_at = new Date().toISOString();
483
+ writeLocal(f);
484
+ const adrs = syncAdrs(f);
485
+ let text = `Marked ${id} as ${it.state}${it.switched_to ? ` for ${it.switched_to}` : ''}${it.reason ? ` (reason: ${it.reason})` : ''} in ${LOCAL_FILE}. Nothing was sent.`;
486
+ if (unresolved) text += `\n"${unresolved}" is not in Lode on ${index.name}; it was not recorded. If the user agrees, tell Lode: node lode.mjs request "${unresolved}" ${eco}`;
487
+ if (adrs.length) text += `\nDecision record updated: ${adrs.join('; ')}.`;
488
+ if (it.switched_to) text += `\nTo track the new integration too: node lode.mjs chose "${switched}" ${eco} (saves locally; add --share only if the user agrees)`;
489
+ if (share) {
490
+ const r = await post('/v1/feedback/retention', { project: f.project, platform: eco, items: retentionPayload(f, eco).items.filter((x) => x.id === id) });
491
+ text = text.replace(' Nothing was sent.', '') + (r.recorded ? '\nShared with Lode: the project code, this integration\'s Lode id, its new state, the reason code and how many days it was kept.' : `\nLode did not record it${r.message ? `: ${r.message}` : ''}.`);
492
+ }
493
+ return text;
494
+ }
495
+
496
+ // ---- D55 (LOD-102): integration decision records. `adr` writes docs/adr/NNN-<platform>-<app>.md in the
497
+ // current folder: a short record built only from Lode's public facts, with a structured block of fixed
498
+ // codes in its frontmatter. Nothing is sent unless --share is added after the user agrees; then only the
499
+ // project code, platform, Lode record ids (other options only as a count), the codes, the status and the days since.
500
+ export const DECISION_STATUSES = ['proposed', 'accepted', 'shipped', 'kept', 'dropped', 'swapped'];
501
+ export const CONSTRAINTS = ['plan-wall', 'rate-limit', 'missing-object', 'one-way-only', 'timeout', 'webhook-gap', 'region', 'currency', 'auth', 'price', 'other'];
502
+ export const WORKAROUNDS = ['custom-retry', 'custom-idempotency', 'polling-not-webhooks', 'extra-sync-tool', 'manual-step', 'plan-upgrade', 'custom-field-mapping', 'batching-for-rate-limits', 'background-job-for-timeouts', 'currency-handling', 'other'];
503
+ export const ADR_DIR = join('docs', 'adr');
504
+ export const dmy = (iso) => { const m = String(iso || '').match(/^(\d{4})-(\d{2})-(\d{2})/); return m ? `${m[3]}-${m[2]}-${m[1]}` : 'unknown date'; };
505
+ const today = (now = new Date()) => new Date(now).toISOString().slice(0, 10);
506
+
507
+ // Codes from a comma list; any code outside the fixed list refuses the command (returns the bad ones)
508
+ export function checkCodes(value, allowed) {
509
+ const given = typeof value === 'string' ? value.split(',').map((x) => x.trim().toLowerCase()).filter(Boolean) : [];
510
+ return { codes: [...new Set(given.filter((c) => allowed.includes(c)))], bad: given.filter((c) => !allowed.includes(c)) };
511
+ }
512
+
513
+ // Frontmatter: one `key: value` per line, values as JSON (valid YAML), so the file needs no YAML library
514
+ export function parseAdr(text) {
515
+ // CRLF and a leading BOM are accepted: git on Windows (core.autocrlf) checks the file out with CRLF
516
+ const m = String(text).match(/^?---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
517
+ if (!m) return null;
518
+ const meta = {};
519
+ for (const line of m[1].split(/\r?\n/)) {
520
+ const i = line.indexOf(':');
521
+ if (i < 1) continue;
522
+ const k = line.slice(0, i).trim(), v = line.slice(i + 1).trim();
523
+ try { meta[k] = JSON.parse(v); } catch { meta[k] = v; }
524
+ }
525
+ return meta.lode_adr ? { meta, body: text.slice(m[0].length) } : null;
526
+ }
527
+ const ADR_KEYS = ['lode_adr', 'project', 'platform', 'considered', 'chosen', 'reason', 'status', 'constraints', 'workarounds', 'decided', 'updated', 'rechecked', 'switched_to'];
528
+ export const adrFrontmatter = (meta) => `---\n${ADR_KEYS.filter((k) => meta[k] !== undefined).map((k) => `${k}: ${JSON.stringify(meta[k])}`).join('\n')}\n---\n`;
529
+ const label = (c) => c.replace(/-/g, ' ');
530
+ export function adrCodesBlock(meta) {
531
+ const c = meta.constraints || [], w = meta.workarounds || [];
532
+ return ['<!-- lode:codes -->', `Constraints hit: ${c.length ? c.map(label).join(', ') : 'none recorded'}`, '', `Workarounds built: ${w.length ? w.map(label).join(', ') : 'none recorded'}`, '<!-- /lode:codes -->'].join('\n');
533
+ }
534
+ const statusLine = (meta) => `**Status:** ${meta.status} (${dmy(meta.updated || meta.decided)})${meta.switched_to ? `, switched to ${meta.switched_to}` : ''}`;
535
+
536
+ // The facts for one option, each line with its Lode page and last-verified date. Built only from the
537
+ // public record; anything the record doesn't hold is "not documented", never "not supported".
538
+ export function adrFacts(opt, ecoName) {
539
+ const r = opt.rec;
540
+ if (!r) return [`### ${opt.name}${opt.chosen ? ' (chosen)' : ''}`, `Lode has no record of ${opt.name} on ${ecoName}: not documented by Lode, which does not mean no integration exists.`];
541
+ const at = `[Lode](${r.url}), verified ${dmy(r.verification?.last_verified)}`;
542
+ const src = Object.fromEntries((r.sources || []).map((s) => [s.id, s.url]));
543
+ const out = [`### ${r.app?.name || opt.name}${opt.chosen ? ' (chosen)' : ''}`, `Lode page: ${r.url} (last verified ${dmy(r.verification?.last_verified)})`];
544
+ if (r.lode?.publish_state !== 'live') out.push('Held by Lode: these facts are not yet confirmed.');
545
+ const c = r.connection || {};
546
+ out.push(`- Built by: ${c.built_by || 'not documented'}. ${at}`);
547
+ for (const s of r.sync || []) out.push(`- ${s.object}: ${DIR[s.direction] || s.direction}${s.notes ? `. ${s.notes}` : ''}${(s.src || []).length ? ` (source: ${(s.src || []).map((id) => src[id]).filter(Boolean).join(' ')})` : ''}. ${at}`);
548
+ if (!(r.sync || []).length) out.push(`- What syncs: not documented. ${at}`);
549
+ out.push(`- Price: ${priceLine(r)}. ${at}`);
550
+ const plan = r.requirements?.ecosystem_plan_min;
551
+ out.push(`- ${ecoName} plan needed: ${plan && plan !== 'unknown' ? plan : 'not documented'}. ${at}`);
552
+ const reg = r.regions || {};
553
+ out.push(`- Regions: ${reg.basis === 'no-restriction-stated' ? 'no restriction stated' : (reg.supported || []).join(', ') || 'not documented'}. ${at}`);
554
+ for (const l of r.limitations || []) out.push(`- Limitation: ${String(l.summary).replace(/[.\s]*$/, '.')} ${at}`);
555
+ return out;
556
+ }
557
+
558
+ export function adrMarkdown(meta, options, ecoName, n) {
559
+ const chosen = options.find((o) => o.chosen);
560
+ const title = `# ${String(n).padStart(3, '0')}. ${chosen?.rec?.app?.name || chosen?.name || meta.chosen} for ${ecoName}`;
561
+ return [
562
+ adrFrontmatter(meta) + title, '', statusLine(meta), '',
563
+ '## Context', `Integration needed on ${ecoName}. Options considered: ${options.map((o) => o.rec?.app?.name || o.name).join(', ')}.`, '',
564
+ '## Decision', `Chose ${chosen?.rec?.app?.name || chosen?.name || meta.chosen}${meta.reason ? `. Main reason: ${label(meta.reason)}` : ''}.`, '',
565
+ '## Constraints and workarounds', adrCodesBlock(meta), '',
566
+ `## Facts from Lode on ${dmy(meta.decided)}`, ...options.flatMap((o) => [...adrFacts(o, ecoName), '']),
567
+ 'Facts are from Lode\'s public records (trylode.io), each with its Lode page and last-verified date. Anything not listed is not documented by Lode, which does not mean it is unsupported. Re-check with: node lode.mjs recheck', '',
568
+ ].join('\n');
569
+ }
570
+
571
+ // Update the frontmatter, the status line and the codes block; the rest of the file is left as written
572
+ export function applyAdrUpdate(text, changes) {
573
+ const p = parseAdr(text);
574
+ if (!p) throw new Error('not a Lode decision record (no lode_adr frontmatter)');
575
+ const meta = { ...p.meta, ...changes };
576
+ for (const k of ['constraints', 'workarounds']) if (changes[k]) meta[k] = [...new Set([...(p.meta[k] || []), ...changes[k]])];
577
+ let body = p.body.replace(/^\*\*Status:\*\*.*$/m, statusLine(meta));
578
+ body = /<!-- lode:codes -->[\s\S]*?<!-- \/lode:codes -->/.test(body) ? body.replace(/<!-- lode:codes -->[\s\S]*?<!-- \/lode:codes -->/, adrCodesBlock(meta)) : `${body.trimEnd()}\n\n## Constraints and workarounds\n${adrCodesBlock(meta)}\n`;
579
+ return { meta, text: adrFrontmatter(meta) + body };
580
+ }
581
+
582
+ // What --share sends for a decision: codes and ids only
583
+ export function decisionPayload(meta, now = new Date()) {
584
+ const days = daysBetween(meta.decided, now);
585
+ // Only Lode record ids leave the machine. Options Lode has no record of (an in-house tool, another
586
+ // product) stay in the local file; only how many there were is sent.
587
+ const isId = (x) => typeof x === 'string' && x.includes('--');
588
+ const others = (meta.considered || []).filter((x) => !isId(x)).length;
589
+ return { project: meta.project, platform: meta.platform, considered: (meta.considered || []).filter(isId), chosen: isId(meta.chosen) ? meta.chosen : 'other', ...(others ? { other_options: others } : {}), ...(meta.reason ? { reason: meta.reason } : {}), status: meta.status, constraints: meta.constraints || [], workarounds: meta.workarounds || [], ...(days !== undefined ? { days } : {}) };
590
+ }
591
+
592
+ const adrDir = () => join(process.cwd(), ADR_DIR);
593
+ export function listAdrs(dir = adrDir()) {
594
+ if (!existsSync(dir)) return [];
595
+ return readdirSync(dir).filter((f) => /^\d{3,}-.*\.md$/.test(f)).sort().map((f) => { const path = join(dir, f); const p = parseAdr(readFileSync(path, 'utf8')); return p ? { file: f, path, meta: p.meta } : null; }).filter(Boolean);
596
+ }
597
+ export const nextAdrNumber = (dir = adrDir()) => (existsSync(dir) ? readdirSync(dir).map((f) => Number((f.match(/^(\d{3,})-/) || [])[1] || 0)).reduce((a, b) => Math.max(a, b), 0) : 0) + 1;
598
+
599
+ async function shareDecision(meta) {
600
+ const r = await post('/v1/feedback/decision', decisionPayload(meta));
601
+ return r.recorded ? 'Shared with Lode (the user agreed): the project code, platform, the Lode ids considered and chosen, the reason, status, constraint and workaround codes, and the days since the decision.' : `Lode did not record the decision${r.message ? `: ${r.message}` : ''}.`;
602
+ }
603
+
604
+ async function adr(platform, opts) {
605
+ const bad = [];
606
+ const cons = checkCodes(opts.constraint, CONSTRAINTS), work = checkCodes(opts.workaround, WORKAROUNDS);
607
+ if (cons.bad.length) bad.push(`constraint ${cons.bad.join(', ')} (allowed: ${CONSTRAINTS.join(', ')})`);
608
+ if (work.bad.length) bad.push(`workaround ${work.bad.join(', ')} (allowed: ${WORKAROUNDS.join(', ')})`);
609
+ if (typeof opts.reason === 'string' && !CHOICE_REASONS.includes(opts.reason)) bad.push(`reason ${opts.reason} (allowed: ${CHOICE_REASONS.join(', ')})`);
610
+ if (typeof opts.status === 'string' && !DECISION_STATUSES.includes(opts.status)) bad.push(`status ${opts.status} (allowed: ${DECISION_STATUSES.join(', ')})`);
611
+ if (bad.length) return `Refused: unknown code. ${bad.join('; ')}. Nothing was written or sent.`;
612
+
613
+ if (typeof opts.update === 'string') {
614
+ const path = opts.update;
615
+ if (!existsSync(path)) return `No file at ${path}.`;
616
+ const changes = { updated: today() };
617
+ if (typeof opts.status === 'string') changes.status = opts.status;
618
+ if (typeof opts.reason === 'string') changes.reason = opts.reason;
619
+ if (cons.codes.length) changes.constraints = cons.codes;
620
+ if (work.codes.length) changes.workarounds = work.codes;
621
+ let u;
622
+ try { u = applyAdrUpdate(readFileSync(path, 'utf8'), changes); } catch (e) { return `Not updated: ${e.message}.`; }
623
+ writeFileSync(path, u.text);
624
+ let text = `Updated ${path}: status ${u.meta.status}; constraints ${(u.meta.constraints || []).join(', ') || 'none'}; workarounds ${(u.meta.workarounds || []).join(', ') || 'none'}.`;
625
+ text += opts.share === true ? `\n${await shareDecision(u.meta)}` : '\nNot sent to Lode. Only if the user agrees to share this decision\'s codes anonymously, run this again with --share.';
626
+ return text;
627
+ }
628
+
629
+ const considered = list(typeof opts.considered === 'string' ? opts.considered : undefined) || [];
630
+ if (typeof opts.chose !== 'string' || !slugish(opts.chose)) return 'Name the app chosen: node lode.mjs adr <platform> --considered "A,B" --chose B';
631
+ const { eco, index } = await platformIndex(platform);
632
+ const entries = (index?.integrations || []).map((i) => ({ ...i, name: i.app }));
633
+ const resolve = (a) => {
634
+ const hits = matchApp(a, entries);
635
+ if (hits.length > 1) throw new Error(`"${a}" matches more than one app on ${index.name}: ${hits.map((h) => h.app).join('; ')}. Use the exact name`);
636
+ return hits.length ? { key: hits[0].id, name: hits[0].app, id: hits[0].id } : { key: slugish(a).slice(0, 60), name: a.slice(0, 60) };
637
+ };
638
+ let options;
639
+ try {
640
+ const all = [...considered, opts.chose].map(resolve);
641
+ options = [];
642
+ for (const o of all) if (o.key && !options.some((x) => x.key === o.key)) options.push(o);
643
+ } catch (e) { return `Not written: ${e.message}.`; }
644
+ options = options.slice(0, 10);
645
+ const chosenKey = resolve(opts.chose).key;
646
+ if (!options.some((o) => o.key === chosenKey)) options[options.length - 1] = resolve(opts.chose);
647
+ for (const o of options) { o.chosen = o.key === chosenKey; o.rec = o.id ? await get(`/api/integrations/${eco}/${o.id.split('--')[0]}.json`) : null; }
648
+
649
+ const f = readLocal() || freshFile();
650
+ const chosenOpt = options.find((o) => o.chosen);
651
+ if (chosenOpt.rec) rememberChoice(f, chosenOpt.rec, eco);
652
+ writeLocal(f);
653
+ const now = today();
654
+ const meta = { lode_adr: 1, project: f.project, platform: eco, considered: options.map((o) => o.key), chosen: chosenKey, ...(typeof opts.reason === 'string' ? { reason: opts.reason } : {}), status: typeof opts.status === 'string' ? opts.status : 'proposed', constraints: cons.codes, workarounds: work.codes, decided: now, updated: now };
655
+ const n = nextAdrNumber();
656
+ if (viaLink(join(adrDir(), 'x.md'))) return `${ADR_DIR} is a link or sits under one, so the Lode skill won't write a decision record there. Nothing was written.`;
657
+ mkdirSync(adrDir(), { recursive: true });
658
+ const file = join(ADR_DIR, `${String(n).padStart(3, '0')}-${eco}-${String(chosenKey).split('--')[0]}.md`);
659
+ writeFileSync(join(process.cwd(), file), adrMarkdown(meta, options, index.name, n));
660
+ let text = `Wrote ${file} (status ${meta.status}). It holds Lode's facts for each option, with links and last-verified dates.${chosenOpt.rec ? ` Saved the choice to ${LOCAL_FILE} too, so recheck and drop keep the record current.` : ''}\nWhen it ships or hits a limit: node lode.mjs adr --update ${file} --status shipped [--constraint ${CONSTRAINTS[0]}] [--workaround ${WORKAROUNDS[0]}]`;
661
+ text += opts.share === true ? `\n${await shareDecision(meta)}` : `\nNot sent to Lode. Only if the user agrees to share the decision's codes anonymously, run: node lode.mjs adr --update ${file} --share`;
662
+ return text;
663
+ }
664
+
665
+ // recheck and drop keep a matching decision record in step with lode-integrations.json: the recheck date,
666
+ // and dropped or swapped when the integration was. They never mark a decision kept (the user says that
667
+ // with adr --update). Nothing is sent from here.
668
+ export function syncAdrs(f, { now = new Date(), dir = adrDir() } = {}) {
669
+ const changed = [];
670
+ for (const a of listAdrs(dir)) {
671
+ const it = f.integrations.find((x) => x.id === a.meta.chosen);
672
+ if (!it) continue;
673
+ const changes = { rechecked: today(now) };
674
+ if (it.state !== 'kept' && a.meta.status !== it.state) Object.assign(changes, { status: it.state, updated: today(now), ...(it.switched_to ? { switched_to: it.switched_to } : {}) });
675
+ const u = applyAdrUpdate(readFileSync(a.path, 'utf8'), changes);
676
+ writeFileSync(a.path, u.text);
677
+ if (changes.status) changed.push(`${join(ADR_DIR, a.file)}: status ${changes.status}`);
678
+ }
679
+ return changed;
680
+ }
681
+
682
+ // ---- D56 (LOD-102): stack check. Reads only the manifest files below (and only the variable NAMES in
683
+ // .env.example, never values), maps them to Lode apps and platforms with /api/stack-signals.json, and
684
+ // reports Lode's facts for that stack. Nothing is sent unless --share is added after the user agrees.
685
+ export const MANIFESTS = ['package.json', 'requirements.txt', 'pyproject.toml', 'Gemfile', 'go.mod', '.env.example', 'vercel.json', 'netlify.toml', join('supabase', 'config.toml')];
686
+ export function parsePackageJson(text) {
687
+ try { const j = JSON.parse(text); return [...new Set(['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].flatMap((k) => Object.keys(j?.[k] || {})))]; } catch { return []; }
688
+ }
689
+ const pyName = (s) => (String(s).trim().match(/^([A-Za-z0-9][A-Za-z0-9._-]*)/) || [])[1];
690
+ export function parseRequirements(text) {
691
+ return [...new Set(String(text).split('\n').map((l) => l.replace(/#.*/, '').trim()).filter((l) => l && !l.startsWith('-')).map(pyName).filter(Boolean))];
692
+ }
693
+ export function parsePyproject(text) {
694
+ const out = new Set();
695
+ const t = String(text);
696
+ for (const m of t.matchAll(/^\s*(?:dependencies|requires)\s*=\s*\[([\s\S]*?)\]/gm)) for (const q of m[1].matchAll(/["']([^"']+)["']/g)) { const n = pyName(q[1]); if (n) out.add(n); }
697
+ for (const sec of t.matchAll(/^\[tool\.poetry\.(?:dev-)?dependencies\]\n([\s\S]*?)(?=^\[|$(?![\s\S]))/gm)) for (const l of sec[1].split('\n')) { const n = (l.match(/^\s*([A-Za-z0-9][A-Za-z0-9._-]*)\s*=/) || [])[1]; if (n && n !== 'python') out.add(n); }
698
+ return [...out];
699
+ }
700
+ export function parseGemfile(text) { return [...new Set([...String(text).matchAll(/^\s*gem\s+["']([^"']+)["']/gm)].map((m) => m[1]))]; }
701
+ export function parseGoMod(text) {
702
+ const out = new Set();
703
+ const t = String(text);
704
+ for (const m of t.matchAll(/^require\s+\(([\s\S]*?)\)/gm)) for (const l of m[1].split('\n')) { const p = l.trim().split(/\s+/)[0]; if (p && !p.startsWith('//')) out.add(p); }
705
+ for (const m of t.matchAll(/^require\s+([^\s(]+)\s+/gm)) out.add(m[1]);
706
+ return [...out];
707
+ }
708
+ // Variable names only: the part before "=" on each line. Values are never read into the result.
709
+ export function parseEnvNames(text) { return [...new Set(String(text).split('\n').map((l) => (l.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/) || [])[1]).filter(Boolean))]; }
710
+
711
+ export function readManifests(dir = process.cwd()) {
712
+ const read = (f) => { const p = join(dir, f); return existsSync(p) ? readFileSync(p, 'utf8') : null; };
713
+ const pkg = read('package.json'), req = read('requirements.txt'), py = read('pyproject.toml'), gem = read('Gemfile'), gomod = read('go.mod'), env = read('.env.example');
714
+ return {
715
+ npm: pkg ? parsePackageJson(pkg) : [], pypi: [...(req ? parseRequirements(req) : []), ...(py ? parsePyproject(py) : [])], gem: gem ? parseGemfile(gem) : [], go: gomod ? parseGoMod(gomod) : [],
716
+ env: env ? parseEnvNames(env) : [], files: MANIFESTS.filter((f) => existsSync(join(dir, f))).map((f) => f.split('\\').join('/')),
717
+ };
718
+ }
719
+
720
+ const FRAMEWORK_SIGNS = [['nextjs', 'npm', 'next'], ['remix', 'npm', '@remix-run/react'], ['astro', 'npm', 'astro'], ['sveltekit', 'npm', '@sveltejs/kit'], ['nuxt', 'npm', 'nuxt'], ['angular', 'npm', '@angular/core'], ['nestjs', 'npm', '@nestjs/core'], ['express', 'npm', 'express'], ['react', 'npm', 'react'], ['vue', 'npm', 'vue'], ['django', 'pypi', 'django'], ['fastapi', 'pypi', 'fastapi'], ['flask', 'pypi', 'flask'], ['rails', 'gem', 'rails']];
721
+ export function detectFramework(m) {
722
+ for (const [fw, kind, name] of FRAMEWORK_SIGNS) if ((m[kind] || []).some((x) => x.toLowerCase() === name)) return fw;
723
+ return (m.go || []).length ? 'go' : undefined;
724
+ }
725
+
726
+ // Manifests -> the stack-signal products found, each with what matched (kept on the user's machine)
727
+ export function detectStack(m, doc) {
728
+ const pub = doc.env_public_prefixes || [];
729
+ const envs = (m.env || []).map((n) => { const u = n.toUpperCase(); const p = pub.find((x) => u.startsWith(x)); return p ? u.slice(p.length) : u; });
730
+ const lower = (a) => (a || []).map((x) => x.toLowerCase());
731
+ const has = { npm: lower(m.npm), pypi: lower(m.pypi).map((x) => x.replace(/_/g, '-')), gem: lower(m.gem), go: lower(m.go) };
732
+ const apps = [];
733
+ for (const s of doc.signals || []) {
734
+ const evidence = [];
735
+ for (const k of ['npm', 'pypi', 'gem']) for (const p of s[k] || []) if (has[k].includes(k === 'pypi' ? p.toLowerCase().replace(/_/g, '-') : p.toLowerCase())) evidence.push(`${k} ${p}`);
736
+ for (const p of s.go || []) if (has.go.some((x) => x === p.toLowerCase() || x.startsWith(`${p.toLowerCase()}/`))) evidence.push(`go ${p}`);
737
+ for (const e of s.env || []) if (envs.some((n) => n.startsWith(e))) evidence.push(`env ${e}*`);
738
+ for (const f of s.files || []) if ((m.files || []).includes(f)) evidence.push(`file ${f}`);
739
+ if (evidence.length) apps.push({ id: s.id, name: s.name, vendor: s.vendor ?? null, ...(s.platform ? { platform: s.platform } : {}), ...(s.app ? { app: s.app } : {}), evidence });
740
+ }
741
+ return apps;
742
+ }
743
+
744
+ // LOD-102: kept identical in logic to stackPairs and stackCheck in Lode's src/lib/stackcheck.mjs (tests check both agree).
745
+ export const STACK_NOTE = 'Facts from Lode\'s published records and the platforms\' own docs, each with its link. Lode does not read or judge your code. An app with no Lode record on a platform is not documented by Lode, not unsupported; a plan or limit not listed is not documented. Limits are the platform\'s published numbers on the date read.';
746
+ export function stackPairs({ apps = [], platforms = [] }, { listings = {}, covered = [] } = {}) {
747
+ const inStack = [...new Set([...platforms, ...apps.map((a) => a.platform).filter(Boolean)])];
748
+ const live = inStack.filter((p) => covered.includes(p)).sort();
749
+ const known = new Set(Object.values(listings).flat());
750
+ const pairs = [];
751
+ for (const platform of live) {
752
+ for (const a of apps) {
753
+ if (a.platform === platform) continue;
754
+ const own = (a.vendor ? listings[a.vendor] ?? [] : []).filter((id) => id.endsWith(`--${platform}`));
755
+ const ids = a.app ? [`${a.app}--${platform}`].filter((id) => known.has(id)) : own;
756
+ pairs.push({ platform, app: a.name, ids });
757
+ }
758
+ }
759
+ return { platforms: live, not_covered: inStack.filter((p) => !covered.includes(p)).sort(), pairs };
760
+ }
761
+
762
+ export function stackCheck(input, data, overlap) {
763
+ const { platforms, not_covered, pairs } = stackPairs(input, data);
764
+ const byId = new Map((data.records ?? []).filter(Boolean).map((r) => [r.id, r]));
765
+ const names = data.names ?? {};
766
+ const out = [];
767
+ for (const platform of platforms) {
768
+ const here = pairs.filter((p) => p.platform === platform);
769
+ const recs = [...new Set(here.flatMap((p) => p.ids))].map((id) => byId.get(id)).filter(Boolean).sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
770
+ const integrations = recs.map((r) => {
771
+ const req = r.requirements ?? {};
772
+ const src = Object.fromEntries((r.sources ?? []).map((s) => [s.id, s.url]));
773
+ const plan = req.ecosystem_plan_min && req.ecosystem_plan_min !== 'unknown' ? req.ecosystem_plan_min : null;
774
+ const planSources = plan ? [...new Set((req.src ?? []).map((id) => src[id]).filter(Boolean))] : [];
775
+ return {
776
+ id: r.id, app: r.app?.name ?? r.id, url: r.url, last_verified: r.verification?.last_verified ?? null,
777
+ ...(r.lode?.publish_state === 'live' ? {} : { held: true }),
778
+ plan_needed: plan ?? 'not documented', ...(planSources.length ? { plan_sources: planSources } : {}),
779
+ };
780
+ });
781
+ const missing = here.filter((p) => !p.ids.some((id) => byId.has(id))).map((p) => p.app).sort();
782
+ const ov = recs.length >= 2 ? overlap(platform, recs) : null;
783
+ const limits = (data.limits ?? []).filter((l) => l.platform === platform).map((l) => ({
784
+ product: l.product, limit: l.limit, plan: l.plan ?? null, seconds: l.seconds, ...(l.condition ? { condition: l.condition } : {}),
785
+ url: l.source.url, quote: l.source.quote, retrieved_at: l.source.retrieved_at,
786
+ }));
787
+ out.push({
788
+ platform, name: names[platform] ?? platform, integrations, not_in_lode: missing,
789
+ ...(ov ? { overlap: { shared_objects: ov.shared_objects, writes: ov.writes.filter((w) => w.apps.length > 1), two_way_pairs: ov.two_way_pairs, documented_no_direction: ov.documented_no_direction } } : {}),
790
+ limits,
791
+ });
792
+ }
793
+ return {
794
+ ...(input.framework ? { framework: input.framework } : {}),
795
+ apps: (input.apps ?? []).map((a) => ({ name: a.name, vendor: a.vendor ?? null, ...(a.platform ? { platform: a.platform } : {}) })),
796
+ ...(input.unrecognised?.length ? { unrecognised: [...input.unrecognised] } : {}),
797
+ platforms: out, platforms_not_covered: not_covered,
798
+ note: STACK_NOTE,
799
+ };
800
+ }
801
+
802
+ const secs = (s) => (s >= 60 && s % 60 === 0 ? `${s}s (${s / 60} min)` : s < 1 ? `${Math.round(s * 1000)} ms` : `${s}s`);
803
+ export function formatStack(res, detected = []) {
804
+ const out = [`## Stack check: ${res.apps.length} app(s) and platform(s) found${res.framework ? `, framework ${res.framework}` : ''}`];
805
+ for (const d of detected) out.push(`- ${d.name}${d.platform ? ' (platform)' : ''}: ${d.evidence.join(', ')}${d.vendor ? '' : ' | no Lode vendor yet'}`);
806
+ for (const p of res.platforms) {
807
+ out.push('', `### ${p.name}`);
808
+ if (p.integrations.length) out.push('Lode records for the other apps in this stack:');
809
+ for (const i of p.integrations) out.push(`- ${i.app}: ${p.name} plan needed: ${i.plan_needed}${i.plan_sources ? ` [${i.plan_sources.join(' ')}]` : ''} | ${i.url} | verified ${dmy(i.last_verified)}${i.held ? ' | HELD: not yet confirmed by Lode' : ''}`);
810
+ if (p.not_in_lode.length) out.push(`Not in Lode on ${p.name}: ${p.not_in_lode.join(', ')} (not documented by Lode, not unsupported).`);
811
+ const shared = p.overlap?.writes || [];
812
+ if (shared.length) {
813
+ out.push(`Objects more than one of these apps writes into ${p.name}:`);
814
+ for (const w of shared) out.push(`- ${w.object}: ${w.apps.map((a) => `${a.app} (${DIR[a.direction] || a.direction}) [${a.sources.join(' ')}]`).join('; ')}`);
815
+ for (const t of p.overlap.two_way_pairs) out.push(` Both two-way: ${t.apps.join(' and ')} on ${t.object}`);
816
+ } else if (p.overlap) out.push(`No object is documented as written into ${p.name} by more than one of these apps.`);
817
+ if (p.limits.length) {
818
+ out.push(`${p.name} function run-time limits (the platform's docs):`);
819
+ for (const l of p.limits) out.push(`- ${l.product}, ${l.limit.replace(/-/g, ' ')}${l.plan ? `, ${l.plan}` : ''}: ${secs(l.seconds)}${l.condition ? ` (${l.condition})` : ''}. "${l.quote}" ${l.url} (read ${dmy(l.retrieved_at)})`);
820
+ }
821
+ }
822
+ if (res.platforms_not_covered.length) out.push('', `Platforms Lode does not cover yet: ${res.platforms_not_covered.join(', ')}.`);
823
+ if (!res.platforms.length) out.push('', 'No platform Lode covers was found in these files (Xero, QuickBooks Online, HubSpot, Shopify, Stripe, Supabase, Vercel, Netlify, n8n, Lovable, Replit, Linear, GitHub, LangChain).');
824
+ out.push('', res.note);
825
+ return out.join('\n');
826
+ }
827
+
828
+ async function stack({ share, framework } = {}) {
829
+ const m = readManifests();
830
+ const found = m.files.filter((f) => f !== '.env.example' || m.env.length);
831
+ if (!found.length) return `No manifest files in this folder. The stack check reads only: ${MANIFESTS.join(', ')} (variable names only from .env.example).`;
832
+ const [doc, limitsDoc, index, vendors] = await Promise.all([get('/api/stack-signals.json'), get('/api/platform-limits.json'), get('/api/index.json'), get('/api/vendors/index.json')]);
833
+ const detected = detectStack(m, doc || {});
834
+ const fw = typeof framework === 'string' ? framework.toLowerCase() : detectFramework(m);
835
+ const covered = (index?.ecosystems || []).filter((e) => e.status !== 'planned').map((e) => e.slug);
836
+ const listings = Object.fromEntries((vendors?.vendors || []).map((v) => [v.id, v.integrations || []]));
837
+ const input = { apps: detected, platforms: [], ...(fw ? { framework: fw } : {}) };
838
+ const ids = [...new Set(stackPairs(input, { listings, covered }).pairs.flatMap((p) => p.ids))];
839
+ const records = (await Promise.all(ids.map((id) => get(`/api/integrations/${id.split('--')[1]}/${id.split('--')[0]}.json`)))).filter(Boolean);
840
+ const res = stackCheck(input, { records, listings, covered, limits: limitsDoc?.limits || [], names: Object.fromEntries((index?.ecosystems || []).map((e) => [e.slug, e.name])) }, stackOverlap);
841
+ let text = `Read: ${found.join(', ')}\n` + formatStack(res, detected);
842
+ if (share) {
843
+ const body = { platforms: detected.filter((d) => d.platform).map((d) => d.platform), apps: detected.filter((d) => !d.platform).map((d) => d.id), ...(fw ? { framework: fw } : {}) };
844
+ const r = await post('/v1/feedback/stack-manifest', body);
845
+ text += r.recorded ? '\n\nShared with Lode (the user agreed): the app and platform codes found, and the framework.' : `\n\nLode did not record the stack${r.message ? `: ${r.message}` : ''}.`;
846
+ } else text += '\n\nNot sent to Lode. Only if the user agrees to share the app and platform codes anonymously, run this again with --share.';
847
+ return text;
848
+ }
849
+
850
+
851
+ // Integration Triage (LOD-165): fixed symptom codes, kept equal to SYMPTOM_CODES in src/lib/triage.mjs by tests/triage.test.mjs
852
+ export const SYMPTOM_CODES = ["credential-invalid", "token-expired", "scope-missing", "authorize-failed", "access-filtered", "platform-plan-required", "app-plan-required", "account-restricted", "rate-limited", "request-too-large", "runtime-limit-exceeded", "config-missing", "package-not-found", "package-incompatible", "capability-missing", "validation-rejected", "data-mismatch", "webhook-not-received", "webhook-signature-failed", "event-duplicate-or-out-of-order", "api-deprecated", "region-unavailable", "connection-failed", "setup-step-missing", "service-outage", "mcp-connect-failed", "mcp-tool-error", "other"];
853
+ export const TRIAGE_OUTCOMES = ['fixed', 'switched', 'gave-up'];
854
+
855
+ async function triageCmd(app, platform, opts) {
856
+ const eco = platformSlug(platform);
857
+ if (!eco) return `Lode does not cover "${platform}" yet. Platforms covered: ${Object.keys(PLATFORMS).join(', ')}.`;
858
+ if (!SYMPTOM_CODES.includes(opts.symptom)) return `Give one symptom code with --symptom: ${SYMPTOM_CODES.join(', ')}`;
859
+ const q = new URLSearchParams({ app, platform: eco, symptom: opts.symptom });
860
+ if (typeof opts.status === 'string' && /^[1-5]\d\d$/.test(opts.status)) q.set('http_status', opts.status);
861
+ // Only one of the platform's own object codes is sent (ClawHub review, 30-11-2026): anything else stays on the machine.
862
+ let objectNote = '';
863
+ if (typeof opts.object === 'string') {
864
+ const code = opts.object.trim().toLowerCase().replace(/[\s_]+/g, '-');
865
+ const vocab = new Set(((await get(`/api/ecosystems/${eco}.json`))?.objects || []).map((o) => o.slug));
866
+ if (vocab.has(code)) q.set('object', code);
867
+ else objectNote = ` The object "${opts.object}" was not sent: it is not one of ${eco}'s object codes.`;
868
+ }
869
+ const share = opts.share === true && TRIAGE_OUTCOMES.includes(opts.outcome);
870
+ if (share) { q.set('outcome', opts.outcome); q.set('share', 'true'); if (typeof opts.switched === 'string') q.set('switched_to', opts.switched); }
871
+ const sent = `Sent to Lode: app "${app}", platform ${eco}, symptom ${opts.symptom}${q.get('http_status') ? `, status class ${q.get('http_status')[0]}xx` : ''}${q.get('object') ? `, object ${q.get('object')}` : ''}${share ? `, outcome ${opts.outcome} (the user agreed)` : ''}. No error text, logs or code.${objectNote}`;
872
+ const body = await get(`/v1/triage?${q}`);
873
+ if (!body || body.found === false) return `${sent}\n${body?.not_documented || `Lode has no record for "${app}" on ${eco}. Not documented is not the same as not supported.`}`;
874
+ const out = [`${body.app} on ${body.platform}: ${body.symptom} (${body.symptom_label})`, body.url ? `Lode page: ${body.url} | verified ${body.last_verified || 'unknown'}` : ''];
875
+ for (const f of body.facts || []) out.push(`- ${f.text}${(f.sources || []).length ? ` [${f.sources.join(' ')}]` : ''}`);
876
+ for (const i of body.incidents || []) out.push(`- Status page: ${i.name} (${i.status}, ${String(i.at).slice(0, 10)}) ${i.link}`);
877
+ if (body.incidents_note) out.push(body.incidents_note);
878
+ for (const a of body.alternatives || []) out.push(`- Also documents it on ${body.platform}: ${a.app} ${a.url || ''}`);
879
+ if (body.not_documented) out.push(body.not_documented);
880
+ out.push(sent);
881
+ if (opts.outcome && !share) out.push('The outcome was not sent. Only if the user agrees to share it anonymously, run this again with --share.');
882
+ return out.filter(Boolean).join('\n');
883
+ }
884
+
885
+ // lode init --gate (LOD-231): switch on Lode Gate, an opt-in Claude Code hook that adds Lode's facts to the agent's
886
+ // context just before it installs a package on Lode's list. Same rules as init: only inside a project, never through
887
+ // links, shows the change first, writes only with --yes, changes no other setting, --remove undoes only what it added.
888
+ // Writes one PreToolUse entry in .claude/settings.json and copies gate.mjs and gate-packages.json with the skill.
889
+ // Exec form (no shell), so the path is one argument on every platform (security review 30-11-2026).
890
+ export const GATE_HOOK = (mode) => ({ matcher: 'Bash|PowerShell', hooks: [{ type: 'command', command: 'node', args: ['${CLAUDE_PROJECT_DIR}/.claude/skills/lode-integration-check/scripts/gate.mjs', ...(mode === 'ask' ? ['--mode', 'ask'] : [])], timeout: 3 }] });
891
+ const GATE_FILES_LIST = ['SKILL.md', 'PERMISSIONS.md', 'scripts/lode.mjs', 'scripts/gate.mjs', 'scripts/gate-packages.json'];
892
+ // By default the hook goes in .claude/settings.local.json (this person only, not committed), so nobody who clones
893
+ // the project sends anything without choosing to; --shared puts it in .claude/settings.json for the whole team.
894
+ async function gateInit({ yes = false, remove = false, mode = 'warn', shared = false } = {}) {
895
+ const fs = await import('node:fs'); const path = await import('node:path'); const url = await import('node:url'); const os = await import('node:os'); const crypto = await import('node:crypto');
896
+ const cwd = fs.realpathSync(process.cwd());
897
+ if (cwd === path.parse(cwd).root || cwd === fs.realpathSync(os.homedir())) return 'lode init --gate only runs inside a project folder, not your home folder or the root. Nothing was written.';
898
+ const MARKERS = ['.git', 'package.json', 'pyproject.toml', 'go.mod', 'Gemfile', 'requirements.txt', 'Cargo.toml', 'deno.json', 'composer.json'];
899
+ if (!MARKERS.some((m) => fs.existsSync(path.join(cwd, m)))) return `lode init --gate didn't find a project here (none of ${MARKERS.join(', ')}). Run it from the project's root folder. Nothing was written.`;
900
+ const safe = (rel) => { let p = cwd; for (const part of rel.split(/[\\/]/)) { p = path.join(p, part); try { if (fs.lstatSync(p).isSymbolicLink()) return false; } catch { return true; } } return true; };
901
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
902
+ const hash = (f) => crypto.createHash('sha256').update(fs.readFileSync(f)).digest('hex');
903
+ const markerRel = path.join('.claude', 'lode-init.json'), markerFile = path.join(cwd, markerRel);
904
+ let marker = { added: [], skill_files: {} };
905
+ try { marker = JSON.parse(fs.readFileSync(markerFile, 'utf8')); } catch { /* none yet */ }
906
+ if (!marker || typeof marker !== 'object' || Array.isArray(marker)) marker = { added: [], skill_files: {} };
907
+ const ALLOWED_SETTINGS = [path.join('.claude', 'settings.local.json'), path.join('.claude', 'settings.json')];
908
+ const settingsRel = remove && ALLOWED_SETTINGS.includes(marker.gate?.file) ? marker.gate.file : ALLOWED_SETTINGS[shared ? 1 : 0];
909
+ const settingsFile = path.join(cwd, settingsRel);
910
+ for (const rel of [markerRel, settingsRel]) if (!safe(rel)) return `${rel}: it or a folder above it is a link, so lode init won't write there. Nothing was written.`;
911
+ let text = null, cur = {};
912
+ try { text = fs.readFileSync(settingsFile, 'utf8'); } catch (e) { if (e.code !== 'ENOENT') return `${settingsRel}: can't be read (${e.code}). Nothing was written.`; }
913
+ if (text != null) {
914
+ try { cur = JSON.parse(text); } catch { cur = undefined; }
915
+ const pre = cur?.hooks?.PreToolUse;
916
+ if (!cur || typeof cur !== 'object' || Array.isArray(cur) || (cur.hooks != null && (typeof cur.hooks !== 'object' || Array.isArray(cur.hooks))) || (pre != null && !Array.isArray(pre)))
917
+ return `${settingsRel}: not plain JSON that lode init can safely edit. Add this under "hooks" -> "PreToolUse" by hand: ${JSON.stringify(GATE_HOOK(mode))}. Nothing was written.`;
918
+ }
919
+ const indent = (text?.match(/\n([ \t]+)"/) || [])[1] || 2;
920
+ const pre = cur.hooks?.PreToolUse ?? [];
921
+ const ours = marker.gate;
922
+ const present = pre.findIndex((h) => same(h, GATE_HOOK('warn')) || same(h, GATE_HOOK('ask')) || (ours && same(h, ours.entry)));
923
+ const skillRel = path.join('.claude', 'skills', 'lode-integration-check');
924
+ const skillDst = path.join(cwd, skillRel), skillSrc = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '..');
925
+ const GATE_FILES = GATE_FILES_LIST.map((f) => f.split('/').join(path.sep));
926
+ if (!safe(skillRel) || GATE_FILES.some((f) => !safe(path.join(skillRel, f)))) return `${skillRel}: it, a folder in it or a file in it is a link, so lode init won't touch it. Nothing was written.`;
927
+ // A Gate file already in the project that differs from this skill's own would run on every shell command: refuse
928
+ if (!remove && path.resolve(skillSrc) !== path.resolve(skillDst)) {
929
+ const differ = GATE_FILES.filter((f) => { const to = path.join(skillDst, f), from = path.join(skillSrc, f); try { return fs.existsSync(to) && (!fs.lstatSync(to).isFile() || hash(to) !== hash(from)); } catch { return true; } });
930
+ if (differ.length) return `${skillRel}: ${differ.join(', ')} already exist and differ from this copy of the Lode skill, so lode init won't switch Gate on (that code would run before every shell command). Check or remove them first. Nothing was written.`;
931
+ }
932
+ const lines = [];
933
+ if (remove) {
934
+ if (present < 0 && !Object.keys(marker.gate_files ?? {}).length) return 'Lode Gate is not set up here by lode init. Nothing to remove.';
935
+ if (present >= 0) lines.push(` ${settingsRel}: remove the Lode Gate hook entry (other settings unchanged)${ours?.created ? '; delete the file if nothing else is left in it' : ''}`);
936
+ if (Object.keys(marker.gate_files ?? {}).length) lines.push(` ${skillRel}/: delete the Gate files lode init copied, if unchanged`);
937
+ } else {
938
+ if (present >= 0) return 'Lode Gate is already on in this project. Turn it off with: node lode.mjs init --gate --remove --yes';
939
+ lines.push(` ${settingsRel}: ${text == null ? 'create it with' : 'add'} one PreToolUse hook entry that runs Lode Gate on shell commands${mode === 'ask' ? ' in ask mode (a warning sends the install to the permission prompt)' : ' (it adds facts; it never blocks)'}${text == null ? '' : ' (other settings unchanged)'}${shared ? '; this file is shared, so everyone who opens the project with Claude Code gets Gate' : '; only for you (Claude Code keeps this file out of git)'}`);
940
+ const missing = GATE_FILES.filter((f) => !fs.existsSync(path.join(skillDst, f)));
941
+ if (missing.length && path.resolve(skillSrc) !== path.resolve(skillDst)) lines.push(` ${skillRel}/: copy ${missing.join(', ')} (no dependencies, nothing runs on install)`);
942
+ lines.push(` ${markerRel}: a small note of what lode init added, so --remove undoes only that`);
943
+ }
944
+ const what = 'Gate sends Lode a request only when the agent installs a package on Lode\'s list: those package names, the package manager, platform codes from config file names, the mode and a random session code. Never the command, versions, paths or file contents. See PERMISSIONS.md.';
945
+ if (!yes) return `lode init --gate would ${remove ? 'change' : 'write'} these files in ${cwd}:\n${lines.join('\n')}\n${remove ? '' : `${what}\n`}Nothing has been written. If the user agrees, run: node lode.mjs init --gate${remove ? ' --remove' : ''}${!remove && mode === 'ask' ? ' --mode ask' : ''}${!remove && shared ? ' --shared' : ''} --yes`;
946
+ if (remove) {
947
+ if (present >= 0) {
948
+ const next = { ...cur, hooks: { ...cur.hooks, PreToolUse: pre.filter((_, i) => i !== present) } };
949
+ if (!next.hooks.PreToolUse.length) delete next.hooks.PreToolUse;
950
+ if (!Object.keys(next.hooks).length) delete next.hooks;
951
+ if (ours?.created && !Object.keys(next).length) fs.rmSync(settingsFile); else fs.writeFileSync(settingsFile, JSON.stringify(next, null, indent) + '\n');
952
+ }
953
+ // Only files from the fixed list, inside the skill folder, not through links, regular files, unchanged
954
+ for (const [rel, h] of Object.entries(marker.gate_files ?? {})) {
955
+ if (!GATE_FILES.includes(rel) || !safe(path.join(skillRel, rel))) continue;
956
+ const f = path.join(skillDst, rel);
957
+ if (!path.resolve(f).startsWith(path.resolve(skillDst) + path.sep)) continue;
958
+ try { if (fs.lstatSync(f).isFile() && hash(f) === h) fs.rmSync(f); } catch { /* gone */ }
959
+ }
960
+ for (const d of [path.join(skillDst, 'scripts'), skillDst, path.dirname(skillDst)]) { try { if (!fs.lstatSync(d).isSymbolicLink() && !fs.readdirSync(d).length) fs.rmdirSync(d); } catch { /* not empty */ } }
961
+ delete marker.gate; delete marker.gate_files;
962
+ } else {
963
+ const entry = GATE_HOOK(mode);
964
+ fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
965
+ const next = { ...cur, hooks: { ...(cur.hooks ?? {}), PreToolUse: [...pre, entry] } };
966
+ fs.writeFileSync(settingsFile, JSON.stringify(next, null, indent) + '\n');
967
+ const back = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
968
+ for (const k of Object.keys(cur)) if (k !== 'hooks' && !same(back[k], cur[k])) throw new Error(`${settingsRel} changed unexpectedly`);
969
+ for (const k of Object.keys(cur.hooks ?? {})) if (k !== 'PreToolUse' && !same(back.hooks?.[k], cur.hooks[k])) throw new Error(`${settingsRel} changed unexpectedly`);
970
+ marker.gate = { file: settingsRel, created: text == null, entry };
971
+ marker.gate_files = marker.gate_files ?? {};
972
+ if (path.resolve(skillSrc) !== path.resolve(skillDst)) for (const rel of GATE_FILES) {
973
+ const from = path.join(skillSrc, rel), to = path.join(skillDst, rel);
974
+ if (fs.existsSync(to) || !fs.existsSync(from)) continue;
975
+ fs.mkdirSync(path.dirname(to), { recursive: true });
976
+ if (!safe(path.join(skillRel, rel))) continue;
977
+ try { fs.copyFileSync(from, to, fs.constants.COPYFILE_EXCL); } catch { continue; }
978
+ marker.gate_files[rel] = hash(to);
979
+ }
980
+ }
981
+ const keep = (marker.added ?? []).length || Object.keys(marker.skill_files ?? {}).length || marker.gate;
982
+ if (keep) { fs.mkdirSync(path.dirname(markerFile), { recursive: true }); fs.writeFileSync(markerFile, JSON.stringify(marker, null, 2) + '\n'); }
983
+ else { try { fs.rmSync(markerFile); } catch { /* none */ } }
984
+ return `${remove ? 'Removed' : 'Done'}:\n${lines.join('\n')}\n${remove ? '' : 'Lode Gate is on for this project from the next Claude Code session. Turn it off with: node lode.mjs init --gate --remove --yes\n'}Nothing was sent to Lode.`;
985
+ }
986
+
987
+ // lode init (Paul approved 27-11-2026): put Lode in the project's own config so teammates and sub-agents have it.
988
+ // Runs only when someone types it, shows the exact files first, writes only with --yes, changes no other entry,
989
+ // adds no code or hooks (Gate's hook only with --gate, see gateInit), sends nothing to Lode, and `init --remove` undoes it.
990
+ const LODE_URL = 'https://trylode.io/mcp';
991
+ // npx trylode setup (LOD-248, Paul approved 01-12-2026) writes the same entry with the listing channel code `setup`;
992
+ // --remove recognises both addresses, so either route can undo the other.
993
+ const SETUP_URL = 'https://trylode.io/mcp?src=setup';
994
+ // LOD-226 (Paul approved init adding it, 30-11-2026): the rules line from trylode.io/agents (kept equal by a test).
995
+ // The harness (LOD-228) measured it: with this line Claude Code checked Lode in 13 of 16 tasks, against 3 of 17 without.
996
+ // The rules line init writes. v2 (Paul approved 01-12-2026) also fires when the agent would build the capability itself;
997
+ // blocks and rule files written with v1 are still recognised, so they count as set up and init --remove still takes them out.
998
+ export const RULE_V1 = "Before you add, recommend or install a third-party integration or SDK, check it with the Lode MCP server (https://trylode.io/mcp?src=rules): call check_stack for the apps this project already uses, or find_integrations or get_integration for the one you are adding. Quote Lode's facts with their dates. If Lode has no record, say it is not documented by Lode, not that it is unsupported.";
999
+ export const RULE = "Before you add, recommend or install a third-party integration or SDK, or decide to build that capability yourself (email, auth, payments, background jobs, rate limiting and similar), check it with the Lode MCP server (https://trylode.io/mcp?src=rules): call check_stack for the apps this project already uses, then find_integrations for the options or get_integration for the one you are adding. Quote Lode's facts with their dates. If Lode has no record, say it is not documented by Lode, not that it is unsupported.";
1000
+ const rulesBlock = (rule) => `<!-- lode:rules (added by lode init; node lode.mjs init --remove --yes takes it out) -->\n## Integrations\n${rule}\n<!-- /lode:rules -->\n`;
1001
+ const rulesMdc = (rule) => `---\ndescription: Check third-party integrations with Lode before adding them\nalwaysApply: true\n---\n${rule}\n`;
1002
+ export const RULES_BLOCK = rulesBlock(RULE);
1003
+ export const RULES_MDC = rulesMdc(RULE);
1004
+ // Every block and rule file a released init has written, newest first.
1005
+ export const KNOWN_BLOCKS = [RULES_BLOCK, rulesBlock(RULE_V1)];
1006
+ export const KNOWN_MDCS = [RULES_MDC, rulesMdc(RULE_V1)];
1007
+ async function initCmd({ client = 'all', yes = false, remove = false, gate = false, gateMode = 'warn', gateShared = false, rules = true, src = null } = {}) {
1008
+ const serverUrl = src === 'setup' ? SETUP_URL : LODE_URL;
1009
+ // The command the user or agent should run next: npx trylode's own when called through it (security review
1010
+ // 01-12-2026: a project has no lode.mjs, so pointing an agent at it failed or wrote the untagged address).
1011
+ const runCmd = (rm) => (src === 'setup' ? `npx trylode ${rm ? 'remove' : 'setup'}` : `node lode.mjs init${rm ? ' --remove' : ''}`);
1012
+ if (gate) return gateInit({ yes, remove, mode: gateMode, shared: gateShared });
1013
+ const fs = await import('node:fs'); const path = await import('node:path'); const url = await import('node:url'); const os = await import('node:os'); const crypto = await import('node:crypto');
1014
+ const cwd = fs.realpathSync(process.cwd());
1015
+ // Only inside a project: never the home folder or the root, and only where a project marker exists (security review 27-11-2026)
1016
+ if (cwd === path.parse(cwd).root || cwd === fs.realpathSync(os.homedir())) return 'lode init only runs inside a project folder, not your home folder or the root. Nothing was written.';
1017
+ const MARKERS = ['.git', 'package.json', 'pyproject.toml', 'go.mod', 'Gemfile', 'requirements.txt', 'Cargo.toml', 'deno.json', 'composer.json'];
1018
+ if (!MARKERS.some((m) => fs.existsSync(path.join(cwd, m)))) return `lode init didn't find a project here (none of ${MARKERS.join(', ')}). Run it from the project's root folder. Nothing was written.`;
1019
+ // A target is safe only when it and every folder between it and the project are real (not symlinks)
1020
+ const safe = (rel) => { let p = cwd; for (const part of rel.split(/[\\/]/)) { p = path.join(p, part); try { if (fs.lstatSync(p).isSymbolicLink()) return false; } catch { return true; } } return true; };
1021
+ const hash = (f) => crypto.createHash('sha256').update(fs.readFileSync(f)).digest('hex');
1022
+ const markerRel = path.join('.claude', 'lode-init.json');
1023
+ const markerFile = path.join(cwd, markerRel);
1024
+ if (!safe(markerRel)) return `${markerRel}: .claude or the file is a link, so lode init won't write there. Nothing was written.`;
1025
+ // Security review 01-12-2026: the MCP files and the marker get the same guards as the rules files. Read only a
1026
+ // regular file with one name, at most 1 MB, opened without following a link and without blocking (a FIFO used to
1027
+ // hang init); a hard-linked file is refused, since writing it would change the other name's file too.
1028
+ const readSafe = (rel) => {
1029
+ const f = path.join(cwd, rel);
1030
+ let st; try { st = fs.lstatSync(f); } catch (e) { return e.code === 'ENOENT' ? { text: null } : { bad: `can't be read (${e.code}).` }; }
1031
+ if (!st.isFile()) return { bad: "not a plain file, so it won't be touched." };
1032
+ if (st.nlink > 1) return { bad: "it has another name elsewhere (a hard link), so it won't be touched." };
1033
+ if (st.size > 1024 * 1024) return { bad: "larger than 1 MB, so it won't be touched." };
1034
+ let fd; try { fd = fs.openSync(f, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0)); } catch (e) { return { bad: `can't be read (${e.code}).` }; }
1035
+ try { const s2 = fs.fstatSync(fd); if (!s2.isFile() || s2.ino !== st.ino) return { bad: 'changed while being read.' }; return { text: fs.readFileSync(fd, 'utf8'), st }; } finally { fs.closeSync(fd); }
1036
+ };
1037
+ try { if (!fs.lstatSync(path.join(cwd, '.claude')).isDirectory()) return '.claude is not a folder, so lode init won\'t write there. Nothing was written.'; } catch { /* absent: created when needed */ }
1038
+ let marker = { added: [], skill_files: {} };
1039
+ const mr = readSafe(markerRel);
1040
+ if (mr.bad) return `${markerRel}: ${mr.bad} Nothing was written.`;
1041
+ if (mr.text != null) {
1042
+ let m; try { m = JSON.parse(mr.text); } catch { m = undefined; }
1043
+ const plainObj = (o) => !!o && typeof o === 'object' && !Array.isArray(o);
1044
+ if (!plainObj(m) || (m.added != null && !(Array.isArray(m.added) && m.added.every(plainObj))) || (m.skill_files != null && !plainObj(m.skill_files)))
1045
+ return `${markerRel} isn't the note lode init writes, so nothing was changed. Nothing was written.`;
1046
+ marker = { added: [], skill_files: {}, ...m };
1047
+ }
1048
+ // Re-serialising must give back the same values: refuse a file whose numbers can't round-trip (1.50, very large
1049
+ // integers) or that repeats a key, since writing it back would change entries the user didn't ask to change.
1050
+ const lossless = (text) => {
1051
+ const bare = text.replace(/"(?:[^"\\]|\\.)*"/g, '""');
1052
+ for (const n of bare.match(/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g) || []) if (String(Number(n)) !== n) return false;
1053
+ const keyCount = (text.match(/"(?:[^"\\]|\\.)*"\s*:/g) || []).length;
1054
+ const count = (v) => (v && typeof v === 'object' ? (Array.isArray(v) ? v.reduce((a, x) => a + count(x), 0) : Object.entries(v).reduce((a, [, x]) => a + 1 + count(x), 0)) : 0);
1055
+ return keyCount === count(JSON.parse(text));
1056
+ };
1057
+ const targets = [];
1058
+ if (client === 'all' || client === 'claude') targets.push({ file: '.mcp.json', entry: { type: 'http', url: serverUrl }, alts: [LODE_URL, SETUP_URL].map((u) => ({ type: 'http', url: u })) });
1059
+ if (client === 'all' || client === 'cursor') targets.push({ file: path.join('.cursor', 'mcp.json'), entry: { url: serverUrl }, alts: [LODE_URL, SETUP_URL].map((u) => ({ url: u })) });
1060
+ const here = path.dirname(url.fileURLToPath(import.meta.url));
1061
+ const skillSrc = path.resolve(here, '..');
1062
+ const skillRel = path.join('.claude', 'skills', 'lode-integration-check');
1063
+ const skillDst = path.join(cwd, skillRel);
1064
+ const SKILL_FILES = ['SKILL.md', 'PERMISSIONS.md', path.join('scripts', 'lode.mjs')];
1065
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1066
+ const plan = [], refused = [];
1067
+ for (const t of targets) {
1068
+ const f = path.join(cwd, t.file);
1069
+ if (!safe(t.file)) { refused.push(`${t.file}: it or a folder above it is a link, so lode init won't touch it.`); continue; }
1070
+ let text = null, cur = {};
1071
+ const rd = readSafe(t.file);
1072
+ if (rd.bad) { refused.push(`${t.file}: ${rd.bad}`); continue; }
1073
+ text = rd.text;
1074
+ if (text != null) {
1075
+ try { cur = JSON.parse(text); } catch { cur = undefined; }
1076
+ if (!cur || typeof cur !== 'object' || Array.isArray(cur) || (cur.mcpServers != null && (typeof cur.mcpServers !== 'object' || Array.isArray(cur.mcpServers)))) {
1077
+ refused.push(`${t.file}: not plain JSON that lode init can safely edit (comments, trailing commas or another shape). Add this entry by hand under "mcpServers": "lode": ${JSON.stringify(t.entry)}`); continue;
1078
+ }
1079
+ if (!lossless(text)) { refused.push(`${t.file}: writing it back would change other entries (a number that can't be kept exactly, or a repeated key). Add this entry by hand under "mcpServers": "lode": ${JSON.stringify(t.entry)}`); continue; }
1080
+ }
1081
+ const indent = (text?.match(/\n([ \t]+)"/) || [])[1] || 2;
1082
+ const has = cur.mcpServers && Object.prototype.hasOwnProperty.call(cur.mcpServers, 'lode');
1083
+ const ours = (marker.added || []).find((a) => a.file === t.file);
1084
+ if (remove) {
1085
+ if (has && (t.alts.some((a) => same(cur.mcpServers.lode, a)) || (ours && same(cur.mcpServers.lode, ours.entry)))) plan.push({ do: 'remove', file: t.file, f, cur, indent, created: !!ours?.created, st: rd.st, eol: /\r\n/.test(text ?? '') });
1086
+ else if (has) refused.push(`${t.file}: its "lode" entry isn't the one lode init adds, so it was left alone.`);
1087
+ } else if (!has) plan.push({ do: 'add', file: t.file, f, cur, indent, entry: t.entry, created: text == null, st: rd.st, eol: /\r\n/.test(text ?? '') });
1088
+ }
1089
+ const skillThere = fs.existsSync(path.join(skillDst, 'SKILL.md'));
1090
+ if (!safe(skillRel)) refused.push(`${skillRel}: it or a folder above it is a link, so lode init won't touch it.`);
1091
+ else if (remove && Object.keys(marker.skill_files || {}).length) plan.push({ do: 'remove-skill', file: skillRel });
1092
+ else if (!remove && !skillThere && path.resolve(skillSrc) !== path.resolve(skillDst)) plan.push({ do: 'copy-skill', file: skillRel });
1093
+ // The rules line: one fixed block in CLAUDE.md (created if missing) and in AGENTS.md (only if it exists), and its own
1094
+ // Cursor rule file. A fixed list of files, never paths read from the marker; --remove takes out only the exact block
1095
+ // (or the exact rule file) init writes, and deletes a file only when nothing else is left in it.
1096
+ // Security review 30-11-2026 (rules line): every instruction file is untrusted. It is checked for links BEFORE it is
1097
+ // read (a link to /dev/zero or a FIFO used to hang or crash init), read only if it is a regular file with one name,
1098
+ // at most 1 MB and plain UTF-8 (init used to rewrite Latin-1 or UTF-16 files with replacement characters), opened
1099
+ // without following a link, and an existing file is only appended to, never rewritten, unless --remove takes the block out.
1100
+ const crlf = (s) => s.replace(/\n/g, '\r\n');
1101
+ const NOFOLLOW = fs.constants.O_NOFOLLOW ?? 0;
1102
+ const readRules = (rel) => {
1103
+ if (!safe(rel)) return { bad: 'it or a folder above it is a link, so lode init won\'t touch it.' };
1104
+ const f = path.join(cwd, rel);
1105
+ let st; try { st = fs.lstatSync(f); } catch (e) { return e.code === 'ENOENT' ? { text: null } : { bad: `can't be read (${e.code}).` }; }
1106
+ if (!st.isFile()) return { bad: 'not a plain file, so lode init won\'t touch it.' };
1107
+ if (st.nlink > 1) return { bad: 'it has another name elsewhere (a hard link), so lode init won\'t touch it.' };
1108
+ if (st.size > 1024 * 1024) return { bad: 'larger than 1 MB, so lode init won\'t touch it.' };
1109
+ let buf;
1110
+ try {
1111
+ const fd = fs.openSync(f, fs.constants.O_RDONLY | NOFOLLOW | (fs.constants.O_NONBLOCK ?? 0));
1112
+ try { const s2 = fs.fstatSync(fd); if (!s2.isFile() || s2.ino !== st.ino || s2.dev !== st.dev) return { bad: 'changed while lode init read it.' }; buf = fs.readFileSync(fd); } finally { fs.closeSync(fd); }
1113
+ } catch (e) { return { bad: `can't be read (${e.code}).` }; }
1114
+ const text = buf.toString('utf8');
1115
+ if (!Buffer.from(text, 'utf8').equals(buf) || text.includes('\0')) return { bad: 'not plain UTF-8 text, so lode init won\'t edit it. Add the rules line by hand if you want it.' };
1116
+ return { text, st };
1117
+ };
1118
+ if (rules || remove) {
1119
+ const ruleTargets = [];
1120
+ if (remove || client === 'all' || client === 'claude') ruleTargets.push({ file: 'CLAUDE.md', kind: 'md', create: true }, { file: 'AGENTS.md', kind: 'md', create: false });
1121
+ if (remove || client === 'all' || client === 'cursor') ruleTargets.push({ file: path.join('.cursor', 'rules', 'lode.mdc'), kind: 'mdc', create: true });
1122
+ for (const t of ruleTargets) {
1123
+ const f = path.join(cwd, t.file);
1124
+ const r = readRules(t.file);
1125
+ if (r.bad) { if (t.create || (() => { try { return !!fs.lstatSync(f); } catch { return false; } })()) refused.push(`${t.file}: ${r.bad}`); continue; }
1126
+ const text = r.text;
1127
+ if (t.kind === 'md') {
1128
+ const block = text == null ? null : KNOWN_BLOCKS.flatMap((b) => [crlf(b), b]).find((b) => text.includes(b));
1129
+ const lookalike = text != null && !block && text.includes('<!-- lode:rules');
1130
+ if (lookalike) { refused.push(`${t.file}: has a lode:rules block that isn't the one lode init writes, so it was left alone.`); continue; }
1131
+ if (remove) { if (block) plan.push({ do: 'rules-remove', file: t.file, f, text, st: r.st, kind: 'md', block }); continue; }
1132
+ if (text == null && !t.create) continue;
1133
+ if (text != null && (block || text.includes(RULE) || text.includes(RULE_V1))) continue;
1134
+ plan.push({ do: 'rules-add', file: t.file, f, text, st: r.st, kind: 'md' });
1135
+ } else if (text == null) { if (!remove) plan.push({ do: 'rules-add', file: t.file, f, text, kind: 'mdc' }); }
1136
+ else if (KNOWN_MDCS.some((m) => text === m || text === crlf(m))) { if (remove) plan.push({ do: 'rules-remove', file: t.file, f, text, st: r.st, kind: 'mdc' }); }
1137
+ else refused.push(`${t.file}: isn't the rule file lode init writes, so it was left alone.`);
1138
+ }
1139
+ }
1140
+ const refusedText = refused.length ? `\nNot changed:\n${refused.map((r) => ` ${r}`).join('\n')}` : '';
1141
+ if (!plan.length) return (remove ? 'Nothing to remove that lode init added.' : 'Lode is already set up in this project.') + refusedText;
1142
+ const lines = plan.map((p) => p.do === 'add' ? ` ${p.file}: ${p.created ? 'create it with' : 'add'} one entry "lode" -> ${serverUrl}${p.created ? '' : ' (other entries unchanged)'}`
1143
+ : p.do === 'remove' ? ` ${p.file}: remove the "lode" entry lode init added (other entries unchanged)${p.created ? '; delete the file if nothing else is left in it' : ''}`
1144
+ : p.do === 'rules-add' ? ` ${p.file}: ${p.text == null ? 'create it with' : 'add, at the end,'} the Lode rules line (the agent checks Lode before it adds an integration)${p.text == null ? '' : '; nothing else in the file changes'}`
1145
+ : p.do === 'rules-remove' ? ` ${p.file}: remove the Lode rules ${p.kind === 'mdc' ? 'file' : 'line'} lode init added${p.kind === 'md' ? ' (nothing else in the file changes)' : ''}`
1146
+ : p.do === 'copy-skill' ? ` ${p.file}/: copy the Lode Integration Check skill (SKILL.md, PERMISSIONS.md, scripts/lode.mjs; no dependencies, nothing runs on install)`
1147
+ : ` ${p.file}/: delete the skill files lode init copied, if unchanged`);
1148
+ if (!remove) lines.push(` ${markerRel}: a small note of what lode init added, so --remove undoes only that`);
1149
+ if (!yes) return `lode init would ${remove ? 'change' : 'write'} these files in ${cwd}:\n${lines.join('\n')}${refusedText}\nNothing has been written and nothing is sent to Lode. If the user agrees, run: ${runCmd(remove)}${client !== 'all' ? ` --client ${client}` : ''}${!remove && !rules ? ' --no-rules' : ''} --yes${!remove && rules && plan.some((p) => p.do === 'rules-add') ? ' (add --no-rules to leave out the rules line)' : ''}`;
1150
+ const write = (p, next) => {
1151
+ if (p.st) { const now = fs.lstatSync(p.f); if (!now.isFile() || now.nlink > 1 || now.ino !== p.st.ino) throw new Error(`${p.file} changed while init ran`); }
1152
+ const out = JSON.stringify(next, null, p.indent) + '\n';
1153
+ fs.writeFileSync(p.f, p.eol ? out.replace(/\n/g, '\r\n') : out);
1154
+ // Check afterwards that every other entry is exactly as it was
1155
+ const back = JSON.parse(fs.readFileSync(p.f, 'utf8'));
1156
+ for (const k of Object.keys(p.cur)) if (k !== 'mcpServers' && !same(back[k], p.cur[k])) throw new Error(`${p.file} changed unexpectedly`);
1157
+ for (const k of Object.keys(p.cur.mcpServers || {})) if (k !== 'lode' && !same(back.mcpServers?.[k], p.cur.mcpServers[k])) throw new Error(`${p.file} changed unexpectedly`);
1158
+ };
1159
+ // The rules line: a new file is created with O_EXCL (never follows a link, never overwrites); an existing file is
1160
+ // opened without following a link, must still be the very file that was read (same inode, size and time), and is
1161
+ // only appended to; --remove writes back the text that was read minus the exact block, or deletes a file left empty.
1162
+ const failed = [];
1163
+ const unchanged = (fd, st) => { const s = fs.fstatSync(fd); return s.isFile() && s.ino === st.ino && s.dev === st.dev && s.size === st.size && s.mtimeMs === st.mtimeMs; };
1164
+ const rulesWrite = (p) => {
1165
+ if (!safe(p.file)) throw new Error('a link appeared');
1166
+ if (p.text == null) {
1167
+ fs.mkdirSync(path.dirname(p.f), { recursive: true });
1168
+ if (!safe(p.file)) throw new Error('a link appeared');
1169
+ fs.writeFileSync(p.f, p.kind === 'mdc' ? RULES_MDC : RULES_BLOCK, { flag: 'wx' });
1170
+ return;
1171
+ }
1172
+ if (p.do === 'rules-add') {
1173
+ const eol = p.text.includes('\r\n') ? '\r\n' : '\n';
1174
+ const fd = fs.openSync(p.f, fs.constants.O_WRONLY | fs.constants.O_APPEND | NOFOLLOW);
1175
+ try {
1176
+ if (!unchanged(fd, p.st)) throw new Error('changed while lode init ran');
1177
+ fs.writeSync(fd, `${p.text.endsWith('\n') ? '' : eol}${eol}${eol === '\n' ? RULES_BLOCK : crlf(RULES_BLOCK)}`);
1178
+ } finally { fs.closeSync(fd); }
1179
+ return;
1180
+ }
1181
+ let next = '';
1182
+ if (p.kind === 'md') {
1183
+ const lead = ['\r\n\r\n', '\n\n'].find((l) => p.text.includes(l + p.block));
1184
+ next = lead ? p.text.replace(lead + p.block, lead.slice(0, lead.length / 2)) : p.text.replace(p.block, '');
1185
+ }
1186
+ const fd = fs.openSync(p.f, fs.constants.O_RDWR | NOFOLLOW);
1187
+ let empty = false;
1188
+ try {
1189
+ if (!unchanged(fd, p.st)) throw new Error('changed while lode init ran');
1190
+ if (!next.trim()) empty = true;
1191
+ else { fs.ftruncateSync(fd, 0); fs.writeSync(fd, next, 0); }
1192
+ } finally { fs.closeSync(fd); }
1193
+ if (empty) fs.unlinkSync(p.f); // unlink removes a link itself, never its target
1194
+ };
1195
+ for (const p of plan) {
1196
+ if (p.do === 'add') {
1197
+ fs.mkdirSync(path.dirname(p.f), { recursive: true });
1198
+ write(p, { ...p.cur, mcpServers: { ...(p.cur.mcpServers || {}), lode: p.entry } });
1199
+ marker.added = [...(marker.added || []).filter((a) => a.file !== p.file), { file: p.file, created: p.created, entry: p.entry }];
1200
+ }
1201
+ if (p.do === 'remove') {
1202
+ const next = { ...p.cur, mcpServers: { ...p.cur.mcpServers } }; delete next.mcpServers.lode;
1203
+ if (p.created && !Object.keys(next.mcpServers).length && Object.keys(next).length === 1) fs.rmSync(p.f); else write(p, next);
1204
+ marker.added = (marker.added || []).filter((a) => a.file !== p.file);
1205
+ }
1206
+ if (p.do === 'rules-add' || p.do === 'rules-remove') {
1207
+ // A failure here is reported, never thrown, so the marker for the steps already done is still written
1208
+ try { rulesWrite(p); } catch (e) { failed.push(` ${p.file}: not changed (${e.code || e.message}).`); }
1209
+ }
1210
+ if (p.do === 'copy-skill') {
1211
+ marker.skill_files = {};
1212
+ for (const rel of SKILL_FILES) {
1213
+ const from = path.join(skillSrc, rel), to = path.join(skillDst, rel);
1214
+ if (!fs.existsSync(from) || !safe(path.join(skillRel, rel))) continue;
1215
+ fs.mkdirSync(path.dirname(to), { recursive: true });
1216
+ if (!safe(path.join(skillRel, rel))) continue;
1217
+ try { fs.copyFileSync(from, to, fs.constants.COPYFILE_EXCL); } catch { continue; } // never over an existing file
1218
+ marker.skill_files[rel] = hash(to);
1219
+ }
1220
+ }
1221
+ if (p.do === 'remove-skill') {
1222
+ // Delete only files lode init copies (a fixed list, never a path read from the marker), inside the skill
1223
+ // folder, not through links, regular files only, and only if nobody has changed them (security review 30-11-2026)
1224
+ for (const [rel, h] of Object.entries(marker.skill_files || {})) {
1225
+ if (!SKILL_FILES.includes(rel) || !safe(path.join(skillRel, rel))) continue;
1226
+ const f = path.join(skillDst, rel);
1227
+ if (!path.resolve(f).startsWith(path.resolve(skillDst) + path.sep)) continue;
1228
+ try { if (fs.lstatSync(f).isFile() && hash(f) === h) fs.rmSync(f); } catch { /* already gone */ }
1229
+ }
1230
+ for (const d of [path.join(skillDst, 'scripts'), skillDst]) { try { if (!fs.lstatSync(d).isSymbolicLink() && !fs.readdirSync(d).length) fs.rmdirSync(d); } catch { /* not empty or gone */ } }
1231
+ marker.skill_files = {};
1232
+ }
1233
+ }
1234
+ if ((marker.added || []).length || Object.keys(marker.skill_files || {}).length || marker.gate || Object.keys(marker.gate_files || {}).length) { fs.mkdirSync(path.dirname(markerFile), { recursive: true }); fs.writeFileSync(markerFile, JSON.stringify(marker, null, 2) + '\n'); }
1235
+ else { try { fs.rmSync(markerFile); } catch { /* none */ } }
1236
+ return `${remove ? 'Removed' : 'Done'}:\n${lines.join('\n')}${refusedText}${failed.length ? `\nFailed:\n${failed.join('\n')}` : ''}\n${remove ? '' : 'Commit these files so teammates and sub-agents in this project have Lode. Undo with: ' + runCmd(true) + ' --yes\n'}Nothing was sent to Lode.`;
1237
+ }
1238
+
1239
+ export async function main(argv) {
1240
+ const [cmd, ...rest] = argv;
1241
+ const flag = (n) => { const i = rest.indexOf(n); if (i < 0) return undefined; const v = rest[i + 1]; rest.splice(i, v && !v.startsWith('--') ? 2 : 1); return v && !v.startsWith('--') ? v : true; };
1242
+ if (cmd === 'check' && rest[0]) return check(rest[0], rest[1]);
1243
+ if (cmd === 'list' && rest[0]) {
1244
+ const category = flag('--category'), all = flag('--all');
1245
+ const eco = platformSlug(rest[0]);
1246
+ if (!eco) return `Lode does not cover "${rest[0]}" yet. Platforms covered: ${Object.keys(PLATFORMS).join(', ')}.`;
1247
+ const index = await get(`/api/ecosystems/${eco}.json`);
1248
+ return formatList(index, index.integrations || [], { category: typeof category === 'string' ? category : undefined, all: !!all });
1249
+ }
1250
+ if (cmd === 'find' && rest[0]) {
1251
+ const opts = { category: flag('--category'), needs: flag('--needs'), region: flag('--region'), stack: flag('--stack'), framework: flag('--framework') };
1252
+ const { eco, index } = await platformIndex(rest[0]);
1253
+ const q = new URLSearchParams({ ecosystem: eco, limit: '10' });
1254
+ const category = categoryFor(typeof opts.category === 'string' ? opts.category : undefined, index.integrations || []);
1255
+ if (opts.category && !category) {
1256
+ // Agents often pass the other product as a category ("shopify" on Xero): point them to check
1257
+ // Only an exact app name or id counts ("postgres" must not be read as Prisma Postgres)
1258
+ const asApp = matchApp(opts.category, (index.integrations || []).map((i) => ({ ...i, name: i.app })))
1259
+ .filter((e) => norm(e.name) === norm(opts.category) || String(e.id).split('--')[0] === slugish(opts.category));
1260
+ if (asApp.length === 1 || platformSlug(opts.category)) return `"${opts.category}" is a product, not a category. For that pair, run: node lode.mjs check "${asApp[0]?.name || opts.category}" ${eco}`;
1261
+ }
1262
+ if (opts.category && !category) return `No category on ${index.name} matches "${opts.category}". Categories: ${[...new Set((index.integrations || []).flatMap((i) => i.categories || []))].sort().join(', ')}`;
1263
+ if (category) q.set('category', category);
1264
+ for (const k of ['needs', 'region', 'stack', 'framework']) if (typeof opts[k] === 'string') q.set(k, opts[k]);
1265
+ return formatFind(await get(`/v1/integrations?${q}`), index.name);
1266
+ }
1267
+ if (cmd === 'chose' && rest[1]) {
1268
+ const opts = { considered: flag('--considered'), reason: flag('--reason'), needs: flag('--needs'), region: flag('--region'), share: flag('--share') };
1269
+ const { eco, index } = await platformIndex(rest[1]);
1270
+ const chosen = idFor(rest[0], index);
1271
+ const considered = (list(opts.considered) || []).map((a) => idFor(a, index));
1272
+ const reason = CHOICE_REASONS.includes(opts.reason) ? opts.reason : 'other';
1273
+ // 22-11-2026 (Paul): nothing goes to Lode unless the user agreed and the agent added --share
1274
+ let text;
1275
+ if (opts.share === true) {
1276
+ const r = await post('/v1/feedback/choice', { chosen, considered, reason, needs: list(opts.needs), region: typeof opts.region === 'string' ? opts.region : undefined });
1277
+ text = r.recorded ? `Sent to Lode (the user agreed): chose ${chosen} (reason: ${reason}). Thank you; this helps keep the facts useful.` : `Lode did not record the choice${r.message ? `: ${r.message}` : ''}.`;
1278
+ } else {
1279
+ text = `Not sent to Lode. Only if the user agrees to tell Lode anonymously which app they chose, run this again with --share.`;
1280
+ }
1281
+ // D51: keep the choice locally too (only for a real Lode record), so `recheck` can say what changed later
1282
+ return chosen === 'none' ? text : text + await saveChoice(eco, chosen);
1283
+ }
1284
+ if (cmd === 'outcome' && rest[2]) {
1285
+ const opts = { failure: flag('--failure-reason'), switched: flag('--switched-to'), share: flag('--share') };
1286
+ const { index } = await platformIndex(rest[1]);
1287
+ const chosen = idFor(rest[0], index);
1288
+ const outcome = OUTCOMES.includes(rest[2]) ? rest[2] : null;
1289
+ if (!outcome) return `Outcome must be one of: ${OUTCOMES.join(', ')}`;
1290
+ const body = { chosen, considered: [chosen], outcome };
1291
+ if (typeof opts.failure === 'string') body.failure_reason = FAILURE_REASONS.includes(opts.failure) ? opts.failure : 'other';
1292
+ if (typeof opts.switched === 'string') { try { body.switched_to = idFor(opts.switched, index); } catch { body.switched_to = opts.switched; } }
1293
+ if (opts.share !== true) return `Not sent to Lode. Only if the user agrees to tell Lode anonymously how the integration went, run this again with --share.`;
1294
+ const r = await post('/v1/feedback/choice', body);
1295
+ return r.recorded ? `Sent to Lode (the user agreed): ${chosen} ${outcome}.` : `Lode did not record the outcome${r.message ? `: ${r.message}` : ''}.`;
1296
+ }
1297
+ if (cmd === 'request' && rest[1]) {
1298
+ const opts = { needs: flag('--needs'), region: flag('--region') };
1299
+ const eco = platformSlug(rest[1]);
1300
+ if (!eco) return `Lode does not cover "${rest[1]}" yet. Platforms covered: ${Object.keys(PLATFORMS).join(', ')}.`;
1301
+ const r = await post('/v1/feedback/coverage', { app: rest[0], ecosystem: eco, needs: list(opts.needs), region: typeof opts.region === 'string' ? opts.region : undefined, reason: 'not-covered' });
1302
+ if (r.already_covered) return `Lode already covers this: ${r.id}. Run: node lode.mjs check "${rest[0]}" ${eco}`;
1303
+ return r.recorded ? `Recorded with Lode: ${rest[0]} on ${eco} is wanted. Lode uses these requests to decide what to research next.` : `Lode did not record the request${r.message ? `: ${r.message}` : ''}.`;
1304
+ }
1305
+ if (cmd === 'overlap' && rest[0]) {
1306
+ const opts = { apps: flag('--apps'), region: flag('--region'), share: flag('--share') };
1307
+ const apps = list(typeof opts.apps === 'string' ? opts.apps : undefined) || [];
1308
+ if (apps.length < 2) return 'Give two or more apps: node lode.mjs overlap <platform> --apps "A,B"';
1309
+ return overlap(rest[0], apps, { region: opts.region, share: opts.share === true });
1310
+ }
1311
+ if (cmd === 'recheck') return recheck({ share: flag('--share') === true });
1312
+ if (cmd === 'drop' && rest[1]) {
1313
+ const opts = { reason: flag('--reason'), switched: flag('--switched-to'), share: flag('--share') };
1314
+ return drop(rest[0], rest[1], { reason: opts.reason, switched: opts.switched, share: opts.share === true });
1315
+ }
1316
+ if (cmd === 'adr' && (rest[0] || rest.includes('--update'))) {
1317
+ const opts = { update: flag('--update'), considered: flag('--considered'), chose: flag('--chose'), reason: flag('--reason'), status: flag('--status'), constraint: flag('--constraint'), workaround: flag('--workaround'), share: flag('--share') };
1318
+ return adr(rest[0], opts);
1319
+ }
1320
+ if (cmd === 'stack') {
1321
+ const opts = { framework: flag('--framework'), share: flag('--share') };
1322
+ return stack({ framework: opts.framework, share: opts.share === true });
1323
+ }
1324
+ if (cmd === 'triage' && rest[1]) {
1325
+ const opts = { symptom: flag('--symptom'), status: flag('--status'), object: flag('--object'), outcome: flag('--outcome'), switched: flag('--switched-to'), share: flag('--share') };
1326
+ return triageCmd(rest[0], rest[1], opts);
1327
+ }
1328
+ if (cmd === 'init') {
1329
+ const opts = { client: flag('--client'), yes: flag('--yes'), remove: flag('--remove'), gate: flag('--gate'), mode: flag('--mode'), shared: flag('--shared'), noRules: flag('--no-rules'), src: flag('--src') };
1330
+ const client = ['claude', 'cursor', 'all'].includes(opts.client) ? opts.client : 'all';
1331
+ return initCmd({ client, yes: opts.yes === true, remove: opts.remove === true, gate: opts.gate === true, gateMode: opts.mode === 'ask' ? 'ask' : 'warn', gateShared: opts.shared === true, rules: opts.noRules !== true, src: opts.src === 'setup' ? 'setup' : null });
1332
+ }
1333
+ if (cmd === 'platforms') return `Lode covers: ${Object.keys(PLATFORMS).join(', ')}. Facts are source-linked and dated; see https://trylode.io/methodology/`;
1334
+ return 'Usage:\n node lode.mjs check <app> [platform]\n node lode.mjs triage <app> <platform> --symptom <code> [--status 429] [--object o]\n node lode.mjs init [--client claude|cursor|all] [--no-rules] [--yes] [--remove]\n node lode.mjs init --gate [--mode ask] [--shared] [--yes] [--remove]\n node lode.mjs find <platform> [--category c] [--needs a,b] [--region XX] [--stack a,b] [--framework f]\n node lode.mjs list <platform> [--category <c>] [--all]\n node lode.mjs chose <app|none> <platform> [--considered "A,B"] [--reason code] [--share]\n node lode.mjs outcome <app> <platform> <integrated|failed|abandoned|not-tried> [--failure-reason code] [--share]\n node lode.mjs request <app> <platform> [--needs a,b] [--region XX]\n node lode.mjs overlap <platform> --apps "A,B,C" [--region XX] [--share]\n node lode.mjs recheck [--share]\n node lode.mjs drop <app> <platform> [--reason code] [--switched-to <app>] [--share]\n node lode.mjs adr <platform> --considered "A,B" --chose B [--reason code] [--status s] [--constraint a,b] [--workaround a,b] [--share]\n node lode.mjs adr --update <file> [--status s] [--constraint a,b] [--workaround a,b] [--share]\n node lode.mjs stack [--framework f] [--share]\n node lode.mjs platforms';
1335
+ }
1336
+
1337
+ // Run only when this very file is the entry point (security review 01-12-2026: endsWith('lode.mjs') also matched trylode.mjs).
1338
+ const isEntry = (() => {
1339
+ if (!process.argv[1]) return false;
1340
+ try { return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href; } catch { return false; }
1341
+ })();
1342
+ if (isEntry) {
1343
+ main(process.argv.slice(2)).then((t) => console.log(t)).catch((e) => { console.error(`Lode check failed: ${e.message}. Say that Lode could not be reached; do not guess the facts.`); process.exit(1); });
1344
+ }