@evomap/evolver-cli 2.0.36 → 2.0.38

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.
Files changed (40) hide show
  1. package/dist/antiGeneRollout.d.ts +2 -0
  2. package/dist/antiGeneRollout.js +21 -3
  3. package/dist/assetTrust.js +9 -0
  4. package/dist/atpAutoDeliver.d.ts +10 -0
  5. package/dist/atpAutoDeliver.js +28 -1
  6. package/dist/autoRecall.js +8 -4
  7. package/dist/autoexec.d.ts +15 -0
  8. package/dist/autoexec.js +148 -7
  9. package/dist/autoexecConfig.d.ts +1 -1
  10. package/dist/autoexecConfig.js +1 -1
  11. package/dist/cliContracts.d.ts +7 -2
  12. package/dist/cliContracts.js +97 -13
  13. package/dist/cursorRewrite.d.ts +6 -0
  14. package/dist/cursorRewrite.js +64 -6
  15. package/dist/cycleConsumer.js +1 -0
  16. package/dist/index.js +11 -3
  17. package/dist/localPublishBinding.d.ts +25 -0
  18. package/dist/localPublishBinding.js +139 -0
  19. package/dist/promptRecallHook.js +86 -10
  20. package/dist/recall.d.ts +2 -0
  21. package/dist/recall.js +19 -1
  22. package/dist/recipe.d.ts +5 -1
  23. package/dist/recipe.js +123 -42
  24. package/dist/referenceAccess.d.ts +3 -0
  25. package/dist/referenceAccess.js +232 -0
  26. package/dist/referencePublish.d.ts +4 -0
  27. package/dist/referencePublish.js +40 -0
  28. package/dist/requiredSandboxValidation.js +6 -1
  29. package/dist/reviewFilter.d.ts +1 -1
  30. package/dist/reviewFilter.js +12 -1
  31. package/dist/sourceQualification.d.ts +2 -0
  32. package/dist/sourceQualification.js +120 -0
  33. package/dist/taskCommitments.d.ts +135 -0
  34. package/dist/taskCommitments.js +492 -0
  35. package/dist/taskReceiver.d.ts +151 -0
  36. package/dist/taskReceiver.js +459 -0
  37. package/dist/thesis.d.ts +3 -0
  38. package/dist/thesis.js +122 -100
  39. package/dist/workflowRuntime.js +13 -2
  40. package/package.json +7 -7
@@ -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
+ }
@@ -0,0 +1,4 @@
1
+ import { assetstore, reference } from '@evomap/evolver-core';
2
+ export declare function hasReferenceEvidenceMode(assets: readonly assetstore.AssetRecord[]): boolean;
3
+ export declare function validateReferencePublishBundle(assets: readonly assetstore.AssetRecord[]): reference.ReferencePair;
4
+ export declare function validReferenceReceipt(body: unknown, assets: readonly assetstore.AssetRecord[], dryRun: boolean): boolean;
@@ -0,0 +1,40 @@
1
+ import { assetstore, hub, reference, wire } from '@evomap/evolver-core';
2
+ export function hasReferenceEvidenceMode(assets) {
3
+ return assets.some((asset) => asset.type === 'Capsule' && asset['evidence_mode'] !== undefined);
4
+ }
5
+ export function validateReferencePublishBundle(assets) {
6
+ if (assets.length !== 2)
7
+ throw new Error('reference_pair_required');
8
+ const pair = reference.decodeReferencePair({
9
+ gene: assets.find((asset) => asset.type === 'Gene'),
10
+ capsule: assets.find((asset) => asset.type === 'Capsule'),
11
+ });
12
+ if (hub.requiresPublishBinding(assets))
13
+ throw new Error('reference_execution_claim_forbidden');
14
+ for (const asset of assets) {
15
+ if (wire.canonicalize(hub.sanitizeAsset(asset)) !== wire.canonicalize(asset)) {
16
+ throw new Error('reference_sanitization_would_change_asset');
17
+ }
18
+ }
19
+ return pair;
20
+ }
21
+ export function validReferenceReceipt(body, assets, dryRun) {
22
+ if (!body || typeof body !== 'object' || Array.isArray(body))
23
+ return false;
24
+ const envelope = body;
25
+ const value = envelope['payload'] ?? envelope;
26
+ if (!value || typeof value !== 'object' || Array.isArray(value))
27
+ return false;
28
+ const payload = value;
29
+ const pair = validateReferencePublishBundle(assets);
30
+ const status = dryRun ? 'validated_reference' : 'stored_reference';
31
+ return payload['decision'] === 'accept' && payload['valid'] === true
32
+ && payload['reason'] === status && payload['status'] === status
33
+ && payload['dry_run'] === dryRun && payload['credit_reward'] === 0
34
+ && payload['evidence_mode'] === 'reference_only'
35
+ && Object.keys(reference.REFERENCE_ELIGIBILITY).every((key) => payload[key] === false)
36
+ && payload['gene_asset_id'] === pair.gene.asset_id
37
+ && payload['capsule_asset_id'] === pair.capsule.asset_id
38
+ && payload['asset_id'] === pair.capsule.asset_id
39
+ && payload['bundle_id'] === reference.referenceBundleId(pair);
40
+ }
@@ -17,10 +17,15 @@ export async function runRequiredSandboxedValidation(commands, cwd, options = {}
17
17
  })),
18
18
  skipped: [],
19
19
  isolated: false,
20
+ isolationTier: 'none',
20
21
  };
21
22
  }
22
23
  const safeCommands = sanitizedPlan.map((command) => command.value);
23
- const result = await runner(safeCommands, cwd, { ...options, requireIsolation: true });
24
+ // AutoExec、distill 与 workflow 共用此入口。默认接受 no-network 的独立根、只读源码和断网边界,
25
+ // 不要求宿主能够只读重挂整棵文件系统或提供聚合 cgroup 限额。调用方明确要求 read-only 时不能降档;
26
+ // 实际采用的档位由 core 回执报告,不能用这里的最低要求代替。无效的运行时值原样交给 core 拒绝。
27
+ const minimumIsolation = options.minimumIsolation === undefined ? 'no-network' : options.minimumIsolation;
28
+ const result = await runner(safeCommands, cwd, { ...options, requireIsolation: true, minimumIsolation });
24
29
  const sanitized = verify.sanitizeExecutionPayload(result);
25
30
  if (!sanitized.blocked)
26
31
  return sanitized.value;
@@ -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
+ }
@@ -0,0 +1,135 @@
1
+ import { AtpHubClient } from '@evomap/evolver-adapter-public';
2
+ /**
3
+ * A claim is a promise, and this file is where the promises live: the execute-queue entry a
4
+ * claimed task becomes, the ledger of what is still owed, and the wiring that keeps or
5
+ * re-files each debt. Choosing which task to take is the receiver's job, not this one's.
6
+ */
7
+ /** The execute-queue record a claimed Hub task becomes. */
8
+ export interface QueueTask {
9
+ id: string;
10
+ hubTaskId: string;
11
+ /** Which filing of this queue id this is. Tells a late result from the current one. */
12
+ generation: string;
13
+ repo: string;
14
+ target: string;
15
+ expectedEffect: string;
16
+ signals: string[];
17
+ commitmentDeadline?: string;
18
+ }
19
+ export interface QueueRetryResult {
20
+ retried: number;
21
+ queued: number;
22
+ pending: number;
23
+ /** Claims let go of: the commitment ran out, or the queue name never came free. */
24
+ dropped: number;
25
+ }
26
+ export interface CompletionRetryResult {
27
+ retried: number;
28
+ completed: number;
29
+ abandoned: number;
30
+ pending: number;
31
+ /** Outcomes the ledger would not take. The next run will see a stale picture. */
32
+ unrecorded: number;
33
+ /** Deliveries given up on. They are gone from the ledger, so they must be said out loud. */
34
+ abandonedTasks: Array<{
35
+ taskId: string;
36
+ resultAssetId: string;
37
+ lastError: string;
38
+ }>;
39
+ }
40
+ export interface CompletedTask {
41
+ /** The Hub was told, but the ledger would not take the update. The next run sees stale state. */
42
+ unrecorded?: boolean;
43
+ taskId: string;
44
+ completed: boolean;
45
+ error?: string;
46
+ /** The report could not be delivered and is now owed to the Hub on a later beat. */
47
+ pending?: boolean;
48
+ }
49
+ export interface PendingCompletion {
50
+ /** Which filing this debt belongs to. A late report from an earlier one is not it. */
51
+ generation?: string;
52
+ taskId: string;
53
+ resultAssetId: string;
54
+ attempts: number;
55
+ nextAttemptMs: number;
56
+ lastError?: string;
57
+ }
58
+ export interface PendingClaim {
59
+ taskId: string;
60
+ queueTask: QueueTask;
61
+ attempts: number;
62
+ lastError?: string;
63
+ }
64
+ /** A claim this node holds, keyed by the execute-queue id it was filed under. */
65
+ export interface OwnedClaim {
66
+ queueTaskId: string;
67
+ hubTaskId: string;
68
+ generation: string;
69
+ commitmentDeadline?: string;
70
+ }
71
+ export interface PendingCompletionLedger {
72
+ version: 1;
73
+ pending: Record<string, PendingCompletion>;
74
+ /** Claims the Hub granted that never reached the execute queue. */
75
+ unqueued?: Record<string, PendingClaim>;
76
+ /**
77
+ * Queue ids this receiver really claimed from the Hub. The `hub-` prefix is only a
78
+ * naming convention — a local task is free to use it — so the register, not the id,
79
+ * is what says a queue entry is remote work under a commitment.
80
+ */
81
+ owned?: Record<string, OwnedClaim>;
82
+ }
83
+ export declare const COMPLETION_LEDGER_FILENAME = "task-complete-pending.json";
84
+ export declare function completionLedgerPath(env?: NodeJS.ProcessEnv): string;
85
+ export declare function readCompletionLedger(path: string): PendingCompletionLedger;
86
+ export declare function rememberUnqueued(path: string, queueTask: QueueTask, error: string): void;
87
+ /** Queue ids the receiver writes carry this prefix, so the loop can tell hub work apart. */
88
+ export declare const HUB_QUEUE_PREFIX = "hub-";
89
+ /** A task id becomes a filename, so it may only be what a filename may safely be. */
90
+ /** The queue entry already under this id, or null when there is none we can read. */
91
+ export declare function defaultReadQueueTask(dir: string, id: string): QueueTask | null;
92
+ export declare function defaultWriteQueueTask(dir: string, task: QueueTask): void;
93
+ export declare function defaultRemoveQueueTask(dir: string, id: string): void;
94
+ type FileOutcome = 'written' | 'name_taken' | 'unrecorded';
95
+ /**
96
+ * File a claimed task under its queue id. An `EEXIST` is only "an earlier beat already did
97
+ * this" when the register says that queue id is ours; otherwise the name belongs to a local
98
+ * task, and treating the collision as success would hand its capsule to the Hub.
99
+ */
100
+ export declare function fileClaim(deps: CommitmentDeps, queueDir: string, claim: QueueTask): FileOutcome;
101
+ /**
102
+ * Wire a receive pass into the resident loop. It stays off without a node
103
+ * identity or an allowlisted repo: claiming a task this daemon cannot execute
104
+ * is a promise to the Hub we would break.
105
+ */
106
+ /** What a receiver can do about promises already made, on or off. */
107
+ export interface CommitmentWiring {
108
+ /**
109
+ * Report a finished task back to the Hub. A claim is a promise; the Hub only
110
+ * learns it was kept when the produced asset comes back.
111
+ */
112
+ complete: (taskId: string, resultAssetId: string, generation?: string) => Promise<CompletedTask>;
113
+ /** Re-send reports the Hub never acknowledged. Due entries only, oldest backoff first. */
114
+ retryCompletions: () => Promise<CompletionRetryResult>;
115
+ /** Re-file claims that never reached the execute queue. The claim is already spent. */
116
+ retryQueueWrites: () => Promise<QueueRetryResult>;
117
+ /**
118
+ * The Hub claim behind an execute-queue id, or null when that id is not remote work.
119
+ * A local task is free to be named `hub-anything`; only a registered claim is ours.
120
+ */
121
+ claimFor: (queueTaskId: string) => OwnedClaim | null;
122
+ }
123
+ export interface CommitmentDeps {
124
+ read?: (dir: string, id: string) => QueueTask | null;
125
+ ledgerPath: string;
126
+ now: () => number;
127
+ queueDir?: string;
128
+ write: (dir: string, task: QueueTask) => void;
129
+ remove?: (dir: string, id: string) => void;
130
+ }
131
+ export declare function unsentCommitments(ledgerPath: string, now: () => number): CommitmentWiring;
132
+ export declare function liveCommitments(client: AtpHubClient, deps: CommitmentDeps): CommitmentWiring;
133
+ /** The Hub task id behind an execute-queue id, or null when the task is local. */
134
+ export declare function hubTaskIdOf(queueTaskId: string): string | null;
135
+ export {};