trylode 0.4.2 → 0.5.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
@@ -6,13 +6,17 @@
6
6
 
7
7
  - `.mcp.json`: one `"lode"` server entry, `https://trylode.io/mcp?src=setup`. Other entries are unchanged.
8
8
  - `.cursor/mcp.json`: the same entry for Grok Build (formerly Cursor).
9
- - `CLAUDE.md` and `AGENTS.md` (each created if missing; `AGENTS.md` left out with `--no-agents-md`): one marked block with the Lode rules line, added at the end. Nothing else in the file changes.
9
+ - `.vscode/mcp.json`: the same entry for VS Code (under `"servers"`). VS Code's Copilot reads the `.mcp.json` entry above.
10
+ - `.gemini/settings.json`: the same entry for Gemini CLI (as `"httpUrl"`). Other settings are unchanged.
11
+ - `.codex/config.toml`: one marked `[mcp_servers.lode]` block with the same address, added at the end, for Codex. Codex reads this file only in a project you have marked trusted. Setup doesn't parse TOML, so it adds the block only when every other mention of `mcp_servers` is a plain `[mcp_servers.<name>]` header for another server and the file has no arrays of tables, `\u` escapes, unclosed multi-line strings or `lode` key; otherwise the file is left alone and setup prints the lines to add by hand. `remove` takes the block out only if setup recorded adding it and nothing was added under it.
12
+ - `CLAUDE.md`, `AGENTS.md` and `GEMINI.md` (each created if missing; `AGENTS.md` left out with `--no-agents-md`): one marked block with the Lode rules line, added at the end. Nothing else in the file changes. Codex and Copilot read `AGENTS.md`; Gemini CLI reads `GEMINI.md`.
10
13
  - `.cursor/rules/lode.mdc`: the rules line as a Grok Build (formerly Cursor) rule.
14
+ - Only with `--no-agents-md`: the rules line in `.github/copilot-instructions.md` (for Copilot), since Copilot would otherwise not get it.
11
15
  - `.grok/rules/lode.md`: the same rules line for Grok Build's terminal app, only when it won't be in `AGENTS.md` (with `--client cursor`, or `--no-agents-md` and no `AGENTS.md`).
12
16
  - `.claude/skills/lode-integration-check/`: a copy of the Lode Integration Check skill.
13
17
  - `.claude/lode-init.json`: a note of what was added, so `remove` can undo exactly that.
14
18
 
15
- `--no-rules` leaves the rules line out. `--client claude` or `--client cursor` writes for one client only.
19
+ `--no-rules` leaves the rules line out (the server entries are still written). `--client` writes for one client only: `claude` writes `.mcp.json`, `CLAUDE.md` and `AGENTS.md`; `cursor` writes `.cursor/mcp.json`, `.cursor/rules/lode.mdc` and `.grok/rules/lode.md`; `--client vscode` writes `.mcp.json`, `.vscode/mcp.json` and `AGENTS.md` (`.github/copilot-instructions.md` instead with `--no-agents-md`); `--client gemini` writes `.gemini/settings.json` and `GEMINI.md`; `--client codex` writes `.codex/config.toml` and `AGENTS.md`. Each also copies the skill and writes the note. Lode Gate and the other hooks are added only with `--client claude` or no `--client`.
16
20
 
17
21
  ### Only with `--gate` (Lode Gate, Claude Code only, off unless you add it)
18
22
 
@@ -46,4 +50,4 @@ Setup and remove make no network requests. The `?src=setup` code in the server a
46
50
 
47
51
  ## Removes
48
52
 
49
- `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.
53
+ `npx trylode remove --yes` takes out only the entries, blocks, rule files, 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
@@ -9,8 +9,8 @@ npx trylode setup --yes # adds it
9
9
 
10
10
  It adds:
11
11
 
12
- 1. **Lode's MCP server** to `.mcp.json` (Claude Code) and `.cursor/mcp.json` (Grok Build, formerly Cursor). Hosted, no sign-in or API key.
13
- 2. **The rules line** to `CLAUDE.md`, `AGENTS.md` (each created if missing; `--no-agents-md` leaves `AGENTS.md` out) and `.cursor/rules/lode.mdc` (plus `.grok/rules/lode.md` for Grok Build's terminal app when the line won't be in `AGENTS.md`). This is the step that matters most: agents reliably use a tool their instructions file tells them about.
12
+ 1. **Lode's MCP server** to `.mcp.json` (Claude Code and VS Code's Copilot), `.cursor/mcp.json` (Grok Build, formerly Cursor), `.vscode/mcp.json` (VS Code), `.gemini/settings.json` (Gemini CLI) and `.codex/config.toml` (Codex, in a trusted project). Hosted, no sign-in or API key.
13
+ 2. **The rules line** to `CLAUDE.md`, `AGENTS.md` (read by Codex and Copilot), `GEMINI.md` (each created if missing; `--no-agents-md` leaves `AGENTS.md` out) and `.cursor/rules/lode.mdc` (plus `.grok/rules/lode.md` for Grok Build's terminal app when the line won't be in `AGENTS.md`). 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
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.
package/bin/cli.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // npx trylode setup (LOD-248, Paul approved 01-12-2026): puts Lode into this project for the coding agents that read it.
3
3
  // It is the Lode Integration Check skill's reviewed `init`, packaged: it writes Lode's MCP server (address tagged
4
- // ?src=setup), the rules line (CLAUDE.md, AGENTS.md, .cursor/rules/lode.mdc) and the skill, shows the plan
4
+ // ?src=setup) for Claude Code, Grok Build (formerly Cursor), VS Code/Copilot, Gemini CLI and Codex (LOD-306), the rules
5
+ // line (CLAUDE.md, AGENTS.md, GEMINI.md, .cursor/rules/lode.mdc) and the skill, shows the plan
5
6
  // first and writes only with --yes. It sends nothing to Lode. `npx trylode remove --yes` undoes only what it added.
6
7
  // With --gate (LOD-262) it also runs the skill's reviewed `init --gate` (warn mode, .claude/settings.local.json only).
7
8
  // With --verify it runs `init --verify` the same way (the Stop hook). `npx trylode verify` runs the check itself: in CI,
@@ -9,12 +10,13 @@
9
10
  // No dependencies, no install scripts. See PERMISSIONS.md.
10
11
 
11
12
  const USAGE = `Usage:
12
- npx trylode setup [--yes] [--client claude|cursor|all] [--no-rules] [--no-agents-md] [--gate] [--triage] [--verify]
13
+ npx trylode setup [--yes] [--client claude|cursor|vscode|gemini|codex|all] [--no-rules] [--no-agents-md] [--gate] [--triage] [--verify]
13
14
  Shows what it would add to this project, and adds it with --yes:
14
- .mcp.json and .cursor/mcp.json: one "lode" server entry (other entries unchanged)
15
- CLAUDE.md, AGENTS.md, .cursor/rules/lode.mdc: the Lode rules line (each created if missing;
16
- --no-agents-md leaves AGENTS.md out); .grok/rules/lode.md for Grok Build's terminal app
17
- when the line won't be in AGENTS.md
15
+ .mcp.json, .cursor/mcp.json, .vscode/mcp.json, .gemini/settings.json: one "lode" server entry
16
+ (other entries unchanged); .codex/config.toml: one [mcp_servers.lode] block at the end
17
+ CLAUDE.md, AGENTS.md, GEMINI.md, .cursor/rules/lode.mdc: the Lode rules line (each created if missing;
18
+ --no-agents-md leaves AGENTS.md out and writes .github/copilot-instructions.md instead);
19
+ .grok/rules/lode.md for Grok Build's terminal app when the line won't be in AGENTS.md
18
20
  .claude/skills/lode-integration-check/: the Lode Integration Check skill
19
21
  --gate Also enables Lode Gate for Claude Code in .claude/settings.local.json (user-local, not shared).
20
22
  Injects Lode's facts into the agent's context before installing a known package; never blocks.
@@ -40,6 +42,9 @@ Setup and remove send nothing to Lode. What Lode Gate sends when it runs: PERMIS
40
42
  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';
41
43
  // LOD-287 (Paul approved the wording 03-12-2026): the one line setup adds when the verify hook is not on.
42
44
  const VERIFY_OFFER = 'Optional for Claude Code: Lode verify checks this project\'s integrations against Lode\'s facts before the agent says it is done, and stops it once for each new finding. Enable with: npx trylode setup --verify --yes';
45
+ // LOD-307 (Paul approved the wording 04-12-2026, plain address): adds Lode as a claude.ai connector for Claude chat and
46
+ // desktop. Printed only; setup never runs it (it signs in to the user's claude.ai account).
47
+ const CONNECTOR_OFFER = 'To use Lode in Claude chat and desktop, run: claude mcp add --web lode https://trylode.io/mcp';
43
48
 
44
49
  const argv = process.argv.slice(2);
45
50
  const cmd = argv[0];
@@ -53,8 +58,10 @@ for (let i = 1; i < argv.length; i++) {
53
58
  else if (a === '--gate') gate = true;
54
59
  else if (a === '--triage') triage = true;
55
60
  else if (a === '--verify') verify = true;
56
- else if (a === '--client' && ['claude', 'cursor', 'all'].includes(argv[i + 1])) { client = argv[i + 1]; flags.push(a, argv[i + 1]); i++; }
61
+ else if (a === '--client' && ['claude', 'cursor', 'vscode', 'gemini', 'codex', 'all'].includes(argv[i + 1])) { client = argv[i + 1]; i++; }
57
62
  }
63
+ // Only the --client kept here is passed on, so the files and the hooks always follow the same client (review 04-12-2026)
64
+ if (client !== 'all') flags.push('--client', client);
58
65
  const yes = flags.includes('--yes') ? ['--yes'] : [];
59
66
  // A refusal (nothing changed because a file looked wrong) exits 2, so a script calling setup notices.
60
67
  const OK = /^(Done|Removed):|would (change|write) these files|already set up|already on in this project|Nothing to remove/;
@@ -65,16 +72,16 @@ async function steps() {
65
72
  if (cmd === 'setup') {
66
73
  const first = await run(['init', '--src', 'setup', ...flags]);
67
74
  if (!OK.test(first)) return { out: [first], ok: false };
68
- if (client === 'cursor') return { out: [first, ...(gate || triage || verify ? ['Lode Gate, the failure hook and the verify hook are for Claude Code only, so they were ignored with --client cursor.'] : [])], ok: true };
75
+ if (client !== 'claude' && client !== 'all') return { out: [first, ...(gate || triage || verify ? [`Lode Gate, the failure hook and the verify hook are for Claude Code only, so they were ignored with --client ${client}.`] : [])], ok: true };
69
76
  if (gate || triage || verify) {
70
77
  const out = [first]; let ok = true;
71
78
  for (const [on, f] of [[gate, '--gate'], [triage, '--triage'], [verify, '--verify']]) if (on) { const g = await run(['init', f, '--src', 'setup', ...yes]); out.push(g); ok = ok && OK.test(g); }
72
- return { out, ok };
79
+ return { out: [...out, CONNECTOR_OFFER], ok };
73
80
  }
74
81
  // Offer Gate and verify only when they aren't on yet (dry runs of the reviewed check; they write nothing)
75
82
  const dry = await run(['init', '--gate', '--src', 'setup']);
76
83
  const dryVerify = await run(['init', '--verify', '--src', 'setup']);
77
- return { out: [first, ...(/already on in this project/.test(dry) ? [] : [GATE_OFFER]), ...(/already on in this project/.test(dryVerify) ? [] : [VERIFY_OFFER])], ok: true };
84
+ return { out: [first, ...(/already on in this project/.test(dry) ? [] : [GATE_OFFER]), ...(/already on in this project/.test(dryVerify) ? [] : [VERIFY_OFFER]), CONNECTOR_OFFER], ok: true };
78
85
  }
79
86
  if (cmd === 'remove') {
80
87
  // Each hook first (only the ones that are on are reported), then the rest unless only hooks were named
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trylode",
3
- "version": "0.4.2",
3
+ "version": "0.5.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" },
@@ -9,5 +9,5 @@
9
9
  "license": "MIT",
10
10
  "homepage": "https://trylode.io/agents/",
11
11
  "repository": { "type": "git", "url": "git+https://github.com/lode-hq/lode-mcp.git", "directory": "npm/trylode" },
12
- "keywords": ["lode", "mcp", "agents", "claude-code", "cursor", "integrations", "agents-md"]
12
+ "keywords": ["lode", "mcp", "agents", "claude-code", "cursor", "integrations", "agents-md", "codex", "gemini-cli", "copilot", "vscode"]
13
13
  }
@@ -16,7 +16,7 @@ secrets. Privacy policy: https://trylode.io/privacy/
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
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 |
19
- | `init` | `.mcp.json`, `.cursor/mcp.json`, `.claude/lode-init.json`, `CLAUDE.md`, `AGENTS.md`, `.cursor/rules/lode.mdc`, `.grok/rules/lode.md` | 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` and `AGENTS.md` (each created if missing; `AGENTS.md` left out with `--no-agents-md`) and as `.cursor/rules/lode.mdc` (left out with `--no-rules`), and as `.grok/rules/lode.md` for Grok Build's terminal app only when the line won't be in `AGENTS.md` (with `--client cursor`, or `--no-agents-md` and no `AGENTS.md`), 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` | `.mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`, `.gemini/settings.json`, `.codex/config.toml`, `.claude/lode-init.json`, `CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, `.cursor/rules/lode.mdc`, `.grok/rules/lode.md` (only when the rules line won't be in `AGENTS.md`), and with `--no-agents-md` `.github/copilot-instructions.md` | nothing | only with `--yes`, only inside a project folder and never through links: one `lode` entry in those MCP files (`--client claude`, `cursor`, `vscode`, `gemini` or `codex` picks one client; in `.codex/config.toml` it is one marked `[mcp_servers.lode]` block added at the end, and a file that already names a `lode` server or has an inline `mcp_servers` table is left alone), a copy of this skill in `.claude/skills/`, the Lode rules line as one marked block at the end of `CLAUDE.md`, `AGENTS.md` and `GEMINI.md` (each created if missing; `AGENTS.md` left out with `--no-agents-md`, which writes the line to `.github/copilot-instructions.md` instead; `.grok/rules/lode.md` gets it whenever it won't be in `AGENTS.md`, and is removed only if unchanged and the note says init created it) 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 |
20
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 |
21
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) |
22
22
  | `init --triage` (the failure hook, opt-in) | the same files as `init --gate`, for the failure hook's own entry | nothing | only with `--yes`, under the same rules as `init --gate`: one `PostToolUseFailure` hook entry in `.claude/settings.local.json` (or `.claude/settings.json` with `--shared`), `failure-hook.mjs` and `failure-signals.json` copied with this skill, the same `.claude/.gitignore` lines and a note in `.claude/lode-init.json`; `init --triage --remove --yes` undoes only that |
@@ -25,7 +25,7 @@
25
25
  // why an integration fails: Lode's sourced facts for that kind of failure
26
26
  // node lode.mjs watch [--share] [--project-code] ask Lode to watch the kept integrations in lode-integrations.json (only with --share)
27
27
  // node lode.mjs watch changes [--since d] what changed in Lode for the watched integrations; watch stop deletes the watch
28
- // node lode.mjs init [--client claude|cursor|all] [--yes] [--remove]
28
+ // node lode.mjs init [--client claude|cursor|vscode|gemini|codex|all] [--yes] [--remove]
29
29
  // add Lode to this project so every teammate and sub-agent has it (shows the files first)
30
30
  //
31
31
  // What Lode receives: the app, platform and options in each request (for find and request: the needs,
@@ -900,6 +900,50 @@ const GATE_FILES_LIST = ['SKILL.md', 'PERMISSIONS.md', 'scripts/lode.mjs', 'scri
900
900
  // Security review 02-12-2026 (LOD-262): every project file gateInit reads is untrusted, so it is read the way init reads
901
901
  // (readSafe): a regular file with one name, at most 1 MB, opened without following a link or blocking (a FIFO or a
902
902
  // link to /dev/zero used to hang remove), checked again once open. { text } | { text: null } when absent | { bad }.
903
+ // Security review 04-12-2026 (LOD-306, finding 6): setup's JSON files and its note are written without ever following a
904
+ // link. Each folder on the way is made one level at a time and must be a plain folder; a new file is created with O_EXCL
905
+ // and O_NOFOLLOW, an existing one is opened with O_NOFOLLOW and must still be the very file that was read (same inode,
906
+ // one name); and after opening, the folder must still resolve to the same place inside the project, so a folder swapped
907
+ // for a link between the check and the write is caught before anything is written. Re-review 04-12-2026: the opened file
908
+ // must also still be the one at that name (same device and inode), so a swap there and back is caught too; on any doubt
909
+ // the file is emptied through its own descriptor and removed only if the name still points at that very file (never an
910
+ // unlink that could follow a new link). On Linux the opened file's real path comes from the kernel (/proc/self/fd), so
911
+ // Lode's text is written only into a file inside the project. Residual, accepted (Node has no openat): a same-user
912
+ // process racing setup can still leave an empty file outside the project (created, then emptied), and, outside Linux
913
+ // only, one that swaps a folder several times between single system calls could get the text written outside. It can
914
+ // never truncate or overwrite a file that already existed (O_EXCL, and the inode check for existing files).
915
+ export function writeInProject(fs, path, cwd, rel, text, st = null) {
916
+ const dirs = rel.split(/[\\/]/).slice(0, -1);
917
+ let d = cwd;
918
+ for (const part of dirs) {
919
+ d = path.join(d, part);
920
+ let s; try { s = fs.lstatSync(d); } catch { fs.mkdirSync(d); s = fs.lstatSync(d); }
921
+ if (s.isSymbolicLink() || !s.isDirectory()) throw new Error(`${rel}: a folder on its path is a link or not a folder`);
922
+ }
923
+ const f = path.join(cwd, rel), C = fs.constants, NF = C.O_NOFOLLOW ?? 0;
924
+ const fd = st ? fs.openSync(f, C.O_WRONLY | NF | (C.O_NONBLOCK ?? 0)) : fs.openSync(f, C.O_WRONLY | C.O_CREAT | C.O_EXCL | NF, 0o644);
925
+ let s, moved = false;
926
+ try {
927
+ s = fs.fstatSync(fd);
928
+ if (!s.isFile() || s.nlink > 1 || (st && (s.ino !== st.ino || s.dev !== st.dev))) throw new Error(`${rel} changed while init ran`);
929
+ // Where the opened file really is. On Linux the kernel says so (/proc/self/fd), which no later swap can change.
930
+ // Elsewhere: the folder must resolve inside the project both before and after the name is checked against the file.
931
+ const inside = () => fs.realpathSync(path.dirname(f)) === path.join(cwd, ...dirs);
932
+ const atName = () => { try { const n = fs.lstatSync(f); return n.isFile() && n.ino === s.ino && n.dev === s.dev; } catch { return false; } };
933
+ let kernel = null; try { kernel = fs.readlinkSync(`/proc/self/fd/${fd}`); } catch { /* not Linux */ }
934
+ const ok = kernel != null ? kernel === f && atName() : inside() && atName() && inside();
935
+ if (!ok) { moved = true; throw new Error(`${rel}: a folder on its path changed while init ran`); }
936
+ if (st) fs.ftruncateSync(fd, 0);
937
+ fs.writeSync(fd, text, 0);
938
+ } finally {
939
+ if (moved && !st) {
940
+ try { fs.ftruncateSync(fd, 0); } catch { /* nothing was written */ }
941
+ try { const n = fs.lstatSync(f); if (n.isFile() && n.ino === s.ino && n.dev === s.dev && n.nlink === 1) fs.unlinkSync(f); } catch { /* gone or not ours */ }
942
+ }
943
+ fs.closeSync(fd);
944
+ }
945
+ }
946
+ const markerSt = (fs, f) => { try { const s = fs.lstatSync(f); return s.isFile() ? s : null; } catch { return null; } };
903
947
  function gateReadText(fs, f) {
904
948
  let st; try { st = fs.lstatSync(f); } catch (e) { return e.code === 'ENOENT' ? { text: null } : { bad: `can't be read (${e.code}).` }; }
905
949
  if (!st.isFile()) return { bad: "not a plain file, so it won't be touched." };
@@ -1110,7 +1154,7 @@ async function gateInit({ yes = false, remove = false, mode = 'warn', shared = f
1110
1154
  }
1111
1155
  }
1112
1156
  const keep = (marker.added ?? []).length || Object.keys(marker.skill_files ?? {}).length || Object.values(HOOK_KINDS).some((k) => marker[k.key] || Object.keys(marker[k.filesKey] ?? {}).length);
1113
- if (keep) { fs.mkdirSync(path.dirname(markerFile), { recursive: true }); fs.writeFileSync(markerFile, JSON.stringify(marker, null, 2) + '\n'); }
1157
+ if (keep) { writeInProject(fs, path, cwd, markerRel, JSON.stringify(marker, null, 2) + '\n', markerSt(fs, markerFile)); }
1114
1158
  else { try { fs.rmSync(markerFile); } catch { /* none */ } }
1115
1159
  return `${remove ? 'Removed' : 'Done'}:\n${lines.join('\n')}\n${remove ? '' : `${K.Name} is on for this project from the next Claude Code session. Turn it off with: ${gateCmd(true)}\n`}Nothing was sent to Lode.`;
1116
1160
  }
@@ -1135,6 +1179,10 @@ export const RULES_MDC = rulesMdc(RULE);
1135
1179
  // Every block and rule file a released init has written, newest first.
1136
1180
  export const KNOWN_BLOCKS = [RULES_BLOCK, rulesBlock(RULE_V1)];
1137
1181
  export const KNOWN_MDCS = [RULES_MDC, rulesMdc(RULE_V1)];
1182
+ // LOD-306: the Codex server block (.codex/config.toml), for either address init writes.
1183
+ export const codexBlock = (u) => `# lode:mcp (added by lode init; npx trylode remove --yes takes it out)\n[mcp_servers.lode]\nurl = "${u}"\n`;
1184
+ export const KNOWN_TOMLS = [SETUP_URL, LODE_URL].map(codexBlock);
1185
+ export const INIT_CLIENTS = ['claude', 'cursor', 'vscode', 'gemini', 'codex', 'all'];
1138
1186
  async function initCmd({ client = 'all', yes = false, remove = false, gate = false, triage = false, verify = false, gateMode = 'warn', gateShared = false, rules = true, agentsMd = true, src = null } = {}) {
1139
1187
  const serverUrl = src === 'setup' ? SETUP_URL : LODE_URL;
1140
1188
  // The command the user or agent should run next: npx trylode's own when called through it (security review
@@ -1187,9 +1235,16 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1187
1235
  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);
1188
1236
  return keyCount === count(JSON.parse(text));
1189
1237
  };
1238
+ // LOD-306 (Paul, 03-12-2026): VS Code/Copilot, Gemini CLI and Codex too. Each location and format is from the
1239
+ // client's own docs (docs/specs/trylode-more-agents.md): VS Code's Copilot harness reads the workspace-root .mcp.json
1240
+ // (mcpServers) and its older Local harness .vscode/mcp.json (servers); Gemini CLI reads .gemini/settings.json
1241
+ // (mcpServers, httpUrl for streamable HTTP); Codex reads .codex/config.toml in a trusted project (handled below).
1242
+ const on = (...c) => client === 'all' || c.includes(client);
1190
1243
  const targets = [];
1191
- 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 })) });
1192
- 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 })) });
1244
+ if (on('claude', 'vscode')) targets.push({ file: '.mcp.json', key: 'mcpServers', entry: { type: 'http', url: serverUrl }, alts: [LODE_URL, SETUP_URL].map((u) => ({ type: 'http', url: u })) });
1245
+ if (on('cursor')) targets.push({ file: path.join('.cursor', 'mcp.json'), key: 'mcpServers', entry: { url: serverUrl }, alts: [LODE_URL, SETUP_URL].map((u) => ({ url: u })) });
1246
+ if (on('vscode')) targets.push({ file: path.join('.vscode', 'mcp.json'), key: 'servers', entry: { type: 'http', url: serverUrl }, alts: [LODE_URL, SETUP_URL].map((u) => ({ type: 'http', url: u })) });
1247
+ if (on('gemini')) targets.push({ file: path.join('.gemini', 'settings.json'), key: 'mcpServers', entry: { httpUrl: serverUrl }, alts: [LODE_URL, SETUP_URL].map((u) => ({ httpUrl: u })) });
1193
1248
  const here = path.dirname(url.fileURLToPath(import.meta.url));
1194
1249
  const skillSrc = path.resolve(here, '..');
1195
1250
  const skillRel = path.join('.claude', 'skills', 'lode-integration-check');
@@ -1206,18 +1261,18 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1206
1261
  text = rd.text;
1207
1262
  if (text != null) {
1208
1263
  try { cur = JSON.parse(text); } catch { cur = undefined; }
1209
- if (!cur || typeof cur !== 'object' || Array.isArray(cur) || (cur.mcpServers != null && (typeof cur.mcpServers !== 'object' || Array.isArray(cur.mcpServers)))) {
1210
- 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;
1264
+ if (!cur || typeof cur !== 'object' || Array.isArray(cur) || (cur[t.key] != null && (typeof cur[t.key] !== 'object' || Array.isArray(cur[t.key])))) {
1265
+ 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 "${t.key}": "lode": ${JSON.stringify(t.entry)}`); continue;
1211
1266
  }
1212
- 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; }
1267
+ 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 "${t.key}": "lode": ${JSON.stringify(t.entry)}`); continue; }
1213
1268
  }
1214
1269
  const indent = (text?.match(/\n([ \t]+)"/) || [])[1] || 2;
1215
- const has = cur.mcpServers && Object.prototype.hasOwnProperty.call(cur.mcpServers, 'lode');
1270
+ const has = cur[t.key] && Object.prototype.hasOwnProperty.call(cur[t.key], 'lode');
1216
1271
  const ours = (marker.added || []).find((a) => a.file === t.file);
1217
1272
  if (remove) {
1218
- 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 ?? '') });
1273
+ if (has && (t.alts.some((a) => same(cur[t.key].lode, a)) || (ours && same(cur[t.key].lode, ours.entry)))) plan.push({ do: 'remove', file: t.file, key: t.key, keyCreated: ours?.key_created === true, f, cur, indent, created: !!ours?.created, st: rd.st, eol: /\r\n/.test(text ?? '') });
1219
1274
  else if (has) refused.push(`${t.file}: its "lode" entry isn't the one lode init adds, so it was left alone.`);
1220
- } 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 ?? '') });
1275
+ } else if (!has) plan.push({ do: 'add', file: t.file, key: t.key, f, cur, indent, entry: t.entry, created: text == null, st: rd.st, eol: /\r\n/.test(text ?? '') });
1221
1276
  }
1222
1277
  const skillThere = fs.existsSync(path.join(skillDst, 'SKILL.md'));
1223
1278
  if (!safe(skillRel)) refused.push(`${skillRel}: it or a folder above it is a link, so lode init won't touch it.`);
@@ -1251,8 +1306,14 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1251
1306
  };
1252
1307
  if (rules || remove) {
1253
1308
  const ruleTargets = [];
1254
- if (remove || client === 'all' || client === 'claude') ruleTargets.push({ file: 'CLAUDE.md', kind: 'md', create: true }, { file: 'AGENTS.md', kind: 'md', create: agentsMd });
1255
- if (remove || client === 'all' || client === 'cursor') ruleTargets.push({ file: path.join('.cursor', 'rules', 'lode.mdc'), kind: 'mdc', create: true });
1309
+ const want = (...c) => remove || on(...c);
1310
+ // LOD-306: Codex and Copilot read AGENTS.md; Gemini CLI reads GEMINI.md by default. Copilot's own file gets the
1311
+ // line only when AGENTS.md is left out (--no-agents-md), so no agent reads it twice. Grok's terminal rules: below.
1312
+ if (want('claude')) ruleTargets.push({ file: 'CLAUDE.md', kind: 'md', create: true });
1313
+ if (want('claude', 'vscode', 'codex')) ruleTargets.push({ file: 'AGENTS.md', kind: 'md', create: agentsMd });
1314
+ if (want('cursor')) ruleTargets.push({ file: path.join('.cursor', 'rules', 'lode.mdc'), kind: 'mdc', create: true });
1315
+ if (want('vscode') && (remove || !agentsMd)) ruleTargets.push({ file: path.join('.github', 'copilot-instructions.md'), kind: 'md', create: true });
1316
+ if (want('gemini')) ruleTargets.push({ file: 'GEMINI.md', kind: 'md', create: true });
1256
1317
  for (const t of ruleTargets) {
1257
1318
  const f = path.join(cwd, t.file);
1258
1319
  const r = readRules(t.file);
@@ -1266,8 +1327,8 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1266
1327
  if (text == null && !t.create) continue;
1267
1328
  if (text != null && (block || text.includes(RULE) || text.includes(RULE_V1))) continue;
1268
1329
  plan.push({ do: 'rules-add', file: t.file, f, text, st: r.st, kind: 'md' });
1269
- } else if (text == null) { if (!remove) plan.push({ do: 'rules-add', file: t.file, f, text, kind: 'mdc' }); }
1270
- 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' }); }
1330
+ } else if (text == null) { if (!remove) plan.push({ do: 'rules-add', file: t.file, f, text, kind: t.kind }); }
1331
+ 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: t.kind }); }
1271
1332
  else refused.push(`${t.file}: isn't the rule file lode init writes, so it was left alone.`);
1272
1333
  }
1273
1334
  // LOD-306 (Paul, 04-12-2026): Grok Build's terminal app (grok) does not read .mdc rules; it reads *.md in
@@ -1293,10 +1354,45 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1293
1354
  }
1294
1355
  }
1295
1356
  }
1357
+ // LOD-306: Codex's project config is TOML, which init doesn't parse. It only ever creates the file with the fixed
1358
+ // block, appends that block to an existing file that has no Lode server and no inline mcp_servers table (a table
1359
+ // header appended there would be invalid), or takes out exactly that block. Anything else is left alone, with the
1360
+ // lines to add by hand. Codex reads it only in a project the user has marked trusted.
1361
+ if (on('codex')) {
1362
+ const rel = path.join('.codex', 'config.toml');
1363
+ const r = readRules(rel);
1364
+ if (r.bad) { if (!remove || (() => { try { return !!fs.lstatSync(path.join(cwd, rel)); } catch { return false; } })()) refused.push(`${rel}: ${r.bad}`); }
1365
+ else {
1366
+ const text = r.text;
1367
+ // Security review 04-12-2026: the block counts only at the start of a line, outside any multi-line string, and
1368
+ // with nothing but blank or comment lines between it and the next table header (or the end), so taking it out
1369
+ // can't move a line the user added under it onto another table. Remove only a block init recorded in its note.
1370
+ const odd = (t) => ((t.match(/"""/g) || []).length % 2) || ((t.match(/'''/g) || []).length % 2);
1371
+ const at = (b) => { const i = text.indexOf(b); if (i < 0 || (i > 0 && text[i - 1] !== '\n') || odd(text.slice(0, i))) return -1; return /^(?:[ \t]*(?:#[^\r\n]*)?\r?\n)*(?:[ \t]*(?:#[^\r\n]*)?$|[ \t]*\[)/.test(text.slice(i + b.length)) ? i : -1; };
1372
+ const block = text == null ? null : KNOWN_TOMLS.flatMap((b) => [crlf(b), b]).find((b) => at(b) >= 0);
1373
+ const rest = block ? text.replace(block, '') : (text ?? '');
1374
+ // TOML isn't parsed, so anything unusual is refused (the user gets the lines to add by hand): every mention of
1375
+ // mcp_servers must be a plain [mcp_servers.<name>] header for a server other than lode; no arrays of tables, no
1376
+ // \\u escapes, no unclosed multi-line string, no key named lode, no other copy of the marker.
1377
+ const plainHeader = /^[ \t]*\[mcp_servers\.(?!lode[ \t.\]])[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*\][ \t]*(?:#[^\r\n]*)?$/;
1378
+ const clash = rest.split(/\r?\n/).some((l) => l.includes('mcp_servers') && !plainHeader.test(l)) || rest.includes('[[') || rest.includes('\\u') || rest.includes('\\U') || odd(rest) || /^[ \t]*["']?lode["']?[ \t]*[.=]/m.test(rest) || rest.includes('lode:mcp');
1379
+ const byHand = `Add these lines by hand if you want Lode in Codex:\n${codexBlock(serverUrl)}`;
1380
+ const noted = (marker.added || []).find((a) => a.file === rel);
1381
+ if (remove) {
1382
+ if (block && noted) plan.push({ do: 'rules-remove', file: rel, f: path.join(cwd, rel), text, st: r.st, kind: 'toml', block });
1383
+ else if (noted || (text != null && text.includes('lode:mcp'))) refused.push(`${rel}: the "lode" block isn't where lode init put it, or lines were added under it, so it was left alone. Remove [mcp_servers.lode] by hand.`);
1384
+ } else if (!block) {
1385
+ if (clash) refused.push(`${rel}: has a "lode" server, an mcp_servers entry or TOML that lode init can't safely add to, so it was left alone. ${byHand}`);
1386
+ else plan.push({ do: 'rules-add', file: rel, f: path.join(cwd, rel), text, st: r.st, kind: 'toml' });
1387
+ }
1388
+ }
1389
+ }
1296
1390
  const refusedText = refused.length ? `\nNot changed:\n${refused.map((r) => ` ${r}`).join('\n')}` : '';
1297
1391
  if (!plan.length) return (remove ? 'Nothing to remove that lode init added.' : 'Lode is already set up in this project.') + refusedText;
1298
1392
  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)'}`
1299
1393
  : 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' : ''}`
1394
+ : p.do === 'rules-add' && p.kind === 'toml' ? ` ${p.file}: ${p.text == null ? 'create it with' : 'add, at the end,'} one server "lode" -> ${serverUrl}${p.text == null ? '' : '; nothing else in the file changes'} (Codex reads it in a trusted project)`
1395
+ : p.do === 'rules-remove' && p.kind === 'toml' ? ` ${p.file}: remove the "lode" server lode init added (nothing else in the file changes)`
1300
1396
  : 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'}`
1301
1397
  : p.do === 'rules-remove' ? ` ${p.file}: remove the Lode rules ${p.kind === 'md' ? 'line' : 'file'} lode init added${p.kind === 'md' ? ' (nothing else in the file changes)' : ''}`
1302
1398
  : 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)`
@@ -1304,25 +1400,24 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1304
1400
  if (!remove) lines.push(` ${markerRel}: a small note of what lode init added, so --remove undoes only that`);
1305
1401
  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' : ''}${!remove && rules && !agentsMd ? ' --no-agents-md' : ''} --yes${!remove && rules && plan.some((p) => p.do === 'rules-add') ? ` (add --no-rules to leave out the rules line${plan.some((p) => p.do === 'rules-add' && p.file === 'AGENTS.md' && p.text == null) ? ', or --no-agents-md to leave out the new AGENTS.md' : ''})` : ''}`;
1306
1402
  const write = (p, next) => {
1307
- 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`); }
1308
1403
  const out = JSON.stringify(next, null, p.indent) + '\n';
1309
- fs.writeFileSync(p.f, p.eol ? out.replace(/\n/g, '\r\n') : out);
1310
- // Check afterwards that every other entry is exactly as it was
1311
- const back = JSON.parse(fs.readFileSync(p.f, 'utf8'));
1312
- for (const k of Object.keys(p.cur)) if (k !== 'mcpServers' && !same(back[k], p.cur[k])) throw new Error(`${p.file} changed unexpectedly`);
1313
- 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`);
1404
+ writeInProject(fs, path, cwd, p.file, p.eol ? out.replace(/\n/g, '\r\n') : out, p.st ?? null);
1405
+ // Check that every other entry is exactly as it was in what was written
1406
+ const back = JSON.parse(out);
1407
+ for (const k of Object.keys(p.cur)) if (k !== p.key && !same(back[k], p.cur[k])) throw new Error(`${p.file} changed unexpectedly`);
1408
+ for (const k of Object.keys(p.cur[p.key] || {})) if (k !== 'lode' && !same(back[p.key]?.[k], p.cur[p.key][k])) throw new Error(`${p.file} changed unexpectedly`);
1314
1409
  };
1315
1410
  // The rules line: a new file is created with O_EXCL (never follows a link, never overwrites); an existing file is
1316
1411
  // opened without following a link, must still be the very file that was read (same inode, size and time), and is
1317
1412
  // only appended to; --remove writes back the text that was read minus the exact block, or deletes a file left empty.
1318
1413
  const failed = [];
1414
+ const content = (kind) => (kind === 'mdc' ? RULES_MDC : kind === 'toml' ? codexBlock(serverUrl) : RULES_BLOCK);
1319
1415
  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; };
1320
1416
  const rulesWrite = (p) => {
1321
1417
  if (!safe(p.file)) throw new Error('a link appeared');
1322
1418
  if (p.text == null) {
1323
- fs.mkdirSync(path.dirname(p.f), { recursive: true });
1324
- if (!safe(p.file)) throw new Error('a link appeared');
1325
- fs.writeFileSync(p.f, p.kind === 'mdc' ? RULES_MDC : RULES_BLOCK, { flag: 'wx' });
1419
+ // Re-review 04-12-2026: a new rules file is created by the same link-proof writer as the JSON files
1420
+ writeInProject(fs, path, cwd, p.file, content(p.kind));
1326
1421
  return;
1327
1422
  }
1328
1423
  if (p.do === 'rules-add') {
@@ -1330,12 +1425,12 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1330
1425
  const fd = fs.openSync(p.f, fs.constants.O_WRONLY | fs.constants.O_APPEND | NOFOLLOW);
1331
1426
  try {
1332
1427
  if (!unchanged(fd, p.st)) throw new Error('changed while lode init ran');
1333
- fs.writeSync(fd, `${p.text.endsWith('\n') ? '' : eol}${eol}${eol === '\n' ? RULES_BLOCK : crlf(RULES_BLOCK)}`);
1428
+ fs.writeSync(fd, `${p.text.endsWith('\n') ? '' : eol}${eol}${eol === '\n' ? content(p.kind) : crlf(content(p.kind))}`);
1334
1429
  } finally { fs.closeSync(fd); }
1335
1430
  return;
1336
1431
  }
1337
1432
  let next = '';
1338
- if (p.kind === 'md') {
1433
+ if (p.kind === 'md' || p.kind === 'toml') {
1339
1434
  const lead = ['\r\n\r\n', '\n\n'].find((l) => p.text.includes(l + p.block));
1340
1435
  next = lead ? p.text.replace(lead + p.block, lead.slice(0, lead.length / 2)) : p.text.replace(p.block, '');
1341
1436
  }
@@ -1350,19 +1445,20 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1350
1445
  };
1351
1446
  for (const p of plan) {
1352
1447
  if (p.do === 'add') {
1353
- fs.mkdirSync(path.dirname(p.f), { recursive: true });
1354
- write(p, { ...p.cur, mcpServers: { ...(p.cur.mcpServers || {}), lode: p.entry } });
1355
- marker.added = [...(marker.added || []).filter((a) => a.file !== p.file), { file: p.file, created: p.created, entry: p.entry }];
1448
+ write(p, { ...p.cur, [p.key]: { ...(p.cur[p.key] || {}), lode: p.entry } });
1449
+ marker.added = [...(marker.added || []).filter((a) => a.file !== p.file), { file: p.file, created: p.created, entry: p.entry, ...(p.cur[p.key] == null && !p.created ? { key_created: true } : {}) }];
1356
1450
  }
1357
1451
  if (p.do === 'remove') {
1358
- const next = { ...p.cur, mcpServers: { ...p.cur.mcpServers } }; delete next.mcpServers.lode;
1359
- if (p.created && !Object.keys(next.mcpServers).length && Object.keys(next).length === 1) fs.rmSync(p.f); else write(p, next);
1452
+ const next = { ...p.cur, [p.key]: { ...p.cur[p.key] } }; delete next[p.key].lode;
1453
+ if (p.keyCreated && !Object.keys(next[p.key]).length) delete next[p.key];
1454
+ if (p.created && !Object.keys(next[p.key] ?? {}).length && Object.keys(next).length === 1) fs.rmSync(p.f); else write(p, next);
1360
1455
  marker.added = (marker.added || []).filter((a) => a.file !== p.file);
1361
1456
  }
1362
1457
  if (p.do === 'rules-add' || p.do === 'rules-remove') {
1363
1458
  // A failure here is reported, never thrown, so the marker for the steps already done is still written
1364
1459
  try {
1365
1460
  rulesWrite(p);
1461
+ if (p.kind === 'toml') marker.added = [...(marker.added || []).filter((a) => a.file !== p.file), ...(p.do === 'rules-add' ? [{ file: p.file, created: p.text == null, toml: true }] : [])];
1366
1462
  // Security review 04-12-2026: the .grok file is removed only when the marker says init created it
1367
1463
  if (p.kind === 'grok') { if (p.do === 'rules-add') marker.grok_rules = true; else delete marker.grok_rules; }
1368
1464
  } catch (e) { failed.push(` ${p.file}: not changed (${e.code || e.message}).`); }
@@ -1391,7 +1487,7 @@ async function initCmd({ client = 'all', yes = false, remove = false, gate = fal
1391
1487
  marker.skill_files = {};
1392
1488
  }
1393
1489
  }
1394
- if ((marker.added || []).length || Object.keys(marker.skill_files || {}).length || marker.grok_rules === true || Object.values(HOOK_KINDS).some((k) => marker[k.key] || Object.keys(marker[k.filesKey] || {}).length)) { fs.mkdirSync(path.dirname(markerFile), { recursive: true }); fs.writeFileSync(markerFile, JSON.stringify(marker, null, 2) + '\n'); }
1490
+ if ((marker.added || []).length || Object.keys(marker.skill_files || {}).length || marker.grok_rules === true || Object.values(HOOK_KINDS).some((k) => marker[k.key] || Object.keys(marker[k.filesKey] || {}).length)) { writeInProject(fs, path, cwd, markerRel, JSON.stringify(marker, null, 2) + '\n', markerSt(fs, markerFile)); }
1395
1491
  else { try { fs.rmSync(markerFile); } catch { /* none */ } }
1396
1492
  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.`;
1397
1493
  }
@@ -1606,7 +1702,7 @@ export async function main(argv) {
1606
1702
  }
1607
1703
  if (cmd === 'init') {
1608
1704
  const opts = { client: flag('--client'), yes: flag('--yes'), remove: flag('--remove'), gate: flag('--gate'), triage: flag('--triage'), verify: flag('--verify'), mode: flag('--mode'), shared: flag('--shared'), noRules: flag('--no-rules'), noAgentsMd: flag('--no-agents-md'), src: flag('--src') };
1609
- const client = ['claude', 'cursor', 'all'].includes(opts.client) ? opts.client : 'all';
1705
+ const client = INIT_CLIENTS.includes(opts.client) ? opts.client : 'all';
1610
1706
  return initCmd({ client, yes: opts.yes === true, remove: opts.remove === true, gate: opts.gate === true, triage: opts.gate !== true && opts.triage === true, verify: opts.gate !== true && opts.triage !== true && opts.verify === true, gateMode: opts.mode === 'ask' ? 'ask' : 'warn', gateShared: opts.shared === true, rules: opts.noRules !== true, agentsMd: opts.noAgentsMd !== true, src: opts.src === 'setup' ? 'setup' : null });
1611
1707
  }
1612
1708
  if (cmd === 'watch') {
@@ -1625,7 +1721,7 @@ export async function main(argv) {
1625
1721
  return v.format(res, failOn);
1626
1722
  }
1627
1723
  if (cmd === 'platforms') return `Lode covers: ${Object.keys(PLATFORMS).join(', ')}. Facts are source-linked and dated; see https://trylode.io/methodology/`;
1628
- 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 init --triage [--shared] [--yes] [--remove]\n node lode.mjs init --verify [--shared] [--yes] [--remove]\n node lode.mjs verify [--fail-on act|any|code,code] [--since YYYY-MM-DD]\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';
1724
+ 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|vscode|gemini|codex|all] [--no-rules] [--yes] [--remove]\n node lode.mjs init --gate [--mode ask] [--shared] [--yes] [--remove]\n node lode.mjs init --triage [--shared] [--yes] [--remove]\n node lode.mjs init --verify [--shared] [--yes] [--remove]\n node lode.mjs verify [--fail-on act|any|code,code] [--since YYYY-MM-DD]\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';
1629
1725
  }
1630
1726
 
1631
1727
  // Run only when this very file is the entry point (security review 01-12-2026: endsWith('lode.mjs') also matched trylode.mjs).