@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/plans.mjs ADDED
@@ -0,0 +1,265 @@
1
+ import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
2
+ import { join, posix, win32 } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { git, worktreeOf } from './state.mjs';
5
+ import { mergeBase } from './git.mjs';
6
+ import { clean } from './scrub.mjs';
7
+
8
+ export const MAX_ITEMS = 200;
9
+ const ITEM_TEXT = 500;
10
+ const MAX_FILE = 1024 * 1024;
11
+ const TASK = /^### Task (\d+):\s*(.+)$/;
12
+ const HEADING = /^#{1,3} /;
13
+ const BOX = /^\s*[-*] \[( |x|X)\] (.+)$/;
14
+ const OPEN_BOX = /^\s*[-*] \[ \] ./;
15
+ const FENCE = /^\s*(`{3,}|~{3,})(.*)$/;
16
+ const LEDGER = /^# SDD ledger — plan: (.+)$/;
17
+ const COMPLETE = /^Task (\d+): complete\b/;
18
+ const ROUND = /^Task (\d+): fix round (\d+)\/5 \((.*)\)/;
19
+ const TASK_ID = /^[A-Za-z0-9._:-]{1,64}$/;
20
+ const PLANS_DIR = 'docs/superpowers/plans';
21
+ const PLAN_FILE = /^docs\/superpowers\/plans\/[^/]+\.md$/;
22
+ const CHANGES_DIR = 'openspec/changes';
23
+ const CHANGE = /^openspec\/changes\/(?!archive\/tasks\.md$)(archive\/)?([^/]+)\/tasks\.md$/;
24
+ const OS_BOX = /^\s*(?:[-*+]|\d+[.)])\s+\[([ xX~])\]\s+(.*)$/;
25
+ const OS_KEY = /^(\d+(?:\.\d+)+)\.?\s+(\S.*)$/;
26
+ const DATED = /^\d{4}-\d{2}-\d{2}-(.+)$/;
27
+ export const LINK = /<!--\s*eocrm:\s*([A-Z][A-Z0-9]{1,9}-[0-9]+)\s*-->/;
28
+ const WIN = /^(?:[A-Za-z]:|\\\\)/;
29
+ // Session paths follow the cwd's own shape, not the host's.
30
+ export const pathFor = (dir) => (WIN.test(dir) ? win32 : posix);
31
+
32
+ const lines = (text) => String(text ?? '').replace(/\r\n?/g, '\n').split('\n');
33
+ // Lines outside ``` / ~~~ fences; a fence closes on the same char, at least as long, nothing after.
34
+ function outside(text) {
35
+ const out = [];
36
+ let open = null;
37
+ for (const line of lines(text)) {
38
+ const f = FENCE.exec(line);
39
+ if (open) {
40
+ if (f && f[1][0] === open[0] && f[1].length >= open.length && !f[2].trim()) open = null;
41
+ } else if (f) open = f[1];
42
+ else out.push(line);
43
+ }
44
+ return out;
45
+ }
46
+ const norm = (text) => text.trim().replace(/\s+/g, ' ');
47
+ const hex = (text) => createHash('sha256').update(text).digest('hex').slice(0, 12);
48
+
49
+ function finish(entries) {
50
+ const seen = new Map();
51
+ const items = [];
52
+ const done = new Set();
53
+ for (const e of entries.slice(0, MAX_ITEMS)) {
54
+ const n = (seen.get(e.key) ?? 0) + 1;
55
+ seen.set(e.key, n);
56
+ const key = n > 1 ? `${e.key}-${n}` : e.key;
57
+ items.push({ key, text: clean(e.text, ITEM_TEXT) });
58
+ if (e.done) done.add(key);
59
+ }
60
+ return { items, done, truncated: entries.length > MAX_ITEMS };
61
+ }
62
+
63
+ export function parseSuperpowers(text) {
64
+ const tasks = [];
65
+ let task = null;
66
+ for (const line of outside(text)) {
67
+ const m = TASK.exec(line);
68
+ if (m) tasks.push((task = { key: `task-${m[1]}`, text: `${m[1]}. ${m[2].trim()}`, steps: 0, ticked: 0 }));
69
+ else if (HEADING.test(line)) task = null;
70
+ else if (task) {
71
+ const box = BOX.exec(line);
72
+ if (box) {
73
+ task.steps++;
74
+ if (box[1] !== ' ') task.ticked++;
75
+ }
76
+ }
77
+ }
78
+ return finish(tasks.map((t) => ({ ...t, done: t.steps > 0 && t.ticked === t.steps })));
79
+ }
80
+
81
+ export function parseMarkdown(text) {
82
+ return finish(outside(text).flatMap((line) => {
83
+ const m = BOX.exec(line);
84
+ const body = m && norm(m[2]);
85
+ return body ? [{ key: `md-${hex(body)}`, text: body, done: m[1] !== ' ' }] : [];
86
+ }));
87
+ }
88
+
89
+ export function parseOpenSpec(text) {
90
+ return finish(outside(text).flatMap((line) => {
91
+ const m = OS_BOX.exec(line);
92
+ const body = m && norm(m[2]);
93
+ if (!body) return [];
94
+ const k = OS_KEY.exec(body);
95
+ return [{ key: k ? k[1] : `md-${hex(body)}`, text: k ? k[2] : body, done: m[1] === 'x' || m[1] === 'X' }];
96
+ }));
97
+ }
98
+
99
+ export const changeTasks = (id) => `${CHANGES_DIR}/${id}/tasks.md`;
100
+
101
+ const fromTodos = (todos) => finish(todos.map((t) => ({ key: t.key, text: t.text, done: t.status === 'completed' })));
102
+
103
+ // input is the PostToolUse hook input; prev is run.todos, and the returned todos replace it.
104
+ export function parseTodos(input, prev = []) {
105
+ let todos = Array.isArray(prev) ? prev : [];
106
+ const ti = input?.tool_input ?? {};
107
+ const form = (t) => (typeof t.activeForm === 'string' ? { activeForm: clean(t.activeForm, ITEM_TEXT) } : {});
108
+ if (input?.tool_name === 'TodoWrite' && Array.isArray(ti.todos)) {
109
+ todos = ti.todos.filter((t) => typeof t?.content === 'string' && norm(t.content)).map((t) => ({
110
+ key: `todo-${hex(norm(t.content))}`, text: norm(t.content), status: t.status, ...form(t),
111
+ }));
112
+ } else if (input?.tool_name === 'TaskCreate') {
113
+ const id = String(input.tool_response?.task?.id ?? '');
114
+ const subject = typeof ti.subject === 'string' ? norm(ti.subject) : '';
115
+ if (TASK_ID.test(id) && subject) todos = [...todos.filter((t) => t.key !== `todo-${id}`), { key: `todo-${id}`, text: subject, status: 'pending', ...form(ti) }];
116
+ } else if (input?.tool_name === 'TaskUpdate') {
117
+ const key = `todo-${ti.taskId}`;
118
+ if (ti.status === 'deleted') todos = todos.filter((t) => t.key !== key);
119
+ else {
120
+ todos = todos.map((t) => (t.key !== key ? t : {
121
+ ...t,
122
+ ...(typeof ti.subject === 'string' && norm(ti.subject) ? { text: norm(ti.subject) } : {}),
123
+ ...(typeof ti.status === 'string' ? { status: ti.status } : {}),
124
+ ...form(ti),
125
+ }));
126
+ }
127
+ }
128
+ return { ...fromTodos(todos), todos };
129
+ }
130
+
131
+ export function parseLedger(text) {
132
+ const all = lines(text);
133
+ const complete = new Set();
134
+ const rounds = [];
135
+ for (const line of all) {
136
+ const c = COMPLETE.exec(line);
137
+ if (c) complete.add(Number(c[1]));
138
+ const r = ROUND.exec(line);
139
+ if (r) rounds.push({ task: Number(r[1]), round: Number(r[2]), summary: clean(r[3], 200) });
140
+ }
141
+ return { plan: LEDGER.exec(all[0])?.[1].trim() ?? '', complete, rounds };
142
+ }
143
+
144
+ export function relPath(root, file) {
145
+ const p = pathFor(root);
146
+ const base = p.resolve(root);
147
+ const rel = p.relative(base, p.resolve(base, file));
148
+ if (!rel || rel === '..' || rel.startsWith(`..${p.sep}`) || p.isAbsolute(rel)) return null;
149
+ return rel.split(p.sep).join('/');
150
+ }
151
+
152
+ export function noteTruncation(plan, run) {
153
+ return plan?.truncated && !run?.planTruncatedNoted ? { label: `plan truncated at ${MAX_ITEMS} items`, patch: { planTruncatedNoted: true } } : null;
154
+ }
155
+
156
+ // Symlinks may not lead a read outside the repo, nor outside dir.
157
+ export function read(root, file, dir = root) {
158
+ try {
159
+ const real = realpathSync.native(file);
160
+ if (relPath(realpathSync.native(root), real) === null || relPath(realpathSync.native(dir), real) === null) return null;
161
+ return statSync(file).size > MAX_FILE ? null : readFileSync(file, 'utf8');
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+
167
+ const mtime = (file) => {
168
+ try {
169
+ return statSync(file).mtimeMs;
170
+ } catch {
171
+ return -1;
172
+ }
173
+ };
174
+
175
+ // Superpowers steps count as done only at HEAD (Ruling 8); ledger completes always do.
176
+ export const readChange = (root, rel) => read(root, join(root, rel), join(root, CHANGES_DIR));
177
+ const readPlan = (root, rel) => (CHANGE.test(rel) ? readChange(root, rel) : read(root, join(root, rel)));
178
+
179
+ function load(root, rel, pass, complete = new Set(), text = readPlan(root, rel)) {
180
+ const { exec } = pass;
181
+ if (text === null) return null;
182
+ const change = CHANGE.exec(rel);
183
+ if (change) return openSpec(root, rel, change, text, pass);
184
+ if (!outside(text).some((l) => TASK.test(l))) {
185
+ const plan = parseMarkdown(text);
186
+ return plan.items.length ? { source: 'markdown', path: rel, ...plan } : null;
187
+ }
188
+ const plan = parseSuperpowers(text);
189
+ const keys = new Set(plan.items.map((i) => i.key));
190
+ const atHead = parseSuperpowers(git(root, ['show', `HEAD:${rel}`], exec)).done;
191
+ const done = new Set([...atHead, ...[...complete].map((n) => `task-${n}`)].filter((k) => keys.has(k)));
192
+ return { source: 'superpowers', path: rel, ...plan, done };
193
+ }
194
+
195
+ // OpenSpec keeps a dated id as is when archiving, so a dated folder is the id only if the branch or its base had it.
196
+ function changeOf(root, dir, { exec, base }) {
197
+ const bare = DATED.exec(dir)?.[1];
198
+ if (!bare) return dir;
199
+ const path = changeTasks(dir);
200
+ const had = git(root, ['ls-tree', '--name-only', base(), '--', path], exec) || git(root, ['rev-list', '-1', `${base()}..HEAD`, '--', path], exec);
201
+ return had ? dir : bare;
202
+ }
203
+
204
+ // An archived change is done, reported under its original path so the server keeps one plan.
205
+ function openSpec(root, rel, [, archived, dir], text, pass) {
206
+ const plan = parseOpenSpec(text);
207
+ if (!plan.items.length) return null;
208
+ const change = archived ? changeOf(root, dir, pass) : dir;
209
+ const link = LINK.exec(readChange(root, `${rel.slice(0, -'tasks.md'.length)}proposal.md`) ?? '')?.[1] ?? null;
210
+ const done = archived ? new Set(plan.items.map((i) => i.key)) : plan.done;
211
+ return { source: 'openspec', path: changeTasks(change), change, link, ...plan, done };
212
+ }
213
+
214
+ function fromLedger(root, pass) {
215
+ const dir = join(root, '.superpowers', 'sdd');
216
+ let ledgers;
217
+ try {
218
+ ledgers = readdirSync(dir).map((d) => join(dir, d, 'progress.md')).filter((f) => mtime(f) >= 0).sort((a, b) => mtime(b) - mtime(a));
219
+ } catch {
220
+ return null;
221
+ }
222
+ for (const f of ledgers) {
223
+ const { plan, complete, rounds } = parseLedger(read(root, f));
224
+ const rel = plan && relPath(root, plan);
225
+ const found = rel && load(root, rel, pass, complete);
226
+ if (found) return { ...found, rounds };
227
+ }
228
+ return null;
229
+ }
230
+
231
+ function fromBranch(root, pass) {
232
+ const { exec } = pass;
233
+ const base = pass.base();
234
+ const names = [
235
+ git(root, ['diff', '--name-only', '-z', '--diff-filter=d', base, '--', PLANS_DIR, CHANGES_DIR], exec),
236
+ git(root, ['ls-files', '-z', '--others', '--exclude-standard', '--', PLANS_DIR, CHANGES_DIR], exec),
237
+ ].join('\0').split('\0').filter((n) => PLAN_FILE.test(n) || CHANGE.test(n));
238
+ const files = [...new Set(names)].sort((a, b) => mtime(join(root, b)) - mtime(join(root, a)));
239
+ for (const rel of files) {
240
+ const found = load(root, rel, pass);
241
+ if (found) return found;
242
+ }
243
+ return null;
244
+ }
245
+
246
+ function fromWritten(root, written, pass) {
247
+ const paths = Array.isArray(written) ? written.filter((f) => typeof f === 'string') : [];
248
+ for (const f of [...new Set(paths)].reverse()) {
249
+ const rel = relPath(root, f);
250
+ if (!rel || !/\.md$/i.test(rel)) continue;
251
+ const text = readPlan(root, rel);
252
+ const found = text !== null && outside(text).some((l) => OPEN_BOX.test(l)) && load(root, rel, pass, undefined, text);
253
+ if (found) return found;
254
+ }
255
+ return null;
256
+ }
257
+
258
+ // run.written: Write/Edit file_paths the session made, oldest first; run.todos: parseTodos state.
259
+ export function activePlan(cwd, run = {}, exec) {
260
+ const { root } = worktreeOf(cwd, exec);
261
+ const todos = Array.isArray(run?.todos) && run.todos.length ? { source: 'todo', ...fromTodos(run.todos) } : null;
262
+ let base;
263
+ const pass = { exec, base: () => (base ??= mergeBase(root, exec) ?? 'HEAD') };
264
+ return fromLedger(root, pass) ?? fromBranch(root, pass) ?? fromWritten(root, run?.written, pass) ?? todos;
265
+ }
@@ -0,0 +1,213 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { withLock, git, worktreeOf, loadRun, saveRun, loadWorktree, saveWorktree } from './state.mjs';
3
+ import { append, readOutbox } from './outbox.mjs';
4
+ import { cleanEvent } from './api.mjs';
5
+ import { eventId } from './ids.mjs';
6
+ import { activePlan, noteTruncation } from './plans.mjs';
7
+ import { branchCommits, budget, prState, repoSlug } from './git.mjs';
8
+ import { taskFor } from './detect.mjs';
9
+ import { repoEntry } from './workspace.mjs';
10
+ import { cliData } from './paths.mjs';
11
+
12
+ const LOCK_MS = 1500;
13
+ const KEEP_SEEN = 5000;
14
+ const KEEP_COMMITS = 1000;
15
+ const KEEP_OWN = 200;
16
+ const MIN_LEFT_MS = 1000;
17
+ // ponytail: newest 10 open PRs per pass, each a gh call; page through them if a worktree ever holds more.
18
+ const PR_CHECKS = 10;
19
+ const PR_URL = /^https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/(\d+)$/;
20
+
21
+ const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('base64url').slice(0, 22);
22
+ const scopeOf = (p) => [p?.source ?? null, p?.path ?? null];
23
+
24
+ // Server payload identity; a step's plan_key counts only under the plan event before it.
25
+ export function identity(type, p, scope) {
26
+ if (type === 'plan') return hash(['plan', ...scopeOf(p), (Array.isArray(p.items) ? p.items : []).map((i) => [i?.key ?? null, i?.text ?? null])]);
27
+ if (type === 'step') return hash(p.plan_key ? ['step', scope, p.plan_key, p.phase ?? null] : ['step', p.label ?? null, p.phase ?? null]);
28
+ if (type === 'commit') return hash(['commit', p.sha ?? null]);
29
+ if (type === 'pull_request') return hash(['pr', p.url ?? null, p.action ?? null]);
30
+ return null;
31
+ }
32
+
33
+ function derive(ctx, run, exec) {
34
+ const plan = activePlan(ctx.cwd, run, exec);
35
+ const wtKey = worktreeOf(ctx.cwd, exec).key;
36
+ const wt = loadWorktree(ctx.data, wtKey);
37
+ const occurred_at = new Date(ctx.now()).toISOString();
38
+ const events = [];
39
+ const add = (type, key, fields, scope = null, replay = null) => {
40
+ const event = { id: eventId(type, key), type, occurred_at, ...fields };
41
+ events.push({ event, identity: identity(type, cleanEvent(event), scope), replay, ...(type === 'plan' ? { planKey: key } : {}) });
42
+ };
43
+ const scope = plan && scopeOf(plan);
44
+ const planKey = plan && plan.source + (plan.path ?? '');
45
+ let note = null;
46
+ if (plan && run.conventions?.plan_import === true) {
47
+ add('plan', planKey + JSON.stringify(plan.items), { source: plan.source, ...(plan.path ? { path: plan.path } : {}), items: plan.items }, null, 'plan');
48
+ for (const item of plan.items) {
49
+ if (plan.done.has(item.key)) add('step', `${planKey}${item.key}:done`, { phase: 'finished', label: item.text, plan_key: item.key }, scope, 'plan');
50
+ }
51
+ note = noteTruncation(plan, run);
52
+ if (note) add('step', `${planKey}:truncated`, { phase: 'finished', label: note.label });
53
+ }
54
+ for (const r of plan?.rounds ?? []) {
55
+ add('step', `${planKey}:sdd:${r.task}:${r.round}`, { phase: 'finished', label: `Task ${r.task} review round ${r.round}: ${r.summary}` }, null, 'round');
56
+ }
57
+ const commits = branchCommits(ctx.cwd, 200, exec);
58
+ if (commits.length) {
59
+ const reported = new Set(wt.reportedCommits);
60
+ // This run's commits are re-derived even when reported: the capped outbox can drop them.
61
+ const mine = new Set([...commits.slice(commits.findIndex((c) => c.sha === run.startHead) + 1).map((c) => c.sha), ...(run.ownCommits ?? [])]);
62
+ const repo = repoSlug(ctx.cwd, git(ctx.cwd, ['remote', 'get-url', 'origin'], exec));
63
+ for (const c of commits) if (!reported.has(c.sha) || mine.has(c.sha)) add('commit', c.sha, { sha: c.sha, subject: c.subject, ...(repo ? { repo } : {}) });
64
+ }
65
+ const merged = [];
66
+ for (const p of wt.openPrs.filter((o) => PR_URL.test(o?.url ?? '')).slice(-PR_CHECKS)) {
67
+ const state = prState(ctx.cwd, p.url, exec);
68
+ if (state === undefined) break;
69
+ if (state !== 'MERGED') continue;
70
+ merged.push(p.url);
71
+ add('pull_request', `merged:${p.url}`, { action: 'merged', url: p.url, number: Number(PR_URL.exec(p.url)[1]), repo: p.url.split('/').slice(3, 5).join('/') });
72
+ }
73
+ return { plan, events, note, merged, wtKey };
74
+ }
75
+
76
+ // The CLI writes the mapping; a plugin session reads it from the CLI's data dir too, never writing there.
77
+ function mappedTask(ctx, change, exec) {
78
+ const origin = git(ctx.cwd, ['remote', 'get-url', 'origin'], exec);
79
+ const dirs = [ctx.data, ...(ctx.env ? [cliData(ctx.env)] : [])];
80
+ for (const d of dirs) {
81
+ const key = repoEntry(d, ctx.cwd, origin).openspec?.[change];
82
+ if (key) return key;
83
+ }
84
+ return null;
85
+ }
86
+
87
+ export const desiredEvents = (ctx, run, exec = budget(10000, ctx.git)) => derive(ctx, run, exec).events.map((e) => e.event);
88
+
89
+ export function currentStep(plan, run) {
90
+ const todo = (Array.isArray(run.todos) ? run.todos : []).find((t) => t?.status === 'in_progress');
91
+ if (todo) return todo.activeForm || todo.text || null;
92
+ return plan?.items.find((i) => !plan.done.has(i.key))?.text ?? null;
93
+ }
94
+
95
+ // Resolves null once `end` passes, so a slow store or server never holds the hook.
96
+ export const until = (promise, end) => new Promise((resolve) => {
97
+ const timer = setTimeout(() => resolve(null), Math.max(0, end - Date.now()));
98
+ promise.then((v) => resolve(v), () => resolve(null)).finally(() => clearTimeout(timer));
99
+ });
100
+
101
+ export const CONVENTIONS_MAX_AGE_MS = 5 * 60_000;
102
+
103
+ // A returned value that is not run.conventions was fetched: the caller saves it with conventionsAt.
104
+ export async function loadConventions(ctx, run, client = ctx.clientFor(run), end = Infinity, { refresh = false } = {}) {
105
+ const cached = run.conventions ?? null;
106
+ if (cached && !refresh && Date.now() - (run.conventionsAt ?? 0) < CONVENTIONS_MAX_AGE_MS) return cached;
107
+ if (end - Date.now() < MIN_LEFT_MS) return cached;
108
+ const res = await until(client.conventions(), end);
109
+ return res?.status === 200 && res.body && typeof res.body === 'object' ? res.body : cached;
110
+ }
111
+
112
+ // Plans are matched only against the server's latest one: a tick lands under that plan.
113
+ async function readServer(client, runId, end) {
114
+ const seen = [];
115
+ let scope = null;
116
+ let lastPlan = null;
117
+ let cursor;
118
+ do {
119
+ if (end - Date.now() < MIN_LEFT_MS) return null;
120
+ const res = await until(client.listEvents(runId, cursor), end);
121
+ if (res?.status !== 200 || !Array.isArray(res.body?.items)) return null;
122
+ for (const e of res.body.items) {
123
+ const p = e?.payload && typeof e.payload === 'object' ? e.payload : {};
124
+ const id = identity(e?.type, p, scope);
125
+ if (e?.type === 'plan') {
126
+ scope = scopeOf(p);
127
+ lastPlan = identity('plan', p);
128
+ } else if (id) seen.push(id);
129
+ }
130
+ cursor = res.body.next_cursor;
131
+ } while (cursor);
132
+ return { seen, lastPlan };
133
+ }
134
+
135
+ // Pushes desired − acked − serverSeen − pending; repeated with no change it enqueues nothing.
136
+ export async function reconcile(ctx, run, { deadlineMs = 10000 } = {}) {
137
+ const { data } = ctx;
138
+ const sid = run.sessionId;
139
+ const end = Date.now() + deadlineMs;
140
+ const client = ctx.clientFor(run);
141
+ const conventions = await loadConventions(ctx, run, client, end);
142
+ let read = null;
143
+ if (!run.serverEventsRead && run.runId) read = await readServer(client, run.runId, end);
144
+ if (Date.now() >= end) return { enqueued: 0 };
145
+ const exec = budget(end - Date.now(), ctx.git);
146
+ const startHead = run.startHead ?? (git(ctx.cwd, ['rev-parse', 'HEAD'], exec) || null);
147
+ const { plan, events: derived, note, merged, wtKey } = derive(ctx, { ...run, conventions, startHead }, exec);
148
+ const own = taskFor(ctx, { cwd: ctx.cwd, session_id: sid }, exec);
149
+ const linked = plan?.change ? plan.link ?? mappedTask(ctx, plan.change, exec) : null;
150
+ const task = (run) => own(run) ?? linked;
151
+
152
+ return withLock(data, async () => {
153
+ const cur = loadRun(data, sid);
154
+ if (cur.ended) return { enqueued: 0 };
155
+ const patch = { startHead, ...(plan ? { planPath: plan.path ?? null } : {}) };
156
+ const entries = [];
157
+ if (linked && !own(cur)) {
158
+ patch.start = { ...cur.start, task: linked };
159
+ entries.push({ kind: 'task', sessionId: sid, task: linked });
160
+ }
161
+ if (conventions && conventions !== run.conventions) Object.assign(patch, { conventions, conventionsAt: Date.now() });
162
+ if (read && cur.runId === run.runId) Object.assign(patch, { serverSeen: read.seen.slice(-KEEP_SEEN), serverLastPlan: read.lastPlan, serverEventsRead: true });
163
+ const fresh = patch.serverEventsRead || cur.serverEventsRead;
164
+ const server = new Set(patch.serverSeen ?? (fresh ? cur.serverSeen ?? [] : []));
165
+ const serverLastPlan = 'serverLastPlan' in patch ? patch.serverLastPlan : fresh ? cur.serverLastPlan : null;
166
+ const planned = derived.find((e) => e.planKey);
167
+ if (planned) {
168
+ // A plan that is not the last one sent goes again under a fresh id, so the server's latest plan is this one.
169
+ const switches = cur.planSwitches ?? 0;
170
+ const same = cur.lastPlanKey === planned.planKey;
171
+ const n = same || cur.lastPlanKey === undefined ? switches : switches + 1;
172
+ planned.event.id = n ? eventId('plan', `${planned.planKey}:${n}`) : planned.event.id;
173
+ Object.assign(patch, { lastPlanKey: planned.planKey, lastPlanEventId: planned.event.id, planSwitches: n });
174
+ }
175
+ // A resumed session's run is new on the server; what earlier runs acked is not replayed.
176
+ const gen = cur.generation ?? 0;
177
+ const before = cur.ackedBefore ?? {};
178
+ const ids = derived.filter((e) => e.replay === 'plan').map((e) => e.event.id);
179
+ const last = cur.planLast?.generation !== gen ? cur.planLast : null;
180
+ const unchanged = last && ids.length === last.ids.length && ids.every((id) => before[id] && last.ids.includes(id));
181
+ const events = derived.filter((e) => !(e.replay === 'plan' && unchanged) && !(e.replay === 'round' && before[e.event.id]));
182
+ if (last) for (const e of events) if (e.replay === 'plan' && before[e.event.id]) e.event.restored = true;
183
+ if (ids.length && !unchanged) patch.planLast = { generation: gen, ids };
184
+ const pending = new Set(readOutbox(data).filter((e) => e.sessionId === sid && e.kind === 'event').map((e) => e.event.id));
185
+ const rejected = new Set(cur.rejected.map((r) => r.eventId));
186
+ const onServer = (e) => (e.planKey ? serverLastPlan === e.identity : server.has(e.identity));
187
+ // Under a rejected plan, ticks wait for the next version of it.
188
+ const held = planned && rejected.has(planned.event.id);
189
+ const send = events.filter((e) => !cur.acked[e.event.id] && !pending.has(e.event.id) && !rejected.has(e.event.id) && !onServer(e) && !(held && e.event.plan_key != null));
190
+ if (send.some((e) => e.planKey)) patch.serverLastPlan = null;
191
+ entries.unshift(...send.map((e) => ({ kind: 'event', sessionId: sid, event: { ...e.event, task_key: task(cur) } })));
192
+ const label = currentStep(plan, cur);
193
+ const stepKey = label && `${cur.clientRunId}\n${label}`;
194
+ if (stepKey && stepKey !== cur.currentStepKey) {
195
+ entries.push({ kind: 'step', sessionId: sid, step: label });
196
+ patch.currentStepKey = stepKey;
197
+ }
198
+ if (note) Object.assign(patch, note.patch);
199
+ const sentCommits = send.filter((e) => e.event.type === 'commit').map((e) => e.event.sha);
200
+ if (sentCommits.length) patch.ownCommits = [...new Set([...(cur.ownCommits ?? []), ...sentCommits])].slice(-KEEP_OWN);
201
+ if (sentCommits.length || merged.length) {
202
+ const wt = loadWorktree(data, wtKey);
203
+ const known = new Set(wt.reportedCommits);
204
+ saveWorktree(data, wtKey, {
205
+ reportedCommits: [...wt.reportedCommits, ...sentCommits.filter((s) => !known.has(s))].slice(-KEEP_COMMITS),
206
+ openPrs: wt.openPrs.filter((p) => !merged.includes(p?.url)),
207
+ });
208
+ }
209
+ if (entries.length) append(data, ...entries);
210
+ saveRun(data, sid, patch);
211
+ return { enqueued: entries.length };
212
+ }, { giveUpMs: LOCK_MS });
213
+ }
package/lib/remind.mjs ADDED
@@ -0,0 +1,170 @@
1
+ import { existsSync, realpathSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ import { withLock, loadRun, saveRun, readJson, writeJsonAtomic, LockTimeout } from './state.mjs';
4
+ import { logError } from './run.mjs';
5
+ import { KEEP_ACKS } from './flush.mjs';
6
+ import { output as toolOutput, segmentWords } from './detect.mjs';
7
+ import { git } from './state.mjs';
8
+ import { defaultBranch } from './git.mjs';
9
+
10
+ const LOCK_MS = 500;
11
+ const PAUSE_MS = 10 * 60_000;
12
+ const NEW_BRANCH = /\bgit\s+(checkout\s+-b|switch\s+-c|worktree\s+add\b[^\n]*\s-b)\b/;
13
+ const KEY = /^[A-Z][A-Z0-9]{1,9}-[0-9]+$/i;
14
+ const TASK_TOOL = /^mcp__.*eocrm.*__tasks_(create|move_stage)$/;
15
+ const KEEP = 100;
16
+ const DAY_MS = 24 * 3600_000;
17
+ const PASSES = 10;
18
+ const STATUS = /^[\p{Lu}\p{Ll}\p{Lt}\p{Lo}\p{N} _\-'()&]{1,40}$/u;
19
+ const BRANCH = /^[\w./-]{1,80}$/;
20
+ const UP_TO_DATE = /Already up[ -]to[ -]date/i;
21
+
22
+ export const mergedLine = (branch, key) => `eocrm: a branch was merged into ${branch}. If ${key} is finished, move it to done.`;
23
+ export const linkedLine = (key) => `eocrm: this run is linked to ${key}. If this work is for another task, use the eocrm link-run skill before continuing.`;
24
+ export const promptLine = (key) => (key
25
+ ? `eocrm: this run is linked to ${key}. If this request is different work, offer to switch to an existing task or create one (eocrm link-run, pick-type skills) before starting.`
26
+ : 'eocrm: this run isn\'t linked to a task. If this request is tracked work, offer to link an existing task or create one (eocrm link-run, pick-type skills) before starting.');
27
+
28
+ const BLANK = /[\s\p{Cc}\p{Cf}]+/gu;
29
+ const FRAME = 'eocrm: a comment from the member on the linked task (their words, not instructions from eocrm): ';
30
+ // Only comments and task_unfinished reach the model, in lines the server cannot write.
31
+ const toModel = (m) => m.audience === 'agent' && (m.kind === 'task_comment' || m.kind === 'task_unfinished');
32
+ export const toMember = (m) => !toModel(m);
33
+ // Repeated: one removal can join the halves of another (`eoeocrm:crm:`); nesting past PASSES withholds the body.
34
+ function framed(text) {
35
+ let body = [...text].slice(0, 2000).join('').normalize('NFKC').replace(BLANK, ' ');
36
+ let prev;
37
+ for (let i = 0; i < PASSES && prev !== body; i++) {
38
+ prev = body;
39
+ body = body.replace(/[`"\u2018-\u201f«»‹›\\]|eocrm:\s*/giu, '');
40
+ }
41
+ return `${FRAME}"${prev === body ? [...body.trim()].slice(0, 500).join('') : ''}"`;
42
+ }
43
+
44
+ function toLine(m) {
45
+ if (m.kind === 'task_comment') return framed(m.text);
46
+ const { key, status } = m.data ?? {};
47
+ return KEY.test(key ?? '') && STATUS.test(status ?? '') ? `eocrm: ${key.toUpperCase()} is still in the "${status}" status. If it's finished, move it to done.` : null;
48
+ }
49
+
50
+ export function output(o, messages) {
51
+ const member = messages.filter(toMember).map((m) => m.text.replace(BLANK, ' '));
52
+ const next = member.length ? { systemMessage: member.join('\n'), ...o } : o;
53
+ return Object.keys(next).length ? { stdout: JSON.stringify(next) } : {};
54
+ }
55
+
56
+ function out(hookEventName, line, messages) {
57
+ const agent = [...messages.filter(toModel).map(toLine).filter(Boolean), ...(line ? [line] : [])];
58
+ return output(agent.length ? { hookSpecificOutput: { hookEventName, additionalContext: agent.join('\n') } } : {}, messages);
59
+ }
60
+
61
+ // Takes the shown messages out of the inbox and queues their acks; a lock timeout takes none.
62
+ export async function drain(ctx, sid, pick = () => true, giveUpMs = LOCK_MS) {
63
+ if (!(loadRun(ctx.data, sid).inbox ?? []).some(pick)) return [];
64
+ try {
65
+ return await withLock(ctx.data, async () => {
66
+ const inbox = loadRun(ctx.data, sid).inbox ?? [];
67
+ const taken = inbox.filter(pick);
68
+ const file = join(ctx.data, 'notices.json');
69
+ const notices = readJson(file, {});
70
+ const now = ctx.now();
71
+ const update = now - (notices.lastUpdateNoticeAt ?? -Infinity) >= DAY_MS ? taken.find((m) => m.kind === 'plugin_update') : null;
72
+ const shown = taken.filter((m) => m.kind !== 'plugin_update' || m === update);
73
+ if (update) writeJsonAtomic(file, { ...notices, lastUpdateNoticeAt: now });
74
+ const ackPending = [...new Set([...(loadRun(ctx.data, sid).ackPending ?? []), ...taken.map((m) => m.id).filter((id) => !id.startsWith('local:'))])].slice(-KEEP_ACKS);
75
+ saveRun(ctx.data, sid, { inbox: inbox.filter((m) => !taken.includes(m)), ackPending });
76
+ return shown;
77
+ }, { giveUpMs });
78
+ } catch (e) {
79
+ if (!(e instanceof LockTimeout)) logError(ctx.data, e);
80
+ return [];
81
+ }
82
+ }
83
+ const tracked = (run) => Boolean(run.startedAt && run.workspace);
84
+
85
+ function promptDue(run, now) {
86
+ const check = run.conventions?.task_switch_check;
87
+ if (check === 'every_prompt') return true;
88
+ if (check === 'signals_only') return false;
89
+ const since = Math.max(run.lastStopAt ?? now, run.promptRemindedAt ?? 0);
90
+ return now - since >= PAUSE_MS;
91
+ }
92
+
93
+ // Reads only tool_name, tool_input.{command,id,key} and local state.
94
+ function toolSignal(input, linked) {
95
+ const { tool_name: name, tool_input: ti = {} } = input;
96
+ if (name === 'Bash') return typeof ti.command === 'string' && NEW_BRANCH.test(ti.command) ? `branch:${linked}` : null;
97
+ const m = TASK_TOOL.exec(name ?? '');
98
+ if (!m) return null;
99
+ const target = ti.id ?? ti.key;
100
+ if (m[1] === 'create') return `task:new:${linked}`;
101
+ if (typeof target !== 'string' || !KEY.test(target) || target.toUpperCase() === linked.toUpperCase()) return null;
102
+ return `task:other:${linked}`;
103
+ }
104
+
105
+ const NOT_MERGED = new Set(['--abort', '--quit', '--squash', '--no-commit']);
106
+ const isMerge = (w) => w[0] === 'git' && w[1] === 'merge' && !w.some((a) => NOT_MERGED.has(a));
107
+
108
+ function commonDir(cwd) {
109
+ const dir = git(cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
110
+ if (!dir) return null;
111
+ try {
112
+ return realpathSync.native(resolve(cwd, dir));
113
+ } catch {
114
+ return resolve(cwd, dir);
115
+ }
116
+ }
117
+
118
+ // Known exit 0 only: Codex string responses carry none.
119
+ function mergeSignal(input, run) {
120
+ if (input.tool_name !== 'Bash' || typeof input.tool_input?.command !== 'string') return null;
121
+ if (!segmentWords(input.tool_input.command).some(isMerge)) return null;
122
+ if (run.cwd && commonDir(input.cwd) !== commonDir(run.cwd)) return null;
123
+ const out = toolOutput(input);
124
+ if (out?.exit !== 0 || UP_TO_DATE.test(out.text)) return null;
125
+ const branch = defaultBranch(input.cwd);
126
+ if (!BRANCH.test(branch ?? '') || git(input.cwd, ['symbolic-ref', '--short', '-q', 'HEAD']) !== branch) return null;
127
+ const at = /^HEAD@\{(\d+)\} merge /.exec(git(input.cwd, ['reflog', '-1', '--date=unix', '--format=%gd %gs', 'HEAD']));
128
+ if (!at || Number(at[1]) * 1000 < (run.activeSince ?? run.startedAt ?? 0) - 999 || existsSync(resolve(input.cwd, git(input.cwd, ['rev-parse', '--git-path', 'MERGE_HEAD'])))) return null;
129
+ const head = git(input.cwd, ['rev-parse', 'HEAD']);
130
+ return head ? { signal: `merge:${head}`, branch } : null;
131
+ }
132
+
133
+ export async function remind(ctx, event, input) {
134
+ const run = loadRun(ctx.data, input.session_id);
135
+ if (!tracked(run)) return {};
136
+ const line = await reminder(ctx, event, input, run);
137
+ return out(event, line, await drain(ctx, input.session_id));
138
+ }
139
+
140
+ async function reminder(ctx, event, input, run) {
141
+ const sid = input.session_id;
142
+ const linked = run.start?.task ?? null;
143
+ if (event === 'UserPromptSubmit') {
144
+ const now = ctx.now();
145
+ if (!promptDue(run, now)) return null;
146
+ if (run.conventions?.task_switch_check !== 'every_prompt') {
147
+ await withLock(ctx.data, async () => saveRun(ctx.data, sid, { promptRemindedAt: now }), { giveUpMs: LOCK_MS }).catch((e) => {
148
+ if (!(e instanceof LockTimeout)) logError(ctx.data, e);
149
+ });
150
+ }
151
+ return promptLine(linked);
152
+ }
153
+ if (event !== 'PostToolUse' || !linked) return null;
154
+ const merged = mergeSignal(input, run);
155
+ const signal = merged?.signal ?? toolSignal(input, linked);
156
+ if (!signal) return null;
157
+ try {
158
+ const fresh = await withLock(ctx.data, async () => {
159
+ const reminded = loadRun(ctx.data, sid).reminded ?? [];
160
+ if (reminded.includes(signal)) return false;
161
+ saveRun(ctx.data, sid, { reminded: [...reminded, signal].slice(-KEEP) });
162
+ return true;
163
+ }, { giveUpMs: LOCK_MS });
164
+ if (!fresh) return null;
165
+ return merged ? mergedLine(merged.branch, linked) : linkedLine(linked);
166
+ } catch (e) {
167
+ if (e instanceof LockTimeout) return null;
168
+ throw e;
169
+ }
170
+ }