@evomap/evolver-cli 2.0.0-beta.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/dist/antiGeneBenchmark.d.ts +9 -0
- package/dist/antiGeneBenchmark.js +173 -0
- package/dist/antiGeneRollout.d.ts +14 -0
- package/dist/antiGeneRollout.js +276 -0
- package/dist/atp.d.ts +122 -0
- package/dist/atp.js +413 -0
- package/dist/atpAutoDeliver.d.ts +53 -0
- package/dist/atpAutoDeliver.js +197 -0
- package/dist/atpAutobuyPrompt.d.ts +48 -0
- package/dist/atpAutobuyPrompt.js +109 -0
- package/dist/autoDistillAntiGene.d.ts +63 -0
- package/dist/autoDistillAntiGene.js +396 -0
- package/dist/autoDistillLlm.d.ts +94 -0
- package/dist/autoDistillLlm.js +510 -0
- package/dist/autoDistillTranscript.d.ts +87 -0
- package/dist/autoDistillTranscript.js +364 -0
- package/dist/autoRecall.d.ts +25 -0
- package/dist/autoRecall.js +80 -0
- package/dist/autoexec.d.ts +237 -0
- package/dist/autoexec.js +1041 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +7 -0
- package/dist/cliContracts.d.ts +72 -0
- package/dist/cliContracts.js +815 -0
- package/dist/commands.d.ts +9 -0
- package/dist/commands.js +10 -0
- package/dist/cursorRewrite.d.ts +42 -0
- package/dist/cursorRewrite.js +65 -0
- package/dist/cycleConsumer.d.ts +42 -0
- package/dist/cycleConsumer.js +519 -0
- package/dist/daemonLoop.d.ts +33 -0
- package/dist/daemonLoop.js +72 -0
- package/dist/dispatch.d.ts +10 -0
- package/dist/dispatch.js +75 -0
- package/dist/distillObserver.d.ts +33 -0
- package/dist/distillObserver.js +146 -0
- package/dist/distillPrimitives.d.ts +48 -0
- package/dist/distillPrimitives.js +142 -0
- package/dist/doctor.d.ts +54 -0
- package/dist/doctor.js +931 -0
- package/dist/geneValue.d.ts +37 -0
- package/dist/geneValue.js +97 -0
- package/dist/index.d.ts +193 -0
- package/dist/index.js +1135 -0
- package/dist/lifecycle.d.ts +75 -0
- package/dist/lifecycle.js +859 -0
- package/dist/login.d.ts +10 -0
- package/dist/login.js +38 -0
- package/dist/migrate/divergenceAudit.d.ts +29 -0
- package/dist/migrate/divergenceAudit.js +37 -0
- package/dist/migrate/fieldMap.d.ts +18 -0
- package/dist/migrate/fieldMap.js +68 -0
- package/dist/migrate/v1Import.d.ts +16 -0
- package/dist/migrate/v1Import.js +118 -0
- package/dist/phub.d.ts +18 -0
- package/dist/phub.js +284 -0
- package/dist/recall.d.ts +26 -0
- package/dist/recall.js +162 -0
- package/dist/recipe.d.ts +61 -0
- package/dist/recipe.js +564 -0
- package/dist/reflectionObserver.d.ts +8 -0
- package/dist/reflectionObserver.js +6 -0
- package/dist/reuse.d.ts +48 -0
- package/dist/reuse.js +300 -0
- package/dist/reuseReport.d.ts +20 -0
- package/dist/reuseReport.js +255 -0
- package/dist/reviewFilter.d.ts +4 -0
- package/dist/reviewFilter.js +6 -0
- package/dist/runtimeSessionSource.d.ts +9 -0
- package/dist/runtimeSessionSource.js +29 -0
- package/dist/setupHooks.d.ts +2 -0
- package/dist/setupHooks.js +410 -0
- package/dist/skill2gep.d.ts +144 -0
- package/dist/skill2gep.js +321 -0
- package/dist/skillDistill.d.ts +75 -0
- package/dist/skillDistill.js +342 -0
- package/dist/solo/breaker.d.ts +14 -0
- package/dist/solo/breaker.js +21 -0
- package/dist/solo/gitGuard.d.ts +17 -0
- package/dist/solo/gitGuard.js +62 -0
- package/dist/solo/mode.d.ts +12 -0
- package/dist/solo/mode.js +55 -0
- package/dist/thesis.d.ts +43 -0
- package/dist/thesis.js +179 -0
- package/dist/trajectoryExport.d.ts +1 -0
- package/dist/trajectoryExport.js +895 -0
- package/dist/valueDigest.d.ts +33 -0
- package/dist/valueDigest.js +94 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +14 -0
- package/package.json +38 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1135 @@
|
|
|
1
|
+
import { events, ops, hooks, mailbox } from '@evomap/evolver-core';
|
|
2
|
+
import { readEvents, statusReport, listCycles, showCycle, listTriggers, buildNarrativeSnapshot, buildRetentionReport } from './commands.js';
|
|
3
|
+
import { runGeneValue } from './geneValue.js';
|
|
4
|
+
import { assetstore, algo, signals, material as materialNs } from '@evomap/evolver-core';
|
|
5
|
+
import { loadPriceTable } from '@evomap/evolver-adapter-public';
|
|
6
|
+
import { makeInjectEmitter } from './autoexec.js';
|
|
7
|
+
import { listApprovedGenes, provenanceStoreForStore, reviewLedgerForStore } from './reviewFilter.js';
|
|
8
|
+
import { ADAPTERS, parseJsonlLines } from '@evomap/evolver-runtime-adapters';
|
|
9
|
+
import { draftGeneCandidate } from './distillPrimitives.js';
|
|
10
|
+
import { emitSessionRecall } from './autoRecall.js';
|
|
11
|
+
import { isRuntimeSessionSourcePath, parseRuntimeSessionSources } from './runtimeSessionSource.js';
|
|
12
|
+
import { existsSync, readFileSync, readdirSync, statSync, unlinkSync } from 'node:fs';
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { join, resolve } from 'node:path';
|
|
15
|
+
import { importV1 } from './migrate/v1Import.js';
|
|
16
|
+
import { explicitRecipeHomes } from './recipe.js';
|
|
17
|
+
import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled } from './lifecycle.js';
|
|
18
|
+
/**
|
|
19
|
+
* Material consumer group for ingest: the cycle is the downstream that claims material → signals. Kept in
|
|
20
|
+
* one place so the recorded Material and any future cycle consumer agree on the group name.
|
|
21
|
+
*/
|
|
22
|
+
const INGEST_CONSUMER_GROUP = 'cycle';
|
|
23
|
+
function resolveIngestDeps(deps) {
|
|
24
|
+
return {
|
|
25
|
+
materialStore: deps.materialStore ?? new materialNs.MaterialStore({ path: events.materialStorePath() }),
|
|
26
|
+
watermarkStore: deps.watermarkStore ?? new materialNs.WatermarkStore(events.materialWatermarkPath()),
|
|
27
|
+
ingestor: deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() }),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Minimal `--flag value` parser (last wins); bare positionals are ignored. */
|
|
31
|
+
function parseFlags(argv) {
|
|
32
|
+
const out = {};
|
|
33
|
+
for (let i = 0; i < argv.length; i++) {
|
|
34
|
+
const a = argv[i];
|
|
35
|
+
if (a && a.startsWith('--')) {
|
|
36
|
+
const next = argv[i + 1];
|
|
37
|
+
if (next !== undefined && !next.startsWith('--')) {
|
|
38
|
+
out[a.slice(2)] = next;
|
|
39
|
+
i++;
|
|
40
|
+
}
|
|
41
|
+
else
|
|
42
|
+
out[a.slice(2)] = '';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
const splitList = (v, sep) => (v ?? '').split(sep).map((s) => s.trim()).filter(Boolean);
|
|
48
|
+
/**
|
|
49
|
+
* Operator identity for human-attributed AE events (the Ingestor requires actor.id when actor.kind=human).
|
|
50
|
+
* Resolved from the environment so the audit spine records WHO taught the system; falls back to a stable
|
|
51
|
+
* `cli` rather than throwing, so a manual command never fails purely for lack of an env var.
|
|
52
|
+
*/
|
|
53
|
+
function operatorActorId() {
|
|
54
|
+
return process.env['EVOLVER_ACTOR_ID'] ?? process.env['USER'] ?? process.env['LOGNAME'] ?? 'cli';
|
|
55
|
+
}
|
|
56
|
+
export const PACKAGE = '@evomap/evolver-cli';
|
|
57
|
+
const LOCAL_SECRET_STATE_KEYS = ['node_secret', 'node_secret_source', 'node_secret_version'];
|
|
58
|
+
const LOCAL_SECRET_ENV_VARS = [
|
|
59
|
+
'EVOMAP_NODE_SECRET',
|
|
60
|
+
'A2A_NODE_SECRET',
|
|
61
|
+
'EVOMAP_NODE_SECRET_VERSION',
|
|
62
|
+
'A2A_NODE_SECRET_VERSION',
|
|
63
|
+
];
|
|
64
|
+
function resolveLocalHome(env) {
|
|
65
|
+
return env['HOME'] && env['HOME'].length > 0 ? env['HOME'] : homedir();
|
|
66
|
+
}
|
|
67
|
+
function resolveEvomapHome(env, homeDir) {
|
|
68
|
+
const configured = env['EVOLVER_HOME'];
|
|
69
|
+
return configured && configured.length > 0 ? configured : join(homeDir, '.evomap');
|
|
70
|
+
}
|
|
71
|
+
function resolveProxyStorePath(env, evomapHome) {
|
|
72
|
+
const configured = env['EVOLVER_PROXY_STORE'];
|
|
73
|
+
return configured && configured.length > 0 ? configured : join(evomapHome, 'proxy', 'mailbox.db');
|
|
74
|
+
}
|
|
75
|
+
function uniquePaths(paths) {
|
|
76
|
+
const seen = new Set();
|
|
77
|
+
const out = [];
|
|
78
|
+
for (const path of paths) {
|
|
79
|
+
const key = resolve(path);
|
|
80
|
+
if (seen.has(key))
|
|
81
|
+
continue;
|
|
82
|
+
seen.add(key);
|
|
83
|
+
out.push(path);
|
|
84
|
+
}
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Every directory the recipe credential layer might write a legacy node_secret/node_secret_version file into.
|
|
89
|
+
* recipe.ts persists rotated legacy files to rotatePersistDir = recipeHomeCandidates(env)[0], which is the FIRST
|
|
90
|
+
* of EVOMAP_DIR / EVOLVER_HOME / EVOMAP_HOME when any is set — so a secret can land under EVOMAP_DIR or EVOMAP_HOME,
|
|
91
|
+
* not just EVOLVER_HOME / ~/.evomap. We union the explicit recipe homes (env-pure, shared with the writer to avoid
|
|
92
|
+
* drift) with the reset's own resolved evomapHome and the ~/.evomap fallback so the reset wipes wherever a secret
|
|
93
|
+
* could have been written; otherwise reset leaves a stale file the recipe path reads back on the next run (H3).
|
|
94
|
+
* The ~/.evomap fallback is always included even when an explicit home is set, because the recipe path also reads
|
|
95
|
+
* legacy files from it (recipeHomeCandidates' HOME/.evomap fallback) and the daemon's own ~/.evomap is canonical.
|
|
96
|
+
*/
|
|
97
|
+
function legacySecretHomes(env, evomapHome, homeDir) {
|
|
98
|
+
return uniquePaths([
|
|
99
|
+
...explicitRecipeHomes(env),
|
|
100
|
+
evomapHome,
|
|
101
|
+
join(homeDir, '.evomap'),
|
|
102
|
+
]);
|
|
103
|
+
}
|
|
104
|
+
function legacySecretFiles(env, evomapHome, homeDir) {
|
|
105
|
+
// Per-home order is secret-then-version; uniquePaths dedupes across homes that resolve to the same dir.
|
|
106
|
+
return uniquePaths(legacySecretHomes(env, evomapHome, homeDir).flatMap((home) => [
|
|
107
|
+
join(home, 'node_secret'),
|
|
108
|
+
join(home, 'node_secret_version'),
|
|
109
|
+
]));
|
|
110
|
+
}
|
|
111
|
+
export function resetLocalSecret(opts = {}) {
|
|
112
|
+
const env = opts.env ?? process.env;
|
|
113
|
+
const homeDir = opts.homeDir ?? resolveLocalHome(env);
|
|
114
|
+
const evomapHome = resolveEvomapHome(env, homeDir);
|
|
115
|
+
const storePath = opts.storePath ?? resolveProxyStorePath(env, evomapHome);
|
|
116
|
+
const clearedStateKeys = [];
|
|
117
|
+
const storeFound = existsSync(storePath);
|
|
118
|
+
if (storeFound) {
|
|
119
|
+
const store = new mailbox.MailboxStore({ path: storePath });
|
|
120
|
+
try {
|
|
121
|
+
for (const key of LOCAL_SECRET_STATE_KEYS) {
|
|
122
|
+
store.setState(key, '');
|
|
123
|
+
clearedStateKeys.push(key);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
store.close();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const removedLegacyFiles = [];
|
|
131
|
+
for (const file of legacySecretFiles(env, evomapHome, homeDir)) {
|
|
132
|
+
if (!existsSync(file))
|
|
133
|
+
continue;
|
|
134
|
+
unlinkSync(file);
|
|
135
|
+
removedLegacyFiles.push(file);
|
|
136
|
+
}
|
|
137
|
+
const envVarsSet = LOCAL_SECRET_ENV_VARS.filter((name) => {
|
|
138
|
+
const value = env[name];
|
|
139
|
+
return typeof value === 'string' && value.length > 0;
|
|
140
|
+
});
|
|
141
|
+
return {
|
|
142
|
+
storePath,
|
|
143
|
+
clearedStateKeys,
|
|
144
|
+
storeFound,
|
|
145
|
+
removedLegacyFiles,
|
|
146
|
+
envVarsSet,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
export function formatResetLocalSecretResult(result) {
|
|
150
|
+
const lines = [
|
|
151
|
+
`cleared local proxy secret state: ${result.storePath}`,
|
|
152
|
+
result.storeFound
|
|
153
|
+
? `cleared keys: ${result.clearedStateKeys.join(', ')}`
|
|
154
|
+
: 'cleared keys: none; mailbox store not found',
|
|
155
|
+
];
|
|
156
|
+
if (result.removedLegacyFiles.length > 0) {
|
|
157
|
+
lines.push(`removed legacy files: ${result.removedLegacyFiles.join(', ')}`);
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
lines.push('removed legacy files: none found');
|
|
161
|
+
}
|
|
162
|
+
if (result.envVarsSet.length > 0) {
|
|
163
|
+
lines.push(`env still set: ${result.envVarsSet.join(', ')}; unset or update these before restarting the proxy.`);
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
lines.push(`env reminder: unset or update ${LOCAL_SECRET_ENV_VARS.join(', ')} before restarting the proxy.`);
|
|
167
|
+
}
|
|
168
|
+
return `${lines.join('\n')}\n`;
|
|
169
|
+
}
|
|
170
|
+
export function runResetLocalSecret(argv, opts = {}) {
|
|
171
|
+
if (argv[0] === '--help' || argv[0] === '-h') {
|
|
172
|
+
process.stdout.write('用法: evolver reset-local-secret\n');
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
|
175
|
+
if (argv.length > 0) {
|
|
176
|
+
process.stderr.write('用法: evolver reset-local-secret\n');
|
|
177
|
+
return 1;
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
process.stdout.write(formatResetLocalSecretResult(resetLocalSecret(opts)));
|
|
181
|
+
return 0;
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
185
|
+
process.stderr.write(`reset-local-secret failed: ${msg}\n`);
|
|
186
|
+
return 1;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** rebuild-views: 删 MV → 从 root_events 全量重放重建 (军杰 §3.6). */
|
|
190
|
+
export function rebuildViews(opts = {}) {
|
|
191
|
+
const ing = new events.Ingestor({ path: opts.eventsPath ?? events.rootEventsPath() });
|
|
192
|
+
const replayer = new events.Replayer({ dir: opts.mvDir ?? events.mvDir(), projectors: events.DEFAULT_PROJECTORS });
|
|
193
|
+
replayer.clear();
|
|
194
|
+
replayer.rebuild(ing.readAll());
|
|
195
|
+
return { rebuilt: events.DEFAULT_PROJECTORS.map((p) => p.name) };
|
|
196
|
+
}
|
|
197
|
+
/** migrate import-v1 <v1dir> [outDir]: v1→v2 只读迁移(异步, 由 cli.ts 调). */
|
|
198
|
+
export async function runMigrate(argv) {
|
|
199
|
+
if (argv[0] !== 'import-v1' || !argv[1]) {
|
|
200
|
+
process.stderr.write('用法: evolver migrate import-v1 <v1dir> [outDir]\n');
|
|
201
|
+
return 1;
|
|
202
|
+
}
|
|
203
|
+
const outDir = argv[2] ?? process.cwd();
|
|
204
|
+
const store = new assetstore.LocalJsonlProvider(`${outDir}/assets`);
|
|
205
|
+
const rep = await importV1(argv[1], store, outDir);
|
|
206
|
+
process.stdout.write(`迁移完成: Gene=${rep.imported.Gene} Capsule=${rep.imported.Capsule} Event=${rep.imported.EvolutionEvent} (冻结${rep.frozen}/新算${rep.recomputed}/去重${rep.deduped}); sidecar=${rep.sidecarExtensions}; memory_graph 归档=${rep.memoryGraphArchived}\n`);
|
|
207
|
+
return 0;
|
|
208
|
+
}
|
|
209
|
+
/** One-line summary of an asset for `asset-log` (pure, testable). */
|
|
210
|
+
export function formatAssetLine(a) {
|
|
211
|
+
const id = String(a.asset_id).replace(/^sha256:/, '').slice(0, 12);
|
|
212
|
+
const o = a['outcome'];
|
|
213
|
+
const desc = a.type === 'Gene' ? `category=${String(a['category'] ?? '?')}`
|
|
214
|
+
: a.type === 'Capsule' ? `gene=${String(a['gene'] ?? '?')} ${String(a['summary'] ?? '')}`.trim()
|
|
215
|
+
: a.type === 'EvolutionEvent' ? `intent=${String(a['intent'] ?? '?')} outcome=${String(o?.status ?? '?')}`
|
|
216
|
+
: a.type === 'AntiGene' ? `trigger=${Array.isArray(a['trigger']) ? a['trigger'].map(String).join(',') : '?'} ${String(a['summary'] ?? '')}`.trim()
|
|
217
|
+
: '';
|
|
218
|
+
return `${a.type.padEnd(15)} ${id} ${desc}`.trimEnd();
|
|
219
|
+
}
|
|
220
|
+
/** asset-log [Gene|Capsule|EvolutionEvent|AntiGene] [limit]: list recent local assets (observability; ported v1 CLI verb). */
|
|
221
|
+
export async function runAssetLog(argv, store) {
|
|
222
|
+
const KINDS = ['Gene', 'Capsule', 'EvolutionEvent', 'AntiGene'];
|
|
223
|
+
let kind;
|
|
224
|
+
let limit = 20;
|
|
225
|
+
for (const a of argv) {
|
|
226
|
+
if (KINDS.includes(a))
|
|
227
|
+
kind = a;
|
|
228
|
+
else if (/^\d+$/.test(a))
|
|
229
|
+
limit = Number(a);
|
|
230
|
+
}
|
|
231
|
+
const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
|
|
232
|
+
const assets = await s.list(kind, limit);
|
|
233
|
+
if (assets.length === 0) {
|
|
234
|
+
process.stdout.write('(no assets)\n');
|
|
235
|
+
return 0;
|
|
236
|
+
}
|
|
237
|
+
for (const a of assets)
|
|
238
|
+
process.stdout.write(formatAssetLine(a) + '\n');
|
|
239
|
+
return 0;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* distill: gate a learned approach into the gene pool (ported v1 CLI verb). Runs the structural intake
|
|
243
|
+
* (schema + dedup + asset_id) and, only if it passes, writes the gene to the store. The agent/runtime is
|
|
244
|
+
* what discovers the strategy; this is the manual entry point that turns it into a pooled, selectable gene.
|
|
245
|
+
* Usage: evolver distill --category <c> --signals <s1,s2> --strategy "<step1; step2>" [--summary <text>] [--id <id>]
|
|
246
|
+
*/
|
|
247
|
+
export async function runDistill(argv, store, deps = {}) {
|
|
248
|
+
const f = parseFlags(argv);
|
|
249
|
+
const candidate = {
|
|
250
|
+
...(f['id'] ? { id: f['id'] } : {}),
|
|
251
|
+
category: f['category'] ?? 'innovate',
|
|
252
|
+
signals_match: splitList(f['signals'], /,/),
|
|
253
|
+
strategy: splitList(f['strategy'], /[;\n]/),
|
|
254
|
+
...(f['summary'] ? { summary: f['summary'] } : {}),
|
|
255
|
+
};
|
|
256
|
+
if (candidate.signals_match.length === 0 || candidate.strategy.length === 0) {
|
|
257
|
+
process.stderr.write('用法: evolver distill --category <c> --signals <s1,s2> --strategy "<step1; step2>" [--summary <t>]\n');
|
|
258
|
+
return 1;
|
|
259
|
+
}
|
|
260
|
+
const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
|
|
261
|
+
const existing = (await s.list('Gene', 1000)).map((g) => ({
|
|
262
|
+
id: typeof g['id'] === 'string' ? String(g['id']) : undefined,
|
|
263
|
+
signals_match: Array.isArray(g['signals_match']) ? g['signals_match'] : [],
|
|
264
|
+
}));
|
|
265
|
+
const r = algo.intakeGene(candidate, existing);
|
|
266
|
+
// Emit nothing on rejection: only a gene that actually lands in the pool is a real "teach".
|
|
267
|
+
if (!r.ok || !r.gene) {
|
|
268
|
+
process.stderr.write(`distill 拒绝: ${r.errors.join('; ')}\n`);
|
|
269
|
+
return 1;
|
|
270
|
+
}
|
|
271
|
+
await s.put(r.gene);
|
|
272
|
+
// AE (#91 item 1): a manual distill IS a human teaching the system a gene — record it on the audit spine.
|
|
273
|
+
const ingestor = deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() });
|
|
274
|
+
await ingestor.ingest({
|
|
275
|
+
type: 'actor.human.teach',
|
|
276
|
+
payload: { geneId: r.gene.id, assetId: r.gene.asset_id, category: r.gene.category },
|
|
277
|
+
human: { title: `teach gene ${r.gene.id}`, severity: 'info' },
|
|
278
|
+
actor: { kind: 'human', id: operatorActorId() },
|
|
279
|
+
});
|
|
280
|
+
process.stdout.write(`distilled gene ${r.gene.id} (${String(r.gene.asset_id).slice(0, 19)}…) → pool\n`);
|
|
281
|
+
return 0;
|
|
282
|
+
}
|
|
283
|
+
// LLM-proxy trace day-files (written by the proxy's JsonlTraceSink as `llm-trace-YYYYMMDD.jsonl`). The name
|
|
284
|
+
// pattern mirrors how runtime adapters detect() by path; a content sniff (event:'llm_turn') backstops renames.
|
|
285
|
+
const TRACE_FILE_RE = /(^|[/\\])llm-trace-[^/\\]*\.jsonl$/i;
|
|
286
|
+
/**
|
|
287
|
+
* Ingest LLM-proxy trace records: print the economic/reliability signals extractTraceSignals mines from the
|
|
288
|
+
* turn metadata, through the same preview shape the session path uses. `--distill` is EXCLUDED for trace
|
|
289
|
+
* sources: a gene needs a strategy, and strategies are drafted from the agent's own narration — trace records
|
|
290
|
+
* are metadata only (models/status/latency/usage, never text), so there is nothing real to draft steps from
|
|
291
|
+
* and fabricating them would break the "real excerpts, not fabricated" rule of the session distill path.
|
|
292
|
+
*/
|
|
293
|
+
/** Print ONE trace file's signals. Sigs are precomputed so the printed count is exactly the count recorded in
|
|
294
|
+
* that file's material.batch_ready event (extractTraceSignals is threshold-based, so it is computed per file). */
|
|
295
|
+
function printTraceSignals(file, turnCount, sigs) {
|
|
296
|
+
process.stdout.write(`ingest [llm-trace] ${file}: ${turnCount} llm_turn record(s) → ${sigs.length} signal(s)\n`);
|
|
297
|
+
for (const s of sigs) {
|
|
298
|
+
process.stdout.write(` [${s.strength}/${s.kind}] ${s.text.replace(/\s+/g, ' ').trim().slice(0, 160)}\n`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/** The runtime agents Material.sourceAgent can represent (closed enum on the schema). */
|
|
302
|
+
const MATERIAL_SOURCE_AGENTS = new Set(['claude-code', 'codex', 'cursor', 'gemini', 'kimi', 'kiro', 'opencode', 'generic-chat']);
|
|
303
|
+
/** Narrow an adapter's free-string agent to the Material source enum (undefined → not recordable). */
|
|
304
|
+
function toMaterialSourceAgent(agent) {
|
|
305
|
+
return MATERIAL_SOURCE_AGENTS.has(agent) ? agent : undefined;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Is a Material for this EXACT file state already on the substrate? A Material's identity is its ULID, so `put`
|
|
309
|
+
* cannot dedup across runs (each build mints a fresh id). Without this, a crash-retry — where a prior run put the
|
|
310
|
+
* material but threw before the watermark advanced — would append a SECOND row for the unchanged file.
|
|
311
|
+
*
|
|
312
|
+
* The match is on (sourcePath, size, contentHash), NOT path+hash alone: contentHash is a PREFIX hash (first few KB),
|
|
313
|
+
* so an append-grown trace day-file keeps the same prefix while `scanFile` correctly reports `changed: true`. Keying
|
|
314
|
+
* on size too means a grown file is NOT mistaken for "already recorded" — it still earns a new material for its new
|
|
315
|
+
* bytes — while a byte-identical retry of the same state is deduped (#100 bugbot).
|
|
316
|
+
*/
|
|
317
|
+
function materialExistsFor(store, sourcePath, wm) {
|
|
318
|
+
if (wm.contentHash === undefined)
|
|
319
|
+
return false;
|
|
320
|
+
for (const m of store.iterate()) {
|
|
321
|
+
if (m.sourcePath === sourcePath && m.watermark.size === wm.size && m.watermark.contentHash === wm.contentHash)
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
return false;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Record a session log as Material on the M1 substrate (idempotent by file watermark), then emit a
|
|
328
|
+
* `material.batch_ready` root_event so the AE is not bypassed. Re-ingesting the same UNCHANGED file records
|
|
329
|
+
* no new material and emits no event (scanFile reports `changed: false` against the persisted cursor).
|
|
330
|
+
* Returns whether new material landed + its materialId so the caller can report it.
|
|
331
|
+
*/
|
|
332
|
+
async function recordSessionMaterial(sourceAgent, absPath, signalCount, d, recordCount = 1) {
|
|
333
|
+
const prev = d.watermarkStore.get(absPath);
|
|
334
|
+
const scan = materialNs.scanFile(absPath, prev);
|
|
335
|
+
// Unchanged source already recorded once → idempotent skip (no duplicate material, no duplicate event).
|
|
336
|
+
if (prev && !scan.changed)
|
|
337
|
+
return { recorded: false };
|
|
338
|
+
const m = materialNs.buildMaterial({
|
|
339
|
+
sourceAgent,
|
|
340
|
+
sourceKind: 'runtime_session',
|
|
341
|
+
sourcePath: absPath,
|
|
342
|
+
kind: 'session_log',
|
|
343
|
+
watermark: scan.watermark,
|
|
344
|
+
consumerGroup: INGEST_CONSUMER_GROUP,
|
|
345
|
+
});
|
|
346
|
+
// Crash-retry idempotency (#100): if a prior run already put this file's material but threw before the
|
|
347
|
+
// watermark advanced, don't append a duplicate row — reuse it and only (re-)emit the lost event below.
|
|
348
|
+
const isNew = !materialExistsFor(d.materialStore, absPath, scan.watermark);
|
|
349
|
+
if (isNew)
|
|
350
|
+
await d.materialStore.put(m);
|
|
351
|
+
await d.ingestor.ingest({
|
|
352
|
+
type: 'material.batch_ready',
|
|
353
|
+
payload: { source: absPath, recordCount, signalCount },
|
|
354
|
+
human: { title: `material 已落地: ${sourceAgent} session`, severity: 'info' },
|
|
355
|
+
actor: { kind: 'machine' },
|
|
356
|
+
});
|
|
357
|
+
// Watermark LAST — only after BOTH the put and its batch_ready event succeed. If ingest throws, the watermark
|
|
358
|
+
// stays unset so a re-run re-emits the event; the content check above keeps that retry from duplicating the row.
|
|
359
|
+
d.watermarkStore.set(absPath, scan.watermark);
|
|
360
|
+
return { recorded: isNew, materialId: m.materialId };
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Record a proxy LLM-trace file as Material on the M1 substrate (#95). A trace is agent-agnostic gateway
|
|
364
|
+
* telemetry, so it carries sourceKind=proxy_trace + kind=llm_trace and NO sourceAgent — the origin taxonomy
|
|
365
|
+
* the closed runtime enum couldn't express. Idempotent by file watermark, same as the session path; both now
|
|
366
|
+
* land on the ONE substrate the cycle daemon will later claim from, instead of the trace path bypassing it.
|
|
367
|
+
*/
|
|
368
|
+
async function recordTraceMaterial(absPath, signalCount, d) {
|
|
369
|
+
const prev = d.watermarkStore.get(absPath);
|
|
370
|
+
const scan = materialNs.scanFile(absPath, prev);
|
|
371
|
+
if (prev && !scan.changed)
|
|
372
|
+
return { recorded: false };
|
|
373
|
+
const m = materialNs.buildMaterial({
|
|
374
|
+
sourceKind: 'proxy_trace', // agent-agnostic — no sourceAgent (#95)
|
|
375
|
+
sourcePath: absPath,
|
|
376
|
+
kind: 'llm_trace',
|
|
377
|
+
watermark: scan.watermark,
|
|
378
|
+
consumerGroup: INGEST_CONSUMER_GROUP,
|
|
379
|
+
});
|
|
380
|
+
// Crash-retry idempotency (#100): reuse an already-recorded material for this unchanged file (see session path).
|
|
381
|
+
const isNew = !materialExistsFor(d.materialStore, absPath, scan.watermark);
|
|
382
|
+
if (isNew)
|
|
383
|
+
await d.materialStore.put(m);
|
|
384
|
+
await d.ingestor.ingest({
|
|
385
|
+
// Same payload shape as the session path: one material per file (recordCount: 1) + signalCount, plus
|
|
386
|
+
// sourceKind so a shared handler can tell a proxy trace from a runtime session (#100 bugbot).
|
|
387
|
+
type: 'material.batch_ready',
|
|
388
|
+
payload: { source: absPath, recordCount: 1, signalCount, sourceKind: 'proxy_trace' },
|
|
389
|
+
human: { title: 'material 已落地: proxy llm-trace', severity: 'info' },
|
|
390
|
+
actor: { kind: 'machine' },
|
|
391
|
+
});
|
|
392
|
+
// Watermark LAST — see recordSessionMaterial: a throw during ingest must leave the file re-ingestable (#100).
|
|
393
|
+
d.watermarkStore.set(absPath, scan.watermark);
|
|
394
|
+
return { recorded: isNew, materialId: m.materialId };
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Recursively enumerate recognized runtime-session sources under the given dirs — the daemon's auto-distill
|
|
398
|
+
* producer source (#106). This includes text session files handled by runtime adapters (`*.jsonl` and Gemini
|
|
399
|
+
* `*.json`) plus Cursor's sqlite `state.vscdb`. A missing/permission-denied dir is silently skipped (a daemon
|
|
400
|
+
* must not crash on an absent home dir).
|
|
401
|
+
*/
|
|
402
|
+
export function scanSessionDirs(dirs) {
|
|
403
|
+
const out = [];
|
|
404
|
+
for (const dir of dirs) {
|
|
405
|
+
let entries;
|
|
406
|
+
try {
|
|
407
|
+
entries = readdirSync(resolve(dir), { recursive: true });
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
continue;
|
|
411
|
+
} // dir absent / unreadable → skip
|
|
412
|
+
for (const e of entries) {
|
|
413
|
+
const file = join(resolve(dir), e);
|
|
414
|
+
if (isRuntimeSessionSourcePath(file))
|
|
415
|
+
out.push(file);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return out;
|
|
419
|
+
}
|
|
420
|
+
function sortedStrings(values) {
|
|
421
|
+
return [...new Set([...values].map(String).filter(Boolean))].sort();
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* One producer tick for the auto-distill loop (#106 slice 1): scan `dirs` for session logs and record any
|
|
425
|
+
* NEW/CHANGED file as `runtime_session` Material via the injected (bus) Ingestor — which emits
|
|
426
|
+
* `material.batch_ready`, the event the distillObserver claims off. Idempotent per file (watermark cursor), so
|
|
427
|
+
* re-scanning an unchanged tree records nothing. Pure producer: it does NOT distill (the observer does). Returns
|
|
428
|
+
* how many files landed new material. Inject `deps.ingestor = new Ingestor({ sink: bus })` so the event reaches
|
|
429
|
+
* the daemon's ObserverBus; defaults to live paths otherwise.
|
|
430
|
+
*/
|
|
431
|
+
export async function runSessionIngestTick(dirs, deps = {}) {
|
|
432
|
+
const d = resolveIngestDeps(deps);
|
|
433
|
+
let recorded = 0;
|
|
434
|
+
const sourceAgents = new Set();
|
|
435
|
+
const signalKinds = new Set();
|
|
436
|
+
const signalStrengths = new Set();
|
|
437
|
+
// #274 auto-recall (default OFF): observe which injected genes were actually used, from the transcript, so the
|
|
438
|
+
// experience loop is fed by observation instead of a self-reported tool call agents skip. Best-effort + idempotent
|
|
439
|
+
// (one value.recall set per session); off → zero extra work. auto-OBSERVE only — it never quarantines.
|
|
440
|
+
const autoRecallOn = process.env['EVOLVER_AUTO_RECALL'] === '1';
|
|
441
|
+
for (const file of scanSessionDirs(dirs)) {
|
|
442
|
+
try {
|
|
443
|
+
const parsedSources = parseRuntimeSessionSources(file);
|
|
444
|
+
const agent = parsedSources[0] ? toMaterialSourceAgent(parsedSources[0].agent) : undefined;
|
|
445
|
+
if (parsedSources.length === 0 || !agent)
|
|
446
|
+
continue; // not a recognized, schema-recordable runtime-session source
|
|
447
|
+
const sigsBySource = parsedSources.map((source) => signals.extractSignals(source.turns));
|
|
448
|
+
const r = await recordSessionMaterial(agent, file, sigsBySource.reduce((sum, sigs) => sum + sigs.length, 0), d, parsedSources.length);
|
|
449
|
+
if (r.recorded) {
|
|
450
|
+
recorded += 1;
|
|
451
|
+
sourceAgents.add(agent);
|
|
452
|
+
for (const sigs of sigsBySource) {
|
|
453
|
+
for (const sig of sigs) {
|
|
454
|
+
signalKinds.add(sig.kind);
|
|
455
|
+
signalStrengths.add(sig.strength);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (autoRecallOn && parsedSources.length === 1 && !parsedSources[0].sessionId) {
|
|
460
|
+
// Drop meta turns (heartbeats/empty) before judging, same as `evolver recall` — counting them would skew overlap.
|
|
461
|
+
const turns = parsedSources[0].turns.filter((t) => !t.isMeta).map((t) => ({ role: t.role, text: t.text }));
|
|
462
|
+
await emitSessionRecall(file, turns, { ingestor: d.ingestor });
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
catch { /* unreadable / unparseable file → skip, never break the scan */ }
|
|
466
|
+
}
|
|
467
|
+
return {
|
|
468
|
+
recorded,
|
|
469
|
+
sourceAgents: sortedStrings(sourceAgents),
|
|
470
|
+
signalKinds: sortedStrings(signalKinds),
|
|
471
|
+
signalStrengths: sortedStrings(signalStrengths),
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Read + parse one or more trace JSONL files, record each as proxy_trace Material on the M1 substrate (#95,
|
|
476
|
+
* idempotent by file watermark), and report their signals as a single batch.
|
|
477
|
+
*/
|
|
478
|
+
async function ingestTraceFiles(files, distill, deps) {
|
|
479
|
+
const d = resolveIngestDeps(deps);
|
|
480
|
+
// Phase 1 — read + parse EVERY file before any substrate write. A later read failure must not leave earlier
|
|
481
|
+
// files already recorded as Material while the command exits 1 (partial side effect on a reported failure, #100).
|
|
482
|
+
const perFile = [];
|
|
483
|
+
for (const f of files) {
|
|
484
|
+
try {
|
|
485
|
+
perFile.push({ file: f, records: parseJsonlLines(readFileSync(f, 'utf8')) });
|
|
486
|
+
}
|
|
487
|
+
catch (e) {
|
|
488
|
+
process.stderr.write(`ingest: cannot read ${f}: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
489
|
+
return 1; // no Material recorded yet — fail clean
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
// Phase 2 — each trace FILE is its own Material AND its own signal set. extractTraceSignals is threshold-based
|
|
493
|
+
// ACROSS a file's turns (e.g. ≥2 upstream 5xx, a slow-turn SHARE), so per-file is the honest unit: the cycle
|
|
494
|
+
// later consumes one material = one file, and that file's event signalCount must equal what is extracted from
|
|
495
|
+
// it alone. Merging files for one count would over/under-fire thresholds vs any single material (#100). One
|
|
496
|
+
// file per material also keeps reporting and the event count in lockstep.
|
|
497
|
+
let recorded = 0;
|
|
498
|
+
for (const { file, records } of perFile) {
|
|
499
|
+
const turns = records.filter((x) => x['event'] === 'llm_turn');
|
|
500
|
+
const sigs = signals.extractTraceSignals(turns);
|
|
501
|
+
const r = await recordTraceMaterial(file, sigs.length, d);
|
|
502
|
+
if (r.recorded)
|
|
503
|
+
recorded++;
|
|
504
|
+
printTraceSignals(file, turns.length, sigs);
|
|
505
|
+
}
|
|
506
|
+
process.stdout.write(distill
|
|
507
|
+
? '\ningest: trace records are turn METADATA with no narration to draft a strategy from — --distill is ignored for trace sources. Nothing stored.\n'
|
|
508
|
+
: '\n(trace preview — economic/reliability signals only; trace sources are excluded from --distill)\n');
|
|
509
|
+
if (recorded)
|
|
510
|
+
process.stdout.write(` → recorded ${recorded} trace file(s) as proxy_trace material (material.batch_ready)\n`);
|
|
511
|
+
return 0;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* ingest: read a REAL agent session log, parse it with the matching runtime adapter, and extract signals
|
|
515
|
+
* (tool errors / explicit failures / difficulty wording) from it — the capture→signals half of the experience
|
|
516
|
+
* loop. The adapter↔core composition lives HERE in the CLI on purpose: evolver-core must stay hub/adapter-
|
|
517
|
+
* agnostic (it never imports runtime-adapters; it consumes turns via the structural SignalSourceTurn shape;
|
|
518
|
+
* trace records reach it as plain parsed objects via the structural LlmTraceRecord shape).
|
|
519
|
+
*
|
|
520
|
+
* Sources:
|
|
521
|
+
* - agent session logs, detected by the runtime adapters' detect();
|
|
522
|
+
* - Cursor `state.vscdb`, read through the dedicated sqlite extractor instead of as text;
|
|
523
|
+
* - LLM-proxy trace JSONL (`llm-trace-*.jsonl` file, or a directory of day files), detected by name or by
|
|
524
|
+
* a content sniff for `event:'llm_turn'` records — closing the loop the proxy's trace-capture seam opened.
|
|
525
|
+
*
|
|
526
|
+
* Material substrate (M1, #91 item 2): a session log IS raw material — the first content the evolution loop
|
|
527
|
+
* ingests. Before signal extraction, `ingest` now records the session as a Material via MaterialStore and
|
|
528
|
+
* emits a `material.batch_ready` root_event so the append-only log (AE) is no longer bypassed. The file
|
|
529
|
+
* watermark cursor makes re-ingesting the SAME unchanged source idempotent (no duplicate material, no
|
|
530
|
+
* duplicate event) — this seats ingest on the substrate that previously had zero consumers, so when the
|
|
531
|
+
* daemon wires M1 up later there is ONE pipeline, not two. Trace sources land on the SAME substrate now
|
|
532
|
+
* (#95): a proxy llm-trace is agent-agnostic, so it records as sourceKind=proxy_trace / kind=llm_trace with
|
|
533
|
+
* no sourceAgent — the origin taxonomy the closed runtime enum previously couldn't express.
|
|
534
|
+
*
|
|
535
|
+
* Default / --dry-run: inspection only (print the signals; material is still recorded so the substrate sees it).
|
|
536
|
+
* --distill: assemble a gene candidate from the session — signals_match from the strong signals, strategy from
|
|
537
|
+
* the agent's OWN substantive turns (real excerpts, not fabricated) — and intake it as an UNPROVEN draft.
|
|
538
|
+
* It is gated by `review` and pruned by the cycle's objective scoring, so a noisy auto-draft can't be trusted.
|
|
539
|
+
* Trace sources are excluded (metadata has no narration to distill — see reportTraceSignals).
|
|
540
|
+
* Usage: evolver ingest <session-log | trace-file | trace-dir> [--dry-run | --distill]
|
|
541
|
+
*/
|
|
542
|
+
// `deps` (the M1 material substrate, #94) and `review` (the quarantine sidecar, #89) are independent injection
|
|
543
|
+
// seams that both default to the live ~/.evomap home; tests inject either in isolation. `deps` stays 3rd to match
|
|
544
|
+
// the rest of the ingest call sites; `review` is 4th.
|
|
545
|
+
export async function runIngest(argv, store, deps = {}, review) {
|
|
546
|
+
const distill = argv.includes('--distill');
|
|
547
|
+
const path = argv.find((a) => !a.startsWith('--'));
|
|
548
|
+
if (!path) {
|
|
549
|
+
process.stderr.write('用法: evolver ingest <session-log | trace-file | trace-dir> [--dry-run | --distill]\n');
|
|
550
|
+
return 1;
|
|
551
|
+
}
|
|
552
|
+
// Trace source, by name: a llm-trace-*.jsonl file, or a directory scanned for the proxy's day files.
|
|
553
|
+
let isDir = false;
|
|
554
|
+
try {
|
|
555
|
+
isDir = statSync(resolve(path)).isDirectory();
|
|
556
|
+
}
|
|
557
|
+
catch { /* missing path → handled by the reads below */ }
|
|
558
|
+
if (isDir) {
|
|
559
|
+
const files = readdirSync(resolve(path)).filter((f) => TRACE_FILE_RE.test(f)).sort().map((f) => join(resolve(path), f));
|
|
560
|
+
if (files.length === 0) {
|
|
561
|
+
process.stderr.write(`ingest: no llm-trace-*.jsonl files in directory: ${path}\n`);
|
|
562
|
+
return 1;
|
|
563
|
+
}
|
|
564
|
+
return ingestTraceFiles(files, distill, deps);
|
|
565
|
+
}
|
|
566
|
+
if (TRACE_FILE_RE.test(path))
|
|
567
|
+
return ingestTraceFiles([resolve(path)], distill, deps);
|
|
568
|
+
let parsedSources;
|
|
569
|
+
try {
|
|
570
|
+
parsedSources = parseRuntimeSessionSources(path);
|
|
571
|
+
}
|
|
572
|
+
catch (e) {
|
|
573
|
+
process.stderr.write(`ingest: cannot read ${path}: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
574
|
+
return 1;
|
|
575
|
+
}
|
|
576
|
+
if (parsedSources.length === 0) {
|
|
577
|
+
// Content sniff: a renamed/copied trace file still carries event:'llm_turn' records.
|
|
578
|
+
try {
|
|
579
|
+
if (parseJsonlLines(readFileSync(resolve(path), 'utf8')).some((r) => r['event'] === 'llm_turn')) {
|
|
580
|
+
return ingestTraceFiles([resolve(path)], distill, deps); // record as proxy_trace material too (#95)
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
catch { /* unreadable → fall through to the unrecognized error */ }
|
|
584
|
+
process.stderr.write(`ingest: unrecognized session-log format: ${path} (supported: ${ADAPTERS.map((a) => a.agent).join(', ')}, llm-trace)\n`);
|
|
585
|
+
return 1;
|
|
586
|
+
}
|
|
587
|
+
const sourceSignalPairs = parsedSources.map((source) => ({ source, sigs: signals.extractSignals(source.turns) }));
|
|
588
|
+
for (const { source, sigs } of sourceSignalPairs) {
|
|
589
|
+
process.stdout.write(`ingest [${source.label}] ${path}: ${source.turns.length} turn(s) → ${sigs.length} signal(s)\n`);
|
|
590
|
+
for (const s of sigs) {
|
|
591
|
+
const tool = s.toolName ? ` ${s.toolName}` : '';
|
|
592
|
+
const text = s.text.replace(/\s+/g, ' ').trim().slice(0, 120);
|
|
593
|
+
process.stdout.write(` [${s.strength}/${s.kind}]${tool} ${text}\n`);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
// Re-seat on the M1 material substrate (#91 item 2): record the session as Material (idempotent by file
|
|
597
|
+
// watermark) and emit a material.batch_ready root_event. Signal extraction now consumes from a path that
|
|
598
|
+
// has first landed the material — the same one pipeline the cycle daemon will later claim from.
|
|
599
|
+
const sourceAgent = toMaterialSourceAgent(parsedSources[0].agent);
|
|
600
|
+
if (sourceAgent) {
|
|
601
|
+
const d = resolveIngestDeps(deps);
|
|
602
|
+
const signalCount = sourceSignalPairs.reduce((sum, pair) => sum + pair.sigs.length, 0);
|
|
603
|
+
const r = await recordSessionMaterial(sourceAgent, resolve(path), signalCount, d, parsedSources.length);
|
|
604
|
+
if (r.recorded)
|
|
605
|
+
process.stdout.write(` → recorded as material ${r.materialId} (material.batch_ready)\n`);
|
|
606
|
+
else
|
|
607
|
+
process.stdout.write(' → source unchanged since last ingest — no new material recorded\n');
|
|
608
|
+
}
|
|
609
|
+
if (!distill) {
|
|
610
|
+
process.stdout.write('\n(preview only — pass --distill to draft an UNPROVEN gene candidate for review)\n');
|
|
611
|
+
return 0;
|
|
612
|
+
}
|
|
613
|
+
// --distill: assemble + intake UNPROVEN draft genes per runtime session (shared draft logic — see distillPrimitives).
|
|
614
|
+
const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
|
|
615
|
+
const accepted = [];
|
|
616
|
+
let existing = (await s.list('Gene', 1000)).map((g) => ({
|
|
617
|
+
id: typeof g['id'] === 'string' ? String(g['id']) : undefined,
|
|
618
|
+
signals_match: Array.isArray(g['signals_match']) ? g['signals_match'] : [],
|
|
619
|
+
}));
|
|
620
|
+
for (const { source, sigs } of sourceSignalPairs) {
|
|
621
|
+
const candidate = draftGeneCandidate(source.turns, sigs, source.agent);
|
|
622
|
+
if (!candidate)
|
|
623
|
+
continue;
|
|
624
|
+
const r = algo.intakeGene(candidate, existing);
|
|
625
|
+
if (!r.ok || !r.gene) {
|
|
626
|
+
process.stderr.write(`\ningest --distill rejected: ${r.errors.join('; ')}\n`);
|
|
627
|
+
return 1;
|
|
628
|
+
}
|
|
629
|
+
accepted.push({ source, candidate, gene: r.gene });
|
|
630
|
+
existing = [...existing, { id: r.gene.id, signals_match: r.gene.signals_match }];
|
|
631
|
+
}
|
|
632
|
+
if (accepted.length === 0) {
|
|
633
|
+
process.stdout.write('\ningest: not enough to distill — need ≥1 strong signal and ≥1 substantive assistant step. Nothing stored.\n');
|
|
634
|
+
return 0;
|
|
635
|
+
}
|
|
636
|
+
const reviewDir = s instanceof assetstore.LocalJsonlProvider ? s.baseDir : events.assetsDir();
|
|
637
|
+
const rev = review ?? new assetstore.ReviewLedger(reviewDir);
|
|
638
|
+
const { ingestor } = resolveIngestDeps(deps);
|
|
639
|
+
for (const { source, candidate, gene } of accepted) {
|
|
640
|
+
// Quarantine the draft: its auto-extracted strategy must not be embedded into a real autonomous run until a
|
|
641
|
+
// human approves it (`evolver review --approve <id>`). The gate lives in makeTrustedGeneResolver (#45+review).
|
|
642
|
+
// Co-locate the sidecar with the RESOLVED store so an injected store quarantines in its own dir (not the real
|
|
643
|
+
// ~/.evomap), keeping gate and gene together.
|
|
644
|
+
const assetId = String(gene.asset_id);
|
|
645
|
+
// Sticky human decision: re-distilling the same session yields the same asset_id; a fresh quarantine must not
|
|
646
|
+
// last-write-win over a human approve/reject. quarantineIfAbsent does the read-and-append as ONE reload-aware
|
|
647
|
+
// op (no caller-side check→act gap that a concurrent `review --approve` could slip through), and the ledger's
|
|
648
|
+
// precedence resolution makes a human decision beat a quarantine regardless of append order — so even a racing
|
|
649
|
+
// quarantine line cannot withhold an already-approved gene. Quarantine BEFORE persisting (asset_id is known from
|
|
650
|
+
// intake): a crash between the two writes leaves at worst a harmless orphan record, never an ungated gene.
|
|
651
|
+
rev.quarantineIfAbsent(assetId);
|
|
652
|
+
await s.put(gene);
|
|
653
|
+
// AE (#91 item 1): auto-distill mints a quarantined draft — record it on the audit spine.
|
|
654
|
+
await ingestor.ingest({
|
|
655
|
+
type: 'gene.distilled',
|
|
656
|
+
payload: { geneId: gene.id, assetId: gene.asset_id, category: gene.category, source: 'ingest', ...(source.sessionId ? { sessionId: source.sessionId } : {}) },
|
|
657
|
+
human: { title: `distilled gene ${gene.id}`, severity: 'info' },
|
|
658
|
+
actor: { kind: 'machine', id: 'ingest' },
|
|
659
|
+
});
|
|
660
|
+
const state = rev.get(assetId)?.state ?? 'quarantined';
|
|
661
|
+
process.stdout.write(`\n✎ drafted UNPROVEN gene ${gene.id} (${assetId.slice(0, 19)}…) — ${state}\n`);
|
|
662
|
+
process.stdout.write(` signals_match: ${candidate.signals_match.join(', ')}\n`);
|
|
663
|
+
process.stdout.write(` strategy: ${candidate.strategy.length} step(s) drafted from the session's own turns\n`);
|
|
664
|
+
if (state === 'quarantined')
|
|
665
|
+
process.stdout.write(' → approve with `evolver review --approve <id>` before it can influence a run; the cycle prunes it if it does not help.\n');
|
|
666
|
+
else
|
|
667
|
+
process.stdout.write(` → already reviewed (${state}); the prior human decision stands.\n`);
|
|
668
|
+
}
|
|
669
|
+
return 0;
|
|
670
|
+
}
|
|
671
|
+
/** Health label for a gene from its learning view (curation hint, not a hard gate). */
|
|
672
|
+
export function reviewStatus(v) {
|
|
673
|
+
if (v.total < 3)
|
|
674
|
+
return 'unproven';
|
|
675
|
+
if (v.successRate >= 0.6)
|
|
676
|
+
return 'healthy';
|
|
677
|
+
if (v.successRate < 0.4)
|
|
678
|
+
return 'weak';
|
|
679
|
+
return 'mixed';
|
|
680
|
+
}
|
|
681
|
+
/** Auto-promote eligibility of a quarantined (probation) gene, shown beside the health label so "[healthy] but
|
|
682
|
+
* never promotes" is not confusing (#306). Uses the SAME predicate as auto-promote (probationWouldPromote), so a
|
|
683
|
+
* single failure reads as blocked here exactly as it blocks promotion. */
|
|
684
|
+
export function promoteHint(v) {
|
|
685
|
+
if (algo.probationWouldPromote(v))
|
|
686
|
+
return 'ready';
|
|
687
|
+
if (v.failed > 0)
|
|
688
|
+
return `blocked(${v.failed} fail)`;
|
|
689
|
+
return `needs ${Math.max(1, algo.DEFAULT_PROMOTE_MIN_SUCCESS - v.success)} more`;
|
|
690
|
+
}
|
|
691
|
+
function stringArrayField(value) {
|
|
692
|
+
return Array.isArray(value) ? value.map(String).map((item) => item.trim()).filter(Boolean) : [];
|
|
693
|
+
}
|
|
694
|
+
function optionalStringField(value) {
|
|
695
|
+
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
|
|
696
|
+
}
|
|
697
|
+
function countField(value) {
|
|
698
|
+
return Array.isArray(value) ? String(value.length) : '0';
|
|
699
|
+
}
|
|
700
|
+
function numberField(value) {
|
|
701
|
+
return typeof value === 'number' && Number.isFinite(value) ? String(value) : '-';
|
|
702
|
+
}
|
|
703
|
+
function antiGeneReviewLine(asset, rev) {
|
|
704
|
+
const assetId = String(asset.asset_id);
|
|
705
|
+
const id = optionalStringField(asset['id']) ?? assetId;
|
|
706
|
+
const state = rev.get(assetId)?.state ?? 'approved';
|
|
707
|
+
const severity = optionalStringField(asset['severity']) ?? '-';
|
|
708
|
+
const trigger = stringArrayField(asset['trigger']).slice(0, 6).join(',') || '-';
|
|
709
|
+
const avoid = stringArrayField(asset['avoid']).slice(0, 2).join(' | ') || '-';
|
|
710
|
+
const evidence = `failures=${numberField(asset['failure_count'])} clusters=${countField(asset['source_clusters'])} evidence=${countField(asset['evidence_capsules'])}`;
|
|
711
|
+
const next = state === 'quarantined'
|
|
712
|
+
? `next: evolver review --approve ${id} <reason> | evolver review --reject ${id} <reason>`
|
|
713
|
+
: state === 'approved'
|
|
714
|
+
? 'next: approved guardrail can be injected when signals match'
|
|
715
|
+
: state === 'rejected'
|
|
716
|
+
? 'next: rejected guardrail is withheld from warning injection'
|
|
717
|
+
: 'next: approved by default';
|
|
718
|
+
return `${id.padEnd(28)} {${state}} severity=${severity} trigger=${trigger} avoid=${avoid} ${evidence} ${next}`;
|
|
719
|
+
}
|
|
720
|
+
async function listReviewVisibleAntiGenes(store, rev) {
|
|
721
|
+
const byAssetId = new Map();
|
|
722
|
+
for (const asset of await store.list('AntiGene', 10_000))
|
|
723
|
+
byAssetId.set(String(asset.asset_id), asset);
|
|
724
|
+
for (const record of rev.records()) {
|
|
725
|
+
if (byAssetId.has(record.assetId))
|
|
726
|
+
continue;
|
|
727
|
+
const asset = await store.get(record.assetId);
|
|
728
|
+
if (asset?.type === 'AntiGene')
|
|
729
|
+
byAssetId.set(record.assetId, asset);
|
|
730
|
+
}
|
|
731
|
+
return [...byAssetId.values()];
|
|
732
|
+
}
|
|
733
|
+
async function findReviewVisibleAntiGene(store, rev, target) {
|
|
734
|
+
if (target.startsWith('sha256:')) {
|
|
735
|
+
const direct = await store.get(target);
|
|
736
|
+
if (direct?.type === 'AntiGene')
|
|
737
|
+
return direct;
|
|
738
|
+
}
|
|
739
|
+
const antiGenes = await listReviewVisibleAntiGenes(store, rev);
|
|
740
|
+
return antiGenes.find((x) => String(x['id']) === target || String(x.asset_id) === target) ?? null;
|
|
741
|
+
}
|
|
742
|
+
async function runAntiGeneReview(store, rev) {
|
|
743
|
+
const antiGenes = await listReviewVisibleAntiGenes(store, rev);
|
|
744
|
+
if (antiGenes.length === 0) {
|
|
745
|
+
process.stdout.write('(no anti-genes)\n');
|
|
746
|
+
return 0;
|
|
747
|
+
}
|
|
748
|
+
const counts = { approved: 0, quarantined: 0, rejected: 0 };
|
|
749
|
+
for (const asset of antiGenes) {
|
|
750
|
+
const state = rev.get(String(asset.asset_id))?.state ?? 'approved';
|
|
751
|
+
counts[state] += 1;
|
|
752
|
+
}
|
|
753
|
+
process.stdout.write(`anti-gene review queue: ${antiGenes.length} AntiGene asset(s); approved=${counts.approved} quarantined=${counts.quarantined} rejected=${counts.rejected}\n`);
|
|
754
|
+
for (const asset of antiGenes)
|
|
755
|
+
process.stdout.write(`${antiGeneReviewLine(asset, rev)}\n`);
|
|
756
|
+
return 0;
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* review: curate the gene pool. Default is a read-only listing (derived learning view + the review-state of each
|
|
760
|
+
* gene); `--approve`/`--reject <id>` is the audited human act that lifts an auto-distilled draft out of (or
|
|
761
|
+
* confirms it out of) quarantine. Approval is what lets a distilled gene's strategy be embedded into a real run
|
|
762
|
+
* (the gate lives in makeTrustedGeneResolver, #45+review). The id may be a logical id or an asset_id.
|
|
763
|
+
* Usage: evolver review [limit] | evolver review --approve <id> [reason…] | evolver review --reject <id> [reason…]
|
|
764
|
+
*/
|
|
765
|
+
export async function runReview(argv, store, review, deps = {}) {
|
|
766
|
+
const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
|
|
767
|
+
// Co-locate the review sidecar with the resolved store (an injected store reads/writes its OWN review.jsonl).
|
|
768
|
+
const reviewDir = s instanceof assetstore.LocalJsonlProvider ? s.baseDir : events.assetsDir();
|
|
769
|
+
const rev = review ?? new assetstore.ReviewLedger(reviewDir);
|
|
770
|
+
// Audited approve/reject: resolve the gene (by logical id or asset_id) to its asset_id and record the act.
|
|
771
|
+
const verb = argv.includes('--approve') ? 'approve' : argv.includes('--reject') ? 'reject' : null;
|
|
772
|
+
if (verb) {
|
|
773
|
+
const flagIdx = argv.indexOf(verb === 'approve' ? '--approve' : '--reject');
|
|
774
|
+
const target = argv[flagIdx + 1];
|
|
775
|
+
if (!target || target.startsWith('--')) {
|
|
776
|
+
process.stderr.write(`用法: evolver review --${verb} <id> [reason…]\n`);
|
|
777
|
+
return 1;
|
|
778
|
+
}
|
|
779
|
+
// An asset_id resolves directly via store.get, so a reviewable asset past the bounded list() window is still
|
|
780
|
+
// reachable; a logical id falls back to a scan. AntiGene shares this ledger before warning injection.
|
|
781
|
+
let g = target.startsWith('sha256:') ? await s.get(target) : null;
|
|
782
|
+
if (g && g.type !== 'Gene' && g.type !== 'AntiGene')
|
|
783
|
+
g = null;
|
|
784
|
+
if (!g) {
|
|
785
|
+
const genes = await s.list('Gene', 1000);
|
|
786
|
+
g = genes.find((x) => String(x['id']) === target || String(x.asset_id) === target) ?? null;
|
|
787
|
+
}
|
|
788
|
+
if (!g)
|
|
789
|
+
g = await findReviewVisibleAntiGene(s, rev, target);
|
|
790
|
+
if (!g) {
|
|
791
|
+
process.stderr.write(`review --${verb}: no reviewable asset matches ${target}\n`);
|
|
792
|
+
return 1;
|
|
793
|
+
}
|
|
794
|
+
const assetId = String(g.asset_id);
|
|
795
|
+
const geneId = typeof g['id'] === 'string' ? String(g['id']) : assetId;
|
|
796
|
+
const assetType = g.type;
|
|
797
|
+
const by = operatorActorId();
|
|
798
|
+
const reason = argv.slice(flagIdx + 2).filter((a) => !a.startsWith('--')).join(' ') || `${verb}d via CLI`;
|
|
799
|
+
if (verb === 'approve')
|
|
800
|
+
rev.approve(assetId, by, reason);
|
|
801
|
+
else
|
|
802
|
+
rev.reject(assetId, by, reason);
|
|
803
|
+
const { ingestor } = resolveIngestDeps(deps);
|
|
804
|
+
await ingestor.ingest({
|
|
805
|
+
type: verb === 'approve' ? 'actor.human.review.approve' : 'actor.human.review.reject',
|
|
806
|
+
payload: { geneId, assetId, assetType, reason },
|
|
807
|
+
human: { title: `${verb} ${assetType} ${geneId}`, severity: 'info' },
|
|
808
|
+
actor: { kind: 'human', id: by },
|
|
809
|
+
});
|
|
810
|
+
process.stdout.write(`${verb === 'approve' ? 'approved' : 'rejected'} ${assetType} ${geneId} (${assetId.slice(0, 19)}...) by ${by}: ${reason}\n`);
|
|
811
|
+
return 0;
|
|
812
|
+
}
|
|
813
|
+
if (argv.includes('--anti-gene'))
|
|
814
|
+
return runAntiGeneReview(s, rev);
|
|
815
|
+
const limit = argv.find((a) => /^\d+$/.test(a)) ? Number(argv.find((a) => /^\d+$/.test(a))) : 50;
|
|
816
|
+
// Auto-drafted visibility (#117-A tail): flag which quarantined genes the distillObserver auto-drafted
|
|
817
|
+
// (gene.distilled with source=distill-observer) vs cycle/manual, and count those awaiting human review — the
|
|
818
|
+
// signal #113's digest surfaces ("N auto-drafted genes waiting for you"). Counted over ALL such events, so the
|
|
819
|
+
// total is accurate regardless of the display limit.
|
|
820
|
+
const { ingestor } = resolveIngestDeps(deps);
|
|
821
|
+
const autoDrafted = new Set(ingestor.readAll()
|
|
822
|
+
.filter((e) => e.type === 'gene.distilled' && e.payload?.['source'] === 'distill-observer')
|
|
823
|
+
.map((e) => String(e.payload?.['assetId'] ?? ''))
|
|
824
|
+
.filter(Boolean));
|
|
825
|
+
const autoPending = [...autoDrafted].filter((a) => rev.get(a)?.state === 'quarantined').length;
|
|
826
|
+
const genes = await s.list('Gene', limit);
|
|
827
|
+
if (genes.length === 0)
|
|
828
|
+
process.stdout.write('(no genes)\n'); // no early return: the auto-pending footer below is
|
|
829
|
+
for (const g of genes) { // computed from the full event set, so it must print
|
|
830
|
+
const id = typeof g['id'] === 'string' ? String(g['id']) : String(g.asset_id);
|
|
831
|
+
const view = await assetstore.aggregateLearningHistory(s, id);
|
|
832
|
+
const cat = String(g['category'] ?? '?');
|
|
833
|
+
const rate = view.total > 0 ? `${Math.round(view.successRate * 100)}%` : '-';
|
|
834
|
+
const state = rev.get(String(g.asset_id))?.state ?? 'eligible'; // no record → eligible by default
|
|
835
|
+
const auto = autoDrafted.has(String(g.asset_id)) ? ' ✎auto-drafted' : '';
|
|
836
|
+
// For a gene on probation, show its AUTO-PROMOTE eligibility next to the success-rate health label — they are
|
|
837
|
+
// different lenses that can disagree (#306 trial): a gene can read [healthy] by success-rate yet never auto-
|
|
838
|
+
// promote because it has a failure. Route through the SAME predicate auto-promote uses so they never diverge.
|
|
839
|
+
const promote = state === 'quarantined' ? ` promote:${promoteHint(view)}` : '';
|
|
840
|
+
process.stdout.write(`${id.padEnd(28)} ${cat.padEnd(10)} total=${view.total} succ=${rate} [${reviewStatus(view)}] {${state}}${promote}${auto}\n`);
|
|
841
|
+
}
|
|
842
|
+
if (autoPending > 0)
|
|
843
|
+
process.stdout.write(`\n${autoPending} auto-drafted gene(s) awaiting review — approve with \`evolver review --approve <id>\`\n`);
|
|
844
|
+
const antiGenePending = (await listReviewVisibleAntiGenes(s, rev)).filter((asset) => rev.get(String(asset.asset_id))?.state === 'quarantined').length;
|
|
845
|
+
if (antiGenePending > 0)
|
|
846
|
+
process.stdout.write(`\n${antiGenePending} anti-gene(s) awaiting review - inspect with \`evolver review --anti-gene\`\n`);
|
|
847
|
+
return 0;
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* `evolver value [--window 7d|30d|all]`: the pull-only, zero-intrusion answer to "is evolver worth it". Reads the
|
|
851
|
+
* proxy trace day-files (route savings) + root_events (reuse / inject) off disk, derives the value ledger through
|
|
852
|
+
* the SAME core aggregation every surface uses (ops.loadValueSummary — no re-implementation here), and prints the
|
|
853
|
+
* three-section report. measured and estimated savings are shown on separate lines (never merged). With no ledger
|
|
854
|
+
* data it prints guidance, not an empty table. This is a THIN command: all aggregation lives in core ops.
|
|
855
|
+
*/
|
|
856
|
+
export function runValue(argv, deps = {}) {
|
|
857
|
+
const f = parseFlags(argv);
|
|
858
|
+
const windowSpec = f['window'];
|
|
859
|
+
const now = deps.now ? deps.now() : Date.now();
|
|
860
|
+
const traces = ops.readTraceRecords(deps.tracesDir ?? events.tracesDir());
|
|
861
|
+
const evts = readEvents(deps.eventsPath ?? events.rootEventsPath());
|
|
862
|
+
const prices = deps.prices ?? loadPriceTable();
|
|
863
|
+
const window = ops.windowFromSpec(windowSpec, now);
|
|
864
|
+
const summary = ops.loadValueSummary({ traces, events: evts, prices }, window);
|
|
865
|
+
process.stdout.write(ops.formatValueReport(summary, windowSpec) + '\n');
|
|
866
|
+
return 0;
|
|
867
|
+
}
|
|
868
|
+
export function formatNarrativeSnapshot(snapshot) {
|
|
869
|
+
const lines = [
|
|
870
|
+
`narrative: total=${snapshot.totalEvents} included=${snapshot.includedEvents} cycles=${snapshot.cycles} reflections=${snapshot.reflections} success=${snapshot.outcomes.success} failed=${snapshot.outcomes.failed} inert=${snapshot.outcomes.inert} unknown=${snapshot.outcomes.unknown}`,
|
|
871
|
+
];
|
|
872
|
+
if (snapshot.entries.length === 0) {
|
|
873
|
+
lines.push(' entries: none');
|
|
874
|
+
return `${lines.join('\n')}\n`;
|
|
875
|
+
}
|
|
876
|
+
lines.push(' entries:');
|
|
877
|
+
for (const entry of snapshot.entries) {
|
|
878
|
+
const cycle = entry.cycleId ? ` cycle=${entry.cycleId}` : '';
|
|
879
|
+
const outcome = entry.outcome ? ` outcome=${entry.outcome}` : '';
|
|
880
|
+
const action = entry.action ? ` action=${entry.action}` : '';
|
|
881
|
+
const gene = entry.geneId ? ` gene=${entry.geneId}` : '';
|
|
882
|
+
const score = typeof entry.score === 'number' ? ` score=${entry.score}` : '';
|
|
883
|
+
lines.push(` #${entry.seq} ${entry.ts} ${entry.type}${cycle}${outcome}${action}${gene}${score} - ${entry.title}`);
|
|
884
|
+
if (entry.summary)
|
|
885
|
+
lines.push(` ${entry.summary}`);
|
|
886
|
+
}
|
|
887
|
+
return `${lines.join('\n')}\n`;
|
|
888
|
+
}
|
|
889
|
+
export function runNarrative(argv, deps = {}) {
|
|
890
|
+
const f = parseFlags(argv);
|
|
891
|
+
const limit = parsePositiveInt(f['limit']);
|
|
892
|
+
const snapshot = buildNarrativeSnapshot(readEvents(deps.eventsPath), { ...(limit !== undefined ? { limit } : {}) });
|
|
893
|
+
if ('json' in f) {
|
|
894
|
+
process.stdout.write(`${JSON.stringify({ ok: true, group: 'narrative', ...snapshot })}\n`);
|
|
895
|
+
}
|
|
896
|
+
else {
|
|
897
|
+
process.stdout.write(formatNarrativeSnapshot(snapshot));
|
|
898
|
+
}
|
|
899
|
+
return 0;
|
|
900
|
+
}
|
|
901
|
+
export function formatRetentionReport(report) {
|
|
902
|
+
const lines = [
|
|
903
|
+
`retention: mode=${report.mode} prune=${report.destructivePruneSupported ? 'enabled' : 'disabled'} generatedAt=${report.generatedAt}`,
|
|
904
|
+
` root_events: state=${report.rootEvents.state} records=${report.rootEvents.records} bytes=${report.rootEvents.bytes} invalid=${report.rootEvents.invalidLines} firstSeq=${report.rootEvents.firstSeq ?? '-'} lastSeq=${report.rootEvents.lastSeq ?? '-'} protectTail=${report.rootEvents.protectTailEvents}`,
|
|
905
|
+
` material: state=${report.material.state} records=${report.material.records} bytes=${report.material.bytes} invalid=${report.material.invalidLines} cursor=${report.material.cursor} effectiveCursor=${report.material.effectiveCursor} cursorValid=${report.material.cursorValid} cursorInRange=${report.material.cursorInRange} consumedPrefix=${report.material.consumedPrefix} pending=${report.material.pending}`,
|
|
906
|
+
];
|
|
907
|
+
if (report.warnings.length > 0) {
|
|
908
|
+
lines.push(' warnings:');
|
|
909
|
+
for (const warning of report.warnings)
|
|
910
|
+
lines.push(` ${warning}`);
|
|
911
|
+
}
|
|
912
|
+
else {
|
|
913
|
+
lines.push(' warnings: none');
|
|
914
|
+
}
|
|
915
|
+
lines.push(' next:');
|
|
916
|
+
for (const action of report.nextActions)
|
|
917
|
+
lines.push(` ${action}`);
|
|
918
|
+
return `${lines.join('\n')}\n`;
|
|
919
|
+
}
|
|
920
|
+
export function runRetention(argv, deps = {}) {
|
|
921
|
+
const f = parseFlags(argv);
|
|
922
|
+
const report = buildRetentionReport({
|
|
923
|
+
rootEventsPath: deps.rootEventsPath,
|
|
924
|
+
materialStorePath: deps.materialStorePath,
|
|
925
|
+
materialCursorPath: deps.materialCursorPath,
|
|
926
|
+
now: deps.now,
|
|
927
|
+
maxRootEvents: parsePositiveInt(f['max-root-events']),
|
|
928
|
+
maxRootBytes: parsePositiveInt(f['max-root-bytes']),
|
|
929
|
+
maxMaterialRecords: parsePositiveInt(f['max-material-records']),
|
|
930
|
+
maxMaterialBytes: parsePositiveInt(f['max-material-bytes']),
|
|
931
|
+
});
|
|
932
|
+
if ('json' in f)
|
|
933
|
+
process.stdout.write(`${JSON.stringify({ ok: true, group: 'retention', ...report })}\n`);
|
|
934
|
+
else
|
|
935
|
+
process.stdout.write(formatRetentionReport(report));
|
|
936
|
+
return 0;
|
|
937
|
+
}
|
|
938
|
+
function parsePositiveInt(value) {
|
|
939
|
+
if (value === undefined || value.trim() === '')
|
|
940
|
+
return undefined;
|
|
941
|
+
const n = Number(value);
|
|
942
|
+
return Number.isFinite(n) && n > 0 ? Math.floor(n) : undefined;
|
|
943
|
+
}
|
|
944
|
+
/** A compact one-line rendering of a gene for SessionStart injection (id + a short hint). Deterministic. */
|
|
945
|
+
export function formatGeneInjectionLine(g) {
|
|
946
|
+
const id = typeof g['id'] === 'string' ? String(g['id']) : String(g.asset_id);
|
|
947
|
+
const cat = String(g['category'] ?? '');
|
|
948
|
+
const summary = String(g['summary'] ?? '').replace(/\s+/g, ' ').trim();
|
|
949
|
+
const hint = summary || (Array.isArray(g['signals_match']) ? g['signals_match'].slice(0, 4).join(', ') : '');
|
|
950
|
+
return `- ${id}${cat ? ` [${cat}]` : ''}${hint ? `: ${hint.slice(0, 160)}` : ''}`;
|
|
951
|
+
}
|
|
952
|
+
/** Read the SessionStart hook's stdin payload, bounded so it can NEVER hang the agent's critical path: skipped on a
|
|
953
|
+
* TTY (a manual run), and capped by a short timeout so a runtime that leaves stdin open without sending EOF still
|
|
954
|
+
* proceeds. Resolves to '' when nothing is available. Only called when the hook opts in (--hook-stdin). */
|
|
955
|
+
function readStdinBounded(timeoutMs = 500) {
|
|
956
|
+
return new Promise((resolve) => {
|
|
957
|
+
const stdin = process.stdin;
|
|
958
|
+
if (stdin.isTTY) {
|
|
959
|
+
resolve('');
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
let data = '';
|
|
963
|
+
let settled = false;
|
|
964
|
+
const finish = (v) => {
|
|
965
|
+
if (settled)
|
|
966
|
+
return;
|
|
967
|
+
settled = true;
|
|
968
|
+
clearTimeout(timer);
|
|
969
|
+
stdin.removeListener('data', onData);
|
|
970
|
+
stdin.removeListener('end', onEnd);
|
|
971
|
+
stdin.removeListener('error', onErr);
|
|
972
|
+
try {
|
|
973
|
+
stdin.pause();
|
|
974
|
+
}
|
|
975
|
+
catch { /* already closed */ }
|
|
976
|
+
resolve(v);
|
|
977
|
+
};
|
|
978
|
+
const onData = (c) => { data += c.toString(); };
|
|
979
|
+
const onEnd = () => finish(data);
|
|
980
|
+
const onErr = () => finish('');
|
|
981
|
+
const timer = setTimeout(() => finish(data), timeoutMs);
|
|
982
|
+
timer.unref?.(); // never keep the process alive for this read
|
|
983
|
+
stdin.setEncoding('utf8');
|
|
984
|
+
stdin.on('data', onData);
|
|
985
|
+
stdin.on('end', onEnd);
|
|
986
|
+
stdin.on('error', onErr);
|
|
987
|
+
try {
|
|
988
|
+
stdin.resume();
|
|
989
|
+
}
|
|
990
|
+
catch {
|
|
991
|
+
finish('');
|
|
992
|
+
}
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
/** Extract `session_id` from the SessionStart hook payload (Claude Code delivers JSON on stdin). Best-effort: any
|
|
996
|
+
* read/parse error is swallowed (the injection must never fail for a missing session id), and a runtime that
|
|
997
|
+
* exposes no per-session id simply yields undefined. */
|
|
998
|
+
async function readHookSessionId(read) {
|
|
999
|
+
try {
|
|
1000
|
+
const raw = read ? read() : await readStdinBounded();
|
|
1001
|
+
if (!raw || !raw.trim())
|
|
1002
|
+
return undefined;
|
|
1003
|
+
const obj = JSON.parse(raw);
|
|
1004
|
+
return typeof obj.session_id === 'string' && obj.session_id.length > 0 ? obj.session_id : undefined;
|
|
1005
|
+
}
|
|
1006
|
+
catch {
|
|
1007
|
+
return undefined;
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* `evolver inject session-start`: the SessionStart hook entrypoint (the command every installer registers).
|
|
1012
|
+
* It selects the eligible local genes, composes the SessionStart injection WITH the value recap (#113) through
|
|
1013
|
+
* core's `composeSessionStartWithRecap`, prints only a quiet memory hint when at least one approved gene actually
|
|
1014
|
+
* lands in the prompt, AND — this is #123 — wires the inject emission seam so a `value.inject` root_event is
|
|
1015
|
+
* appended carrying the genes that ACTUALLY landed in the prompt (post budget-trim). That feeds the ledger's source=inject rail with real data, attribution-only:
|
|
1016
|
+
* the event has NO savings number (the genes are recorded for outcome attribution, never scored).
|
|
1017
|
+
*
|
|
1018
|
+
* The outcome is NOT observable here — at SessionStart the session has not run yet — so the event records the
|
|
1019
|
+
* injected genes only; outcome stays absent for a possible later attribution pass.
|
|
1020
|
+
*
|
|
1021
|
+
* Best-effort by construction: the emit promise is awaited so the event is durable before the command returns,
|
|
1022
|
+
* but emitInject swallows every error, so a sink failure can never break or block the attribution path.
|
|
1023
|
+
*/
|
|
1024
|
+
export async function runInject(argv, deps = {}) {
|
|
1025
|
+
const sub = argv[0];
|
|
1026
|
+
if (sub !== 'session-start') {
|
|
1027
|
+
process.stderr.write('用法: evolver inject session-start\n');
|
|
1028
|
+
return sub === undefined ? 0 : 1;
|
|
1029
|
+
}
|
|
1030
|
+
const fromHookStdin = argv.includes('--hook-stdin');
|
|
1031
|
+
if (fromHookStdin) {
|
|
1032
|
+
try {
|
|
1033
|
+
await (deps.ensureProxyAutostart ?? (() => maybeAutoRestartProxyForSessionStart()))();
|
|
1034
|
+
}
|
|
1035
|
+
catch (err) {
|
|
1036
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1037
|
+
if (sessionStartHookVerboseEnabled(process.env)) {
|
|
1038
|
+
process.stderr.write(`[evolver-session-start] proxy auto-restart failed: ${msg}\n`);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
|
|
1043
|
+
const ingestor = deps.ingestor ?? new events.Ingestor({ path: deps.eventsPath ?? events.rootEventsPath() });
|
|
1044
|
+
const review = deps.review ?? reviewLedgerForStore(store); // co-located with the store, not pinned to live dir
|
|
1045
|
+
const provenance = deps.provenance ?? provenanceStoreForStore(store); // co-located with the store, not pinned to live dir
|
|
1046
|
+
const maxGenes = deps.maxGenes ?? 8;
|
|
1047
|
+
const hardCap = deps.tokenBudgetHardCap ?? 8000;
|
|
1048
|
+
// Gene pool → injection candidates: the most recent TRUSTED + REVIEW-APPROVED local genes (bounded), rendered as
|
|
1049
|
+
// compact hint lines. The provenance gate keeps untrusted hub assets out until promotion; the review gate (A2a)
|
|
1050
|
+
// keeps auto-distilled UNPROVEN drafts out until approval.
|
|
1051
|
+
const genes = await listApprovedGenes(store, review, maxGenes, provenance);
|
|
1052
|
+
const geneLines = genes.map(formatGeneInjectionLine);
|
|
1053
|
+
const geneIds = genes.map((g) => (typeof g['id'] === 'string' ? String(g['id']) : String(g.asset_id)));
|
|
1054
|
+
// Value recap (#113): same load path as `evolver value`, over the default recap window (7d).
|
|
1055
|
+
const now = deps.now ? deps.now() : Date.now();
|
|
1056
|
+
const traces = ops.readTraceRecords(deps.tracesDir ?? events.tracesDir());
|
|
1057
|
+
const evts = readEvents(deps.eventsPath ?? events.rootEventsPath());
|
|
1058
|
+
const prices = deps.prices ?? loadPriceTable();
|
|
1059
|
+
const summary = ops.loadValueSummary({ traces, events: evts, prices }, ops.windowFromSpec('7d', now));
|
|
1060
|
+
// Inject emission seam (#123): wire the ingestor so core's onInject lands a `value.inject` root_event. The
|
|
1061
|
+
// composition (Ingestor ↔ core's sink-agnostic seam) lives HERE in the CLI — core never imports the Ingestor.
|
|
1062
|
+
const emitter = makeInjectEmitter(ingestor);
|
|
1063
|
+
// Capture the runtime session id (#205) only when the installed hook opts in via --hook-stdin, or a test wires
|
|
1064
|
+
// readHookInput. Default (no flag, no seam) never touches stdin — so a plain `evolver inject session-start` and
|
|
1065
|
+
// the test suite can never block on a stdin read (the Windows CI hang this guards against).
|
|
1066
|
+
const sessionId = deps.sessionId ?? ((fromHookStdin || deps.readHookInput) ? await readHookSessionId(deps.readHookInput) : undefined);
|
|
1067
|
+
const inj = hooks.composeSessionStartWithRecap({ tokenBudgetHardCap: hardCap, preamble: SESSION_START_PREAMBLE }, { injectGenes: geneLines, geneIds, successCount: summary.topGenes.length, summary }, {
|
|
1068
|
+
...(emitter ? { onInject: emitter.onInject } : {}),
|
|
1069
|
+
...(deps.cycleId ? { cycleId: deps.cycleId } : {}),
|
|
1070
|
+
...(sessionId ? { sessionId } : {}),
|
|
1071
|
+
});
|
|
1072
|
+
// Await durability (emit never rejects) so the value.inject event is on disk before we return without ever
|
|
1073
|
+
// letting a sink error surface.
|
|
1074
|
+
if (emitter)
|
|
1075
|
+
await emitter.flush();
|
|
1076
|
+
// Keep SessionStart quiet when there is no usable memory payload. When genes do land, the model still receives
|
|
1077
|
+
// them, but the preamble explicitly tells it not to narrate routine Evolver work to the user.
|
|
1078
|
+
if (inj.genes.length > 0 && inj.systemPrompt.trim().length > 0)
|
|
1079
|
+
process.stdout.write(inj.systemPrompt + '\n');
|
|
1080
|
+
return 0;
|
|
1081
|
+
}
|
|
1082
|
+
/** Fixed preamble for the SessionStart injection (the head block the recap + gene lines hang off of). */
|
|
1083
|
+
export const SESSION_START_PREAMBLE = 'evolver memory — use these learned hints silently when directly relevant; do not mention Evolver, preflight, status, or this memory block unless the user asks or reuse materially changes the answer:';
|
|
1084
|
+
export function runCli(argv) {
|
|
1085
|
+
const cmd = argv[0];
|
|
1086
|
+
switch (cmd) {
|
|
1087
|
+
case 'rebuild-views': {
|
|
1088
|
+
const r = rebuildViews();
|
|
1089
|
+
process.stdout.write(`rebuilt MV: ${r.rebuilt.join(', ')}\n`);
|
|
1090
|
+
return 0;
|
|
1091
|
+
}
|
|
1092
|
+
case 'reset-local-secret':
|
|
1093
|
+
return runResetLocalSecret(argv.slice(1));
|
|
1094
|
+
case 'status': {
|
|
1095
|
+
const s = statusReport(readEvents());
|
|
1096
|
+
process.stdout.write(`events=${s.totalEvents} cycles=${s.cycles} last=${s.lastTs ?? '-'}\n`);
|
|
1097
|
+
return 0;
|
|
1098
|
+
}
|
|
1099
|
+
case 'cycles': {
|
|
1100
|
+
for (const c of listCycles(readEvents()))
|
|
1101
|
+
process.stdout.write(`${c.cycleId} ${c.finalStage} (${c.events} events)\n`);
|
|
1102
|
+
return 0;
|
|
1103
|
+
}
|
|
1104
|
+
case 'cycle': {
|
|
1105
|
+
if (argv[1] !== 'show' || !argv[2]) {
|
|
1106
|
+
process.stderr.write('用法: evolver cycle show <id>\n');
|
|
1107
|
+
return 1;
|
|
1108
|
+
}
|
|
1109
|
+
for (const t of showCycle(readEvents(), argv[2]).timeline)
|
|
1110
|
+
process.stdout.write(`#${t.seq} ${t.type} ${t.title}\n`);
|
|
1111
|
+
return 0;
|
|
1112
|
+
}
|
|
1113
|
+
case 'trigger': {
|
|
1114
|
+
for (const t of listTriggers(readEvents()))
|
|
1115
|
+
process.stdout.write(`${t.patternId} ${t.triggered ? '触发' : '抑制'} value=${t.value}\n`);
|
|
1116
|
+
return 0;
|
|
1117
|
+
}
|
|
1118
|
+
case 'value':
|
|
1119
|
+
return runValue(argv.slice(1));
|
|
1120
|
+
case 'narrative':
|
|
1121
|
+
return runNarrative(argv.slice(1));
|
|
1122
|
+
case 'retention':
|
|
1123
|
+
return runRetention(argv.slice(1));
|
|
1124
|
+
case 'gene-value':
|
|
1125
|
+
return runGeneValue(argv.slice(1));
|
|
1126
|
+
case 'replay': {
|
|
1127
|
+
const r = rebuildViews();
|
|
1128
|
+
process.stdout.write(`replayed → MV: ${r.rebuilt.join(', ')}\n`);
|
|
1129
|
+
return 0;
|
|
1130
|
+
}
|
|
1131
|
+
default:
|
|
1132
|
+
process.stderr.write('用法: evolver [--version|-v] <status|cycles|cycle show <id>|cycle status [--json]|cycle recover [--limit N] [--json]|trigger|value [--window 7d|30d|all]|narrative [--limit N] [--json]|retention [--json]|trajectory-export [--input <trace-file-or-dir>] [--output <jsonl>]|gene-value [--gene <id>] [--json]|inject session-start|lifecycle <start|stop|restart|status|check|watch|install-service>|phub <init|doctor|status>|replay|rebuild-views|reset-local-secret|asset-log [kind] [limit]|distill ...|review [limit]|recipe build|reuse ...|publish ...|skill-distill --skill <path> [--execution <json|@file>]|skill-md-update --gene <id> --skill <path> [--dry-run]|autoexec [home]|setup-hooks [--runtime] [--root] [--uninstall]|buy|orders|verify|atp|recall <transcript> (--gene <id> ...|--from-inject)>\n');
|
|
1133
|
+
return cmd === undefined ? 0 : 1;
|
|
1134
|
+
}
|
|
1135
|
+
}
|