@evomap/evolver-cli 2.0.0-beta.2 → 2.0.0-beta.22

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 (124) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.d.ts +6 -0
  4. package/dist/assetHealth.js +107 -0
  5. package/dist/assetRepair.d.ts +24 -0
  6. package/dist/assetRepair.js +172 -0
  7. package/dist/assetSidecarRecovery.d.ts +14 -0
  8. package/dist/assetSidecarRecovery.js +171 -0
  9. package/dist/assetTrust.d.ts +24 -0
  10. package/dist/assetTrust.js +231 -0
  11. package/dist/atp.d.ts +10 -5
  12. package/dist/atp.js +119 -26
  13. package/dist/atpAutoBuyer.d.ts +120 -0
  14. package/dist/atpAutoBuyer.js +814 -0
  15. package/dist/atpAutoDeliver.js +2 -2
  16. package/dist/autoDistillAntiGene.js +7 -5
  17. package/dist/autoDistillLlm.d.ts +26 -0
  18. package/dist/autoDistillLlm.js +119 -22
  19. package/dist/autoDistillTranscript.js +3 -2
  20. package/dist/autoexec.d.ts +111 -24
  21. package/dist/autoexec.js +887 -120
  22. package/dist/autoexecConfig.d.ts +10 -0
  23. package/dist/autoexecConfig.js +69 -0
  24. package/dist/cli.js +13 -0
  25. package/dist/cliContracts.d.ts +33 -2
  26. package/dist/cliContracts.js +818 -78
  27. package/dist/commandCatalog.d.ts +72 -0
  28. package/dist/commandCatalog.js +120 -0
  29. package/dist/commands.d.ts +1 -0
  30. package/dist/commands.js +1 -0
  31. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  32. package/dist/curriculumCapabilityGaps.js +24 -0
  33. package/dist/cycleConsumer.d.ts +17 -2
  34. package/dist/cycleConsumer.js +374 -50
  35. package/dist/dashboard.d.ts +13 -1
  36. package/dist/dashboard.js +235 -18
  37. package/dist/dispatch.d.ts +9 -2
  38. package/dist/dispatch.js +29 -6
  39. package/dist/distillAdmission.d.ts +13 -0
  40. package/dist/distillAdmission.js +35 -0
  41. package/dist/distillObserver.js +27 -12
  42. package/dist/distillPrimitives.d.ts +11 -8
  43. package/dist/distillPrimitives.js +116 -22
  44. package/dist/doctor.d.ts +13 -0
  45. package/dist/doctor.js +177 -10
  46. package/dist/identityHome.d.ts +9 -0
  47. package/dist/identityHome.js +47 -0
  48. package/dist/index.d.ts +73 -40
  49. package/dist/index.js +745 -207
  50. package/dist/issueReport.d.ts +7 -0
  51. package/dist/issueReport.js +291 -0
  52. package/dist/learningTrace.d.ts +15 -0
  53. package/dist/learningTrace.js +73 -0
  54. package/dist/lifecycle.d.ts +199 -2
  55. package/dist/lifecycle.js +4999 -152
  56. package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
  57. package/dist/lifecycleBootstrapTransaction.js +2182 -0
  58. package/dist/localMemoryGraph.d.ts +184 -0
  59. package/dist/localMemoryGraph.js +2689 -0
  60. package/dist/login.d.ts +1 -1
  61. package/dist/login.js +3 -3
  62. package/dist/materialPackage.js +3 -6
  63. package/dist/materialSnapshot.d.ts +35 -1
  64. package/dist/materialSnapshot.js +265 -18
  65. package/dist/memoryGraphOps.d.ts +8 -0
  66. package/dist/memoryGraphOps.js +140 -0
  67. package/dist/migrate/assetFormatMap.d.ts +61 -0
  68. package/dist/migrate/assetFormatMap.js +53 -0
  69. package/dist/migrate/envTranslate.d.ts +26 -0
  70. package/dist/migrate/envTranslate.js +147 -0
  71. package/dist/migrate/fieldMap.d.ts +7 -5
  72. package/dist/migrate/fieldMap.js +20 -14
  73. package/dist/migrate/oauthImport.d.ts +66 -0
  74. package/dist/migrate/oauthImport.js +667 -0
  75. package/dist/migrate/v1Import.d.ts +98 -1
  76. package/dist/migrate/v1Import.js +1532 -71
  77. package/dist/modelCompatibility.d.ts +10 -0
  78. package/dist/modelCompatibility.js +296 -0
  79. package/dist/promptRecallHook.d.ts +24 -0
  80. package/dist/promptRecallHook.js +425 -0
  81. package/dist/recallVerifyReport.d.ts +37 -0
  82. package/dist/recallVerifyReport.js +244 -0
  83. package/dist/recipe.d.ts +14 -2
  84. package/dist/recipe.js +543 -65
  85. package/dist/repairedAssetStore.d.ts +2 -0
  86. package/dist/repairedAssetStore.js +12 -0
  87. package/dist/requiredSandboxValidation.d.ts +5 -0
  88. package/dist/requiredSandboxValidation.js +4 -0
  89. package/dist/reuse.d.ts +18 -4
  90. package/dist/reuse.js +375 -107
  91. package/dist/reviewFilter.d.ts +3 -1
  92. package/dist/reviewFilter.js +3 -1
  93. package/dist/runtimeCapabilities.d.ts +18 -0
  94. package/dist/runtimeCapabilities.js +81 -0
  95. package/dist/runtimeSessionSource.d.ts +8 -2
  96. package/dist/runtimeSessionSource.js +63 -11
  97. package/dist/selectionPolicyConfig.d.ts +8 -0
  98. package/dist/selectionPolicyConfig.js +18 -0
  99. package/dist/semanticIdfConfig.d.ts +2 -0
  100. package/dist/semanticIdfConfig.js +4 -0
  101. package/dist/sessionIngest.d.ts +43 -0
  102. package/dist/sessionIngest.js +180 -0
  103. package/dist/setupHooks.d.ts +5 -0
  104. package/dist/setupHooks.js +330 -14
  105. package/dist/skill2gep.d.ts +13 -9
  106. package/dist/skill2gep.js +99 -36
  107. package/dist/skillDistill.d.ts +8 -4
  108. package/dist/skillDistill.js +39 -9
  109. package/dist/solo/mode.js +1 -0
  110. package/dist/sync.d.ts +13 -1
  111. package/dist/sync.js +1947 -265
  112. package/dist/thesis.d.ts +1 -1
  113. package/dist/thesis.js +20 -3
  114. package/dist/trajectoryExport.js +21 -3
  115. package/dist/v1Compat.d.ts +1 -0
  116. package/dist/v1Compat.js +9 -0
  117. package/dist/valueDigest.js +8 -1
  118. package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
  119. package/dist/windowsLegacyTaskCleanup.js +1475 -0
  120. package/dist/workflow.d.ts +39 -0
  121. package/dist/workflow.js +386 -0
  122. package/dist/workflowRuntime.d.ts +66 -0
  123. package/dist/workflowRuntime.js +638 -0
  124. package/package.json +14 -7
@@ -172,8 +172,8 @@ export function buildAtpAutoDeliverProofPayload(task, nowDate = () => new Date()
172
172
  return {
173
173
  result: 'completed',
174
174
  asset_id: assetId,
175
- completed_at: taskString(task, 'claimed_at') ?? nowDate().toISOString(),
176
- pass_rate: 1.0,
175
+ completed_at: taskString(task, 'completed_at') ?? taskString(task, 'completedAt') ?? nowDate().toISOString(),
176
+ // pass_rate is deliberately absent: auto-delivery has an asset reference, not measured validation evidence.
177
177
  signals: Array.isArray(task['signals']) ? task['signals'].filter((s) => typeof s === 'string').slice(0, 10) : [],
178
178
  submitter: 'evolver_auto_deliver',
179
179
  };
@@ -197,8 +197,8 @@ function slug(value) {
197
197
  const out = value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64);
198
198
  return out || 'recurring-failure-guardrail';
199
199
  }
200
- function buildAntiGenePrompt(input) {
201
- const clusters = hub.redactDeep(input.failureClusters.map((cluster) => ({
200
+ function buildAntiGenePrompt(input, redact = true) {
201
+ const rawClusters = input.failureClusters.map((cluster) => ({
202
202
  clusterId: cluster.clusterId,
203
203
  trigger: cluster.trigger,
204
204
  sharedTrigger: cluster.sharedTrigger,
@@ -212,7 +212,8 @@ function buildAntiGenePrompt(input) {
212
212
  outcome: capsule.outcome,
213
213
  proofOfWork: capsule.proofOfWork,
214
214
  })),
215
- })));
215
+ }));
216
+ const clusters = redact ? hub.redactDeep(rawClusters) : rawClusters;
216
217
  return [
217
218
  'You are synthesizing one EvoMap AntiGene from recurring failed Capsules.',
218
219
  'An AntiGene is a guardrail: it says what to avoid or check before repeating a known failure pattern.',
@@ -343,10 +344,11 @@ export async function autoDistillAntiGene(options) {
343
344
  if (!patchState(statePath, input.dataHash, { last_attempt_at: new Date(now).toISOString() }, hashCap)) {
344
345
  return { ok: false, mode, reason: 'state_write_failed', dataHash: input.dataHash };
345
346
  }
346
- const prompt = buildAntiGenePrompt(input);
347
- if (hub.detectEnvValueLeaks(prompt, env).length > 0) {
347
+ // 先扫描脱敏前的同构 prompt,防止新增的模式脱敏掩盖反向环境变量泄漏证据。
348
+ if (hub.detectEnvValueLeaks(buildAntiGenePrompt(input, false), env).length > 0) {
348
349
  return { ok: false, mode, reason: 'prompt_env_leak_blocked', dataHash: input.dataHash };
349
350
  }
351
+ const prompt = buildAntiGenePrompt(input);
350
352
  const runner = options.runner ?? resolveDistillRunner(env);
351
353
  const timeoutMs = envInt(env, 'EVOLVE_DISTILL_TIMEOUT_MS', DEFAULT_TIMEOUT_MS);
352
354
  const llm = await runner(prompt, { cwd: options.cwd ?? process.cwd(), timeoutMs, env });
@@ -30,6 +30,7 @@ export interface LlmDistillRunnerResult {
30
30
  exitCode: number | null;
31
31
  stdout: string;
32
32
  stderr?: string;
33
+ stdoutTruncated?: boolean;
33
34
  }
34
35
  export type LlmDistillRunner = (prompt: string, ctx: {
35
36
  cwd: string;
@@ -61,6 +62,26 @@ export declare function p3Decide(mode: Exclude<AutoDistillLlmMode, 'off'>, rec:
61
62
  cooldownMs?: number;
62
63
  maxAttempts?: number;
63
64
  }): 'spawn' | 'enforced_idempotent_skip' | 'shadow_idempotent_skip' | 'failed_exhausted' | 'p3_cooldown';
65
+ /**
66
+ * Resolve a distilled candidate's hard scope facets against the vocabulary the existing genes actually declare.
67
+ *
68
+ * This closes the failure the autonomous-scope experiment isolated (bench/thesis/result-recovery-autoscope-joint-metric.json):
69
+ * a distiller told that `required:<tag>` is a hard facet chose one in 5/5 runs and aimed it at the right dimension, but
70
+ * wrote `required:v2` where the live signal is `rounding-v2`. A facet is matched against live signals, so it never
71
+ * matched and the asset was never eligible anywhere. The distiller cannot be blamed for that: it reads solved code and
72
+ * never observes the retrieval vocabulary. Here the substrate supplies what it cannot see.
73
+ *
74
+ * Conservative by construction: only an exact hit or a single unambiguous qualifier relation is rewritten. Ambiguous
75
+ * and unknown tags are left EXACTLY as the distiller wrote them, because silently retargeting a scope key on a weak
76
+ * similarity would be a worse governance failure than an unmatched facet — scope decides what enters agent context.
77
+ */
78
+ export declare function resolveCandidateScopeFacets(candidate: algo.GeneCandidate, existingGenes: readonly assetstore.AssetRecord[]): {
79
+ candidate: algo.GeneCandidate;
80
+ rewrites: Array<{
81
+ from: string;
82
+ to: string;
83
+ }>;
84
+ };
64
85
  export declare function parseDistillOutput(stdout: string): unknown | null;
65
86
  export declare function asGeneCandidate(value: unknown): algo.GeneCandidate | null;
66
87
  export declare function jaccardDuplicate(candidate: algo.GeneCandidate, existing: readonly algo.ExistingGeneRef[], threshold?: number): string | null;
@@ -80,6 +101,11 @@ export declare function runClaudeDistill(prompt: string, ctx: {
80
101
  * `--output-last-message <file>`: capture ONLY the final assistant message (the gene JSON), avoiding codex's stdout
81
102
  * preamble/token-count noise. Prompt arrives via stdin (the trailing `-`). Verified live against codex-cli 0.137.0. */
82
103
  export declare function codexDistillArgs(cwd: string, lastMessageFile: string, model?: string): string[];
104
+ /** Read Codex's final-message file without allowing that subprocess-owned file to bypass output bounds. */
105
+ export declare function readBoundedDistillOutputFile(path: string, maxBytes?: number): {
106
+ text: string;
107
+ truncated: boolean;
108
+ };
83
109
  /** Distill a prompt with `codex exec` (read-only). Reads the clean final message from --output-last-message so
84
110
  * parseDistillOutput sees a bare gene JSON; falls back to raw stdout (pickGeneObject scans it) if the file is absent.
85
111
  * Windows: codex is a `.cmd` npm shim, so route through resolveSpawnCommand (shell-free). */
@@ -1,8 +1,9 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
- import { algo, assetstore, events, exec, hub, verify } from '@evomap/evolver-core';
5
+ import { algo, assetstore, events, exec, hub, signals, verify } from '@evomap/evolver-core';
6
+ import { runRequiredSandboxedValidation } from './requiredSandboxValidation.js';
6
7
  const DEFAULT_MIN_CAPSULES = 10;
7
8
  const DEFAULT_MAX_CAPSULES = 24;
8
9
  const DEFAULT_MIN_SUCCESS_SCORE = 0.7;
@@ -98,6 +99,37 @@ function normalizedSignals(record) {
98
99
  const raw = record['signals_match'];
99
100
  return Array.isArray(raw) ? raw.map(String).filter(Boolean) : [];
100
101
  }
102
+ /**
103
+ * Resolve a distilled candidate's hard scope facets against the vocabulary the existing genes actually declare.
104
+ *
105
+ * This closes the failure the autonomous-scope experiment isolated (bench/thesis/result-recovery-autoscope-joint-metric.json):
106
+ * a distiller told that `required:<tag>` is a hard facet chose one in 5/5 runs and aimed it at the right dimension, but
107
+ * wrote `required:v2` where the live signal is `rounding-v2`. A facet is matched against live signals, so it never
108
+ * matched and the asset was never eligible anywhere. The distiller cannot be blamed for that: it reads solved code and
109
+ * never observes the retrieval vocabulary. Here the substrate supplies what it cannot see.
110
+ *
111
+ * Conservative by construction: only an exact hit or a single unambiguous qualifier relation is rewritten. Ambiguous
112
+ * and unknown tags are left EXACTLY as the distiller wrote them, because silently retargeting a scope key on a weak
113
+ * similarity would be a worse governance failure than an unmatched facet — scope decides what enters agent context.
114
+ */
115
+ export function resolveCandidateScopeFacets(candidate, existingGenes) {
116
+ const tags = candidate.signals_match?.map(String) ?? [];
117
+ if (tags.length === 0 || existingGenes.length === 0)
118
+ return { candidate, rewrites: [] };
119
+ const vocab = signals.scopeVocabularyFromRecords(existingGenes);
120
+ const rewrites = [];
121
+ const next = tags.map((tag) => {
122
+ if (!tag.startsWith('required:'))
123
+ return tag;
124
+ const r = signals.resolveScopeTag(tag, vocab);
125
+ if (r.status !== 'resolved')
126
+ return tag;
127
+ const to = `required:${r.resolved}`;
128
+ rewrites.push({ from: tag, to });
129
+ return to;
130
+ });
131
+ return rewrites.length > 0 ? { candidate: { ...candidate, signals_match: next }, rewrites } : { candidate, rewrites: [] };
132
+ }
101
133
  function existingGeneRefs(records) {
102
134
  return records.map((record) => ({
103
135
  id: typeof record['id'] === 'string' ? record['id'] : undefined,
@@ -135,14 +167,25 @@ async function collectDistillInput(store, maxCapsules, minSuccessScore) {
135
167
  const successCapsules = capsules.filter((record) => isSuccessCapsule(record, minSuccessScore)).slice(-maxCapsules);
136
168
  return { dataHash: hashCapsules(successCapsules), successCapsules, existingGenes };
137
169
  }
138
- function buildDistillPrompt(input) {
139
- const capsules = hub.redactDeep(input.successCapsules.map(capsuleDigestView));
140
- const genes = hub.redactDeep(input.existingGenes.map((gene) => ({
170
+ function buildDistillPrompt(input, redact = true) {
171
+ const rawCapsules = input.successCapsules.map(capsuleDigestView);
172
+ const rawGenes = input.existingGenes.map((gene) => ({
141
173
  id: gene['id'],
142
174
  category: gene['category'],
143
175
  signals_match: gene['signals_match'],
144
176
  summary: gene['summary'],
145
- })));
177
+ }));
178
+ const capsules = redact ? hub.redactDeep(rawCapsules) : rawCapsules;
179
+ const genes = redact ? hub.redactDeep(rawGenes) : rawGenes;
180
+ // Scope-language alignment (review ②): show the model the signals the store ACTUALLY uses BEFORE it chooses a
181
+ // scope facet. The autonomous-scope experiment (result-recovery-autoscope-joint-metric.json) isolated the
182
+ // failure as structural, not a model weakness — the distiller reads solved source code and never observes the
183
+ // retrieval vocabulary its consumers present, so it wrote `required:v2` where the live signal was `rounding-v2`
184
+ // and the asset matched nothing. `resolveCandidateScopeFacets` corrects that post-hoc only for the single
185
+ // unambiguous qualifier relation; surfacing the real vocabulary up front lets the model pick a signal that
186
+ // EXISTS in the first place, covering the ambiguous/unknown cases the post-hoc rewrite deliberately refuses to
187
+ // guess. Descriptive, not prescriptive: it does not forbid a genuinely new signal, only makes the real ones visible.
188
+ const vocab = signals.scopeVocabularyFromRecords(input.existingGenes);
146
189
  return [
147
190
  'You are synthesizing one high-quality EvoMap Gene from recurring successful Capsules.',
148
191
  'Return only JSON. Do not use markdown. Do not include commentary.',
@@ -153,11 +196,23 @@ function buildDistillPrompt(input) {
153
196
  '- Strategy steps must be concrete, defensive, and reusable.',
154
197
  '- Validation must be light. Prefer ["node --version"]. Do not use test suites, node --test, jest, mocha, or node -e.',
155
198
  '- Avoid duplicating existing genes.',
199
+ // Scope facets are matched against LIVE retrieval signals, so a facet naming a signal that does not exist is
200
+ // dead on arrival. Reuse a signal from OBSERVED_SIGNALS below when it names the scope you mean; only invent a
201
+ // new signal for a genuinely new scope dimension. For a hard scope facet write `required:<signal>` using the
202
+ // EXACT signal string as it appears there (e.g. `required:rounding-v2`, never a bare qualifier like `required:v2`).
203
+ '- Scope signals must name signals that exist: reuse an OBSERVED_SIGNALS entry verbatim unless the scope is genuinely new.',
204
+ // K_auto coordinates (optional but preferred). Intake fills honest defaults when omitted; when present they
205
+ // must use closed vocabularies so the gene can enter automatic claim-level governance.
206
+ '- Optional K_auto fields: claims (closed predicates), scope.signals (prefer namespaced terms like capability:<signal> or repo:org/name), runtime_profile, verifier_profile.',
207
+ '- claims[].predicate MUST be one of: source_of_truth, requires_service, requires_tool, forbids_action, output_contract, ordering_constraint, environment_precondition.',
156
208
  '',
157
209
  'Required JSON shape:',
158
- '{"type":"Gene","id":"gene_distilled_<descriptive-kebab-name>","summary":"...","category":"repair|optimize|innovate|explore","signals_match":["signal"],"preconditions":["condition"],"strategy":["step"],"constraints":{"max_files":3,"forbidden_paths":[".git","node_modules"]},"validation":["node --version"]}',
210
+ '{"type":"Gene","id":"gene_distilled_<descriptive-kebab-name>","summary":"...","category":"repair|optimize|innovate|explore","signals_match":["signal"],"preconditions":["condition"],"strategy":["step"],"constraints":{"max_files":3,"forbidden_paths":[".git","node_modules"]},"validation":["node --version"],"claims":[{"predicate":"output_contract","kind":"behavioral"}],"scope":{"signals":["capability:signal"]},"runtime_profile":{"runtime":"model-id","env_class":"local"},"verifier_profile":{"verifier":"evolver-sandboxed-validation","decision":"pass"}}',
159
211
  '',
160
212
  `DATA_HASH: ${input.dataHash}`,
213
+ 'OBSERVED_SIGNALS (signal (asset_count), most-used first — reuse these exact strings for scope):',
214
+ signals.renderScopeVocabulary(vocab),
215
+ '',
161
216
  'SUCCESS_CAPSULES:',
162
217
  JSON.stringify(capsules, null, 2),
163
218
  '',
@@ -267,6 +322,12 @@ export function asGeneCandidate(value) {
267
322
  },
268
323
  } : {}),
269
324
  ...(Array.isArray(value['validation']) ? { validation: value['validation'].map(String) } : {}),
325
+ // K_auto coordinates: pass through when the model supplies them. intakeGene normalizes + fills honest
326
+ // defaults for any missing coordinate so forward genes can enter strict K_auto without inventing claims.
327
+ ...(value['claims'] !== undefined ? { claims: value['claims'] } : {}),
328
+ ...(value['scope'] !== undefined ? { scope: value['scope'] } : {}),
329
+ ...(value['runtime_profile'] !== undefined ? { runtime_profile: value['runtime_profile'] } : {}),
330
+ ...(value['verifier_profile'] !== undefined ? { verifier_profile: value['verifier_profile'] } : {}),
270
331
  // An LLM-distilled gene is distilled from prior capsule/session evidence (not a verified fail→pass trajectory,
271
332
  // not a human-taught gene) → `distilled` per V1 #302 classifyProvenance. intakeGene normalizes + validates it.
272
333
  generation_meta: { source: 'distilled' },
@@ -338,7 +399,7 @@ export async function runClaudeDistill(prompt, ctx) {
338
399
  const env = exec.scrubAgentEnv(ctx.env, { allowPrefixes: exec.getRunnerSpec('claude').envAllow.prefixes });
339
400
  try {
340
401
  const r = await exec.spawnCapture('claude', args, { cwd: ctx.cwd, timeoutMs: ctx.timeoutMs, input: prompt, env });
341
- return { exitCode: r.code, stdout: r.stdout, stderr: r.stderr };
402
+ return { exitCode: r.code, stdout: r.stdout, stderr: r.stderr, stdoutTruncated: r.stdoutTruncated };
342
403
  }
343
404
  catch (e) {
344
405
  return { exitCode: null, stdout: '', stderr: e instanceof Error ? e.message : String(e) };
@@ -356,6 +417,30 @@ export function codexDistillArgs(cwd, lastMessageFile, model) {
356
417
  args.push('-');
357
418
  return args;
358
419
  }
420
+ /** Read Codex's final-message file without allowing that subprocess-owned file to bypass output bounds. */
421
+ export function readBoundedDistillOutputFile(path, maxBytes = exec.DEFAULT_MAX_CAPTURE_BYTES) {
422
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 256)
423
+ throw new RangeError('maxBytes must be an integer >= 256');
424
+ const fd = openSync(path, 'r');
425
+ try {
426
+ const buffer = Buffer.allocUnsafe(maxBytes + 1);
427
+ let offset = 0;
428
+ while (offset < buffer.length) {
429
+ const read = readSync(fd, buffer, offset, buffer.length - offset, null);
430
+ if (read === 0)
431
+ break;
432
+ offset += read;
433
+ }
434
+ const truncated = offset > maxBytes;
435
+ return {
436
+ text: truncated ? '' : buffer.subarray(0, offset).toString('utf8').trim(),
437
+ truncated,
438
+ };
439
+ }
440
+ finally {
441
+ closeSync(fd);
442
+ }
443
+ }
359
444
  /** Distill a prompt with `codex exec` (read-only). Reads the clean final message from --output-last-message so
360
445
  * parseDistillOutput sees a bare gene JSON; falls back to raw stdout (pickGeneObject scans it) if the file is absent.
361
446
  * Windows: codex is a `.cmd` npm shim, so route through resolveSpawnCommand (shell-free). */
@@ -367,13 +452,20 @@ export async function runCodexDistill(prompt, ctx) {
367
452
  try {
368
453
  const r = await exec.spawnCapture(resolved.cmd, resolved.args, { cwd: ctx.cwd, timeoutMs: ctx.timeoutMs, input: prompt, env });
369
454
  let stdout = r.stdout;
455
+ let stdoutTruncated = r.stdoutTruncated;
370
456
  try {
371
- const last = readFileSync(lastMessageFile, 'utf8').trim();
372
- if (last)
373
- stdout = last;
457
+ const last = readBoundedDistillOutputFile(lastMessageFile);
458
+ if (last.truncated) {
459
+ stdout = '';
460
+ stdoutTruncated = true;
461
+ }
462
+ else if (last.text) {
463
+ stdout = last.text;
464
+ stdoutTruncated = false;
465
+ }
374
466
  }
375
467
  catch { /* file absent (codex failed early) → keep raw stdout for pickGeneObject */ }
376
- return { exitCode: r.code, stdout, stderr: r.stderr };
468
+ return { exitCode: r.code, stdout, stderr: r.stderr, stdoutTruncated };
377
469
  }
378
470
  catch (e) {
379
471
  return { exitCode: null, stdout: '', stderr: e instanceof Error ? e.message : String(e) };
@@ -447,16 +539,12 @@ export async function autoDistillLlm(options) {
447
539
  }
448
540
  const runner = options.runner ?? resolveDistillRunner(env);
449
541
  const timeoutMs = envInt(env, 'EVOLVE_DISTILL_TIMEOUT_MS', DEFAULT_TIMEOUT_MS);
450
- const prompt = buildDistillPrompt(input);
451
- // Egress-floor parity: buildDistillPrompt already pattern-redacts via hub.redactDeep, but the Hub publish path
452
- // additionally runs a REVERSE env-value scan (hub.detectEnvValueLeaks) that flags any process-env value
453
- // appearing verbatim in the payload — catching custom-format secrets no pattern matches. The prompt is an
454
- // off-box egress (stdin to a spawned `claude`), so hold it to the same floor the repo enforces on publish: if a
455
- // daemon env secret leaked into a capsule, fail CLOSED and never send it. This is a data-hygiene block, not a
456
- // deterministic claude failure, so — like a transient exit below — it does NOT bump failed_attempts.
457
- if (hub.detectEnvValueLeaks(prompt, env).length > 0) {
542
+ // LLM prompt 属于外部输出边界。先对脱敏前的同构内容执行反向环境变量扫描,
543
+ // 避免高熵模式先替换秘密后让泄漏检查误判为安全;该阻断不计入确定性失败次数。
544
+ if (hub.detectEnvValueLeaks(buildDistillPrompt(input, false), env).length > 0) {
458
545
  return { ok: false, mode, reason: 'prompt_env_leak_blocked', dataHash: input.dataHash };
459
546
  }
547
+ const prompt = buildDistillPrompt(input);
460
548
  const llm = await runner(prompt, { cwd, timeoutMs, env });
461
549
  if (llm.exitCode !== 0) {
462
550
  // V1 parity: a PROCESS-level claude failure — spawn error/ENOENT or timeout→SIGKILL (exitCode === null), OR a
@@ -467,6 +555,9 @@ export async function autoDistillLlm(options) {
467
555
  // permanently exhaust this data hash after MAX_ATTEMPTS — the exact silent stall this exemption prevents.
468
556
  return { ok: false, mode, reason: llm.exitCode === null ? 'claude_spawn_error' : 'claude_nonzero_exit', dataHash: input.dataHash };
469
557
  }
558
+ if (llm.stdoutTruncated) {
559
+ return { ok: false, mode, reason: 'llm_output_truncated', dataHash: input.dataHash };
560
+ }
470
561
  const raw = parseDistillOutput(llm.stdout);
471
562
  const candidate0 = asGeneCandidate(raw);
472
563
  if (!candidate0) {
@@ -474,7 +565,13 @@ export async function autoDistillLlm(options) {
474
565
  return { ok: false, mode, reason: 'no_gene_in_response', dataHash: input.dataHash };
475
566
  }
476
567
  const existing = existingGeneRefs(input.existingGenes);
477
- const normalized = normalizeValidation(candidate0, cwd).candidate;
568
+ // Resolve hard scope facets against the observed vocabulary BEFORE dedup/intake, so a near-miss facet
569
+ // (`required:v2` for a store that declares `rounding-v2`) becomes eligible instead of silently unmatched.
570
+ const scoped = resolveCandidateScopeFacets(candidate0, input.existingGenes);
571
+ if (scoped.rewrites.length > 0) {
572
+ console.warn(`[AutoDistill] resolved scope facet(s) against store vocabulary: ${scoped.rewrites.map((r) => `${r.from} -> ${r.to}`).join(', ')}`);
573
+ }
574
+ const normalized = normalizeValidation(scoped.candidate, cwd).candidate;
478
575
  const duplicate = jaccardDuplicate(normalized, existing, envFloat(env, 'EVOLVER_AUTO_DISTILL_LLM_DUP_JACCARD', DEFAULT_DUP_JACCARD));
479
576
  if (duplicate) {
480
577
  patchState(statePath, input.dataHash, { failed_attempts_inc: true }, hashCap);
@@ -485,7 +582,7 @@ export async function autoDistillLlm(options) {
485
582
  patchState(statePath, input.dataHash, { failed_attempts_inc: true }, hashCap);
486
583
  return { ok: false, mode, reason: 'validation_failed', dataHash: input.dataHash };
487
584
  }
488
- const validation = await verify.runSandboxedValidation(intake.gene.validation, cwd, {
585
+ const validation = await runRequiredSandboxedValidation(intake.gene.validation, cwd, {
489
586
  timeoutMs: options.validationTimeoutMs ?? envInt(env, 'EVOLVE_DISTILL_VALIDATION_TIMEOUT_MS', DEFAULT_VALIDATION_TIMEOUT_MS),
490
587
  });
491
588
  if (!validation.passed) {
@@ -12,9 +12,10 @@
12
12
  import { createHash } from 'node:crypto';
13
13
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
14
14
  import { basename, dirname, join } from 'node:path';
15
- import { algo, assetstore, events, hub, verify, signals } from '@evomap/evolver-core';
15
+ import { algo, assetstore, events, hub, signals } from '@evomap/evolver-core';
16
16
  import { adapterForPath } from '@evomap/evolver-runtime-adapters';
17
17
  import { asGeneCandidate, parseDistillOutput, normalizeValidation, jaccardDuplicate, resolveDistillRunner, p3Decide, } from './autoDistillLlm.js';
18
+ import { runRequiredSandboxedValidation } from './requiredSandboxValidation.js';
18
19
  const DEFAULT_MIN_TURNS = 2;
19
20
  const DEFAULT_MIN_CHARS = 200;
20
21
  const DEFAULT_TIMEOUT_MS = 180_000;
@@ -169,7 +170,7 @@ export async function autoDistillTranscript(options) {
169
170
  const intake = algo.intakeGene(normalized, existing);
170
171
  if (!intake.ok || !intake.gene)
171
172
  return { ok: false, mode, reason: 'validation_failed', candidate: normalized };
172
- const validation = await verify.runSandboxedValidation(intake.gene.validation, cwd, {
173
+ const validation = await runRequiredSandboxedValidation(intake.gene.validation, cwd, {
173
174
  timeoutMs: options.validationTimeoutMs ?? envInt(env, 'EVOLVE_DISTILL_VALIDATION_TIMEOUT_MS', DEFAULT_VALIDATION_TIMEOUT_MS),
174
175
  });
175
176
  if (!validation.passed)
@@ -1,4 +1,4 @@
1
- import { events, assetstore, algo, exec, hooks, material as materialNs, verify, hub as hubNs } from '@evomap/evolver-core';
1
+ import { events, assetstore, algo, exec, hooks, material as materialNs, util, verify, hub as hubNs } from '@evomap/evolver-core';
2
2
  import { type Beat } from './daemonLoop.js';
3
3
  import { connectPublicHub, ReuseCache } from '@evomap/evolver-adapter-public';
4
4
  import type { FetchLike, MemoryGraphEventReceipt, MemoryGraphEventReport, OfflinePermitStore, OutcomeReport, OutcomeReceipt } from '@evomap/evolver-adapter-public';
@@ -8,29 +8,41 @@ import { resolveDistillObserver } from './distillObserver.js';
8
8
  import { type AutoDistillLlmResult, type LlmDistillRunner } from './autoDistillLlm.js';
9
9
  import { type AutoDistillAntiGeneMode, type AutoDistillAntiGeneResult } from './autoDistillAntiGene.js';
10
10
  import { type AutoDistillTranscriptMode, type TranscriptDistillTickResult } from './autoDistillTranscript.js';
11
- import { type SessionIngestTickResult } from './index.js';
11
+ import { type SessionIngestTickResult } from './sessionIngest.js';
12
+ import { AtpAutoBuyer, type AtpAutoBuyerClient, type AtpAutoBuyerRequest } from './atpAutoBuyer.js';
13
+ import { type ConfiguredSelectionGuard } from './selectionPolicyConfig.js';
14
+ export { readAutoExecConfig, type AutoExecConfig } from './autoexecConfig.js';
15
+ export { semanticIdfEnabled } from './semanticIdfConfig.js';
16
+ export { selectionFloorFromEnv, selectionGuardFromEnv, selectionPolicyFromEnv, type ConfiguredSelectionGuard, } from './selectionPolicyConfig.js';
17
+ export declare function withAutoExecSelectionPolicy<T extends object>(deps: T, env?: NodeJS.ProcessEnv): T & {
18
+ selectionPolicy?: exec.AutoExecDeps['selectionPolicy'];
19
+ };
20
+ export declare function withAutoExecSelectionConfig<T extends object>(deps: T, env?: NodeJS.ProcessEnv): T & {
21
+ selectionPolicy?: exec.AutoExecDeps['selectionPolicy'];
22
+ selectionGuard: ConfiguredSelectionGuard;
23
+ selectionFloor?: number;
24
+ };
12
25
  export interface AutoExecDirs {
13
26
  base: string;
14
27
  tasks: string;
28
+ inflight: string;
15
29
  done: string;
16
30
  refused: string;
17
31
  }
18
- export interface AutoExecConfig {
19
- allowedRoots: string[];
20
- pollMs: number;
21
- timeoutMs: number;
22
- runner: 'claude' | 'codex' | 'cursor';
23
- }
24
- /** Create the queue layout under <home>/autoexec/{tasks,done,refused}. */
32
+ /** Create the queue layout under <home>/autoexec/{tasks,inflight,done,refused}. */
25
33
  export declare function ensureAutoExecDirs(base: string): AutoExecDirs;
26
- /** Read <base>/config.json; deny-by-default (empty allowedRoots) when absent. Default runner 'claude' (#66). */
27
- export declare function readAutoExecConfig(base: string): AutoExecConfig;
28
34
  export declare function summarizeSandboxedValidation(result: verify.SandboxedValidationResult): string | null;
29
35
  /**
30
- * One queue pass: drain every tasks/*.json through `runOne`, route the verdict to done/ (success or failure)
31
- * or refused/ (deny-by-default), and move the task file out of the queue. Sequential; returns the verdicts.
36
+ * One queue pass: atomically claim regular tasks/*.json into inflight/, then route each verdict to done/
37
+ * (success or failure) or refused/ (deny-by-default). A claim is atomically marked started before runOne;
38
+ * after a crash, started and legacy claims are ambiguous and fail closed instead of repeating side effects.
39
+ * Unreadable or incomplete claimed tasks stay pending because the drop-directory has no atomic publish marker.
32
40
  */
33
- export declare function autoExecPass(dirs: AutoExecDirs, runOne: (task: exec.AutoExecTask) => Promise<exec.AutoExecVerdict>): Promise<exec.AutoExecVerdict[]>;
41
+ export declare function autoExecPass(dirs: AutoExecDirs, runOne: (task: exec.AutoExecTask) => Promise<exec.AutoExecVerdict>, options?: {
42
+ executePendingTasks?: boolean;
43
+ }): Promise<exec.AutoExecVerdict[]>;
44
+ /** Keep unsupported built-in runners away from the execution queue without stopping the resident daemon. */
45
+ export declare function runnerBoundAutoExecPass(runner: exec.RunnerName, dirs: AutoExecDirs, runOne: (task: exec.AutoExecTask) => Promise<exec.AutoExecVerdict>): () => Promise<exec.AutoExecVerdict[]>;
34
46
  /**
35
47
  * Build the reuse-before-solve seam (#110) — THE real injection point. This is the public-repo composition
36
48
  * layer that owns BOTH core's autoexec kernel and the adapter's hub capability, so it is where the adapter's
@@ -40,7 +52,48 @@ export declare function autoExecPass(dirs: AutoExecDirs, runOne: (task: exec.Aut
40
52
  * (a repeat signal set → zero hub calls). Off by default: only wired when EVOLVER_REUSE_BEFORE_SOLVE === '1'
41
53
  * AND a hub credential exists (no token → no seam → zero hub calls, exactly today's behavior).
42
54
  */
43
- export declare function makeHubReuseSeam(cap: hubNs.HubCapability, cache: ReuseCache, ingestor?: events.Ingestor, onAssetReused?: (assetId: string) => void): exec.HubReuseSeam;
55
+ export type VerifiedHubSearchMissReason = 'no_results' | 'below_threshold';
56
+ export interface VerifiedHubSearchMiss {
57
+ reason: VerifiedHubSearchMissReason;
58
+ signals: readonly string[];
59
+ cycleId?: string;
60
+ }
61
+ export type VerifiedHubSearchMissHandler = (miss: VerifiedHubSearchMiss) => void;
62
+ /** Minimal audit seam so autoexec tests never have to touch the operator's real asset-call log. */
63
+ export interface AssetCallLogger {
64
+ append(entry: hubNs.AssetCallEntry): void;
65
+ assetCostIndex?(): Record<string, number>;
66
+ }
67
+ interface HubSearchHitAudit {
68
+ runId: string | null;
69
+ assetId?: string;
70
+ assetType?: string;
71
+ sourceNodeId?: string;
72
+ chainId?: string;
73
+ score?: number;
74
+ mode: 'direct' | 'reference';
75
+ signals: readonly string[];
76
+ tokensSaved: number;
77
+ tokensSavedBasis: hubNs.TokensSavedBasis;
78
+ }
79
+ interface HubReuseAuditOptions {
80
+ assetLog?: AssetCallLogger;
81
+ onSearchHit?: (hit: HubSearchHitAudit) => void;
82
+ env?: NodeJS.ProcessEnv;
83
+ }
84
+ /** Build the deliberately small, public-safe ATP request allowed to leave autoexec after a verified Hub miss. */
85
+ export declare function atpCapabilityGapRequest(signals: readonly string[]): AtpAutoBuyerRequest;
86
+ /** Schedule economic work outside the reuse/task critical path and contain all asynchronous failures. */
87
+ export declare function scheduleAtpAutoBuyForVerifiedMiss(miss: VerifiedHubSearchMiss, buyer: Pick<AtpAutoBuyer, 'consider'>): void;
88
+ /** Resolve an autonomous buyer only after an explicit env/ack consent check; the buyer checks consent again. */
89
+ export declare function resolveAtpAutoBuyer(env?: NodeJS.ProcessEnv, createClient?: (resolvedEnv: NodeJS.ProcessEnv) => AtpAutoBuyerClient): AtpAutoBuyer | undefined;
90
+ export declare function makeHubReuseSeam(cap: hubNs.HubCapability, cache: ReuseCache, ingestor?: events.Ingestor, onAssetReused?: (assetId: string) => void, onVerifiedSearchMiss?: VerifiedHubSearchMissHandler, audit?: HubReuseAuditOptions): exec.HubReuseSeam;
91
+ /**
92
+ * Free search-only seam used by ATP auto-buy when reuse injection is disabled. It proves a capability miss with
93
+ * the same dual-leg search and score threshold as reuse, but never performs the paid fetch or contributes a Hub
94
+ * candidate.
95
+ */
96
+ export declare function makeHubSearchMissProbe(cap: hubNs.HubCapability, cache: ReuseCache, onVerifiedSearchMiss: VerifiedHubSearchMissHandler, enabled: () => boolean, env?: NodeJS.ProcessEnv, assetLog?: AssetCallLogger): exec.HubReuseSeam;
44
97
  /**
45
98
  * Append a `value.inject` root_event for a SessionStart gene injection (#123). Attribution-only — the payload
46
99
  * carries the injected gene ids (+ cycle/outcome when known) and NO savings number, exactly per the ledger's
@@ -113,6 +166,43 @@ export declare function verdictToOutcomeStatus(status: exec.AutoExecVerdict['sta
113
166
  export declare function questionGeneratorStatePath(home?: string): string;
114
167
  export declare function makeHubQuestionLink(cap: hubNs.HubCapability, options?: HubQuestionLinkOptions): HubQuestionLink;
115
168
  export declare function shouldSubmitProactiveQuestionsForTask(task: exec.AutoExecTask): boolean;
169
+ export declare function autoexecLockFailureMessage(error: unknown): string;
170
+ export declare function autoexecLockReleaseFailureMessage(error: unknown): string;
171
+ export interface AutoexecLockReleaseDeps {
172
+ releaseLock?: (path: string) => util.ReleaseLockResult | void;
173
+ stderr?: (text: string) => void;
174
+ }
175
+ export declare function releaseAutoexecLock(lockPath: string, deps?: AutoexecLockReleaseDeps): boolean;
176
+ type AutoexecStreamErrorListener = (error: NodeJS.ErrnoException) => void;
177
+ export interface AutoexecErrorStream {
178
+ on(event: 'error', listener: AutoexecStreamErrorListener): unknown;
179
+ off?(event: 'error', listener: AutoexecStreamErrorListener): unknown;
180
+ removeListener?(event: 'error', listener: AutoexecStreamErrorListener): unknown;
181
+ }
182
+ export interface AutoexecBrokenPipeGuardDeps {
183
+ stdout?: AutoexecErrorStream;
184
+ stderr?: AutoexecErrorStream;
185
+ }
186
+ /** Keep a detached daemon alive when its output consumer closes, without hiding other stream failures. */
187
+ export declare function installAutoexecBrokenPipeGuards(deps?: AutoexecBrokenPipeGuardDeps): () => void;
188
+ export type AutoexecProcessSignal = 'SIGINT' | 'SIGTERM' | 'SIGHUP';
189
+ type AutoexecSignalListener = () => void;
190
+ export interface AutoexecSignalSource {
191
+ on(event: AutoexecProcessSignal, listener: AutoexecSignalListener): unknown;
192
+ off?(event: AutoexecProcessSignal, listener: AutoexecSignalListener): unknown;
193
+ removeListener?(event: AutoexecProcessSignal, listener: AutoexecSignalListener): unknown;
194
+ }
195
+ export interface AutoexecShutdownDeps {
196
+ stop: () => Promise<void>;
197
+ cleanup: () => void;
198
+ signals?: AutoexecSignalSource;
199
+ write?: (message: string) => void;
200
+ }
201
+ /**
202
+ * Own autoexec's process-signal lifetime. V2 intentionally has no hot-reload seam: SIGHUP is informational and
203
+ * keeps the current generation alive; SIGINT/SIGTERM drain the resident loop before cleanup and exit.
204
+ */
205
+ export declare function waitForAutoexecShutdown(deps: AutoexecShutdownDeps): Promise<number>;
116
206
  export declare function urgentQuestionRuntimeWiringStatus(): typeof hubNs.URGENT_QUESTION_RUNTIME_WIRING_STATUS;
117
207
  export declare function submitDistillTickExplorationQuestion(questions: HubQuestionLink | undefined, source: DistillTickQuestionSource | undefined): Promise<HubQuestionSubmitResult>;
118
208
  export declare function scheduleAutoExecHubSideEffects(task: exec.AutoExecTask, verdict: exec.AutoExecVerdict, links: {
@@ -125,15 +215,13 @@ export declare function scheduleAutoExecHubSideEffects(task: exec.AutoExecTask,
125
215
  * candidate can be withheld by trust/review gates or lose selection, so fetch-time attribution would overclaim.
126
216
  * Reporting never throws and never blocks the verdict.
127
217
  */
128
- export declare function makeHubLink(cap: OutcomeReportingHub, ingestor?: events.Ingestor, reportEnabled?: boolean): HubLink;
218
+ export declare function makeHubLink(cap: OutcomeReportingHub, ingestor?: events.Ingestor, reportEnabled?: boolean, onVerifiedSearchMiss?: VerifiedHubSearchMissHandler, assetLog?: AssetCallLogger, env?: NodeJS.ProcessEnv): HubLink;
129
219
  /**
130
- * Resolve the hub link (reuse seam + outcome reporter) from the environment, or undefined when reuse is
131
- * not enabled/credentialed. Default OFF: requires EVOLVER_REUSE_BEFORE_SOLVE === '1' and an OAuth token at
132
- * <evomapDir>/token.json. Any setup failure degrades to undefined (no link) so the daemon never blocks on
133
- * hub config — reuse is an optimization. Outcome reporting rides the same gate (it is the read-back half
134
- * of the same paid hub relationship); EVOLVER_OUTCOME_REPORT=0 turns just the reporting off.
220
+ * Resolve public/private reuse wiring. Reuse remains default-off. When a public ATP miss handler is supplied,
221
+ * a consent-gated free search-only seam may still be composed so auto-buy can prove a miss independently of
222
+ * reuse injection; that seam never fetches or injects Hub assets.
135
223
  */
136
- export declare function resolveHubLink(env?: NodeJS.ProcessEnv, ingestor?: events.Ingestor, connectHub?: PublicHubConnector): HubLink | undefined;
224
+ export declare function resolveHubLink(env?: NodeJS.ProcessEnv, ingestor?: events.Ingestor, connectHub?: PublicHubConnector, onVerifiedSearchMiss?: VerifiedHubSearchMissHandler, assetLog?: AssetCallLogger): HubLink | undefined;
137
225
  export declare function resolveHubQuestionLink(env?: NodeJS.ProcessEnv, connectHub?: PublicHubConnector): HubQuestionLink | undefined;
138
226
  export declare function resolveMemoryEventMirror(env?: NodeJS.ProcessEnv, connectHub?: PublicHubConnector): MemoryEventMirrorWiring;
139
227
  export declare function offlinePermitDir(env?: NodeJS.ProcessEnv): string;
@@ -236,5 +324,4 @@ export declare function runIdleTranscriptDistillForBeat(beat: Pick<Beat, 'intens
236
324
  * autoExecPass on an interval. Real agent execution only happens for repos the operator has allowlisted in
237
325
  * <home>/autoexec/config.json (allowedRoots) — empty by default = nothing runs.
238
326
  */
239
- export declare function runAutoExec(argv: readonly string[]): Promise<number>;
240
- export {};
327
+ export declare function runAutoExec(argv: readonly string[]): Promise<number>;