Evolver for Claude Code as function hooks: recalls one EvoMap strategy per prompt, reports each reuse with the evidence the turn produced, and distills…

<img src="assets/logo.png" alt="Evolver" width="96" height="96" />
<h1 align="center">Evolver for Claude Code (Mods)</h1>
Gives Claude Code a persistent evolution memory and a live link to the EvoMap network. It is built on Claude Code's function hooks. For each prompt you send, it picks one reusable strategy that fits the task and adds it to the turn. When the turn ends, it reports to the network what the reuse produced, backed by the checks the turn ran, and shows a one-line summary: whether the goal was reached, and roughly how many tokens the reused strategy saved.
Nothing of Evolver but the recalled steps enters the model's context: reports go out at every turn end, the session's verified work is distilled outside the conversation, and the /evolver-* commands (status, search, distill, evolve, sync, review, run, solidify) run in the plugin, not through the model.
In Claude Code:
/plugin marketplace add EvoMap/evolver-claude-code-mods
/plugin install evolver-mods@evolver-mods
Restart Claude Code afterwards. To update, refresh the marketplace first, then the plugin, and restart:
claude plugin marketplace update evolver-mods && claude plugin update evolver-mods@evolver-mods
Run one Evolver plugin, not two: if the older evolver@evolver plugin is installed, disable it so that each reuse is reported only once:
claude plugin disable evolver@evolver
Local memory works without an account. To reuse strategies from the network:
npm install -g @evomap/evolver
evolver once inside a git repository. It starts the local Proxy and prints a claim link./evolver-status in Claude Code to confirm the Proxy and node.Network recall needs @evomap/evolver 2.0.39 or newer.
Claude Code 2.1.286+, Node.js 22.13+.
Commands, settings and troubleshooting are in docs/architecture.md.
npm ci
npm test
claude --plugin-dir ./
MIT © EvoMap.
hooks/register.ts 575 lines1import type { EngineInterface, PluginOptions, Register } from 'claude-code'
2
3import { evolverCommands, runEvolverCli } from '../lib/commands.js'
4import { candidateOf, distillCandidate, skipReason } from '../lib/distill.js'
5import { EDIT_TOOL_NAMES, changedLinesOf, editedPath } from '../lib/edited-content.js'
6import { feedbackLabelOf } from '../lib/feedback-label.js'
7import { noticeDecision, pendingClaimUrl, upgradeNoticeText, versionOf, versionProbeArgv } from '../lib/onboarding.js'
8import { isPersonPrompt, promptTextOf, recallStrategy } from '../lib/recall.js'
9import { DEFAULT_PROXY_PORT, proxyResultOf, proxySettingsFrom, timedOutResult, unreachableResult } from '../lib/proxy-response.js'
10import { OUTBOX_TTL_MS, withQueued } from '../lib/report-outbox.js'
11import { ABSENT, retentionOf } from '../lib/retention.js'
12import { correctionReportOf, deliverPending, immediateReportOf, reportedReuseOf, retentionReportOf } from '../lib/reuse.js'
13import { recallStatusOf, statusLineOf } from '../lib/status-line.js'
14import { turnSummaryOf } from '../lib/turn-summary.js'
15import { outcomeOfReason } from '../lib/turn-outcomes.js'
16import { checkCommandOf, checkLabelOf, verificationFailed } from '../lib/verification.js'
17
18type ProxyResult = { ok: true; data: any } | { ok: false; error: string }
19type Check = { command: string; label: string; failed: boolean }
20type TurnRecord = {
21 reusedNames: string[]
22 changedLines: number
23 checks: Check[]
24 commands: string[]
25 paths: string[]
26 edits: string[]
27 editedBefore: Map<string, string>
28}
29type Report = ReturnType<typeof immediateReportOf>
30type QueuedReport = { report: Report; sessionId: string }
31type ReportedReuse = ReturnType<typeof reportedReuseOf>
32type PendingRetention = { sessionId: string; projectDir: string; reuses: ReportedReuse[]; files: { path: string; before: string; after: string }[]; atMs: number }
33type RecallMatch = { ids: string[]; name?: string; text: string }
34type OpenAsset = { assetId: string; strategyText: string; turn: number; sessionId?: string }
35type Candidate = ReturnType<typeof candidateOf>
36type DueCandidate = { sessionId: string; candidate: Candidate }
37type DistillOutcome = { status: string; error?: string; data?: unknown; usage?: unknown }
38
39const NOTICES_KEY = 'notices'
40const SIDECAR_TIMEOUT_MS = 90_000
41const PROXY_TIMEOUT_MS = 8_000
42const DISTILL_TIMEOUT_MS = 120_000
43const CLI_TIMEOUT_MS = 10 * 60 * 1000
44const UPGRADE_NOTICE_TTL_MS = 24 * 60 * 60 * 1000
45const CLAIM_NOTICE_TTL_MS = 12 * 60 * 60 * 1000
46const TURN_COUNTER_TTL_MS = 30 * 24 * 60 * 60 * 1000
47const OUTBOX_KEY = 'reports:outbox'
48const RETENTION_KEY = 'retention:pending'
49const PATH_KEYS = ['file_path', 'notebook_path', 'path']
50const WINDOWS_COMMAND_NOT_FOUND = 9009
51
52const freshTurnRecord = (): TurnRecord => ({
53 reusedNames: [],
54 changedLines: 0,
55 checks: [],
56 commands: [],
57 paths: [],
58 edits: [],
59 editedBefore: new Map(),
60})
61
62let turnRecord: TurnRecord = freshTurnRecord()
63const personPrompts = new Set<string>()
64const turnNumbers = new Map<string, number>()
65const abortedTurns = new Set<string>()
66const distillations = new Map<string, { outcome: Promise<DistillOutcome>; controller: AbortController }>()
67const lastPrompts = new Map<string, string>()
68let outboxWork: Promise<unknown> = Promise.resolve()
69let outboxWrites: Promise<unknown> = Promise.resolve()
70let stateWork: Promise<unknown> = Promise.resolve()
71
72const turnCounterKey = (sessionId: string) => `turns:${sessionId}`
73const labelableKey = (sessionId: string) => `labelable:${sessionId}`
74
75function showRecallStatus($: EngineInterface, text: string | null): void {
76 $.ui.status(statusLineOf([text]))
77}
78
79const ERRORS_KEY = 'errors'
80const RECALLS_KEY = 'recalls'
81const MAX_ERRORS = 10
82const MAX_RECALLS = 10
83
84// Background work and recall fail quietly so a turn never pays for them; the
85// last failures are kept in the store so a silent seam can still be diagnosed.
86async function recordFailure($: EngineInterface, where: string, error: unknown): Promise<void> {
87 const at = new Date(await $.clock.now()).toISOString()
88 const message = String((error as Error)?.stack ?? error).slice(0, 500)
89 const kept = await $.store.get(ERRORS_KEY)
90 await $.store.set(ERRORS_KEY, [...(Array.isArray(kept) ? kept : []), { at, where, message }].slice(-MAX_ERRORS))
91}
92
93// The status line is not drawn on every surface, so each recall decision is
94// also kept, newest last, where it can be read back after the turn.
95async function recordRecall($: EngineInterface, prompt: string, startedAt: number, trace: unknown): Promise<void> {
96 const now = await $.clock.now()
97 const entry = { at: new Date(now).toISOString(), prompt: prompt.slice(0, 60), elapsedMs: now - startedAt, trace }
98 const kept = await $.store.get(RECALLS_KEY)
99 await $.store.set(RECALLS_KEY, [...(Array.isArray(kept) ? kept : []), entry].slice(-MAX_RECALLS))
100}
101
102function quietly($: EngineInterface, where: string, work: Promise<unknown>): Promise<unknown> {
103 return work.catch(error => recordFailure($, where, error).catch(() => undefined))
104}
105
106function track($: EngineInterface, where: string, work: Promise<unknown>): void {
107 void quietly($, where, work)
108}
109
110async function homeDir($: EngineInterface): Promise<string> {
111 return (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''
112}
113
114async function proxyFetch($: EngineInterface, options: PluginOptions, method: string, path: string, body?: unknown): Promise<ProxyResult> {
115 const home = await homeDir($)
116 const settingsText = home ? await $.fs.read(`${home}/.evolver/settings.json`).catch(() => '') : ''
117 const port = String(options.proxy_port || (await $.env.get('EVOMAP_PROXY_PORT')) || DEFAULT_PROXY_PORT)
118 const { url: base, token } = proxySettingsFrom(typeof settingsText === 'string' ? settingsText : '', port)
119 const headers: Record<string, string> = {}
120 if (body !== undefined) headers['Content-Type'] = 'application/json'
121 if (token) headers.Authorization = `Bearer ${token}`
122 const request = $.http
123 .fetch(base + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) })
124 .then(response => proxyResultOf(response, base, token), error => unreachableResult(base, error))
125 const deadline = $.clock.sleep(PROXY_TIMEOUT_MS).then(() => timedOutResult(base, PROXY_TIMEOUT_MS), () => timedOutResult(base, PROXY_TIMEOUT_MS))
126 return Promise.race([request, deadline])
127}
128
129function proxyFetcher($: EngineInterface, options: PluginOptions) {
130 return (method: string, path: string, body?: unknown) => proxyFetch($, options, method, path, body)
131}
132
133async function projectDirOf($: EngineInterface): Promise<string> {
134 const cwd = await $.session.cwd()
135 const stat = await $.fs.stat(cwd, { resolve: true }).catch(() => undefined)
136 return stat?.realPath ?? cwd
137}
138
139// `$.session.turns()` counts only the person's prompts, so a turn a task
140// notification starts would reuse the previous number and its reuse report
141// would share that turn's task id, which the Hub drops as a duplicate. Every
142// turn draws its own number from a per-session counter instead, kept past the
143// session's end because `claude --resume` continues under the same id.
144function turnCountOf(stored: unknown): number {
145 const count = typeof stored === 'object' && stored !== null ? (stored as { turn?: unknown }).turn : stored
146 return Number(count ?? 0) || 0
147}
148
149// A counter is only needed while its session may still be resumed; the store is capped at 4 MiB in all.
150async function pruneTurnCounters($: EngineInterface): Promise<void> {
151 const now = await $.clock.now()
152 for (const key of await $.store.keys()) {
153 if (!key.startsWith('turns:')) continue
154 const atMs = Number(((await $.store.get(key)) as { atMs?: unknown } | undefined)?.atMs)
155 if (Number.isFinite(atMs) && now - atMs > TURN_COUNTER_TTL_MS) await $.store.delete(key)
156 }
157}
158
159async function turnNumberFor($: EngineInterface, sessionId: string, turnId: string): Promise<number> {
160 const known = turnNumbers.get(turnId)
161 if (known !== undefined) return known
162 const next = turnCountOf(await $.store.get(turnCounterKey(sessionId))) + 1
163 await $.store.set(turnCounterKey(sessionId), { turn: next, atMs: await $.clock.now() })
164 turnNumbers.set(turnId, next)
165 return next
166}
167
168async function runSidecar($: EngineInterface, options: PluginOptions, command: string, request: unknown = {}): Promise<any> {
169 const ran = await $.process.run(
170 [String(options.node_path || 'node'), `${$.plugin.root}/bin/evolver-io.mjs`, command],
171 { stdin: JSON.stringify(request), timeoutMs: SIDECAR_TIMEOUT_MS },
172 )
173 const answer = JSON.parse(ran.stdout || '{}')
174 if (ran.exitCode !== 0 || answer.error) throw new Error(answer.error ?? `evolver-io ${command} exited ${ran.exitCode}`)
175 return answer
176}
177
178// The ledger and candidate files are written by separate sidecar processes, so their order is this module's:
179// a correction's drop never lands before the candidate it drops, nor a turn's report before its injection.
180function inOrder<T>(work: () => Promise<T>): Promise<T> {
181 const next = stateWork.catch(() => undefined).then(work)
182 stateWork = next
183 return next
184}
185
186function stateCall($: EngineInterface, options: PluginOptions, command: string, request: unknown = {}): Promise<any> {
187 return inOrder(() => runSidecar($, options, command, request))
188}
189
190function reuseLedgers($: EngineInterface, options: PluginOptions) {
191 return {
192 proxyFetch: proxyFetcher($, options),
193 recordLocally: async (request: unknown) => (await runSidecar($, options, 'record-reuse', request)).recorded === true,
194 onRejected: (rejection: unknown) => recordFailure($, 'reuse-report-rejected', JSON.stringify(rejection)),
195 }
196}
197
198async function noticeIsDue($: EngineInterface, key: string, ttlMs: number): Promise<boolean> {
199 const { isDue, state } = noticeDecision(await $.store.get(NOTICES_KEY), key, ttlMs, await $.clock.now())
200 if (isDue) await $.store.set(NOTICES_KEY, state)
201 return isDue
202}
203
204async function sha256Hex(text: string): Promise<string> {
205 const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
206 return [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join('')
207}
208
209async function isWindows($: EngineInterface): Promise<boolean> {
210 return (await $.env.get('OS')) === 'Windows_NT'
211}
212
213async function showOnboardingNotices($: EngineInterface, options: PluginOptions): Promise<void> {
214 const probe = await $.process.run(versionProbeArgv(await isWindows($)), { timeoutMs: 5_000 }).catch(() => null)
215 const version = probe && probe.exitCode === 0 ? versionOf(probe.stdout) : null
216 const upgrade = upgradeNoticeText(version)
217 if (upgrade && (await noticeIsDue($, `evolver-version:${version}`, UPGRADE_NOTICE_TTL_MS))) $.ui.toast(upgrade)
218
219 if (options.claim_nudge_enabled !== true) return
220 const home = await homeDir($)
221 const claimText = home ? await $.fs.read(`${home}/.evomap/claim_url`).catch(() => '') : ''
222 const claimUrl = pendingClaimUrl(claimText)
223 if (claimUrl && (await noticeIsDue($, `claim:${await sha256Hex(claimUrl)}`, CLAIM_NOTICE_TTL_MS))) {
224 $.ui.toast(`Evolver node not connected to EvoMap yet — open ${claimUrl} while signed in to evomap.ai.`)
225 }
226}
227
228async function injectStrategy($: EngineInterface, options: PluginOptions, sessionId: string, turn: number, match: RecallMatch): Promise<void> {
229 if (!match.text) return
230 turnRecord.reusedNames.push(match.name ?? match.ids.join(', '))
231 await stateCall($, options, 'remember-injected', { sessionId, assetIds: match.ids, turn, strategyText: match.text })
232 await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: match.text }] } })
233}
234
235// `turn.start` observes and holds no model call, so whatever this appends
236// reaches the model from the turn's next step; the wait only decides whether
237// the append happens here or once a slower recall lands in the background.
238// Assets this session already saw are read off the ledger, so a hot reload does
239// not re-inject them.
240async function recallForTurn($: EngineInterface, options: PluginOptions, sessionId: string, turn: number, turnId: string, prompt: string, signal: AbortSignal): Promise<void> {
241 if (options.recall_enabled === false) return
242 const listedIds = new Set<string>((await stateCall($, options, 'listed-assets', { sessionId })).ids)
243 const startedAt = await $.clock.now()
244 const recall: Promise<RecallMatch> = recallStrategy(proxyFetcher($, options), promptTextOf(prompt), {
245 listedIds,
246 minSimilarity: Number(options.recall_min_similarity ?? 0.3),
247 onTrace: (trace: unknown) => {
248 showRecallStatus($, recallStatusOf(trace))
249 track($, 'recall-trace', recordRecall($, prompt, startedAt, trace))
250 },
251 })
252 const waitMs = Number(options.recall_wait_ms ?? 6_000)
253 const inline = await Promise.race([recall, $.clock.sleep(waitMs).then(() => null)])
254 if (signal.aborted) return
255 if (inline) return injectStrategy($, options, sessionId, turn, inline)
256 showRecallStatus($, recallStatusOf({ outcome: 'waiting', waitedMs: waitMs }))
257 track($, 'late-recall', recall.then(late => {
258 if (!abortedTurns.has(turnId)) return injectStrategy($, options, sessionId, turn, late)
259 if (late.text) showRecallStatus($, recallStatusOf({ outcome: 'dropped' }))
260 }))
261}
262
263function writeOutbox($: EngineInterface, change: (outbox: any, now: number) => unknown): Promise<unknown> {
264 outboxWrites = outboxWrites.catch(() => undefined).then(async () => $.store.set(OUTBOX_KEY, change(await $.store.get(OUTBOX_KEY), await $.clock.now())))
265 return outboxWrites
266}
267
268function enqueueReports($: EngineInterface, queued: QueuedReport[]): Promise<unknown> {
269 return writeOutbox($, (outbox, now) => withQueued(outbox, queued, now))
270}
271
272// Delivery waits on the network, so a report queued meanwhile is merged with what was delivered, not overwritten.
273function queueReports($: EngineInterface, options: PluginOptions, queued: QueuedReport[]): Promise<unknown> {
274 const queuedNow = enqueueReports($, queued)
275 outboxWork = outboxWork.catch(() => undefined).then(() => queuedNow).then(async () => {
276 const delivered = await deliverPending(reuseLedgers($, options), (await $.store.get(OUTBOX_KEY)) ?? {}, await $.clock.now())
277 await writeOutbox($, latest => ({ ...(latest ?? {}), ...delivered }))
278 })
279 return outboxWork
280}
281
282function reportsOf(assets: OpenAsset[], { sessionId, turn, turnReason, checks }: { sessionId: string; turn?: number; turnReason: string; checks: Check[] }): Report[] {
283 return assets.map(asset => immediateReportOf({ asset, sessionId, turn: turn ?? asset.turn, turnReason, checks }))
284}
285
286async function closeTurnReuse($: EngineInterface, options: PluginOptions, sessionId: string, turn: number, end: { reason: string; answer: string }, finished: TurnRecord): Promise<Report[]> {
287 const { assets: due } = await stateCall($, options, 'take-unreported', { sessionId, turn })
288 const reports = reportsOf(due, { sessionId, turn, turnReason: end.reason, checks: finished.checks })
289 await $.store.set(labelableKey(sessionId), reports.map(reportedReuseOf))
290 return reports
291}
292
293// A strategy whose turn never ended is reported as aborted, with no evidence of its own.
294function abortedReports(assets: OpenAsset[], sessionOf: (asset: OpenAsset) => string): QueuedReport[] {
295 return assets.map(asset => {
296 const sessionId = sessionOf(asset)
297 return { report: reportsOf([asset], { sessionId, turnReason: 'aborted', checks: [] })[0]!, sessionId }
298 })
299}
300
301// A session killed mid-turn (a closed terminal, a harness timeout) leaves its injections open; once the process
302// that held them is gone, the next session start reports them. A session that is merely idle keeps its own.
303async function reportOrphanedInjections($: EngineInterface, options: PluginOptions): Promise<void> {
304 const { assets } = await stateCall($, options, 'take-orphaned-unreported')
305 await queueReports($, options, abortedReports(assets, asset => asset.sessionId ?? 'unknown'))
306}
307
308async function contentHashOf($: EngineInterface, path: string): Promise<string> {
309 const text = await $.fs.read(path).catch(() => null)
310 return typeof text === 'string' ? sha256Hex(text) : ABSENT
311}
312
313async function pendingRetentions($: EngineInterface): Promise<PendingRetention[]> {
314 const stored = await $.store.get(RETENTION_KEY)
315 return Array.isArray(stored) ? (stored as PendingRetention[]) : []
316}
317
318async function rememberForRetention($: EngineInterface, sessionId: string, reuses: ReportedReuse[], editedBefore: Map<string, string>): Promise<void> {
319 if (reuses.length === 0 || editedBefore.size === 0) return
320 const files = await Promise.all([...editedBefore].map(async ([path, before]) => ({ path, before, after: await contentHashOf($, path) })))
321 const entry: PendingRetention = { sessionId, projectDir: await projectDirOf($), reuses, files, atMs: await $.clock.now() }
322 await $.store.set(RETENTION_KEY, [...(await pendingRetentions($)), entry])
323}
324
325async function retentionReportsOf($: EngineInterface, entry: PendingRetention): Promise<QueuedReport[]> {
326 const files = await Promise.all(entry.files.map(async file => ({ ...file, now: await contentHashOf($, file.path) })))
327 const verdict = retentionOf(files).class
328 return entry.reuses
329 .map(reuse => retentionReportOf(reuse, verdict))
330 .filter(report => report !== null)
331 .map(report => ({ report, sessionId: entry.sessionId }))
332}
333
334async function takeDueRetentions($: EngineInterface, sessionId: string): Promise<PendingRetention[]> {
335 const pending = await pendingRetentions($)
336 if (pending.length === 0) return []
337 const projectDir = await projectDirOf($)
338 const now = await $.clock.now()
339 const isDue = (entry: PendingRetention) => entry.projectDir === projectDir && entry.sessionId !== sessionId
340 await $.store.set(RETENTION_KEY, pending.filter(entry => !isDue(entry) && now - entry.atMs <= OUTBOX_TTL_MS))
341 return pending.filter(isDue)
342}
343
344async function settleRetention($: EngineInterface, options: PluginOptions, sessionId: string): Promise<void> {
345 const due = await takeDueRetentions($, sessionId)
346 const queued = (await Promise.all(due.map(entry => retentionReportsOf($, entry)))).flat()
347 await queueReports($, options, queued)
348}
349
350// The session's own model runs the distillation, outside its conversation. A candidate stays on disk until
351// distilled (or given up), and one whose session is over — ended, or killed with its process — is claimed and
352// retried by the next session that starts. One distillation per session runs at a time: a second request while
353// the first runs shares its outcome.
354async function settle($: EngineInterface, options: PluginOptions, due: DueCandidate, sent: boolean): Promise<void> {
355 await stateCall($, options, 'settle-candidate', { ...due, sent }).catch(error => recordFailure($, 'settle-candidate', error))
356}
357
358async function distillOnce($: EngineInterface, options: PluginOptions, { sessionId, candidate }: DueCandidate, focus = ''): Promise<DistillOutcome> {
359 const running = distillations.get(sessionId)
360 if (running) return running.outcome
361 const controller = new AbortController()
362 const outcome = (async () => {
363 const isCurrent = async () => (await stateCall($, options, 'is-current-candidate', { sessionId, candidate })).current === true
364 const complete = (request: any, init?: { signal: AbortSignal }) => $.model.complete(request, init)
365 const distilled = await distillCandidate({ proxyFetch: proxyFetcher($, options), complete, candidate, focus, timeoutMs: DISTILL_TIMEOUT_MS, cancel: controller.signal, isCurrent })
366 await settle($, options, { sessionId, candidate }, distilled.status === 'sent')
367 return distilled
368 })().finally(() => distillations.delete(sessionId))
369 distillations.set(sessionId, { outcome, controller })
370 return outcome
371}
372
373async function distillSession($: EngineInterface, options: PluginOptions, sessionId: string, focus: string): Promise<DistillOutcome> {
374 const { due } = await stateCall($, options, 'due-candidates', { sessionId })
375 return due.length > 0 ? distillOnce($, options, due[0], focus) : { status: 'nothing' }
376}
377
378async function distillLeftovers($: EngineInterface, options: PluginOptions): Promise<void> {
379 const { claimed } = await stateCall($, options, 'claim-leftover-candidates')
380 await Promise.all(claimed.map((due: DueCandidate) => quietly($, 'distill', distillOnce($, options, due))))
381}
382
383/** The session's turn no longer deserves a Gene: its candidate goes, and a distillation already running stops. */
384async function forgetCandidate($: EngineInterface, options: PluginOptions, sessionId: string): Promise<void> {
385 await stateCall($, options, 'drop-candidate', { sessionId })
386 distillations.get(sessionId)?.controller.abort()
387}
388
389// Queued at once, so a correction that follows the turn finds the candidate already written.
390function rememberTurnCandidate($: EngineInterface, options: PluginOptions, sessionId: string, turn: number, end: { reason: string; answer: string }, finished: TurnRecord, reports: Report[]): Promise<void> {
391 const record = { ...finished, answer: end.answer }
392 if (skipReason(end.reason, record)) return Promise.resolve()
393 const prompt = lastPrompts.get(sessionId)
394 return inOrder(async () => {
395 const candidate = candidateOf({ prompt, record, model: await $.session.model(), turn, now: await $.clock.now() })
396 await runSidecar($, options, 'remember-candidate', { sessionId, candidate })
397 })
398}
399
400// The next prompt is the only verdict on a turn available without asking anyone: when it reads as a correction,
401// the reuse reports are revised and the turn is no longer worth distilling.
402async function reportFollowUpLabel($: EngineInterface, options: PluginOptions, sessionId: string, prompt: string): Promise<void> {
403 const label = feedbackLabelOf(promptTextOf(prompt))
404 if (label === 'correction') await forgetCandidate($, options, sessionId)
405 const reuses = ((await $.store.get(labelableKey(sessionId))) ?? []) as ReportedReuse[]
406 if (reuses.length === 0) return
407 await $.store.delete(labelableKey(sessionId))
408 const reports = reuses.map(reuse => correctionReportOf(reuse, label)).filter(report => report !== null)
409 await queueReports($, options, reports.map(report => ({ report, sessionId })))
410}
411
412function noteToolUse(input: Record<string, unknown>): void {
413 if (typeof input.command === 'string') turnRecord.commands.push(input.command)
414 for (const key of PATH_KEYS) if (typeof input[key] === 'string') turnRecord.paths.push(input[key] as string)
415}
416
417function noteEditedFile(input: Record<string, unknown>): void {
418 const edited = editedPath(input)
419 if (edited) turnRecord.edits.push(edited)
420}
421
422async function noteFileBeforeEdit($: EngineInterface, input: Record<string, unknown>): Promise<void> {
423 const path = editedPath(input)
424 if (!path || turnRecord.editedBefore.has(path)) return
425 const before = await contentHashOf($, path)
426 if (!turnRecord.editedBefore.has(path)) turnRecord.editedBefore.set(path, before)
427}
428
429// `$.process.run` takes no shell, so on Windows the `evolver` and `npx` shims run through cmd.exe, which
430// reports a missing command by its exit code instead of failing to start.
431function cliRunner($: EngineInterface) {
432 return async (argv: string[]) => {
433 const onWindows = await isWindows($)
434 const ran = await $.process.run(onWindows ? ['cmd.exe', '/d', '/s', '/c', ...argv] : argv, { timeoutMs: CLI_TIMEOUT_MS })
435 .catch((error: Error) => ({ exitCode: -1, stdout: '', stderr: String(error?.message ?? error), isMissing: !/time/i.test(String(error?.message)) }))
436 const output = `${ran.stdout ?? ''}${ran.stderr ? `\n${ran.stderr}` : ''}`.trim()
437 const isMissing = 'isMissing' in ran ? ran.isMissing : onWindows && ran.exitCode === WINDOWS_COMMAND_NOT_FOUND
438 if (isMissing) return { error: { code: 'ENOENT', message: output }, output }
439 return { error: ran.exitCode === 0 ? null : { message: `exited ${ran.exitCode}` }, output }
440 }
441}
442
443async function proxyStatus($: EngineInterface, options: PluginOptions): Promise<unknown> {
444 const answered = await proxyFetch($, options, 'GET', '/proxy/status')
445 return {
446 proxy: answered.ok ? answered.data : { error: answered.error },
447 recentRecalls: (await $.store.get(RECALLS_KEY)) ?? [],
448 recentErrors: (await $.store.get(ERRORS_KEY)) ?? [],
449 }
450}
451
452function commandsFor($: EngineInterface, options: PluginOptions) {
453 return evolverCommands({
454 status: () => proxyStatus($, options),
455 search: async (text: string) => {
456 const answered = await proxyFetch($, options, 'POST', '/asset/search', { text, limit: 5 })
457 return answered.ok ? { ok: true, data: answered.data } : { ok: false, error: answered.error }
458 },
459 distillNow: async (focus: string) => distillSession($, options, await $.session.id(), focus),
460 evolveText: async () => String(await $.fs.read(`${$.plugin.root}/assets/commands/evolve.md`)),
461 followup: async (text: string) => { void quietly($, 'evolve', $.prompt.submit({ text })) },
462 runCli: (args: string[]) => runEvolverCli(args, cliRunner($)),
463 })
464}
465
466async function registerCommands($: EngineInterface, options: PluginOptions): Promise<void> {
467 for (const command of commandsFor($, options)) {
468 const hint = 'argumentHint' in command ? { argumentHint: command.argumentHint } : {}
469 await $.command.register({ name: command.name, description: command.description, ...hint })
470 }
471}
472
473async function dropRetiredStoreLedgers($: EngineInterface): Promise<void> {
474 for (const key of await $.store.keys()) if (key.startsWith('injected:')) await $.store.delete(key)
475}
476
477async function startSession($: EngineInterface, options: PluginOptions): Promise<void> {
478 const sessionId = await $.session.id()
479 await registerCommands($, options)
480 track($, 'store-ledgers', dropRetiredStoreLedgers($))
481 track($, 'turn-counters', pruneTurnCounters($))
482 track($, 'onboarding', showOnboardingNotices($, options))
483 track($, 'retention', settleRetention($, options, sessionId))
484 track($, 'orphaned', reportOrphanedInjections($, options))
485 void quietly($, 'distill', distillLeftovers($, options))
486}
487
488// `session.end` shares one short bound with every plugin's hook, so it only writes: the aborted reports wait in
489// the outbox for the next delivery, and the closed candidate for the next session start.
490async function endSession($: EngineInterface, options: PluginOptions, sessionId: string): Promise<void> {
491 const closing = Promise.all([
492 stateCall($, options, 'take-unreported', { sessionId }).then(({ assets }) => enqueueReports($, abortedReports(assets, () => sessionId))),
493 stateCall($, options, 'close-candidate', { sessionId }),
494 stateCall($, options, 'forget-session', { sessionId }),
495 ])
496 await quietly($, 'session-end', closing)
497 await $.store.delete(labelableKey(sessionId))
498 lastPrompts.delete(sessionId)
499}
500
501export const register: Register = (on, options) => {
502 on('session.start', async ($, e, next) => {
503 await startSession($, options)
504 return next(e)
505 })
506
507 // `prompt.submit` knows who sent the prompt but resolves only after its turn
508 // started, so the person's prompt is marked before `next`; `turn.start` then
509 // recalls for it. A prompt folded into a running turn starts no turn.
510 on('prompt.submit', async ($, e, next) => {
511 if (!isPersonPrompt(e.origin)) return next(e)
512 personPrompts.add(e.text)
513 lastPrompts.set(await $.session.id(), promptTextOf(e.text))
514 if (e.origin?.kind === 'composer') track($, 'follow-up', reportFollowUpLabel($, options, await $.session.id(), e.text))
515 return next(e)
516 }).catch(($, e, next) => next(e))
517
518 on('turn.start', async ($, e, next) => {
519 if (personPrompts.delete(e.text)) {
520 const sessionId = await $.session.id()
521 const turn = await turnNumberFor($, sessionId, e.turnId)
522 await recallForTurn($, options, sessionId, turn, e.turnId, e.text, next.signal).catch(error => recordFailure($, 'recall', error))
523 }
524 return next(e)
525 })
526
527 on('tool.call', async ($, e, next) => {
528 noteToolUse(e as Record<string, unknown>)
529 const isEdit = EDIT_TOOL_NAMES.includes(e.tool)
530 if (isEdit) await noteFileBeforeEdit($, e as Record<string, unknown>)
531 const ran = await next(e)
532 const checkCommand = ran.deny === undefined ? checkCommandOf(e) : null
533 if (checkCommand) turnRecord.checks.push({ command: checkCommand.slice(0, 200), label: checkLabelOf(e), failed: verificationFailed(ran) })
534 if (!isEdit || ran.deny !== undefined || ran.isError) return ran
535 turnRecord.changedLines += changedLinesOf(e)
536 noteEditedFile(e as Record<string, unknown>)
537 return ran
538 }).catch(($, e, next) => next(e))
539
540 on('turn.complete', async ($, e, next) => {
541 if (e.agentId !== undefined || !outcomeOfReason(e.reason)) return next(e)
542 if (e.reason === 'aborted') abortedTurns.add(e.turnId)
543 const sessionId = await $.session.id()
544 const turn = await turnNumberFor($, sessionId, e.turnId)
545 turnNumbers.delete(e.turnId)
546 const finished = turnRecord
547 turnRecord = freshTurnRecord()
548 const reports = await closeTurnReuse($, options, sessionId, turn, e, finished).catch(async error => {
549 await recordFailure($, 'reuse-report', error)
550 return []
551 })
552 track($, 'reuse-report', queueReports($, options, reports.map(report => ({ report, sessionId }))))
553 track($, 'retention', rememberForRetention($, sessionId, reports.map(reportedReuseOf), finished.editedBefore))
554 track($, 'distill-candidate', rememberTurnCandidate($, options, sessionId, turn, e, finished, reports))
555 const answered = await next(e)
556 const summary = turnSummaryOf({ ...finished, lastCheck: finished.checks.at(-1), turnReason: e.reason, usage: e.usage })
557 return summary ? { ...answered, text: summary } : answered
558 })
559
560 on('command.run', async ($, e, next) => {
561 const command = commandsFor($, options).find(candidate => candidate.name === e.command)
562 if (!command) return next(e)
563 const { kind, text } = await command.handler({ rawInput: e.args })
564 return kind === 'error' ? { text, exitCode: 1 } : { text }
565 })
566
567 on('session.end', async ($, e, next) => {
568 await endSession($, options, e.sessionId)
569 personPrompts.clear()
570 turnNumbers.clear()
571 abortedTurns.clear()
572 return next(e)
573 })
574}
575lib/commands.js 131 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4import { MIN_EVOLVER_VERSION } from './onboarding.js';
5
6// Commands are how a person reaches Evolver, so nothing about them sits in the model's context: each one
7// runs in the plugin and answers in the transcript. Only /evolver-evolve hands the agent a one-off prompt,
8// because reflecting on the current work is the agent's job.
9
10const NAME_PREFIX = 'evolver-';
11const OUTPUT_MAX_CHARS = 4_000;
12// The fallback runs whatever npm resolves, so it is held to the range this plugin is built against.
13const CLI_PACKAGE = `@evomap/evolver@^${MIN_EVOLVER_VERSION}`;
14
15const success = (text) => ({ kind: 'success', text });
16const failure = (text) => ({ kind: 'error', text });
17
18function shown(value) {
19 const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
20 return text.length > OUTPUT_MAX_CHARS ? `${text.slice(0, OUTPUT_MAX_CHARS)}\n…` : text;
21}
22
23/**
24 * Quotes group words the way a shell would (`--summary="two words"` stays one argument) and a backslash
25 * escapes the character after it, so a quote can be part of a value; nothing else is expanded.
26 */
27export function argumentsOf(rawInput) {
28 const args = [];
29 let current = '';
30 let quote = null;
31 let started = false;
32 let escaped = false;
33 for (const char of rawInput) {
34 if (escaped) {
35 current += char;
36 escaped = false;
37 } else if (char === '\\' && quote !== "'") {
38 escaped = true;
39 started = true;
40 } else if (quote) {
41 if (char === quote) quote = null;
42 else current += char;
43 } else if (char === '"' || char === "'") {
44 quote = char;
45 started = true;
46 } else if (/\s/.test(char)) {
47 if (started) args.push(current);
48 current = '';
49 started = false;
50 } else {
51 current += char;
52 started = true;
53 }
54 }
55 if (started) args.push(current);
56 return args;
57}
58
59/**
60 * The installed `evolver` when there is one, else the published package through npx. `run` takes an argv and
61 * resolves `{ error, output }`, with `error.code === 'ENOENT'` when the executable is missing.
62 */
63export async function runEvolverCli(args, run) {
64 let { error, output } = await run(['evolver', ...args]);
65 if (error?.code === 'ENOENT') ({ error, output } = await run(['npx', '-y', CLI_PACKAGE, ...args]));
66 return error ? failure(shown(output || String(error.message))) : success(shown(output || 'done'));
67}
68
69function cliCommand(subcommand, description, argumentHint, runCli) {
70 return {
71 name: `${NAME_PREFIX}${subcommand}`,
72 description,
73 argumentHint,
74 handler: ({ rawInput }) => runCli([subcommand, ...argumentsOf(rawInput)]),
75 };
76}
77
78function evolveCommand(evolveText, followup) {
79 return {
80 name: `${NAME_PREFIX}evolve`,
81 description: 'Run an evolution checkpoint — recall relevant past outcomes, reflect on the current task, and record what was learned.',
82 argumentHint: 'optional focus',
83 handler: async ({ rawInput }) => {
84 const focus = rawInput.trim();
85 const body = await evolveText();
86 await followup(focus ? `${body}\n\nFocus: ${focus}` : body);
87 return success(`Running /${NAME_PREFIX}evolve.`);
88 },
89 };
90}
91
92/**
93 * `status` and `search` answer from the Proxy, `distill` distills the session's latest verified turn now,
94 * and the engine commands run the `evolver` executable. A command that takes no argument has no hint.
95 */
96export function evolverCommands({ status, search, distillNow, evolveText, followup, runCli }) {
97 return [
98 {
99 name: `${NAME_PREFIX}status`,
100 description: 'Show Evolver health: the Proxy, Hub auth, recent recalls and reuse reports.',
101 handler: async () => success(shown(await status())),
102 },
103 {
104 name: `${NAME_PREFIX}search`,
105 description: 'Search the EvoMap network for reusable assets.',
106 argumentHint: '<task description or error text>',
107 handler: async ({ rawInput }) => {
108 const text = rawInput.trim();
109 if (!text) return failure(`Usage: /${NAME_PREFIX}search <task description or error text>`);
110 const result = await search(text);
111 return result.ok ? success(shown(result.data)) : failure(String(result.error));
112 },
113 },
114 {
115 name: `${NAME_PREFIX}distill`,
116 description: "Distill this session's latest verified turn into a reusable Gene now, instead of at the next session start.",
117 argumentHint: 'optional focus',
118 handler: async ({ rawInput }) => {
119 const outcome = await distillNow(rawInput.trim());
120 if (outcome.status === 'nothing') return failure('Nothing to distill yet: no turn of this session finished verified.');
121 return outcome.status === 'sent' ? success(shown(outcome.data ?? 'distilled')) : failure(`Distillation ${outcome.status}: ${outcome.error ?? ''}`.trim());
122 },
123 },
124 evolveCommand(evolveText, followup),
125 cliCommand('sync', 'Sync assets between the local store and the EvoMap Hub (evolver sync).', '[--scope=…] [--type=…] [--dry-run]', runCli),
126 cliCommand('review', "Review Evolver's pending evolved changes, then approve or reject them (evolver review).", '[--approve | --reject]', runCli),
127 cliCommand('run', 'Run one Evolver self-evolution cycle on this repository (evolver run).', '[--loop] [--dry-run] [--strategy=…]', runCli),
128 cliCommand('solidify', 'Solidify the working changes into a durable Gene or Capsule (evolver solidify).', '[--dry-run] [--intent=…] [--summary=…]', runCli),
129 ];
130}
131lib/distill.js 139 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4import { withoutSecrets } from './redact.js';
5
6// Distillation runs once a session and outside the agent's conversation: each turn that finished verified only
7// leaves a candidate, the latest one wins, and the candidate becomes a Gene through one model call over a digest
8// of the turn — never the whole history, which cost ten times as much for fewer usable Genes in the benchmark.
9
10const PROMPT_MAX_CHARS = 6_000;
11const ANSWER_MAX_CHARS = 3_000;
12const COMMAND_MAX_CHARS = 300;
13const MAX_COMMANDS = 40;
14const LIST_FIELDS = ['strategy', 'validation', 'signals', 'preconditions'];
15const ARGUMENT_FIELDS = ['title', 'summary', ...LIST_FIELDS];
16const ITEM_NUMBER = /^\s*(?:\d+[.)]|[-*•])\s+/;
17const ANSWERED = 'answer';
18const DISTILL_MAX_TOKENS = 4_096;
19
20/**
21 * Why a finished turn leaves no candidate, or null when it does. A chat reply without a single command has no
22 * method to keep. A turn that reused an injected strategy is distilled too: the engine's intake drops a Gene
23 * that repeats one it already has.
24 */
25export function skipReason(turnReason, record) {
26 if (turnReason !== ANSWERED) return 'not_answered';
27 if (!record.answer) return 'no_answer';
28 if (record.checks.at(-1)?.failed) return 'failed_check';
29 if (record.commands.length === 0 && record.edits.length === 0) return 'no_tool_use';
30 return null;
31}
32
33// Keys and tokens are stripped before anything is written to disk or sent to a model or the Proxy. The
34// sidecar stamps the owning process when it writes the candidate.
35export function candidateOf({ prompt, record, model, turn, now }) {
36 return {
37 prompt: withoutSecrets(String(prompt ?? '')).slice(0, PROMPT_MAX_CHARS),
38 commands: record.commands.slice(-MAX_COMMANDS).map((command) => withoutSecrets(command).slice(0, COMMAND_MAX_CHARS)),
39 paths: [...new Set(record.paths)].map((path) => withoutSecrets(path)),
40 checks: record.checks.map(({ command, failed }) => ({ command: withoutSecrets(command), failed })),
41 answer: withoutSecrets(record.answer).slice(0, ANSWER_MAX_CHARS),
42 model,
43 turn,
44 attempts: 0,
45 at: now,
46 };
47}
48
49export function distillPrompt(candidate, focus = '') {
50 const lines = (items, render) => items.map(render).join('\n') || '(none)';
51 const focusText = withoutSecrets(String(focus ?? ''));
52 return [
53 'Below is the record of a task an agent has just finished and verified. Turn it into one reusable Gene:',
54 'a method another agent could follow on a similar task, written for the kind of data or system involved,',
55 'not for these files, names or values. Do not include the answer itself.',
56 ...(focusText ? [`Focus on: ${focusText}`] : []),
57 'Answer with a JSON object only, with these fields:',
58 ' title: short capability name',
59 ' summary: what was solved and under which conditions',
60 ' strategy: ordered, reproducible steps',
61 ' validation: checks that proved the result',
62 ' signals: keywords of the problem this generalizes to',
63 ' preconditions: when the method applies',
64 '',
65 '## Task',
66 candidate.prompt,
67 '',
68 '## Commands run',
69 lines(candidate.commands, (command) => `- ${command}`),
70 '',
71 '## Files read or written',
72 lines(candidate.paths, (path) => `- ${path}`),
73 '',
74 '## Checks',
75 lines(candidate.checks, (check) => `- ${check.failed ? 'FAILED' : 'passed'}: ${check.command}`),
76 '',
77 '## Final answer',
78 candidate.answer,
79 ].join('\n');
80}
81
82// Models sometimes write a list field as one numbered paragraph ("1. … 2. …"), which the core reads as one step.
83function listOf(value) {
84 if (Array.isArray(value)) return value;
85 if (typeof value !== 'string') return value;
86 return value.split(/\n+|(?<=\.)\s+(?=\d+[.)]\s)/).map((item) => item.replace(ITEM_NUMBER, '').trim()).filter(Boolean);
87}
88
89export function argumentsOf(text) {
90 const match = String(text ?? '').match(/\{[\s\S]*\}/);
91 if (!match) return null;
92 try {
93 const parsed = JSON.parse(match[0]);
94 if (typeof parsed?.summary !== 'string' || !parsed.summary.trim()) return null;
95 for (const field of LIST_FIELDS) if (field in parsed) parsed[field] = listOf(parsed[field]);
96 return Object.fromEntries(ARGUMENT_FIELDS.filter((field) => parsed[field] !== undefined).map((field) => [field, parsed[field]]));
97 } catch {
98 return null;
99 }
100}
101
102export function distillBody(candidate, args, usage) {
103 return {
104 platform: 'claude-code',
105 trigger: 'session_end',
106 user_prompt: candidate.prompt,
107 // The core rejects a Gene that repeats this answer's values (answer_leak).
108 final_answer: candidate.answer,
109 ...args,
110 execution: { trace: candidate.checks.map((check) => ({ command: check.command, exit: check.failed ? 1 : 0 })) },
111 persist: true,
112 publish: false,
113 // What this distillation itself cost, kept apart from the agent's own tokens.
114 ...(usage ? { distill_usage: usage } : {}),
115 };
116}
117
118/**
119 * Distill one candidate through the session's own model (`complete` is `$.model.complete`). `cancel` stops it
120 * and `isCurrent` is asked once more before anything is persisted, since the candidate may have been dropped
121 * while the model answered. Resolves to what happened; never throws.
122 */
123export async function distillCandidate({ proxyFetch, complete, candidate, focus, timeoutMs, cancel, isCurrent = async () => true }) {
124 if (!complete || !candidate?.model) return { status: 'no_model' };
125 try {
126 const request = { model: candidate.model, prompt: distillPrompt(candidate, focus), maxTokens: DISTILL_MAX_TOKENS, timeoutMs };
127 const answered = await complete(request, cancel ? { signal: cancel } : undefined);
128 if (!answered.isAnswered) return cancel?.aborted ? { status: 'dropped', usage: answered.usage } : { status: 'failed', error: answered.reason };
129 const args = argumentsOf(answered.text);
130 if (!args) return { status: 'unparsed', usage: answered.usage };
131 const isWanted = !cancel?.aborted && (await isCurrent()) && !cancel?.aborted;
132 if (!isWanted) return { status: 'dropped', usage: answered.usage };
133 const result = await proxyFetch('POST', '/conversation/distill', distillBody(candidate, args, answered.usage));
134 return result?.ok ? { status: 'sent', usage: answered.usage, data: result.data } : { status: 'failed', error: String(result?.error) };
135 } catch (error) {
136 return { status: 'failed', error: String(error?.message ?? error) };
137 }
138}
139lib/edited-content.js 27 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4export const EDIT_TOOL_NAMES = ['Write', 'Edit', 'MultiEdit', 'NotebookEdit'];
5
6function firstString(input, keys) {
7 for (const key of keys) {
8 if (typeof input?.[key] === 'string' && input[key].length > 0) return input[key];
9 }
10 return '';
11}
12
13export function editedPath(input) {
14 return firstString(input, ['file_path', 'notebook_path']);
15}
16
17function lineCount(text) {
18 return typeof text === 'string' && text.length > 0 ? text.split('\n').length : 0;
19}
20
21// Lines a successful edit touched, removed plus written: the blast radius the
22// savings estimator is sized by.
23export function changedLinesOf(input) {
24 const edits = Array.isArray(input?.edits) ? input.edits : [input];
25 return edits.reduce((total, edit) => total + lineCount(edit?.old_string) + lineCount(edit?.new_string ?? edit?.content ?? edit?.new_source), 0);
26}
27lib/feedback-label.js 16 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4import { looksLikeCorrection } from './dissatisfaction.js';
5
6const PRAISE_PATTERNS = [
7 /\b(?:thanks|thank you|thx|perfect|great|awesome|nice|excellent|works now|it works|that works|lgtm|looks good)\b/i,
8 /谢谢|感谢|完美|好了|可以了|搞定|没问题了|成功了|不错|很好|太好了|牛/,
9];
10
11export function feedbackLabelOf(text) {
12 if (typeof text !== 'string' || !text.trim()) return null;
13 if (looksLikeCorrection(text)) return 'correction';
14 return PRAISE_PATTERNS.some((pattern) => pattern.test(text)) ? 'praise' : null;
15}
16lib/onboarding.js 60 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4// 2.0.39 is the first Proxy whose `/asset/fetch` recalls by text; an older one
5// answers every recall empty, so priming silently never injects anything.
6export const MIN_EVOLVER_VERSION = '2.0.39';
7
8const STATE_PRUNE_MS = 7 * 24 * 60 * 60 * 1000;
9
10export function versionOf(text) {
11 const match = /(\d+)\.(\d+)\.(\d+)/.exec(String(text ?? ''));
12 return match ? match.slice(1, 4).join('.') : null;
13}
14
15export function isOlderThan(version, minimum) {
16 const have = versionOf(version)?.split('.').map(Number);
17 const need = versionOf(minimum)?.split('.').map(Number);
18 if (!have || !need) return false;
19 for (let index = 0; index < 3; index += 1) {
20 if (have[index] !== need[index]) return have[index] < need[index];
21 }
22 return false;
23}
24
25export function upgradeNoticeText(version) {
26 if (!version || !isOlderThan(version, MIN_EVOLVER_VERSION)) return null;
27 return `Evolver ${version} is installed; network strategy recall needs ${MIN_EVOLVER_VERSION}+. `
28 + 'Run `npm install -g @evomap/evolver@latest`, then `evolver` once to restart the Proxy.';
29}
30
31export function pendingClaimUrl(text) {
32 try {
33 const parsed = new URL(String(text ?? '').trim());
34 const host = parsed.hostname.toLowerCase();
35 if (parsed.protocol !== 'https:') return null;
36 if (host !== 'evomap.ai' && !host.endsWith('.evomap.ai')) return null;
37 return parsed.toString();
38 } catch {
39 return null;
40 }
41}
42
43// Shared by every throttled notice, so callers pass a namespaced key. A claim
44// url carries a secret, so callers hash it before it becomes a key.
45export function noticeDecision(state, key, ttlMs, now) {
46 const previous = state?.[key];
47 if (typeof previous === 'number' && now - previous < ttlMs) return { isDue: false, state };
48 const next = { [key]: now };
49 for (const [existing, timestamp] of Object.entries(state ?? {})) {
50 if (existing !== key && typeof timestamp === 'number' && now - timestamp <= STATE_PRUNE_MS) next[existing] = timestamp;
51 }
52 return { isDue: true, state: next };
53}
54
55// On Windows the global `evolver` is an `evolver.cmd` shim, which Node will not
56// start without a shell, so the probe goes through cmd.exe there.
57export function versionProbeArgv(isWindows) {
58 return isWindows ? ['cmd.exe', '/d', '/s', '/c', 'evolver --version'] : ['evolver', '--version'];
59}
60lib/recall.js 162 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4import { withoutSecrets } from './redact.js';
5import { MIN_RELEVANCE, relevanceOf, sharedTerms } from './relevance.js';
6
7// `/asset/fetch` with text and no ids recalls whole assets in one round trip.
8// No limit is sent: the Hub's default for a text recall (two assets) applies,
9// and the Hub charges per asset it returns, so asking for more costs credits a
10// new account may not have.
11const MIN_PROMPT_CHARS = 8;
12const PROMPT_MAX_CHARS = 400;
13// One strategy should read as an approach, not a transcript; a candidate that
14// would inject more than this is passed over for the next.
15const MAX_INJECTED_CHARS = 4000;
16const STEP_MAX_CHARS = 400;
17const TITLE_MAX_CHARS = 80;
18const DEFAULT_MIN_SIMILARITY = 0.3;
19// Text recall skips the Hub's search tuning, so it returns genes too thin to
20// follow: two or three steps say too little to reuse. Longer strategies are
21// kept whole, each step capped at STEP_MAX_CHARS.
22const MIN_STRATEGY_STEPS = 4;
23const UNSCORED = -1;
24const EMPTY_MATCH = { ids: [], text: '' };
25
26function strategySteps(asset) {
27 const steps = asset?.strategy ?? asset?.payload?.strategy ?? asset?.gene?.strategy;
28 const list = Array.isArray(steps) ? steps : [steps];
29 return list
30 .filter((step) => typeof step === 'string' && step.trim())
31 .map((step) => step.trim().slice(0, STEP_MAX_CHARS));
32}
33
34// Only what the person typed is matched: notifications, peer messages and other
35// plugins' prompts are not the person's task, and Claude Code's own reminders
36// would drown the task in boilerplate.
37const PERSON_ORIGINS = new Set(['composer', 'bridge', 'sdk', 'scheduled-trigger']);
38
39export function isPersonPrompt(origin) {
40 return origin === undefined || PERSON_ORIGINS.has(origin?.kind);
41}
42
43// Engine reminders, task markup and links are not what the person asked:
44// a session notification is nothing but a `<system-reminder>`, and a link's
45// host and path words matched assets that only shared a domain.
46const REMINDER_BLOCK = /<system-reminder>[\s\S]*?(?:<\/system-reminder>|$)/g;
47const MARKUP_TAG = /<\/?[a-z][\w-]*(?:\s[^<>]*)?>/gi;
48const LINK = /\b(?:https?:\/\/|www\.)\S+/gi;
49
50export function promptTextOf(text) {
51 if (typeof text !== 'string') return '';
52 return withoutSecrets(text)
53 .replace(REMINDER_BLOCK, ' ')
54 .replace(MARKUP_TAG, ' ')
55 .replace(LINK, ' ')
56 .replace(/\s+/g, ' ')
57 .trim()
58 .slice(0, PROMPT_MAX_CHARS);
59}
60
61function recalledAssets(data) {
62 const found = [data?.assets, data?.results, data?.payload?.results].find(Array.isArray) ?? [];
63 return found.filter((asset) => asset && typeof asset.asset_id === 'string' && asset.asset_id);
64}
65
66const CJK_SCRIPT = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
67const MIN_CJK_TITLE_CHARS = 5;
68
69function trimmedText(value) {
70 return typeof value === 'string' && value.trim() ? value.trim() : '';
71}
72
73// A Hub short_title is sometimes a truncated fragment: `Object`, `自动化小`.
74// Character count cannot separate those from a good title, because `智能缓存优化`
75// says as much in six characters as a Latin title says in forty.
76function looksLikeAName(text) {
77 if (!text) return false;
78 if (CJK_SCRIPT.test(text)) return [...text].length >= MIN_CJK_TITLE_CHARS;
79 return /\s/.test(text);
80}
81
82function readableNameOf(asset) {
83 const title = trimmedText(asset?.short_title);
84 if (looksLikeAName(title)) return title.slice(0, TITLE_MAX_CHARS);
85 const described = trimmedText(asset?.nl_summary) || trimmedText(asset?.summary);
86 if (described) return described.slice(0, TITLE_MAX_CHARS);
87 return title || asset?.asset_type || asset?.type || 'Gene';
88}
89
90function similarityOf(asset) {
91 return typeof asset.similarity === 'number' ? asset.similarity : UNSCORED;
92}
93
94// A Proxy's similarity score is advisory — the same question scored 0.88 asked
95// one way and 0.40 another — and a Proxy that reports none must not filter
96// everything out, so the floor applies only where a score exists. Relevance to
97// the prompt gates every candidate and breaks ties; the Hub's own order is not
98// trusted, since it weighs more than this prompt.
99function rankedCandidates(text, assets, listedIds, minSimilarity) {
100 return assets
101 .filter((asset) => !listedIds.has(asset.asset_id))
102 .filter((asset) => typeof asset.similarity !== 'number' || asset.similarity >= minSimilarity)
103 .map((asset) => ({ asset, relevance: relevanceOf(sharedTerms(text, asset)) }))
104 .filter(({ relevance }) => relevance >= MIN_RELEVANCE)
105 .sort((left, right) => similarityOf(right.asset) - similarityOf(left.asset) || right.relevance - left.relevance)
106 .map(({ asset }) => asset);
107}
108
109function bestRelevanceOf(text, assets, listedIds) {
110 return assets
111 .filter((asset) => !listedIds.has(asset.asset_id))
112 .reduce((best, asset) => Math.max(best, relevanceOf(sharedTerms(text, asset))), 0);
113}
114
115async function recalledData(proxyFetch, text) {
116 try {
117 const result = await proxyFetch('POST', '/asset/fetch', { text });
118 return result?.ok ? result.data : null;
119 } catch {
120 return null;
121 }
122}
123
124// Picks one strategy for the prompt, or none. An unreachable Proxy, a slow Hub
125// or a malformed body yields none rather than an error: recall must never cost
126// the turn. Only the steps are injected — a summary tells the model something
127// exists, the steps are what it can reuse. `onTrace` hears how the decision was
128// made, so it can be shown or kept without reaching the model.
129export async function recallStrategy(proxyFetch, text, { listedIds = new Set(), minSimilarity = DEFAULT_MIN_SIMILARITY, onTrace = (_trace) => {} } = {}) {
130 if (text.length < MIN_PROMPT_CHARS) {
131 onTrace({ outcome: 'short' });
132 return EMPTY_MATCH;
133 }
134
135 const recalled = await recalledData(proxyFetch, text);
136 if (!recalled) {
137 onTrace({ outcome: 'unavailable' });
138 return EMPTY_MATCH;
139 }
140
141 const assets = recalledAssets(recalled);
142 const ranked = rankedCandidates(text, assets, listedIds, minSimilarity);
143 for (const candidate of ranked) {
144 const steps = strategySteps(candidate);
145 if (steps.length < MIN_STRATEGY_STEPS) continue;
146
147 const name = readableNameOf(candidate);
148 const injected = [
149 `[Evolution Memory] ${name} (EvoMap network):`,
150 ...steps.map((step, index) => `${index + 1}. ${step}`),
151 '',
152 'Apply them where they fit.',
153 ].join('\n');
154 if (injected.length > MAX_INJECTED_CHARS) continue;
155
156 onTrace({ outcome: 'injected', recalled: assets.length, eligible: ranked.length, name, relevance: relevanceOf(sharedTerms(text, candidate)) });
157 return { ids: [candidate.asset_id], name, text: injected };
158 }
159 onTrace({ outcome: 'skipped', recalled: assets.length, eligible: ranked.length, bestRelevance: bestRelevanceOf(text, assets, listedIds) });
160 return EMPTY_MATCH;
161}
162lib/proxy-response.js 62 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4import { normalizeLoopbackUrl } from './loopback.js';
5
6/** @typedef {{ ok: true, data: any } | { ok: false, error: string }} ProxyResult */
7
8export const DEFAULT_PROXY_PORT = '19820';
9
10const START_HINT =
11 'Start it by running `evolver` once inside a git repo (the CLI launches the Proxy). '
12 + 'Set the proxy_port option if you use a non-default port.';
13
14// The Proxy rotates its loopback URL and bearer token into ~/.evolver/settings.json;
15// a URL that is not loopback is ignored so the token never leaves the machine.
16export function proxySettingsFrom(settingsText, port) {
17 let url = null;
18 let token = null;
19 try {
20 const settings = JSON.parse(settingsText);
21 if (settings?.proxy?.url) url = normalizeLoopbackUrl(settings.proxy.url);
22 if (settings?.proxy?.token) token = String(settings.proxy.token);
23 } catch {
24 }
25 return { url: url ?? `http://127.0.0.1:${port || DEFAULT_PROXY_PORT}`, token };
26}
27
28function httpErrorHint(status, base, token) {
29 if (status === 401 || status === 403) {
30 return token
31 ? ' The Proxy token in ~/.evolver/settings.json was rejected; restart Evolver so it writes fresh settings.'
32 : ` No Proxy token was found and the request was rejected — another process may be using ${base}. ${START_HINT}`;
33 }
34 if (status === 404) return ` Endpoint not found at ${base} — upgrade or verify the Evolver Proxy.`;
35 return '';
36}
37
38/** @returns {ProxyResult} */
39export function timedOutResult(base, timeoutMs) {
40 return { ok: false, error: `Proxy request timed out after ${timeoutMs}ms. Evolver Proxy not reachable at ${base}. ${START_HINT}` };
41}
42
43/** @returns {ProxyResult} */
44export function unreachableResult(base, error) {
45 return { ok: false, error: `Proxy connection failed: ${error?.message ?? error}. Evolver Proxy not reachable at ${base}. ${START_HINT}` };
46}
47
48/** @returns {ProxyResult} */
49export function proxyResultOf(response, base, token) {
50 let data;
51 try {
52 data = response.text ? JSON.parse(response.text) : {};
53 } catch {
54 data = { raw: response.text };
55 }
56 if (response.ok) return { ok: true, data };
57 return {
58 ok: false,
59 error: `Proxy at ${base} returned HTTP ${response.status}: ${JSON.stringify(data)}.${httpErrorHint(response.status, base, token)}`,
60 };
61}
62lib/report-outbox.js 40 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4export const OUTBOX_TTL_MS = 8 * 24 * 60 * 60 * 1000;
5
6const keyOf = (report) => `${report.task_id}\0${report.asset_id}`;
7
8function pruned(outbox, now) {
9 return Object.fromEntries(Object.entries(outbox ?? {}).filter(([, entry]) => now - Number(entry?.queuedAt) <= OUTBOX_TTL_MS));
10}
11
12export function withQueued(outbox, queued, now) {
13 const kept = pruned(outbox, now);
14 for (const { report, sessionId } of queued) {
15 kept[keyOf(report)] ??= { report, sessionId, queuedAt: now, attempts: 0 };
16 }
17 return kept;
18}
19
20export const SENT = 'sent';
21export const REJECTED = 'rejected';
22export const RETRY = 'retry';
23
24export function isSettled(entry) {
25 return Boolean(entry.sentAt || entry.rejectedAt);
26}
27
28function settlementOf({ verdict, reason, status }, now) {
29 if (verdict === SENT) return { sentAt: now };
30 if (verdict === REJECTED) return { rejectedAt: now, rejection: { reason, ...(status !== undefined && { status }) } };
31 return {};
32}
33
34export function withAttempt(outbox, key, attempt, now) {
35 const entry = outbox[key];
36 if (!entry) return outbox;
37 const local = attempt.isLocal ? { localAt: now } : {};
38 return { ...outbox, [key]: { ...entry, attempts: entry.attempts + 1, ...local, ...settlementOf(attempt, now) } };
39}
40lib/retention.js 19 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4export const ABSENT = 'absent';
5
6function fileFateOf({ before, after, now }) {
7 if (now === after) return 'kept';
8 if (now === before) return 'reverted';
9 return 'rewritten';
10}
11
12export function retentionOf(files) {
13 const changed = (files ?? []).filter(({ before, after }) => before !== after);
14 if (changed.length === 0) return { class: 'no_change', files: 0 };
15 const fates = new Set(changed.map(fileFateOf));
16 const verdict = fates.size === 1 ? [...fates][0] : 'rewritten';
17 return { class: verdict, files: changed.length };
18}
19lib/reuse.js 129 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4import { checkEvidenceOf } from './checks.js';
5import { REJECTED, RETRY, SENT, isSettled, withAttempt } from './report-outbox.js';
6import { outcomeOfReason } from './turn-outcomes.js';
7
8const LABEL_OUTCOMES = { correction: 'failed', praise: 'success' };
9const RETENTION_OUTCOMES = { kept: 'success', reverted: 'failed' };
10
11export function turnTaskId(sessionId, turn) {
12 return `claude-code:${sessionId || 'unknown'}:${turn ?? 'unknown'}`;
13}
14
15// The model follows a strategy injected into its turn, so an injection is a use; whether it helped is
16// what the outcome, the check, the next prompt and the edits' retention tell.
17const APPLIED = 'used';
18
19export function immediateEvidenceOf({ checks, turnReason }) {
20 const check = checkEvidenceOf(checks);
21 return {
22 tier: check ? 'L1' : 'none',
23 applied: APPLIED,
24 ...(check && { check }),
25 aborted: turnReason === 'aborted',
26 stage: 'immediate',
27 };
28}
29
30function immediateOutcomeOf(evidence, turnReason) {
31 if (evidence.check) return evidence.check.passed ? 'success' : 'failed';
32 return outcomeOfReason(turnReason) ?? 'failed';
33}
34
35function checkPhrase(check) {
36 if (!check) return 'no check ran';
37 const result = check.passed ? 'passed' : 'failed';
38 return `last ${check.kind} ${result}${check.fail_then_pass ? ' after failing earlier' : ''}`;
39}
40
41function reportOf({ assetId, taskId, outcome, reason, evidence }) {
42 return { asset_id: assetId, outcome, task_id: taskId, reason, evidence };
43}
44
45export function immediateReportOf({ asset, sessionId, turn, turnReason, checks }) {
46 const evidence = immediateEvidenceOf({ checks, turnReason });
47 return reportOf({
48 assetId: asset.assetId,
49 taskId: turnTaskId(sessionId, turn),
50 outcome: immediateOutcomeOf(evidence, turnReason),
51 reason: `Injected by Evolver into Claude Code turn ${turn}; ${checkPhrase(evidence.check)}.`,
52 evidence,
53 });
54}
55
56export function reportedReuseOf(report) {
57 return { assetId: report.asset_id, applied: report.evidence.applied, taskId: report.task_id };
58}
59
60export function correctionReportOf(reuse, label) {
61 if (!LABEL_OUTCOMES[label]) return null;
62 return reportOf({
63 ...reuse,
64 taskId: `${reuse.taskId}:correction`,
65 outcome: LABEL_OUTCOMES[label],
66 reason: `The person's next prompt read as ${label} of the turn that reused this strategy.`,
67 evidence: { tier: 'L3', applied: reuse.applied, stage: 'correction' },
68 });
69}
70
71export function retentionReportOf(reuse, retentionClass) {
72 if (!RETENTION_OUTCOMES[retentionClass]) return null;
73 return reportOf({
74 ...reuse,
75 taskId: `${reuse.taskId}:retention`,
76 outcome: RETENTION_OUTCOMES[retentionClass],
77 reason: `By the next session the files the turn edited were ${retentionClass}.`,
78 evidence: { tier: 'L2', applied: reuse.applied, stage: 'retention' },
79 });
80}
81
82const REJECTED_BY_HUB = /^hub (?:400|422)\b/;
83
84function isRejection(data) {
85 return data?.terminal === true || REJECTED_BY_HUB.test(String(data?.reason ?? ''));
86}
87
88function isTaken(data) {
89 return data?.recorded !== false || data?.reason === 'duplicate_report';
90}
91
92export function deliveryOf(result) {
93 if (result?.ok !== true) return { verdict: RETRY };
94 if (isRejection(result.data)) return { verdict: REJECTED, reason: String(result.data.reason ?? 'rejected'), status: result.data.status };
95 return { verdict: isTaken(result.data) ? SENT : RETRY };
96}
97
98async function postToHub(proxyFetch, report) {
99 try {
100 return deliveryOf(await proxyFetch('POST', '/asset/reuse-result', report));
101 } catch {
102 return { verdict: RETRY };
103 }
104}
105
106function isLocalRecordDue({ report, localAt }, delivery) {
107 return !localAt && delivery.verdict !== REJECTED && report.evidence.tier !== 'none';
108}
109
110async function recordedLocally(recordLocally, { report, sessionId }) {
111 return recordLocally({ assetId: report.asset_id, outcome: report.outcome, sessionId }).catch(() => false);
112}
113
114async function attemptOf(ledgers, entry) {
115 const delivery = await postToHub(ledgers.proxyFetch, entry.report);
116 const isLocal = isLocalRecordDue(entry, delivery) && (await recordedLocally(ledgers.recordLocally, entry));
117 if (delivery.verdict === REJECTED) await ledgers.onRejected({ taskId: entry.report.task_id, assetId: entry.report.asset_id, ...delivery });
118 return { ...delivery, isLocal };
119}
120
121export async function deliverPending(ledgers, outbox, now) {
122 let delivered = outbox;
123 for (const [key, entry] of Object.entries(outbox)) {
124 if (isSettled(entry)) continue;
125 delivered = withAttempt(delivered, key, await attemptOf(ledgers, entry), now);
126 }
127 return delivered;
128}
129lib/status-line.js 38 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2026 EvoMap
3
4import { MIN_RELEVANCE } from './relevance.js';
5
6const NAME_MAX_CHARS = 40;
7const LINE_MAX_CHARS = 160;
8
9function plural(count, noun) {
10 return `${count} ${noun}${count === 1 ? '' : 's'}`;
11}
12
13export function recallStatusOf(trace) {
14 switch (trace?.outcome) {
15 case 'short':
16 return 'recall: prompt too short';
17 case 'unavailable':
18 return 'recall: Proxy gave no answer';
19 case 'waiting':
20 return `recall: still waiting after ${Math.round(trace.waitedMs / 1000)}s, lands next step`;
21 case 'dropped':
22 return 'recall: arrived after the turn was interrupted, dropped';
23 case 'injected':
24 return `recall: injected "${String(trace.name).slice(0, NAME_MAX_CHARS)}" (${plural(trace.recalled, 'hit')}, relevance ${trace.relevance})`;
25 case 'skipped':
26 return trace.recalled === 0
27 ? 'recall: no assets came back'
28 : `recall: ${plural(trace.recalled, 'hit')}, best relevance ${trace.bestRelevance} (needs ${MIN_RELEVANCE}), none injected`;
29 default:
30 return null;
31 }
32}
33
34export function statusLineOf(parts) {
35 const shown = parts.filter(Boolean);
36 return shown.length === 0 ? undefined : `evolver · ${shown.join(' · ')}`.slice(0, LINE_MAX_CHARS);
37}
38