@cohesivity/init 0.5.0 → 0.6.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.
Files changed (3) hide show
  1. package/README.md +154 -20
  2. package/bin/cli.js +618 -76
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,43 +1,177 @@
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`, `CLAUDE.md`, or `README.md`, so whoever opens this project later — a person or another agent — knows it uses Cohesivity and where to check its backend. It only touches a file that is already there, and creates nothing on its own. The pointer sits between `<!-- BEGIN:cohesivity -->` and `<!-- END:cohesivity -->` markers; delete the block and it will be written again on the next run.
14
+ ## Client delivery
14
15
 
15
- It writes nothing else.
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
+ These checks apply to the decoded response bytes: HTTP transfer `Content-Length`
66
+ can describe compressed bytes and is not used as a decoded-size claim. Reads
67
+ stop as soon as decoded content exceeds its pin, before hashing or parsing.
68
+ The manifest schema is:
69
+
70
+ ```json
71
+ {
72
+ "schema_version": 1,
73
+ "version": "2.1.1",
74
+ "packages": [
75
+ {
76
+ "client": "portable",
77
+ "immutable_url": "https://immutable.example/portable.tar.gz",
78
+ "size": 1234,
79
+ "sha256": "64 lowercase hexadecimal characters",
80
+ "archive": "cohesivity-portable-2.1.1.tar.gz"
81
+ }
82
+ ]
83
+ }
25
84
  ```
26
85
 
86
+ The installer maps Claude to `claude`; Cursor, OpenClaw, and Hermes to
87
+ `portable`; Codex to `codex`; Gemini to `gemini`; and Antigravity to
88
+ `antigravity`. The 2.1.1 manifest also carries the direct `openai` package,
89
+ which this marketplace-based Codex installer does not select. Extraction
90
+ rejects absolute paths, traversal, links, duplicate paths, special files,
91
+ malformed headers, oversized content, and archives without an end marker.
92
+ Staged portable installs replace the previous directory atomically, with
93
+ rollback if the commit fails.
94
+
95
+ The immutable manifest commit, byte size, and SHA-256 are isolated in the
96
+ `PLUGIN_RELEASE` block in `bin/cli.js`. Tests use the
97
+ `COHESIVITY_PLUGIN_MANIFEST_PIN` injection hook with local, fully pinned
98
+ fixtures; normal users should not set it.
99
+
100
+ ## Tenant bootstrap and failure behavior
101
+
102
+ After client delivery, the command:
103
+
104
+ 1. Ensures `.cohesivity` is ignored before requesting credentials.
105
+ 2. Creates a tenant with `POST /api/genesis`, or validates and reuses an
106
+ existing `.cohesivity`.
107
+ 3. Atomically installs complete credentials only after validating the tenant,
108
+ management key, application key, expiry, lifecycle, and runtime profile.
109
+ 4. Stores a server-issued opaque setup identifier at
110
+ `~/.config/cohesivity/machine-id` so tenants created by one setup can be
111
+ grouped.
112
+ 5. Adds or updates a managed Cohesivity block in existing `AGENTS.md`,
113
+ `CLAUDE.md`, and `README.md` files. It never creates those files.
114
+
115
+ A plugin download, verification, extraction, copy, or native-command failure
116
+ does not skip tenant bootstrap. The command still completes the idempotent
117
+ tenant flow and project pointers, then exits nonzero, identifies every failed
118
+ delivery, and says installation is incomplete. It never prints the normal
119
+ complete-installation message in that state.
120
+
121
+ Tenant failures remain fail-closed. Network, HTTP, incomplete-response,
122
+ credential-validation, and ignore-write failures exit nonzero without project
123
+ pointers or a false success message. Existing incomplete credentials are never
124
+ overwritten.
125
+
126
+ ## Dry run
127
+
128
+ `--dry-run` has zero side effects. It performs no fetch, tenant request, native
129
+ command, directory creation, file write, OAuth, or browser action. It detects
130
+ clients using filesystem/PATH reads and prints the exact manifest checks,
131
+ artifact checks, native argument-vector commands, atomic destinations, tenant
132
+ request, and project-pointer changes it would perform.
133
+
134
+ ## Attribution and privacy
135
+
136
+ The tenant request identifies the coding agent that launched the command. The
137
+ installer walks only its own parent-process lineage and sends one sanitized name
138
+ as `{npx:<name>}`. If it cannot infer a name, it sends `{npx:none}`. `--runtime`
139
+ overrides that label when measurement is wrong.
140
+
141
+ It never enumerates the system process table: no session logs, conversations,
142
+ or model settings are read, nor files outside the documented client homes,
143
+ project bootstrap files, and machine-id path. The machine id is opaque,
144
+ server-issued, and not derived from hardware or user data. Delete
145
+ `~/.config/cohesivity/machine-id` to end that association.
146
+
27
147
  ## Options
28
148
 
29
149
  | flag | effect |
30
150
  | --- | --- |
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`) |
151
+ | `--runtime <name>` | override the measured harness label |
152
+ | `--no-plugin` | install only the canonical standalone skill; add no plugin or MCP |
153
+ | `--dry-run` | print exact actions with zero side effects |
154
+ | `--base <url>` | API base for tenant bootstrap (default `https://cohesivity.ai`) |
155
+ | `-h`, `--help` | show command help and the exact package version |
156
+
157
+ ## 0.6.1 verification fixes
34
158
 
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.
159
+ Version 0.6.1 accepts an immutable manifest when Node has transparently decoded
160
+ its gzip transfer and the decoded bytes match the size and SHA-256 pins. It
161
+ still rejects decoded oversize, size mismatch, and hash mismatch, pins the final
162
+ Cohesivity plugin 2.1.1 manifest, and makes `--help` identify the exact
163
+ CLI/package version.
164
+
165
+ ## Verifying the release
36
166
 
37
- ## Requirements
167
+ Every npm version publishes from this repository through npm Trusted Publishing
168
+ with provenance:
38
169
 
39
- Node.js 18+ for the built-in `fetch`. Zero dependencies.
170
+ ```bash
171
+ npm audit signatures
172
+ ```
40
173
 
41
- ## Docs
174
+ Node.js 18+ is required for built-in `fetch`. The package has zero dependencies
175
+ and no `postinstall` hook.
42
176
 
43
- <https://cohesivity.ai/llms.txt>
177
+ Full product documentation: <https://cohesivity.ai/llms.txt>
package/bin/cli.js CHANGED
@@ -10,14 +10,18 @@
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
18
  * 3. If AGENTS.md, CLAUDE.md, or README.md already exists, add a descriptive
19
19
  * pointer to it.
20
20
  *
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
+ *
21
25
  * It writes nothing else, and it creates none of those three files. The pointer
22
26
  * is descriptive rather than promotional — it states where this project's
23
27
  * backend state lives, which is what makes it worth carrying in a repo someone
@@ -26,21 +30,40 @@
26
30
  * The first line is the shebang. It tells npx to run this file as a program.
27
31
  */
28
32
 
29
- import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
30
- import { execSync } from 'node:child_process';
31
- import { homedir } from 'node:os';
32
- 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';
33
42
 
34
43
  // ── args ────────────────────────────────────────────────────────────────────
35
44
  const argv = process.argv.slice(2);
36
45
  const has = (f) => argv.includes(f);
37
46
  const flag = (f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : undefined; };
47
+ const PKG_VERSION = '0.6.1';
48
+
49
+ function validateArgs() {
50
+ const switches = new Set(['--dry-run', '--no-plugin', '--no-branding', '--help', '-h']);
51
+ const values = new Set(['--runtime', '--base']);
52
+ for (let i = 0; i < argv.length; i++) {
53
+ if (switches.has(argv[i])) continue;
54
+ if (values.has(argv[i])) {
55
+ if (!argv[i + 1] || argv[i + 1].startsWith('-')) throw new Error(`${argv[i]} requires a value`);
56
+ i++; continue;
57
+ }
58
+ throw new Error(`unknown option ${argv[i]}`);
59
+ }
60
+ }
38
61
 
39
62
  if (has('--help') || has('-h')) { help(); process.exit(0); }
40
63
 
41
64
  // ── config ──────────────────────────────────────────────────────────────────
42
- const PKG_VERSION = '0.5.0';
43
65
  const BASE = (flag('--base') || process.env.COHESIVITY_BASE || 'https://cohesivity.ai').replace(/\/+$/, '');
66
+ const MCP_URL = 'https://cohesivity.ai/mcp/manage';
44
67
 
45
68
  // Machine id: one per machine, stored outside any project. A project's
46
69
  // .cohesivity is per project, so a machine that runs setup in several projects
@@ -55,9 +78,26 @@ const MACHINE_ID_FILE = join(MACHINE_ID_DIR, 'machine-id');
55
78
 
56
79
  // The skill is pinned to an immutable commit in the public, auditable repo.
57
80
  // Bumping the pin is a deliberate release step. See COH-172.
58
- const SKILL_PIN = '6c4c04d94d344590f6732763f0116b155a32753c';
81
+ const SKILL_PIN = 'f97e0d2ac8a653b7d54d1bb6e70aee78a8887e60';
59
82
  const SKILL_URL = `https://raw.githubusercontent.com/cohesivity-org/cohesivity-skill/${SKILL_PIN}/cohesivity.skill.md`;
60
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/e30d49df188184b9ee4b477210a3a4fdcca47f85/artifacts/v2.1.1/install-manifest.v1.json',
89
+ manifestBytes: 9610,
90
+ manifestSha256: 'a6be8cac99534be83e52b3c97a93bea5667c3458737eebc8d5c4bd5c44f953bb',
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
+
61
101
  // Harness: the nearest ancestor process that is not generic plumbing. Only
62
102
  // this process's own lineage is read — never the system process list — and only
63
103
  // the resulting name is sent. The sets below are closed lists of Unix plumbing,
@@ -86,8 +126,8 @@ function inferHarness() {
86
126
  ppid = Number(readFileSync(`/proc/${pid}/stat`, 'utf8').split(') ').pop().split(' ')[1]);
87
127
  } catch {
88
128
  try {
89
- argv = execSync(`ps -o args= -p ${pid}`, { timeout: 2000 }).toString().trim().split(/\s+/);
90
- 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());
91
131
  } catch { return null; }
92
132
  }
93
133
  let name = (argv[0] || '').split('/').pop().replace(/^-/, '');
@@ -105,6 +145,7 @@ function inferHarness() {
105
145
  }
106
146
 
107
147
  const DRY = has('--dry-run');
148
+ const NO_PLUGIN = has('--no-plugin');
108
149
 
109
150
  const CWD = process.cwd();
110
151
  const rel = (p) => p.replace(CWD + '/', '');
@@ -117,69 +158,521 @@ const EXPLICIT = String(flag('--runtime') || process.env.COHESIVITY_RUNTIME || '
117
158
  const HARNESS = EXPLICIT || inferHarness() || 'none';
118
159
  const UA = `{npx:${HARNESS}}`;
119
160
 
120
- main().catch((e) => { console.error(`cohesivity: unexpected error: ${e.message}`); process.exit(1); });
121
-
122
161
  async function main() {
162
+ validateArgs();
123
163
  console.log(`\ncohesivity/init v${PKG_VERSION}: setting up (harness: ${HARNESS})${DRY ? ' [dry-run: no changes]' : ''}\n`);
124
- await installSkill();
164
+ const deliveryFailures = NO_PLUGIN
165
+ ? await installStandaloneSkill()
166
+ : await installClientIntegrations();
125
167
  await ensureTenant();
126
168
  augmentProjectFiles();
127
- ground();
128
- }
129
-
130
- // ── 1) install the skill into the skill dirs present on this machine ─────────
131
- // Presence on disk is the measurement: each known agent skill dir is written
132
- // only when its harness home already exists. When none exist, the cross-tool
133
- // ~/.agents dir is the fallback so the skill lands somewhere.
134
- function skillDirs() {
135
- const codexHome = process.env.CODEX_HOME || join(homedir(), '.codex');
136
- const gated = [
137
- [join(homedir(), '.claude'), join(homedir(), '.claude', 'skills', 'cohesivity')],
138
- [join(homedir(), '.cursor'), join(homedir(), '.cursor', 'skills', 'cohesivity')],
139
- [codexHome, join(codexHome, 'skills', 'cohesivity')],
140
- [join(homedir(), '.agents'), join(homedir(), '.agents', 'skills', 'cohesivity')],
141
- ];
142
- const dirs = gated.filter(([home]) => existsSync(home)).map(([, dir]) => dir);
143
- return dirs.length ? dirs : [join(homedir(), '.agents', 'skills', 'cohesivity')];
144
- }
145
-
146
- async function installSkill() {
147
- let skill;
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; }
148
265
  try {
149
266
  const res = await fetch(SKILL_URL, { headers: { 'User-Agent': UA } });
150
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
151
- skill = await res.text();
152
- } catch (e) {
153
- log(`could not fetch the skill (${e.message}). Continuing. Docs: ${BASE}/llms.txt`);
154
- 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;
155
278
  }
156
- const liveVer = versionOf(skill) || 'unknown';
157
- let installed = 0; let updated = 0; let current = 0;
158
- for (const dir of skillDirs()) {
159
- const shown = dir.replace(homedir(), '~');
160
- const file = join(dir, 'SKILL.md');
161
- const cur = existsSync(file) ? versionOf(readFileSync(file, 'utf8')) : null;
162
- if (cur && cur === liveVer) { current++; continue; }
163
- if (DRY) { act(`install the skill (version ${liveVer}) -> ${shown}`); continue; }
164
- try {
165
- mkdirSync(dir, { recursive: true });
166
- writeFileSync(file, skill);
167
- if (cur) updated++; else installed++;
168
- } catch (e) {
169
- 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 chunks = [];
401
+ let length = 0;
402
+ const reader = res.body.getReader();
403
+ while (true) {
404
+ const { done, value } = await reader.read();
405
+ if (done) break;
406
+ length += value.byteLength;
407
+ if (length > expectedBytes) {
408
+ try { await reader.cancel(); } catch {}
409
+ throw new Error(`${label} byte size ${length} exceeds pinned ${expectedBytes}`);
170
410
  }
411
+ chunks.push(Buffer.from(value));
171
412
  }
172
- if (!DRY) log(`skill added=${installed} updated=${updated} current=${current} (version ${liveVer})`);
413
+ const bytes = Buffer.concat(chunks, length);
414
+ if (bytes.length !== expectedBytes) throw new Error(`${label} byte size ${bytes.length} does not match pinned ${expectedBytes}`);
415
+ const digest = createHash('sha256').update(bytes).digest('hex');
416
+ if (digest !== expectedSha256) throw new Error(`${label} SHA-256 does not match its pin`);
417
+ return bytes;
173
418
  }
174
419
 
420
+ function extractTarGzSafely(archive, destination) {
421
+ let tar;
422
+ try { tar = gunzipSync(archive, { maxOutputLength: 64 * 1024 * 1024 }); }
423
+ catch (error) { throw new Error(`artifact is not a safe gzip archive (${error.message})`); }
424
+ let offset = 0; let entries = 0; let ended = false;
425
+ const seenPaths = new Set();
426
+ while (offset + 512 <= tar.length) {
427
+ const header = tar.subarray(offset, offset + 512);
428
+ offset += 512;
429
+ if (header.every((byte) => byte === 0)) { ended = true; break; }
430
+ if (++entries > 2048) throw new Error('artifact contains too many entries');
431
+ validateTarChecksum(header);
432
+ const name = tarString(header, 0, 100);
433
+ const prefix = tarString(header, 345, 155);
434
+ const path = validateArchivePath(prefix ? `${prefix}/${name}` : name, true);
435
+ const type = String.fromCharCode(header[156] || 48);
436
+ const size = tarOctal(header, 124, 12, 'size');
437
+ if (size > 32 * 1024 * 1024 || offset + size > tar.length) throw new Error(`artifact entry ${path} has an invalid size`);
438
+ if (path === '.') {
439
+ if (type !== '5' || size !== 0) throw new Error('artifact root entry is not a directory');
440
+ if (seenPaths.has(path)) throw new Error(`artifact path ${path} is duplicated`);
441
+ seenPaths.add(path);
442
+ continue;
443
+ }
444
+ if (seenPaths.has(path)) throw new Error(`artifact path ${path} is duplicated`);
445
+ seenPaths.add(path);
446
+ const target = resolveInside(destination, path);
447
+ if (type === '5') {
448
+ if (size !== 0) throw new Error(`artifact directory ${path} has data`);
449
+ if (existsSync(target) && !lstatSync(target).isDirectory()) throw new Error(`artifact path ${path} is duplicated`);
450
+ mkdirSync(target, { recursive: true, mode: 0o700 });
451
+ } else if (type === '0') {
452
+ if (existsSync(target)) throw new Error(`artifact path ${path} is duplicated`);
453
+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 });
454
+ const mode = tarOctal(header, 100, 8, 'mode');
455
+ writeFileSync(target, tar.subarray(offset, offset + size), { flag: 'wx', mode: 0o600 | (mode & 0o111) });
456
+ } else if (type === '1' || type === '2') {
457
+ throw new Error(`artifact link ${path} is not allowed`);
458
+ } else {
459
+ throw new Error(`artifact special entry ${path} (type ${JSON.stringify(type)}) is not allowed`);
460
+ }
461
+ offset += Math.ceil(size / 512) * 512;
462
+ }
463
+ if (!ended) throw new Error('artifact tar is truncated or has no end marker');
464
+ }
465
+
466
+ function tarString(header, start, length) {
467
+ const end = header.indexOf(0, start);
468
+ return header.toString('utf8', start, end >= start && end < start + length ? end : start + length);
469
+ }
470
+
471
+ function tarOctal(header, start, length, field) {
472
+ const value = tarString(header, start, length).trim().replace(/\0/g, '');
473
+ if (!/^[0-7]*$/.test(value)) throw new Error(`artifact tar ${field} is invalid`);
474
+ const parsed = value ? Number.parseInt(value, 8) : 0;
475
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error(`artifact tar ${field} is invalid`);
476
+ return parsed;
477
+ }
478
+
479
+ function validateTarChecksum(header) {
480
+ const expected = tarOctal(header, 148, 8, 'checksum');
481
+ let actual = 0;
482
+ for (let i = 0; i < header.length; i++) actual += i >= 148 && i < 156 ? 32 : header[i];
483
+ if (actual !== expected) throw new Error('artifact tar header checksum is invalid');
484
+ }
485
+
486
+ function validateArchivePath(value, allowDot) {
487
+ if (typeof value !== 'string' || value.includes('\0') || value.includes('\\') || isAbsolute(value) || /^[A-Za-z]:/.test(value)) {
488
+ throw new Error(`artifact path ${JSON.stringify(value)} is unsafe`);
489
+ }
490
+ const rawParts = value.split('/').filter((part) => part !== '');
491
+ if (rawParts.some((part) => part === '..')) throw new Error(`artifact path ${JSON.stringify(value)} is unsafe`);
492
+ const parts = rawParts.filter((part) => part !== '.');
493
+ if (!parts.length) {
494
+ if (allowDot && rawParts.every((part) => part === '.')) return '.';
495
+ throw new Error(`artifact path ${JSON.stringify(value)} is unsafe`);
496
+ }
497
+ return parts.join('/');
498
+ }
499
+
500
+ function resolveInside(root, path) {
501
+ const target = resolve(root, ...path.split('/'));
502
+ const rel = relative(resolve(root), target);
503
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error(`artifact path ${JSON.stringify(path)} escapes extraction root`);
504
+ return target;
505
+ }
506
+
507
+ async function installForClient(client, artifact) {
508
+ if (!artifact) throw new Error(`verified ${client.artifact} artifact is unavailable`);
509
+ const root = artifact.root;
510
+ switch (client.id) {
511
+ case 'claude':
512
+ requireClientCli(client);
513
+ runNative(client.bin, ['plugin', 'marketplace', 'add', root, '--scope', 'user']);
514
+ runNative(client.bin, ['plugin', 'install', 'cohesivity@cohesivity', '--scope', 'user']);
515
+ break;
516
+ case 'cursor':
517
+ installDirectoryAtomically(root, join(HOME, '.cursor', 'plugins', 'local', 'cohesivity'));
518
+ break;
519
+ case 'codex':
520
+ requireClientCli(client);
521
+ runNative(client.bin, ['plugin', 'marketplace', 'add', root]);
522
+ runNative(client.bin, ['plugin', 'add', 'cohesivity@cohesivity']);
523
+ break;
524
+ case 'gemini':
525
+ requireClientCli(client);
526
+ runNative(client.bin, ['extensions', 'install', root, '--consent']);
527
+ break;
528
+ case 'antigravity':
529
+ if (client.bin) runNative(client.bin, ['plugin', 'install', root]);
530
+ else if (hasAny(POSITIVE_ANTIGRAVITY_HOMES)) {
531
+ installDirectoryAtomically(root, join(HOME, '.gemini', 'config', 'plugins', 'cohesivity'));
532
+ } else throw new Error('Antigravity CLI is not on PATH and no positive Antigravity home was found');
533
+ break;
534
+ case 'openclaw':
535
+ requireClientCli(client);
536
+ runNative(client.bin, ['plugins', 'install', root, '--force']);
537
+ runNative(client.bin, ['plugins', 'enable', 'cohesivity']);
538
+ break;
539
+ case 'hermes':
540
+ installDirectoryAtomically(root, join(HOME, '.hermes', 'plugins', 'cohesivity'));
541
+ requireClientCli(client);
542
+ runNative(client.bin, ['plugins', 'enable', 'cohesivity']);
543
+ break;
544
+ default:
545
+ throw new Error(`unknown client ${client.id}`);
546
+ }
547
+ }
548
+
549
+ function requireClientCli(client) {
550
+ if (!client.bin) throw new Error('client state exists but its native CLI is not on PATH');
551
+ }
552
+
553
+ function runNative(command, args) {
554
+ const result = spawnSync(command, args, { cwd: CWD, encoding: 'utf8', env: process.env, shell: false, timeout: 120000 });
555
+ if (result.error) throw new Error(`${formatCommand(command, args)} failed (${result.error.message})`);
556
+ if (result.status !== 0) {
557
+ const detail = String(result.stderr || result.stdout || '').trim().replace(/\s+/g, ' ').slice(0, 300);
558
+ throw new Error(`${formatCommand(command, args)} exited ${result.status}${detail ? `: ${detail}` : ''}`);
559
+ }
560
+ }
561
+
562
+ function installDirectoryAtomically(source, destination) {
563
+ const parent = dirname(destination);
564
+ mkdirSync(parent, { recursive: true, mode: 0o700 });
565
+ const stage = join(parent, `.${destination.split(/[\\/]/).pop()}.stage-${process.pid}-${Date.now()}`);
566
+ const backup = join(parent, `.${destination.split(/[\\/]/).pop()}.backup-${process.pid}-${Date.now()}`);
567
+ let backedUp = false;
568
+ try {
569
+ copyVerifiedDirectory(source, stage);
570
+ if (existsSync(destination)) { renameSync(destination, backup); backedUp = true; }
571
+ renameSync(stage, destination);
572
+ if (backedUp) { rmSync(backup, { recursive: true, force: true }); backedUp = false; }
573
+ } catch (error) {
574
+ rmSync(stage, { recursive: true, force: true });
575
+ if (backedUp && !existsSync(destination)) { renameSync(backup, destination); backedUp = false; }
576
+ throw error;
577
+ } finally {
578
+ if (!backedUp) rmSync(backup, { recursive: true, force: true });
579
+ }
580
+ }
581
+
582
+ function copyVerifiedDirectory(source, destination) {
583
+ const stat = lstatSync(source);
584
+ if (!stat.isDirectory()) throw new Error(`verified plugin root ${source} is not a directory`);
585
+ mkdirSync(destination, { mode: 0o700 });
586
+ for (const entry of readdirSync(source)) {
587
+ const from = join(source, entry); const to = join(destination, entry);
588
+ const child = lstatSync(from);
589
+ if (child.isSymbolicLink()) throw new Error(`verified plugin contains a link at ${from}`);
590
+ if (child.isDirectory()) copyVerifiedDirectory(from, to);
591
+ else if (child.isFile()) writeFileSync(to, readFileSync(from), { flag: 'wx', mode: 0o600 | (child.mode & 0o111) });
592
+ else throw new Error(`verified plugin contains a special file at ${from}`);
593
+ }
594
+ }
595
+
596
+ function installFileAtomically(file, body) {
597
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
598
+ const temporary = join(dirname(file), `.${file.split(/[\\/]/).pop()}.tmp-${process.pid}-${Date.now()}`);
599
+ try {
600
+ writeFileSync(temporary, body, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
601
+ renameSync(temporary, file);
602
+ } finally {
603
+ rmSync(temporary, { force: true });
604
+ }
605
+ }
606
+
607
+ function describeDryRunPluginDelivery(clients) {
608
+ const pin = manifestPin();
609
+ act(`fetch and validate plugin manifest ${pin.manifestUrl} (bytes=${pin.manifestBytes}, sha256=${pin.manifestSha256})`);
610
+ for (const key of new Set(clients.map((client) => client.artifact))) {
611
+ act(`fetch, byte-size/SHA-256 validate, and safely extract artifact ${key} from the verified manifest`);
612
+ }
613
+ for (const client of clients) {
614
+ const root = `<verified:${client.artifact}>`;
615
+ if (client.id === 'claude') {
616
+ act(`run ${formatCommand(client.bin || 'claude', ['plugin', 'marketplace', 'add', root, '--scope', 'user'])}`);
617
+ act(`run ${formatCommand(client.bin || 'claude', ['plugin', 'install', 'cohesivity@cohesivity', '--scope', 'user'])}`);
618
+ } else if (client.id === 'cursor') {
619
+ act(`atomically replace ${displayPath(join(HOME, '.cursor', 'plugins', 'local', 'cohesivity'))} from ${root}`);
620
+ } else if (client.id === 'codex') {
621
+ act(`run ${formatCommand(client.bin || 'codex', ['plugin', 'marketplace', 'add', root])}`);
622
+ act(`run ${formatCommand(client.bin || 'codex', ['plugin', 'add', 'cohesivity@cohesivity'])}`);
623
+ } else if (client.id === 'gemini') {
624
+ act(`run ${formatCommand(client.bin || 'gemini', ['extensions', 'install', root, '--consent'])}`);
625
+ } else if (client.id === 'antigravity' && client.bin) {
626
+ act(`run ${formatCommand(client.bin, ['plugin', 'install', root])}`);
627
+ } else if (client.id === 'antigravity') {
628
+ act(`atomically replace ${displayPath(join(HOME, '.gemini', 'config', 'plugins', 'cohesivity'))} from ${root}`);
629
+ } else if (client.id === 'openclaw') {
630
+ act(`run ${formatCommand(client.bin || 'openclaw', ['plugins', 'install', root, '--force'])}`);
631
+ act(`run ${formatCommand(client.bin || 'openclaw', ['plugins', 'enable', 'cohesivity'])}`);
632
+ } else if (client.id === 'hermes') {
633
+ act(`atomically replace ${displayPath(join(HOME, '.hermes', 'plugins', 'cohesivity'))} from ${root}`);
634
+ act(`run ${formatCommand(client.bin || 'hermes', ['plugins', 'enable', 'cohesivity'])}`);
635
+ }
636
+ }
637
+ }
638
+
639
+ function printClientInstructions(clients, adapters) {
640
+ if (!clients.length && !adapters.length) return;
641
+ console.log('');
642
+ log('restart/authentication steps (the installer does not open a browser or start OAuth):');
643
+ for (const client of clients) {
644
+ const instruction = {
645
+ claude: 'Claude: start a new session (or /reload-plugins), then authenticate Cohesivity from /mcp if prompted.',
646
+ cursor: 'Cursor: run Developer: Reload Window, then authenticate Cohesivity in Customize > MCP if prompted.',
647
+ codex: 'Codex: start a new session, open /plugins, and complete Cohesivity authentication if prompted.',
648
+ gemini: 'Gemini: restart the CLI, then run /mcp auth cohesivity if authentication is required.',
649
+ antigravity: 'Antigravity: restart, open /mcp (or Installed MCP Servers), and authenticate Cohesivity.',
650
+ openclaw: 'OpenClaw: restart the Gateway if it did not auto-restart, then run openclaw mcp login cohesivity.',
651
+ 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.',
652
+ }[client.id];
653
+ console.log(` - ${instruction}`);
654
+ }
655
+ for (const adapter of adapters) console.log(` - ${adapter.name}: restart the client and authenticate the Cohesivity MCP server when prompted.`);
656
+ }
657
+
658
+ function displayPath(path) { return path.startsWith(HOME + sep) ? `~${path.slice(HOME.length)}` : path; }
659
+ function formatCommand(command, args) { return [command, ...args].map((arg) => /^[A-Za-z0-9_@%+=:,./~<>-]+$/.test(arg) ? arg : JSON.stringify(arg)).join(' '); }
660
+
175
661
  // ── 2) create or reuse the project tenant ─────────────────────────────────────
176
662
  async function ensureTenant() {
177
663
  const dotfile = join(CWD, '.cohesivity');
178
- if (existsSync(dotfile) && readFileSync(dotfile, 'utf8').includes('coh_management_key=')) {
664
+ if (existsSync(dotfile)) {
665
+ const existing = readFileSync(dotfile, 'utf8');
666
+ if (!DRY) ensureGitignore();
667
+ if (!validTenantCredentials(existing, false)) {
668
+ throw new Error('existing .cohesivity is incomplete; repair or remove it before retrying');
669
+ }
670
+ if (DRY) act('ensure .cohesivity is listed in .gitignore');
179
671
  log('reusing existing .cohesivity (no new tenant created)');
180
672
  return;
181
673
  }
182
674
  if (DRY) { act(`create a tenant: POST ${BASE}/api/genesis -> ./.cohesivity (+ .gitignore)`); return; }
675
+ ensureGitignore();
183
676
  const machineId = readMachineId();
184
677
  let body;
185
678
  let issuedMachineId = null;
@@ -188,21 +681,19 @@ async function ensureTenant() {
188
681
  if (machineId) headers[MACHINE_ID_HEADER] = machineId;
189
682
  const res = await fetch(`${BASE}/api/genesis`, { method: 'POST', headers });
190
683
  body = await res.text();
684
+ if (!res.ok) throw new Error(`genesis returned HTTP ${res.status}`);
191
685
  // Returned on any request that MINTED an id, which is when we sent none
192
686
  // *or* when the id we sent no longer verifies (secret rotated, file
193
687
  // corrupted). It is not "non-null exactly when we sent none" — assuming
194
688
  // that is what left a machine pinned to a dead id forever.
195
689
  issuedMachineId = res.headers.get(MACHINE_ID_HEADER);
196
690
  } catch (e) {
197
- log(`no tenant created (network: ${e.message}). Re-run to retry. The command is idempotent.`);
198
- return;
691
+ throw new Error(`no tenant created (${e.message}). Re-run to retry; the command is idempotent`);
199
692
  }
200
- if (!body.includes('coh_management_key=')) {
201
- log('no tenant created (likely the 10/60s rate limit). Re-run shortly. The command is idempotent.');
202
- return;
693
+ if (!validTenantCredentials(body, true)) {
694
+ throw new Error('genesis returned an incomplete credential response; no project credentials were installed');
203
695
  }
204
- writeFileSync(dotfile, body);
205
- ensureGitignore();
696
+ installCredentialsAtomically(dotfile, body);
206
697
  // Store whatever the server issued. Its presence already means "we minted
207
698
  // this for you", so gating on `!machineId` as well dropped every replacement
208
699
  // a machine with a stale id was handed: it re-minted on every genesis, kept
@@ -211,6 +702,35 @@ async function ensureTenant() {
211
702
  log('created an ephemeral tenant -> ./.cohesivity');
212
703
  }
213
704
 
705
+ function credentialValue(body, name) {
706
+ const match = String(body).match(new RegExp(`^${name}=([^\\r\\n]+)$`, 'm'));
707
+ return match?.[1]?.trim() || null;
708
+ }
709
+
710
+ function validTenantCredentials(body, requireBootstrapMetadata) {
711
+ const tenantId = credentialValue(body, 'tenant_id');
712
+ const managementKey = credentialValue(body, 'coh_management_key');
713
+ const applicationKey = credentialValue(body, 'coh_application_key');
714
+ if (!tenantId || !managementKey?.startsWith('coh_man_') || !applicationKey?.startsWith('coh_app_')) return false;
715
+ if (!requireBootstrapMetadata) return true;
716
+ const expiresAt = credentialValue(body, 'expires_at');
717
+ const lifecycle = credentialValue(body, 'tenant_lifecycle');
718
+ const runtimeProfile = credentialValue(body, 'runtime_profile');
719
+ return Boolean(expiresAt && Number.isFinite(Date.parse(expiresAt))
720
+ && (lifecycle === 'ephemeral' || lifecycle === 'claimed')
721
+ && /^v1-[0-9]+$/.test(runtimeProfile || ''));
722
+ }
723
+
724
+ function installCredentialsAtomically(dotfile, body) {
725
+ const temporary = join(CWD, `.cohesivity.tmp-${process.pid}-${Date.now()}`);
726
+ try {
727
+ writeFileSync(temporary, body, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
728
+ renameSync(temporary, dotfile);
729
+ } finally {
730
+ rmSync(temporary, { force: true });
731
+ }
732
+ }
733
+
214
734
  // Read the machine id, or null when this machine has none. Every failure —
215
735
  // missing file, unreadable dir, garbage contents — reads as "none", which just
216
736
  // means the next genesis call is issued a fresh id.
@@ -295,43 +815,65 @@ function upsertManagedBlock(file, inner) {
295
815
  }
296
816
 
297
817
  // ── ground the session with the result and next steps ─────────────────────────
298
- function ground() {
818
+ function ground(deliveryFailures) {
299
819
  const dotfile = join(CWD, '.cohesivity');
300
820
  const tid = existsSync(dotfile) ? (readFileSync(dotfile, 'utf8').match(/^tenant_id=(.+)$/m) || [])[1] || '' : '';
301
821
  console.log('');
302
- log(tid ? `ready. tenant ${tid}` : 'ready');
822
+ if (deliveryFailures.length) log(tid ? `tenant ${tid} is ready, but client delivery is incomplete` : 'tenant bootstrap is ready, but client delivery is incomplete');
823
+ else log(tid ? `ready. tenant ${tid}` : 'ready');
303
824
  console.log(` - Keys are in .cohesivity (gitignored, do not commit).`);
304
825
  console.log(` - Provision a service: POST ${BASE}/api/resources/<name> (Authorization: Bearer <coh_management_key>)`);
305
826
  console.log(` - Per-service docs: ${BASE}/offerings/<name> \u00b7 full reference: ${BASE}/llms.txt`);
306
- 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.');
827
+ if (NO_PLUGIN) {
828
+ console.log(` - Only the standalone skill was installed at ${displayPath(CANONICAL_SKILL_DIR)}; no plugin or MCP configuration was added.`);
829
+ } else if (deliveryFailures.length) {
830
+ console.log(' - Retry after correcting the delivery errors above; tenant bootstrap is idempotent.');
831
+ } else {
832
+ console.log(' - Detected client integrations are installed. Follow the restart/authentication steps above.');
833
+ }
307
834
  }
308
835
 
309
- function versionOf(md) { return (md.match(/^version:\s*(.+)$/m) || [])[1]?.trim() || null; }
836
+ function versionOf(md) {
837
+ return (md.match(/^metadata:\s*\n(?:[ \t]+[^\n]*\n)*?[ \t]+version:\s*["']?([0-9a-f]{12})["']?\s*$/m) || [])[1] || null;
838
+ }
310
839
 
311
840
  function help() {
312
841
  console.log(`
313
- @cohesivity/init: set up Cohesivity in this project.
842
+ @cohesivity/init v${PKG_VERSION}: set up Cohesivity in this project.
314
843
 
315
844
  Usage:
316
845
  npx @cohesivity/init [options]
317
846
 
318
847
  Options:
319
- --runtime <name> explicit harness label override (normally measured from
320
- the process ancestry; use only when the measurement is wrong)
321
- --dry-run print what would happen. Make no changes
322
- --base <url> API base (default https://cohesivity.ai)
323
- -h, --help show this help
848
+ --runtime <name> explicit harness label override (normally measured from
849
+ the process ancestry; use only when the measurement is wrong)
850
+ --no-plugin install only the canonical standalone skill; add no plugin or MCP
851
+ --dry-run print what would happen. Make no changes
852
+ --base <url> API base (default https://cohesivity.ai)
853
+ -h, --help show this help
324
854
 
325
855
  What it does:
326
- 1. Installs the Cohesivity agent skill into every known agent skill dir
327
- whose harness is present on this machine
856
+ 1. Detects Claude, Cursor, Codex, Gemini, Antigravity, OpenClaw, and Hermes
857
+ independently and installs each client's native or portable plugin package
858
+ (known adapters without a plugin receive the standalone skill plus MCP)
328
859
  2. Creates or reuses a project tenant -> ./.cohesivity (gitignored)
329
860
  3. Adds a descriptive pointer to an existing AGENTS.md / CLAUDE.md / README.md
330
861
  (never creates any of them)
331
862
 
863
+ With --no-plugin, step 1 installs only ~/.agents/skills/cohesivity/SKILL.md.
864
+ It adds no plugin or MCP. Steps 2 and 3, including machine attribution and
865
+ existing project-pointer behavior, are unchanged.
866
+
867
+ Plugin supply chain: a pinned immutable manifest supplies every artifact URL,
868
+ byte size, SHA-256, archive format, and package root. Archives are verified,
869
+ safely extracted without links/traversal/special files, and portable installs
870
+ are replaced atomically. Native client commands are invoked without a shell.
871
+
332
872
  Attribution: the tenant-creation call carries a User-Agent of the shape
333
873
  {npx:<harness>}, where the harness is measured from this process's own
334
874
  parents. Nothing else about your machine is read or sent, and anything not
335
875
  inferable is sent as "none".
336
876
  `);
337
877
  }
878
+
879
+ 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.5.0",
3
+ "version": "0.6.1",
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": {