@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.
package/lib/flush.mjs ADDED
@@ -0,0 +1,260 @@
1
+ import { join } from 'node:path';
2
+ import { createHash } from 'node:crypto';
3
+ import { withLock, loadRun, saveRun } from './state.mjs';
4
+ import { readOutbox, rewrite } from './outbox.mjs';
5
+ import { logError } from './run.mjs';
6
+ import { VERSION } from './api.mjs';
7
+
8
+ const BATCH = 100;
9
+ const EXTRA_PASSES = 3;
10
+ const KEEP_REJECTED = 50;
11
+ const KEEP_FINGERPRINTS = 500;
12
+ const KEEP_MESSAGES = 50;
13
+ const KEEP_MESSAGE_IDS = 500;
14
+ export const KEEP_ACKS = 100;
15
+ const MAX_MESSAGES = 20;
16
+ const KINDS = new Set(['plugin_update', 'task_comment', 'notice', 'task_unfinished']);
17
+ const AUDIENCES = new Set(['member', 'agent']);
18
+ const EVENT_KEY = /^events\.(\d+)(?:\.(.+))?$/;
19
+ const GIVE_UP_MS = 5000;
20
+ const lockFor = (end) => ({ giveUpMs: Math.max(0, Math.min(GIVE_UP_MS, end - Date.now())) });
21
+ // A server older than the plugin refuses these; they must never block the stop gate.
22
+ const SIGNALS = new Set(['waiting', 'resumed', 'turn']);
23
+ const isTick = (e) => e.kind === 'event' && e.event?.type === 'step' && e.event.plan_key != null;
24
+
25
+ const local = (id, text) => ({ id: `local:${id}`, kind: 'notice', audience: 'member', text });
26
+ const OFF = local('module_disabled', 'eocrm: Agent work is off for this workspace.');
27
+ const signedOut = (harness) => local('signed_out', harness === 'cli' ? 'eocrm: you\'re signed out of eocrm; run eocrm login.' : 'eocrm: you\'re signed out of eocrm; run /eocrm:login (Codex: the login skill).');
28
+ const below = (what, minimum) => `eocrm: ${what} ${VERSION} is below the minimum ${String(minimum ?? 'version').slice(0, 40)}, so tracking is paused.`;
29
+ export const outdatedNotice = (minimum, harness) => local(`outdated:${VERSION}`, harness === 'cli' ? `${below('CLI', minimum)} Run npx @eocrm/cli@latest init.` : `${below('plugin', minimum)} Run /plugin marketplace update eocrm (Codex: codex plugin marketplace upgrade eocrm).`);
30
+
31
+ export const fingerprint = (r) => createHash('sha256').update(JSON.stringify([r.type, r.eventId ?? null, r.status, r.code ?? null, r.message])).digest('base64url').slice(0, 22);
32
+
33
+ export const clientRunId = (sessionId, generation) => (generation ? `${sessionId}.${generation}` : sessionId);
34
+
35
+ function classify(status) {
36
+ if (status >= 200 && status < 300) return 'ok';
37
+ if (status === 401) return 'signedOut';
38
+ if (status === 404 || status === 409) return 'roll';
39
+ if (status === 400 || status === 403 || status === 422) return 'reject';
40
+ if (status >= 400 && status < 500 && status !== 408 && status !== 429) return 'refuse';
41
+ return 'retry';
42
+ }
43
+
44
+ function nextBatch(events) {
45
+ const batch = [];
46
+ for (const entry of events) {
47
+ if (batch.length === BATCH) break;
48
+ // The server ticks against a batch's latest plan, so each plan opens its own batch.
49
+ if (entry.event.type === 'plan' && batch.length) break;
50
+ batch.push(entry);
51
+ }
52
+ return batch;
53
+ }
54
+
55
+ function rejection(entry, status, body, message, fields) {
56
+ const e = entry.event ?? {};
57
+ return {
58
+ ...(fields?.length ? { fields } : {}),
59
+ eventId: e.id ?? null,
60
+ type: e.type ?? entry.kind,
61
+ label: e.label ?? e.subject ?? e.command ?? e.url ?? e.what ?? e.summary ?? entry.step ?? entry.kind,
62
+ status,
63
+ ...(typeof body?.code === 'string' ? { code: body.code } : {}),
64
+ message: message ?? (typeof body?.message === 'string' ? body.message : `HTTP ${status}`),
65
+ };
66
+ }
67
+
68
+ const lifecycle = (action, run) => (action.kind === 'start' || action.kind === 'finish' ? run : undefined);
69
+
70
+ function plan(pending, run) {
71
+ const starts = pending.filter((e) => e.kind === 'start');
72
+ if (!run.runId || starts.length) return { kind: 'start', entries: starts };
73
+ const events = pending.filter((e) => e.kind === 'event');
74
+ if (events.length) return { kind: 'event', entries: nextBatch(events) };
75
+ for (const kind of ['task', 'step', 'heartbeat', 'finish']) {
76
+ const entries = pending.filter((e) => e.kind === kind);
77
+ if (entries.length) return { kind, entries };
78
+ }
79
+ return null;
80
+ }
81
+
82
+ function unfinishedData(data) {
83
+ const { key, status } = data ?? {};
84
+ return { key: String(key ?? ''), status: typeof status === 'string' && status.length <= 40 ? status : '' };
85
+ }
86
+
87
+ const messagesOf = (body) => (Array.isArray(body?.messages) ? body.messages.slice(0, MAX_MESSAGES) : [])
88
+ .filter((m) => typeof m?.id === 'string' && KINDS.has(m.kind) && AUDIENCES.has(m.audience) && typeof m.text === 'string')
89
+ .map((m) => ({
90
+ id: m.id.slice(0, 64),
91
+ kind: m.kind,
92
+ audience: m.audience,
93
+ text: m.text.slice(0, 1000),
94
+ ...(typeof m.data?.reload === 'string' ? { data: { reload: m.data.reload } } : {}),
95
+ ...(m.kind === 'task_unfinished' ? { data: unfinishedData(m.data) } : {}),
96
+ }));
97
+
98
+ function send(client, run, sessionId, { kind, entries }, ack) {
99
+ if (kind === 'start') return client.startRun({ ...run.start, client_run_id: clientRunId(run.owner ?? sessionId, run.generation ?? 0) });
100
+ if (kind === 'event') return client.recordEvents(run.runId, entries.map((e) => e.event), ack);
101
+ if (kind === 'task') return client.updateRun(run.runId, { task: entries.at(-1).task });
102
+ if (kind === 'step') return client.updateRun(run.runId, { step: entries.at(-1).step });
103
+ if (kind === 'heartbeat') return client.heartbeat(run.runId, ack);
104
+ const endedAt = entries.at(-1)?.endedAt;
105
+ return client.updateRun(run.runId, { state: 'finished', ...(endedAt ? { ended_at: endedAt } : {}) });
106
+ }
107
+
108
+ function rejectedEntries(action, status, body) {
109
+ const keys = Object.keys(body?.errors ?? {});
110
+ const indexed = action.kind === 'event' && status === 422 && keys.length > 0 && keys.every((k) => EVENT_KEY.test(k));
111
+ if (!indexed) return action.entries.map((entry) => [entry, null, []]);
112
+ const byIndex = new Map();
113
+ for (const k of keys) {
114
+ const [, i, field] = EVENT_KEY.exec(k);
115
+ const hit = byIndex.get(Number(i)) ?? { messages: [], fields: [] };
116
+ hit.messages.push(...body.errors[k]);
117
+ if (field) hit.fields.push(field);
118
+ byIndex.set(Number(i), hit);
119
+ }
120
+ const hit = [...byIndex].filter(([i]) => action.entries[i]).map(([i, h]) => [action.entries[i], h.messages.join(' '), h.fields]);
121
+ return hit.length ? hit : action.entries.map((entry) => [entry, null, []]);
122
+ }
123
+
124
+ // A rejected plan's ticks, up to the next plan, go unsent and unrecorded: alone they would tick the previous plan.
125
+ function orphanedTicks(pending, rejected) {
126
+ const gone = new Set(rejected.map(([entry]) => entry));
127
+ const out = [];
128
+ let orphan = false;
129
+ for (const entry of pending) {
130
+ if (entry.kind === 'event' && entry.event?.type === 'plan') orphan = gone.has(entry);
131
+ else if (orphan && isTick(entry) && !gone.has(entry)) out.push(entry);
132
+ }
133
+ return out;
134
+ }
135
+
136
+ async function settle(data, sessionId, { removed = [], acked = [], rejected = [], patch = {}, messages = [], ackSent = [], notices = [], sentRun }, end) {
137
+ await withLock(data, async () => {
138
+ const gone = new Set(removed.map((e) => e.seq));
139
+ rewrite(data, (entries) => entries.filter((e) => !gone.has(e.seq)));
140
+ const run = loadRun(data, sessionId);
141
+ if (sentRun && (run.generation ?? 0) !== (sentRun.generation ?? 0)) {
142
+ saveRun(data, `${sessionId}--w${sentRun.generation ?? 0}`, patch);
143
+ patch = {};
144
+ }
145
+ const seen = new Set(run.rejectedFingerprints ?? run.rejected.map(fingerprint));
146
+ const fresh = rejected.filter((r) => {
147
+ const fp = fingerprint(r);
148
+ return !seen.has(fp) && seen.add(fp);
149
+ });
150
+ const known = new Set(run.messageIds ?? []);
151
+ const arrived = [...messages, ...notices].filter((m) => !known.has(m.id) && known.add(m.id));
152
+ const sent = new Set(ackSent);
153
+ if (arrived.some((m) => m.kind === 'notice' && m.data?.reload === 'conventions')) patch = { ...patch, conventionsAt: null };
154
+ if (messages.length || ackSent.length || notices.length) {
155
+ const all = [...(run.inbox ?? []), ...arrived];
156
+ const inbox = all.slice(-KEEP_MESSAGES);
157
+ const evicted = new Set(all.slice(0, -KEEP_MESSAGES).map((m) => m.id));
158
+ const kept = new Set(inbox.map((m) => m.id));
159
+ const shown = messages.filter((m) => (run.messageIds ?? []).includes(m.id) && !kept.has(m.id) && !evicted.has(m.id));
160
+ for (const id of evicted) known.delete(id);
161
+ patch = {
162
+ ...patch,
163
+ inbox,
164
+ messageIds: [...known].slice(-KEEP_MESSAGE_IDS),
165
+ ackPending: [...new Set([...(run.ackPending ?? []).filter((id) => !sent.has(id)), ...shown.map((m) => m.id)])].slice(-KEEP_ACKS),
166
+ };
167
+ }
168
+ saveRun(data, sessionId, {
169
+ ...patch,
170
+ acked: { ...(patch.acked ?? run.acked), ...Object.fromEntries(acked.map((id) => [id, true])) },
171
+ rejected: [...run.rejected, ...fresh].slice(-KEEP_REJECTED),
172
+ rejectedFingerprints: [...seen].slice(-KEEP_FINGERPRINTS),
173
+ });
174
+ }, lockFor(end));
175
+ }
176
+
177
+ async function flushSession(data, sessionId, clientFor, end, result, harness) {
178
+ let rolled = false;
179
+ for (;;) {
180
+ const pending = readOutbox(data).filter((e) => e.sessionId === sessionId);
181
+ if (!pending.length) return;
182
+ if (Date.now() >= end) {
183
+ result.retryable = true;
184
+ return;
185
+ }
186
+ const run = loadRun(data, sessionId);
187
+ if (!run.runId && run.startBlocked) return;
188
+ if (run.outdated?.version === VERSION) return;
189
+ const action = plan(pending, run);
190
+ const ack = action.kind === 'event' || action.kind === 'heartbeat' ? run.ackPending ?? [] : [];
191
+ const { status, body } = await send(clientFor(run), run, sessionId, action, ack);
192
+ if (status === 426) {
193
+ await settle(data, sessionId, { patch: { outdated: { minimum: body?.minimum ?? null, latest: body?.latest ?? null, at: Date.now(), version: VERSION } }, notices: [outdatedNotice(body?.minimum, harness)] }, end);
194
+ return;
195
+ }
196
+ let outcome = classify(status);
197
+ if (outcome === 'roll' && action.kind === 'start') outcome = 'reject';
198
+ else if (outcome === 'roll' && action.kind !== 'event') outcome = 'drop';
199
+
200
+ const ended = action.kind === 'finish' ? { ended: true } : {};
201
+ if (outcome === 'drop') {
202
+ await settle(data, sessionId, { removed: action.entries, patch: ended, sentRun: lifecycle(action, run) }, end);
203
+ } else if (outcome === 'ok') {
204
+ const acked = action.kind === 'event' ? action.entries.map((e) => e.event.id) : [];
205
+ const patch = action.kind === 'start' ? { runId: body?.id, generation: run.generation ?? 0, clientRunId: clientRunId(run.owner ?? sessionId, run.generation ?? 0) } : {};
206
+ await settle(data, sessionId, { removed: action.entries, acked, patch: { ...patch, ...ended }, messages: messagesOf(body), ackSent: ack, sentRun: lifecycle(action, run) }, end);
207
+ result.sent += action.entries.length;
208
+ if (action.kind === 'start' && typeof body?.id !== 'string') return;
209
+ } else if (outcome === 'reject' || outcome === 'refuse') {
210
+ const rejected = rejectedEntries(action, status, body);
211
+ const orphans = action.kind === 'event' ? orphanedTicks(pending, rejected) : [];
212
+ const all = (rejected.length ? rejected : [[{ kind: action.kind }, null, []]]).map(([entry, message, fields]) => rejection(entry, status, body, message, fields));
213
+ const records = all.filter((r) => !SIGNALS.has(r.type));
214
+ if (records.length < all.length) logError(data, `eocrm: dropped ${all.length - records.length} refused signal event(s) (HTTP ${status})`);
215
+ const patch = action.kind === 'start' && outcome === 'reject' ? { startBlocked: fingerprint(records[0]) } : ended;
216
+ await settle(data, sessionId, { removed: [...rejected.map(([entry]) => entry), ...orphans], rejected: records, patch, notices: body?.code === 'module_disabled' ? [OFF] : [], sentRun: lifecycle(action, run) }, end);
217
+ result.rejected.push(...records);
218
+ if (action.kind === 'start') return;
219
+ } else if (outcome === 'roll' && !rolled) {
220
+ rolled = true;
221
+ const generation = (run.generation ?? 0) + 1;
222
+ await settle(data, sessionId, { patch: { generation, runId: null, clientRunId: clientRunId(run.owner ?? sessionId, generation), acked: {}, serverEventsRead: false } }, end);
223
+ } else {
224
+ if (outcome !== 'signedOut') result.retryable = true;
225
+ else {
226
+ result.signedOut = true;
227
+ await settle(data, sessionId, { notices: [signedOut(harness)] }, end);
228
+ }
229
+ return;
230
+ }
231
+ }
232
+ }
233
+
234
+ export async function flush({ data, sessionId, deadlineMs = 20000, lockWaitMs = 0, clientFor, harness }) {
235
+ const result = { sent: 0, rejected: [], retryable: false, signedOut: false };
236
+ const end = Date.now() + deadlineMs;
237
+ try {
238
+ await withLock(join(data, 'flush'), async () => {
239
+ for (let pass = 0; pass <= EXTRA_PASSES; pass++) {
240
+ await withLock(data, async () => rewrite(data, (entries) => entries), lockFor(end)).catch(() => {});
241
+ const before = readOutbox(data);
242
+ const seen = new Set(before.map((e) => e.seq));
243
+ const sessions = sessionId ? [sessionId] : [...new Set(before.map((e) => e.sessionId))];
244
+ for (const sid of sessions) {
245
+ try {
246
+ await flushSession(data, sid, clientFor, end, result, harness);
247
+ } catch {
248
+ result.retryable = true;
249
+ }
250
+ if (result.signedOut) return;
251
+ }
252
+ const arrived = readOutbox(data).some((e) => !seen.has(e.seq) && (!sessionId || e.sessionId === sessionId));
253
+ if (!arrived || result.retryable || Date.now() >= end) return;
254
+ }
255
+ }, { giveUpMs: lockWaitMs });
256
+ } catch {
257
+ result.retryable = true;
258
+ }
259
+ return result;
260
+ }
package/lib/gate.mjs ADDED
@@ -0,0 +1,87 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { withLock, loadRun, saveRun } from './state.mjs';
3
+ import { flush, fingerprint } from './flush.mjs';
4
+ import { clean } from './scrub.mjs';
5
+ import { endpoints } from './endpoints.mjs';
6
+ import { storeFor } from './credentials.mjs';
7
+ import { until } from './reconcile.mjs';
8
+ import { reconcileNow, runClient, logError, waitMs } from './run.mjs';
9
+ import { drain, output, toMember } from './remind.mjs';
10
+
11
+ // Under the hook's 30 s timeout, with room for node to start and exit.
12
+ const GATE_MS = 24000;
13
+ const FLUSH_MS = 20000;
14
+ const REQUEST_MS = 3000;
15
+ // A send can outlast flush's deadline by one call, its refresh and its retry.
16
+ const OVERRUN_MS = 3 * REQUEST_MS + 1000;
17
+ const SHOWN = 5;
18
+ const REASON_MAX = 1000;
19
+ const LABEL_MAX = 80;
20
+ const KEEP = 500;
21
+ const LOCK_MS = 1500;
22
+ const TAIL = '. Fix what it names or tell the member; tracking continues.';
23
+ const WORD = /^[a-z_]{1,40}$/;
24
+ const FIELD = /^[a-z_.]{1,40}$/;
25
+ const UNSAFE = /["'`‘-‟\p{Cc}\p{Cf}]/gu;
26
+
27
+ // Server free text never reaches the model: only patterned tokens and the member's own label.
28
+ function item(r) {
29
+ const label = [...clean(String(r.label ?? ''), 4000).replace(UNSAFE, '')].slice(0, LABEL_MAX).join('');
30
+ const detail = [r.status, WORD.test(r.code) ? r.code : null, ...(Array.isArray(r.fields) ? r.fields.filter((f) => FIELD.test(f)) : [])];
31
+ return `${WORD.test(r.type) ? r.type : 'event'} "${label}" (${detail.filter((d) => d != null).join(' ')})`;
32
+ }
33
+
34
+ function reason(rejected) {
35
+ const head = `eocrm refused ${rejected.length} tracking update(s): ${rejected.slice(-SHOWN).map(item).join('; ')}`;
36
+ return clean(head, REASON_MAX - TAIL.length) + TAIL;
37
+ }
38
+
39
+ async function gate(ctx, input, before, end) {
40
+ const left = (cap) => waitMs(cap, end);
41
+ const sid = input.session_id;
42
+ if (!(await before(end))) return {};
43
+ await reconcileNow(ctx, input, 'Stop', end);
44
+ const run = loadRun(ctx.data, sid);
45
+ const store = ctx.store ?? storeFor(ctx.data, ctx.harness);
46
+ const key = run.region ? endpoints({ region: run.region, env: ctx.env }).key : null;
47
+ const failed = key ? (await store.get(key, { timeoutMs: left(2500) }).catch(() => null))?.access_token : null;
48
+ const deadlineMs = Math.max(0, Math.min(FLUSH_MS, end - Date.now() - OVERRUN_MS));
49
+ const clientFor = ctx.clientFor ?? runClient({ ...ctx, store }, { timeoutMs: REQUEST_MS, end });
50
+ const result = await flush({ data: ctx.data, sessionId: sid, deadlineMs, lockWaitMs: deadlineMs, clientFor });
51
+ // Only the tokens that got the 401: a login since then stays.
52
+ if (result.signedOut && failed) await store.del(key, { when: (t) => t?.access_token === failed, timeoutMs: left(5000) }).catch((e) => logError(ctx.data, e));
53
+
54
+ const decision = await block(ctx, input, end);
55
+ // Last, so a throw or deadline above keeps the inbox. An agent line at Stop would need a block.
56
+ return output(decision, await drain(ctx, sid, toMember, Math.max(0, Math.min(500, end - Date.now()))));
57
+ }
58
+
59
+ async function block(ctx, input, end) {
60
+ const sid = input.session_id;
61
+ const { rejected: all, blockedFingerprints } = loadRun(ctx.data, sid);
62
+ // Agent work is off: nothing to enforce, the member notice says so.
63
+ const rejected = all.filter((r) => r.code !== 'module_disabled');
64
+ if (!rejected.length) return {};
65
+ const fp = createHash('sha256').update(rejected.map(fingerprint).sort().join('\n')).digest('base64url');
66
+ if (blockedFingerprints.includes(fp)) return {};
67
+ try {
68
+ await withLock(ctx.data, async () => {
69
+ const seen = loadRun(ctx.data, sid).blockedFingerprints;
70
+ saveRun(ctx.data, sid, { blockedFingerprints: [...seen, fp].slice(-KEEP) });
71
+ }, { giveUpMs: Math.max(0, Math.min(LOCK_MS, end - Date.now())) });
72
+ } catch (e) {
73
+ logError(ctx.data, e);
74
+ // Unrecorded, the same block would loop through every continuation.
75
+ if (input.stop_hook_active) return {};
76
+ }
77
+ return { decision: 'block', reason: reason(rejected) };
78
+ }
79
+
80
+ export async function stopGate(ctx, input, before = async () => true) {
81
+ const end = Date.now() + GATE_MS;
82
+ const body = gate(ctx, input, before, end).catch((e) => {
83
+ logError(ctx.data, e);
84
+ return {};
85
+ });
86
+ return (await until(body, end)) ?? {};
87
+ }
package/lib/git.mjs ADDED
@@ -0,0 +1,101 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { git } from './state.mjs';
3
+ import { clean } from './scrub.mjs';
4
+
5
+ const BASES = ['refs/remotes/origin/HEAD', 'refs/remotes/origin/main', 'refs/remotes/origin/master', 'refs/heads/main', 'refs/heads/master'];
6
+
7
+ const SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
8
+ const FORGE = /^(?:www\.)?(?:github\.com|gitlab\.com|bitbucket\.org)$/i;
9
+ const UNSAFE = /[@:?#]/;
10
+
11
+ export function repoSlug(cwd, origin = git(cwd, ['remote', 'get-url', 'origin'])) {
12
+ const url = origin.trim();
13
+ let host;
14
+ let path;
15
+ if (SCHEME.test(url)) {
16
+ try {
17
+ ({ hostname: host, pathname: path } = new URL(url));
18
+ } catch {
19
+ return null;
20
+ }
21
+ } else {
22
+ const colon = url.indexOf(':');
23
+ if (colon < 0) return null;
24
+ const auth = url.slice(0, colon);
25
+ host = auth.slice(auth.lastIndexOf('@') + 1);
26
+ path = url.slice(colon + 1);
27
+ if (host.length < 2 || /[\\/]/.test(host)) return null;
28
+ }
29
+ path = path.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '');
30
+ if (!host || !path || UNSAFE.test(host + path)) return null;
31
+ return clean(FORGE.test(host) ? path : `${host}/${path}`, 200);
32
+ }
33
+
34
+ export function budget(ms, { exec = execFileSync, now = Date.now } = {}) {
35
+ const end = now() + ms;
36
+ return (cmd, args, opts) => {
37
+ const left = end - now();
38
+ if (left <= 0) throw new Error('eocrm: hook budget spent');
39
+ return exec(cmd, args, { ...opts, timeout: Math.min(opts.timeout || left, left) });
40
+ };
41
+ }
42
+
43
+ export function mergeBase(cwd, run) {
44
+ const have = new Set(git(cwd, ['for-each-ref', '--format=%(refname)', ...BASES], run).split('\n'));
45
+ const ref = BASES.find((r) => have.has(r));
46
+ return (ref && git(cwd, ['merge-base', 'HEAD', ref], run)) || null;
47
+ }
48
+
49
+ export function defaultBranch(cwd, run) {
50
+ const remote = git(cwd, ['symbolic-ref', '--short', '-q', 'refs/remotes/origin/HEAD'], run);
51
+ if (remote) return remote.replace(/^origin\//, '');
52
+ const have = git(cwd, ['for-each-ref', '--format=%(refname:short)', 'refs/heads/main', 'refs/heads/master'], run).split('\n');
53
+ return ['main', 'master'].find((b) => have.includes(b)) ?? null;
54
+ }
55
+
56
+ export function branchCommits(cwd, limit = 200, run) {
57
+ const base = mergeBase(cwd, run);
58
+ if (!base) return [];
59
+ const log = git(cwd, ['log', '-z', `-n${limit}`, '--format=%H%x1f%s', `${base}..HEAD`], run);
60
+ return log.split('\0').filter(Boolean).map((line) => {
61
+ const [sha, subject = ''] = line.split('\x1f');
62
+ return { sha: sha.trim(), subject };
63
+ }).reverse();
64
+ }
65
+
66
+ export function localBranches(cwd, run) {
67
+ const out = git(cwd, ['for-each-ref', '--format=%(refname:short)', 'refs/heads'], run);
68
+ return out ? out.split('\n') : null;
69
+ }
70
+
71
+ export function prView(cwd, arg, run = execFileSync) {
72
+ try {
73
+ const args = ['pr', 'view', ...(arg ? [arg] : []), '--json', 'url', '-q', '.url'];
74
+ return String(run('gh', args, { cwd, encoding: 'utf8', timeout: 5000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] })).trim() || null;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+
80
+ // undefined: gh is not installed, so the caller stops asking.
81
+ export function prState(cwd, url, run = execFileSync) {
82
+ try {
83
+ return String(run('gh', ['pr', 'view', url, '--json', 'state', '-q', '.state'], { cwd, encoding: 'utf8', timeout: 5000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] })).trim() || null;
84
+ } catch (e) {
85
+ return e?.code === 'ENOENT' ? undefined : null;
86
+ }
87
+ }
88
+
89
+ const PULL = /^https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/\d+$/;
90
+ const PR_ACTIONS = { OPEN: 'opened', MERGED: 'merged' };
91
+
92
+ // The current branch's PR, via an installed and signed-in gh; a closed PR has no eocrm action.
93
+ export function prStatus(cwd, run = execFileSync) {
94
+ try {
95
+ const o = JSON.parse(String(run('gh', ['pr', 'view', '--json', 'url,state,number'], { cwd, encoding: 'utf8', timeout: 5000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] })));
96
+ const action = PR_ACTIONS[o?.state];
97
+ return action && PULL.test(o.url) && Number.isInteger(o.number) ? { action, url: o.url, number: o.number } : null;
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
package/lib/ids.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export const eventId = (type, naturalKey) => `${type.slice(0, 41)}:${createHash('sha256').update(naturalKey).digest('base64url').slice(0, 22)}`;