trylode 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/PERMISSIONS.md CHANGED
@@ -13,14 +13,24 @@
13
13
 
14
14
  `--no-rules` leaves the rules line out. `--client claude` or `--client cursor` writes for one client only.
15
15
 
16
+ ### Only with `--gate` (Lode Gate, Claude Code only, off unless you add it)
17
+
18
+ - `.claude/settings.local.json`: one `PreToolUse` hook entry that runs `.claude/skills/lode-integration-check/scripts/gate.mjs` before shell commands. This file is yours only, so nobody who clones the project gets Gate without choosing it. Setup never writes the shared `.claude/settings.json`.
19
+ - `.claude/.gitignore` (only inside a git repository): two lines at the end, a comment and `settings.local.json`, so git never picks up the hook. `remove` takes out exactly those two lines, never a line you wrote.
20
+ - `.claude/skills/lode-integration-check/scripts/gate.mjs` and `gate-packages.json`: the hook and Lode's list of package names it looks for.
21
+
22
+ If a `gate.mjs` or `gate-packages.json` that differs from this package's copy is already in the project, setup refuses (exit 2) rather than point the hook at it.
23
+
16
24
  ## Reads
17
25
 
18
26
  Only the files above, to see what is already there. It never follows links, never edits a file it can't parse or couldn't write back exactly (a repeated key, or a number JSON can't keep exactly), and refuses files that are links, hard links, larger than 1 MB or not plain UTF-8.
19
27
 
20
28
  ## Sends
21
29
 
22
- Nothing. Setup and remove make no network requests. The `?src=setup` code in the server address only tells Lode, when your agent later connects, that the connection came from this command. The skill it copies sends requests to Lode only when your agent uses it; what it sends is in `skill/PERMISSIONS.md`.
30
+ Setup and remove make no network requests. The `?src=setup` code in the server address only tells Lode, when your agent later connects, that the connection came from this command. The skill it copies sends requests to Lode only when your agent uses it; what it sends is in `skill/PERMISSIONS.md`.
31
+
32
+ **Lode Gate, if you add it,** runs on your machine before each shell command the agent runs in Claude Code. It sends a request to Lode (`POST https://trylode.io/v1/gate`, 1.5 second limit) only when the command installs a package on Lode's list: those package names, the package manager, Lode platform codes worked out from config file names (never their contents), the mode and a random code for the Claude Code session. Never the command, versions, paths, file contents or the session id. Lode's answer is added to the agent's context as facts; Gate never blocks an install, and if Lode is slow or offline nothing changes. Set `LODE_GATE_LOG=0` to get the facts with nothing kept by Lode. Full detail: `skill/PERMISSIONS.md`.
23
33
 
24
34
  ## Removes
25
35
 
26
- `npx trylode remove --yes` takes out only the entries, blocks, rule file and skill copy that setup added, and deletes a file only when nothing else is left in it.
36
+ `npx trylode remove --yes` takes out only the entries, blocks, rule file, skill copy and Gate hook that setup added, and deletes a file only when nothing else is left in it. `npx trylode remove --gate --yes` takes out only Lode Gate.
package/README.md CHANGED
@@ -13,6 +13,8 @@ It adds:
13
13
  2. **The rules line** to `CLAUDE.md`, `AGENTS.md` (if present) and `.cursor/rules/lode.mdc`. This is the step that matters most: agents reliably use a tool their instructions file tells them about.
14
14
  3. **The Lode Integration Check skill** in `.claude/skills/`.
15
15
 
16
- Undo it with `npx trylode remove --yes`. Setup sends nothing to Lode. See [PERMISSIONS.md](PERMISSIONS.md).
16
+ Optional (Claude Code only): Lode Gate. Running `npx trylode setup --gate --yes` adds a hook that runs just before the agent installs a package Lode knows (for example, `npm install resend`) and injects Lode's facts into the agent's context: required platform plan, recorded regions, and any SDK deprecation or published security advisory (each with a link and date). It never blocks an install and applies only to you, in this project (`.claude/settings.local.json`, kept out of git). When triggered, it sends only package names and a few codes to Lode—never your full command, source code, or local file paths. See [PERMISSIONS.md](PERMISSIONS.md) for details.
17
+
18
+ Undo it with `npx trylode remove --yes` (or `npx trylode remove --gate --yes` for Gate only). Setup itself sends nothing to Lode. See [PERMISSIONS.md](PERMISSIONS.md).
17
19
 
18
20
  Source: [lode-hq/lode-mcp](https://github.com/lode-hq/lode-mcp). MIT licence. Lode's data is free to use with a link per fact; see [trylode.io](https://trylode.io).
package/bin/cli.mjs CHANGED
@@ -3,41 +3,69 @@
3
3
  // It is the Lode Integration Check skill's reviewed `init`, packaged: it writes Lode's MCP server (address tagged
4
4
  // ?src=setup), the rules line (CLAUDE.md, AGENTS.md if present, .cursor/rules/lode.mdc) and the skill, shows the plan
5
5
  // first and writes only with --yes. It sends nothing to Lode. `npx trylode remove --yes` undoes only what it added.
6
+ // With --gate (LOD-262) it also runs the skill's reviewed `init --gate` (warn mode, .claude/settings.local.json only).
6
7
  // No dependencies, no install scripts. See PERMISSIONS.md.
7
- import { main } from '../skill/scripts/lode.mjs';
8
8
 
9
9
  const USAGE = `Usage:
10
- npx trylode setup [--yes] [--client claude|cursor|all] [--no-rules]
10
+ npx trylode setup [--yes] [--client claude|cursor|all] [--no-rules] [--gate]
11
11
  Shows what it would add to this project, and adds it with --yes:
12
12
  .mcp.json and .cursor/mcp.json: one "lode" server entry (other entries unchanged)
13
13
  CLAUDE.md, AGENTS.md (only if present), .cursor/rules/lode.mdc: the Lode rules line
14
14
  .claude/skills/lode-integration-check/: the Lode Integration Check skill
15
- npx trylode remove [--yes]
15
+ --gate Also enables Lode Gate for Claude Code in .claude/settings.local.json (user-local, not shared).
16
+ Injects Lode's facts into the agent's context before installing a known package; never blocks.
17
+ npx trylode remove [--yes] [--gate]
16
18
  Takes out only what setup (or the skill's init) added.
19
+ --gate Removes only Lode Gate (leaves the rest of your Lode setup intact).
17
20
 
18
- Nothing is sent to Lode by setup or remove. More: https://trylode.io/agents/`;
21
+ Setup and remove send nothing to Lode. What Lode Gate sends when it runs: PERMISSIONS.md. More: https://trylode.io/agents/`;
22
+
23
+ // LOD-262 (Paul's wording, 02-12-2026): the one line setup adds when Gate is not on.
24
+ const GATE_OFFER = 'Optional for Claude Code: Lode Gate adds Lode\'s facts to your agent\'s context before installing a known package (never blocks). Enable with: npx trylode setup --gate --yes';
19
25
 
20
26
  const argv = process.argv.slice(2);
21
27
  const cmd = argv[0];
22
- // Only these flags are passed on; anything else is ignored.
28
+ // Only these flags are passed on; anything else is ignored. --gate is handled here (warn mode, this person only):
29
+ // --shared and --mode are never passed through, so setup can't put the hook in a committed file (LOD-262).
23
30
  const flags = [];
31
+ let gate = false, client = 'all';
24
32
  for (let i = 1; i < argv.length; i++) {
25
33
  const a = argv[i];
26
34
  if (a === '--yes' || a === '--no-rules') flags.push(a);
27
- else if (a === '--client' && ['claude', 'cursor', 'all'].includes(argv[i + 1])) { flags.push(a, argv[i + 1]); i++; }
35
+ else if (a === '--gate') gate = true;
36
+ else if (a === '--client' && ['claude', 'cursor', 'all'].includes(argv[i + 1])) { client = argv[i + 1]; flags.push(a, argv[i + 1]); i++; }
28
37
  }
38
+ const yes = flags.includes('--yes') ? ['--yes'] : [];
39
+ // A refusal (nothing changed because a file looked wrong) exits 2, so a script calling setup notices.
40
+ const OK = /^(Done|Removed):|would (change|write) these files|already set up|already on in this project|Nothing to remove/;
29
41
 
30
- let args = null;
31
- if (cmd === 'setup') args = ['init', '--src', 'setup', ...flags];
32
- else if (cmd === 'remove') args = ['init', '--remove', '--src', 'setup', ...flags.filter((f) => f === '--yes')];
42
+ async function steps() {
43
+ const { main } = await import('../skill/scripts/lode.mjs');
44
+ const run = async (args) => String(await main(args));
45
+ if (cmd === 'setup') {
46
+ const first = await run(['init', '--src', 'setup', ...flags]);
47
+ if (!OK.test(first)) return { out: [first], ok: false };
48
+ if (client === 'cursor') return { out: [first, ...(gate ? ['Lode Gate is for Claude Code only, so --gate was ignored with --client cursor.'] : [])], ok: true };
49
+ if (gate) { const g = await run(['init', '--gate', '--src', 'setup', ...yes]); return { out: [first, g], ok: OK.test(g) }; }
50
+ // Offer Gate only when it isn't on yet (a dry run of the reviewed check; it writes nothing)
51
+ const dry = await run(['init', '--gate', '--src', 'setup']);
52
+ return { out: [first, ...(/already on in this project/.test(dry) ? [] : [GATE_OFFER])], ok: true };
53
+ }
54
+ if (cmd === 'remove') {
55
+ const g = await run(['init', '--gate', '--remove', '--src', 'setup', ...yes]);
56
+ if (gate) return { out: [g], ok: OK.test(g) };
57
+ const rest = await run(['init', '--remove', '--src', 'setup', ...yes]);
58
+ const gateOn = !/Nothing to remove/.test(g);
59
+ return { out: [...(gateOn ? [g] : []), rest], ok: OK.test(rest) && (!gateOn || OK.test(g)) };
60
+ }
61
+ return null;
62
+ }
33
63
 
34
- if (!args) { console.log(USAGE); process.exit(cmd && !['help', '--help', '-h'].includes(cmd) ? 1 : 0); }
35
64
  try {
36
- const out = await main(args);
37
- const text = String(out);
38
- console.log(text);
39
- // A refusal (nothing changed because a file looked wrong) exits 2, so a script calling setup notices.
40
- if (!/^(Done|Removed):|would (change|write) these files|already set up|Nothing to remove/.test(text)) process.exit(2);
65
+ const r = await steps();
66
+ if (!r) { console.log(USAGE); process.exit(cmd && !['help', '--help', '-h'].includes(cmd) ? 1 : 0); }
67
+ console.log(r.out.join('\n\n'));
68
+ if (!r.ok) process.exit(2);
41
69
  } catch (e) {
42
70
  console.error(`trylode: ${e.message}`);
43
71
  process.exit(1);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trylode",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "One command puts Lode in your project: the MCP server, the rules line and the skill, so your coding agent checks integration facts before it adds a third-party service.",
5
5
  "type": "module",
6
6
  "bin": { "trylode": "bin/cli.mjs" },
@@ -15,8 +15,9 @@ secrets. Privacy policy: https://trylode.io/privacy/
15
15
  | `adr` | `lode-integrations.json`, the ADR it updates | with `--share`: project code, platform, Lode ids, fixed codes, days | `docs/adr/NNN-<platform>-<app>.md` |
16
16
  | `stack` | `package.json`, `requirements.txt`, `pyproject.toml`, `Gemfile`, `go.mod`, variable NAMES in `.env.example`, `vercel.json`, `netlify.toml`, `supabase/config.toml` | with `--share`: the app and platform codes found, the framework | nothing |
17
17
  | `triage` | nothing | the app, platform, one fixed symptom code, the HTTP status if given (only its class is kept) and the `--object` code if given (sent only when it is one of the platform's object codes, otherwise not sent); with `--share`: the outcome code and the `--switched-to` app | nothing |
18
+ | `watch` (`watch`, `watch changes`, `watch stop`) | `lode-integrations.json`, `.lode/watch.json` and an existing `.gitignore` (never through links; a file not in the expected shape is refused) | `watch`: only with `--share`, the Lode ids of the integrations still kept in `lode-integrations.json` (at most 50); Lode makes a fresh random watch code, unless `--project-code` asks it to use the file's own project code; the watch code and token on later updates. `watch changes` and `watch stop`: the watch code and the token only. Lode keeps the list of ids until the watch is stopped; `stop` deletes it | `watch --share`: `.lode/watch.json` (mode 0600: the watch code and the secret token Lode returns once; the `.lode` folder is made if missing) and, only when a `.gitignore` already exists, one appended `.lode/` line; `watch stop` removes the token file |
18
19
  | `init` | `.mcp.json`, `.cursor/mcp.json`, `.claude/lode-init.json`, `CLAUDE.md`, `AGENTS.md`, `.cursor/rules/lode.mdc` | nothing | only with `--yes`, only inside a project folder and never through links: one `lode` entry in those MCP files, a copy of this skill in `.claude/skills/`, the Lode rules line as one marked block at the end of `CLAUDE.md` (created if missing) and `AGENTS.md` (only if it exists) and as `.cursor/rules/lode.mdc` (left out with `--no-rules`), and a note of what was added in `.claude/lode-init.json`; a file it can't parse is left alone; `init --remove --yes` undoes only what init added (the rules block only when unchanged); with `--src setup` (used by `npx trylode setup`) the entry's address is `https://trylode.io/mcp?src=setup`, and `--remove` recognises either address |
19
- | `init --gate` (Lode Gate, opt-in) | `.claude/settings.local.json` (or `.claude/settings.json` with `--shared`), `.claude/lode-init.json`, the Gate files already in `.claude/skills/lode-integration-check/` | nothing | only with `--yes`, only inside a project folder and never through links: one PreToolUse hook entry in that settings file (by default only for you: Claude Code keeps `settings.local.json` out of git; `--shared` gives it to everyone who opens the project), a copy of this skill with `gate.mjs` and `gate-packages.json` in `.claude/skills/` (it never overwrites a file, and refuses if Gate files already there differ from its own), and a note in `.claude/lode-init.json`; `init --gate --remove --yes` deletes only the files it copied, unchanged, from its fixed list |
20
+ | `init --gate` (Lode Gate, opt-in) | `.claude/settings.local.json` (or `.claude/settings.json` with `--shared`), `.claude/lode-init.json`, `.claude/.gitignore`, the Gate files already in `.claude/skills/lode-integration-check/` | nothing | only with `--yes`, only inside a project folder and never through links: one PreToolUse hook entry in that settings file (by default only for you: Claude Code keeps `settings.local.json` out of git; `--shared` gives it to everyone who opens the project), a copy of this skill with `gate.mjs` and `gate-packages.json` in `.claude/skills/` (it never overwrites a file, and refuses if Gate files already there differ from its own), two lines at the end of `.claude/.gitignore` inside a git repository (a comment and `settings.local.json`, so the hook file is never committed; `--remove` takes out exactly those two), and a note in `.claude/lode-init.json`; `init --gate --remove --yes` deletes only the files it copied, unchanged, from its fixed list |
20
21
  | Gate hook (`scripts/gate.mjs`, runs before each shell command once switched on) | the shell command Claude is about to run and the session id (on your machine only; the id is used only to name the temp file below), the project folder (`CLAUDE_PROJECT_DIR`, else the working folder), whether `vercel.json`, `.vercel/project.json`, `netlify.toml`, `supabase/config.toml`, `wrangler.toml`, `wrangler.json` or `wrangler.jsonc` exist there (names only, never contents), `gate-packages.json`, and `LODE_GATE_LOG` | only when the command installs a package on Lode's list: those package names, the package manager, the platform codes found, the mode and a random code for the Claude Code session; never the command, versions, paths, file contents or the session id; with `LODE_GATE_LOG=0` Lode keeps nothing except the daily rate-limit count | a random session code in your temp folder (tidied after a day) |
21
22
 
22
23
  Connect the MCP server at `https://trylode.io/mcp?log=0` to keep Lode from logging your requests (only the daily
package/skill/SKILL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: lode-integration-check
3
- description: 'Verified, source-linked facts about how two software products work together, from Lode (trylode.io). Use before recommending, comparing, connecting or installing an app or integration on Xero, QuickBooks Online, HubSpot, Shopify, Stripe, Supabase, Vercel, Netlify, n8n, Lovable, Replit, Linear, GitHub, LangChain, Cursor or Cloudflare, for example "connect Shopify to Xero", "which Xero app syncs purchase orders", "add auth to my Supabase project", "use Clerk with Supabase", "vercel integration add" or "sync Stripe payouts to QuickBooks", or adding a database, Postgres, Redis, auth, email or other service to a Vercel, Netlify or Supabase project through its marketplace. Answers what syncs and in which direction, price, the platform plan needed, regions, known limitations and who built the integration, each with its source and date. Also checks whether apps already connected to one platform write the same data into it ("A2X and Synder on Xero: do they overlap?"), reads a project''s package.json, requirements or config files to report what Lode documents about its stack (plan needed, overlaps, function run-time limits), writes an integration decision record (ADR) when the user picks an integration, and explains from sourced facts why an integration fails (auth, plan, rate or run-time limits, webhooks, outages).'
3
+ description: 'Use before you add, recommend, compare, connect or install a third-party service, SDK or integration, or decide to build that capability yourself (auth, email, payments, database, background jobs, rate limiting), on Xero, QuickBooks Online, HubSpot, Shopify, Stripe, Supabase, Vercel, Netlify, n8n, Lovable, Replit, Linear, GitHub, LangChain, Cursor or Cloudflare. Also use to ask if two products work together, or when an integration fails. Examples: "add auth to my Supabase app", "which Xero app syncs purchase orders", "Stripe payouts stopped reaching QuickBooks". Returns Lode''s facts, each with its source link and last-verified date: what syncs and which way, price by currency, platform plan, regions, limits, who built it; also checks a project''s stack and overlaps. Sends Lode only what you look up (app, platform, needs, region) and fixed codes, never errors, logs or code; choices only with --share after the user agrees. Writes: init only with --yes; chose and adr save to lode-integrations.json and docs/adr/.'
4
4
  ---
5
5
 
6
6
  # Lode Integration Check
@@ -145,6 +145,20 @@ add `--share` if they say yes. It sends, per platform, the file's random project
145
145
  integration, its Lode id, kept, dropped or swapped, the reason code and how many days since it was
146
146
  chosen. Nothing else from the file or the project.
147
147
 
148
+ To hear about changes without re-checking by hand, the user can ask Lode to watch the kept integrations.
149
+ Always ask first whether Lode may keep the list of these integrations (Lode ids only, under a fresh
150
+ random watch code) until they stop the watch; only add `--share` if they say yes:
151
+
152
+ ```bash
153
+ node scripts/lode.mjs watch --share # start, or update the list after new choices
154
+ node scripts/lode.mjs watch changes # what changed in Lode for those records since the watch began
155
+ node scripts/lode.mjs watch stop # delete the watch at Lode
156
+ ```
157
+
158
+ Lode makes a fresh random watch code. The secret token it returns is saved in `.lode/watch.json`
159
+ (readable only by the user), and `.lode/` is added to an existing `.gitignore`; if there is none, tell the
160
+ user to keep `.lode/` out of version control. Report changes as Lode's facts with their links, never as advice.
161
+
148
162
  ## Decision records
149
163
 
150
164
  When the user has decided on an integration and is working in their project, offer to write a short
@@ -0,0 +1,182 @@
1
+ {
2
+ "note": "Package names on Lode's list (https://trylode.io/api/stack-signals.json). Lode Gate sends a request only for these.",
3
+ "npm": [
4
+ "@ably/pubsub-device",
5
+ "@ably/pubsub-server",
6
+ "@anthropic-ai/sdk",
7
+ "@arcjet/next",
8
+ "@arcjet/node",
9
+ "@auth0/auth0-react",
10
+ "@auth0/nextjs-auth0",
11
+ "@axiomhq/js",
12
+ "@browserbasehq/sdk",
13
+ "@clerk/backend",
14
+ "@clerk/clerk-react",
15
+ "@clerk/nextjs",
16
+ "@clerk/react",
17
+ "@customerio/cdp-analytics-node",
18
+ "@descope/nextjs-sdk",
19
+ "@descope/node-sdk",
20
+ "@descope/react-sdk",
21
+ "@fal-ai/client",
22
+ "@getbrevo/brevo",
23
+ "@growthbook/growthbook",
24
+ "@hatchet-dev/typescript-sdk",
25
+ "@hexclave/js",
26
+ "@hexclave/next",
27
+ "@hexclave/react",
28
+ "@hubspot/api-client",
29
+ "@kinde-oss/kinde-auth-nextjs",
30
+ "@knocklabs/node",
31
+ "@launchdarkly/node-server-sdk",
32
+ "@lemonsqueezy/lemonsqueezy.js",
33
+ "@libsql/client",
34
+ "@logto/express",
35
+ "@logto/next",
36
+ "@logto/node",
37
+ "@mailchimp/mailchimp_marketing",
38
+ "@mendable/firecrawl-js",
39
+ "@mux/mux-node",
40
+ "@mux/ts",
41
+ "@neondatabase/serverless",
42
+ "@netlify/functions",
43
+ "@notionhq/client",
44
+ "@novu/api",
45
+ "@novu/nextjs",
46
+ "@novu/react",
47
+ "@okta/okta-auth-js",
48
+ "@paddle/paddle-node-sdk",
49
+ "@paypal/paypal-server-sdk",
50
+ "@planetscale/database",
51
+ "@polar-sh/sdk",
52
+ "@prisma/client",
53
+ "@prisma/orm-mongo",
54
+ "@prisma/orm-postgres",
55
+ "@propelauth/nextjs",
56
+ "@propelauth/node",
57
+ "@sanity/client",
58
+ "@sendgrid/mail",
59
+ "@sentry/nextjs",
60
+ "@sentry/node",
61
+ "@shopify/shopify-api",
62
+ "@shopify/shopify-app-remix",
63
+ "@slack/web-api",
64
+ "@stackframe/stack",
65
+ "@storyblok/js",
66
+ "@stripe/stripe-js",
67
+ "@stytch/nextjs",
68
+ "@stytch/vanilla-js",
69
+ "@supabase/ssr",
70
+ "@supabase/supabase-js",
71
+ "@temporalio/client",
72
+ "@temporalio/worker",
73
+ "@temporalio/workflow",
74
+ "@trigger.dev/react-hooks",
75
+ "@trigger.dev/sdk",
76
+ "@trycourier/courier",
77
+ "@unkey/api",
78
+ "@unkey/nextjs",
79
+ "@unkey/ratelimit",
80
+ "@upstash/qstash",
81
+ "@upstash/redis",
82
+ "@vercel/analytics",
83
+ "@vercel/blob",
84
+ "@vercel/functions",
85
+ "@workos-inc/node",
86
+ "@xata.io/client",
87
+ "ably",
88
+ "airtable",
89
+ "algoliasearch",
90
+ "auth0",
91
+ "better-auth",
92
+ "bullmq",
93
+ "cloudinary",
94
+ "contentful",
95
+ "convex",
96
+ "customerio-node",
97
+ "dd-trace",
98
+ "drizzle-orm",
99
+ "exa-js",
100
+ "firebase",
101
+ "firebase-admin",
102
+ "firecrawl",
103
+ "inngest",
104
+ "intuit-oauth",
105
+ "klaviyo-api",
106
+ "loops",
107
+ "mailersend",
108
+ "mailgun.js",
109
+ "mongodb",
110
+ "netlify-cli",
111
+ "newrelic",
112
+ "next-auth",
113
+ "node-mailjet",
114
+ "node-quickbooks",
115
+ "openai",
116
+ "posthog-js",
117
+ "posthog-node",
118
+ "postmark",
119
+ "replicate",
120
+ "resend",
121
+ "rollbar",
122
+ "sparkpost",
123
+ "square",
124
+ "statsig-node",
125
+ "stripe",
126
+ "stytch",
127
+ "svix",
128
+ "twilio",
129
+ "uploadthing",
130
+ "vercel",
131
+ "xero-node"
132
+ ],
133
+ "pypi": [
134
+ "algoliasearch",
135
+ "anthropic",
136
+ "auth0-python",
137
+ "brevo-python",
138
+ "cloudinary",
139
+ "contentful",
140
+ "convex",
141
+ "customerio",
142
+ "customerio-cdp-analytics",
143
+ "descope",
144
+ "exa-py",
145
+ "hubspot-api-client",
146
+ "inngest",
147
+ "intuit-oauth",
148
+ "klaviyo-api",
149
+ "knockapi",
150
+ "launchdarkly-server-sdk",
151
+ "mailchimp-marketing",
152
+ "mailersend",
153
+ "mailjet-rest",
154
+ "mux-python",
155
+ "notion-client",
156
+ "novu-py",
157
+ "openai",
158
+ "paddle-python-sdk",
159
+ "posthog",
160
+ "propelauth-py",
161
+ "pyairtable",
162
+ "pymongo",
163
+ "python-quickbooks",
164
+ "replicate",
165
+ "resend",
166
+ "sendgrid",
167
+ "sentry-sdk",
168
+ "shopifyapi",
169
+ "slack-sdk",
170
+ "squareup",
171
+ "stripe",
172
+ "stytch",
173
+ "supabase",
174
+ "temporalio",
175
+ "trycourier",
176
+ "twilio",
177
+ "unkey-py",
178
+ "upstash-redis",
179
+ "workos",
180
+ "xero-python"
181
+ ]
182
+ }
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env node
2
+ // Lode Gate (LOD-231): an opt-in Claude Code PreToolUse hook. Just before the agent installs a package on Lode's list
3
+ // (gate-packages.json, from https://trylode.io/api/stack-signals.json), it adds Lode's facts to the agent's context.
4
+ // Switched on only by a person's choice: `node lode.mjs init --gate --yes`, `npx trylode setup --gate --yes`, or installing
5
+ // the `lode-gate` Claude Code plugin (LOD-262); each has its own remove. See PERMISSIONS.md.
6
+ //
7
+ // What it sends, only when an install names a package on Lode's list: those package names, the package manager,
8
+ // Lode platform codes found from config file NAMES in the project (never their contents), the mode and a random
9
+ // code for this Claude Code session. Never the command, versions, paths, file contents or the session id.
10
+ // Installs of other packages send nothing. Any failure (offline, slow, bad answer) passes silently: Gate can't
11
+ // break an install. In `ask` mode a warning sends the install to the permission prompt; Gate never denies.
12
+ // No dependencies (Node 18+). Set LODE_GATE_LOG=0 to get the facts with nothing kept by Lode.
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import os from 'node:os';
16
+ import crypto from 'node:crypto';
17
+ import { fileURLToPath } from 'node:url';
18
+
19
+ const VERSION = '0.1';
20
+ // Lode's own tests may point the hook at this machine; nothing else can change where it sends (security review 30-11-2026).
21
+ const BASE = (() => { const u = process.env.LODE_GATE_URL || ''; return /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(u) ? u : 'https://trylode.io'; })();
22
+ const UA = /^lode-gate-test\b/.test(process.env.LODE_UA || '') ? process.env.LODE_UA : `lode-gate/${VERSION}`;
23
+ const BUDGET_MS = 1500;
24
+ const MAX_CONTEXT = 1200;
25
+ // Kept equal to GATE_WARNINGS in Lode's src/lib/gate.mjs (test)
26
+ const GATE_WARNINGS = ['plan-needed', 'region-limited', 'sdk-deprecated', 'latest-affected', 'pinned-affected', 'no-record-on-platform', 'held-record'];
27
+ // Platforms told apart by a config file's name only (kept equal to PLATFORM_FILES in Lode's src/lib/gate.mjs)
28
+ const PLATFORM_FILES = { vercel: ['vercel.json', '.vercel/project.json'], netlify: ['netlify.toml'], supabase: ['supabase/config.toml'], cloudflare: ['wrangler.toml', 'wrangler.json', 'wrangler.jsonc'] };
29
+
30
+ // BEGIN PARSER
31
+ // Splits a shell command into simple commands and returns every package an install names:
32
+ // [{ manager, system: 'npm'|'pypi', name, version }]. version is an exact pin (e.g. 1.2.3) or null.
33
+ // Anything that isn't a plain registry name (paths, URLs, git specs, requirement files) is skipped.
34
+ function gateTokens(segment) {
35
+ const out = []; let cur = ''; let q = null; let has = false;
36
+ for (const ch of segment) {
37
+ if (q) { if (ch === q) q = null; else cur += ch; continue; }
38
+ if (ch === '"' || ch === "'") { q = ch; has = true; continue; }
39
+ if (/\s/.test(ch)) { if (has || cur) out.push(cur); cur = ''; has = false; continue; }
40
+ cur += ch; has = true;
41
+ }
42
+ if (has || cur) out.push(cur);
43
+ return out;
44
+ }
45
+ const NPM_VALUE_FLAGS = new Set(['--registry', '--prefix', '-w', '--workspace', '--filter', '-F', '--cwd', '--tag', '--cache', '--userconfig']);
46
+ const PIP_VALUE_FLAGS = new Set(['-r', '--requirement', '-c', '--constraint', '-e', '--editable', '-i', '--index-url', '--extra-index-url', '-t', '--target', '--prefix', '--root', '-f', '--find-links', '--python', '-p', '--group', '--optional', '-G', '--source', '--platform', '--python-version']);
47
+ function gateNpmSpec(t) {
48
+ if (!t || /^[./~]|^(https?|git|git\+\w+|file|link|github|gitlab|bitbucket|npm|workspace|portal|patch):/i.test(t) || t.includes('/') && !t.startsWith('@')) return null;
49
+ const at = t.startsWith('@') ? t.indexOf('@', 1) : t.indexOf('@');
50
+ const name = (at > 0 ? t.slice(0, at) : t).toLowerCase();
51
+ if (!/^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(name)) return null;
52
+ const v = at > 0 ? t.slice(at + 1) : '';
53
+ return { name, version: /^v?\d+\.\d+\.\d+([-+][0-9A-Za-z.-]+)?$/.test(v) ? v.replace(/^v/, '') : null };
54
+ }
55
+ function gatePipSpec(t) {
56
+ if (!t || /^[./~]|:\/\/|^git\+/i.test(t) || /\.(whl|tar\.gz|zip)$/i.test(t)) return null;
57
+ const m = /^([A-Za-z0-9][A-Za-z0-9._-]*)(\[[^\]]*\])?\s*(==\s*(\d+(\.\d+)*))?/.exec(t);
58
+ if (!m) return null;
59
+ return { name: m[1].toLowerCase().replace(/[-_.]+/g, '-'), version: m[4] ?? null };
60
+ }
61
+ // Splits on ; | & and newlines that sit outside quotes, so text inside a quoted argument is never read as a command.
62
+ function gateSegments(command) {
63
+ const out = []; let cur = ''; let q = null;
64
+ for (const ch of command) {
65
+ if (q) { cur += ch; if (ch === q) q = null; continue; }
66
+ if (ch === '"' || ch === "'") { q = ch; cur += ch; continue; }
67
+ if (ch === ';' || ch === '|' || ch === '&' || ch === '\n') { out.push(cur); cur = ''; continue; }
68
+ cur += ch;
69
+ }
70
+ out.push(cur);
71
+ return out;
72
+ }
73
+ function parseInstall(command) {
74
+ const found = [];
75
+ if (typeof command !== 'string' || command.length > 20000) return found;
76
+ for (const seg of gateSegments(command)) {
77
+ let t = gateTokens(seg.trim());
78
+ while (t.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0]) || ['sudo', 'env', 'command', 'time', 'exec'].includes(t[0]))) t = t.slice(1);
79
+ if (!t.length) continue;
80
+ const bin = t[0].split('/').pop().toLowerCase();
81
+ let manager = null, system = null, rest = null;
82
+ if (bin === 'npm' && ['install', 'i', 'add', 'in'].includes(t[1])) [manager, system, rest] = ['npm', 'npm', t.slice(2)];
83
+ else if (bin === 'pnpm' && ['add', 'install', 'i'].includes(t[1])) [manager, system, rest] = ['pnpm', 'npm', t.slice(2)];
84
+ else if (bin === 'yarn' && t[1] === 'add') [manager, system, rest] = ['yarn', 'npm', t.slice(2)];
85
+ else if (bin === 'yarn' && t[1] === 'global' && t[2] === 'add') [manager, system, rest] = ['yarn', 'npm', t.slice(3)];
86
+ else if (bin === 'bun' && ['add', 'install', 'i', 'a'].includes(t[1])) [manager, system, rest] = ['bun', 'npm', t.slice(2)];
87
+ else if (/^pip3?(\.\d+)?$/.test(bin) && t[1] === 'install') [manager, system, rest] = ['pip', 'pypi', t.slice(2)];
88
+ else if (/^python3?(\.\d+)?$/.test(bin) && t[1] === '-m' && t[2] === 'pip' && t[3] === 'install') [manager, system, rest] = ['pip', 'pypi', t.slice(4)];
89
+ else if (bin === 'uv' && t[1] === 'add') [manager, system, rest] = ['uv', 'pypi', t.slice(2)];
90
+ else if (bin === 'uv' && t[1] === 'pip' && t[2] === 'install') [manager, system, rest] = ['uv', 'pypi', t.slice(3)];
91
+ else if (bin === 'poetry' && t[1] === 'add') [manager, system, rest] = ['poetry', 'pypi', t.slice(2)];
92
+ if (!manager || rest.includes('--dry-run')) continue;
93
+ const valueFlags = system === 'npm' ? NPM_VALUE_FLAGS : PIP_VALUE_FLAGS;
94
+ for (let i = 0; i < rest.length; i++) {
95
+ const a = rest[i];
96
+ if (a === '--') continue;
97
+ if (a.startsWith('-')) { if (valueFlags.has(a)) i++; continue; }
98
+ const spec = system === 'npm' ? gateNpmSpec(a) : gatePipSpec(a);
99
+ if (spec) found.push({ manager, system, name: spec.name, version: spec.version });
100
+ }
101
+ }
102
+ return found;
103
+ }
104
+ // Exact-version comparison for the local "pinned version inside an affected range" check.
105
+ // Numbers first; a version with a pre-release part (1.2.0-beta.1, PyPI 1.2.0rc1) sorts before the release.
106
+ function gateCmp(a, b) {
107
+ const split = (v) => { const m = /^(\d+(?:\.\d+)*)(.*)$/.exec(String(v).replace(/^v/, '').split('+')[0]) || [null, '0', String(v)]; return [m[1].split('.').map(Number), m[2].replace(/^[-.]/, '')]; };
108
+ const [na, pa] = split(a), [nb, pb] = split(b);
109
+ for (let i = 0; i < Math.max(na.length, nb.length); i++) { const d = (na[i] || 0) - (nb[i] || 0); if (d) return d < 0 ? -1 : 1; }
110
+ if (pa === pb) return 0;
111
+ if (!pa) return 1;
112
+ if (!pb) return -1;
113
+ return pa < pb ? -1 : 1;
114
+ }
115
+ function gateAffected(version, ranges) {
116
+ if (!version) return [];
117
+ return (ranges || []).filter((r) => r && typeof r.id === 'string'
118
+ && (!r.introduced || r.introduced === '0' || gateCmp(version, r.introduced) >= 0)
119
+ && (r.fixed ? gateCmp(version, r.fixed) < 0 : r.last_affected ? gateCmp(version, r.last_affected) <= 0 : true)).map((r) => r.id);
120
+ }
121
+ // END PARSER
122
+
123
+ const here = path.dirname(fileURLToPath(import.meta.url));
124
+ // Lode's answer is untrusted text: control and formatting characters (incl. Unicode tag characters) are removed, and a
125
+ // line that looks like a command or links anywhere but Lode and the package registries is dropped, not shown.
126
+ const clean = (t, n = 300) => String(t ?? '').replace(/[\p{Cc}\p{Cf}\p{Co}\p{Cn}]/gu, ' ').replace(/\s+/g, ' ').trim().slice(0, n);
127
+ const OK_HOSTS = ['trylode.io', 'www.npmjs.com', 'pypi.org', 'osv.dev'];
128
+ const looksSafe = (t) => !/[`$<>{}\\]|\|\s*\w|\b(curl|wget|bash|sh|sudo|rm|chmod|eval|exec|powershell|iex)\b/i.test(t)
129
+ && [...t.matchAll(/https?:\/\/([^/\s)]+)/g)].every((m) => OK_HOSTS.includes(m[1].toLowerCase()));
130
+
131
+ // A random code per Claude Code session, kept in the temp folder under a hash of the session id, so Lode can link
132
+ // the checks of one session without ever receiving the session id.
133
+ function sessionCode(sessionId) {
134
+ if (typeof sessionId !== 'string' || !sessionId) return undefined;
135
+ try {
136
+ const dir = os.tmpdir();
137
+ const f = path.join(dir, `lode-gate-${crypto.createHash('sha256').update(sessionId).digest('hex').slice(0, 24)}`);
138
+ const read = () => { const st = fs.lstatSync(f); if (!st.isFile() || (typeof process.getuid === 'function' && st.uid !== process.getuid())) return undefined; const c = fs.readFileSync(f, 'utf8').trim(); return /^[0-9a-f]{16}$/.test(c) ? c : undefined; };
139
+ try { const c = read(); if (c) return c; } catch { /* new session */ }
140
+ const c = crypto.randomBytes(8).toString('hex');
141
+ try { fs.writeFileSync(f, c, { mode: 0o600, flag: 'wx' }); } catch { try { return read(); } catch { return undefined; } }
142
+ // Tidy codes from sessions more than a day old (only this hook's own files)
143
+ try { for (const n of fs.readdirSync(dir)) if (/^lode-gate-[0-9a-f]{24}$/.test(n)) { const g = path.join(dir, n); const st = fs.lstatSync(g); if (st.isFile() && Date.now() - st.mtimeMs > 86400000) fs.rmSync(g); } } catch { /* best effort */ }
144
+ return c;
145
+ } catch { return undefined; }
146
+ }
147
+
148
+ export async function run(input, { fetchImpl = globalThis.fetch, env = process.env, mode = 'warn' } = {}) {
149
+ if (!input || !['Bash', 'PowerShell'].includes(input.tool_name)) return null;
150
+ const command = input.tool_input?.command;
151
+ const found = parseInstall(command);
152
+ if (!found.length) return null;
153
+ let list;
154
+ try { list = JSON.parse(fs.readFileSync(path.join(here, 'gate-packages.json'), 'utf8')); } catch { return null; }
155
+ const known = { npm: new Set(list.npm ?? []), pypi: new Set(list.pypi ?? []) };
156
+ const matched = found.filter((p) => known[p.system]?.has(p.name));
157
+ if (!matched.length) return null; // nothing on Lode's list: no request at all
158
+ const root = typeof env.CLAUDE_PROJECT_DIR === 'string' && env.CLAUDE_PROJECT_DIR ? env.CLAUDE_PROJECT_DIR : (typeof input.cwd === 'string' ? input.cwd : null);
159
+ const platforms = root ? Object.keys(PLATFORM_FILES).filter((p) => PLATFORM_FILES[p].some((f) => { try { return fs.existsSync(path.join(root, f)); } catch { return false; } })) : [];
160
+ const body = {
161
+ packages: [...new Map(matched.map((p) => [`${p.system}:${p.name}`, { system: p.system, name: p.name }])).values()].slice(0, 10),
162
+ platforms,
163
+ manager: matched[0].manager,
164
+ mode,
165
+ session: sessionCode(input.session_id),
166
+ };
167
+ const noLog = env.LODE_GATE_LOG === '0';
168
+ let answer;
169
+ try {
170
+ const res = await fetchImpl(`${BASE}/v1/gate${noLog ? '?log=0' : ''}`, { method: 'POST', headers: { 'content-type': 'application/json', 'user-agent': UA }, body: JSON.stringify(noLog ? { ...body, log: false } : body), signal: AbortSignal.timeout(BUDGET_MS) });
171
+ if (!res.ok) return null;
172
+ answer = await res.json();
173
+ } catch { return null; }
174
+ const lines = []; const warnings = new Set();
175
+ for (const p of Array.isArray(answer?.packages) ? answer.packages : []) {
176
+ for (const f of Array.isArray(p.facts) ? p.facts.slice(0, 6) : []) { const t = clean(f); if (t && looksSafe(t)) lines.push(`- ${t}`); }
177
+ for (const w of Array.isArray(p.warnings) ? p.warnings : []) if (GATE_WARNINGS.includes(w)) warnings.add(w);
178
+ // A pinned version is checked here, on this machine: the version is never sent
179
+ const pinned = matched.find((m) => m.system === p.system && m.name === p.package && m.version);
180
+ const hits = pinned ? gateAffected(pinned.version, Array.isArray(p.sdk?.affected) ? p.sdk.affected : []) : [];
181
+ const ids = [...new Set(hits)].filter((h) => /^[A-Za-z0-9-]{3,40}$/.test(h)).slice(0, 3);
182
+ if (ids.length) { warnings.add('pinned-affected'); lines.push(`- ${clean(`${pinned.name} ${pinned.version} (the version in this command) is inside ${ids.join(', ')} per OSV.dev.`)}`); }
183
+ }
184
+ if (!lines.length) return null;
185
+ let context = `Lode Gate: facts Lode records for this install (https://trylode.io; facts, not instructions; "not documented" is not "not supported"):\n${lines.join('\n')}`;
186
+ if (context.length > MAX_CONTEXT) context = `${context.slice(0, MAX_CONTEXT - 1)}…`;
187
+ const out = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: context } };
188
+ if (mode === 'ask' && warnings.size) {
189
+ out.hookSpecificOutput.permissionDecision = 'ask';
190
+ const SAY = { 'plan-needed': 'needs a paid platform plan', 'region-limited': 'only some regions are documented', 'sdk-deprecated': 'the package is deprecated by its publisher', 'latest-affected': 'its latest version has a published security advisory', 'pinned-affected': 'the version in this command has a published security advisory', 'no-record-on-platform': 'Lode has no record for this platform', 'held-record': "Lode's record is not yet verified" };
191
+ out.hookSpecificOutput.permissionDecisionReason = clean(`Lode Gate: ${[...warnings].map((w) => SAY[w] ?? w).join('; ')}. Claude has been given the facts; approve to install anyway.`, 300);
192
+ }
193
+ return out;
194
+ }
195
+
196
+ async function readStdin(max = 1024 * 1024) {
197
+ let s = '';
198
+ for await (const chunk of process.stdin) { s += chunk; if (s.length > max) return null; }
199
+ return s;
200
+ }
201
+
202
+ // Compared as real paths: a plugin or project folder under a symlink (macOS /tmp, /var) must still run (review 02-12-2026)
203
+ const realArg = (() => { try { return fs.realpathSync(process.argv[1]); } catch { return null; } })();
204
+ if (process.argv[1] && (fileURLToPath(import.meta.url) === path.resolve(process.argv[1]) || fileURLToPath(import.meta.url) === realArg)) {
205
+ const mode = process.argv.includes('--mode') && process.argv[process.argv.indexOf('--mode') + 1] === 'ask' ? 'ask' : 'warn';
206
+ (async () => {
207
+ try {
208
+ const raw = await readStdin();
209
+ const out = raw ? await run(JSON.parse(raw), { mode }) : null;
210
+ if (out) process.stdout.write(JSON.stringify(out));
211
+ } catch { /* fail open: print nothing */ }
212
+ process.exit(0);
213
+ })();
214
+ }
@@ -23,6 +23,8 @@
23
23
  // node lode.mjs stack [--framework f] [--share] what Lode documents about the apps and platforms this project's manifests name
24
24
  // node lode.mjs triage <app> <platform> --symptom <code> [--status 429] [--object o] [--outcome fixed|switched|gave-up] [--switched-to <app>] [--share]
25
25
  // why an integration fails: Lode's sourced facts for that kind of failure
26
+ // node lode.mjs watch [--share] [--project-code] ask Lode to watch the kept integrations in lode-integrations.json (only with --share)
27
+ // node lode.mjs watch changes [--since d] what changed in Lode for the watched integrations; watch stop deletes the watch
26
28
  // node lode.mjs init [--client claude|cursor|all] [--yes] [--remove]
27
29
  // add Lode to this project so every teammate and sub-agent has it (shows the files first)
28
30
  //
@@ -47,7 +49,7 @@
47
49
  // copies this skill into .claude/skills/, after showing the files and only with --yes; it sends nothing to Lode.
48
50
  // Nothing else from your project, prompt or machine is sent; no free text. https://trylode.io/privacy/
49
51
  import { createHash, randomUUID } from 'node:crypto';
50
- import { readFileSync, writeFileSync as fsWriteFileSync, existsSync, readdirSync, mkdirSync, lstatSync, realpathSync } from 'node:fs';
52
+ import { readFileSync, writeFileSync as fsWriteFileSync, existsSync, readdirSync, mkdirSync, lstatSync, realpathSync, openSync, fstatSync, closeSync, constants as fsConstants } from 'node:fs';
51
53
  import { join, resolve as resolvePath, relative as relativePath, isAbsolute as isAbsolutePath } from 'node:path';
52
54
  import { pathToFileURL } from 'node:url';
53
55
 
@@ -889,9 +891,51 @@ async function triageCmd(app, platform, opts) {
889
891
  // Exec form (no shell), so the path is one argument on every platform (security review 30-11-2026).
890
892
  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
893
  const GATE_FILES_LIST = ['SKILL.md', 'PERMISSIONS.md', 'scripts/lode.mjs', 'scripts/gate.mjs', 'scripts/gate-packages.json'];
894
+ // Security review 02-12-2026 (LOD-262): every project file gateInit reads is untrusted, so it is read the way init reads
895
+ // (readSafe): a regular file with one name, at most 1 MB, opened without following a link or blocking (a FIFO or a
896
+ // link to /dev/zero used to hang remove), checked again once open. { text } | { text: null } when absent | { bad }.
897
+ function gateReadText(fs, f) {
898
+ let st; try { st = fs.lstatSync(f); } catch (e) { return e.code === 'ENOENT' ? { text: null } : { bad: `can't be read (${e.code}).` }; }
899
+ if (!st.isFile()) return { bad: "not a plain file, so it won't be touched." };
900
+ if (st.nlink > 1) return { bad: "it has another name elsewhere (a hard link), so it won't be touched." };
901
+ if (st.size > 1024 * 1024) return { bad: "larger than 1 MB, so it won't be touched." };
902
+ 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}).` }; }
903
+ 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') }; } finally { fs.closeSync(fd); }
904
+ }
905
+ // Writing the settings back must keep every value: refuse numbers JSON can't keep exactly (1.50, very large integers)
906
+ // and repeated keys (same rule as init).
907
+ function gateLossless(text) {
908
+ const bare = text.replace(/"(?:[^"\\]|\\.)*"/g, '""');
909
+ for (const n of bare.match(/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g) || []) if (String(Number(n)) !== n) return false;
910
+ const keyCount = (text.match(/"(?:[^"\\]|\\.)*"\s*:/g) || []).length;
911
+ 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);
912
+ return keyCount === count(JSON.parse(text));
913
+ }
914
+ // .claude/settings.local.json is only kept out of git when Claude Code itself created it, so inside a git work tree
915
+ // (found by walking up, so monorepo folders count; git itself is never run, since a project's git config can run
916
+ // commands) gateInit appends its own block to .claude/.gitignore. That is the deepest ignore file for the hook file and
917
+ // the block comes last, so it wins over any earlier rule. --remove takes out only that exact block (re-check
918
+ // 02-12-2026: never a bare line the user may own) and deletes the file only if nothing else is in it and it made it.
919
+ const GATE_IGNORE_LINE = 'settings.local.json';
920
+ const GATE_IGNORE_BLOCK = `# Lode Gate: keep this person's hook out of git (added by lode init --gate)\n${GATE_IGNORE_LINE}\n`;
921
+ // A file git already tracks is committed whatever .gitignore says, so a hook added to it would reach everyone.
922
+ // Read .git/index directly (git is never run): true when an entry's path is exactly `rel`. The entry's path is
923
+ // preceded by its flags, whose low 12 bits are the path length, so a longer path ending the same way never matches.
924
+ // Index v4 compresses paths and may not match; then this says false (re-check 02-12-2026, low impact).
925
+ function gateTracked(fs, indexFile, rel) {
926
+ let st; try { st = fs.lstatSync(indexFile); } catch { return false; }
927
+ if (!st.isFile() || st.size > 256 * 1024 * 1024) return false;
928
+ let fd, buf; try { fd = fs.openSync(indexFile, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0)); if (!fs.fstatSync(fd).isFile()) return false; buf = fs.readFileSync(fd); } catch { return false; } finally { if (fd !== undefined) fs.closeSync(fd); }
929
+ const needle = Buffer.from(`${rel}\0`), len = needle.length - 1;
930
+ for (let i = buf.indexOf(needle, 12); i >= 0; i = buf.indexOf(needle, i + 1)) if (i >= 2 && buf[i - 1] === (len & 0xff) && (buf[i - 2] & 0x0f) === ((len >> 8) & 0x0f)) return true;
931
+ return false;
932
+ }
933
+ const gateIsHook = (h) => JSON.stringify(h) === JSON.stringify(GATE_HOOK('warn')) || JSON.stringify(h) === JSON.stringify(GATE_HOOK('ask'));
892
934
  // By default the hook goes in .claude/settings.local.json (this person only, not committed), so nobody who clones
893
935
  // 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 } = {}) {
936
+ async function gateInit({ yes = false, remove = false, mode = 'warn', shared = false, src = null } = {}) {
937
+ // Through npx trylode (LOD-262) the user has no lode.mjs, so every command shown is trylode's own.
938
+ const gateCmd = (rm) => (src === 'setup' ? `npx trylode ${rm ? 'remove' : 'setup'} --gate --yes` : `node lode.mjs init --gate${rm ? ' --remove' : ''} --yes`);
895
939
  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
940
  const cwd = fs.realpathSync(process.cwd());
897
941
  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.';
@@ -901,17 +945,32 @@ async function gateInit({ yes = false, remove = false, mode = 'warn', shared = f
901
945
  const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
902
946
  const hash = (f) => crypto.createHash('sha256').update(fs.readFileSync(f)).digest('hex');
903
947
  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
948
  const ALLOWED_SETTINGS = [path.join('.claude', 'settings.local.json'), path.join('.claude', 'settings.json')];
949
+ const ignoreRel = path.join('.claude', '.gitignore'), ignoreFile = path.join(cwd, ignoreRel);
950
+ for (const rel of [markerRel, ignoreRel]) if (!safe(rel)) return `${rel}: it or a folder above it is a link, so lode init won't write there. Nothing was written.`;
951
+ let marker = { added: [], skill_files: {} };
952
+ const mr = gateReadText(fs, markerFile);
953
+ if (mr.bad) return `${markerRel}: ${mr.bad} Nothing was written.`;
954
+ if (mr.text != null) {
955
+ let m; try { m = JSON.parse(mr.text); } catch { m = undefined; }
956
+ const plainObj = (o) => !!o && typeof o === 'object' && !Array.isArray(o);
957
+ // A planted note must not steer which file is edited or which hook is taken out (security review 02-12-2026)
958
+ const g = m?.gate, ig = g?.ignore;
959
+ const gateOk = g == null || (plainObj(g) && ALLOWED_SETTINGS.includes(g.file) && typeof g.created === 'boolean' && gateIsHook(g.entry)
960
+ && (ig == null || (plainObj(ig) && ig.line === GATE_IGNORE_LINE && typeof ig.created === 'boolean')));
961
+ if (!plainObj(m) || !gateOk || (m.gate_files != null && !(plainObj(m.gate_files) && Object.values(m.gate_files).every((h) => typeof h === 'string' && /^[0-9a-f]{64}$/.test(h)))))
962
+ return `${markerRel} isn't the note lode init writes, so nothing was changed. Nothing was written.`;
963
+ marker = m;
964
+ }
908
965
  const settingsRel = remove && ALLOWED_SETTINGS.includes(marker.gate?.file) ? marker.gate.file : ALLOWED_SETTINGS[shared ? 1 : 0];
909
966
  const settingsFile = path.join(cwd, settingsRel);
910
967
  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.`; }
968
+ let cur = {};
969
+ const sr = gateReadText(fs, settingsFile);
970
+ if (sr.bad) return `${settingsRel}: ${sr.bad} Nothing was written.`;
971
+ const text = sr.text;
913
972
  if (text != null) {
914
- try { cur = JSON.parse(text); } catch { cur = undefined; }
973
+ try { cur = JSON.parse(text); if (!gateLossless(text)) cur = undefined; } catch { cur = undefined; }
915
974
  const pre = cur?.hooks?.PreToolUse;
916
975
  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
976
  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.`;
@@ -919,7 +978,8 @@ async function gateInit({ yes = false, remove = false, mode = 'warn', shared = f
919
978
  const indent = (text?.match(/\n([ \t]+)"/) || [])[1] || 2;
920
979
  const pre = cur.hooks?.PreToolUse ?? [];
921
980
  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)));
981
+ // Only Lode's own hook entry, never an entry named by the note (security review 02-12-2026)
982
+ const present = pre.findIndex(gateIsHook);
923
983
  const skillRel = path.join('.claude', 'skills', 'lode-integration-check');
924
984
  const skillDst = path.join(cwd, skillRel), skillSrc = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '..');
925
985
  const GATE_FILES = GATE_FILES_LIST.map((f) => f.split('/').join(path.sep));
@@ -929,20 +989,35 @@ async function gateInit({ yes = false, remove = false, mode = 'warn', shared = f
929
989
  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
990
  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
991
  }
992
+ // settings.local.json must stay out of git, or teammates get Gate without choosing it (security review 02-12-2026)
993
+ let ign = null;
994
+ if (!remove && settingsRel === ALLOWED_SETTINGS[0]) {
995
+ const ir = gateReadText(fs, ignoreFile);
996
+ if (ir.bad) return `${ignoreRel}: ${ir.bad} Nothing was written.`;
997
+ let git = false, gitRoot = null; for (let d = cwd; ; d = path.dirname(d)) { if (fs.existsSync(path.join(d, '.git'))) { git = true; gitRoot = d; break; } if (d === path.dirname(d)) break; }
998
+ const inRepo = gitRoot ? path.relative(gitRoot, settingsFile).split(path.sep).join('/') : null;
999
+ if (gitRoot && gateTracked(fs, path.join(gitRoot, '.git', 'index'), inRepo))
1000
+ return `${settingsRel} is already committed to git, so a hook added there would reach everyone who clones the project. To have Gate only for you, untrack it first (git rm --cached ${inRepo}). Nothing was written.`;
1001
+ const t = (ir.text ?? '').replace(/\r\n/g, '\n');
1002
+ ign = { text: ir.text, need: git && !t.endsWith(GATE_IGNORE_BLOCK) };
1003
+ }
1004
+ const ignOurs = marker.gate?.ignore;
932
1005
  const lines = [];
933
1006
  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.';
1007
+ if (present < 0 && !Object.keys(marker.gate_files ?? {}).length && !ignOurs) return 'Lode Gate is not set up here by lode init. Nothing to remove.';
935
1008
  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
1009
  if (Object.keys(marker.gate_files ?? {}).length) lines.push(` ${skillRel}/: delete the Gate files lode init copied, if unchanged`);
1010
+ if (ignOurs) lines.push(` ${ignoreRel}: remove the two lines lode init added, if they are still there${ignOurs.created ? '; delete the file if nothing else is left in it' : ''}`);
937
1011
  } 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)'}`);
1012
+ if (present >= 0) return `Lode Gate is already on in this project. Turn it off with: ${gateCmd(true)}`;
1013
+ 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 (kept out of git)'}`);
940
1014
  const missing = GATE_FILES.filter((f) => !fs.existsSync(path.join(skillDst, f)));
941
1015
  if (missing.length && path.resolve(skillSrc) !== path.resolve(skillDst)) lines.push(` ${skillRel}/: copy ${missing.join(', ')} (no dependencies, nothing runs on install)`);
1016
+ if (ign?.need) lines.push(` ${ignoreRel}: ${ign.text == null ? 'create it with' : 'add at the end'} two lines (a comment and ${GATE_IGNORE_LINE}), so git never picks up this hook for teammates`);
942
1017
  lines.push(` ${markerRel}: a small note of what lode init added, so --remove undoes only that`);
943
1018
  }
944
1019
  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`;
1020
+ 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: ${src === 'setup' ? gateCmd(remove) : `node lode.mjs init --gate${remove ? ' --remove' : ''}${!remove && mode === 'ask' ? ' --mode ask' : ''}${!remove && shared ? ' --shared' : ''} --yes`}`;
946
1021
  if (remove) {
947
1022
  if (present >= 0) {
948
1023
  const next = { ...cur, hooks: { ...cur.hooks, PreToolUse: pre.filter((_, i) => i !== present) } };
@@ -958,6 +1033,12 @@ async function gateInit({ yes = false, remove = false, mode = 'warn', shared = f
958
1033
  try { if (fs.lstatSync(f).isFile() && hash(f) === h) fs.rmSync(f); } catch { /* gone */ }
959
1034
  }
960
1035
  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 */ } }
1036
+ if (ignOurs) {
1037
+ const ir = gateReadText(fs, ignoreFile);
1038
+ const t = ir.text ?? '';
1039
+ const i = t.lastIndexOf(GATE_IGNORE_BLOCK);
1040
+ if (!ir.bad && i >= 0 && (i === 0 || t[i - 1] === '\n')) { const rest = t.slice(0, i) + t.slice(i + GATE_IGNORE_BLOCK.length); if (ignOurs.created && rest === '') fs.rmSync(ignoreFile); else fs.writeFileSync(ignoreFile, rest); }
1041
+ }
961
1042
  delete marker.gate; delete marker.gate_files;
962
1043
  } else {
963
1044
  const entry = GATE_HOOK(mode);
@@ -968,6 +1049,11 @@ async function gateInit({ yes = false, remove = false, mode = 'warn', shared = f
968
1049
  for (const k of Object.keys(cur)) if (k !== 'hooks' && !same(back[k], cur[k])) throw new Error(`${settingsRel} changed unexpectedly`);
969
1050
  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
1051
  marker.gate = { file: settingsRel, created: text == null, entry };
1052
+ if (ign?.need) {
1053
+ const t = ign.text ?? '';
1054
+ fs.writeFileSync(ignoreFile, `${t}${t && !t.endsWith('\n') ? '\n' : ''}${GATE_IGNORE_BLOCK}`);
1055
+ marker.gate.ignore = { line: GATE_IGNORE_LINE, created: ign.text == null };
1056
+ }
971
1057
  marker.gate_files = marker.gate_files ?? {};
972
1058
  if (path.resolve(skillSrc) !== path.resolve(skillDst)) for (const rel of GATE_FILES) {
973
1059
  const from = path.join(skillSrc, rel), to = path.join(skillDst, rel);
@@ -981,7 +1067,7 @@ async function gateInit({ yes = false, remove = false, mode = 'warn', shared = f
981
1067
  const keep = (marker.added ?? []).length || Object.keys(marker.skill_files ?? {}).length || marker.gate;
982
1068
  if (keep) { fs.mkdirSync(path.dirname(markerFile), { recursive: true }); fs.writeFileSync(markerFile, JSON.stringify(marker, null, 2) + '\n'); }
983
1069
  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.`;
1070
+ 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: ${gateCmd(true)}\n`}Nothing was sent to Lode.`;
985
1071
  }
986
1072
 
987
1073
  // lode init (Paul approved 27-11-2026): put Lode in the project's own config so teammates and sub-agents have it.
@@ -1009,7 +1095,7 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1009
1095
  // The command the user or agent should run next: npx trylode's own when called through it (security review
1010
1096
  // 01-12-2026: a project has no lode.mjs, so pointing an agent at it failed or wrote the untagged address).
1011
1097
  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 });
1098
+ if (gate) return gateInit({ yes, remove, mode: gateMode, shared: gateShared, src });
1013
1099
  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
1100
  const cwd = fs.realpathSync(process.cwd());
1015
1101
  // Only inside a project: never the home folder or the root, and only where a project marker exists (security review 27-11-2026)
@@ -1236,6 +1322,125 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1236
1322
  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
1323
  }
1238
1324
 
1325
+ // D93 stack watch (LOD-239). `watch --share` asks Lode to watch the integrations kept in lode-integrations.json under a
1326
+ // fresh random watch code (the file's own project code only with --project-code, an explicit opt-in: that code can
1327
+ // appear in committed decision records). Lode returns a secret watch token once; it is kept in .lode/watch.json (mode
1328
+ // 0600), and `.lode/` is added to an existing .gitignore (one appended line; a missing .gitignore is never created).
1329
+ // `watch changes` reads what changed in Lode for exactly those records since the watch began; `watch stop` deletes the
1330
+ // watch at Lode and the local token file. Nothing is sent without --share, except `changes` and `stop`, which send only
1331
+ // the code and the token. Every file read here is untrusted input: links, non-regular or oversized files and anything
1332
+ // not in the expected shape are refused, never followed.
1333
+ export const WATCH_DIR = '.lode';
1334
+ export const WATCH_FILE = '.lode/watch.json';
1335
+ export const WATCH_PROJECT = /^[0-9a-f]{16,32}$/;
1336
+ export const WATCH_TOKEN = /^lws_[0-9a-f]{48}$/;
1337
+ const WATCH_ID = /^[a-z0-9][a-z0-9-]{0,80}--[a-z0-9][a-z0-9-]{0,40}$/;
1338
+ // Read a small project file without following links. { text } | { missing } | { bad: reason }
1339
+ export function readProjectFile(name, { cwd = process.cwd(), max = 1024 * 1024 } = {}) {
1340
+ const f = join(cwd, name);
1341
+ if (viaLink(f, cwd)) return { bad: `${name} is a link or sits under one, so the Lode skill won't read it` };
1342
+ let st; try { st = lstatSync(f); } catch (e) { return e.code === 'ENOENT' ? { missing: true } : { bad: `${name} can't be read (${e.code})` }; }
1343
+ if (!st.isFile()) return { bad: `${name} is not a regular file` };
1344
+ if (st.size > max) return { bad: `${name} is larger than expected` };
1345
+ let fd; try { fd = openSync(f, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0)); } catch (e) { return { bad: `${name} can't be read (${e.code})` }; }
1346
+ try {
1347
+ const s2 = fstatSync(fd);
1348
+ if (!s2.isFile() || s2.ino !== st.ino || s2.dev !== st.dev || s2.size > max) return { bad: `${name} changed while being read` };
1349
+ return { text: readFileSync(fd, 'utf8') };
1350
+ } catch (e) { return { bad: `${name} can't be read (${e.code})` }; } finally { closeSync(fd); }
1351
+ }
1352
+ // The watch token file: exactly { version: 1, project, watch_token } with both in their fixed formats, else refused.
1353
+ export function readWatchFile(cwd = process.cwd()) {
1354
+ const r = readProjectFile(WATCH_FILE, { cwd, max: 4096 });
1355
+ if (r.missing || r.bad) return r;
1356
+ let j; try { j = JSON.parse(r.text); } catch { return { bad: `${WATCH_FILE} is not valid JSON; remove it to start again` }; }
1357
+ if (!j || typeof j !== 'object' || Array.isArray(j) || !WATCH_PROJECT.test(j.project ?? '') || !WATCH_TOKEN.test(j.watch_token ?? '')) return { bad: `${WATCH_FILE} is not in the expected format; remove it to start again` };
1358
+ return { watch: { project: j.project, watch_token: j.watch_token } };
1359
+ }
1360
+ // The ids to watch: integrations still kept in lode-integrations.json, Lode-id shaped only, at most 50.
1361
+ export function watchIdsFrom(f) {
1362
+ if (!f || typeof f !== 'object' || !Array.isArray(f.integrations)) return [];
1363
+ return [...new Set(f.integrations.filter((x) => x && x.state === 'kept' && typeof x.id === 'string' && WATCH_ID.test(x.id)).map((x) => x.id))].sort().slice(0, 50);
1364
+ }
1365
+ async function watchPost(path, body) {
1366
+ const res = await fetch(`${BASE}${path}`, { method: 'POST', redirect: 'error', headers: { 'user-agent': UA, 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(body) });
1367
+ const json = await res.json().catch(() => ({}));
1368
+ if (res.status >= 500 || res.status === 429 || res.status === 401) throw new Error(`Lode answered HTTP ${res.status} for ${path}`);
1369
+ return { status: res.status, json };
1370
+ }
1371
+ // Write the token file with mode 0600 inside .lode/ (made if missing), never through a link.
1372
+ export async function writeWatchFile(w, cwd = process.cwd()) {
1373
+ const fs = await import('node:fs');
1374
+ const dir = join(cwd, WATCH_DIR), f = join(cwd, WATCH_FILE);
1375
+ if (viaLink(f, cwd)) throw new Error(`${WATCH_FILE} is a link or sits under one, so the Lode skill won't write there`);
1376
+ let st; try { st = fs.lstatSync(dir); } catch { st = null; }
1377
+ if (st && !st.isDirectory()) throw new Error(`${WATCH_DIR} is not a folder`);
1378
+ if (!st) fs.mkdirSync(dir, { mode: 0o700 });
1379
+ const fd = fs.openSync(f, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
1380
+ try {
1381
+ if (!fs.fstatSync(fd).isFile()) throw new Error(`${WATCH_FILE} is not a regular file`);
1382
+ fs.fchmodSync(fd, 0o600);
1383
+ fs.writeSync(fd, JSON.stringify({ version: 1, project: w.project, watch_token: w.watch_token }, null, 2) + '\n');
1384
+ } finally { fs.closeSync(fd); }
1385
+ }
1386
+ // Add `.lode/` to .gitignore only when one already exists (one appended line); never create it, never follow a link.
1387
+ export async function ignoreWatchDir(cwd = process.cwd()) {
1388
+ const r = readProjectFile('.gitignore', { cwd });
1389
+ if (r.missing) return `There is no .gitignore here: keep ${WATCH_DIR}/ out of version control yourself (it holds the secret token).`;
1390
+ if (r.bad) return `${r.bad}; it was left alone. Keep ${WATCH_DIR}/ out of version control yourself.`;
1391
+ if (r.text.split(/\r?\n/).some((l) => /^\/?\.lode\/?$/.test(l.trim()))) return `${WATCH_DIR}/ is already in .gitignore.`;
1392
+ const fs = await import('node:fs');
1393
+ const fd = fs.openSync(join(cwd, '.gitignore'), fs.constants.O_WRONLY | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0));
1394
+ try { fs.writeSync(fd, `${r.text && !/\n$/.test(r.text) ? '\n' : ''}${WATCH_DIR}/\n`); } finally { fs.closeSync(fd); }
1395
+ return `Added ${WATCH_DIR}/ to .gitignore so the token stays out of version control.`;
1396
+ }
1397
+
1398
+ async function watchCmd(sub, { share, projectCode, since } = {}) {
1399
+ const cwd = process.cwd();
1400
+ const wf = readWatchFile(cwd);
1401
+ if (wf.bad) return `${wf.bad}. Nothing was sent to Lode.`;
1402
+ if (sub === 'changes') {
1403
+ if (!wf.watch) return `No watch in this folder (${WATCH_FILE} not found). Start one with: node lode.mjs watch --share (only if the user agrees).`;
1404
+ const { status, json } = await watchPost('/v1/watch/changes', { ...wf.watch, ...(typeof since === 'string' ? { since } : {}) });
1405
+ if (status !== 200) return `Lode did not return changes${json.message ? `: ${json.message}` : ''}.`;
1406
+ const lines = [`## Changes in Lode for ${json.watching?.length ?? 0} watched integration(s) since ${String(json.since ?? '').slice(0, 10)}`];
1407
+ for (const c of json.changes ?? []) lines.push(`- ${c.title} (${String(c.observed_at ?? '').slice(0, 10)})${c.fact ? `: ${c.fact}` : ''}${c.url ? ` | ${c.url}` : ''}`);
1408
+ if (!(json.changes ?? []).length) lines.push('No changes recorded for these records since the watch began.');
1409
+ lines.push('', 'Facts from Lode\'s change history only. Anything Lode does not record is "not documented".');
1410
+ return lines.join('\n');
1411
+ }
1412
+ if (sub === 'stop') {
1413
+ if (!wf.watch) return `No watch in this folder (${WATCH_FILE} not found). Nothing was sent to Lode.`;
1414
+ const { status, json } = await watchPost('/v1/watch', { action: 'unsubscribe', ...wf.watch });
1415
+ if (status !== 200) return `Lode did not stop the watch${json.message ? `: ${json.message}` : ''}. ${WATCH_FILE} was left in place.`;
1416
+ try { if (!viaLink(join(cwd, WATCH_FILE), cwd) && lstatSync(join(cwd, WATCH_FILE)).isFile()) (await import('node:fs')).rmSync(join(cwd, WATCH_FILE)); } catch { /* already gone */ }
1417
+ return `Stopped: Lode deleted the watch and its list of integrations, and ${WATCH_FILE} was removed.`;
1418
+ }
1419
+ // start or update the watch
1420
+ const lr = readProjectFile(LOCAL_FILE, { cwd });
1421
+ if (lr.bad) return `${lr.bad}. Nothing was sent to Lode.`;
1422
+ if (lr.missing) return `No ${LOCAL_FILE} in this folder, so there is nothing to watch. Record a choice first: node lode.mjs chose <app> <platform>`;
1423
+ let f; try { f = JSON.parse(lr.text); } catch { return `${LOCAL_FILE} is not valid JSON; fix or remove it. Nothing was sent to Lode.`; }
1424
+ const ids = watchIdsFrom(f);
1425
+ if (!ids.length) return `No kept integrations with Lode ids in ${LOCAL_FILE}. Nothing was sent to Lode.`;
1426
+ // A fresh random code made by Lode by default; the file's own project code only with --project-code
1427
+ if (!wf.watch && projectCode && !WATCH_PROJECT.test(f.project ?? '')) return `The project code in ${LOCAL_FILE} is not a 16 to 32 character hex code; run without --project-code to use a fresh random one. Nothing was sent to Lode.`;
1428
+ const codeNote = wf.watch ? `the watch code in ${WATCH_FILE}` : projectCode ? `the project code in ${LOCAL_FILE}` : 'a fresh random watch code';
1429
+ if (share !== true) return `Not sent to Lode. With the user's agreement, run this again with --share and Lode will watch these ${ids.length} integration(s) under ${codeNote}, keeping only that list until you stop it:\n${ids.map((x) => `- ${x}`).join('\n')}`;
1430
+ const body = wf.watch ? { action: 'update', ...wf.watch, ids } : { action: 'subscribe', ...(projectCode ? { project: f.project } : {}), ids };
1431
+ const { status, json } = await watchPost('/v1/watch', body);
1432
+ if (status === 404 && !wf.watch) return `Lode could not start a watch under that code. Run again with --share and without --project-code to use a fresh random code. Nothing else was sent.`;
1433
+ if (status === 409) return 'Lode could not make a new watch code this time; run the command again.';
1434
+ if (status !== 200 && status !== 201) return `Lode did not record the watch${json.message ? `: ${json.message}` : ''}.`;
1435
+ let ignored = '';
1436
+ if (status === 201) {
1437
+ if (!WATCH_TOKEN.test(json.watch_token ?? '') || !WATCH_PROJECT.test(json.project ?? '')) return 'Lode\'s answer was not in the expected format; nothing was saved.';
1438
+ try { await writeWatchFile({ project: json.project, watch_token: json.watch_token }, cwd); } catch (e) { return `Lode started the watch but ${WATCH_FILE} could not be written (${e.message}). Stop it later with the watch code ${json.project}.`; }
1439
+ try { ignored = ` ${await ignoreWatchDir(cwd)}`; } catch (e) { ignored = ` .gitignore could not be updated (${e.message}); keep ${WATCH_DIR}/ out of version control yourself.`; }
1440
+ }
1441
+ return `${status === 201 ? 'Watching' : 'Updated the watch on'} ${json.ids?.length ?? ids.length} integration(s) (the user agreed). Lode keeps only that list until you stop it.${status === 201 ? ` The secret token is in ${WATCH_FILE} (readable only by you).${ignored}` : ''}\nLater, run: node lode.mjs watch changes (stop with: node lode.mjs watch stop)`;
1442
+ }
1443
+
1239
1444
  export async function main(argv) {
1240
1445
  const [cmd, ...rest] = argv;
1241
1446
  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; };
@@ -1330,8 +1535,13 @@ export async function main(argv) {
1330
1535
  const client = ['claude', 'cursor', 'all'].includes(opts.client) ? opts.client : 'all';
1331
1536
  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
1537
  }
1538
+ if (cmd === 'watch') {
1539
+ const opts = { share: flag('--share'), projectCode: flag('--project-code'), since: flag('--since') };
1540
+ const sub = ['changes', 'stop'].includes(rest[0]) ? rest[0] : 'start';
1541
+ return watchCmd(sub, { share: opts.share === true, projectCode: opts.projectCode === true, since: opts.since });
1542
+ }
1333
1543
  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';
1544
+ 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 watch [--share] [--project-code] | watch changes [--since d] | watch stop\n node lode.mjs platforms';
1335
1545
  }
1336
1546
 
1337
1547
  // Run only when this very file is the entry point (security review 01-12-2026: endsWith('lode.mjs') also matched trylode.mjs).