@eocrm/cli 0.0.0-stage → 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,210 @@
1
+ import { appendFileSync, cpSync, existsSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync, unlinkSync, mkdirSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { git, remove, worktreeOf, writeFileAtomic } from '../state.mjs';
6
+ import { VERSION } from '../api.mjs';
7
+
8
+ export const HOOKS = ['post-commit', 'pre-push', 'post-checkout'];
9
+ const MARK = '# eocrm-cli';
10
+ const CREATED = `# created by eocrm init ${MARK}`;
11
+ const SHEBANG = '#!/bin/sh\n';
12
+ const SH = /^#!\s*(?:\/usr\/bin\/env\s+(?:-S\s+)?)?(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:sh|bash|dash|zsh|ksh)\b/;
13
+ const LOCAL_SCOPES = new Set(['local', 'worktree']);
14
+ const LEFTHOOK = ['lefthook.yml', '.lefthook.yml', 'lefthook.yaml', '.lefthook.yaml'];
15
+ const LEFTHOOK_LOCAL = ['lefthook-local.yml', '.lefthook-local.yml', 'lefthook-local.yaml', '.lefthook-local.yaml'];
16
+ const PACKAGE = fileURLToPath(new URL('../../', import.meta.url));
17
+ const SHIPPED = ['package.json', 'scripts/cli.mjs', 'scripts/eocrm.mjs', 'hooks/dispatch.mjs', 'lib'];
18
+ const LAUNCH = /^await import\("\.\/([^"/]+)\/scripts\/cli\.mjs"\);$/m;
19
+
20
+ export const launcherOf = (data) => join(data, 'bin', 'eocrm.mjs');
21
+
22
+ // Git for Windows runs hooks under its own sh: forward slashes, single quotes.
23
+ export function shq(path, platform = process.platform) {
24
+ const p = platform === 'win32' ? path.replace(/\\/g, '/') : path;
25
+ return `'${p.replace(/'/g, `'\\''`)}'`;
26
+ }
27
+
28
+ // Never reads the hook's stdin (pre-push refs), never fails the hook, leaks no variables.
29
+ function hookCommand(name, { node = process.execPath, launcher, data, platform = process.platform }, args) {
30
+ return `( L=${shq(launcher, platform)}; [ -f "$L" ] || exit 0; N=${shq(node, platform)}; [ -x "$N" ] || N=node; "$N" "$L" hook ${name} --data ${shq(data, platform)} ${args} </dev/null >/dev/null 2>&1 ) || :`;
31
+ }
32
+
33
+ export const hookLine = (name, opts) => `${hookCommand(name, opts, '"$@"')} ${MARK}`;
34
+
35
+ // A versioned copy under the data dir plus a launcher that imports it: hooks keep working after npx's cache is collected.
36
+ export function installCopy(data, { from = PACKAGE, version = VERSION } = {}) {
37
+ const bin = join(data, 'bin');
38
+ const dest = join(bin, version);
39
+ if (resolve(from) !== resolve(dest)) {
40
+ const tmp = `${dest}.${randomBytes(4).toString('hex')}.tmp`;
41
+ mkdirSync(tmp, { recursive: true });
42
+ for (const f of SHIPPED) cpSync(join(from, f), join(tmp, f), { recursive: true });
43
+ remove(dest);
44
+ renameSync(tmp, dest);
45
+ }
46
+ writeFileAtomic(launcherOf(data), `await import(${JSON.stringify(`./${version}/scripts/cli.mjs`)});\n`);
47
+ for (const old of readdirSync(bin)) if (old !== version && old !== 'eocrm.mjs') remove(join(bin, old));
48
+ return launcherOf(data);
49
+ }
50
+
51
+ // The version the launcher points at, or null when it or its copy is gone.
52
+ export function launcherTarget(data) {
53
+ try {
54
+ const version = LAUNCH.exec(readFileSync(launcherOf(data), 'utf8'))?.[1];
55
+ return version && existsSync(join(data, 'bin', version, 'scripts', 'cli.mjs')) ? version : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ export function hooksDir(cwd) {
62
+ const dir = git(cwd, ['rev-parse', '--git-path', 'hooks']);
63
+ if (!dir) throw Object.assign(new Error('not a git repository'), { exitCode: 2 });
64
+ return resolve(cwd, dir);
65
+ }
66
+
67
+ // The config scope of core.hooksPath: null when unset; global or system means other repositories share the dir.
68
+ export function hooksScope(cwd) {
69
+ const scope = git(cwd, ['config', '--show-scope', '--get', 'core.hooksPath']).split('\t')[0];
70
+ return scope ? { scope, shared: !LOCAL_SCOPES.has(scope) } : null;
71
+ }
72
+
73
+ // latin1 round-trips any bytes, so uninstall restores the file exactly.
74
+ const read = (file) => readFileSync(file, 'latin1');
75
+ const write = (file, text, opts) => writeFileSync(file, text, { encoding: 'latin1', ...opts });
76
+ const eolOf = (text) => (text.includes('\r\n') ? '\r\n' : '\n');
77
+ const strip = (text) => text.split(/(?<=\n)/).filter((l) => !l.trimEnd().endsWith(MARK)).join('');
78
+ const tracked = (cwd, file) => Boolean(git(cwd, ['ls-files', '--error-unmatch', '--', file]));
79
+
80
+ // Our lines go after the shebang, or first when there is none.
81
+ function withLines(text, lines) {
82
+ const eol = eolOf(text);
83
+ const add = lines.map((l) => `${l}${eol}`).join('');
84
+ const [first = '', ...rest] = text.split(/(?<=\n)/);
85
+ return first.startsWith('#!') ? `${first}${first.endsWith('\n') ? '' : eol}${add}${rest.join('')}` : `${add}${text}`;
86
+ }
87
+
88
+ function refusal(cwd, file, text) {
89
+ if (tracked(cwd, file)) return 'tracked in git, so eocrm will not write local paths into it';
90
+ if ([...text.slice(0, 512)].some((c) => (c < ' ' && !'\t\n\r\f\v\x1b'.includes(c)) || c === '\x7f')) return 'not a script';
91
+ if (process.platform !== 'win32' && !(statSync(file).mode & 0o111)) return 'not executable, so git does not run it';
92
+ if (text.startsWith('#!') && !SH.test(text)) return 'not a shell script';
93
+ return null;
94
+ }
95
+
96
+ const lefthookLocal = (root) => (LEFTHOOK.some((f) => existsSync(join(root, f))) ? LEFTHOOK_LOCAL.map((f) => join(root, f)).find((f) => existsSync(f)) ?? join(root, LEFTHOOK_LOCAL[0]) : null);
97
+ const excludeOf = (cwd) => resolve(cwd, git(cwd, ['rev-parse', '--git-path', 'info/exclude']));
98
+ const ours = (root) => LEFTHOOK_LOCAL.map((f) => join(root, f)).find((f) => existsSync(f) && read(f).includes(MARK));
99
+ // Which exclude entry was written says how to remove it byte-exact: plain, after an added newline, or into a file eocrm created.
100
+ const excludeEntries = (root, file) => {
101
+ const pattern = `/${file.slice(root.length + 1).replace(/\\/g, '/')}\n`;
102
+ return { plain: `${MARK}\n${pattern}`, newline: `\n${MARK} (newline)\n${pattern}`, created: `${MARK} (created)\n${pattern}` };
103
+ };
104
+ const yamlQuoted = (s) => `'${s.replace(/'/g, "''")}'`;
105
+
106
+ // lefthook rewrites its hook files on every install; lefthook-local.yml keeps the command across that.
107
+ function installLefthook(cwd, root, opts) {
108
+ const file = lefthookLocal(root);
109
+ if (!file) return null;
110
+ if (tracked(cwd, file)) return { skipped: `${file} is tracked in git` };
111
+ const text = existsSync(file) ? read(file) : null;
112
+ const clean = text === null ? '' : strip(text);
113
+ const taken = HOOKS.find((h) => new RegExp(`^${h}\\s*:`, 'm').test(clean));
114
+ if (taken) return { skipped: `${file} already defines ${taken}` };
115
+ const block = HOOKS.flatMap((h) => [`${h}: ${MARK}`, ` commands: ${MARK}`, ` eocrm: ${MARK}`, ` run: ${yamlQuoted(hookCommand(h, opts, '{0}'))} ${MARK}`]);
116
+ write(file, withLines(clean, [...(text === null || text.includes(CREATED) ? [CREATED] : []), ...block]));
117
+ if (!git(cwd, ['check-ignore', '--', file])) {
118
+ const exclude = excludeOf(cwd);
119
+ mkdirSync(resolve(exclude, '..'), { recursive: true });
120
+ const before = existsSync(exclude) ? read(exclude) : null;
121
+ const entries = excludeEntries(root, file);
122
+ appendFileSync(exclude, before === null ? entries.created : before && !before.endsWith('\n') ? entries.newline : entries.plain, 'latin1');
123
+ }
124
+ return { file };
125
+ }
126
+
127
+ // Linked worktrees share info/exclude: another one still carrying our block keeps the entry.
128
+ const sharedElsewhere = (cwd, root) => git(cwd, ['worktree', 'list', '--porcelain']).split('\n')
129
+ .filter((l) => l.startsWith('worktree '))
130
+ .map((l) => resolve(l.slice(9)))
131
+ .some((other) => other !== resolve(root) && ours(other));
132
+
133
+ function uninstallLefthook(cwd, root) {
134
+ const file = ours(root);
135
+ if (!file) return false;
136
+ const text = read(file);
137
+ const clean = strip(text);
138
+ if (clean === text) return false;
139
+ if (text.includes(CREATED) && !clean.trim()) unlinkSync(file);
140
+ else write(file, clean);
141
+ const exclude = excludeOf(cwd);
142
+ if (!existsSync(exclude) || sharedElsewhere(cwd, root)) return true;
143
+ const entries = excludeEntries(root, file);
144
+ const before = read(exclude);
145
+ const kind = ['created', 'newline', 'plain'].find((k) => before.includes(entries[k]));
146
+ const after = kind ? before.replace(entries[kind], '') : before;
147
+ if (kind === 'created' && !after) unlinkSync(exclude);
148
+ else if (kind) write(exclude, after);
149
+ return true;
150
+ }
151
+
152
+ export function install(cwd, opts) {
153
+ const dir = hooksDir(cwd);
154
+ mkdirSync(dir, { recursive: true });
155
+ const done = [];
156
+ const skipped = [];
157
+ for (const name of HOOKS) {
158
+ const file = join(dir, name);
159
+ const line = hookLine(name, opts);
160
+ const text = existsSync(file) ? read(file) : null;
161
+ if (text === null) {
162
+ write(file, `${SHEBANG}${CREATED}\n${line}\n`, { mode: 0o755 });
163
+ done.push(name);
164
+ continue;
165
+ }
166
+ const why = text.includes(CREATED) ? null : refusal(cwd, file, text);
167
+ if (why) {
168
+ skipped.push(`${name}: ${why}`);
169
+ continue;
170
+ }
171
+ write(file, withLines(strip(text), [...(text.includes(CREATED) ? [CREATED] : []), line]));
172
+ done.push(name);
173
+ }
174
+ const lefthook = installLefthook(cwd, worktreeOf(cwd).root, opts);
175
+ if (lefthook?.skipped) skipped.push(`lefthook-local: ${lefthook.skipped}`);
176
+ return { dir, done, skipped, lefthook: lefthook?.file ?? null };
177
+ }
178
+
179
+ // Removes only our lines; a file eocrm created goes only when nothing else was added to it.
180
+ export function uninstall(cwd) {
181
+ const dir = hooksDir(cwd);
182
+ const removed = [];
183
+ for (const name of HOOKS) {
184
+ const file = join(dir, name);
185
+ let text;
186
+ try {
187
+ text = read(file);
188
+ } catch {
189
+ continue;
190
+ }
191
+ const clean = strip(text);
192
+ if (clean === text) continue;
193
+ if (text.includes(CREATED) && clean === SHEBANG) unlinkSync(file);
194
+ else write(file, clean);
195
+ removed.push(name);
196
+ }
197
+ if (uninstallLefthook(cwd, worktreeOf(cwd).root)) removed.push('lefthook-local');
198
+ return { dir, removed };
199
+ }
200
+
201
+ export function installed(cwd) {
202
+ try {
203
+ const dir = hooksDir(cwd);
204
+ const local = ours(worktreeOf(cwd).root);
205
+ const block = local ? read(local) : '';
206
+ return HOOKS.filter((n) => (existsSync(join(dir, n)) && read(join(dir, n)).includes(MARK)) || block.includes(`\n${n}: ${MARK}`) || block.startsWith(`${n}: ${MARK}`));
207
+ } catch {
208
+ return [];
209
+ }
210
+ }
@@ -0,0 +1,102 @@
1
+ import { lstatSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { worktreeOf } from '../state.mjs';
5
+ import { LINK, MAX_ITEMS, changeTasks, parseOpenSpec, readChange } from '../plans.mjs';
6
+ import { repoEntry, repoKey, updateRepo } from '../workspace.mjs';
7
+ import { plain } from '../login.mjs';
8
+
9
+ const FENCE = /^\s*(`{3,}|~{3,})/;
10
+ const TITLE = /^# (.+)$/;
11
+ const SECTION = /^## /;
12
+ const WHY = /^## why\s*$/i;
13
+ export const CHANGE_ID = /^\w[\w.-]*$/;
14
+
15
+ // Sections by `## ` heading, fenced lines kept but never split on.
16
+ function sections(text) {
17
+ const out = [{ heading: null, lines: [] }];
18
+ let fence = null;
19
+ for (const line of text.replace(/\r\n?/g, '\n').split('\n')) {
20
+ const f = FENCE.exec(line);
21
+ if (f) fence = fence === null ? f[1][0] : fence === f[1][0] ? null : fence;
22
+ if (fence === null && !f && SECTION.test(line)) out.push({ heading: line, lines: [line] });
23
+ else out.at(-1).lines.push(line);
24
+ }
25
+ return out;
26
+ }
27
+
28
+ export function proposalOf(text, id) {
29
+ const all = sections(text ?? '');
30
+ const title = all[0].lines.map((l) => TITLE.exec(l)?.[1]).find(Boolean)?.trim() || id;
31
+ const why = all.find((s) => WHY.test(s.heading ?? '')) ?? all[1];
32
+ return { title, description: why ? why.lines.join('\n').trim() : null, link: LINK.exec(text ?? '')?.[1] ?? null };
33
+ }
34
+
35
+ export function openChanges(root) {
36
+ let dirs;
37
+ try {
38
+ dirs = readdirSync(join(root, 'openspec', 'changes'), { withFileTypes: true });
39
+ } catch {
40
+ return [];
41
+ }
42
+ const exists = (rel) => {
43
+ try {
44
+ return Boolean(lstatSync(join(root, rel)));
45
+ } catch {
46
+ return false;
47
+ }
48
+ };
49
+ return dirs.filter((d) => (d.isDirectory() || d.isSymbolicLink()) && d.name !== 'archive' && CHANGE_ID.test(d.name)).flatMap((d) => {
50
+ const tasks = readChange(root, changeTasks(d.name));
51
+ if (tasks === null) return exists(changeTasks(d.name)) ? [{ id: d.name, unreadable: true }] : [];
52
+ return [{ id: d.name, tasks, ...proposalOf(readChange(root, `openspec/changes/${d.name}/proposal.md`), d.name) }];
53
+ }).sort((a, b) => a.id.localeCompare(b.id));
54
+ }
55
+
56
+ export const linkChange = (data, cwd, id, key) => {
57
+ const mapping = { ...repoEntry(data, cwd).openspec };
58
+ if (key) mapping[id] = key;
59
+ else delete mapping[id];
60
+ updateRepo(data, cwd, { openspec: mapping });
61
+ };
62
+
63
+ // The ref is a hash, so the remote never leaves the machine.
64
+ const clientRef = (cwd, id) => createHash('sha256').update(`${repoKey(cwd)}#${id}`).digest('hex');
65
+
66
+ export async function importChanges({ client, data, cwd, space, out }) {
67
+ const mapped = repoEntry(data, cwd).openspec ?? {};
68
+ const open = openChanges(worktreeOf(cwd).root).filter((c) => !c.link && !mapped[c.id]);
69
+ const unreadable = open.filter((c) => c.unreadable);
70
+ for (const c of unreadable) out(`${c.id}: unreadable, skipped`);
71
+ const todo = open.filter((c) => !c.unreadable);
72
+ if (!todo.length) {
73
+ out(unreadable.length ? 'nothing else to import' : 'nothing to import: every open change is linked');
74
+ return unreadable.length ? 1 : 0;
75
+ }
76
+ if (!space) {
77
+ const res = await client.conventions();
78
+ const spaces = res.status === 200 && Array.isArray(res.body?.spaces) ? res.body.spaces : null;
79
+ if (!spaces) throw Object.assign(new Error(`spaces unavailable (HTTP ${res.status})`), { exitCode: 3 });
80
+ for (const s of spaces) out(`space ${plain(s.key)} ${plain(s.name)}`);
81
+ throw Object.assign(new Error('choose a space: eocrm openspec import --space <KEY>'), { exitCode: 2 });
82
+ }
83
+ let failed = unreadable.length;
84
+ for (const c of todo) {
85
+ const { items, truncated } = parseOpenSpec(c.tasks);
86
+ if (truncated) out(`${c.id}: plan truncated at ${MAX_ITEMS} items`);
87
+ if (!items.length) {
88
+ out(`${c.id}: no tasks, skipped`);
89
+ continue;
90
+ }
91
+ const res = await client.importTask({ client_ref: clientRef(cwd, c.id), space, title: c.title, description: c.description, plan: { source: 'openspec', path: changeTasks(c.id), items } });
92
+ if ((res.status === 200 || res.status === 201) && res.body?.key) {
93
+ linkChange(data, cwd, c.id, res.body.key);
94
+ out(`${c.id}: ${plain(res.body.key)}`);
95
+ } else {
96
+ const tracked = res.status === 422 && res.body?.code === 'plan_on_other_task';
97
+ if (!tracked) failed++;
98
+ out(`${c.id}: ${tracked ? `already on another task${res.body?.message ? ` (${plain(res.body.message)})` : ''}` : `not imported (HTTP ${res.status}${res.body?.message ? `: ${plain(res.body.message)}` : ''})`}`);
99
+ }
100
+ }
101
+ return failed ? 1 : 0;
102
+ }
@@ -0,0 +1,229 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { appendFileSync, mkdirSync, readFileSync, renameSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { randomBytes } from 'node:crypto';
6
+ import { git, worktreeOf, withLock, loadRun, saveRun, loadWorktree, saveWorktree, liveDirOf, liveSession, gitTimeout, remove } from '../state.mjs';
7
+ import { append } from '../outbox.mjs';
8
+ import { eventId } from '../ids.mjs';
9
+ import { prStatus, repoSlug } from '../git.mjs';
10
+ import { taskFor } from '../detect.mjs';
11
+ import { cloneEntry, repoEntry } from '../workspace.mjs';
12
+ import { ensureRun, gather, handle, logError, reconcileNow, runClient, runsOf, spawnFlush } from '../run.mjs';
13
+ import { flush } from '../flush.mjs';
14
+ import { agentOf, detectAgent } from './attribute.mjs';
15
+
16
+ // A commit-bounded run ends when the next commit comes this long after the last one.
17
+ export const IDLE_MS = 60 * 60 * 1000;
18
+ export const HOOK_MS = 3000;
19
+ const HOOK_GIT_MS = 1000;
20
+ const LOCK_MS = 1500;
21
+ const KEEP_COMMITS = 1000;
22
+ const KEEP_OWN = 200;
23
+ const ENTRY = fileURLToPath(new URL('../../scripts/cli.mjs', import.meta.url));
24
+
25
+ export const sessionOf = (wtKey, agent) => `cli-${wtKey}-${agent}`;
26
+
27
+ export const liveRuns = (data, cwd) => runsOf(data, worktreeOf(cwd).key).filter((r) => !r.ended && r.sessionId.startsWith('cli-'));
28
+
29
+ export const pluginLive = (cwd, now) => {
30
+ const dir = liveDirOf(cwd);
31
+ return dir ? liveSession(dir, now) : null;
32
+ };
33
+
34
+ const queueFile = (data, wtKey) => join(data, 'cli-queue', `${wtKey}.jsonl`);
35
+
36
+ const readQueue = (file) => {
37
+ try {
38
+ return readFileSync(file, 'utf8').split('\n').flatMap((l) => {
39
+ try {
40
+ return l ? [JSON.parse(l)] : [];
41
+ } catch {
42
+ return [];
43
+ }
44
+ });
45
+ } catch {
46
+ return [];
47
+ }
48
+ };
49
+
50
+ function headCommit(cwd) {
51
+ const [sha = '', subject = '', author = '', committer = '', ...body] = git(cwd, ['log', '-1', '--format=%H%x1f%s%x1f%an%x1f%cn%x1f%B']).split('\x1f');
52
+ return { sha, subject, author, committer, message: body.join('\x1f') };
53
+ }
54
+
55
+ // An explicit run (run start) carries its agent to commits that show none.
56
+ export function agentFor(ctx, cwd, commit = {}) {
57
+ const explicit = liveRuns(ctx.data, cwd).find((r) => r.explicit)?.agent;
58
+ return detectAgent({ env: ctx.env, commit }) ?? explicit ?? agentOf({ env: {}, setting: repoEntry(ctx.data, cwd).agent });
59
+ }
60
+
61
+ export function spawnSync(ctx, cwd) {
62
+ try {
63
+ (ctx.spawn ?? spawn)(process.execPath, [ENTRY, 'sync', '--quiet', '--data', ctx.data], { cwd, detached: true, stdio: 'ignore', windowsHide: true, env: ctx.env })
64
+ .on('error', (e) => logError(ctx.data, e))
65
+ .unref();
66
+ } catch (e) {
67
+ logError(ctx.data, e);
68
+ }
69
+ }
70
+
71
+ const finish = (ctx, cwd, sessionId, endedAt) => handle('SessionEnd', { cwd, session_id: sessionId }, { ...ctx, endedAt, spawnFlush: () => {} });
72
+ const lastAt = (run, at) => run.lastCommitAt ?? run.startedAt ?? at;
73
+ const endAt = (run, at) => new Date(Math.min(at, lastAt(run, at) + IDLE_MS)).toISOString();
74
+ const idle = (run, at) => !run.explicit && at - lastAt(run, at) > IDLE_MS;
75
+ const moved = (run, branch) => !run.explicit && (run.start?.branch ?? '') !== branch;
76
+
77
+ // Ends commit-bounded runs idle past IDLE_MS or left on another branch, stamped at the last commit plus IDLE_MS.
78
+ export async function endStale(ctx, cwd) {
79
+ const branch = git(cwd, ['symbolic-ref', '--short', '-q', 'HEAD']);
80
+ const stale = liveRuns(ctx.data, cwd).filter((r) => idle(r, ctx.now()) || moved(r, branch));
81
+ for (const r of stale) await finish(ctx, cwd, r.sessionId, endAt(r, ctx.now()));
82
+ return stale;
83
+ }
84
+
85
+ // Local only: queues the start; the caller sends.
86
+ export async function startRun(ctx, cwd, agent, { explicit = false, at = ctx.now() } = {}) {
87
+ const facts = { ...gather(ctx.data, cwd), newSession: true };
88
+ const sid = sessionOf(facts.wt.key, agent);
89
+ const prev = loadRun(ctx.data, sid);
90
+ if (prev.startedAt && !prev.ended && (idle(prev, at) || moved(prev, facts.branch))) await finish(ctx, cwd, sid, endAt(prev, at));
91
+ const run = await ensureRun({ ...ctx, agent, spawnFlush: () => {} }, { session_id: sid, cwd }, facts);
92
+ if (!run) return null;
93
+ return withLock(ctx.data, async () => saveRun(ctx.data, sid, { agent, ...(explicit ? { explicit: true } : {}) }), { giveUpMs: LOCK_MS });
94
+ }
95
+
96
+ function remember(data, wtKey, shas) {
97
+ const wt = loadWorktree(data, wtKey);
98
+ const known = new Set(wt.reportedCommits);
99
+ saveWorktree(data, wtKey, { reportedCommits: [...wt.reportedCommits, ...shas.filter((s) => !known.has(s))].slice(-KEEP_COMMITS) });
100
+ }
101
+
102
+ // The foreground hook only appends here; the detached sync starts runs and queues events.
103
+ async function postCommit(ctx, cwd) {
104
+ const head = headCommit(cwd);
105
+ if (!head.sha) return 'no commit';
106
+ const wt = worktreeOf(cwd);
107
+ const file = queueFile(ctx.data, wt.key);
108
+ if (loadWorktree(ctx.data, wt.key).reportedCommits.includes(head.sha) || readQueue(file).some((q) => q.sha === head.sha)) return 'duplicate';
109
+ if (pluginLive(cwd, ctx.now())) {
110
+ await withLock(ctx.data, async () => remember(ctx.data, wt.key, [head.sha]), { giveUpMs: LOCK_MS });
111
+ return 'quiet';
112
+ }
113
+ const agent = agentFor(ctx, cwd, head);
114
+ if (!agent) return 'no agent';
115
+ mkdirSync(join(ctx.data, 'cli-queue'), { recursive: true });
116
+ appendFileSync(file, `${JSON.stringify({ sha: head.sha, subject: head.subject, agent, at: ctx.now() })}\n`);
117
+ (ctx.spawnSync ?? spawnSync)(ctx, cwd);
118
+ return 'queued';
119
+ }
120
+
121
+ async function prePush(ctx, cwd) {
122
+ if (pluginLive(cwd, ctx.now()) || !liveRuns(ctx.data, cwd).length) return 'quiet';
123
+ (ctx.spawnSync ?? spawnSync)(ctx, cwd);
124
+ return 'queued';
125
+ }
126
+
127
+ async function postCheckout(ctx, cwd, [, , branchFlag]) {
128
+ if (branchFlag !== '1' || pluginLive(cwd, ctx.now()) || !liveRuns(ctx.data, cwd).length) return 'quiet';
129
+ (ctx.spawnSync ?? spawnSync)(ctx, cwd);
130
+ return 'queued';
131
+ }
132
+
133
+ const HOOKS = { 'post-commit': postCommit, 'pre-push': prePush, 'post-checkout': postCheckout };
134
+
135
+ // Never touches the network, and gives up after HOOK_MS: queues, then a detached process sends.
136
+ export async function runHook(ctx, name, cwd, args = []) {
137
+ const hook = HOOKS[name];
138
+ if (!hook) return 'unknown hook';
139
+ const budget = ctx.hookMs ?? HOOK_MS;
140
+ Object.assign(gitTimeout, { ms: HOOK_GIT_MS, deadline: Date.now() + budget });
141
+ if (!cloneEntry(ctx.data, cwd).initialized) return 'not initialized';
142
+ let timer;
143
+ const late = new Promise((resolve) => {
144
+ timer = setTimeout(() => resolve('timeout'), budget);
145
+ timer.unref?.();
146
+ });
147
+ try {
148
+ return await Promise.race([hook(ctx, cwd, args), late]);
149
+ } catch (e) {
150
+ logError(ctx.data, e);
151
+ return 'failed';
152
+ } finally {
153
+ clearTimeout(timer);
154
+ gitTimeout.deadline = null;
155
+ }
156
+ }
157
+
158
+ // Takes the queue by rename, so two syncs never process one commit twice.
159
+ async function drain(ctx, cwd) {
160
+ const wt = worktreeOf(cwd);
161
+ const file = queueFile(ctx.data, wt.key);
162
+ const taken = `${file}.${process.pid}.${randomBytes(4).toString('hex')}`;
163
+ try {
164
+ renameSync(file, taken);
165
+ } catch {
166
+ return;
167
+ }
168
+ const items = readQueue(taken).sort((a, b) => a.at - b.at);
169
+ const repo = repoSlug(cwd);
170
+ let i = 0;
171
+ try {
172
+ for (; i < items.length; i++) await queueCommit(ctx, cwd, wt, repo, items[i]);
173
+ } catch (e) {
174
+ appendFileSync(file, items.slice(i).map((item) => `${JSON.stringify(item)}\n`).join(''));
175
+ throw e;
176
+ } finally {
177
+ remove(taken);
178
+ }
179
+ }
180
+
181
+ async function queueCommit(ctx, cwd, wt, repo, item) {
182
+ const run = await (ctx.startRun ?? startRun)(ctx, cwd, item.agent, { at: item.at });
183
+ if (!run) return;
184
+ const task = taskFor(ctx, { cwd, session_id: run.sessionId });
185
+ await withLock(ctx.data, async () => {
186
+ const cur = loadRun(ctx.data, run.sessionId);
187
+ const occurred_at = new Date(item.at).toISOString();
188
+ const task_key = task(cur);
189
+ append(ctx.data,
190
+ { kind: 'event', sessionId: cur.sessionId, event: { id: eventId('commit', item.sha), type: 'commit', occurred_at, sha: item.sha, subject: item.subject, ...(repo ? { repo } : {}), task_key } },
191
+ // Between commits the run shows idle, not stalled.
192
+ { kind: 'event', sessionId: cur.sessionId, event: { id: eventId('turn', `${cur.clientRunId}:${item.sha}`), type: 'turn', phase: 'ended', occurred_at, task_key } });
193
+ saveRun(ctx.data, cur.sessionId, { lastCommitAt: item.at, ownCommits: [...new Set([...(cur.ownCommits ?? []), item.sha])].slice(-KEEP_OWN) });
194
+ remember(ctx.data, wt.key, [item.sha]);
195
+ }, { giveUpMs: LOCK_MS });
196
+ }
197
+
198
+ export async function queuePr(ctx, cwd, run) {
199
+ const pr = (ctx.prStatus ?? prStatus)(cwd);
200
+ if (!pr) return null;
201
+ const id = eventId('pull_request', `${pr.action}:${pr.url}`);
202
+ await withLock(ctx.data, async () => {
203
+ const cur = loadRun(ctx.data, run.sessionId);
204
+ if (cur.ended || cur.acked[id]) return;
205
+ append(ctx.data, { kind: 'event', sessionId: cur.sessionId, event: { id, type: 'pull_request', occurred_at: new Date(ctx.now()).toISOString(), ...pr, repo: pr.url.split('/').slice(3, 5).join('/'), task_key: cur.start?.task ?? null } });
206
+ }, { giveUpMs: LOCK_MS });
207
+ return pr;
208
+ }
209
+
210
+ // Stale runs end, queued commits start or continue runs, then plans, reconcile and the PR check per live run, then a send.
211
+ export async function sync(ctx, cwd) {
212
+ if (pluginLive(cwd, ctx.now())) return { quiet: true, runs: 0 };
213
+ await endStale(ctx, cwd);
214
+ await drain(ctx, cwd).catch((e) => logError(ctx.data, e));
215
+ const runs = liveRuns(ctx.data, cwd);
216
+ for (const run of runs) {
217
+ await queuePr(ctx, cwd, run).catch((e) => logError(ctx.data, e));
218
+ await reconcileNow({ ...ctx, spawnFlush: () => {} }, { session_id: run.sessionId, cwd }, 'Stop');
219
+ }
220
+ const result = await flush({ data: ctx.data, clientFor: runClient(ctx), harness: 'cli' });
221
+ return { quiet: false, runs: runs.length, result };
222
+ }
223
+
224
+ export async function stopRuns(ctx, cwd) {
225
+ const runs = liveRuns(ctx.data, cwd);
226
+ for (const r of runs) await finish(ctx, cwd, r.sessionId);
227
+ if (runs.length) (ctx.spawnFlush ?? spawnFlush)(ctx);
228
+ return runs;
229
+ }
package/lib/codex.mjs ADDED
@@ -0,0 +1,78 @@
1
+ import { basename } from 'node:path';
2
+ import { pathFor } from './plans.mjs';
3
+
4
+ export const SHELL_TOOLS = new Set(['Bash', 'shell', 'local_shell', 'exec_command', 'container.exec']);
5
+ const SHELLS = new Set(['bash', 'sh', 'zsh']);
6
+ const PATCH_PATH = /^\*\*\* (?:Add File|Update File|Move to): (.+)$/gm;
7
+ const SAME = new Set(['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'Stop']);
8
+
9
+ const TEST_MARK = /\s*#\s*eocrm:test\s*$/;
10
+
11
+ const quote = (w) => (/^[\w@%+=:,./-]+$/.test(w) ? w : `'${w.replace(/'/g, "'\\''")}'`);
12
+
13
+ function command(ti) {
14
+ const c = ti?.command ?? ti?.cmd;
15
+ if (typeof c === 'string') return c;
16
+ if (!Array.isArray(c)) return '';
17
+ if (SHELLS.has(basename(String(c[0])))) {
18
+ for (let i = 1; i < c.length - 1 && String(c[i]).startsWith('-'); i++) if (/^-[A-Za-z]*c[A-Za-z]*$/.test(c[i])) return String(c[i + 1]);
19
+ }
20
+ return c.map((w) => quote(String(w))).join(' ');
21
+ }
22
+
23
+ function response(r) {
24
+ if (typeof r === 'string') return { stdout: r, stderr: '', exit: null };
25
+ if (!r || typeof r !== 'object') return r;
26
+ const exit = [r.exit_code, r.exitCode, r.exit].find(Number.isInteger) ?? null;
27
+ return { stdout: String(r.aggregated_output ?? r.formatted_output ?? r.output ?? r.stdout ?? ''), stderr: typeof r.stderr === 'string' ? r.stderr : '', exit };
28
+ }
29
+
30
+ function tool(input) {
31
+ const ti = input.tool_input ?? {};
32
+ if (SHELL_TOOLS.has(input.tool_name)) {
33
+ const raw = command(ti);
34
+ const marked = TEST_MARK.test(raw);
35
+ const cmd = marked ? raw.replace(TEST_MARK, '') : raw;
36
+ const tool_input = marked ? { command: cmd, description: `test: ${cmd.trim().split('\n')[0]}` } : { command: cmd };
37
+ if (typeof ti.workdir === 'string') tool_input.workdir = ti.workdir;
38
+ return { ...input, tool_name: 'Bash', tool_input, tool_response: response(input.tool_response) };
39
+ }
40
+ if (input.tool_name === 'apply_patch') {
41
+ const text = [ti.input, ti.patch, ti.command].flat().filter((s) => typeof s === 'string').join('\n');
42
+ const cwd = input.cwd ?? '';
43
+ const file_paths = [...text.matchAll(PATCH_PATH)].map((m) => pathFor(cwd).resolve(cwd, m[1].trim()));
44
+ return { ...input, tool_name: 'Write', tool_input: { file_paths } };
45
+ }
46
+ if (input.tool_name === 'update_plan') {
47
+ const plan = Array.isArray(ti.plan) ? ti.plan : [];
48
+ return { ...input, tool_name: 'TodoWrite', tool_input: { todos: plan.filter((p) => typeof p?.step === 'string').map((p) => ({ content: p.step, status: p.status })) } };
49
+ }
50
+ return input;
51
+ }
52
+
53
+ const n = (v) => (Number.isFinite(v) && v > 0 ? v : 0);
54
+
55
+ export function addModelUsage(run, input) {
56
+ const u = input.token_usage;
57
+ if (input.status !== 'completed' || !u || typeof input.model !== 'string' || !input.model) return null;
58
+ const all = { ...run.codexUsage };
59
+ const t = { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, ...all[input.model] };
60
+ t.input_tokens += n(n(u.input_tokens) - n(u.cached_input_tokens));
61
+ t.output_tokens += n(u.output_tokens) + n(u.reasoning_output_tokens);
62
+ t.cache_read_tokens += n(u.cached_input_tokens ?? u.cache_read_input_tokens);
63
+ t.cache_write_tokens += n(u.cache_write_input_tokens ?? u.cache_creation_input_tokens);
64
+ all[input.model] = t;
65
+ return { codexUsage: all };
66
+ }
67
+
68
+ export function codexEvents(event, raw) {
69
+ const input = { ...raw };
70
+ delete input.prompt;
71
+ delete input.last_assistant_message;
72
+ if (SAME.has(event)) return [{ event, input }];
73
+ if (event === 'PreToolUse' || event === 'Remind') return [{ event, input: tool(input) }];
74
+ if (event === 'PostToolUse') return [{ event: 'Resume', input }, { event, input: tool(input) }];
75
+ if (event === 'PostModelRequest') return [{ event, input }];
76
+ if (event === 'PermissionRequest') return [{ event: 'Notification', input: { ...input, notification_type: 'permission_prompt' } }];
77
+ return [];
78
+ }