@cohesivity/init 0.2.4 → 0.3.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 (2) hide show
  1. package/bin/cli.js +39 -152
  2. package/package.json +1 -1
package/bin/cli.js CHANGED
@@ -21,7 +21,7 @@
21
21
  * The first line is the shebang. It tells npx to run this file as a program.
22
22
  */
23
23
 
24
- import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, readdirSync, statSync, openSync, readSync, closeSync } from 'node:fs';
24
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
25
25
  import { execSync } from 'node:child_process';
26
26
  import { homedir } from 'node:os';
27
27
  import { join } from 'node:path';
@@ -34,7 +34,7 @@ const flag = (f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : u
34
34
  if (has('--help') || has('-h')) { help(); process.exit(0); }
35
35
 
36
36
  // ── config ──────────────────────────────────────────────────────────────────
37
- const PKG_VERSION = '0.2.4';
37
+ const PKG_VERSION = '0.3.1';
38
38
  const BASE = (flag('--base') || process.env.COHESIVITY_BASE || 'https://cohesivity.ai').replace(/\/+$/, '');
39
39
 
40
40
  // Machine id: one per machine, stored outside any project. A project's
@@ -51,154 +51,43 @@ const MACHINE_ID_FILE = join(MACHINE_ID_DIR, 'machine-id');
51
51
  const SKILL_PIN = 'a4c0e90373b2d61501e4fb544a760b4a602fc14e';
52
52
  const SKILL_URL = `https://raw.githubusercontent.com/cohesivity-org/cohesivity-skill/${SKILL_PIN}/cohesivity.skill.md`;
53
53
 
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', 'timelimit', '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); }
54
+ // Harness: the nearest ancestor process that is not generic plumbing. Only
55
+ // this process's own lineage is read — never the system process list — and only
56
+ // the resulting name is sent. The sets below are closed lists of Unix plumbing,
57
+ // interpreters, and generic path segments; they never name a harness, so any
58
+ // harness, present or future, identifies itself by its own process or script
59
+ // name. Nothing inferable -> null, never a guess.
60
+ const PLUMBING = new Set('sh bash zsh fish dash ksh csh tcsh env sudo doas timeout timelimit nice setsid nohup xargs script ssh sshd tmux screen login su init systemd launchd docker containerd containerd-shim runc podman npm npx pnpm yarn bunx ps awk grep sed find curl wget gnome-terminal konsole xterm alacritty kitty wezterm tilix terminator iterm2 terminal warp-terminal'.split(' '));
61
+ const INTERPRETERS = new Set('node bun deno python python2 python3 ruby perl'.split(' '));
62
+ const GENERIC = new Set('cli index main app run dist build bin lib libexec src out node_modules _npx versions current'.split(' '));
63
+
64
+ function inferHarness() {
65
+ let pid = process.ppid;
66
+ for (let i = 0; i < 20 && pid > 1; i++) {
67
+ let argv, ppid;
68
+ try {
69
+ argv = readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').filter(Boolean);
70
+ ppid = Number(readFileSync(`/proc/${pid}/stat`, 'utf8').split(') ').pop().split(' ')[1]);
71
+ } catch {
72
+ try {
73
+ argv = execSync(`ps -o args= -p ${pid}`, { timeout: 2000 }).toString().trim().split(/\s+/);
74
+ ppid = Number(execSync(`ps -o ppid= -p ${pid}`, { timeout: 2000 }).toString().trim());
75
+ } catch { return null; }
84
76
  }
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(reduceEntry(cmd[p]));
89
- return chain.filter(Boolean).join(' | ').replace(/[^\w ._:;()/+~@,|-]/g, '').slice(0, 800) || null;
90
- } catch { return null; }
91
- }
92
-
93
- // Keep the program that ran; drop its arguments before anything is sent.
94
- //
95
- // Arguments are pure liability and identify nothing. A real caller's chain
96
- // reached the server carrying live AWS credentials, because its parent was
97
- // `sh -c export AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=...`; agent
98
- // invocations put the user's prompt on the command line the same way. argv[0]
99
- // names the harness, and for an interpreter the script path does, so one
100
- // path-like argument that is neither a URL nor a k=v assignment survives.
101
- function reduceEntry(entry) {
102
- const tokens = String(entry).trim().split(/\s+/).filter(Boolean);
103
- if (!tokens.length) return '';
104
- const prog = tokens[0];
105
- const base = prog.split('/').pop().replace(/^-/, '');
106
- if (!INTERPRETERS.has(base)) return prog;
107
- for (const tok of tokens.slice(1)) {
108
- if (tok.includes('=') || tok.includes('://')) continue;
109
- if (tok.includes('/')) return `${prog} ${tok}`;
110
- }
111
- return prog;
112
- }
113
-
114
- function inferHarness(chain) {
115
- for (const entry of (chain || '').split(' | ')) {
116
- const tokens = entry.trim().split(' ');
117
- const first = (tokens[0] || '').split('/').pop().replace(/^-/, '');
118
- if (INTERPRETERS.has(first)) {
119
- // Interpreter: the name lives in the script path (…/pi-coding-agent/dist/cli.js).
120
- for (const tok of tokens.slice(1)) {
121
- if (!tok.includes('/')) continue;
122
- const segs = tok.split('/');
123
- for (let k = segs.length - 1; k >= 0; k--) {
124
- const s = segs[k].replace(/^@/, '');
125
- if (s && s !== '~' && !GENERIC_SEGMENTS.has(s) && !PLUMBING.has(s)) {
126
- return s.replace(/\.(js|mjs|cjs|py|rb|pl)$/, '').slice(0, 40);
127
- }
128
- }
129
- }
130
- } else if (first && !PLUMBING.has(first)) {
131
- return first.slice(0, 40);
77
+ let name = (argv[0] || '').split('/').pop().replace(/^-/, '');
78
+ if (INTERPRETERS.has(name)) {
79
+ const script = argv.slice(1).find((a) => a.includes('/') && !a.includes('='));
80
+ const segs = (script || '').split('/').filter(Boolean);
81
+ while (segs.length && GENERIC.has(segs[segs.length - 1].replace(/\.\w+$/, ''))) segs.pop();
82
+ if (segs.length) name = segs.pop().replace(/\.\w+$/, '');
132
83
  }
84
+ if (name && !PLUMBING.has(name)) return name.replace(/[^\w.-]/g, '').slice(0, 40) || null;
85
+ if (!Number.isFinite(ppid)) return null;
86
+ pid = ppid;
133
87
  }
134
88
  return null;
135
89
  }
136
90
 
137
- // The identified harness is writing its session log right now inside its own
138
- // state dir (~/.<harness> and the XDG variants — a naming convention, not a
139
- // harness list). The newest recently-touched file keyed to this project
140
- // carries the model id as metadata; only that one token is read and sent — no
141
- // session content leaves the machine.
142
- function inferModel(harness) {
143
- if (!harness) return null;
144
- try {
145
- // A harness's state dir is not always named exactly like its process: the
146
- // binary is cursor-agent but the dir is ~/.cursor, the script is
147
- // pi-coding-agent but the dir is ~/.pi. So the measured name is also tried
148
- // truncated at each hyphen — a general string rule over the name, not a
149
- // list of harnesses. Nonexistent paths cost nothing; the walk skips them.
150
- const names = [];
151
- for (let n = harness; n; n = n.includes('-') ? n.slice(0, n.lastIndexOf('-')) : '') {
152
- if (!names.includes(n)) names.push(n);
153
- }
154
- const cfgHome = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
155
- const dataHome = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share');
156
- const roots = names.flatMap((n) => [join(homedir(), '.' + n), join(cfgHome, n), join(dataHome, n)]);
157
- const cutoff = Date.now() - 10 * 60 * 1000;
158
- const files = [];
159
- const walk = (dir, depth) => {
160
- if (depth > 6 || files.length > 400) return;
161
- let entries; try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
162
- for (const e of entries) {
163
- if (files.length > 400) return;
164
- const p = join(dir, e.name);
165
- if (e.isDirectory()) walk(p, depth + 1);
166
- else if (e.isFile()) {
167
- try { const st = statSync(p); if (st.mtimeMs >= cutoff) files.push({ p, m: st.mtimeMs, s: st.size }); } catch { /* unreadable: skip */ }
168
- }
169
- }
170
- };
171
- for (const r of roots) walk(r, 0);
172
- files.sort((a, b) => b.m - a.m);
173
- // Try candidates in order until one yields a model. Testing only the
174
- // newest file is not enough: a harness touches lock, session-env and
175
- // file-history files alongside its session log, so the most recently
176
- // written file frequently carries no model — and reporting "none" while
177
- // the answer sits in the next file is a loss, not a safe default.
178
- const cwdKey = CWD.split('/').pop();
179
- const ordered = [
180
- ...files.filter((f) => cwdKey && f.p.includes(cwdKey)),
181
- ...files,
182
- ].slice(0, 20);
183
- for (const pick of ordered) {
184
- let text;
185
- try {
186
- const fd = openSync(pick.p, 'r');
187
- const len = Math.min(pick.s, 100000);
188
- const buf = Buffer.alloc(len);
189
- readSync(fd, buf, 0, len, Math.max(0, pick.s - len));
190
- closeSync(fd);
191
- text = buf.toString('utf8');
192
- } catch { continue; }
193
- const matches = text.match(/"model(_?[iI][dD])?"\s*:\s*"([^"]{2,50})"/g);
194
- if (!matches) continue;
195
- const value = matches[matches.length - 1].match(/"([^"]{2,50})"$/)[1];
196
- if (/^[A-Za-z0-9][\w .,:=[\]-]{1,63}$/.test(value)) return value;
197
- }
198
- return null;
199
- } catch { return null; }
200
- }
201
-
202
91
  const DRY = has('--dry-run');
203
92
  const NO_BRANDING = has('--no-branding');
204
93
 
@@ -207,13 +96,11 @@ const rel = (p) => p.replace(CWD + '/', '');
207
96
  const log = (m) => console.log(`cohesivity: ${m}`);
208
97
  const act = (m) => console.log(`cohesivity: ${DRY ? '[dry-run] would ' : ''}${m}`);
209
98
 
210
- const ANCESTRY = ancestry();
211
99
  // --runtime / COHESIVITY_RUNTIME is an explicit override for the label — user
212
100
  // intent, not detection. Everything else is measured.
213
101
  const EXPLICIT = String(flag('--runtime') || process.env.COHESIVITY_RUNTIME || '').toLowerCase().replace(/[^a-z0-9-]/g, '');
214
- const HARNESS = EXPLICIT || inferHarness(ANCESTRY) || 'none';
215
- const MODEL = inferModel(HARNESS) || 'none';
216
- const UA = `{npx:${HARNESS}, ${MODEL}}`;
102
+ const HARNESS = EXPLICIT || inferHarness() || 'none';
103
+ const UA = `{npx:${HARNESS}}`;
217
104
 
218
105
  // claude-web's sandbox is non-persistent, so a global skill install cannot
219
106
  // survive the session; skip it there. IS_SANDBOX is the sandbox's own signal.
@@ -292,7 +179,6 @@ async function ensureTenant() {
292
179
  let issuedMachineId = null;
293
180
  try {
294
181
  const headers = { 'User-Agent': UA };
295
- if (ANCESTRY) headers[ANCESTRY_HEADER] = ANCESTRY;
296
182
  if (machineId) headers[MACHINE_ID_HEADER] = machineId;
297
183
  const res = await fetch(`${BASE}/api/genesis`, { method: 'POST', headers });
298
184
  body = await res.text();
@@ -424,8 +310,9 @@ What it does:
424
310
  3. Adds a descriptive pointer to an existing AGENTS.md / CLAUDE.md
425
311
  4. Adds one branding line to the README (managed block)
426
312
 
427
- Attribution: the tenant-creation call carries the raw ancestor-process chain
428
- (X-Cohesivity-Ancestry) and a measured User-Agent {npx:<harness>, <model>}.
429
- Nothing is guessed: anything not inferable is sent as "none".
313
+ Attribution: the tenant-creation call carries a User-Agent of the shape
314
+ {npx:<harness>}, where the harness is measured from this process's own
315
+ parents. Nothing else about your machine is read or sent, and anything not
316
+ inferable is sent as "none".
430
317
  `);
431
318
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cohesivity/init",
3
- "version": "0.2.4",
3
+ "version": "0.3.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": {