@cohesivity/init 0.1.3 → 0.2.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 +4 -4
  2. package/bin/cli.js +163 -76
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -8,8 +8,8 @@ npx @cohesivity/init
8
8
 
9
9
  The command runs once and does four things:
10
10
 
11
- 1. **Installs the Cohesivity agent skill** into the detected agent's skill dir (Claude Code, Cursor, Codex, or the cross-tool `~/.agents`). The skill comes from a public, version-pinned commit, so you can audit the exact bytes.
12
- 2. **Creates or reuses a project tenant** and writes the credentials to `.cohesivity`, which it adds to `.gitignore`. 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.
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 comes from a public, version-pinned commit, so you can audit the exact bytes.
12
+ 2. **Creates or reuses a project tenant** and writes the credentials to `.cohesivity`, which it adds to `.gitignore`. The tenant-creation request carries measured attribution: the raw ancestor-process command chain that launched the command (home path folded to `~`), and a User-Agent of the shape `{npx:<harness>, <model>}` where the harness is the innermost non-plumbing ancestor and the model id is read from that harness's own local session log — only that one token, no session content. Anything not inferable is sent as the literal `none`; nothing is guessed. 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
13
  3. **Adds a descriptive pointer** to an existing `AGENTS.md` or `CLAUDE.md`. It only touches a file that is already there. It creates nothing on its own.
14
14
  4. **Adds one branding line** to the README. Pass `--no-branding` to skip.
15
15
 
@@ -27,12 +27,12 @@ npm audit signatures
27
27
 
28
28
  | flag | effect |
29
29
  | --- | --- |
30
- | `--runtime <name>` | your agent runtime (`claude-code`, `cursor`, `codex`, ...) for attribution |
30
+ | `--runtime <name>` | explicit harness label override — use only when the measurement is wrong |
31
31
  | `--no-branding` | leave the README untouched |
32
32
  | `--dry-run` | print what would happen. Change nothing |
33
33
  | `--base <url>` | API base (default `https://cohesivity.ai`) |
34
34
 
35
- The tool detects your runtime from the environment, so `--runtime` is an override, not a requirement.
35
+ The harness is measured from the process ancestry (the chain of parent processes that launched the command), so `--runtime` is an override, not a requirement — and an unrecognized harness simply names itself through its own process name.
36
36
 
37
37
  ## Requirements
38
38
 
package/bin/cli.js CHANGED
@@ -11,8 +11,9 @@
11
11
  * so the registry ships this one file and nothing else.
12
12
  *
13
13
  * The command does four things, in order:
14
- * 1. Install the Cohesivity agent skill into the detected agent's skill dir.
15
- * This is the global, persistent playbook the agent loads later.
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.
16
17
  * 2. Create or reuse a project tenant, write ./.cohesivity, gitignore it.
17
18
  * 3. If AGENTS.md or CLAUDE.md already exists, add a descriptive pointer to it.
18
19
  * 4. Add one branding line to the README. Pass --no-branding to skip.
@@ -20,7 +21,8 @@
20
21
  * The first line is the shebang. It tells npx to run this file as a program.
21
22
  */
22
23
 
23
- import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
24
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, readdirSync, statSync, openSync, readSync, closeSync } from 'node:fs';
25
+ import { execSync } from 'node:child_process';
24
26
  import { homedir } from 'node:os';
25
27
  import { join } from 'node:path';
26
28
 
@@ -32,7 +34,7 @@ const flag = (f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : u
32
34
  if (has('--help') || has('-h')) { help(); process.exit(0); }
33
35
 
34
36
  // ── config ──────────────────────────────────────────────────────────────────
35
- const PKG_VERSION = '0.1.3';
37
+ const PKG_VERSION = '0.2.0';
36
38
  const BASE = (flag('--base') || process.env.COHESIVITY_BASE || 'https://cohesivity.ai').replace(/\/+$/, '');
37
39
 
38
40
  // Machine id: one per machine, stored outside any project. A project's
@@ -46,15 +48,114 @@ const MACHINE_ID_FILE = join(MACHINE_ID_DIR, 'machine-id');
46
48
 
47
49
  // The skill is pinned to an immutable commit in the public, auditable repo.
48
50
  // Bumping the pin is a deliberate release step. See COH-172.
49
- const SKILL_PIN = '135ea5c5d9598825277fe82373f89384d0e815b6';
51
+ const SKILL_PIN = '969ae0a160ac91c26639f55ba9995a95a0fb3da1';
50
52
  const SKILL_URL = `https://raw.githubusercontent.com/cohesivity-org/cohesivity-skill/${SKILL_PIN}/cohesivity.skill.md`;
51
53
 
52
- // The detected runtime rides in the User-Agent on every request this tool makes.
53
- // The genesis endpoint records it, so installs are attributed by agent, not lumped
54
- // under one generic HTTP client. See detectRuntime below.
55
- const RUNTIME_ENUM = ['claude-code', 'claude-web', 'codex', 'cursor', 'opencode', 'windsurf', 'hermes', 'openclaw', 'other'];
56
- const RUNTIME = detectRuntime();
57
- const UA = `npm-${PKG_VERSION}:${RUNTIME}`;
54
+ // ── attribution: measured from the machine, never asked of the model ────────
55
+ // The genesis call carries two measured facts:
56
+ // - The raw ancestor-process command chain (innermost first, home folded to
57
+ // ~), sent verbatim as X-Cohesivity-Ancestry. The server stores it
58
+ // untouched, so harness classification stays a query-time lens and a new
59
+ // harness is discovered from data, never shipped in a list here.
60
+ // - UA `{npx:<harness>, <model>}`: the harness is the innermost ancestor
61
+ // that is not generic plumbing (closed sets below — shells, wrappers,
62
+ // interpreters, terminals; never harness names, so any harness names
63
+ // itself), and the model id is read out of that harness's own live
64
+ // session log. Anything not inferable is the literal "none" — no info is
65
+ // better than false info.
66
+ const ANCESTRY_HEADER = 'X-Cohesivity-Ancestry';
67
+
68
+ // Closed sets: the plumbing an ancestor chain routes through, the interpreter
69
+ // binaries whose script path carries the real name, and the generic segments
70
+ // inside those paths. Harness names never belong in any of these.
71
+ const PLUMBING = new Set(['sh', 'bash', 'zsh', 'fish', 'dash', 'ksh', 'csh', 'tcsh', 'env', 'sudo', 'doas', 'timeout', 'nice', 'ionice', 'stdbuf', 'setsid', 'nohup', 'xargs', 'script', 'ssh', 'sshd', 'tmux', 'screen', 'login', 'su', 'init', 'systemd', 'launchd', 'docker', 'containerd', 'containerd-shim', 'runc', 'podman', 'npm', 'npx', 'pnpm', 'yarn', 'bunx', 'corepack', 'ps', 'awk', 'grep', 'sed', 'cat', 'tr', 'cut', 'head', 'tail', 'find', 'curl', 'wget', 'gnome-terminal', 'konsole', 'xterm', 'alacritty', 'kitty', 'wezterm', 'tilix', 'terminator', 'iterm2', 'terminal', 'warp-terminal']);
72
+ const INTERPRETERS = new Set(['node', 'bun', 'deno', 'python', 'python3', 'python2', 'ruby', 'perl']);
73
+ const GENERIC_SEGMENTS = new Set(['dist', 'build', 'bin', '.bin', 'lib', 'libexec', 'src', 'out', 'app', 'node_modules', '_npx', 'versions', 'current', 'cli.js', 'index.js', 'main.js', 'app.js', 'run.py', 'main.py', '__main__.py', 'npm-cli.js', 'npx-cli.js', 'yarn.js', 'pnpm.cjs', 'corepack.js']);
74
+
75
+ // The raw chain, or null when unreadable (no `ps`, restricted /proc) — null
76
+ // sends nothing; it never guesses.
77
+ function ancestry() {
78
+ try {
79
+ const out = execSync('ps -eo pid=,ppid=,args=', { timeout: 2000 }).toString();
80
+ const pp = {}; const cmd = {};
81
+ for (const line of out.split('\n')) {
82
+ const m = line.match(/^\s*(\d+)\s+(\d+)\s+(.*)/);
83
+ if (m) { pp[m[1]] = m[2]; cmd[m[1]] = m[3].split(homedir()).join('~').slice(0, 120); }
84
+ }
85
+ const chain = [];
86
+ // Start at the PARENT: this process is `node .../cli.js` and must never
87
+ // infer itself as the harness.
88
+ for (let p = pp[String(process.pid)], i = 0; i < 20 && cmd[p]; p = pp[p], i++) chain.push(cmd[p]);
89
+ return chain.join(' | ').replace(/[^\w ._:;()/+~@=,|-]/g, '').slice(0, 800) || null;
90
+ } catch { return null; }
91
+ }
92
+
93
+ function inferHarness(chain) {
94
+ for (const entry of (chain || '').split(' | ')) {
95
+ const tokens = entry.trim().split(' ');
96
+ const first = (tokens[0] || '').split('/').pop().replace(/^-/, '');
97
+ if (INTERPRETERS.has(first)) {
98
+ // Interpreter: the name lives in the script path (…/pi-coding-agent/dist/cli.js).
99
+ for (const tok of tokens.slice(1)) {
100
+ if (!tok.includes('/')) continue;
101
+ const segs = tok.split('/');
102
+ for (let k = segs.length - 1; k >= 0; k--) {
103
+ const s = segs[k].replace(/^@/, '');
104
+ if (s && s !== '~' && !GENERIC_SEGMENTS.has(s) && !PLUMBING.has(s)) {
105
+ return s.replace(/\.(js|mjs|cjs|py|rb|pl)$/, '').slice(0, 40);
106
+ }
107
+ }
108
+ }
109
+ } else if (first && !PLUMBING.has(first)) {
110
+ return first.slice(0, 40);
111
+ }
112
+ }
113
+ return null;
114
+ }
115
+
116
+ // The identified harness is writing its session log right now inside its own
117
+ // state dir (~/.<harness> and the XDG variants — a naming convention, not a
118
+ // harness list). The newest recently-touched file keyed to this project
119
+ // carries the model id as metadata; only that one token is read and sent — no
120
+ // session content leaves the machine.
121
+ function inferModel(harness) {
122
+ if (!harness) return null;
123
+ try {
124
+ const roots = [
125
+ join(homedir(), '.' + harness),
126
+ join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), harness),
127
+ join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), harness),
128
+ ];
129
+ const cutoff = Date.now() - 10 * 60 * 1000;
130
+ const files = [];
131
+ const walk = (dir, depth) => {
132
+ if (depth > 6 || files.length > 400) return;
133
+ let entries; try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
134
+ for (const e of entries) {
135
+ if (files.length > 400) return;
136
+ const p = join(dir, e.name);
137
+ if (e.isDirectory()) walk(p, depth + 1);
138
+ else if (e.isFile()) {
139
+ try { const st = statSync(p); if (st.mtimeMs >= cutoff) files.push({ p, m: st.mtimeMs, s: st.size }); } catch { /* unreadable: skip */ }
140
+ }
141
+ }
142
+ };
143
+ for (const r of roots) walk(r, 0);
144
+ files.sort((a, b) => b.m - a.m);
145
+ const cwdKey = CWD.split('/').pop();
146
+ const pick = files.find((f) => cwdKey && f.p.includes(cwdKey)) || files[0];
147
+ if (!pick) return null;
148
+ const fd = openSync(pick.p, 'r');
149
+ const len = Math.min(pick.s, 100000);
150
+ const buf = Buffer.alloc(len);
151
+ readSync(fd, buf, 0, len, Math.max(0, pick.s - len));
152
+ closeSync(fd);
153
+ const matches = buf.toString('utf8').match(/"model(_?[iI][dD])?"\s*:\s*"([^"]{2,50})"/g);
154
+ if (!matches) return null;
155
+ const value = matches[matches.length - 1].match(/"([^"]{2,50})"$/)[1];
156
+ return /^[A-Za-z0-9][\w .,:=[\]-]{1,63}$/.test(value) ? value : null;
157
+ } catch { return null; }
158
+ }
58
159
 
59
160
  const DRY = has('--dry-run');
60
161
  const NO_BRANDING = has('--no-branding');
@@ -64,10 +165,22 @@ const rel = (p) => p.replace(CWD + '/', '');
64
165
  const log = (m) => console.log(`cohesivity: ${m}`);
65
166
  const act = (m) => console.log(`cohesivity: ${DRY ? '[dry-run] would ' : ''}${m}`);
66
167
 
168
+ const ANCESTRY = ancestry();
169
+ // --runtime / COHESIVITY_RUNTIME is an explicit override for the label — user
170
+ // intent, not detection. Everything else is measured.
171
+ const EXPLICIT = String(flag('--runtime') || process.env.COHESIVITY_RUNTIME || '').toLowerCase().replace(/[^a-z0-9-]/g, '');
172
+ const HARNESS = EXPLICIT || inferHarness(ANCESTRY) || 'none';
173
+ const MODEL = inferModel(HARNESS) || 'none';
174
+ const UA = `{npx:${HARNESS}, ${MODEL}}`;
175
+
176
+ // claude-web's sandbox is non-persistent, so a global skill install cannot
177
+ // survive the session; skip it there. IS_SANDBOX is the sandbox's own signal.
178
+ const IS_CLAUDE_WEB = HARNESS === 'claude-web' || /^(1|yes|true)$/i.test(process.env.IS_SANDBOX || '');
179
+
67
180
  main().catch((e) => { console.error(`cohesivity: unexpected error: ${e.message}`); process.exit(1); });
68
181
 
69
182
  async function main() {
70
- console.log(`\ncohesivity/init v${PKG_VERSION}: setting up (runtime: ${RUNTIME})${DRY ? ' [dry-run: no changes]' : ''}\n`);
183
+ console.log(`\ncohesivity/init v${PKG_VERSION}: setting up (harness: ${HARNESS})${DRY ? ' [dry-run: no changes]' : ''}\n`);
71
184
  await installSkill();
72
185
  await ensureTenant();
73
186
  augmentAgentsFile();
@@ -75,60 +188,24 @@ async function main() {
75
188
  ground();
76
189
  }
77
190
 
78
- // ── runtime detection ─────────────────────────────────────────────────────────
79
- // Identify the calling agent from known environment signals. The value ships in
80
- // the User-Agent, so the server attributes each install to a specific runtime.
81
- // Priority: explicit flag, explicit env, the AI_AGENT/AGENT standard, per-agent
82
- // signals, then a generic sandbox signal (claude-web). Anything unknown falls back
83
- // to `other`, and the `npm-` prefix still marks the install as through this package.
84
- function detectRuntime() {
85
- const clean = (v) => String(v || '').toLowerCase().replace(/[^a-z0-9-]/g, '');
86
-
87
- const explicit = clean(flag('--runtime') || process.env.COHESIVITY_RUNTIME);
88
- if (explicit) return explicit;
89
-
90
- const e = process.env;
91
-
92
- // AI_AGENT / AGENT is the cross-tool standard (HuggingFace, Laravel detector).
93
- const standard = clean(e.AI_AGENT || e.AGENT);
94
- if (RUNTIME_ENUM.includes(standard)) return standard;
95
-
96
- // Per-agent environment signals.
97
- if (e.CLAUDECODE || e.CLAUDE_CODE) return 'claude-code';
98
- if (e.CURSOR_AGENT || e.CURSOR_TRACE_ID) return 'cursor';
99
- if (e.CODEX_SANDBOX || e.CODEX_THREAD_ID || e.CODEX_CI) return 'codex';
100
- if (e.OPENCODE || e.OPENCODE_CLIENT) return 'opencode';
101
- if (e.WINDSURF || e.WINDSURF_AGENT) return 'windsurf';
102
-
103
- // claude-web's sandbox advertises IS_SANDBOX. It carries no more specific agent
104
- // signal, so this check sits last: any per-agent match above wins first, and a
105
- // Codex sandbox (CODEX_SANDBOX) has already resolved to codex by here.
106
- const sandbox = clean(e.IS_SANDBOX);
107
- if (sandbox === 'yes' || sandbox === '1' || sandbox === 'true') return 'claude-web';
108
-
109
- return 'other';
110
- }
111
-
112
- // Map a runtime to its skill dir. Install targets only the detected agent, not
113
- // every known runtime: higher trust, one write. Unknown runtimes get the
114
- // cross-tool ~/.agents dir. (We may revisit multi-dir install later.)
115
- function skillDirFor(runtime) {
191
+ // ── 1) install the skill into the skill dirs present on this machine ─────────
192
+ // Presence on disk is the measurement: each known agent skill dir is written
193
+ // only when its harness home already exists. When none exist, the cross-tool
194
+ // ~/.agents dir is the fallback so the skill lands somewhere.
195
+ function skillDirs() {
116
196
  const codexHome = process.env.CODEX_HOME || join(homedir(), '.codex');
117
- const map = {
118
- 'claude-code': join(homedir(), '.claude', 'skills', 'cohesivity'),
119
- 'cursor': join(homedir(), '.cursor', 'skills', 'cohesivity'),
120
- 'codex': join(codexHome, 'skills', 'cohesivity'),
121
- };
122
- return map[runtime] || join(homedir(), '.agents', 'skills', 'cohesivity');
197
+ const gated = [
198
+ [join(homedir(), '.claude'), join(homedir(), '.claude', 'skills', 'cohesivity')],
199
+ [join(homedir(), '.cursor'), join(homedir(), '.cursor', 'skills', 'cohesivity')],
200
+ [codexHome, join(codexHome, 'skills', 'cohesivity')],
201
+ [join(homedir(), '.agents'), join(homedir(), '.agents', 'skills', 'cohesivity')],
202
+ ];
203
+ const dirs = gated.filter(([home]) => existsSync(home)).map(([, dir]) => dir);
204
+ return dirs.length ? dirs : [join(homedir(), '.agents', 'skills', 'cohesivity')];
123
205
  }
124
206
 
125
- // ── 1) install the skill into the detected agent's skill dir ───────────────────
126
- // claude-web runs in an ephemeral sandbox: a global skill install does not survive
127
- // the session, so there is nothing to persist. Skip it and let the tenant plus the
128
- // project-local .cohesivity carry the session. This mirrors the quickstart's
129
- // per-runtime content negotiation.
130
207
  async function installSkill() {
131
- if (RUNTIME === 'claude-web') {
208
+ if (IS_CLAUDE_WEB) {
132
209
  log('claude-web sandbox is ephemeral, skipping the global skill install (tenant + .cohesivity only)');
133
210
  return;
134
211
  }
@@ -142,19 +219,22 @@ async function installSkill() {
142
219
  return;
143
220
  }
144
221
  const liveVer = versionOf(skill) || 'unknown';
145
- const dir = skillDirFor(RUNTIME);
146
- const shown = dir.replace(homedir(), '~');
147
- const file = join(dir, 'SKILL.md');
148
- const cur = existsSync(file) ? versionOf(readFileSync(file, 'utf8')) : null;
149
- if (cur && cur === liveVer) { log(`skill already current (version ${liveVer}) at ${shown}`); return; }
150
- if (DRY) { act(`install the skill (version ${liveVer}) -> ${shown}`); return; }
151
- try {
152
- mkdirSync(dir, { recursive: true });
153
- writeFileSync(file, skill);
154
- log(`skill ${cur ? 'updated' : 'installed'} (version ${liveVer}) -> ${shown}`);
155
- } catch (e) {
156
- log(`could not write the skill to ${shown} (${e.message}). Continuing.`);
222
+ let installed = 0; let updated = 0; let current = 0;
223
+ for (const dir of skillDirs()) {
224
+ const shown = dir.replace(homedir(), '~');
225
+ const file = join(dir, 'SKILL.md');
226
+ const cur = existsSync(file) ? versionOf(readFileSync(file, 'utf8')) : null;
227
+ if (cur && cur === liveVer) { current++; continue; }
228
+ if (DRY) { act(`install the skill (version ${liveVer}) -> ${shown}`); continue; }
229
+ try {
230
+ mkdirSync(dir, { recursive: true });
231
+ writeFileSync(file, skill);
232
+ if (cur) updated++; else installed++;
233
+ } catch (e) {
234
+ log(`could not write the skill to ${shown} (${e.message}). Continuing.`);
235
+ }
157
236
  }
237
+ if (!DRY) log(`skill added=${installed} updated=${updated} current=${current} (version ${liveVer})`);
158
238
  }
159
239
 
160
240
  // ── 2) create or reuse the project tenant ─────────────────────────────────────
@@ -170,6 +250,7 @@ async function ensureTenant() {
170
250
  let issuedMachineId = null;
171
251
  try {
172
252
  const headers = { 'User-Agent': UA };
253
+ if (ANCESTRY) headers[ANCESTRY_HEADER] = ANCESTRY;
173
254
  if (machineId) headers[MACHINE_ID_HEADER] = machineId;
174
255
  const res = await fetch(`${BASE}/api/genesis`, { method: 'POST', headers });
175
256
  body = await res.text();
@@ -287,16 +368,22 @@ Usage:
287
368
  npx @cohesivity/init [options]
288
369
 
289
370
  Options:
290
- --runtime <name> your agent runtime (claude-code, cursor, codex, ...) for attribution
371
+ --runtime <name> explicit harness label override (normally measured from
372
+ the process ancestry; use only when the measurement is wrong)
291
373
  --no-branding do not add the branding line to the README
292
374
  --dry-run print what would happen. Make no changes
293
375
  --base <url> API base (default https://cohesivity.ai)
294
376
  -h, --help show this help
295
377
 
296
378
  What it does:
297
- 1. Installs the Cohesivity agent skill into the detected agent's skill dir
379
+ 1. Installs the Cohesivity agent skill into every known agent skill dir
380
+ whose harness is present on this machine
298
381
  2. Creates or reuses a project tenant -> ./.cohesivity (gitignored)
299
382
  3. Adds a descriptive pointer to an existing AGENTS.md / CLAUDE.md
300
383
  4. Adds one branding line to the README (managed block)
384
+
385
+ Attribution: the tenant-creation call carries the raw ancestor-process chain
386
+ (X-Cohesivity-Ancestry) and a measured User-Agent {npx:<harness>, <model>}.
387
+ Nothing is guessed: anything not inferable is sent as "none".
301
388
  `);
302
389
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cohesivity/init",
3
- "version": "0.1.3",
3
+ "version": "0.2.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": {