@cohesivity/init 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +140 -20
  2. package/bin/cli.js +642 -88
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,43 +1,163 @@
1
1
  # @cohesivity/init
2
2
 
3
- Set up [Cohesivity](https://cohesivity.ai) in a project with one command.
3
+ Set up [Cohesivity](https://cohesivity.ai) in a project with one command:
4
4
 
5
5
  ```bash
6
6
  npx @cohesivity/init
7
7
  ```
8
8
 
9
- The command runs once and does three things:
9
+ The installer detects every supported client independently, so one run can
10
+ configure several clients. It then creates or reuses the project's Cohesivity
11
+ tenant and updates existing project pointers. Installation has no side effects;
12
+ every effect happens only when this command runs.
10
13
 
11
- 1. **Installs the Cohesivity agent skill** into every known agent skill dir whose harness is present on this machine (Claude Code, Cursor, Codex; the cross-tool `~/.agents` when none are). The skill is a markdown file your agent loads in later sessions, fetched from a public commit pinned in this file — so you can read the exact bytes it will install before running anything.
12
- 2. **Creates or reuses a project tenant** and writes the credentials to `.cohesivity`, which it adds to `.gitignore`. The tenant-creation request identifies the coding agent that ran the command: the tool walks its own parent processes and sends **that one name** — `claude`, `opencode`, or whatever the program calls itself — as its User-Agent, in the form `{npx:<name>}`. If it cannot tell, it sends `none`. It reads nothing else about your machine: no list of your running processes, no session logs, no conversations, no model settings, no files outside the project. Creating a tenant also stores an opaque random setup id at `~/.config/cohesivity/machine-id` and sends it with that request, so tenants created from one machine can be grouped rather than looking like unrelated people. It is issued by the server, is not derived from your hardware or user, and carries nothing about you or your project. Delete the file to end the association.
13
- 3. **Adds a descriptive pointer** to an existing `AGENTS.md` or `CLAUDE.md`, so an agent opening this project later knows it uses Cohesivity. It only touches a file that is already there, and creates nothing on its own.
14
+ ## Client delivery
14
15
 
15
- It writes nothing else. It does not touch your README.
16
+ Plain `npx @cohesivity/init` uses each detected client's supported installation
17
+ surface. Native commands are executed as argument arrays without a shell.
18
+ Portable directories are staged and atomically replaced.
16
19
 
17
- Install does nothing. Every effect happens when you run the command, and you can read the script first. There is no `postinstall` hook.
18
-
19
- ## Verifying the release
20
-
21
- Every version publishes from [this repository's](https://github.com/cohesivity-org/cohesivity-init) release workflow with npm provenance, so the tarball you run is tied to a specific commit:
20
+ | detected client | delivery |
21
+ | --- | --- |
22
+ | Claude | `claude plugin marketplace add <verified-local-root> --scope user`, then `claude plugin install cohesivity@cohesivity --scope user` |
23
+ | Cursor | atomically copy the portable plugin to `~/.cursor/plugins/local/cohesivity` |
24
+ | Codex | `codex plugin marketplace add <verified-local-marketplace>`, then `codex plugin add cohesivity@cohesivity` |
25
+ | Gemini | `gemini extensions install <verified-local-gemini-root> --consent` |
26
+ | Antigravity | `agy plugin install <verified-local-root>`; if `agy` is absent, atomically copy to `~/.gemini/config/plugins/cohesivity` only when an Antigravity-specific home is present |
27
+ | OpenClaw | `openclaw plugins install <verified-local-portable-root> --force`, then enable `cohesivity` |
28
+ | Hermes | atomically copy to `~/.hermes/plugins/cohesivity`, then `hermes plugins enable cohesivity` |
29
+
30
+ Detection is additive rather than first-match-wins. A Claude home does not stop
31
+ Cursor, Codex, Gemini, Antigravity, OpenClaw, or Hermes from also being
32
+ configured. A shared `~/.gemini` directory alone is not treated as positive
33
+ Antigravity detection.
34
+
35
+ Known adapters without a Cohesivity plugin package receive the canonical
36
+ standalone skill plus the remote MCP endpoint
37
+ `https://cohesivity.ai/mcp/manage`, configured through the adapter's documented
38
+ native command. The installer currently supports this fallback for GitHub
39
+ Copilot CLI, VS Code, Cline CLI, and Grok. It does not modify JSON, TOML, or YAML
40
+ configuration with regular expressions.
41
+
42
+ The installer never starts OAuth or opens a browser. It prints the relevant
43
+ restart and authentication steps after delivery. Hermes remote MCP OAuth is
44
+ qualified: automatic login works only when the endpoint supports Dynamic Client
45
+ Registration; otherwise Hermes needs a pre-registered OAuth client.
46
+
47
+ ## Standalone skill only
48
+
49
+ Use `--no-plugin` when plugins and MCP configuration are unwanted:
22
50
 
23
51
  ```bash
24
- npm audit signatures
52
+ npx @cohesivity/init --no-plugin
53
+ ```
54
+
55
+ This installs only the canonical skill at
56
+ `~/.agents/skills/cohesivity/SKILL.md`. It installs no client plugin and adds no
57
+ MCP server. Tenant creation, machine attribution, `.gitignore`, `.cohesivity`,
58
+ and existing project pointers follow the same flow as plain init.
59
+
60
+ ## Verified plugin artifacts
61
+
62
+ Plugin delivery begins with one immutable, pinned manifest. The installer
63
+ checks the manifest's exact byte size and SHA-256 before parsing it, then checks
64
+ the exact byte size and SHA-256 of every selected artifact before extraction.
65
+ The manifest schema is:
66
+
67
+ ```json
68
+ {
69
+ "schema_version": 1,
70
+ "version": "2.1.0",
71
+ "packages": [
72
+ {
73
+ "client": "portable",
74
+ "immutable_url": "https://immutable.example/portable.tar.gz",
75
+ "size": 1234,
76
+ "sha256": "64 lowercase hexadecimal characters",
77
+ "archive": "cohesivity-portable-2.1.0.tar.gz"
78
+ }
79
+ ]
80
+ }
25
81
  ```
26
82
 
83
+ The required artifact keys are `claude`, `portable`, `codex`, `gemini`, and
84
+ `antigravity`. Extraction rejects absolute paths, traversal, links, duplicate paths,
85
+ special files, malformed headers, oversized content, and archives without an
86
+ end marker. Staged portable installs replace the previous directory atomically,
87
+ with rollback if the commit fails.
88
+
89
+ The immutable manifest commit, byte size, and SHA-256 are isolated in the
90
+ `PLUGIN_RELEASE` block in `bin/cli.js`. Tests use the
91
+ `COHESIVITY_PLUGIN_MANIFEST_PIN` injection hook with local, fully pinned
92
+ fixtures; normal users should not set it.
93
+
94
+ ## Tenant bootstrap and failure behavior
95
+
96
+ After client delivery, the command:
97
+
98
+ 1. Ensures `.cohesivity` is ignored before requesting credentials.
99
+ 2. Creates a tenant with `POST /api/genesis`, or validates and reuses an
100
+ existing `.cohesivity`.
101
+ 3. Atomically installs complete credentials only after validating the tenant,
102
+ management key, application key, expiry, lifecycle, and runtime profile.
103
+ 4. Stores a server-issued opaque setup identifier at
104
+ `~/.config/cohesivity/machine-id` so tenants created by one setup can be
105
+ grouped.
106
+ 5. Adds or updates a managed Cohesivity block in existing `AGENTS.md`,
107
+ `CLAUDE.md`, and `README.md` files. It never creates those files.
108
+
109
+ A plugin download, verification, extraction, copy, or native-command failure
110
+ does not skip tenant bootstrap. The command still completes the idempotent
111
+ tenant flow and project pointers, then exits nonzero, identifies every failed
112
+ delivery, and says installation is incomplete. It never prints the normal
113
+ complete-installation message in that state.
114
+
115
+ Tenant failures remain fail-closed. Network, HTTP, incomplete-response,
116
+ credential-validation, and ignore-write failures exit nonzero without project
117
+ pointers or a false success message. Existing incomplete credentials are never
118
+ overwritten.
119
+
120
+ ## Dry run
121
+
122
+ `--dry-run` has zero side effects. It performs no fetch, tenant request, native
123
+ command, directory creation, file write, OAuth, or browser action. It detects
124
+ clients using filesystem/PATH reads and prints the exact manifest checks,
125
+ artifact checks, native argument-vector commands, atomic destinations, tenant
126
+ request, and project-pointer changes it would perform.
127
+
128
+ ## Attribution and privacy
129
+
130
+ The tenant request identifies the coding agent that launched the command. The
131
+ installer walks only its own parent-process lineage and sends one sanitized name
132
+ as `{npx:<name>}`. If it cannot infer a name, it sends `{npx:none}`. `--runtime`
133
+ overrides that label when measurement is wrong.
134
+
135
+ It never enumerates the system process table: no session logs, conversations,
136
+ or model settings are read, nor files outside the documented client homes,
137
+ project bootstrap files, and machine-id path. The machine id is opaque,
138
+ server-issued, and not derived from hardware or user data. Delete
139
+ `~/.config/cohesivity/machine-id` to end that association.
140
+
27
141
  ## Options
28
142
 
29
143
  | flag | effect |
30
144
  | --- | --- |
31
- | `--runtime <name>` | explicit harness label override — use only when the measurement is wrong |
32
- | `--dry-run` | print what would happen. Change nothing |
33
- | `--base <url>` | API base (default `https://cohesivity.ai`) |
145
+ | `--runtime <name>` | override the measured harness label |
146
+ | `--no-plugin` | install only the canonical standalone skill; add no plugin or MCP |
147
+ | `--dry-run` | print exact actions with zero side effects |
148
+ | `--base <url>` | API base for tenant bootstrap (default `https://cohesivity.ai`) |
149
+ | `-h`, `--help` | show command help |
34
150
 
35
- The name comes from the process that launched the command, so `--runtime` is an override, not a requirement — and an agent this package has never heard of simply names itself. Nothing about the detection is specific to any vendor.
151
+ ## Verifying the release
36
152
 
37
- ## Requirements
153
+ Every npm version publishes from this repository through npm Trusted Publishing
154
+ with provenance:
38
155
 
39
- Node.js 18+ for the built-in `fetch`. Zero dependencies.
156
+ ```bash
157
+ npm audit signatures
158
+ ```
40
159
 
41
- ## Docs
160
+ Node.js 18+ is required for built-in `fetch`. The package has zero dependencies
161
+ and no `postinstall` hook.
42
162
 
43
- <https://cohesivity.ai/llms.txt>
163
+ Full product documentation: <https://cohesivity.ai/llms.txt>
package/bin/cli.js CHANGED
@@ -10,35 +10,60 @@
10
10
  * Zero dependencies. Node 18+ provides global `fetch` and the `node:` builtins,
11
11
  * so the registry ships this one file and nothing else.
12
12
  *
13
- * The command does three things, in order:
14
- * 1. Install the Cohesivity agent skill into every known agent skill dir
15
- * whose harness is present on this machine. This is the global,
16
- * persistent playbook the agent loads later.
13
+ * By default, the command does three things, in order:
14
+ * 1. Detect every installed supported client and install its native or
15
+ * portable Cohesivity plugin package. Unsupported adapters with a safe,
16
+ * documented MCP command receive the standalone skill and remote MCP.
17
17
  * 2. Create or reuse a project tenant, write ./.cohesivity, gitignore it.
18
- * 3. If AGENTS.md or CLAUDE.md already exists, add a descriptive pointer to it.
18
+ * 3. If AGENTS.md, CLAUDE.md, or README.md already exists, add a descriptive
19
+ * pointer to it.
19
20
  *
20
- * It writes nothing else. It does not add anything to your README: an installer
21
- * putting promotional text in someone's repo is an edit they did not ask for,
22
- * and it forced every careful agent to stop and request permission mid-setup.
21
+ * With --no-plugin, step 1 installs only the canonical standalone skill. No
22
+ * plugin or MCP configuration is installed. Tenant creation, machine
23
+ * attribution, and project pointers are unchanged.
24
+ *
25
+ * It writes nothing else, and it creates none of those three files. The pointer
26
+ * is descriptive rather than promotional — it states where this project's
27
+ * backend state lives, which is what makes it worth carrying in a repo someone
28
+ * else (or some other agent) opens later.
23
29
  *
24
30
  * The first line is the shebang. It tells npx to run this file as a program.
25
31
  */
26
32
 
27
- import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
28
- import { execSync } from 'node:child_process';
29
- import { homedir } from 'node:os';
30
- import { join } from 'node:path';
33
+ import {
34
+ accessSync, appendFileSync, constants as fsConstants, existsSync, lstatSync,
35
+ mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync,
36
+ } from 'node:fs';
37
+ import { execFileSync, spawnSync } from 'node:child_process';
38
+ import { createHash } from 'node:crypto';
39
+ import { homedir, tmpdir } from 'node:os';
40
+ import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
41
+ import { gunzipSync } from 'node:zlib';
31
42
 
32
43
  // ── args ────────────────────────────────────────────────────────────────────
33
44
  const argv = process.argv.slice(2);
34
45
  const has = (f) => argv.includes(f);
35
46
  const flag = (f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : undefined; };
36
47
 
48
+ function validateArgs() {
49
+ const switches = new Set(['--dry-run', '--no-plugin', '--no-branding', '--help', '-h']);
50
+ const values = new Set(['--runtime', '--base']);
51
+ for (let i = 0; i < argv.length; i++) {
52
+ if (switches.has(argv[i])) continue;
53
+ if (values.has(argv[i])) {
54
+ if (!argv[i + 1] || argv[i + 1].startsWith('-')) throw new Error(`${argv[i]} requires a value`);
55
+ i++; continue;
56
+ }
57
+ throw new Error(`unknown option ${argv[i]}`);
58
+ }
59
+ }
60
+
37
61
  if (has('--help') || has('-h')) { help(); process.exit(0); }
38
62
 
39
63
  // ── config ──────────────────────────────────────────────────────────────────
40
- const PKG_VERSION = '0.4.1';
64
+ const PKG_VERSION = '0.6.0';
41
65
  const BASE = (flag('--base') || process.env.COHESIVITY_BASE || 'https://cohesivity.ai').replace(/\/+$/, '');
66
+ const MCP_URL = 'https://cohesivity.ai/mcp/manage';
42
67
 
43
68
  // Machine id: one per machine, stored outside any project. A project's
44
69
  // .cohesivity is per project, so a machine that runs setup in several projects
@@ -53,9 +78,26 @@ const MACHINE_ID_FILE = join(MACHINE_ID_DIR, 'machine-id');
53
78
 
54
79
  // The skill is pinned to an immutable commit in the public, auditable repo.
55
80
  // Bumping the pin is a deliberate release step. See COH-172.
56
- const SKILL_PIN = '6c4c04d94d344590f6732763f0116b155a32753c';
81
+ const SKILL_PIN = 'f97e0d2ac8a653b7d54d1bb6e70aee78a8887e60';
57
82
  const SKILL_URL = `https://raw.githubusercontent.com/cohesivity-org/cohesivity-skill/${SKILL_PIN}/cohesivity.skill.md`;
58
83
 
84
+ // Plugin release pins live in this one block. Bump all three values together
85
+ // after publishing a new two-commit artifact manifest from cohesivity-plugin.
86
+ // Tests inject a complete pin with COHESIVITY_PLUGIN_MANIFEST_PIN.
87
+ const PLUGIN_RELEASE = Object.freeze({
88
+ manifestUrl: 'https://raw.githubusercontent.com/cohesivity-org/cohesivity-plugin/621beb765f34ea082ad8a9ff59488cd432aa0099/artifacts/v2.1.0/install-manifest.v1.json',
89
+ manifestBytes: 9610,
90
+ manifestSha256: '403ecc59865f752fdc7f647104d6006588be834a1e285c94f2f70e18144e34cd',
91
+ });
92
+
93
+ const ARTIFACT_KEYS = Object.freeze({
94
+ claude: 'claude',
95
+ portable: 'portable',
96
+ codex: 'codex',
97
+ gemini: 'gemini',
98
+ antigravity: 'antigravity',
99
+ });
100
+
59
101
  // Harness: the nearest ancestor process that is not generic plumbing. Only
60
102
  // this process's own lineage is read — never the system process list — and only
61
103
  // the resulting name is sent. The sets below are closed lists of Unix plumbing,
@@ -84,8 +126,8 @@ function inferHarness() {
84
126
  ppid = Number(readFileSync(`/proc/${pid}/stat`, 'utf8').split(') ').pop().split(' ')[1]);
85
127
  } catch {
86
128
  try {
87
- argv = execSync(`ps -o args= -p ${pid}`, { timeout: 2000 }).toString().trim().split(/\s+/);
88
- ppid = Number(execSync(`ps -o ppid= -p ${pid}`, { timeout: 2000 }).toString().trim());
129
+ argv = execFileSync('ps', ['-o', 'args=', '-p', String(pid)], { timeout: 2000 }).toString().trim().split(/\s+/);
130
+ ppid = Number(execFileSync('ps', ['-o', 'ppid=', '-p', String(pid)], { timeout: 2000 }).toString().trim());
89
131
  } catch { return null; }
90
132
  }
91
133
  let name = (argv[0] || '').split('/').pop().replace(/^-/, '');
@@ -103,6 +145,7 @@ function inferHarness() {
103
145
  }
104
146
 
105
147
  const DRY = has('--dry-run');
148
+ const NO_PLUGIN = has('--no-plugin');
106
149
 
107
150
  const CWD = process.cwd();
108
151
  const rel = (p) => p.replace(CWD + '/', '');
@@ -115,69 +158,512 @@ const EXPLICIT = String(flag('--runtime') || process.env.COHESIVITY_RUNTIME || '
115
158
  const HARNESS = EXPLICIT || inferHarness() || 'none';
116
159
  const UA = `{npx:${HARNESS}}`;
117
160
 
118
- main().catch((e) => { console.error(`cohesivity: unexpected error: ${e.message}`); process.exit(1); });
119
-
120
161
  async function main() {
162
+ validateArgs();
121
163
  console.log(`\ncohesivity/init v${PKG_VERSION}: setting up (harness: ${HARNESS})${DRY ? ' [dry-run: no changes]' : ''}\n`);
122
- await installSkill();
164
+ const deliveryFailures = NO_PLUGIN
165
+ ? await installStandaloneSkill()
166
+ : await installClientIntegrations();
123
167
  await ensureTenant();
124
- augmentAgentsFile();
125
- ground();
126
- }
127
-
128
- // ── 1) install the skill into the skill dirs present on this machine ─────────
129
- // Presence on disk is the measurement: each known agent skill dir is written
130
- // only when its harness home already exists. When none exist, the cross-tool
131
- // ~/.agents dir is the fallback so the skill lands somewhere.
132
- function skillDirs() {
133
- const codexHome = process.env.CODEX_HOME || join(homedir(), '.codex');
134
- const gated = [
135
- [join(homedir(), '.claude'), join(homedir(), '.claude', 'skills', 'cohesivity')],
136
- [join(homedir(), '.cursor'), join(homedir(), '.cursor', 'skills', 'cohesivity')],
137
- [codexHome, join(codexHome, 'skills', 'cohesivity')],
138
- [join(homedir(), '.agents'), join(homedir(), '.agents', 'skills', 'cohesivity')],
139
- ];
140
- const dirs = gated.filter(([home]) => existsSync(home)).map(([, dir]) => dir);
141
- return dirs.length ? dirs : [join(homedir(), '.agents', 'skills', 'cohesivity')];
142
- }
143
-
144
- async function installSkill() {
145
- let skill;
168
+ augmentProjectFiles();
169
+ if (deliveryFailures.length) {
170
+ for (const failure of deliveryFailures) console.error(`cohesivity: delivery failed for ${failure.client}: ${failure.message}`);
171
+ }
172
+ ground(deliveryFailures);
173
+ if (deliveryFailures.length) process.exitCode = 1;
174
+ }
175
+
176
+ // ── 1) detect clients and deliver verified integrations ──────────────────────
177
+ const HOME = homedir();
178
+ const CODEX_HOME = process.env.CODEX_HOME || join(HOME, '.codex');
179
+ const CANONICAL_SKILL_DIR = join(HOME, '.agents', 'skills', 'cohesivity');
180
+ const POSITIVE_ANTIGRAVITY_HOMES = [
181
+ join(HOME, '.gemini', 'antigravity'),
182
+ join(HOME, '.gemini', 'antigravity-cli'),
183
+ join(HOME, '.gemini', 'antigravity-ide'),
184
+ ];
185
+
186
+ function executable(names) {
187
+ for (const name of names) {
188
+ if (name.includes('/') || name.includes('\\')) {
189
+ try { accessSync(name, fsConstants.X_OK); return name; } catch { continue; }
190
+ }
191
+ for (const dir of String(process.env.PATH || '').split(delimiter).filter(Boolean)) {
192
+ const candidates = process.platform === 'win32'
193
+ ? String(process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';').map((ext) => join(dir, name + ext.toLowerCase()))
194
+ : [join(dir, name)];
195
+ for (const candidate of candidates) {
196
+ try { accessSync(candidate, fsConstants.X_OK); return candidate; } catch { /* keep looking */ }
197
+ }
198
+ }
199
+ }
200
+ return null;
201
+ }
202
+
203
+ function hasAny(paths) { return paths.some((path) => existsSync(path)); }
204
+
205
+ function detectClients() {
206
+ const bins = {
207
+ claude: executable(['claude']),
208
+ cursor: executable(['cursor', 'cursor-agent']),
209
+ codex: executable(['codex']),
210
+ gemini: executable(['gemini']),
211
+ antigravity: executable(['agy']),
212
+ openclaw: executable(['openclaw']),
213
+ hermes: executable(['hermes']),
214
+ };
215
+ const harnessIs = (...names) => names.includes(HARNESS);
216
+ return [
217
+ { id: 'claude', name: 'Claude', bin: bins.claude, detected: Boolean(bins.claude || existsSync(join(HOME, '.claude')) || harnessIs('claude')), artifact: ARTIFACT_KEYS.claude },
218
+ { id: 'cursor', name: 'Cursor', bin: bins.cursor, detected: Boolean(bins.cursor || existsSync(join(HOME, '.cursor')) || harnessIs('cursor', 'cursor-agent')), artifact: ARTIFACT_KEYS.portable },
219
+ { id: 'codex', name: 'Codex', bin: bins.codex, detected: Boolean(bins.codex || existsSync(CODEX_HOME) || harnessIs('codex')), artifact: ARTIFACT_KEYS.codex },
220
+ {
221
+ id: 'gemini', name: 'Gemini', bin: bins.gemini,
222
+ detected: Boolean(bins.gemini || hasAny([join(HOME, '.gemini', 'settings.json'), join(HOME, '.gemini', 'extensions')]) || harnessIs('gemini')),
223
+ artifact: ARTIFACT_KEYS.gemini,
224
+ },
225
+ {
226
+ id: 'antigravity', name: 'Antigravity', bin: bins.antigravity,
227
+ detected: Boolean(bins.antigravity || hasAny(POSITIVE_ANTIGRAVITY_HOMES) || harnessIs('agy', 'antigravity')), artifact: ARTIFACT_KEYS.antigravity,
228
+ },
229
+ { id: 'openclaw', name: 'OpenClaw', bin: bins.openclaw, detected: Boolean(bins.openclaw || existsSync(join(HOME, '.openclaw')) || harnessIs('openclaw')), artifact: ARTIFACT_KEYS.portable },
230
+ { id: 'hermes', name: 'Hermes', bin: bins.hermes, detected: Boolean(bins.hermes || existsSync(join(HOME, '.hermes')) || harnessIs('hermes')), artifact: ARTIFACT_KEYS.portable },
231
+ ].filter((client) => client.detected);
232
+ }
233
+
234
+ const FALLBACK_ADAPTERS = [
235
+ { id: 'copilot', name: 'GitHub Copilot CLI', homes: [join(HOME, '.copilot')], bins: ['copilot'], args: [
236
+ 'mcp', 'add', '--transport', 'http', 'cohesivity', MCP_URL,
237
+ ] },
238
+ { id: 'vscode', name: 'VS Code', homes: [join(HOME, '.vscode')], bins: ['code'], args: [
239
+ '--add-mcp', JSON.stringify({ name: 'cohesivity', type: 'http', url: MCP_URL }),
240
+ ] },
241
+ { id: 'cline', name: 'Cline CLI', homes: [join(HOME, '.cline')], bins: ['cline'], args: [
242
+ 'mcp', 'add', 'cohesivity', MCP_URL, '--type', 'http',
243
+ ] },
244
+ { id: 'grok', name: 'Grok', homes: [join(HOME, '.grok')], bins: ['grok'], args: [
245
+ 'mcp', 'add', '--transport', 'http', 'cohesivity', MCP_URL,
246
+ ] },
247
+ ];
248
+
249
+ function detectFallbackAdapters() {
250
+ return FALLBACK_ADAPTERS.map((adapter) => {
251
+ const bin = executable(adapter.bins);
252
+ return { ...adapter, bin, detected: Boolean(bin || hasAny(adapter.homes) || adapter.bins.includes(HARNESS)) };
253
+ }).filter((adapter) => adapter.detected);
254
+ }
255
+
256
+ async function installStandaloneSkill() {
257
+ log('plugin and MCP installation disabled (--no-plugin)');
258
+ const error = await writeStandaloneSkill();
259
+ return error ? [{ client: 'standalone skill', message: error.message }] : [];
260
+ }
261
+
262
+ async function writeStandaloneSkill() {
263
+ const shown = displayPath(CANONICAL_SKILL_DIR);
264
+ if (DRY) { act(`fetch ${SKILL_URL} and atomically install the standalone skill -> ${shown}`); return null; }
146
265
  try {
147
266
  const res = await fetch(SKILL_URL, { headers: { 'User-Agent': UA } });
148
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
149
- skill = await res.text();
150
- } catch (e) {
151
- log(`could not fetch the skill (${e.message}). Continuing. Docs: ${BASE}/llms.txt`);
152
- return;
267
+ if (!res.ok) throw new Error(`skill returned HTTP ${res.status}`);
268
+ const skill = await res.text();
269
+ if (!versionOf(skill)) throw new Error('skill has no version field');
270
+ const file = join(CANONICAL_SKILL_DIR, 'SKILL.md');
271
+ const current = existsSync(file) ? readFileSync(file, 'utf8') : null;
272
+ if (current === skill) { log(`standalone skill current -> ${shown}`); return null; }
273
+ installFileAtomically(file, skill);
274
+ log(`standalone skill ${current === null ? 'installed' : 'updated'} -> ${shown}`);
275
+ return null;
276
+ } catch (error) {
277
+ return error;
153
278
  }
154
- const liveVer = versionOf(skill) || 'unknown';
155
- let installed = 0; let updated = 0; let current = 0;
156
- for (const dir of skillDirs()) {
157
- const shown = dir.replace(homedir(), '~');
158
- const file = join(dir, 'SKILL.md');
159
- const cur = existsSync(file) ? versionOf(readFileSync(file, 'utf8')) : null;
160
- if (cur && cur === liveVer) { current++; continue; }
161
- if (DRY) { act(`install the skill (version ${liveVer}) -> ${shown}`); continue; }
162
- try {
163
- mkdirSync(dir, { recursive: true });
164
- writeFileSync(file, skill);
165
- if (cur) updated++; else installed++;
166
- } catch (e) {
167
- log(`could not write the skill to ${shown} (${e.message}). Continuing.`);
279
+ }
280
+
281
+ async function installClientIntegrations() {
282
+ const clients = detectClients();
283
+ const adapters = detectFallbackAdapters();
284
+ if (!clients.length && !adapters.length) {
285
+ log('no supported client detected; installing the canonical standalone skill');
286
+ const error = await writeStandaloneSkill();
287
+ return error ? [{ client: 'standalone skill', message: error.message }] : [];
288
+ }
289
+
290
+ log(`detected clients: ${[...clients, ...adapters].map((client) => client.name).join(', ')}`);
291
+ const failures = [];
292
+ let artifacts = null;
293
+ if (clients.length) {
294
+ if (DRY) describeDryRunPluginDelivery(clients);
295
+ else {
296
+ try { artifacts = await fetchPluginArtifacts(new Set(clients.map((client) => client.artifact))); }
297
+ catch (error) {
298
+ for (const client of clients) failures.push({ client: client.name, message: error.message });
299
+ }
300
+ }
301
+ }
302
+
303
+ if (artifacts) {
304
+ for (const client of clients) {
305
+ try {
306
+ await installForClient(client, artifacts.get(client.artifact));
307
+ log(`${client.name} integration installed or reconciled`);
308
+ } catch (error) {
309
+ failures.push({ client: client.name, message: error.message });
310
+ }
311
+ }
312
+ for (const artifact of artifacts.values()) {
313
+ try { rmSync(artifact.temporary, { recursive: true, force: true }); }
314
+ catch (error) { failures.push({ client: 'plugin staging cleanup', message: error.message }); }
315
+ }
316
+ }
317
+
318
+ if (adapters.length) {
319
+ const skillError = await writeStandaloneSkill();
320
+ if (skillError) failures.push({ client: 'standalone skill', message: skillError.message });
321
+ for (const adapter of adapters) {
322
+ if (DRY) {
323
+ act(`run ${formatCommand(adapter.bin || adapter.bins[0], adapter.args)}`);
324
+ continue;
325
+ }
326
+ if (!adapter.bin) {
327
+ failures.push({ client: adapter.name, message: 'client state exists but its native CLI is not on PATH' });
328
+ continue;
329
+ }
330
+ try { runNative(adapter.bin, adapter.args); }
331
+ catch (error) { failures.push({ client: adapter.name, message: error.message }); }
332
+ }
333
+ }
334
+
335
+ printClientInstructions(clients, adapters);
336
+ return failures;
337
+ }
338
+
339
+ function manifestPin() {
340
+ if (!process.env.COHESIVITY_PLUGIN_MANIFEST_PIN) return { ...PLUGIN_RELEASE, injected: false };
341
+ let pin;
342
+ try { pin = JSON.parse(process.env.COHESIVITY_PLUGIN_MANIFEST_PIN); }
343
+ catch { throw new Error('COHESIVITY_PLUGIN_MANIFEST_PIN is not valid JSON'); }
344
+ return { manifestUrl: pin.url, manifestBytes: pin.bytes, manifestSha256: pin.sha256, injected: true };
345
+ }
346
+
347
+ async function fetchPluginArtifacts(keys) {
348
+ const pin = manifestPin();
349
+ validatePin(pin.manifestUrl, pin.manifestBytes, pin.manifestSha256, 'plugin manifest', pin.injected, 1024 * 1024);
350
+ const manifestBytes = await fetchVerified(pin.manifestUrl, pin.manifestBytes, pin.manifestSha256, 'plugin manifest');
351
+ let manifest;
352
+ try { manifest = JSON.parse(manifestBytes.toString('utf8')); }
353
+ catch { throw new Error('verified plugin manifest is not valid JSON'); }
354
+ if (manifest.schema_version !== 1 || !Array.isArray(manifest.packages)) {
355
+ throw new Error('verified plugin manifest has an unsupported schema');
356
+ }
357
+ const entries = new Map(manifest.packages.map((entry) => [entry?.client, entry]));
358
+
359
+ const result = new Map();
360
+ try {
361
+ for (const key of keys) {
362
+ const entry = entries.get(key);
363
+ if (!entry || typeof entry !== 'object') throw new Error(`plugin manifest has no ${key} artifact`);
364
+ validatePin(entry.immutable_url, entry.size, entry.sha256, `${key} artifact`, pin.injected, 32 * 1024 * 1024);
365
+ if (typeof entry.archive !== 'string' || !entry.archive.endsWith('.tar.gz')) {
366
+ throw new Error(`${key} artifact format must be tar.gz`);
367
+ }
368
+ const archive = await fetchVerified(entry.immutable_url, entry.size, entry.sha256, `${key} artifact`);
369
+ const temporary = mkdtempSync(join(tmpdir(), 'cohesivity-plugin-'));
370
+ try {
371
+ const extracted = join(temporary, 'extracted');
372
+ mkdirSync(extracted, { mode: 0o700 });
373
+ extractTarGzSafely(archive, extracted);
374
+ result.set(key, { root: extracted, temporary });
375
+ } catch (error) {
376
+ rmSync(temporary, { recursive: true, force: true });
377
+ throw error;
378
+ }
379
+ }
380
+ return result;
381
+ } catch (error) {
382
+ for (const artifact of result.values()) rmSync(artifact.temporary, { recursive: true, force: true });
383
+ throw error;
384
+ }
385
+ }
386
+
387
+ function validatePin(url, bytes, sha256, label, injected, maximumBytes) {
388
+ let parsed;
389
+ try { parsed = new URL(url); } catch { throw new Error(`${label} URL is invalid`); }
390
+ if ((!injected && parsed.protocol !== 'https:') || (injected && !['http:', 'https:'].includes(parsed.protocol))) {
391
+ throw new Error(`${label} URL must use HTTPS`);
392
+ }
393
+ if (!Number.isSafeInteger(bytes) || bytes <= 0 || bytes > maximumBytes) throw new Error(`${label} byte-size pin is invalid`);
394
+ if (!/^[0-9a-f]{64}$/.test(String(sha256))) throw new Error(`${label} SHA-256 pin is invalid`);
395
+ }
396
+
397
+ async function fetchVerified(url, expectedBytes, expectedSha256, label) {
398
+ const res = await fetch(url, { headers: { 'User-Agent': UA } });
399
+ if (!res.ok) throw new Error(`${label} returned HTTP ${res.status}`);
400
+ const claimed = res.headers?.get?.('content-length');
401
+ if (claimed !== null && claimed !== undefined && /^\d+$/.test(claimed) && Number(claimed) !== expectedBytes) {
402
+ throw new Error(`${label} Content-Length ${claimed} does not match pinned ${expectedBytes}`);
403
+ }
404
+ const bytes = Buffer.from(await res.arrayBuffer());
405
+ if (bytes.length !== expectedBytes) throw new Error(`${label} byte size ${bytes.length} does not match pinned ${expectedBytes}`);
406
+ const digest = createHash('sha256').update(bytes).digest('hex');
407
+ if (digest !== expectedSha256) throw new Error(`${label} SHA-256 does not match its pin`);
408
+ return bytes;
409
+ }
410
+
411
+ function extractTarGzSafely(archive, destination) {
412
+ let tar;
413
+ try { tar = gunzipSync(archive, { maxOutputLength: 64 * 1024 * 1024 }); }
414
+ catch (error) { throw new Error(`artifact is not a safe gzip archive (${error.message})`); }
415
+ let offset = 0; let entries = 0; let ended = false;
416
+ const seenPaths = new Set();
417
+ while (offset + 512 <= tar.length) {
418
+ const header = tar.subarray(offset, offset + 512);
419
+ offset += 512;
420
+ if (header.every((byte) => byte === 0)) { ended = true; break; }
421
+ if (++entries > 2048) throw new Error('artifact contains too many entries');
422
+ validateTarChecksum(header);
423
+ const name = tarString(header, 0, 100);
424
+ const prefix = tarString(header, 345, 155);
425
+ const path = validateArchivePath(prefix ? `${prefix}/${name}` : name, true);
426
+ const type = String.fromCharCode(header[156] || 48);
427
+ const size = tarOctal(header, 124, 12, 'size');
428
+ if (size > 32 * 1024 * 1024 || offset + size > tar.length) throw new Error(`artifact entry ${path} has an invalid size`);
429
+ if (path === '.') {
430
+ if (type !== '5' || size !== 0) throw new Error('artifact root entry is not a directory');
431
+ if (seenPaths.has(path)) throw new Error(`artifact path ${path} is duplicated`);
432
+ seenPaths.add(path);
433
+ continue;
168
434
  }
435
+ if (seenPaths.has(path)) throw new Error(`artifact path ${path} is duplicated`);
436
+ seenPaths.add(path);
437
+ const target = resolveInside(destination, path);
438
+ if (type === '5') {
439
+ if (size !== 0) throw new Error(`artifact directory ${path} has data`);
440
+ if (existsSync(target) && !lstatSync(target).isDirectory()) throw new Error(`artifact path ${path} is duplicated`);
441
+ mkdirSync(target, { recursive: true, mode: 0o700 });
442
+ } else if (type === '0') {
443
+ if (existsSync(target)) throw new Error(`artifact path ${path} is duplicated`);
444
+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 });
445
+ const mode = tarOctal(header, 100, 8, 'mode');
446
+ writeFileSync(target, tar.subarray(offset, offset + size), { flag: 'wx', mode: 0o600 | (mode & 0o111) });
447
+ } else if (type === '1' || type === '2') {
448
+ throw new Error(`artifact link ${path} is not allowed`);
449
+ } else {
450
+ throw new Error(`artifact special entry ${path} (type ${JSON.stringify(type)}) is not allowed`);
451
+ }
452
+ offset += Math.ceil(size / 512) * 512;
453
+ }
454
+ if (!ended) throw new Error('artifact tar is truncated or has no end marker');
455
+ }
456
+
457
+ function tarString(header, start, length) {
458
+ const end = header.indexOf(0, start);
459
+ return header.toString('utf8', start, end >= start && end < start + length ? end : start + length);
460
+ }
461
+
462
+ function tarOctal(header, start, length, field) {
463
+ const value = tarString(header, start, length).trim().replace(/\0/g, '');
464
+ if (!/^[0-7]*$/.test(value)) throw new Error(`artifact tar ${field} is invalid`);
465
+ const parsed = value ? Number.parseInt(value, 8) : 0;
466
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error(`artifact tar ${field} is invalid`);
467
+ return parsed;
468
+ }
469
+
470
+ function validateTarChecksum(header) {
471
+ const expected = tarOctal(header, 148, 8, 'checksum');
472
+ let actual = 0;
473
+ for (let i = 0; i < header.length; i++) actual += i >= 148 && i < 156 ? 32 : header[i];
474
+ if (actual !== expected) throw new Error('artifact tar header checksum is invalid');
475
+ }
476
+
477
+ function validateArchivePath(value, allowDot) {
478
+ if (typeof value !== 'string' || value.includes('\0') || value.includes('\\') || isAbsolute(value) || /^[A-Za-z]:/.test(value)) {
479
+ throw new Error(`artifact path ${JSON.stringify(value)} is unsafe`);
480
+ }
481
+ const rawParts = value.split('/').filter((part) => part !== '');
482
+ if (rawParts.some((part) => part === '..')) throw new Error(`artifact path ${JSON.stringify(value)} is unsafe`);
483
+ const parts = rawParts.filter((part) => part !== '.');
484
+ if (!parts.length) {
485
+ if (allowDot && rawParts.every((part) => part === '.')) return '.';
486
+ throw new Error(`artifact path ${JSON.stringify(value)} is unsafe`);
487
+ }
488
+ return parts.join('/');
489
+ }
490
+
491
+ function resolveInside(root, path) {
492
+ const target = resolve(root, ...path.split('/'));
493
+ const rel = relative(resolve(root), target);
494
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error(`artifact path ${JSON.stringify(path)} escapes extraction root`);
495
+ return target;
496
+ }
497
+
498
+ async function installForClient(client, artifact) {
499
+ if (!artifact) throw new Error(`verified ${client.artifact} artifact is unavailable`);
500
+ const root = artifact.root;
501
+ switch (client.id) {
502
+ case 'claude':
503
+ requireClientCli(client);
504
+ runNative(client.bin, ['plugin', 'marketplace', 'add', root, '--scope', 'user']);
505
+ runNative(client.bin, ['plugin', 'install', 'cohesivity@cohesivity', '--scope', 'user']);
506
+ break;
507
+ case 'cursor':
508
+ installDirectoryAtomically(root, join(HOME, '.cursor', 'plugins', 'local', 'cohesivity'));
509
+ break;
510
+ case 'codex':
511
+ requireClientCli(client);
512
+ runNative(client.bin, ['plugin', 'marketplace', 'add', root]);
513
+ runNative(client.bin, ['plugin', 'add', 'cohesivity@cohesivity']);
514
+ break;
515
+ case 'gemini':
516
+ requireClientCli(client);
517
+ runNative(client.bin, ['extensions', 'install', root, '--consent']);
518
+ break;
519
+ case 'antigravity':
520
+ if (client.bin) runNative(client.bin, ['plugin', 'install', root]);
521
+ else if (hasAny(POSITIVE_ANTIGRAVITY_HOMES)) {
522
+ installDirectoryAtomically(root, join(HOME, '.gemini', 'config', 'plugins', 'cohesivity'));
523
+ } else throw new Error('Antigravity CLI is not on PATH and no positive Antigravity home was found');
524
+ break;
525
+ case 'openclaw':
526
+ requireClientCli(client);
527
+ runNative(client.bin, ['plugins', 'install', root, '--force']);
528
+ runNative(client.bin, ['plugins', 'enable', 'cohesivity']);
529
+ break;
530
+ case 'hermes':
531
+ installDirectoryAtomically(root, join(HOME, '.hermes', 'plugins', 'cohesivity'));
532
+ requireClientCli(client);
533
+ runNative(client.bin, ['plugins', 'enable', 'cohesivity']);
534
+ break;
535
+ default:
536
+ throw new Error(`unknown client ${client.id}`);
537
+ }
538
+ }
539
+
540
+ function requireClientCli(client) {
541
+ if (!client.bin) throw new Error('client state exists but its native CLI is not on PATH');
542
+ }
543
+
544
+ function runNative(command, args) {
545
+ const result = spawnSync(command, args, { cwd: CWD, encoding: 'utf8', env: process.env, shell: false, timeout: 120000 });
546
+ if (result.error) throw new Error(`${formatCommand(command, args)} failed (${result.error.message})`);
547
+ if (result.status !== 0) {
548
+ const detail = String(result.stderr || result.stdout || '').trim().replace(/\s+/g, ' ').slice(0, 300);
549
+ throw new Error(`${formatCommand(command, args)} exited ${result.status}${detail ? `: ${detail}` : ''}`);
550
+ }
551
+ }
552
+
553
+ function installDirectoryAtomically(source, destination) {
554
+ const parent = dirname(destination);
555
+ mkdirSync(parent, { recursive: true, mode: 0o700 });
556
+ const stage = join(parent, `.${destination.split(/[\\/]/).pop()}.stage-${process.pid}-${Date.now()}`);
557
+ const backup = join(parent, `.${destination.split(/[\\/]/).pop()}.backup-${process.pid}-${Date.now()}`);
558
+ let backedUp = false;
559
+ try {
560
+ copyVerifiedDirectory(source, stage);
561
+ if (existsSync(destination)) { renameSync(destination, backup); backedUp = true; }
562
+ renameSync(stage, destination);
563
+ if (backedUp) { rmSync(backup, { recursive: true, force: true }); backedUp = false; }
564
+ } catch (error) {
565
+ rmSync(stage, { recursive: true, force: true });
566
+ if (backedUp && !existsSync(destination)) { renameSync(backup, destination); backedUp = false; }
567
+ throw error;
568
+ } finally {
569
+ if (!backedUp) rmSync(backup, { recursive: true, force: true });
570
+ }
571
+ }
572
+
573
+ function copyVerifiedDirectory(source, destination) {
574
+ const stat = lstatSync(source);
575
+ if (!stat.isDirectory()) throw new Error(`verified plugin root ${source} is not a directory`);
576
+ mkdirSync(destination, { mode: 0o700 });
577
+ for (const entry of readdirSync(source)) {
578
+ const from = join(source, entry); const to = join(destination, entry);
579
+ const child = lstatSync(from);
580
+ if (child.isSymbolicLink()) throw new Error(`verified plugin contains a link at ${from}`);
581
+ if (child.isDirectory()) copyVerifiedDirectory(from, to);
582
+ else if (child.isFile()) writeFileSync(to, readFileSync(from), { flag: 'wx', mode: 0o600 | (child.mode & 0o111) });
583
+ else throw new Error(`verified plugin contains a special file at ${from}`);
584
+ }
585
+ }
586
+
587
+ function installFileAtomically(file, body) {
588
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
589
+ const temporary = join(dirname(file), `.${file.split(/[\\/]/).pop()}.tmp-${process.pid}-${Date.now()}`);
590
+ try {
591
+ writeFileSync(temporary, body, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
592
+ renameSync(temporary, file);
593
+ } finally {
594
+ rmSync(temporary, { force: true });
169
595
  }
170
- if (!DRY) log(`skill added=${installed} updated=${updated} current=${current} (version ${liveVer})`);
171
596
  }
172
597
 
598
+ function describeDryRunPluginDelivery(clients) {
599
+ const pin = manifestPin();
600
+ act(`fetch and validate plugin manifest ${pin.manifestUrl} (bytes=${pin.manifestBytes}, sha256=${pin.manifestSha256})`);
601
+ for (const key of new Set(clients.map((client) => client.artifact))) {
602
+ act(`fetch, byte-size/SHA-256 validate, and safely extract artifact ${key} from the verified manifest`);
603
+ }
604
+ for (const client of clients) {
605
+ const root = `<verified:${client.artifact}>`;
606
+ if (client.id === 'claude') {
607
+ act(`run ${formatCommand(client.bin || 'claude', ['plugin', 'marketplace', 'add', root, '--scope', 'user'])}`);
608
+ act(`run ${formatCommand(client.bin || 'claude', ['plugin', 'install', 'cohesivity@cohesivity', '--scope', 'user'])}`);
609
+ } else if (client.id === 'cursor') {
610
+ act(`atomically replace ${displayPath(join(HOME, '.cursor', 'plugins', 'local', 'cohesivity'))} from ${root}`);
611
+ } else if (client.id === 'codex') {
612
+ act(`run ${formatCommand(client.bin || 'codex', ['plugin', 'marketplace', 'add', root])}`);
613
+ act(`run ${formatCommand(client.bin || 'codex', ['plugin', 'add', 'cohesivity@cohesivity'])}`);
614
+ } else if (client.id === 'gemini') {
615
+ act(`run ${formatCommand(client.bin || 'gemini', ['extensions', 'install', root, '--consent'])}`);
616
+ } else if (client.id === 'antigravity' && client.bin) {
617
+ act(`run ${formatCommand(client.bin, ['plugin', 'install', root])}`);
618
+ } else if (client.id === 'antigravity') {
619
+ act(`atomically replace ${displayPath(join(HOME, '.gemini', 'config', 'plugins', 'cohesivity'))} from ${root}`);
620
+ } else if (client.id === 'openclaw') {
621
+ act(`run ${formatCommand(client.bin || 'openclaw', ['plugins', 'install', root, '--force'])}`);
622
+ act(`run ${formatCommand(client.bin || 'openclaw', ['plugins', 'enable', 'cohesivity'])}`);
623
+ } else if (client.id === 'hermes') {
624
+ act(`atomically replace ${displayPath(join(HOME, '.hermes', 'plugins', 'cohesivity'))} from ${root}`);
625
+ act(`run ${formatCommand(client.bin || 'hermes', ['plugins', 'enable', 'cohesivity'])}`);
626
+ }
627
+ }
628
+ }
629
+
630
+ function printClientInstructions(clients, adapters) {
631
+ if (!clients.length && !adapters.length) return;
632
+ console.log('');
633
+ log('restart/authentication steps (the installer does not open a browser or start OAuth):');
634
+ for (const client of clients) {
635
+ const instruction = {
636
+ claude: 'Claude: start a new session (or /reload-plugins), then authenticate Cohesivity from /mcp if prompted.',
637
+ cursor: 'Cursor: run Developer: Reload Window, then authenticate Cohesivity in Customize > MCP if prompted.',
638
+ codex: 'Codex: start a new session, open /plugins, and complete Cohesivity authentication if prompted.',
639
+ gemini: 'Gemini: restart the CLI, then run /mcp auth cohesivity if authentication is required.',
640
+ antigravity: 'Antigravity: restart, open /mcp (or Installed MCP Servers), and authenticate Cohesivity.',
641
+ openclaw: 'OpenClaw: restart the Gateway if it did not auto-restart, then run openclaw mcp login cohesivity.',
642
+ hermes: 'Hermes: restart, then run hermes mcp login cohesivity from a fresh terminal. OAuth works only when the endpoint supports Dynamic Client Registration; otherwise Hermes needs a pre-registered OAuth client.',
643
+ }[client.id];
644
+ console.log(` - ${instruction}`);
645
+ }
646
+ for (const adapter of adapters) console.log(` - ${adapter.name}: restart the client and authenticate the Cohesivity MCP server when prompted.`);
647
+ }
648
+
649
+ function displayPath(path) { return path.startsWith(HOME + sep) ? `~${path.slice(HOME.length)}` : path; }
650
+ function formatCommand(command, args) { return [command, ...args].map((arg) => /^[A-Za-z0-9_@%+=:,./~<>-]+$/.test(arg) ? arg : JSON.stringify(arg)).join(' '); }
651
+
173
652
  // ── 2) create or reuse the project tenant ─────────────────────────────────────
174
653
  async function ensureTenant() {
175
654
  const dotfile = join(CWD, '.cohesivity');
176
- if (existsSync(dotfile) && readFileSync(dotfile, 'utf8').includes('coh_management_key=')) {
655
+ if (existsSync(dotfile)) {
656
+ const existing = readFileSync(dotfile, 'utf8');
657
+ if (!DRY) ensureGitignore();
658
+ if (!validTenantCredentials(existing, false)) {
659
+ throw new Error('existing .cohesivity is incomplete; repair or remove it before retrying');
660
+ }
661
+ if (DRY) act('ensure .cohesivity is listed in .gitignore');
177
662
  log('reusing existing .cohesivity (no new tenant created)');
178
663
  return;
179
664
  }
180
665
  if (DRY) { act(`create a tenant: POST ${BASE}/api/genesis -> ./.cohesivity (+ .gitignore)`); return; }
666
+ ensureGitignore();
181
667
  const machineId = readMachineId();
182
668
  let body;
183
669
  let issuedMachineId = null;
@@ -186,21 +672,19 @@ async function ensureTenant() {
186
672
  if (machineId) headers[MACHINE_ID_HEADER] = machineId;
187
673
  const res = await fetch(`${BASE}/api/genesis`, { method: 'POST', headers });
188
674
  body = await res.text();
675
+ if (!res.ok) throw new Error(`genesis returned HTTP ${res.status}`);
189
676
  // Returned on any request that MINTED an id, which is when we sent none
190
677
  // *or* when the id we sent no longer verifies (secret rotated, file
191
678
  // corrupted). It is not "non-null exactly when we sent none" — assuming
192
679
  // that is what left a machine pinned to a dead id forever.
193
680
  issuedMachineId = res.headers.get(MACHINE_ID_HEADER);
194
681
  } catch (e) {
195
- log(`no tenant created (network: ${e.message}). Re-run to retry. The command is idempotent.`);
196
- return;
682
+ throw new Error(`no tenant created (${e.message}). Re-run to retry; the command is idempotent`);
197
683
  }
198
- if (!body.includes('coh_management_key=')) {
199
- log('no tenant created (likely the 10/60s rate limit). Re-run shortly. The command is idempotent.');
200
- return;
684
+ if (!validTenantCredentials(body, true)) {
685
+ throw new Error('genesis returned an incomplete credential response; no project credentials were installed');
201
686
  }
202
- writeFileSync(dotfile, body);
203
- ensureGitignore();
687
+ installCredentialsAtomically(dotfile, body);
204
688
  // Store whatever the server issued. Its presence already means "we minted
205
689
  // this for you", so gating on `!machineId` as well dropped every replacement
206
690
  // a machine with a stale id was handed: it re-minted on every genesis, kept
@@ -209,6 +693,35 @@ async function ensureTenant() {
209
693
  log('created an ephemeral tenant -> ./.cohesivity');
210
694
  }
211
695
 
696
+ function credentialValue(body, name) {
697
+ const match = String(body).match(new RegExp(`^${name}=([^\\r\\n]+)$`, 'm'));
698
+ return match?.[1]?.trim() || null;
699
+ }
700
+
701
+ function validTenantCredentials(body, requireBootstrapMetadata) {
702
+ const tenantId = credentialValue(body, 'tenant_id');
703
+ const managementKey = credentialValue(body, 'coh_management_key');
704
+ const applicationKey = credentialValue(body, 'coh_application_key');
705
+ if (!tenantId || !managementKey?.startsWith('coh_man_') || !applicationKey?.startsWith('coh_app_')) return false;
706
+ if (!requireBootstrapMetadata) return true;
707
+ const expiresAt = credentialValue(body, 'expires_at');
708
+ const lifecycle = credentialValue(body, 'tenant_lifecycle');
709
+ const runtimeProfile = credentialValue(body, 'runtime_profile');
710
+ return Boolean(expiresAt && Number.isFinite(Date.parse(expiresAt))
711
+ && (lifecycle === 'ephemeral' || lifecycle === 'claimed')
712
+ && /^v1-[0-9]+$/.test(runtimeProfile || ''));
713
+ }
714
+
715
+ function installCredentialsAtomically(dotfile, body) {
716
+ const temporary = join(CWD, `.cohesivity.tmp-${process.pid}-${Date.now()}`);
717
+ try {
718
+ writeFileSync(temporary, body, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
719
+ renameSync(temporary, dotfile);
720
+ } finally {
721
+ rmSync(temporary, { force: true });
722
+ }
723
+ }
724
+
212
725
  // Read the machine id, or null when this machine has none. Every failure —
213
726
  // missing file, unreadable dir, garbage contents — reads as "none", which just
214
727
  // means the next genesis call is issued a fresh id.
@@ -242,7 +755,7 @@ function ensureGitignore() {
242
755
  }
243
756
  }
244
757
 
245
- // ── 3) add a descriptive pointer to an existing AGENTS.md / CLAUDE.md ──────────
758
+ // ── 3) add a descriptive pointer to an existing AGENTS.md / CLAUDE.md / README ─
246
759
  // Describe the platform. Never command the agent. The line states a fact: this
247
760
  // project uses Cohesivity, and the state lives here. Auth stays in .cohesivity
248
761
  // and the skill. An agent without the skill still learns the project uses
@@ -251,13 +764,31 @@ const AGENTS_LINE =
251
764
  `This project uses [Cohesivity](https://cohesivity.ai) for its managed backend. ` +
252
765
  `Credentials and tenant state live in \`.cohesivity\`. Live status is at \`GET ${BASE}/api/status\`.`;
253
766
 
254
- function augmentAgentsFile() {
255
- // Only touch files that already exist. Never create an agent file unprompted.
256
- const targets = ['AGENTS.md', 'CLAUDE.md'].map((f) => join(CWD, f)).filter(existsSync);
257
- if (!targets.length) { log('no AGENTS.md / CLAUDE.md present. Skipping (nothing created)'); return; }
258
- for (const file of targets) {
767
+ // The README is read by whoever opens the repo cold, which is a different
768
+ // audience from an agent already working here: it has no skill installed and no
769
+ // reason yet to trust a dotfile it does not recognise. So this line points at
770
+ // the status endpoint and the docs rather than at .cohesivity. The URL is the
771
+ // public docs page and stays absolute — unlike the API base, it is not
772
+ // something a --base override should repoint.
773
+ const README_LINE =
774
+ `If you are another agent who just picked up this project, you can get the status of its backend ` +
775
+ `using the status endpoint, read more at https://cohesivity.ai/backend-for-ai-agents`;
776
+
777
+ const POINTER_FILES = [
778
+ ['AGENTS.md', AGENTS_LINE],
779
+ ['CLAUDE.md', AGENTS_LINE],
780
+ ['README.md', README_LINE],
781
+ ];
782
+
783
+ function augmentProjectFiles() {
784
+ // Only touch files that already exist. Never create one unprompted.
785
+ const targets = POINTER_FILES
786
+ .map(([name, line]) => [join(CWD, name), line])
787
+ .filter(([file]) => existsSync(file));
788
+ if (!targets.length) { log('no AGENTS.md / CLAUDE.md / README.md present. Skipping (nothing created)'); return; }
789
+ for (const [file, line] of targets) {
259
790
  if (DRY) { act(`add a Cohesivity managed block to ${rel(file)}`); continue; }
260
- upsertManagedBlock(file, AGENTS_LINE);
791
+ upsertManagedBlock(file, line);
261
792
  log(`updated ${rel(file)}`);
262
793
  }
263
794
  }
@@ -275,18 +806,27 @@ function upsertManagedBlock(file, inner) {
275
806
  }
276
807
 
277
808
  // ── ground the session with the result and next steps ─────────────────────────
278
- function ground() {
809
+ function ground(deliveryFailures) {
279
810
  const dotfile = join(CWD, '.cohesivity');
280
811
  const tid = existsSync(dotfile) ? (readFileSync(dotfile, 'utf8').match(/^tenant_id=(.+)$/m) || [])[1] || '' : '';
281
812
  console.log('');
282
- log(tid ? `ready. tenant ${tid}` : 'ready');
813
+ if (deliveryFailures.length) log(tid ? `tenant ${tid} is ready, but client delivery is incomplete` : 'tenant bootstrap is ready, but client delivery is incomplete');
814
+ else log(tid ? `ready. tenant ${tid}` : 'ready');
283
815
  console.log(` - Keys are in .cohesivity (gitignored, do not commit).`);
284
816
  console.log(` - Provision a service: POST ${BASE}/api/resources/<name> (Authorization: Bearer <coh_management_key>)`);
285
817
  console.log(` - Per-service docs: ${BASE}/offerings/<name> \u00b7 full reference: ${BASE}/llms.txt`);
286
- console.log(' - The skill is set up for future sessions. Claude Code auto-loads it if ~/.claude/skills already existed, otherwise restart; Cursor and Codex pick it up on reload/restart.');
818
+ if (NO_PLUGIN) {
819
+ console.log(` - Only the standalone skill was installed at ${displayPath(CANONICAL_SKILL_DIR)}; no plugin or MCP configuration was added.`);
820
+ } else if (deliveryFailures.length) {
821
+ console.log(' - Retry after correcting the delivery errors above; tenant bootstrap is idempotent.');
822
+ } else {
823
+ console.log(' - Detected client integrations are installed. Follow the restart/authentication steps above.');
824
+ }
287
825
  }
288
826
 
289
- function versionOf(md) { return (md.match(/^version:\s*(.+)$/m) || [])[1]?.trim() || null; }
827
+ function versionOf(md) {
828
+ return (md.match(/^metadata:\s*\n(?:[ \t]+[^\n]*\n)*?[ \t]+version:\s*["']?([0-9a-f]{12})["']?\s*$/m) || [])[1] || null;
829
+ }
290
830
 
291
831
  function help() {
292
832
  console.log(`
@@ -296,17 +836,29 @@ Usage:
296
836
  npx @cohesivity/init [options]
297
837
 
298
838
  Options:
299
- --runtime <name> explicit harness label override (normally measured from
300
- the process ancestry; use only when the measurement is wrong)
301
- --dry-run print what would happen. Make no changes
302
- --base <url> API base (default https://cohesivity.ai)
303
- -h, --help show this help
839
+ --runtime <name> explicit harness label override (normally measured from
840
+ the process ancestry; use only when the measurement is wrong)
841
+ --no-plugin install only the canonical standalone skill; add no plugin or MCP
842
+ --dry-run print what would happen. Make no changes
843
+ --base <url> API base (default https://cohesivity.ai)
844
+ -h, --help show this help
304
845
 
305
846
  What it does:
306
- 1. Installs the Cohesivity agent skill into every known agent skill dir
307
- whose harness is present on this machine
847
+ 1. Detects Claude, Cursor, Codex, Gemini, Antigravity, OpenClaw, and Hermes
848
+ independently and installs each client's native or portable plugin package
849
+ (known adapters without a plugin receive the standalone skill plus MCP)
308
850
  2. Creates or reuses a project tenant -> ./.cohesivity (gitignored)
309
- 3. Adds a descriptive pointer to an existing AGENTS.md / CLAUDE.md
851
+ 3. Adds a descriptive pointer to an existing AGENTS.md / CLAUDE.md / README.md
852
+ (never creates any of them)
853
+
854
+ With --no-plugin, step 1 installs only ~/.agents/skills/cohesivity/SKILL.md.
855
+ It adds no plugin or MCP. Steps 2 and 3, including machine attribution and
856
+ existing project-pointer behavior, are unchanged.
857
+
858
+ Plugin supply chain: a pinned immutable manifest supplies every artifact URL,
859
+ byte size, SHA-256, archive format, and package root. Archives are verified,
860
+ safely extracted without links/traversal/special files, and portable installs
861
+ are replaced atomically. Native client commands are invoked without a shell.
310
862
 
311
863
  Attribution: the tenant-creation call carries a User-Agent of the shape
312
864
  {npx:<harness>}, where the harness is measured from this process's own
@@ -314,3 +866,5 @@ parents. Nothing else about your machine is read or sent, and anything not
314
866
  inferable is sent as "none".
315
867
  `);
316
868
  }
869
+
870
+ main().catch((e) => { console.error(`cohesivity: setup failed: ${e.message}`); process.exit(1); });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cohesivity/init",
3
- "version": "0.4.1",
3
+ "version": "0.6.0",
4
4
  "description": "Set up Cohesivity in a project: install the agent skill, create a managed backend tenant, write the project config. Run with `npx @cohesivity/init`.",
5
5
  "type": "module",
6
6
  "bin": {