@eocrm/cli 0.0.1-bootstrap.0 → 0.4.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.
@@ -0,0 +1,395 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { join } from 'node:path';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import { dataDir, cliHarness, cliData, codexData, installData } from '../lib/paths.mjs';
5
+ import { endpoints } from '../lib/endpoints.mjs';
6
+ import { createClient } from '../lib/api.mjs';
7
+ import { storeFor, spawnWithStdin } from '../lib/credentials.mjs';
8
+ import { login, openBrowser, requestPair, recordPairing, pairing, plain } from '../lib/login.mjs';
9
+ import { accountFile, loadAccount, resolveWorkspace, useWorkspace, answerCommitted, committedLine, command as cmd, repoEntry, updateRepo, cloneEntry, updateClone } from '../lib/workspace.mjs';
10
+ import { AGENTS } from '../lib/cli/attribute.mjs';
11
+ import { hooksDir, hooksScope, install, installCopy, installed, launcherTarget, uninstall } from '../lib/cli/hooks.mjs';
12
+ import { agentFor, endStale, liveRuns, pluginLive, queuePr, runHook, startRun, stopRuns, sync } from '../lib/cli/run.mjs';
13
+ import { linkWorktree, runsOf, runClient, spawnFlush as realSpawnFlush } from '../lib/run.mjs';
14
+ import { loadConventions } from '../lib/reconcile.mjs';
15
+ import { enqueue } from '../lib/outbox.mjs';
16
+ import { eventId } from '../lib/ids.mjs';
17
+ import { taskFor } from '../lib/detect.mjs';
18
+ import { worktreeOf, lastHookAt, writeJsonAtomic, withLock, saveRun } from '../lib/state.mjs';
19
+ import { CHANGE_ID, importChanges, linkChange } from '../lib/cli/openspec.mjs';
20
+
21
+ const OPTIONS = { data: { type: 'string' }, device: { type: 'boolean' }, harness: { type: 'string' }, region: { type: 'string' }, here: { type: 'boolean' }, accept: { type: 'boolean' }, decline: { type: 'boolean' }, what: { type: 'string' }, why: { type: 'string' }, 'cost-if-wrong': { type: 'string' }, severity: { type: 'string' }, summary: { type: 'string' }, outcome: { type: 'string' }, session: { type: 'string' }, refresh: { type: 'boolean' }, repo: { type: 'string' }, agent: { type: 'string' }, quiet: { type: 'boolean' }, 'shared-hooks': { type: 'boolean' }, space: { type: 'string' } };
22
+ const SEVERITIES = ['critical', 'important', 'minor', 'theoretical'];
23
+ const OUTCOMES = ['open', 'fixed', 'accepted', 'disputed', 'dropped'];
24
+ const LINK_KEY = /^[A-Z][A-Z0-9]{1,9}-[0-9]+$/;
25
+ const CONVENTIONS_MS = 4000;
26
+ const TRUST = 'Hooks have not run here yet. In Codex, open /hooks and trust the eocrm hooks.';
27
+ const APPROVE = 'pairing requested: approve in Account → Agents within 15 minutes';
28
+ const LIVE = 'a Claude Code or Codex session is reporting this worktree';
29
+ const CLI_ONLY = (name) => `${name} is for the eocrm CLI (npx @eocrm/cli ${name})`;
30
+
31
+ class Usage extends Error {
32
+ exitCode = 2;
33
+ }
34
+
35
+ function pairingLines(p) {
36
+ if (p.status === 'requested') return [p.approveUrl ? `${APPROVE}: ${p.approveUrl}` : APPROVE];
37
+ if (p.status === 'paired') return ['already paired'];
38
+ if (p.status === 'choose') return ['pairing: choose a connection, then run pair <id>', ...p.candidates.map((c) => `connection ${plain(c.id)} ${plain(c.label).replace(/\s+/g, ' ')}`)];
39
+ return [p.refused ? `running standalone (${p.refused})` : 'running standalone'];
40
+ }
41
+
42
+ async function recheck({ data, env, store, workspace, region, harness }) {
43
+ try {
44
+ const result = await pairing(createClient({ endpoints: endpoints({ region, env }), workspace, store, harness }));
45
+ if (result.status === 'choose' || result.refused) return ['pairing requested'];
46
+ recordPairing(data, workspace, result.status);
47
+ return pairingLines(result);
48
+ } catch {
49
+ return ['pairing requested'];
50
+ }
51
+ }
52
+
53
+ // Without a matching --session, the most recently touched run.
54
+ function liveRun(data, cwd, session) {
55
+ const live = runsOf(data, worktreeOf(cwd).key).filter((r) => !r.ended);
56
+ const run = live.find((r) => r.sessionId === session) ?? live[0];
57
+ if (!run) throw new Error('no active run in this worktree');
58
+ return run;
59
+ }
60
+
61
+ const need = (v, name) => {
62
+ if (typeof v !== 'string' || !v.trim()) throw new Usage(`--${name} required`);
63
+ return v;
64
+ };
65
+
66
+ function missingHooks(data, cwd) {
67
+ const entry = cloneEntry(data, cwd);
68
+ if (!entry.initialized) return [];
69
+ const have = installed(cwd);
70
+ return (entry.hooks ?? []).filter((h) => !have.includes(h));
71
+ }
72
+
73
+ const warnMissing = (data, cwd, out) => {
74
+ const missing = missingHooks(data, cwd);
75
+ if (missing.length) out(`eocrm hooks missing from ${missing.join(', ')} (a hook manager rewrote them?): run eocrm init again`);
76
+ };
77
+
78
+ async function cliStatus({ cwd, out, data, env, store, harness, spawnFlush }) {
79
+ const ctx = { data, env, store, harness, now: Date.now };
80
+ const entry = repoEntry(data, cwd);
81
+ if (!cloneEntry(data, cwd).initialized) out('not set up in this repository: run eocrm init');
82
+ else {
83
+ const hooks = installed(cwd);
84
+ out(hooks.length ? `hooks ${hooks.join(', ')}` : 'hooks not installed: run eocrm init');
85
+ warnMissing(data, cwd, out);
86
+ }
87
+ if (!launcherTarget(data)) out('the hooks\' copy of the CLI is missing or broken: run npx @eocrm/cli@latest init');
88
+ out(entry.agent ? `agent ${entry.agent}` : 'no agent set');
89
+ if (pluginLive(cwd, Date.now())) {
90
+ out(LIVE);
91
+ return;
92
+ }
93
+ const ended = await endStale(ctx, cwd);
94
+ for (const r of ended) out(`run ${r.agent} ended: idle or on another branch`);
95
+ const runs = liveRuns(data, cwd);
96
+ for (const r of runs) {
97
+ out(`run ${r.agent}${r.explicit ? ' (started)' : ''}${r.start?.task ? ` on ${r.start.task}` : ''}`);
98
+ if (r.outdated) out(`this CLI is below the minimum ${plain(r.outdated.minimum ?? 'version')}: run npx @eocrm/cli@latest init`);
99
+ const pr = await queuePr(ctx, cwd, r).catch(() => null);
100
+ if (pr) out(`pull request #${pr.number} ${pr.action}`);
101
+ }
102
+ if (runs.length || ended.length) (spawnFlush ?? realSpawnFlush)(ctx);
103
+ }
104
+
105
+ const who = (account, workspace) => `Signed in at ${new URL(account.issuer).host} — reporting to ${workspace}`;
106
+
107
+ const commands = {
108
+ async login({ values, positionals: [workspace], env, cwd, out, data, store, open, harness, sleep }) {
109
+ if (values.device && harness !== 'cli') throw new Usage('--device is for the eocrm CLI (npx @eocrm/cli login --device)');
110
+ const region = values.region ?? 'eu';
111
+ const result = await login({ data, region, workspace, env, store, harness, device: values.device, sleep, print: out, openBrowser: (u) => open(u, { print: out }) });
112
+ const lines = [`${who(loadAccount(data), result.workspace)} (${region})`];
113
+ if (result.storage === 'file') lines.push(`tokens stored in ${join(data, 'credentials.json')}: no keychain found`);
114
+ lines.push(...pairingLines(result.pairing));
115
+ const { pending } = resolveWorkspace({ data, cwd });
116
+ if (pending) lines.push(committedLine(pending, harness));
117
+ lines.forEach((l) => out(l));
118
+ },
119
+
120
+ async use({ values, positionals: [workspace], cwd, out, data, harness }) {
121
+ if (values.accept || values.decline) {
122
+ const file = answerCommitted({ data, cwd, accepted: Boolean(values.accept) });
123
+ out(values.accept ? `this repository uses ${file.workspace} (.claude/eocrm.json)` : 'this repository keeps your default workspace');
124
+ return;
125
+ }
126
+ if (!workspace) throw new Usage('workspace required');
127
+ useWorkspace({ data, cwd, workspace, here: values.here });
128
+ out(values.here ? `this worktree uses ${workspace}` : `this repository uses ${workspace}`);
129
+ if (!(workspace in (loadAccount(data).workspaces ?? {}))) out(`run ${cmd(harness, 'login')} ${workspace}`);
130
+ },
131
+
132
+ async pair({ positionals: [id], env, cwd, out, data, store, harness }) {
133
+ if (!id) throw new Usage('connection id required');
134
+ const { workspace, region } = resolveWorkspace({ data, cwd });
135
+ if (!workspace || !region) throw new Usage(`workspace required: run ${cmd(harness, 'login')} first`);
136
+ const result = await requestPair(createClient({ endpoints: endpoints({ region, env }), workspace, store, harness }), id);
137
+ recordPairing(data, workspace, result.status);
138
+ pairingLines(result).forEach((l) => out(l));
139
+ return result.status === 'standalone' ? 3 : 0;
140
+ },
141
+
142
+ async status({ env, cwd, out, data, store, harness, spawnFlush }) {
143
+ const account = loadAccount(data);
144
+ const { workspace, region, source, pending } = resolveWorkspace({ data, cwd });
145
+ const tokens = account.region ? await store.get(endpoints({ region: account.region, env }).key, { timeoutMs: 2500 }) : null;
146
+ out(tokens?.access_token ? `signed in (${account.region})` : `signed out: run ${cmd(harness, 'login')}`);
147
+ if (harness === 'codex') {
148
+ const ran = lastHookAt(data, worktreeOf(cwd).key);
149
+ if (ran === null || ran < (account.signedInAt ?? 0)) out(TRUST);
150
+ }
151
+ if (harness === 'cli') await cliStatus({ cwd, out, data, env, store, harness, spawnFlush });
152
+ if (!workspace) return;
153
+ out(`workspace ${workspace} (${source})`);
154
+ const known = account.workspaces?.[workspace];
155
+ if (tokens?.access_token && account.issuer && region === account.region && known) out(who(account, workspace));
156
+ if (region !== account.region) out(`run ${cmd(harness, 'login')} --region ${region} ${workspace}`);
157
+ else if (!known) out(`run ${cmd(harness, 'login')} ${workspace}`);
158
+ else if (known === 'requested') for (const l of await recheck({ data, env, store, workspace, region, harness })) out(l);
159
+ else out(`pairing ${known}`);
160
+ if (pending) out(committedLine(pending, harness));
161
+ },
162
+
163
+ async link({ values, positionals: [answer, change], env, cwd, out, data, spawnFlush, harness }) {
164
+ if (change !== undefined) {
165
+ if (!CHANGE_ID.test(answer) || (change !== 'none' && !LINK_KEY.test(change))) throw new Usage('usage: eocrm link <change> <KEY|none>');
166
+ linkChange(data, cwd, answer, change === 'none' ? null : change);
167
+ out(change === 'none' ? `${answer} not linked` : `${answer} linked to ${change}`);
168
+ return;
169
+ }
170
+ if (answer !== 'none' && !LINK_KEY.test(answer ?? '')) throw new Usage('usage: eocrm link <KEY|none>');
171
+ const taskKey = answer === 'none' ? null : answer;
172
+ const { others, pending } = await linkWorktree({ data, env, now: Date.now, spawnFlush, harness }, cwd, taskKey, values.session);
173
+ out(`${taskKey ? `linked to ${taskKey}` : 'not linked to a task'}${pending ? ` (applies when work moves to ${pending})` : ''}`);
174
+ if (!values.session) out('Only the default for new sessions changed (no --session).');
175
+ if (others.length) {
176
+ const tasks = [...new Set(others.map((o) => o.task ?? 'none'))].sort().join(', ');
177
+ out(`Also active here: ${others.length} other session${others.length === 1 ? '' : 's'} (on ${tasks}).`);
178
+ }
179
+ },
180
+
181
+ async record({ values: v, positionals: [kind], cwd, out, data }) {
182
+ let type;
183
+ let key;
184
+ let fields;
185
+ if (kind === 'ruling') {
186
+ type = 'ruling';
187
+ fields = { what: need(v.what, 'what'), why: need(v.why, 'why'), ...(v['cost-if-wrong'] ? { cost_if_wrong: v['cost-if-wrong'] } : {}) };
188
+ key = `${fields.what}\0${fields.why}`;
189
+ } else if (kind === 'finding') {
190
+ type = 'review_finding';
191
+ if (!SEVERITIES.includes(v.severity)) throw new Usage(`--severity must be ${SEVERITIES.join('|')}`);
192
+ if (v.outcome !== undefined && !OUTCOMES.includes(v.outcome)) throw new Usage(`--outcome must be ${OUTCOMES.join('|')}`);
193
+ fields = { severity: v.severity, summary: need(v.summary, 'summary'), ...(v.outcome ? { outcome: v.outcome } : {}) };
194
+ key = `${fields.severity}\0${fields.summary}\0${fields.outcome ?? ""}`;
195
+ } else throw new Usage('usage: eocrm record ruling|finding');
196
+ const run = liveRun(data, cwd, v.session);
197
+ const queued = await enqueue(data, { kind: 'event', sessionId: run.sessionId, event: { id: eventId(type, key), type, occurred_at: new Date().toISOString(), ...fields, task_key: taskFor({ data }, { cwd, session_id: run.sessionId })(run) } });
198
+ if (!queued) throw Object.assign(new Error(`${kind} not recorded: the local queue is unavailable`), { exitCode: 1 });
199
+ out(`recorded ${kind}`);
200
+ },
201
+
202
+ async conventions({ values, env, cwd, out, data, store, harness }) {
203
+ const run = liveRun(data, cwd, values.session);
204
+ const conventions = await loadConventions({}, run, { conventions: () => runClient({ data, env, store, harness })(run).conventions() }, Date.now() + CONVENTIONS_MS, { refresh: values.refresh });
205
+ if (!conventions) throw new Error('conventions unavailable: ask the member');
206
+ if (conventions !== run.conventions) {
207
+ await withLock(data, async () => {
208
+ saveRun(data, run.sessionId, { conventions, conventionsAt: Date.now() });
209
+ }, { giveUpMs: 1500 }).catch(() => {});
210
+ }
211
+ const compact = { workspace: run.workspace, ...conventions };
212
+ delete compact.workflows;
213
+ out(JSON.stringify(compact));
214
+ },
215
+
216
+ async init(ctx) {
217
+ const { values, positionals: [workspace], env, cwd, out, data, store, harness } = ctx;
218
+ if (harness !== 'cli') throw new Usage(CLI_ONLY('init'));
219
+ if (values.agent !== undefined && values.agent !== 'none' && !AGENTS.includes(values.agent)) throw new Usage(`--agent must be ${[...AGENTS, 'none'].join('|')}`);
220
+ const dir = hooksDir(cwd);
221
+ const scope = hooksScope(cwd);
222
+ if (scope?.shared && !values['shared-hooks']) throw new Usage(`core.hooksPath comes from your ${scope.scope} git config, so ${dir} is shared by other repositories: pass --shared-hooks to add eocrm there anyway`);
223
+ if (scope?.shared) out(`core.hooksPath is shared (${scope.scope} config): eocrm's line goes into ${dir} for every repository using it, and stays quiet where eocrm init never ran`);
224
+ const account = loadAccount(data);
225
+ const tokens = account.region ? await store.get(endpoints({ region: account.region, env }).key, { timeoutMs: 2500 }) : null;
226
+ const signedIn = tokens?.access_token && !(workspace && !(workspace in (account.workspaces ?? {})));
227
+ if (!signedIn) await commands.login({ ...ctx, positionals: [workspace] });
228
+ if (workspace) useWorkspace({ data, cwd, workspace });
229
+ const target = resolveWorkspace({ data, cwd }).workspace;
230
+ if (signedIn && account.issuer && target) out(who(account, target));
231
+ const launcher = installCopy(data);
232
+ const { done, skipped, lefthook } = install(cwd, { launcher, data });
233
+ updateClone(data, cwd, { initialized: true, hooks: done });
234
+ if (values.agent !== undefined) updateRepo(data, cwd, { agent: values.agent === 'none' ? null : values.agent });
235
+ out(`git hooks in ${dir}: ${done.join(', ') || 'none'}`);
236
+ if (lefthook) out(`lefthook: commands added to ${lefthook}`);
237
+ for (const why of skipped) out(`skipped ${why}`);
238
+ const agent = repoEntry(data, cwd).agent;
239
+ out(agent ? `commits without an agent signal count as ${agent}` : `no agent set: only commits with an agent signal are tracked (eocrm init --agent ${AGENTS.join('|')})`);
240
+ },
241
+
242
+ async uninstall({ data, cwd, out, harness }) {
243
+ if (harness !== 'cli') throw new Usage(CLI_ONLY('uninstall'));
244
+ const { dir, removed } = uninstall(cwd);
245
+ if (cloneEntry(data, cwd).initialized) updateClone(data, cwd, { initialized: false, hooks: [] });
246
+ out(removed.length ? `removed eocrm from ${removed.join(', ')} in ${dir}` : 'no eocrm hooks here');
247
+ },
248
+
249
+ async hook({ positionals: [name, ...args], cwd, data, env, store, harness }) {
250
+ if (harness !== 'cli') throw new Usage(CLI_ONLY('hook'));
251
+ await runHook({ data, env, store, harness, now: Date.now }, name, cwd, args);
252
+ },
253
+
254
+ async sync({ values, cwd, out, data, env, store, harness }) {
255
+ if (harness !== 'cli') throw new Usage(CLI_ONLY('sync'));
256
+ const { quiet, runs, result } = await sync({ data, env, store, harness, now: Date.now }, cwd);
257
+ if (values.quiet) return;
258
+ warnMissing(data, cwd, out);
259
+ if (quiet) out(LIVE);
260
+ else if (!runs) out('no active run here: eocrm run start');
261
+ else out(`sent ${result.sent}${result.retryable ? ', more queued' : ''}${result.signedOut ? ': signed out, run eocrm login' : ''}`);
262
+ },
263
+
264
+ async run({ values, positionals: [action], cwd, out, data, env, store, harness, spawnFlush }) {
265
+ if (harness !== 'cli') throw new Usage(CLI_ONLY('run'));
266
+ const ctx = { data, env, store, harness, now: Date.now, spawnFlush: spawnFlush ?? realSpawnFlush };
267
+ if (action === 'stop') {
268
+ const runs = await stopRuns(ctx, cwd);
269
+ out(runs.length ? `stopped ${runs.map((r) => r.agent).join(', ')}` : 'no active run here');
270
+ return;
271
+ }
272
+ if (action !== 'start') throw new Usage('usage: eocrm run start|stop [--agent <agent>]');
273
+ if (values.agent !== undefined && !AGENTS.includes(values.agent)) throw new Usage(`--agent must be ${AGENTS.join('|')}`);
274
+ if (pluginLive(cwd, Date.now())) throw Object.assign(new Error(LIVE), { exitCode: 3 });
275
+ const agent = values.agent ?? agentFor(ctx, cwd);
276
+ if (!agent) throw new Usage(`no agent: pass --agent ${AGENTS.join('|')}`);
277
+ const run = await startRun(ctx, cwd, agent, { explicit: true });
278
+ if (!run) throw new Usage(`no workspace: run ${cmd(harness, 'init')}`);
279
+ ctx.spawnFlush(ctx);
280
+ out(`run started for ${agent}`);
281
+ warnMissing(data, cwd, out);
282
+ },
283
+
284
+ async openspec({ values, positionals: [action], cwd, out, data, env, store, harness }) {
285
+ if (action !== 'import') throw new Usage('usage: eocrm openspec import [--space <KEY>]');
286
+ const { workspace, region } = resolveWorkspace({ data, cwd });
287
+ if (!workspace || !region) throw new Usage(`workspace required: run ${cmd(harness, 'init')}`);
288
+ return importChanges({ client: createClient({ endpoints: endpoints({ region, env }), workspace, store, harness }), data, cwd, space: values.space, out });
289
+ },
290
+
291
+ async logout({ env, out, data, store, harness }) {
292
+ const account = loadAccount(data);
293
+ const keys = new Set(Array.isArray(account.keys) ? account.keys : []);
294
+ if (account.region) keys.add(endpoints({ region: account.region, env }).key);
295
+ const failed = [];
296
+ for (const key of keys) {
297
+ try {
298
+ await store.del(key);
299
+ out(`signed out of ${plain(String(key).split(' ')[0])}`);
300
+ } catch {
301
+ failed.push(key);
302
+ }
303
+ }
304
+ writeJsonAtomic(accountFile(data), { ...account, keys: failed });
305
+ if (failed.length) out(`sign-out incomplete, run ${cmd(harness, 'logout')} again`);
306
+ else if (!keys.size) out('signed out');
307
+ },
308
+
309
+ async 'smoke-seed'(ctx) {
310
+ const { values, env, cwd, out, data, store, gh } = ctx;
311
+ const repo = values.repo;
312
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo ?? '')) throw new Usage('--repo <owner>/<repo> required');
313
+ const account = loadAccount(data);
314
+ const signIn = () => new Usage('sign in first: /eocrm:login');
315
+ if (!account.region) throw signIn();
316
+ const key = endpoints({ region: account.region, env }).key;
317
+ const tokens = await store.get(key);
318
+ if (!tokens?.refresh_token || !tokens.client_id) throw signIn();
319
+ const { workspace } = resolveWorkspace({ data, cwd });
320
+ const writes = [
321
+ ['secret', 'EOCRM_SMOKE_REGION', account.region],
322
+ ['secret', 'EOCRM_SMOKE_CLIENT_ID', tokens.client_id],
323
+ ['secret', 'EOCRM_SMOKE_REFRESH_TOKEN', tokens.refresh_token],
324
+ ...(workspace ? [['variable', 'EOCRM_SMOKE_WORKSPACE', workspace]] : []),
325
+ ];
326
+ for (const [kind, name, value] of writes) {
327
+ const { code } = await gh([kind, 'set', name, '--repo', repo], value);
328
+ if (code !== 0) {
329
+ const e = new Error(code === -1 ? 'gh not found or timed out; local sign-in kept' : `gh ${kind} set ${name} failed (exit ${code}); local sign-in kept`);
330
+ e.exitCode = 1;
331
+ throw e;
332
+ }
333
+ out(`set ${name}`);
334
+ }
335
+ const gone = await store.del(key, { when: (t) => t?.refresh_token === tokens.refresh_token });
336
+ if (gone === false) {
337
+ const e = new Error('refresh token rotated while seeding; run smoke-seed again');
338
+ e.exitCode = 1;
339
+ throw e;
340
+ }
341
+ await commands.logout(ctx);
342
+ out('signed out locally: the refresh token now belongs to CI');
343
+ },
344
+ };
345
+
346
+ export async function main({
347
+ argv = process.argv.slice(2),
348
+ env = process.env,
349
+ cwd = process.cwd(),
350
+ out = (l) => process.stdout.write(`${l}\n`),
351
+ err = (l) => process.stderr.write(`${l}\n`),
352
+ version = process.versions.node,
353
+ store,
354
+ openBrowser: open = openBrowser,
355
+ spawnFlush,
356
+ gh = (args, stdin) => spawnWithStdin('gh', args, stdin, { timeoutMs: 30000 }),
357
+ script = fileURLToPath(import.meta.url),
358
+ harness: forced,
359
+ sleep,
360
+ } = {}) {
361
+ if (!(Number(String(version).split('.')[0]) >= 20)) {
362
+ err('eocrm needs Node 20+ on PATH');
363
+ return 1;
364
+ }
365
+ try {
366
+ const { values, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
367
+ const [name, ...rest] = positionals;
368
+ const command = Object.hasOwn(commands, name) ? commands[name] : null;
369
+ if (!command) throw new Usage('usage: eocrm init|login|use|pair|status|link|record|conventions|sync|run|openspec|uninstall|logout|smoke-seed --data <dir>');
370
+ const harness = forced ?? cliHarness({ flag: values.harness, env, script });
371
+ if (harness === 'codex') values.session ||= env.CODEX_THREAD_ID;
372
+ if (values.session && !/^[\w-]+$/.test(values.session)) throw new Usage('invalid --session');
373
+ let data;
374
+ try {
375
+ // The CLI ignores plugin data env, so its sign-in never lands in a plugin's dir.
376
+ data = harness === 'cli'
377
+ ? dataDir({ argv: [], env: {}, data: values.data || cliData(env) })
378
+ : dataDir({ argv, env, data: values.data, fallback: harness === 'codex' ? installData(script) ?? codexData(env) : undefined });
379
+ } catch (e) {
380
+ throw new Usage(e.message);
381
+ }
382
+ const code = await command({ values, positionals: rest, env, cwd, out, data, harness, store: store ?? storeFor(data, harness), open, spawnFlush, gh, sleep });
383
+ return code ?? 0;
384
+ } catch (e) {
385
+ for (const line of e.lines ?? []) out(line);
386
+ err(`eocrm: ${String(e.message).replace(/^eocrm: /, '')}`);
387
+ return e.exitCode ?? (String(e.code).startsWith('ERR_PARSE_ARGS') ? 2 : 3);
388
+ }
389
+ }
390
+
391
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
392
+ main().then((code) => {
393
+ process.exitCode = code;
394
+ });
395
+ }