@evomap/evolver-cli 2.0.35 → 2.0.37

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/index.js CHANGED
@@ -1654,12 +1654,15 @@ export async function runInject(argv, deps = {}) {
1654
1654
  const ingestor = deps.ingestor ?? new events.Ingestor({ path: deps.eventsPath ?? events.rootEventsPath() });
1655
1655
  const review = deps.review ?? reviewLedgerForStore(store); // co-located with the store, not pinned to live dir
1656
1656
  const provenance = deps.provenance ?? provenanceStoreForStore(store); // co-located with the store, not pinned to live dir
1657
- const maxGenes = deps.maxGenes ?? 8;
1657
+ const maxGenes = process.env['EVOLVER_BENCHMARK_ID'] !== undefined ? Math.min(deps.maxGenes ?? 8, 8) : (deps.maxGenes ?? 8);
1658
1658
  const hardCap = deps.tokenBudgetHardCap ?? 8000;
1659
1659
  // Gene pool → injection candidates: the most recent TRUSTED + REVIEW-APPROVED local genes (bounded), rendered as
1660
1660
  // compact hint lines. The provenance gate keeps untrusted hub assets out until promotion; the review gate (A2a)
1661
1661
  // keeps auto-distilled UNPROVEN drafts out until approval.
1662
- const genes = await listApprovedGenes(store, review, maxGenes, provenance);
1662
+ let sourceQualifications;
1663
+ const genes = await listApprovedGenes(store, review, maxGenes, provenance, {
1664
+ onQualification: (receipts) => { sourceQualifications = receipts; },
1665
+ });
1663
1666
  const rendered = genes.map((g) => renderSessionGene(g, contentMode, hardCap * 4));
1664
1667
  const geneLines = rendered.map((gene) => gene.text);
1665
1668
  const geneIds = genes.map((g) => (typeof g['id'] === 'string' ? String(g['id']) : String(g.asset_id)));
@@ -1677,6 +1680,10 @@ export async function runInject(argv, deps = {}) {
1677
1680
  // readHookInput. Default (no flag, no seam) never touches stdin — so a plain `evolver inject session-start` and
1678
1681
  // the test suite can never block on a stdin read (the Windows CI hang this guards against).
1679
1682
  const sessionId = deps.sessionId ?? ((fromHookStdin || deps.readHookInput) ? await readHookSessionId(deps.readHookInput) : undefined);
1683
+ if (sourceQualifications && [sessionId, deps.cycleId].some((id) => id !== undefined && Buffer.byteLength(id, 'utf8') > 128)) {
1684
+ process.stderr.write('inject session-start: benchmark关联ID超过审计预算,未注入。\n');
1685
+ return 1;
1686
+ }
1680
1687
  const compose = (count) => {
1681
1688
  injectedInfo = undefined;
1682
1689
  return hooks.composeSessionStartWithRecap({ tokenBudgetHardCap: hardCap, preamble: SESSION_START_PREAMBLE }, { injectGenes: geneLines.slice(0, count), geneIds: geneIds.slice(0, count), successCount: summary.topGenes.length, summary }, {
@@ -1689,13 +1696,14 @@ export async function runInject(argv, deps = {}) {
1689
1696
  const content = rendered.slice(0, count).map((gene) => gene.content);
1690
1697
  return { ...injectedInfo, geneIds: geneIds.slice(0, count), contentSchema: 'session-gene-content.v1', content,
1691
1698
  omittedByBudget: rendered.length - count + content.filter((gene) => gene.omissionReason === 'budget').length,
1699
+ ...(sourceQualifications ? { sourceQualifications: sourceQualifications.slice(0, count) } : {}),
1692
1700
  };
1693
1701
  };
1694
1702
  let inj = compose(rendered.length);
1695
1703
  const tokenLimitedCount = inj.genes.length;
1696
1704
  let low = 0;
1697
1705
  let high = inj.genes.length;
1698
- // Find the largest whole-gene prefix whose content receipts fit
1706
+ // Find the largest whole-gene prefix whose content and qualification receipts fit
1699
1707
  // the actual writer envelope, before any prompt bytes reach the runtime.
1700
1708
  while (low < high) {
1701
1709
  const count = Math.ceil((low + high) / 2);
@@ -235,14 +235,19 @@ function localRecallFilesWithinBudget(store) {
235
235
  function yieldToEventLoop() {
236
236
  return new Promise((resolve) => setImmediate(resolve));
237
237
  }
238
- async function selectPromptGenes(prompt, store, review, provenance, maxGenes, budget) {
238
+ async function selectPromptGenes(prompt, store, review, provenance, maxGenes, budget, benchmark) {
239
239
  const tokenSegments = promptTokenSegments(prompt);
240
240
  const promptTokens = tokenSegments.flat();
241
241
  if (promptTokens.length === 0)
242
242
  return [];
243
243
  const promptIndex = buildPromptSequenceIndex(tokenSegments);
244
244
  const boundedPrompt = promptTokens.join(' ');
245
- const approved = await assetstore.listApprovedGenes(store, review, PROMPT_RECALL_SCAN_LIMIT, provenance);
245
+ const receipts = new Map();
246
+ const approved = await assetstore.listApprovedGenes(store, review, PROMPT_RECALL_SCAN_LIMIT, provenance, {
247
+ ...(benchmark ? { benchmark } : {}),
248
+ onQualification: (values) => { for (const receipt of values)
249
+ receipts.set(receipt.assetId, receipt); },
250
+ });
246
251
  if (selectionExpired(budget))
247
252
  return [];
248
253
  const ranked = [];
@@ -264,6 +269,7 @@ async function selectPromptGenes(prompt, store, review, provenance, maxGenes, bu
264
269
  literalHits,
265
270
  semanticScore,
266
271
  assetKey: String(gene.asset_id).slice(0, 128),
272
+ ...(receipts.has(gene.asset_id) ? { sourceQualification: receipts.get(gene.asset_id) } : {}),
267
273
  });
268
274
  }
269
275
  if ((index + 1) % PROMPT_RECALL_YIELD_EVERY_GENES === 0) {
@@ -277,7 +283,7 @@ async function selectPromptGenes(prompt, store, review, provenance, maxGenes, bu
277
283
  ranked.sort((left, right) => (right.literalHits - left.literalHits
278
284
  || right.semanticScore - left.semanticScore
279
285
  || left.assetKey.localeCompare(right.assetKey)));
280
- return ranked.slice(0, maxGenes);
286
+ return ranked.slice(0, benchmark ? Math.min(maxGenes, 8) : maxGenes);
281
287
  }
282
288
  function renderGeneLine(gene) {
283
289
  const id = (typeof gene['id'] === 'string' ? gene['id'] : String(gene.asset_id)).slice(0, 128);
@@ -334,6 +340,7 @@ function logPromptRecallSelections(genes, mode, sessionId, env, injectedLog) {
334
340
  attribution: 'correlational_local',
335
341
  origin: 'local',
336
342
  literal_hits: ranked.literalHits,
343
+ ...(ranked.sourceQualification ? assetstore.compactQualificationReceipts([ranked.sourceQualification]) : {}),
337
344
  },
338
345
  });
339
346
  }
@@ -401,7 +408,7 @@ export async function runPromptRecallHook(argv, deps = {}) {
401
408
  const review = deps.review ?? assetstore.reviewLedgerForStore(store);
402
409
  const provenance = deps.provenance ?? assetstore.provenanceStoreForStore(store);
403
410
  const timeoutMs = deps.selectionTimeoutMs ?? PROMPT_RECALL_SELECTION_TIMEOUT_MS;
404
- const ranked = await withSelectionBudget(timeoutMs, [], (budget) => selectPromptGenes(prompt, store, review, provenance, promptRecallMaxGenes(env), budget));
411
+ const ranked = await withSelectionBudget(timeoutMs, [], (budget) => selectPromptGenes(prompt, store, review, provenance, promptRecallMaxGenes(env), budget, assetstore.benchmarkContext(env['EVOLVER_BENCHMARK_ID'])));
405
412
  if (ranked.length > 0) {
406
413
  const rendered = renderPromptRecallContext(ranked);
407
414
  if (rendered.text) {
package/dist/recall.d.ts CHANGED
@@ -20,6 +20,8 @@ export declare function sessionIdFromTranscript(p: string): string | undefined;
20
20
  export declare function pickInjectEvent(evts: readonly events.ReportEvent[], sessionId?: string): events.ReportEvent | undefined;
21
21
  export declare function geneIdsOf(e: events.ReportEvent | undefined): string[];
22
22
  export declare function geneFromAsset(a: assetstore.AssetRecord): ops.GeneRecallInput;
23
+ /** 仅来源资格事件中的实际 canonical 引用保留版本身份,历史和独立手动参数仍按 logical ID 归因。 */
24
+ export declare function geneFromRecallSelection(asset: assetstore.AssetRecord, requestedId: string, inject?: events.ReportEvent): ops.GeneRecallInput | null;
23
25
  export declare function resolveGene(store: Pick<assetstore.AssetStoreProvider, 'get' | 'list'>, id: string): Promise<assetstore.AssetRecord | null>;
24
26
  export declare function runRecall(argv: readonly string[], deps?: RecallCliDeps): Promise<number>;
25
27
  /** Registry-shaped handler (argv -> exit code). */
package/dist/recall.js CHANGED
@@ -43,6 +43,17 @@ export function geneFromAsset(a) {
43
43
  const summary = typeof a['summary'] === 'string' ? a['summary'] : undefined;
44
44
  return { geneId, ...(strategy ? { strategy } : {}), ...(summary ? { summary } : {}) };
45
45
  }
46
+ /** 仅来源资格事件中的实际 canonical 引用保留版本身份,历史和独立手动参数仍按 logical ID 归因。 */
47
+ export function geneFromRecallSelection(asset, requestedId, inject) {
48
+ const canonicalReference = inject?.payload?.['sourceQualificationSchema'] === 'benchmark-source-references.v1'
49
+ && geneIdsOf(inject).includes(requestedId);
50
+ if (!canonicalReference)
51
+ return geneFromAsset(asset);
52
+ // 自定义 provider 或旧 logical-ID fallback 返回其他版本时,不能借用被注入资产的身份。
53
+ if (asset.asset_id !== requestedId)
54
+ return null;
55
+ return { ...geneFromAsset(asset), geneId: requestedId };
56
+ }
46
57
  // Resolve a --gene argument to its Gene asset, mirroring `evolver review`: an asset_id (sha256:…) hits the index
47
58
  // directly (guarded to type Gene, since asset_id is a content hash), while a LOGICAL id (the `gene-a` style id that
48
59
  // value.inject records in geneIds) falls back to a bounded Gene-only scan. Resolving via asset_id ALONE would report
@@ -83,6 +94,7 @@ export async function runRecall(argv, deps = {}) {
83
94
  const log = deps.log ?? ((s) => process.stdout.write(`${s}\n`));
84
95
  const err = deps.err ?? ((s) => process.stderr.write(`${s}\n`));
85
96
  const { transcript, geneIds, fromInject } = parseArgs(argv);
97
+ let selectedInject;
86
98
  // --from-inject: pull the geneIds off the most recent value.inject root_event so the operator does not have to
87
99
  // retype them (a semi-automatic step toward the auto-loop, which still needs the inject<->session key #205 to
88
100
  // pick the RIGHT inject for THIS transcript). Union with any explicit --gene; dedupe preserving order.
@@ -90,6 +102,7 @@ export async function runRecall(argv, deps = {}) {
90
102
  const evts = (deps.readEvents ?? events.readEvents)();
91
103
  const wantSession = transcript ? sessionIdFromTranscript(transcript) : undefined;
92
104
  const picked = pickInjectEvent(evts, wantSession);
105
+ selectedInject = picked;
93
106
  const fromEvent = geneIdsOf(picked);
94
107
  // Empty inject is fatal only when there is nothing else to run; with explicit --gene present, honour the union
95
108
  // and continue (just warn) rather than discarding the genes the operator typed.
@@ -142,7 +155,12 @@ export async function runRecall(argv, deps = {}) {
142
155
  err(`recall: gene not found in local store: ${id}`);
143
156
  continue;
144
157
  }
145
- genes.push(geneFromAsset(a));
158
+ const gene = geneFromRecallSelection(a, id, selectedInject);
159
+ if (!gene) {
160
+ err(`recall: injected gene identity mismatch: ${id}`);
161
+ continue;
162
+ }
163
+ genes.push(gene);
146
164
  }
147
165
  if (genes.length === 0) {
148
166
  err('recall: no resolvable genes');
@@ -0,0 +1,3 @@
1
+ import type { AssetTrustDeps } from './assetTrust.js';
2
+ /** CLI composition只拼接runtime证据与core策略;不执行冻结轨迹中的命令。 */
3
+ export declare function runReferenceAccessCommand(argv: readonly string[], deps: AssetTrustDeps): Promise<number>;
@@ -0,0 +1,232 @@
1
+ import { constants, closeSync, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
2
+ import { basename, resolve } from 'node:path';
3
+ import { assetstore, benchmark, events, hub } from '@evomap/evolver-core';
4
+ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
5
+ import { referenceToolPairs } from '@evomap/evolver-runtime-adapters';
6
+ const HASH = /^sha256:[a-f0-9]{64}$/;
7
+ const RAW_CALL_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
8
+ const replayCallId = (value) => `call:${benchmark.referenceDigest(value).slice(7)}`;
9
+ const INPUT_FAILURES = new Set([
10
+ 'env_file_unavailable',
11
+ 'invalid_arguments', 'invalid_reference_input', 'reference_input_changed', 'invalid_reference_manifest', 'reference_manifest_mismatch',
12
+ 'invalid_trajectory_digest', 'invalid_reference_bindings', 'invalid_reference_binding', 'reference_binding_mismatch',
13
+ 'duplicate_reference_binding', 'reference_asset_not_found', 'invalid_reference_pair', 'invalid_reference_events',
14
+ 'reference_call_collision', 'reference_tool_mismatch', 'reference_event_order', 'invalid_reference_line', 'reference_event_limit',
15
+ 'invalid_reference_call', 'invalid_reference_tool', 'reference_line_collision',
16
+ ]);
17
+ const USAGE = [
18
+ 'evolver asset-trust access replay --case <file> --manifest <file> --bindings <trusted-file> --policy <file> --run <id> [--events <journal>] [--asset-id <id>] [--json]',
19
+ 'evolver asset-trust access get --url <url> --policy <file> --run <id> --call <id> --events <journal> [--include-data] [--json]',
20
+ 'evolver asset-trust access read --path <file> --policy <file> --run <id> --call <id> --events <journal> [--include-data] [--json]',
21
+ 'replay默认只读并只输出摘要。bindings必须由宿主或operator独立复核,不能使用模型自报分类。',
22
+ 'get/read只控制本次操作,不隔离任意shell;--include-data显式返回base64原文,journal从不保存正文。',
23
+ '',
24
+ ].join('\n');
25
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
26
+ /** 单descriptor有界读取,禁止symlink、变化中的文件及宽松UTF-8解码。 */
27
+ function readJson(path, limit) {
28
+ const before = lstatSync(path);
29
+ if (!before.isFile() || before.isSymbolicLink() || before.size > limit)
30
+ throw new Error('invalid_reference_input');
31
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)
32
+ | (process.platform === 'win32' ? 0 : constants.O_NONBLOCK));
33
+ try {
34
+ const opened = fstatSync(fd);
35
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== before.size)
36
+ throw new Error('reference_input_changed');
37
+ const bytes = Buffer.alloc(opened.size);
38
+ let offset = 0;
39
+ while (offset < bytes.length) {
40
+ const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
41
+ if (!count)
42
+ throw new Error('reference_input_changed');
43
+ offset += count;
44
+ }
45
+ const after = fstatSync(fd);
46
+ const named = lstatSync(path);
47
+ if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs
48
+ || named.isSymbolicLink() || named.dev !== opened.dev || named.ino !== opened.ino)
49
+ throw new Error('reference_input_changed');
50
+ return { value: JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)), bytes, digest: benchmark.referenceDigest(bytes) };
51
+ }
52
+ finally {
53
+ closeSync(fd);
54
+ }
55
+ }
56
+ function argumentsFor(argv) {
57
+ const action = argv[0];
58
+ if (action !== 'replay' && action !== 'get' && action !== 'read')
59
+ throw new Error('invalid_arguments');
60
+ const allowed = action === 'replay' ? ['--case', '--manifest', '--bindings', '--policy', '--run', '--events', '--asset-id']
61
+ : ['--policy', '--run', '--call', '--events', action === 'get' ? '--url' : '--path'];
62
+ const flags = new Map();
63
+ const seen = new Set();
64
+ let includeData = false;
65
+ for (let i = 1; i < argv.length; i++) {
66
+ const key = argv[i];
67
+ if (seen.has(key))
68
+ throw new Error('invalid_arguments');
69
+ seen.add(key);
70
+ if (key === '--json')
71
+ continue;
72
+ if (key === '--include-data' && action !== 'replay') {
73
+ includeData = true;
74
+ continue;
75
+ }
76
+ if (!allowed.includes(key) || !argv[i + 1] || argv[i + 1].startsWith('--'))
77
+ throw new Error('invalid_arguments');
78
+ flags.set(key, argv[++i]);
79
+ }
80
+ const required = action === 'replay' ? ['--case', '--manifest', '--bindings', '--policy', '--run'] : allowed;
81
+ if (required.some((key) => !flags.has(key)) || !benchmark.referenceId(flags.get('--run'))
82
+ || (action !== 'replay' && !benchmark.referenceId(flags.get('--call')))
83
+ || (flags.has('--asset-id') && (!flags.has('--events') || !HASH.test(flags.get('--asset-id')))))
84
+ throw new Error('invalid_arguments');
85
+ return { action, flags, includeData };
86
+ }
87
+ function replayInput(flags) {
88
+ const source = readJson(flags.get('--case'), 4 * 1024 * 1024);
89
+ const manifest = object(readJson(flags.get('--manifest'), 256 * 1024).value);
90
+ const rows = manifest?.['files'];
91
+ if (!Array.isArray(rows) || rows.length > 512)
92
+ throw new Error('invalid_reference_manifest');
93
+ const name = basename(flags.get('--case'));
94
+ const matches = rows.map(object).filter((row) => row?.['name'] === name || row?.['path'] === name);
95
+ if (matches.length !== 1 || matches[0]?.['bytes'] !== source.bytes.length
96
+ || `sha256:${String(matches[0]?.['sha256'])}` !== source.digest)
97
+ throw new Error('reference_manifest_mismatch');
98
+ const input = object(source.value);
99
+ const hashes = object(input?.['source_hashes']);
100
+ const trajectoryDigest = `sha256:${String(hashes?.['pi_sha256'])}`;
101
+ if (!HASH.test(trajectoryDigest))
102
+ throw new Error('invalid_trajectory_digest');
103
+ const trusted = object(readJson(flags.get('--bindings'), 512 * 1024).value);
104
+ if (trusted?.['schema'] !== 'benchmark-reference-bindings.v1' || trusted['caseDigest'] !== source.digest
105
+ || trusted['trajectoryDigest'] !== trajectoryDigest || !benchmark.referenceId(trusted['reviewer'])
106
+ || hub.redactString(trusted['reviewer']) !== trusted['reviewer']
107
+ || !Array.isArray(trusted['bindings']) || trusted['bindings'].length > 256)
108
+ throw new Error('invalid_reference_bindings');
109
+ const pairs = referenceToolPairs(source.value);
110
+ const byCall = new Map(pairs.map((pair) => [pair.callId, pair]));
111
+ const seen = new Set();
112
+ const bindings = trusted['bindings'].map((value) => {
113
+ const row = object(value);
114
+ const resource = object(row?.['resource']);
115
+ if (!row || typeof row['callId'] !== 'string' || !RAW_CALL_ID.test(row['callId']) || row['trajectoryDigest'] !== trajectoryDigest
116
+ || typeof row['eventDigest'] !== 'string' || !HASH.test(row['eventDigest'])
117
+ || typeof row['resultDigest'] !== 'string' || !HASH.test(row['resultDigest'])
118
+ || (row['outcome'] !== 'read' && row['outcome'] !== 'failed')
119
+ || (resource?.['type'] !== 'url' && resource?.['type'] !== 'file') || typeof resource['value'] !== 'string')
120
+ throw new Error('invalid_reference_binding');
121
+ const binding = { callId: row['callId'], trajectoryDigest, eventDigest: row['eventDigest'], resultDigest: row['resultDigest'],
122
+ resource: { type: resource['type'], value: resource['value'] }, outcome: row['outcome'] };
123
+ const pair = byCall.get(binding.callId);
124
+ if (!pair?.complete || pair.eventDigest !== binding.eventDigest || pair.resultDigest !== binding.resultDigest)
125
+ throw new Error('reference_binding_mismatch');
126
+ const key = `${binding.callId}:${benchmark.referenceResourceDigest(binding.resource)}`;
127
+ if (seen.has(key))
128
+ throw new Error('duplicate_reference_binding');
129
+ seen.add(key);
130
+ return binding;
131
+ });
132
+ // 原始toolCallId可能是高熵opaque标识。先在私有输入内精确配对,再散列公开身份;不放宽core的脱敏门禁。
133
+ return { caseDigest: source.digest, trajectoryDigest,
134
+ pairs: pairs.map((pair) => ({ ...pair, callId: replayCallId(pair.callId) })),
135
+ bindings: bindings.map((binding) => ({ ...binding, callId: replayCallId(binding.callId) })) };
136
+ }
137
+ /** CLI composition只拼接runtime证据与core策略;不执行冻结轨迹中的命令。 */
138
+ export async function runReferenceAccessCommand(argv, deps) {
139
+ const output = deps.stdout ?? ((text) => { process.stdout.write(text); });
140
+ if (argv.includes('--help') || argv.includes('-h')) {
141
+ output(USAGE);
142
+ return 0;
143
+ }
144
+ let controller;
145
+ let retryInitializationCleanup;
146
+ let journalRequested = false;
147
+ let journalMayContainEvents = false;
148
+ let result;
149
+ let code = 0;
150
+ try {
151
+ const { action, flags, includeData } = argumentsFor(argv);
152
+ journalRequested = flags.has('--events');
153
+ const env = deps.env ?? process.env;
154
+ if (loadEnvFileFromEnv(env).error)
155
+ throw new Error('env_file_unavailable');
156
+ const policy = benchmark.parseReferencePolicy(readJson(flags.get('--policy'), 128 * 1024).value);
157
+ const runId = flags.get('--run');
158
+ if (action === 'replay') {
159
+ const input = replayInput(flags);
160
+ const observations = [];
161
+ for (const pair of input.pairs) {
162
+ const bindings = input.bindings.filter((binding) => binding.callId === pair.callId);
163
+ if (!bindings.length)
164
+ observations.push(benchmark.observeReferencePair(policy, input.trajectoryDigest, pair));
165
+ for (const binding of bindings)
166
+ observations.push(benchmark.observeReferencePair(policy, input.trajectoryDigest, pair, binding));
167
+ }
168
+ let qualification;
169
+ if (journalRequested) {
170
+ journalMayContainEvents = true;
171
+ controller = new benchmark.ReferenceAccessController({ policy, runId, eventsPath: resolve(flags.get('--events')), mode: 'observe' });
172
+ for (const binding of input.bindings) {
173
+ const pair = input.pairs.find((item) => item.callId === binding.callId);
174
+ await controller.observe(input.trajectoryDigest, pair, binding);
175
+ }
176
+ if (flags.has('--asset-id')) {
177
+ const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir(env));
178
+ const asset = await store.get(flags.get('--asset-id'));
179
+ if (!asset || asset.asset_id !== flags.get('--asset-id'))
180
+ throw new Error('reference_asset_not_found');
181
+ qualification = controller.qualification(asset, input.trajectoryDigest);
182
+ }
183
+ }
184
+ result = { ok: true, schema: 'benchmark-reference-replay.v1', benchmarkId: policy.benchmarkId, runId,
185
+ policyDigest: benchmark.referenceDigest(JSON.stringify(policy)), caseDigest: input.caseDigest, trajectoryDigest: input.trajectoryDigest,
186
+ sourceArchiveVerified: false, originalReward: 'unchanged', bindingsTrust: 'operator-reviewed',
187
+ callIdentitySchema: 'benchmark-reference-call-id.v1',
188
+ capabilities: { mode: 'observe', httpGet: false, fileRead: false, arbitraryProcessContainment: false, observationCoverage: 'partial' },
189
+ sourceStatus: observations.some((item) => item.outcome === 'read' && benchmark.forbiddenReference(item.kind)) ? 'ineligible' : 'unknown',
190
+ pairedCalls: input.pairs.length, boundResources: input.bindings.length, pairs: input.pairs, observations,
191
+ journalRequested, journaledResources: journalRequested ? input.bindings.length : 0,
192
+ ...(qualification ? { qualification } : {}) };
193
+ }
194
+ else {
195
+ journalMayContainEvents = true;
196
+ controller = new benchmark.ReferenceAccessController({ policy, runId, eventsPath: resolve(flags.get('--events')), mode: 'enforce' });
197
+ const accessed = action === 'get' ? await controller.get(flags.get('--call'), flags.get('--url'))
198
+ : await controller.readFile(flags.get('--call'), resolve(flags.get('--path')));
199
+ result = { ok: true, schema: 'benchmark-reference-read.v1', capabilities: controller.capabilities(),
200
+ receipt: accessed.receipt, bytes: accessed.data.length, journalRequested,
201
+ ...(includeData ? { encoding: 'base64', data: Buffer.from(accessed.data).toString('base64') } : {}) };
202
+ }
203
+ }
204
+ catch (error) {
205
+ code = 1;
206
+ if (error instanceof benchmark.ReferenceAccessError)
207
+ retryInitializationCleanup = error.retryCleanup;
208
+ const reason = error instanceof benchmark.ReferenceAccessError ? error.code
209
+ : error instanceof Error && INPUT_FAILURES.has(error.message) ? error.message : 'reference_access_failed';
210
+ result = { ok: false, group: 'asset-trust', reason,
211
+ journalRequested, journalMayContainEvents,
212
+ ...(error instanceof benchmark.ReferenceAccessError && error.operationCode ? { operationReason: error.operationCode } : {}),
213
+ ...(error instanceof benchmark.ReferenceAccessError && error.receipt ? { receipt: error.receipt } : {}) };
214
+ }
215
+ if (controller || retryInitializationCleanup) {
216
+ try {
217
+ if (controller)
218
+ await controller.close();
219
+ else
220
+ await retryInitializationCleanup();
221
+ }
222
+ catch {
223
+ code = 1;
224
+ const { data: _data, encoding: _encoding, ...metadata } = result;
225
+ result = { ...metadata, ok: false, group: 'asset-trust', journalMayContainEvents: true,
226
+ reason: typeof metadata['reason'] === 'string' ? metadata['reason'] : 'reference_release_failed',
227
+ cleanupReason: 'reference_release_failed', cleanupPending: true, operationOk: metadata['ok'] };
228
+ }
229
+ }
230
+ output(`${JSON.stringify(result)}\n`);
231
+ return code;
232
+ }
@@ -1,6 +1,6 @@
1
1
  import { assetstore } from '@evomap/evolver-core';
2
2
  export declare const reviewLedgerForStore: typeof assetstore.reviewLedgerForStore;
3
3
  export declare const provenanceStoreForStore: typeof assetstore.provenanceStoreForStore;
4
- export declare const listApprovedGenes: typeof assetstore.listApprovedGenes;
4
+ export declare function listApprovedGenes(store: assetstore.AssetStoreProvider, review: assetstore.ReviewLedger, maxGenes: number, provenance?: assetstore.ProvenanceStore, options?: assetstore.SourceSelectionOptions): Promise<assetstore.AssetRecord[]>;
5
5
  export declare const pendingReviewRecords: typeof assetstore.pendingReviewRecords;
6
6
  export declare const pendingGeneReviewRecords: typeof assetstore.pendingGeneReviewRecords;
@@ -3,6 +3,17 @@
3
3
  import { assetstore } from '@evomap/evolver-core';
4
4
  export const reviewLedgerForStore = assetstore.reviewLedgerForStore;
5
5
  export const provenanceStoreForStore = assetstore.provenanceStoreForStore;
6
- export const listApprovedGenes = assetstore.listApprovedGenes;
6
+ export async function listApprovedGenes(store, review, maxGenes, provenance = provenanceStoreForStore(store), options = {}) {
7
+ // 调用方绑定的 context 优先;仅未传 context 时使用 CLI 的进程默认值。
8
+ const benchmark = options.benchmark === undefined
9
+ ? assetstore.benchmarkContext(process.env['EVOLVER_BENCHMARK_ID'])
10
+ : assetstore.benchmarkContext(options.benchmark.benchmarkId);
11
+ if (options.benchmark !== undefined && !benchmark)
12
+ throw new Error('invalid_benchmark_id');
13
+ if (benchmark && (!Number.isSafeInteger(maxGenes) || maxGenes < 1))
14
+ throw new Error('invalid_benchmark_gene_limit');
15
+ // Cursor与SessionStart共享八条收据预算;不改变普通生产模式的调用方上限。
16
+ return assetstore.listApprovedGenes(store, review, benchmark ? Math.min(maxGenes, 8) : maxGenes, provenance, { ...options, ...(benchmark ? { benchmark } : {}) });
17
+ }
7
18
  export const pendingReviewRecords = assetstore.pendingReviewRecords;
8
19
  export const pendingGeneReviewRecords = assetstore.pendingGeneReviewRecords;
@@ -0,0 +1,2 @@
1
+ import type { AssetTrustDeps } from './assetTrust.js';
2
+ export declare function runSourceQualificationCommand(argv: readonly string[], deps: AssetTrustDeps, actorId: (env: Record<string, string | undefined>) => string): Promise<number>;
@@ -0,0 +1,120 @@
1
+ import { constants, closeSync, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
2
+ import { assetstore, events, hub, wire } from '@evomap/evolver-core';
3
+ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
4
+ const USAGE = 'evolver asset-trust qualify <asset_id> --evidence <file> --reason <text> [--exception <reason>] [--json]\n'
5
+ + 'evolver asset-trust qualification <asset_id> --benchmark <id> [--evidence-digest <sha256>] [--json]\n';
6
+ /** 有界、单descriptor读取;不执行证据中的命令,不跟随symlink或读取增长中的文件。 */
7
+ function readEvidence(path) {
8
+ const before = lstatSync(path);
9
+ if (!before.isFile() || before.isSymbolicLink() || before.size > 128 * 1024)
10
+ throw new Error('invalid_evidence_file');
11
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
12
+ try {
13
+ const opened = fstatSync(fd);
14
+ if (!opened.isFile() || before.dev !== opened.dev || before.ino !== opened.ino || before.size !== opened.size)
15
+ throw new Error('evidence_changed');
16
+ const bytes = Buffer.alloc(opened.size);
17
+ let offset = 0;
18
+ while (offset < bytes.length) {
19
+ const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
20
+ if (count === 0)
21
+ throw new Error('evidence_changed');
22
+ offset += count;
23
+ }
24
+ const after = fstatSync(fd);
25
+ const named = lstatSync(path);
26
+ if (opened.size !== after.size || opened.mtimeMs !== after.mtimeMs || opened.ctimeMs !== after.ctimeMs
27
+ || named.isSymbolicLink() || named.dev !== opened.dev || named.ino !== opened.ino)
28
+ throw new Error('evidence_changed');
29
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
30
+ }
31
+ finally {
32
+ closeSync(fd);
33
+ }
34
+ }
35
+ export async function runSourceQualificationCommand(argv, deps, actorId) {
36
+ const output = deps.stdout ?? ((text) => { process.stdout.write(text); });
37
+ if (argv.includes('--help') || argv.includes('-h')) {
38
+ output(USAGE);
39
+ return 0;
40
+ }
41
+ const fail = (reason, persisted = false) => {
42
+ output(`${JSON.stringify({ ok: false, group: 'asset-trust', reason, persisted })}\n`);
43
+ return 1;
44
+ };
45
+ const action = argv[0];
46
+ const assetId = argv[1];
47
+ if ((action !== 'qualify' && action !== 'qualification') || !assetId || !/^sha256:[a-f0-9]{64}$/.test(assetId))
48
+ return fail('invalid_arguments');
49
+ const flags = new Map();
50
+ for (let index = 2; index < argv.length; index++) {
51
+ const flag = argv[index];
52
+ if (flag === '--json')
53
+ continue;
54
+ if (!['--evidence', '--reason', '--exception', '--benchmark', '--evidence-digest'].includes(flag) || flags.has(flag)
55
+ || !argv[index + 1] || argv[index + 1].startsWith('--'))
56
+ return fail('invalid_arguments');
57
+ flags.set(flag, argv[++index]);
58
+ }
59
+ if (action === 'qualify' && (!flags.has('--evidence') || !flags.has('--reason') || flags.has('--benchmark') || flags.has('--evidence-digest')))
60
+ return fail('invalid_arguments');
61
+ if (action === 'qualification' && (!flags.has('--benchmark') || [...flags.keys()].some((key) => key !== '--benchmark' && key !== '--evidence-digest')))
62
+ return fail('invalid_arguments');
63
+ if (flags.has('--evidence-digest') && !/^sha256:[a-f0-9]{64}$/.test(flags.get('--evidence-digest')))
64
+ return fail('invalid_arguments');
65
+ let persisted = false;
66
+ try {
67
+ const env = deps.env ?? process.env;
68
+ if (loadEnvFileFromEnv(env).error)
69
+ return fail('env_file_unavailable');
70
+ const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
71
+ if (!(store instanceof assetstore.LocalJsonlProvider) && !deps.provenance)
72
+ return fail('provenance_required');
73
+ const provenance = deps.provenance ?? assetstore.provenanceStoreForStore(store);
74
+ const asset = await store.get(assetId);
75
+ if (!asset || asset.asset_id !== assetId)
76
+ return fail('asset_not_found');
77
+ if (action === 'qualification') {
78
+ const context = assetstore.benchmarkContext(flags.get('--benchmark'));
79
+ const record = provenance.get(assetId);
80
+ output(`${JSON.stringify({ ok: true, assetId, benchmarkId: context.benchmarkId,
81
+ decision: assetstore.assessSourceEligibility(asset, record, context),
82
+ qualification: record?.sourceQualifications?.find((item) => item.benchmarkId === context.benchmarkId) ?? null,
83
+ ...(flags.has('--evidence-digest') ? { historicalQualifications: provenance.qualificationHistory(assetId, context.benchmarkId, flags.get('--evidence-digest')) } : {}) })}\n`);
84
+ return 0;
85
+ }
86
+ const request = assetstore.parseSourceQualificationRequest(readEvidence(flags.get('--evidence')));
87
+ if (!request || request.assetId !== assetId || request.assetContentId !== wire.computeAssetId(asset))
88
+ return fail('evidence_asset_mismatch');
89
+ // The validated benchmark ID is public policy metadata, not a credential. Keep every other env check.
90
+ const leakCheckEnv = { ...env, EVOLVER_BENCHMARK_ID: undefined };
91
+ const reason = flags.get('--reason');
92
+ const exceptionReason = flags.get('--exception');
93
+ // 决策理由会进入sidecar、审计或输出;直接检查原字符串,避免JSON转义遮住环境秘密。
94
+ // core仍负责metadata校验和资格判定,这里不改写理由,也不豁免其他环境键的同值。
95
+ if (hub.fullLeakCheck(JSON.stringify(request), leakCheckEnv).found
96
+ || [reason, exceptionReason].some((value) => value !== undefined && hub.fullLeakCheck(value, leakCheckEnv).found)) {
97
+ return fail('unsafe_source_evidence');
98
+ }
99
+ const qualification = provenance.qualify(request, actorId(env), reason, exceptionReason);
100
+ persisted = true;
101
+ const ingestor = deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() });
102
+ await ingestor.ingest({
103
+ type: 'actor.human.source.qualify',
104
+ actor: { kind: 'human', id: qualification.by },
105
+ human: { title: '记录benchmark来源资格', why: qualification.reason },
106
+ payload: { assetId, benchmarkId: qualification.benchmarkId, state: qualification.state,
107
+ evidenceDigest: qualification.evidenceDigest, trajectoryDigest: qualification.trajectoryDigest,
108
+ runId: qualification.runId, exception: qualification.exception !== undefined },
109
+ });
110
+ output(`${JSON.stringify({ ok: true, persisted, qualification })}\n`);
111
+ return 0;
112
+ }
113
+ catch (error) {
114
+ if (!persisted && error instanceof assetstore.SourceQualificationProvenanceRequiredError) {
115
+ return fail('source_qualification_provenance_required');
116
+ }
117
+ // sidecar已经落盘而audit失败时不得谎称回滚;operator可用qualification命令读取权威结果。
118
+ return fail(persisted ? 'qualification_saved_audit_failed' : 'source_qualification_failed', persisted);
119
+ }
120
+ }