@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/reuse.js
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
// `evolver reuse --id <asset_id> [--mode reference|direct] [--run <run_id>] [--json]`
|
|
2
|
+
//
|
|
3
|
+
// FR-C5 完整态 native write path (docs/evomap-write-flows-design.md §4): pull ONE global asset by id into this
|
|
4
|
+
// machine's local recall library + record one `asset_reuse` audit line. One-shot writes are owned by evolver-cli
|
|
5
|
+
// (主题 C 写通道方案 B); the proxy HTTP surface stays read/connectivity-oriented.
|
|
6
|
+
//
|
|
7
|
+
// The `--json` output is the STABLE `reuse.v1` machine contract consumed by evox-desktop's
|
|
8
|
+
// EvolverProxyAPI.ReuseAsset (backend/bindings/evolver_proxy.go `evolverReuseEnvelope`, locked per evox-desktop
|
|
9
|
+
// #1008). That adapter parses stdout JSON ONLY (never stderr/interactive output), keys on `contract === "reuse.v1"`,
|
|
10
|
+
// and degrades to the agent `/pack apply` path on any non-ok result. Two hard rules follow:
|
|
11
|
+
// 1. Print EXACTLY ONE envelope object to STDOUT on BOTH success and failure (in --json mode).
|
|
12
|
+
// 2. NEVER let a token/secret reach any stream — error text is mapped to fixed messages / redacted.
|
|
13
|
+
import { assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
|
|
14
|
+
import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled } from '@evomap/evolver-adapter-public';
|
|
15
|
+
import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
|
|
16
|
+
import { createRecipeHubFromEnv } from './recipe.js';
|
|
17
|
+
const REUSE_CONTRACT = 'reuse.v1';
|
|
18
|
+
const MAX_ID_LENGTH = 200;
|
|
19
|
+
const REUSE_USAGE = [
|
|
20
|
+
'usage: evolver reuse --id <asset_id> --json [--mode reference|direct] [--run <run_id>]',
|
|
21
|
+
' evolver reuse <asset_id> --json [--mode reference|direct] [--run <run_id>]',
|
|
22
|
+
].join('\n');
|
|
23
|
+
// Flags that consume the following token as their value. firstPositional must skip those values so a flag value
|
|
24
|
+
// (e.g. the `reference` in `--mode reference`) is never mistaken for a bare positional asset id.
|
|
25
|
+
const VALUE_FLAGS = new Set(['--id', '--mode', '--run']);
|
|
26
|
+
const HUB_METADATA_KEYS = new Set([
|
|
27
|
+
'credit_cost',
|
|
28
|
+
'gdi_score',
|
|
29
|
+
'success_rate',
|
|
30
|
+
'reuse_count',
|
|
31
|
+
'ranking_score',
|
|
32
|
+
'source_node_id',
|
|
33
|
+
'fetched_at',
|
|
34
|
+
'receipt',
|
|
35
|
+
'hub_receipt',
|
|
36
|
+
'already_purchased',
|
|
37
|
+
'_semantic_similarity',
|
|
38
|
+
'semantic_similarity',
|
|
39
|
+
'_search_score',
|
|
40
|
+
'search_score',
|
|
41
|
+
'_match_score',
|
|
42
|
+
'match_score',
|
|
43
|
+
'_retrieval_rank',
|
|
44
|
+
'retrieval_rank',
|
|
45
|
+
'original_asset_id',
|
|
46
|
+
]);
|
|
47
|
+
export async function runReuseCommand(argv, deps = {}) {
|
|
48
|
+
const ctx = {
|
|
49
|
+
jsonOut: argv.includes('--json'),
|
|
50
|
+
stdout: deps.stdout ?? ((line) => { process.stdout.write(`${line}\n`); }),
|
|
51
|
+
stderr: deps.stderr ?? ((line) => { process.stderr.write(`${line}\n`); }),
|
|
52
|
+
};
|
|
53
|
+
if (argv.includes('--help') || argv.includes('-h')) {
|
|
54
|
+
if (ctx.jsonOut) {
|
|
55
|
+
ctx.stdout(JSON.stringify({
|
|
56
|
+
ok: true,
|
|
57
|
+
contract: REUSE_CONTRACT,
|
|
58
|
+
status: 'ok',
|
|
59
|
+
reason: 'help',
|
|
60
|
+
message: REUSE_USAGE,
|
|
61
|
+
}));
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
ctx.stdout(REUSE_USAGE);
|
|
65
|
+
return 0;
|
|
66
|
+
}
|
|
67
|
+
const parsed = parseReuseArgs(argv);
|
|
68
|
+
if (!parsed.ok)
|
|
69
|
+
return emit({ ok: false, status: parsed.status ?? 'invalid_arg', message: parsed.error }, ctx);
|
|
70
|
+
const opts = parsed.value;
|
|
71
|
+
try {
|
|
72
|
+
const env = deps.env ?? process.env;
|
|
73
|
+
// Keep the native reuse path aligned with publish/contract transport: env-file values must be present before
|
|
74
|
+
// dry-run checks and Hub construction. The loader mutates `env` and does not expose secret values.
|
|
75
|
+
loadEnvFileFromEnv(env);
|
|
76
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
|
|
77
|
+
// 1) Already in the local recall library → reuse is idempotent: log + ok, no hub round-trip.
|
|
78
|
+
const local = await resolveLocalReuseAsset(store, opts.id);
|
|
79
|
+
if (local) {
|
|
80
|
+
logReuse(deps, opts, local, 'local');
|
|
81
|
+
return emit({ ok: true, status: 'ok', message: 'asset already in local recall library' }, ctx);
|
|
82
|
+
}
|
|
83
|
+
// 2) Dry-run: describe the intended pull, touch nothing.
|
|
84
|
+
if (isHubDryRunEnabled(env)) {
|
|
85
|
+
return emit({ ok: true, status: 'dry_run', message: `would fetch ${opts.id} and write it to the local recall library` }, ctx);
|
|
86
|
+
}
|
|
87
|
+
// 3) Pull the global asset by id, write it into the local recall library (put dedups → idempotent on repeat).
|
|
88
|
+
const hub = deps.hub ?? createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
|
|
89
|
+
const asset = await hub.fetchAssetById(opts.id);
|
|
90
|
+
if (!asset)
|
|
91
|
+
return emit({ ok: false, status: 'not_found', message: `asset ${opts.id} not found on the hub` }, ctx);
|
|
92
|
+
const cleaned = await ingestHubAsset(store, deps, asset, opts.id);
|
|
93
|
+
logReuse(deps, opts, cleaned, 'hub');
|
|
94
|
+
return emit({ ok: true, status: 'ok', message: 'reused into local recall library' }, ctx);
|
|
95
|
+
}
|
|
96
|
+
catch (e) {
|
|
97
|
+
return emit(mapError(e), ctx);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** Flags this CLI understands. parseReuseArgs walks argv and rejects anything outside this set with reason
|
|
101
|
+
* `unsupported` so a typoed flag never silently falls through to a Hub round-trip — review blocker on V1 #283
|
|
102
|
+
* (the previous tightening lived only in cliContracts.ts; dispatch.ts routes `reuse` here, so this is the path
|
|
103
|
+
* end-users actually hit). Message text MUST stay byte-equal to cliContracts.ts::parseReuseArgs for v1↔v2 parity. */
|
|
104
|
+
const KNOWN_REUSE_FLAGS = new Set(['--id', '--mode', '--run', '--json']);
|
|
105
|
+
export function parseReuseArgs(argv) {
|
|
106
|
+
// Walk argv explicitly so unknown long flags fail closed instead of being ignored. We still let `--id`/`--mode`/
|
|
107
|
+
// `--run` use either `--flag value` or `--flag=value`, and we still accept a single bare positional as the id
|
|
108
|
+
// (the legacy ergonomics covered by parseReuseArgs's own contract test + recipe.ts callers).
|
|
109
|
+
let jsonOut = false;
|
|
110
|
+
let positional;
|
|
111
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
112
|
+
const token = argv[i];
|
|
113
|
+
if (token === undefined)
|
|
114
|
+
continue;
|
|
115
|
+
if (token === '--json') {
|
|
116
|
+
jsonOut = true;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (token.startsWith('--')) {
|
|
120
|
+
const eq = token.indexOf('=');
|
|
121
|
+
const flag = eq >= 0 ? token.slice(0, eq) : token;
|
|
122
|
+
if (!KNOWN_REUSE_FLAGS.has(flag))
|
|
123
|
+
return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${flag}` };
|
|
124
|
+
if (eq < 0 && VALUE_FLAGS.has(flag)) {
|
|
125
|
+
// Value flag in space form consumes the next token; skip it so it doesn't get re-checked as a flag/positional.
|
|
126
|
+
const next = argv[i + 1];
|
|
127
|
+
if (next !== undefined && !next.startsWith('--'))
|
|
128
|
+
i += 1;
|
|
129
|
+
}
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
// Reject single-dash short options (e.g. `-x`) before the bare-positional branch: they bypass the
|
|
133
|
+
// `--`-prefixed check above and would otherwise be silently accepted as an asset id, violating the
|
|
134
|
+
// fail-closed contract. Legal asset ids (`sha256:…`, `gene_distilled_…`, logical ids) never start with `-`.
|
|
135
|
+
if (token.startsWith('-'))
|
|
136
|
+
return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${token}` };
|
|
137
|
+
// First (and only) bare positional is the asset id; further positionals are unsupported.
|
|
138
|
+
if (positional !== undefined)
|
|
139
|
+
return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${token}` };
|
|
140
|
+
positional = token;
|
|
141
|
+
}
|
|
142
|
+
if (!jsonOut)
|
|
143
|
+
return { ok: false, status: 'unsupported', error: 'reuse requires --json' };
|
|
144
|
+
// Reject a stray bare positional supplied alongside --id/--id=: silently preferring the flag would let a
|
|
145
|
+
// typo'd/extra arg — or a conflicting second id — pass fail-OPEN, contradicting the fail-closed contract.
|
|
146
|
+
const idFromFlag = flagValue(argv, '--id');
|
|
147
|
+
if (idFromFlag !== null && positional !== undefined) {
|
|
148
|
+
return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${positional}` };
|
|
149
|
+
}
|
|
150
|
+
const id = idFromFlag ?? positional;
|
|
151
|
+
if (!id)
|
|
152
|
+
return { ok: false, status: 'missing_id', error: 'reuse requires --id <asset_id>' };
|
|
153
|
+
if (id.length > MAX_ID_LENGTH)
|
|
154
|
+
return { ok: false, status: 'missing_id', error: `asset id must be <= ${MAX_ID_LENGTH} characters` };
|
|
155
|
+
const modeRaw = flagValue(argv, '--mode');
|
|
156
|
+
if (modeRaw !== null && modeRaw !== 'direct' && modeRaw !== 'reference')
|
|
157
|
+
return { ok: false, status: 'invalid_arg', error: '--mode must be direct|reference' };
|
|
158
|
+
const runId = flagValue(argv, '--run');
|
|
159
|
+
return { ok: true, value: { id, mode: modeRaw === 'direct' ? 'direct' : 'reference', ...(runId ? { runId } : {}) } };
|
|
160
|
+
}
|
|
161
|
+
async function ingestHubAsset(store, deps, asset, requestedId) {
|
|
162
|
+
const cleaned = stripHubMetadata(asset);
|
|
163
|
+
const actualAssetId = wire.computeAssetId(cleaned);
|
|
164
|
+
const contentAssetId = stringField(cleaned, 'asset_id');
|
|
165
|
+
if (!actualAssetId || !contentAssetId || actualAssetId !== contentAssetId) {
|
|
166
|
+
throw new Error('asset integrity verification failed');
|
|
167
|
+
}
|
|
168
|
+
if (isContentAssetId(requestedId) && actualAssetId !== requestedId) {
|
|
169
|
+
throw new Error('asset integrity verification failed');
|
|
170
|
+
}
|
|
171
|
+
if (!isContentAssetId(requestedId) && stringField(cleaned, 'id') !== requestedId) {
|
|
172
|
+
throw new Error('asset integrity verification failed');
|
|
173
|
+
}
|
|
174
|
+
await assertNoLocalReuseIdConflict(cleaned, store);
|
|
175
|
+
const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, deps));
|
|
176
|
+
const stored = await assetstore.ingestUntrusted(store, provenance, cleaned, 'hub');
|
|
177
|
+
return { ...cleaned, asset_id: stored.asset_id };
|
|
178
|
+
}
|
|
179
|
+
async function resolveLocalReuseAsset(store, id) {
|
|
180
|
+
const direct = await store.get(id);
|
|
181
|
+
if (direct)
|
|
182
|
+
return direct;
|
|
183
|
+
for (const kind of ['Gene', 'Capsule']) {
|
|
184
|
+
const rows = await store.list(kind, 10_000);
|
|
185
|
+
const match = rows.find((row) => stringField(row, 'id') === id || String(row.asset_id) === id);
|
|
186
|
+
if (match)
|
|
187
|
+
return match;
|
|
188
|
+
}
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
async function assertNoLocalReuseIdConflict(asset, store) {
|
|
192
|
+
if (asset.type !== 'Gene' && asset.type !== 'Capsule')
|
|
193
|
+
return;
|
|
194
|
+
const id = stringField(asset, 'id');
|
|
195
|
+
if (!id)
|
|
196
|
+
return;
|
|
197
|
+
const rows = await store.list(asset.type, 10_000);
|
|
198
|
+
const local = rows.find((row) => stringField(row, 'id') === id);
|
|
199
|
+
if (!local)
|
|
200
|
+
return;
|
|
201
|
+
const incomingAssetId = wire.computeAssetId(asset);
|
|
202
|
+
const localAssetId = wire.computeAssetId(local);
|
|
203
|
+
if (incomingAssetId !== localAssetId)
|
|
204
|
+
throw new Error('local asset id conflict');
|
|
205
|
+
}
|
|
206
|
+
function stripHubMetadata(asset) {
|
|
207
|
+
const out = {};
|
|
208
|
+
for (const [key, value] of Object.entries(asset))
|
|
209
|
+
if (!HUB_METADATA_KEYS.has(key))
|
|
210
|
+
out[key] = value;
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
function storeBaseDir(store, deps) {
|
|
214
|
+
return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
|
|
215
|
+
}
|
|
216
|
+
function stringField(record, key) {
|
|
217
|
+
const value = record[key];
|
|
218
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
219
|
+
}
|
|
220
|
+
function isContentAssetId(value) {
|
|
221
|
+
return value.startsWith('sha256:');
|
|
222
|
+
}
|
|
223
|
+
function logReuse(deps, opts, asset, source) {
|
|
224
|
+
// AssetCallLog.append is best-effort (never throws) — a logging failure must not break the reuse write.
|
|
225
|
+
const callLog = deps.callLog ?? new hubNs.AssetCallLog(events.assetCallLogPath());
|
|
226
|
+
callLog.append({
|
|
227
|
+
action: 'asset_reuse',
|
|
228
|
+
asset_id: asset.asset_id,
|
|
229
|
+
asset_type: asset.type,
|
|
230
|
+
mode: opts.mode,
|
|
231
|
+
...(opts.runId ? { run_id: opts.runId } : {}),
|
|
232
|
+
extra: { source },
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
function mapError(e) {
|
|
236
|
+
if (e instanceof AuthError)
|
|
237
|
+
return { ok: false, status: 'unauthorized', message: 'hub authentication failed; run `evolver login` or set EVOMAP_NODE_SECRET' };
|
|
238
|
+
if (e instanceof HubUnreachableError)
|
|
239
|
+
return { ok: false, status: 'network', message: 'hub is unreachable' };
|
|
240
|
+
if (e instanceof HubClientError) {
|
|
241
|
+
if (e.status === 401 || e.status === 403)
|
|
242
|
+
return { ok: false, status: 'unauthorized', message: 'hub authentication failed; run `evolver login` or set EVOMAP_NODE_SECRET' };
|
|
243
|
+
if (e.status === 404)
|
|
244
|
+
return { ok: false, status: 'not_found', message: 'asset not found on the hub' };
|
|
245
|
+
if (e.status === 429 || e.status >= 500)
|
|
246
|
+
return { ok: false, status: 'network', message: 'hub is temporarily unavailable' };
|
|
247
|
+
return { ok: false, status: 'internal_error', message: 'hub rejected the reuse request' };
|
|
248
|
+
}
|
|
249
|
+
// createRecipeHubFromEnv/connectHub can throw plain configuration errors. Keep Hub URL issues apart from auth:
|
|
250
|
+
// a bad URL is a configuration gap, NOT an auth failure — conflating them would tell the operator/desktop adapter
|
|
251
|
+
// to "log in" when the real fix is to correct the Hub URL.
|
|
252
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
253
|
+
if (/Hub URL|EVOMAP_HUB_URL|A2A_HUB_URL/i.test(msg)) {
|
|
254
|
+
return { ok: false, status: 'unavailable', message: redact(msg) };
|
|
255
|
+
}
|
|
256
|
+
if (/Hub credentials|node identity|evolver login|EVOMAP_NODE_SECRET/i.test(msg)) {
|
|
257
|
+
return { ok: false, status: 'unauthorized', message: redact(msg) };
|
|
258
|
+
}
|
|
259
|
+
if (/\b(?:hub|http)\s*5\d\d\b/i.test(msg) || /\b(network|fetch failed|ECONN[A-Z_]*|ENOTFOUND|ETIMEDOUT)\b/i.test(msg)) {
|
|
260
|
+
return { ok: false, status: 'network', message: 'hub is unreachable' };
|
|
261
|
+
}
|
|
262
|
+
return { ok: false, status: 'internal_error', message: redact(msg) };
|
|
263
|
+
}
|
|
264
|
+
function emit(outcome, ctx) {
|
|
265
|
+
if (ctx.jsonOut) {
|
|
266
|
+
// stdout ONLY, exactly one object — the desktop adapter json.Unmarshals the whole stdout stream.
|
|
267
|
+
const envelope = { ok: outcome.ok, contract: REUSE_CONTRACT, status: outcome.status, reason: outcome.status, message: outcome.message };
|
|
268
|
+
ctx.stdout(JSON.stringify(envelope));
|
|
269
|
+
}
|
|
270
|
+
else if (outcome.ok) {
|
|
271
|
+
ctx.stdout(`reuse: ${outcome.message}`);
|
|
272
|
+
}
|
|
273
|
+
else {
|
|
274
|
+
ctx.stderr(`reuse failed (${outcome.status}): ${outcome.message}`);
|
|
275
|
+
}
|
|
276
|
+
return outcome.ok ? 0 : 1;
|
|
277
|
+
}
|
|
278
|
+
/** Defensive redaction so a stray credential in an error string never reaches stdout/stderr. */
|
|
279
|
+
function redact(value) {
|
|
280
|
+
return value
|
|
281
|
+
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')
|
|
282
|
+
.replace(/\b([A-Z][A-Z0-9_]*(?:_SECRET|_TOKEN))\b\s*[:=]\s*["']?[^"',\s;}]+/g, '$1=[redacted]')
|
|
283
|
+
.replace(/\b(authorization|node_secret|nodeSecret|access_token|refresh_token|token|secret)\b\s*[:=]\s*["']?[^"',\s;}]+/gi, '$1=[redacted]')
|
|
284
|
+
.replace(/\bsk-[A-Za-z0-9-]{16,}/g, 'sk-[redacted]')
|
|
285
|
+
.replace(/\bgh[pousr]_[A-Za-z0-9]{20,}/g, 'gh_[redacted]');
|
|
286
|
+
}
|
|
287
|
+
function flagValue(args, flag) {
|
|
288
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
289
|
+
const token = args[i];
|
|
290
|
+
if (token === undefined)
|
|
291
|
+
continue;
|
|
292
|
+
if (token === flag) {
|
|
293
|
+
const next = args[i + 1];
|
|
294
|
+
return next && !next.startsWith('--') ? next : null;
|
|
295
|
+
}
|
|
296
|
+
if (token.startsWith(`${flag}=`))
|
|
297
|
+
return token.slice(flag.length + 1);
|
|
298
|
+
}
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { events, assetstore, algo } from '@evomap/evolver-core';
|
|
2
|
+
export interface ReuseReportDeps {
|
|
3
|
+
/** Test seam: read root_events. Default reads the real root_events log. */
|
|
4
|
+
readEvents?: (eventsPath?: string) => events.ReportEvent[];
|
|
5
|
+
/** Store to resolve reuse-event ids and to list AntiGene assets for the #326 report. */
|
|
6
|
+
store?: Pick<assetstore.AssetStoreProvider, 'get' | 'list'>;
|
|
7
|
+
/** Review ledger to quarantine into or read from. Structural so fakes are trivial. */
|
|
8
|
+
review?: {
|
|
9
|
+
quarantine(assetId: string, reason?: string): unknown;
|
|
10
|
+
get?(assetId: string): assetstore.ReviewRecord | null;
|
|
11
|
+
records?(): assetstore.ReviewRecord[];
|
|
12
|
+
};
|
|
13
|
+
/** Test seam for `--promote`: returns the probation status list. Default scans the real store + review ledger
|
|
14
|
+
* via algo.scanProbationGenes (the SAME predicate the daemon's auto-promote acts on). */
|
|
15
|
+
scanProbation?: () => Promise<algo.ProbationStatus[]>;
|
|
16
|
+
log?: (line: string) => void;
|
|
17
|
+
}
|
|
18
|
+
export declare function runReuseReport(argv: readonly string[], deps?: ReuseReportDeps): Promise<number>;
|
|
19
|
+
/** Registry-shaped handler (argv -> exit code). */
|
|
20
|
+
export declare const runReuseReportCommand: (argv: string[]) => Promise<number>;
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// `evolver reuse-report` (#268 slice C + Pha 2 v1) — surface the CROSS-RUNTIME keep/prune signal AND, with
|
|
2
|
+
// `--quarantine`, act on it under a HUMAN gate. Rolls up reuse outcomes from root_events (success from
|
|
3
|
+
// value.reuse_hit, failed/mismatched/stale/unsafe from value.reuse_outcome) per gene, and lists prune candidates
|
|
4
|
+
// (genes reused but never successfully) — across EVERY runtime, MCP-native agents included.
|
|
5
|
+
//
|
|
6
|
+
// Read-only by default. `--quarantine` is the operator-gated Pha 2 v1: for genes with a STRONG, PERSISTENT
|
|
7
|
+
// negative reuse signal it sets a ReviewLedger quarantine (which the review-first selection gate then excludes
|
|
8
|
+
// from the pool) — NEVER deletes (genes are content-addressed) and is reversible via `review --approve`. The
|
|
9
|
+
// operator runs it deliberately and a human still owns the final call, so it acts on a self-reported (weak)
|
|
10
|
+
// signal safely WITHOUT needing an A/B first. Autonomous (daemon, no human-per-gene) quarantine is a later step.
|
|
11
|
+
//
|
|
12
|
+
// `--promote` is the read-only counterpart for the PROBATION pool (#306): it lists every quarantined gene with its
|
|
13
|
+
// cycle evidence and whether it would auto-promote now (same bar the daemon acts on). It never mutates — it exists
|
|
14
|
+
// so an operator can watch the gated auto-promote machinery before flipping EVOLVER_GENE_PROBATION on.
|
|
15
|
+
//
|
|
16
|
+
// `--anti-gene` is the read-only operator view for #326: it surfaces local AntiGene assets, review state, shadow
|
|
17
|
+
// observations, and whether approved warnings have actually appeared in selection decisions.
|
|
18
|
+
import { events, ops, assetstore, algo } from '@evomap/evolver-core';
|
|
19
|
+
function parseFlags(argv) {
|
|
20
|
+
let quarantine = false, promote = false, antiGene = false, minNegative = 3, minUnsafe = 1;
|
|
21
|
+
for (let i = 0; i < argv.length; i++) {
|
|
22
|
+
const a = argv[i];
|
|
23
|
+
if (a === '--quarantine')
|
|
24
|
+
quarantine = true;
|
|
25
|
+
else if (a === '--promote')
|
|
26
|
+
promote = true;
|
|
27
|
+
else if (a === '--anti-gene')
|
|
28
|
+
antiGene = true;
|
|
29
|
+
else if (a === '--min-negative') {
|
|
30
|
+
const n = Number(argv[++i]);
|
|
31
|
+
if (Number.isFinite(n) && n >= 1)
|
|
32
|
+
minNegative = n;
|
|
33
|
+
}
|
|
34
|
+
else if (a === '--min-unsafe') {
|
|
35
|
+
const n = Number(argv[++i]);
|
|
36
|
+
if (Number.isFinite(n) && n >= 1)
|
|
37
|
+
minUnsafe = n;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return { quarantine, promote, antiGene, minNegative, minUnsafe };
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* `--promote`: read-only visibility into the PROBATION pool (#306). Lists every quarantined gene with its cycle
|
|
44
|
+
* evidence so far and whether it would auto-promote right now, against the SAME bar the daemon acts on
|
|
45
|
+
* (scanProbationGenes). This NEVER promotes — the daemon's auto-promote tick does, when EVOLVER_GENE_PROBATION=1.
|
|
46
|
+
* It exists so an operator can SEE the gated machinery working (and tune) before flipping the default on.
|
|
47
|
+
*/
|
|
48
|
+
async function reportProbation(deps, log) {
|
|
49
|
+
const statuses = deps.scanProbation
|
|
50
|
+
? await deps.scanProbation()
|
|
51
|
+
: await algo.scanProbationGenes(deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir()), new assetstore.ReviewLedger(events.assetsDir()));
|
|
52
|
+
const first = statuses[0];
|
|
53
|
+
if (!first) {
|
|
54
|
+
log('probation: no genes on probation (none quarantined awaiting evidence).');
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
57
|
+
log(`probation: ${statuses.length} gene(s) on probation (promote bar: >=${first.minSuccess} clean success, 0 fail)`);
|
|
58
|
+
for (const s of statuses) {
|
|
59
|
+
const note = s.wouldPromote
|
|
60
|
+
? 'READY (auto-promotes on the next daemon tick when EVOLVER_GENE_PROBATION=1)'
|
|
61
|
+
: s.failed > 0
|
|
62
|
+
? `blocked by ${s.failed} failure(s)`
|
|
63
|
+
: `needs ${Math.max(1, s.minSuccess - s.success)} more clean success`;
|
|
64
|
+
log(` ${s.geneId} success=${s.success} fail=${s.failed} inert=${s.inert} total=${s.total} ${note}`);
|
|
65
|
+
}
|
|
66
|
+
const ready = statuses.filter((s) => s.wouldPromote).map((s) => s.geneId);
|
|
67
|
+
log(ready.length > 0
|
|
68
|
+
? `ready to promote now: ${ready.join(', ')} (read-only view; the daemon performs the promotion)`
|
|
69
|
+
: 'none ready to promote yet.');
|
|
70
|
+
return 0;
|
|
71
|
+
}
|
|
72
|
+
function reviewState(review, assetId) {
|
|
73
|
+
return reviewRecord(review, assetId)?.state ?? 'approved';
|
|
74
|
+
}
|
|
75
|
+
function reviewRecord(review, assetId) {
|
|
76
|
+
return review?.get?.(assetId) ?? null;
|
|
77
|
+
}
|
|
78
|
+
function stringArray(value) {
|
|
79
|
+
return Array.isArray(value) ? value.map(String).map((item) => item.trim()).filter(Boolean) : [];
|
|
80
|
+
}
|
|
81
|
+
function optionalString(value) {
|
|
82
|
+
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
|
|
83
|
+
}
|
|
84
|
+
function countLabel(value) {
|
|
85
|
+
return Array.isArray(value) ? String(value.length) : '0';
|
|
86
|
+
}
|
|
87
|
+
function numberLabel(value) {
|
|
88
|
+
return typeof value === 'number' && Number.isFinite(value) ? String(value) : '-';
|
|
89
|
+
}
|
|
90
|
+
function reviewAuditLabel(record) {
|
|
91
|
+
if (!record)
|
|
92
|
+
return '';
|
|
93
|
+
const parts = [];
|
|
94
|
+
if (record.by)
|
|
95
|
+
parts.push(`by=${record.by}`);
|
|
96
|
+
if (record.reason)
|
|
97
|
+
parts.push(`reason=${record.reason}`);
|
|
98
|
+
if (record.at)
|
|
99
|
+
parts.push(`at=${record.at}`);
|
|
100
|
+
return parts.length > 0 ? `review ${parts.join(' ')}` : '';
|
|
101
|
+
}
|
|
102
|
+
async function listReviewVisibleAntiGenes(store, review) {
|
|
103
|
+
const byAssetId = new Map();
|
|
104
|
+
for (const asset of await store.list('AntiGene', 10_000))
|
|
105
|
+
byAssetId.set(String(asset.asset_id), asset);
|
|
106
|
+
for (const record of review?.records?.() ?? []) {
|
|
107
|
+
if (byAssetId.has(record.assetId))
|
|
108
|
+
continue;
|
|
109
|
+
const asset = await store.get(record.assetId);
|
|
110
|
+
if (asset?.type === 'AntiGene')
|
|
111
|
+
byAssetId.set(record.assetId, asset);
|
|
112
|
+
}
|
|
113
|
+
return [...byAssetId.values()];
|
|
114
|
+
}
|
|
115
|
+
function antiWarningIdsFromDecision(event) {
|
|
116
|
+
const payload = event.payload;
|
|
117
|
+
const warnings = payload?.['antiWarnings'];
|
|
118
|
+
if (!Array.isArray(warnings))
|
|
119
|
+
return [];
|
|
120
|
+
return warnings
|
|
121
|
+
.map((warning) => warning && typeof warning === 'object' && !Array.isArray(warning)
|
|
122
|
+
? String(warning['antiGeneId'] ?? warning['assetId'] ?? '')
|
|
123
|
+
: '')
|
|
124
|
+
.filter(Boolean);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* `--anti-gene`: read-only visibility for the negative-memory side of #326. It intentionally does not approve,
|
|
128
|
+
* reject, promote, quarantine, or alter selection. It only answers: what did shadow/enforce distill produce, what
|
|
129
|
+
* is still pending review, and did approved warnings appear in real selection decisions yet?
|
|
130
|
+
*/
|
|
131
|
+
async function reportAntiGenes(deps, log) {
|
|
132
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
|
|
133
|
+
const review = deps.review ?? new assetstore.ReviewLedger(events.assetsDir());
|
|
134
|
+
const evts = (deps.readEvents ?? events.readEvents)();
|
|
135
|
+
const assets = await listReviewVisibleAntiGenes(store, review);
|
|
136
|
+
const injectedCounts = new Map();
|
|
137
|
+
for (const event of evts.filter((e) => e.type === 'decision.gene_selected')) {
|
|
138
|
+
for (const id of antiWarningIdsFromDecision(event)) {
|
|
139
|
+
injectedCounts.set(id, (injectedCounts.get(id) ?? 0) + 1);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const shadow = evts.filter((event) => event.type === 'anti_gene.distill_shadowed');
|
|
143
|
+
const shadowCandidates = shadow.filter((event) => event.payload?.['status'] === 'candidate');
|
|
144
|
+
const shadowDeclines = shadow.filter((event) => event.payload?.['status'] === 'declined');
|
|
145
|
+
if (assets.length === 0 && shadow.length === 0) {
|
|
146
|
+
log('anti-gene: no AntiGene assets or shadow observations recorded yet.');
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
const counts = { approved: 0, quarantined: 0, rejected: 0 };
|
|
150
|
+
for (const asset of assets)
|
|
151
|
+
counts[reviewState(review, String(asset.asset_id))] += 1;
|
|
152
|
+
log(`anti-gene: ${assets.length} stored asset(s); review approved=${counts.approved} quarantined=${counts.quarantined} rejected=${counts.rejected}; shadow candidate=${shadowCandidates.length} declined=${shadowDeclines.length}`);
|
|
153
|
+
for (const asset of assets) {
|
|
154
|
+
const assetId = String(asset.asset_id);
|
|
155
|
+
const id = typeof asset['id'] === 'string' ? String(asset['id']) : assetId;
|
|
156
|
+
const record = reviewRecord(review, assetId);
|
|
157
|
+
const state = record?.state ?? 'approved';
|
|
158
|
+
const severity = optionalString(asset['severity']) ?? '-';
|
|
159
|
+
const trigger = stringArray(asset['trigger']).slice(0, 6).join(',');
|
|
160
|
+
const avoid = stringArray(asset['avoid']).slice(0, 2).join(' | ');
|
|
161
|
+
const evidence = `failures=${numberLabel(asset['failure_count'])} clusters=${countLabel(asset['source_clusters'])} evidence=${countLabel(asset['evidence_capsules'])}`;
|
|
162
|
+
const audit = reviewAuditLabel(record);
|
|
163
|
+
const injected = (injectedCounts.get(id) ?? 0) + (id === assetId ? 0 : injectedCounts.get(assetId) ?? 0);
|
|
164
|
+
const next = state === 'quarantined'
|
|
165
|
+
? 'approve with evolver review --approve before warning injection'
|
|
166
|
+
: state === 'approved'
|
|
167
|
+
? (injected > 0 ? `observed in ${injected} decision(s)` : 'approved; waiting for matching selection')
|
|
168
|
+
: 'rejected; withheld from warning injection';
|
|
169
|
+
log(` ${id} {${state}} severity=${severity} trigger=${trigger || '-'} avoid=${avoid || '-'} ${evidence}${audit ? ` ${audit}` : ''} ${next}`);
|
|
170
|
+
}
|
|
171
|
+
if (shadowCandidates.length > 0 || shadowDeclines.length > 0) {
|
|
172
|
+
log(`shadow observations: candidate=${shadowCandidates.length} declined=${shadowDeclines.length} (shadow mode stores no AntiGene assets).`);
|
|
173
|
+
}
|
|
174
|
+
return 0;
|
|
175
|
+
}
|
|
176
|
+
/** Resolve a reuse-event id (logical `gene-a` OR content `sha256:…`) to the Gene's content asset_id, mirroring
|
|
177
|
+
* recall's resolveGene: a sha256 hits the index directly (guarded to a Gene), else a bounded Gene-only scan by
|
|
178
|
+
* logical id or asset_id. Returns null when no Gene matches. */
|
|
179
|
+
async function resolveGeneAssetId(store, id) {
|
|
180
|
+
let g = id.startsWith('sha256:') ? await store.get(id) : null;
|
|
181
|
+
if (g && g.type !== 'Gene')
|
|
182
|
+
g = null;
|
|
183
|
+
if (!g) {
|
|
184
|
+
const genes = await store.list('Gene', 1000);
|
|
185
|
+
g = genes.find((x) => String(x['id']) === id || String(x.asset_id) === id) ?? null;
|
|
186
|
+
}
|
|
187
|
+
return g ? String(g.asset_id) : null;
|
|
188
|
+
}
|
|
189
|
+
export async function runReuseReport(argv, deps = {}) {
|
|
190
|
+
const log = deps.log ?? ((s) => process.stdout.write(`${s}\n`));
|
|
191
|
+
const err = (s) => { process.stderr.write(`${s}\n`); };
|
|
192
|
+
const flags = parseFlags(argv);
|
|
193
|
+
// `--promote` is a standalone, read-only probation view (review-ledger + cycle evidence), not derived from the
|
|
194
|
+
// reuse-outcome rollup below — handle it first and return.
|
|
195
|
+
if (flags.promote)
|
|
196
|
+
return reportProbation(deps, log);
|
|
197
|
+
if (flags.antiGene)
|
|
198
|
+
return reportAntiGenes(deps, log);
|
|
199
|
+
const evts = (deps.readEvents ?? events.readEvents)();
|
|
200
|
+
const sum = ops.summarizeReuseOutcomes(evts);
|
|
201
|
+
if (sum.total === 0) {
|
|
202
|
+
log('reuse-report: no reuse outcomes recorded yet (agents report via evolver_asset_reuse_result).');
|
|
203
|
+
return 0;
|
|
204
|
+
}
|
|
205
|
+
log(`reuse-report: ${sum.total} reuse outcome(s) across ${sum.perGene.length} gene(s)`);
|
|
206
|
+
for (const g of sum.perGene) {
|
|
207
|
+
const neg = Object.entries(g.byOutcome).filter(([, n]) => n > 0).map(([k, n]) => `${k}=${n}`).join(', ');
|
|
208
|
+
log(` ${g.assetId} success=${g.success} negative=${g.negative}${neg ? ` [${neg}]` : ''}`);
|
|
209
|
+
}
|
|
210
|
+
if (sum.pruneCandidates.length > 0) {
|
|
211
|
+
log(`prune candidates (reused but never succeeded): ${sum.pruneCandidates.join(', ')}`);
|
|
212
|
+
}
|
|
213
|
+
if (!flags.quarantine)
|
|
214
|
+
return 0;
|
|
215
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
|
|
216
|
+
const review = deps.review ?? new assetstore.ReviewLedger(events.assetsDir());
|
|
217
|
+
const meetsMargin = (c) => c.success === 0 && (c.negative >= flags.minNegative || c.unsafe >= flags.minUnsafe);
|
|
218
|
+
// COMBINE counts per RESOLVED gene before applying the margin (#273 Bugbot): a gene's events can split across
|
|
219
|
+
// its logical id and content asset_id, so judging each summary entry alone would quarantine a gene that actually
|
|
220
|
+
// succeeded under its other id. Resolve every summary id to the Gene's asset_id, group + sum, THEN decide.
|
|
221
|
+
const byGene = new Map();
|
|
222
|
+
for (const g of sum.perGene) {
|
|
223
|
+
const assetId = await resolveGeneAssetId(store, g.assetId);
|
|
224
|
+
if (!assetId) {
|
|
225
|
+
// Only warn for an id that WOULD have been a candidate on its own, so a real prune target isn't lost silently.
|
|
226
|
+
if (meetsMargin({ success: g.success, negative: g.negative, unsafe: g.byOutcome.unsafe })) {
|
|
227
|
+
err(`quarantine: gene not found in local store, skipped: ${g.assetId}`);
|
|
228
|
+
}
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
const agg = byGene.get(assetId) ?? { success: 0, negative: 0, unsafe: 0, ids: [] };
|
|
232
|
+
agg.success += g.success;
|
|
233
|
+
agg.negative += g.negative;
|
|
234
|
+
agg.unsafe += g.byOutcome.unsafe;
|
|
235
|
+
agg.ids.push(g.assetId);
|
|
236
|
+
byGene.set(assetId, agg);
|
|
237
|
+
}
|
|
238
|
+
// Pha 2 v1 (operator-gated): quarantine genes with a STRONG, PERSISTENT negative signal — never on a single
|
|
239
|
+
// failure. `success === 0` AND (negative >= minNegative OR unsafe >= minUnsafe); `unsafe` fires on a lower bar
|
|
240
|
+
// because one unsafe reuse is a stronger signal than several plain failures.
|
|
241
|
+
let quarantined = 0;
|
|
242
|
+
for (const [assetId, c] of byGene) {
|
|
243
|
+
if (!meetsMargin(c))
|
|
244
|
+
continue;
|
|
245
|
+
review.quarantine(assetId, `reuse-prune: 0 success / ${c.negative} negative (unsafe=${c.unsafe})`);
|
|
246
|
+
quarantined += 1;
|
|
247
|
+
log(`quarantined ${assetId} (from ${c.ids.join(', ')})`);
|
|
248
|
+
}
|
|
249
|
+
log(quarantined > 0
|
|
250
|
+
? `quarantine: ${quarantined} gene(s) sent to review (reversible via 'evolver review --approve').`
|
|
251
|
+
: `quarantine: no gene meets the threshold (success=0 AND negative>=${flags.minNegative} OR unsafe>=${flags.minUnsafe}).`);
|
|
252
|
+
return 0;
|
|
253
|
+
}
|
|
254
|
+
/** Registry-shaped handler (argv -> exit code). */
|
|
255
|
+
export const runReuseReportCommand = (argv) => runReuseReport(argv);
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { assetstore } from '@evomap/evolver-core';
|
|
2
|
+
export declare const reviewLedgerForStore: typeof assetstore.reviewLedgerForStore;
|
|
3
|
+
export declare const provenanceStoreForStore: typeof assetstore.provenanceStoreForStore;
|
|
4
|
+
export declare const listApprovedGenes: typeof assetstore.listApprovedGenes;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// The read-side trust/review gate moved into evolver-core (assetstore.reviewFilter) so the MCP recall tool can
|
|
2
|
+
// share the EXACT same gate (#mcp-recall). Re-exported here so the existing cli import sites stay unchanged.
|
|
3
|
+
import { assetstore } from '@evomap/evolver-core';
|
|
4
|
+
export const reviewLedgerForStore = assetstore.reviewLedgerForStore;
|
|
5
|
+
export const provenanceStoreForStore = assetstore.provenanceStoreForStore;
|
|
6
|
+
export const listApprovedGenes = assetstore.listApprovedGenes;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type NormalizedTurn } from '@evomap/evolver-runtime-adapters';
|
|
2
|
+
export interface RuntimeSessionSource {
|
|
3
|
+
agent: string;
|
|
4
|
+
label: string;
|
|
5
|
+
sessionId?: string;
|
|
6
|
+
turns: NormalizedTurn[];
|
|
7
|
+
}
|
|
8
|
+
export declare function isRuntimeSessionSourcePath(path: string): boolean;
|
|
9
|
+
export declare function parseRuntimeSessionSources(path: string, readSource?: (path: string) => string): RuntimeSessionSource[];
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { adapterForPath, isCursorStateVscdbPath, parseCursorStateVscdb, } from '@evomap/evolver-runtime-adapters';
|
|
4
|
+
export function isRuntimeSessionSourcePath(path) {
|
|
5
|
+
return isCursorStateVscdbPath(path) || adapterForPath(path) !== undefined;
|
|
6
|
+
}
|
|
7
|
+
function cursorSourceFromSession(session, index) {
|
|
8
|
+
if (session.turns.length === 0)
|
|
9
|
+
return null;
|
|
10
|
+
const sessionId = session.sessionId?.trim();
|
|
11
|
+
return {
|
|
12
|
+
agent: 'cursor',
|
|
13
|
+
label: sessionId ? `cursor-vscdb:${sessionId}` : `cursor-vscdb:${index + 1}`,
|
|
14
|
+
...(sessionId ? { sessionId } : {}),
|
|
15
|
+
turns: session.turns,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export function parseRuntimeSessionSources(path, readSource = (p) => readFileSync(p, 'utf8')) {
|
|
19
|
+
const absPath = resolve(path);
|
|
20
|
+
if (isCursorStateVscdbPath(absPath)) {
|
|
21
|
+
return parseCursorStateVscdb(absPath)
|
|
22
|
+
.map(cursorSourceFromSession)
|
|
23
|
+
.filter((source) => source !== null);
|
|
24
|
+
}
|
|
25
|
+
const adapter = adapterForPath(absPath);
|
|
26
|
+
if (!adapter)
|
|
27
|
+
return [];
|
|
28
|
+
return [{ agent: adapter.agent, label: adapter.agent, turns: adapter.parse(readSource(absPath)) }];
|
|
29
|
+
}
|